Core Java Code Snippets and Programming Fundamentals
1. Control Statements in Java
public class ControlStatementsDemo {
public static void main(String[] args) {
int number = 5;
if (number > 0) {
System.out.println("Number is positive");
} else if (number < 0) {
System.out.println("Number is negative");
} else {
System.out.println("Number is zero");
}
int day = 3;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Invalid day");
}
// Loops and control flow
}
}2. Working with Arrays
public class Groceries {
int itemId;
String itemName;
double price;
void display() {
System.out.println("Item ID: " + itemId + ", Item Name: " + itemName + ", Price: " + price);
}
}3. Essential String Functions
length()toUpperCase()toLowerCase()substring()trim()
4. Class Constructors and Overloading
Constructors initialize objects. Overloading allows multiple constructors with different parameters.
5. Instance Methods
Instance methods operate on specific object data using the this keyword.
6. Method Overloading and Dynamic Invocation
Demonstrates polymorphism through method overriding and overloading.
7. Wrapper Classes
Wrapper classes convert primitive types into objects (e.g., Integer, Double).
8. Inheritance and Method Overriding
Subclasses inherit properties and override methods from the parent Animal class.
9. Multilevel Inheritance and Access Specifiers
Explores private, protected, and public access modifiers across class hierarchies.
10. Implementing Interfaces
Interfaces define a contract that classes must implement, supporting multiple inheritance of type.
11. User-Defined Packages
Organize code into namespaces using the package keyword.
12. Threading with Runnable Interface
Implementing Runnable is a preferred way to create threads in Java.
13. Predefined Exception Handling
Using try-catch blocks to handle runtime errors like ArithmeticException.
14. User-Defined Exceptions
Create custom exceptions by extending the Exception class.
15. Java Collections Framework
Utilizing ArrayList, Iterator, and sorting mechanisms.
16. Generics in Java
Generics provide type safety for classes and methods.
17. Multi-Threading
Extending the Thread class to perform concurrent tasks.
18. Synchronization
Ensures thread safety by preventing concurrent access to shared resources.
19. Inter-Thread Communication
Using wait() and notify() for coordination between producer and consumer threads.
