JAVA COMPREHENSIVE NOTES
1. VARIABLES
Variables are containers for storing data values in Java.
Types of Variables:
Local Variables: Declared inside methods, constructors, or blocks
Instance Variables: Declared in a class but outside methods
Static Variables: Declared with static keyword (class variables)
Primitive Data Types:
java
public class VariableExamples {
// Instance variables
int instanceVar = 100;
String instanceString = "Hello";
// Static variable (shared across all instances)
static int staticVar = 500;
public static void main(String[] args) {
// Local variables - must be initialized before use
int age = 25;
double salary = 55000.50;
char grade = 'A';
boolean isActive = true;
float height = 5.9f;
long population = 7800000000L;
[Link]("Age: " + age);
[Link]("Salary: " + salary);
[Link]("Grade: " + grade);
[Link]("Active: " + isActive);
[Link]("Height: " + height);
[Link]("Population: " + population);
// Variable declaration and initialization
int x; // declaration
x = 10; // initialization
int y = 20; // declaration + initialization
Variable Scope:
java
public class ScopeExample {
int classVar = 10; // class-level scope
public void myMethod() {
int methodVar = 20; // method-level scope
if (true) {
int blockVar = 30; // block-level scope
[Link](blockVar);
// [Link](blockVar); // ERROR: out of scope
[Link](classVar); // accessible
[Link](methodVar); // accessible
Constants (final variables):
java
public class ConstantsExample {
final int MAX_VALUE = 100; // cannot be changed
static final double PI = 3.14159; // class constant
public static void main(String[] args) {
final String APP_NAME = "MyApp";
// APP_NAME = "NewName"; // ERROR: cannot reassign final variable
[Link](PI);
2. PARITY (Even/Odd Numbers)
Parity refers to whether a number is even or odd.
Checking Even/Odd:
java
public class ParityExamples {
public static void main(String[] args) {
// Method 1: Using modulus operator
int num1 = 7;
if (num1 % 2 == 0) {
[Link](num1 + " is even");
} else {
[Link](num1 + " is odd");
// Method 2: Using bitwise AND (faster)
int num2 = 10;
if ((num2 & 1) == 0) {
[Link](num2 + " is even");
} else {
[Link](num2 + " is odd");
// Method 3: Function to check parity
[Link](isEven(24)); // true
[Link](isOdd(17)); // true
// Array parity check
int[] numbers = {1, 2, 3, 4, 5, 6};
countParity(numbers);
// Separating even and odd numbers
separateEvenOdd(numbers);
public static boolean isEven(int n) {
return n % 2 == 0;
}
public static boolean isOdd(int n) {
return n % 2 != 0;
public static void countParity(int[] arr) {
int evenCount = 0, oddCount = 0;
for (int num : arr) {
if (num % 2 == 0) evenCount++;
else oddCount++;
[Link]("Even numbers: " + evenCount);
[Link]("Odd numbers: " + oddCount);
public static void separateEvenOdd(int[] arr) {
[Link]("Even numbers: ");
for (int num : arr) {
if (num % 2 == 0) [Link](num + " ");
[Link]("\nOdd numbers: ");
for (int num : arr) {
if (num % 2 != 0) [Link](num + " ");
[Link]();
}
3. CONDITIONS
Conditional statements control the flow of execution based on conditions.
if-else Statements:
java
public class ConditionExamples {
public static void main(String[] args) {
int score = 85;
// Simple if
if (score >= 60) {
[Link]("Passing grade");
// if-else
if (score >= 50) {
[Link]("Pass");
} else {
[Link]("Fail");
// if-else if ladder
if (score >= 90) {
[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B");
} else if (score >= 70) {
[Link]("Grade: C");
} else if (score >= 60) {
[Link]("Grade: D");
} else {
[Link]("Grade: F");
// Nested if
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
[Link]("You can drive");
} else {
[Link]("Get a license first");
} else {
[Link]("Too young to drive");
Ternary Operator:
java
public class TernaryExample {
public static void main(String[] args) {
int a = 10, b = 20;
// Ternary operator: condition ? value_if_true : value_if_false
int max = (a > b) ? a : b;
[Link]("Maximum: " + max);
String result = (a % 2 == 0) ? "Even" : "Odd";
[Link]("a is " + result);
// Nested ternary
int num = 0;
String type = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";
[Link]("Number is " + type);
Switch Statement:
java
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
String dayName;
// Traditional switch
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;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
[Link]("Day: " + dayName);
// Switch with multiple cases (fall-through)
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
case 'C':
[Link]("Passing grade");
break;
case 'D':
case 'F':
[Link]("Failing grade");
break;
default:
[Link]("Invalid grade");
// Java 12+ enhanced switch (expression)
String result = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> "Invalid";
};
[Link]("Day type: " + result);
4. LOOPS
Loops execute a block of code repeatedly.
for Loop:
java
public class ForLoopExamples {
public static void main(String[] args) {
// Basic for loop
for (int i = 1; i <= 5; i++) {
[Link](i + " ");
[Link]();
// Sum of first 10 numbers
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
[Link]("Sum: " + sum);
// For loop with multiple variables
for (int i = 0, j = 10; i < j; i++, j--) {
[Link]("i=" + i + ", j=" + j);
// Nested for loop (multiplication table)
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
[Link]("%4d", i * j);
[Link]();
// Enhanced for loop (for-each)
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
[Link](num + " ");
[Link]();
// Loop through string
String text = "Hello";
for (char c : [Link]()) {
[Link](c + "-");
[Link]();
while Loop:
java
public class WhileLoopExamples {
public static void main(String[] args) {
// Basic while loop
int i = 1;
while (i <= 5) {
[Link](i + " ");
i++;
[Link]();
// Sum until condition met
int sum = 0;
int num = 1;
while (sum < 100) {
sum += num;
num++;
[Link]("Sum reached 100 at number: " + (num-1));
// Password validation
String password = "secret";
String input = "wrong";
int attempts = 0;
while ( && attempts < 3) {
input = "secret"; // simulating correct input
attempts++;
[Link]("Attempt " + attempts);
// Infinite loop (with break)
int count = 0;
while (true) {
[Link]("Count: " + count);
count++;
if (count >= 5) break;
do-while Loop:
java
public class DoWhileExamples {
public static void main(String[] args) {
// Basic do-while (executes at least once)
int i = 1;
do {
[Link](i + " ");
i++;
} while (i <= 5);
[Link]();
// Menu system example
int choice = 0;
do {
[Link]("\n--- MENU ---");
[Link]("1. Option 1");
[Link]("2. Option 2");
[Link]("3. Exit");
[Link]("Enter choice: ");
// Simulating input
choice = 3;
switch (choice) {
case 1:
[Link]("Option 1 selected");
break;
case 2:
[Link]("Option 2 selected");
break;
case 3:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice");
} while (choice != 3);
Loop Control Statements:
java
public class LoopControlExamples {
public static void main(String[] args) {
// break - exit loop completely
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // stops when i=5
[Link](i + " ");
[Link]("\n---");
// continue - skip current iteration
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
[Link](i + " ");
[Link]("\n---");
// Labeled break (break outer loop)
outer: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i * j > 4) {
break outer; // breaks both loops
[Link]("i=" + i + ", j=" + j);
5. FUNCTIONS (Methods)
Methods are blocks of code that perform specific tasks.
Basic Method Structure:
java
public class MethodExamples {
// Method without parameters and without return value
public void sayHello() {
[Link]("Hello, World!");
// Method with parameters and return value
public int add(int a, int b) {
return a + b;
// Method with return type but no parameters
public String getGreeting() {
return "Welcome to Java!";
// Method with multiple parameters
public double calculateArea(double length, double width) {
return length * width;
// Method overloading (same name, different parameters)
public int multiply(int a, int b) {
return a * b;
public double multiply(double a, double b) {
return a * b;
}
public int multiply(int a, int b, int c) {
return a * b * c;
public static void main(String[] args) {
MethodExamples obj = new MethodExamples();
[Link]();
int sum = [Link](5, 3);
[Link]("Sum: " + sum);
[Link]([Link]());
double area = [Link](5.5, 3.2);
[Link]("Area: " + area);
[Link]([Link](4, 5));
[Link]([Link](2.5, 3.5));
[Link]([Link](2, 3, 4));
Method Types:
java
public class MethodTypes {
// 1. Static method - belongs to class, not instance
public static void staticMethod() {
[Link]("Static method called");
// 2. Instance method - requires object
public void instanceMethod() {
[Link]("Instance method called");
// 3. Void method - no return value
public void voidMethod(String message) {
[Link]("Message: " + message);
// 4. Return type method
public int getNumber() {
return 42;
// 5. Method with varargs (variable arguments)
public int sumAll(int... numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
return sum;
}
// 6. Recursive method
public int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
public static void main(String[] args) {
// Calling static method
[Link]();
// Calling instance method
MethodTypes obj = new MethodTypes();
[Link]();
// Varargs example
[Link]("Sum: " + [Link](1, 2, 3, 4, 5));
// Recursion example
[Link]("Factorial of 5: " + [Link](5));
Method Parameters:
java
public class ParameterExamples {
// Pass by value (primitives)
public void modifyPrimitive(int x) {
x = 100; // This doesn't affect original
[Link]("Inside method: " + x);
// Pass by reference (objects)
public void modifyArray(int[] arr) {
arr[0] = 100; // This affects original
[Link]("Inside method: arr[0] = " + arr[0]);
// Final parameter (cannot be modified)
public void finalParameter(final int x) {
// x = 10; // ERROR: cannot modify final parameter
[Link]("Final parameter: " + x);
public static void main(String[] args) {
ParameterExamples obj = new ParameterExamples();
int num = 10;
[Link](num);
[Link]("Outside method: " + num); // Still 10
int[] array = {1, 2, 3};
[Link](array);
[Link]("Outside method: arr[0] = " + array[0]); // Changed
to 100
}
6. CLASSES
Classes are blueprints for creating objects.
Basic Class Definition:
java
// Class definition
public class Student {
// Fields (instance variables)
private String name;
private int age;
private String studentId;
private double gpa;
// Static field (class variable)
private static int totalStudents = 0;
// Constructor (no parameters)
public Student() {
[Link] = "Unknown";
[Link] = 0;
[Link] = generateStudentId();
totalStudents++;
// Parameterized constructor
public Student(String name, int age) {
[Link] = name;
[Link] = age;
[Link] = generateStudentId();
totalStudents++;
// Copy constructor
public Student(Student other) {
[Link] = [Link];
[Link] = [Link];
[Link] = generateStudentId();
totalStudents++;
// Getter methods
public String getName() {
return name;
public int getAge() {
return age;
public String getStudentId() {
return studentId;
}
public double getGpa() {
return gpa;
// Setter methods
public void setName(String name) {
[Link] = name;
public void setAge(int age) {
if (age >= 0 && age <= 150) {
[Link] = age;
} else {
[Link]("Invalid age");
public void setGpa(double gpa) {
if (gpa >= 0.0 && gpa <= 4.0) {
[Link] = gpa;
} else {
[Link]("Invalid GPA");
// Static method
public static int getTotalStudents() {
return totalStudents;
// Helper method
private String generateStudentId() {
return "STU" + [Link]();
// Instance method
public void displayInfo() {
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Student ID: " + studentId);
[Link]("GPA: " + gpa);
[Link]("---");
@Override
public String toString() {
return [Link]("Student{name='%s', age=%d, id='%s', gpa=
%.2f}",
name, age, studentId, gpa);
Using the Class:
java
public class ClassDemo {
public static void main(String[] args) {
// Creating objects
Student student1 = new Student();
[Link]("Alice");
[Link](20);
[Link](3.8);
Student student2 = new Student("Bob", 22);
[Link](3.5);
Student student3 = new Student(student2); // Copy
[Link]();
[Link]();
[Link]("Total students: " + [Link]());
[Link]([Link]());
[Link](student2);
Inheritance:
java
// Parent class
class Animal {
protected String name;
protected int age;
public Animal(String name, int age) {
[Link] = name;
[Link] = age;
public void eat() {
[Link](name + " is eating");
public void sleep() {
[Link](name + " is sleeping");
public void makeSound() {
[Link]("Some animal sound");
// Child class
class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age); // Call parent constructor
[Link] = breed;
}
// Method overriding
@Override
public void makeSound() {
[Link](name + " says: Woof! Woof!");
// New method
public void wagTail() {
[Link](name + " is wagging tail");
// Another child class
class Cat extends Animal {
public Cat(String name, int age) {
super(name, age);
@Override
public void makeSound() {
[Link](name + " says: Meow!");
public void climb() {
[Link](name + " is climbing");
}
public class InheritanceDemo {
public static void main(String[] args) {
Dog dog = new Dog("Buddy", 3, "Golden Retriever");
Cat cat = new Cat("Whiskers", 2);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
// Polymorphism
Animal animal1 = new Dog("Max", 4, "German Shepherd");
Animal animal2 = new Cat("Luna", 1);
[Link](); // Dog's version
[Link](); // Cat's version
Abstract Classes and Interfaces:
java
// Abstract class
abstract class Shape {
protected String color;
public Shape(String color) {
[Link] = color;
// Abstract methods
public abstract double getArea();
public abstract double getPerimeter();
// Concrete method
public void displayColor() {
[Link]("Color: " + color);
// Interface
interface Drawable {
void draw();
default void print() {
[Link]("Printing...");
static void info() {
[Link]("Drawable interface");
}
interface Resizable {
void resize(double factor);
// Concrete class implementing abstract class and interfaces
class Circle extends Shape implements Drawable, Resizable {
private double radius;
public Circle(String color, double radius) {
super(color);
[Link] = radius;
@Override
public double getArea() {
return [Link] * radius * radius;
@Override
public double getPerimeter() {
return 2 * [Link] * radius;
@Override
public void draw() {
[Link]("Drawing circle with radius " + radius);
}
@Override
public void resize(double factor) {
radius *= factor;
[Link]("Circle resized to radius " + radius);
public class AbstractDemo {
public static void main(String[] args) {
Circle circle = new Circle("Red", 5.0);
[Link]();
[Link]("Area: %.2f\n", [Link]());
[Link]("Perimeter: %.2f\n", [Link]());
[Link]();
[Link](2.0);
[Link]();
[Link]();
7. FILES
File handling for reading and writing data.
Reading Files:
java
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class FileReadExamples {
// Method 1: Using FileReader and BufferedReader
public static void readWithBuffer(String filename) {
try (BufferedReader reader = new BufferedReader(new
FileReader(filename))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
// Method 2: Using Scanner
public static void readWithScanner(String filename) {
try (Scanner scanner = new Scanner(new File(filename))) {
while ([Link]()) {
String line = [Link]();
[Link](line);
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
// Method 3: Using Files class (Java NIO)
public static void readWithFilesClass(String filename) {
try {
List<String> lines = [Link]([Link](filename));
for (String line : lines) {
[Link](line);
} catch (IOException e) {
[Link]("Error: " + [Link]());
// Method 4: Reading entire file as string
public static String readEntireFile(String filename) {
try {
return new String([Link]([Link](filename)));
} catch (IOException e) {
[Link]();
return "";
// Reading formatted data
public static void readFormattedData(String filename) {
try (Scanner scanner = new Scanner(new File(filename))) {
while ([Link]()) {
if ([Link]()) {
int num = [Link]();
[Link]("Integer: " + num);
} else if ([Link]()) {
double d = [Link]();
[Link]("Double: " + d);
} else {
String word = [Link]();
[Link]("String: " + word);
} catch (FileNotFoundException e) {
[Link]();
public static void main(String[] args) {
readWithBuffer("[Link]");
readWithScanner("[Link]");
String content = readEntireFile("[Link]");
[Link]("File content length: " + [Link]());
Writing Files:
java
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class FileWriteExamples {
// Method 1: Using FileWriter
public static void writeWithFileWriter(String filename, String content) {
try (FileWriter writer = new FileWriter(filename)) {
[Link](content);
[Link]("File written successfully");
} catch (IOException e) {
[Link]();
// Method 2: Using BufferedWriter (more efficient)
public static void writeWithBuffer(String filename, String[] lines) {
try (BufferedWriter writer = new BufferedWriter(new
FileWriter(filename))) {
for (String line : lines) {
[Link](line);
[Link](); // Add new line
} catch (IOException e) {
[Link]();
// Method 3: Append to file
public static void appendToFile(String filename, String content) {
try (FileWriter writer = new FileWriter(filename, true)) { // true =
append
[Link](content + "\n");
[Link]("Content appended");
} catch (IOException e) {
[Link]();
// Method 4: Using PrintWriter
public static void writeWithPrintWriter(String filename) {
try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
[Link]("First line");
[Link]("Formatted number: %.2f\n", 3.14159);
[Link]("Last line");
} catch (IOException e) {
[Link]();
// Method 5: Using Files class (NIO)
public static void writeWithFilesClass(String filename, String content) {
try {
[Link]([Link](filename), [Link]());
} catch (IOException e) {
[Link]();
// Method 6: Write multiple lines
public static void writeMultipleLines(String filename, List<String> lines) {
try {
[Link]([Link](filename), lines);
} catch (IOException e) {
[Link]();
public static void main(String[] args) {
// Writing examples
writeWithFileWriter("[Link]", "Hello, World!");
String[] lines = {"Line 1", "Line 2", "Line 3"};
writeWithBuffer("[Link]", lines);
appendToFile("[Link]", "New log entry");
List<String> data = [Link]("Item 1", "Item 2", "Item 3");
writeMultipleLines("[Link]", data);
File Operations:
java
import [Link];
import [Link];
import [Link].*;
public class FileOperations {
public static void main(String[] args) {
// Create file
File file = new File("[Link]");
try {
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists");
} catch (IOException e) {
[Link]();
// File information
if ([Link]()) {
[Link]("File name: " + [Link]());
[Link]("Absolute path: " + [Link]());
[Link]("Writable: " + [Link]());
[Link]("Readable: " + [Link]());
[Link]("File size: " + [Link]() + " bytes");
// List directory contents
File dir = new File(".");
File[] files = [Link]();
if (files != null) {
for (File f : files) {
if ([Link]()) {
[Link]("[DIR] " + [Link]());
} else {
[Link]("[FILE] " + [Link]() + " (" + [Link]() + "
bytes)");
// Delete file
if ([Link]()) {
[Link]("File deleted: " + [Link]());
} else {
[Link]("Failed to delete file");
}
// NIO operations
Path source = [Link]("[Link]");
Path destination = [Link]("[Link]");
try {
// Copy file
[Link](source, destination,
StandardCopyOption.REPLACE_EXISTING);
// Move file
[Link](source, [Link]("[Link]"),
StandardCopyOption.REPLACE_EXISTING);
// Delete file
[Link]([Link]("[Link]"));
} catch (IOException e) {
[Link]();
8. DATA STRUCTURES
Java Collections Framework provides various data structures.
Arrays:
java
import [Link];
public class ArrayExamples {
public static void main(String[] args) {
// 1D Array
int[] numbers = new int[5]; // Declaration with size
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Array literal
int[] scores = {95, 87, 92, 78, 88};
// 2D Array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Jagged array (different row lengths)
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[3];
// Array operations
[Link]("Array length: " + [Link]);
[Link]("First element: " + numbers[0]);
// Sorting
[Link](scores);
[Link]("Sorted: " + [Link](scores));
// Searching (array must be sorted)
int index = [Link](scores, 92);
[Link]("92 found at index: " + index);
// Fill array
int[] fillArray = new int[5];
[Link](fillArray, 100);
[Link]("Filled: " + [Link](fillArray));
// Copy array
int[] copied = [Link](numbers, [Link]);
int[] range = [Link](numbers, 1, 4);
// Compare arrays
boolean isEqual = [Link](numbers, copied);
// Iterating
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
// Enhanced for loop
for (int num : scores) {
[Link](num + " ");
[Link]();
ArrayList (Dynamic Array):
java
import [Link].*;
public class ArrayListExamples {
public static void main(String[] args) {
// Creating ArrayList
ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> numbers = new ArrayList<>(100); // Initial
capacity
// Adding elements
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
[Link](1, "David"); // Insert at index 1
// Bulk add
List<String> moreNames = [Link]("Eve", "Frank");
[Link](moreNames);
// Accessing elements
String first = [Link](0);
[Link]("First: " + first);
// Modifying elements
[Link](2, "Chris");
// Removing elements
[Link]("David"); // Remove by object
[Link](3); // Remove by index
// Size and capacity
int size = [Link]();
boolean isEmpty = [Link]();
// Checking existence
boolean containsBob = [Link]("Bob");
int indexOfBob = [Link]("Bob");
int lastIndex = [Link]("Bob");
// Iterating
[Link]("Using for-each:");
for (String name : names) {
[Link](name);
[Link]("Using iterator:");
Iterator<String> iterator = [Link]();
while ([Link]()) {
[Link]([Link]());
[Link]("Using ListIterator (backward):");
ListIterator<String> listIterator = [Link]([Link]());
while ([Link]()) {
[Link]([Link]());
// Sorting
[Link](names);
[Link](names, [Link]());
// Converting to array
String[] array = [Link](new String[0]);
// Clearing
[Link]();
// Practical example
ArrayList<Student> students = new ArrayList<>();
[Link](new Student("Alice", 20));
[Link](new Student("Bob", 22));
for (Student s : students) {
[Link](s);
LinkedList:
java
import [Link].*;
public class LinkedListExamples {
public static void main(String[] args) {
// Creating LinkedList
LinkedList<String> list = new LinkedList<>();
// Adding elements
[Link]("First");
[Link]("Second");
[Link]("Zero"); // Add to beginning
[Link]("Third"); // Add to end
[Link](2, "Middle"); // Add at index
// Stack operations
[Link]("Top"); // Add to front
String top = [Link](); // Remove