Practical code examples and solutions for all Java concepts
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
The most basic Java program that outputs "Hello, World!" to the console.
// Class declaration
public class Structure {
// Main method - program entry point
public static void main(String[] args) {
// Variable declaration
int number = 10;
// Output statement
System.out.println("Number is: " + number);
// Method call
printMessage();
}
// Custom method
static void printMessage() {
System.out.println("This is a method in Java");
}
}
Shows the basic structure of a Java program with comments explaining each part.
public class DataTypes {
public static void main(String[] args) {
// Primitive data types
byte smallNumber = 100; // 8-bit integer
short mediumNumber = 10000; // 16-bit integer
int age = 25; // 32-bit integer
long bigNumber = 1000000000L; // 64-bit integer
// Floating point types
float price = 19.99f; // 32-bit float
double pi = 3.14159; // 64-bit double
// Character type
char grade = 'A'; // 16-bit Unicode
// Boolean type
boolean isValid = true; // true or false
// Output values
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Grade: " + grade);
System.out.println("Is Valid: " + isValid);
// Reference data type
String name = "Java Programming";
System.out.println("Name: " + name);
}
}
Demonstrates different data types available in Java.
public class Constants {
// Define a constant using final keyword
static final double PI = 3.14159;
static final int MAX_SIZE = 100;
public static void main(String[] args) {
// Literals examples
int decimal = 100; // Decimal literal
int octal = 0144; // Octal literal (starts with 0)
int hex = 0x64; // Hexadecimal literal (starts with 0x)
int binary = 0b1100100; // Binary literal (starts with 0b)
float f1 = 3.14f; // Float literal (ends with f)
double d1 = 3.14; // Double literal
char ch = 'A'; // Character literal
String str = "Hello"; // String literal
boolean flag = true; // Boolean literal
// Using constants
System.out.println("PI: " + PI);
System.out.println("MAX_SIZE: " + MAX_SIZE);
System.out.println("Hexadecimal 0x64: " + hex);
System.out.println("Binary 0b1100100: " + binary);
// Special literals
String multiLine = "This is a " +
"multi-line " +
"string literal";
System.out.println(multiLine);
}
}
Shows how to define constants and use different types of literals in Java.
import java.util.Scanner;
public class InputOutput {
public static void main(String[] args) {
// Create Scanner object for input
Scanner scanner = new Scanner(System.in);
// Getting different types of input
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your height (in meters): ");
double height = scanner.nextDouble();
// Consume the leftover newline
scanner.nextLine();
System.out.print("Enter your city: ");
String city = scanner.nextLine();
// Displaying output
System.out.println("\n--- User Information ---");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Height: " + height + " meters");
System.out.println("City: " + city);
// Formatted output
System.out.printf("\nFormatted Output: %s is %d years old and %.2f meters tall\n",
name, age, height);
// Close the scanner
scanner.close();
}
}
Demonstrates basic input and output operations in Java using Scanner class.
public class Operators {
public static void main(String[] args) {
int a = 10, b = 3;
// Arithmetic operators
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
// Relational operators
System.out.println("a == b: " + (a == b));
System.out.println("a != b: " + (a != b));
System.out.println("a > b: " + (a > b));
System.out.println("a < b: " + (a < b));
// Logical operators
boolean x = true, y = false;
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
// Assignment operators
int c = a;
c += b;
System.out.println("c += b: " + c);
// Increment/Decrement
System.out.println("a++: " + (a++)); // Post-increment
System.out.println("++a: " + (++a)); // Pre-increment
// Ternary operator
int max = (a > b) ? a : b;
System.out.println("Maximum: " + max);
// Bitwise operators
int num1 = 5; // Binary: 0101
int num2 = 3; // Binary: 0011
System.out.println("num1 & num2: " + (num1 & num2)); // AND: 0001 (1)
System.out.println("num1 | num2: " + (num1 | num2)); // OR: 0111 (7)
System.out.println("num1 ^ num2: " + (num1 ^ num2)); // XOR: 0110 (6)
}
}
Shows different types of operators available in Java.
import java.util.Scanner;
public class IfElse {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Simple if statement
if (number > 0) {
System.out.println("The number is positive.");
}
// If-else statement
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
// If-else if ladder
if (number > 0) {
System.out.println("Positive number");
} else if (number < 0) {
System.out.println("Negative number");
} else {
System.out.println("Zero");
}
// Nested if statements
System.out.print("Enter your age: ");
int age = scanner.nextInt();
if (age >= 18) {
System.out.print("Do you have a voter ID? (true/false): ");
boolean hasVoterId = scanner.nextBoolean();
if (hasVoterId) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You need a voter ID to vote.");
}
} else {
System.out.println("You are not eligible to vote.");
}
scanner.close();
}
}
Demonstrates different forms of if-else conditional statements in Java.
import java.util.Scanner;
public class SwitchExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a day number (1-7): ");
int day = scanner.nextInt();
// Traditional switch statement
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day number");
}
// Enhanced switch expression (Java 14+)
System.out.print("Enter a month number (1-12): ");
int month = scanner.nextInt();
String monthName = switch (month) {
case 1 -> "January";
case 2 -> "February";
case 3 -> "March";
case 4 -> "April";
case 5 -> "May";
case 6 -> "June";
case 7 -> "July";
case 8 -> "August";
case 9 -> "September";
case 10 -> "October";
case 11 -> "November";
case 12 -> "December";
default -> "Invalid month";
};
System.out.println("Month: " + monthName);
// Switch with multiple cases
System.out.print("Enter your grade (A, B, C, D, F): ");
char grade = scanner.next().charAt(0);
switch (Character.toUpperCase(grade)) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
System.out.println("Well done!");
break;
case 'C':
System.out.println("Good job!");
break;
case 'D':
System.out.println("You passed, but could do better.");
break;
case 'F':
System.out.println("Sorry, you failed.");
break;
default:
System.out.println("Invalid grade entered.");
}
scanner.close();
}
}
Shows how to use switch statements for multiple conditional branches in Java.
public class ForLoop {
public static void main(String[] args) {
// Basic for loop
System.out.println("Counting from 1 to 5:");
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
System.out.println("\n");
// Nested for loop (multiplication table)
System.out.println("Multiplication Table (1-5):");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print((i * j) + "\t");
}
System.out.println();
}
System.out.println();
// For-each loop (enhanced for loop)
int[] numbers = {10, 20, 30, 40, 50};
System.out.print("Array elements using for-each: ");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
// For loop with break and continue
System.out.println("Numbers from 1 to 10 (skipping 5 and stopping at 8):");
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip iteration when i is 5
}
if (i == 9) {
break; // Exit loop when i is 9
}
System.out.print(i + " ");
}
System.out.println();
// Infinite for loop with break
System.out.println("Counting until 5 with infinite loop:");
int count = 1;
for (;;) {
System.out.print(count + " ");
if (count == 5) {
break;
}
count++;
}
}
}
Demonstrates different uses of for loops in Java.
import java.util.Scanner;
public class WhileLoop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// While loop example
System.out.println("While loop - counting from 1 to 5:");
int i = 1;
while (i <= 5) {
System.out.print(i + " ");
i++;
}
System.out.println("\n");
// Do-while loop example
System.out.println("Do-while loop - counting from 1 to 5:");
int j = 1;
do {
System.out.print(j + " ");
j++;
} while (j <= 5);
System.out.println("\n");
// Practical example: Sum of numbers until 0 is entered
int number, sum = 0;
System.out.println("Enter numbers to sum (enter 0 to stop):");
while (true) {
number = scanner.nextInt();
if (number == 0) {
break;
}
sum += number;
}
System.out.println("Sum of entered numbers: " + sum);
// Another example: Password validation
String password;
int attempts = 0;
final String correctPassword = "Java123";
do {
System.out.print("Enter password: ");
password = scanner.next();
attempts++;
if (password.equals(correctPassword)) {
System.out.println("Access granted!");
break;
} else {
System.out.println("Incorrect password. Attempts: " + attempts);
}
if (attempts >= 3) {
System.out.println("Too many failed attempts. Access denied.");
break;
}
} while (true);
// While loop with condition
System.out.println("Counting down from 10:");
int counter = 10;
while (counter > 0) {
System.out.print(counter + " ");
counter--;
}
System.out.println();
scanner.close();
}
}
Shows how to use while and do-while loops in Java.
import java.util.Arrays;
public class SingleArray {
public static void main(String[] args) {
// Different ways to declare and initialize arrays
int[] numbers1 = new int[5]; // Declaration with size
int[] numbers2 = {1, 2, 3, 4, 5}; // Declaration with initialization
int numbers3[] = new int[]{10, 20, 30, 40, 50}; // Alternative syntax
// Initialize array elements
numbers1[0] = 5;
numbers1[1] = 10;
numbers1[2] = 15;
numbers1[3] = 20;
numbers1[4] = 25;
// Access and print array elements
System.out.print("numbers1: ");
for (int i = 0; i < numbers1.length; i++) {
System.out.print(numbers1[i] + " ");
}
System.out.println();
System.out.print("numbers2: ");
for (int num : numbers2) {
System.out.print(num + " ");
}
System.out.println();
// Using Arrays class utility methods
System.out.println("numbers3: " + Arrays.toString(numbers3));
// Array operations
int sum = 0;
for (int num : numbers2) {
sum += num;
}
System.out.println("Sum of numbers2: " + sum);
// Find maximum value
int max = numbers3[0];
for (int i = 1; i < numbers3.length; i++) {
if (numbers3[i] > max) {
max = numbers3[i];
}
}
System.out.println("Max in numbers3: " + max);
// Copy arrays
int[] numbersCopy = Arrays.copyOf(numbers2, numbers2.length);
System.out.println("Copied array: " + Arrays.toString(numbersCopy));
// Sort arrays
int[] unsorted = {64, 34, 25, 12, 22, 11, 90};
Arrays.sort(unsorted);
System.out.println("Sorted array: " + Arrays.toString(unsorted));
// Search in sorted array
int index = Arrays.binarySearch(unsorted, 25);
System.out.println("Index of 25: " + index);
// Array of strings
String[] fruits = {"Apple", "Banana", "Cherry", "Date"};
System.out.println("Fruits: " + Arrays.toString(fruits));
}
}
Demonstrates how to work with single-dimensional arrays in Java.
import java.util.Arrays;
public class MultiArray {
public static void main(String[] args) {
// 2D array declaration and initialization
int[][] matrix1 = new int[3][3]; // 3x3 matrix
int[][] matrix2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Initialize 2D array
int value = 1;
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
matrix1[i][j] = value++;
}
}
// Print 2D array
System.out.println("matrix1:");
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.println();
}
System.out.println("\nmatrix2:");
for (int[] row : matrix2) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
// Using Arrays.deepToString()
System.out.println("\nmatrix2 using deepToString:");
System.out.println(Arrays.deepToString(matrix2));
// Jagged array (arrays with different lengths)
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[3];
jagged[2] = new int[4];
// Initialize jagged array
int counter = 1;
for (int i = 0; i < jagged.length; i++) {
for (int j = 0; j < jagged[i].length; j++) {
jagged[i][j] = counter++;
}
}
System.out.println("\nJagged array:");
for (int[] row : jagged) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
// 3D array
int[][][] threeD = new int[2][2][2];
threeD[0][0][0] = 1;
threeD[0][0][1] = 2;
threeD[0][1][0] = 3;
threeD[0][1][1] = 4;
threeD[1][0][0] = 5;
threeD[1][0][1] = 6;
threeD[1][1][0] = 7;
threeD[1][1][1] = 8;
System.out.println("\n3D array:");
for (int[][] matrix : threeD) {
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
System.out.println();
}
// Matrix operations - addition
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] result = new int[2][2];
System.out.println("Matrix addition:");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
result[i][j] = a[i][j] + b[i][j];
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
Shows how to work with multi-dimensional arrays in Java.