Fundamentals of Java Programming
// Variable Declaration
int age = 20;
double price = 19.99;
boolean isJavaFun = true;
char grade = 'A';
// Casting Examples
double distance = 50; // Implicit (int to double)
int count = (int) 5.75; // Explicit (truncates to 5)
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else {
System.out.println("Keep trying!");
}
A cleaner alternative to multiple if-else blocks.
int day = 3;
String dayName;
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
case 4: dayName = "Thursday"; break;
case 5: dayName = "Friday"; break;
default: dayName = "Weekend/Invalid"; break;
}
System.out.println(dayName); // Output: Wednesday
// For Loop (Known number of iterations)
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
// While Loop (Condition based)
int count = 0;
while (count < 3) {
System.out.println("Counting...");
count++;
}
// Declaration and Initialization
int[] numbers = new int[3];
numbers[0] = 10; // Assigning values
// Array Literal
String[] fruits = {"Apple", "Banana", "Cherry"};
// Accessing
System.out.println(fruits[1]); // Prints Banana
// A method that returns a value
public static int sum(int a, int b) {
return a + b;
}
// A void method (returns nothing)
public static void greet(String name) {
System.out.println("Hello, " + name);
}
Occur during execution, causing the program to crash.
// Example: Division by zero
int x = 10 / 0; // ArithmeticException
// Example: Index out of bounds
int[] arr = new int[2];
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
String msg = " Hello Java ";
System.out.println(msg.length()); // 14
System.out.println(msg.trim()); // "Hello Java"
System.out.println(msg.toUpperCase()); // " HELLO JAVA "
System.out.println(msg.charAt(2)); // 'H'
System.out.println(msg.indexOf("J")); // 8