0% found this document useful (0 votes)
8 views31 pages

Java

Uploaded by

sindhesagar095
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views31 pages

Java

Uploaded by

sindhesagar095
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Comprehensive Java Programming Notes

Table of Contents
1. Java Basics
2. Data Types and Variables

3. Operators
4. Control Statements

5. Methods
6. Object-Oriented Programming

7. Arrays

8. Strings

9. Exception Handling

10. Collections Framework


11. File I/O
12. Multithreading

Java Basics

What is Java?
Java is a high-level, object-oriented programming language developed by Sun Microsystems (now
Oracle). It's platform-independent, meaning "Write Once, Run Anywhere" (WORA).

Key Features of Java


Platform Independent: Runs on any system with JVM
Object-Oriented: Everything is an object

Simple: Easy to learn and use

Secure: Built-in security features


Robust: Strong memory management

Multithreaded: Supports concurrent programming


Portable: Code can run on different platforms

Java Environment
JDK (Java Development Kit): Complete development environment
JRE (Java Runtime Environment): Runtime environment to run Java programs
JVM (Java Virtual Machine): Executes Java bytecode

First Java Program

java

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Program Structure
Class Declaration: public class ClassName

Main Method: Entry point of program

Statements: End with semicolon (;)

Blocks: Code enclosed in curly braces {}

Comments

java

// Single-line comment

/*
Multi-line comment
Can span multiple lines
*/

/**
* Documentation comment
* Used for generating documentation
*/

Data Types and Variables

Primitive Data Types

Integer Types

java
byte b = 127; // 8-bit, range: -128 to 127
short s = 32767; // 16-bit, range: -32,768 to 32,767
int i = 2147483647; // 32-bit, range: -2^31 to 2^31-1
long l = 9223372036854775807L; // 64-bit, range: -2^63 to 2^63-1

Floating-Point Types

java

float f = 3.14f; // 32-bit, single precision


double d = 3.14159; // 64-bit, double precision

Character Type

java

char c = 'A'; // 16-bit Unicode character


char unicode = '\u0041'; // Unicode representation of 'A'

Boolean Type

java

boolean isTrue = true;


boolean isFalse = false;

Non-Primitive Data Types


String: Sequence of characters

Arrays: Collection of similar elements

Classes: User-defined types

Interfaces: Contract for classes

Variable Declaration and Initialization

java
// Declaration
int number;

// Initialization
number = 10;

// Declaration and initialization


int age = 25;
String name = "John";

// Multiple variables
int a = 1, b = 2, c = 3;

Constants (Final Variables)

java

final int MAX_SIZE = 100;


final double PI = 3.14159;

Variable Scope
Local Variables: Declared inside methods

Instance Variables: Declared inside class but outside methods

Class Variables (Static): Shared among all instances

Operators

Arithmetic Operators

java
int a = 10, b = 3;

int sum = a + b; // Addition: 13


int diff = a - b; // Subtraction: 7
int product = a * b; // Multiplication: 30
int quotient = a / b; // Division: 3
int remainder = a % b; // Modulus: 1

// Increment and Decrement


a++; // Post-increment
++a; // Pre-increment
b--; // Post-decrement
--b; // Pre-decrement

Relational Operators

java

int x = 5, y = 10;

boolean equal = (x == y); // false


boolean notEqual = (x != y); // true
boolean greater = (x > y); // false
boolean less = (x < y); // true
boolean greaterEqual = (x >= y); // false
boolean lessEqual = (x <= y); // true

Logical Operators

java

boolean a = true, b = false;

boolean and = a && b; // Logical AND: false


boolean or = a || b; // Logical OR: true
boolean not = !a; // Logical NOT: false

Assignment Operators

java
int x = 10;

x += 5; // x = x + 5; Result: 15
x -= 3; // x = x - 3; Result: 12
x *= 2; // x = x * 2; Result: 24
x /= 4; // x = x / 4; Result: 6
x %= 3; // x = x % 3; Result: 0

Bitwise Operators

java

int a = 5; // Binary: 101


int b = 3; // Binary: 011

int bitwiseAnd = a & b; // 001 = 1


int bitwiseOr = a | b; // 111 = 7
int bitwiseXor = a ^ b; // 110 = 6
int bitwiseNot = ~a; // ...11111010
int leftShift = a << 1; // 1010 = 10
int rightShift = a >> 1; // 10 = 2

Ternary Operator

java

int max = (a > b) ? a : b; // If a > b, return a, else return b

Control Statements

Conditional Statements

if Statement

java

int age = 18;

if (age >= 18) {


System.out.println("You are an adult");
}

if-else Statement

java
int score = 85;

if (score >= 90) {


System.out.println("Grade A");
} else if (score >= 80) {
System.out.println("Grade B");
} else if (score >= 70) {
System.out.println("Grade C");
} else {
System.out.println("Grade F");
}

switch Statement

java

int day = 3;
String dayName;

switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Invalid day";
break;
}

Loop Statements

for Loop

java
// Basic for loop
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}

// Enhanced for loop (for-each)


int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}

while Loop

java

int i = 0;
while (i < 5) {
System.out.println("Count: " + i);
i++;
}

do-while Loop

java

int i = 0;
do {
System.out.println("Count: " + i);
i++;
} while (i < 5);

Jump Statements

java
// break statement
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit loop when i equals 5
}
System.out.println(i);
}

// continue statement
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}

// return statement (in methods)


public int findMax(int a, int b) {
if (a > b) {
return a;
}
return b;
}

Methods

Method Declaration

java

[access_modifier] [static] return_type method_name(parameter_list) {


// Method body
return value; // if return_type is not void
}

Method Examples

java
// Method with no parameters and no return value
public void greet() {
System.out.println("Hello!");
}

// Method with parameters and return value


public int add(int a, int b) {
return a + b;
}

// Static method
public static void displayMessage() {
System.out.println("This is a static method");
}

// Method with variable arguments (varargs)


public int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}

Method Overloading

java

public class Calculator {


// Method with 2 int parameters
public int add(int a, int b) {
return a + b;
}

// Method with 3 int parameters


public int add(int a, int b, int c) {
return a + b + c;
}

// Method with 2 double parameters


public double add(double a, double b) {
return a + b;
}
}
Recursion

java

// Factorial calculation using recursion


public int factorial(int n) {
if (n <= 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive call
}

// Fibonacci sequence
public int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}

Object-Oriented Programming

Class and Object

Class Definition

java
public class Student {
// Instance variables (attributes)
private String name;
private int age;
private double gpa;

// Constructor
public Student(String name, int age, double gpa) {
this.name = name;
this.age = age;
this.gpa = gpa;
}

// Default constructor
public Student() {
this("Unknown", 0, 0.0);
}

// Methods (behaviors)
public void study() {
System.out.println(name + " is studying");
}

public void displayInfo() {


System.out.println("Name: " + name + ", Age: " + age + ", GPA: " + gpa);
}

// Getter methods
public String getName() { return name; }
public int getAge() { return age; }
public double getGpa() { return gpa; }

// Setter methods
public void setName(String name) { this.name = name; }
public void setAge(int age) { this.age = age; }
public void setGpa(double gpa) { this.gpa = gpa; }
}

Object Creation and Usage

java
public class Main {
public static void main(String[] args) {
// Creating objects
Student student1 = new Student("Alice", 20, 3.8);
Student student2 = new Student();

// Using object methods


student1.study();
student1.displayInfo();

// Modifying object state


student2.setName("Bob");
student2.setAge(19);
student2.setGpa(3.5);
student2.displayInfo();
}
}

The Four Pillars of OOP

1. Encapsulation

java

public class BankAccount {


private double balance; // Private - cannot be accessed directly

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
}
}

public boolean withdraw(double amount) {


if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}

public double getBalance() {


return balance; // Controlled access through getter
}
}
2. Inheritance

java

// Parent class (Superclass)


public class Animal {
protected String name;
protected int age;

public Animal(String name, int age) {


this.name = name;
this.age = age;
}

public void eat() {


System.out.println(name + " is eating");
}

public void sleep() {


System.out.println(name + " is sleeping");
}
}

// Child class (Subclass)


public class Dog extends Animal {
private String breed;

public Dog(String name, int age, String breed) {


super(name, age); // Call parent constructor
this.breed = breed;
}

public void bark() {


System.out.println(name + " is barking");
}

@Override
public void eat() {
System.out.println(name + " the dog is eating dog food");
}
}

3. Polymorphism

java
public class Shape {
public void draw() {
System.out.println("Drawing a shape");
}

public double calculateArea() {


return 0;
}
}

public class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public void draw() {
System.out.println("Drawing a circle");
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

public class Rectangle extends Shape {


private double length, width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public void draw() {
System.out.println("Drawing a rectangle");
}

@Override
public double calculateArea() {
return length * width;
}
}
// Using polymorphism
public class TestPolymorphism {
public static void main(String[] args) {
Shape[] shapes = {
new Circle(5),
new Rectangle(4, 6),
new Shape()
};

for (Shape shape : shapes) {


shape.draw(); // Different implementations called
System.out.println("Area: " + shape.calculateArea());
}
}
}

4. Abstraction

java
// Abstract class
public abstract class Vehicle {
protected String brand;

public Vehicle(String brand) {


this.brand = brand;
}

// Abstract method - must be implemented by subclasses


public abstract void start();

// Concrete method
public void stop() {
System.out.println(brand + " vehicle stopped");
}
}

public class Car extends Vehicle {


public Car(String brand) {
super(brand);
}

@Override
public void start() {
System.out.println(brand + " car started with key");
}
}

// Interface
public interface Drawable {
void draw(); // Abstract method (implicitly public abstract)

default void display() { // Default method (Java 8+)


System.out.println("Displaying drawable object");
}
}

public class Circle implements Drawable {


@Override
public void draw() {
System.out.println("Drawing a circle");
}
}

Arrays
Array Declaration and Initialization

java

// Declaration
int[] numbers;
int numbers2[];

// Declaration and initialization


int[] arr1 = new int[5]; // Array of size 5, initialized to 0
int[] arr2 = {1, 2, 3, 4, 5}; // Array literal
int[] arr3 = new int[]{1, 2, 3, 4, 5}; // Alternative syntax

// Different data types


String[] names = {"Alice", "Bob", "Charlie"};
double[] grades = new double[10];
boolean[] flags = {true, false, true};

Array Operations

java

int[] numbers = {10, 20, 30, 40, 50};

// Accessing elements
int first = numbers[0]; // 10
int last = numbers[numbers.length - 1]; // 50

// Modifying elements
numbers[2] = 35; // Changes 30 to 35

// Array length
int size = numbers.length; // 5

// Iterating through array


for (int i = 0; i < numbers.length; i++) {
System.out.println("Element " + i + ": " + numbers[i]);
}

// Enhanced for loop


for (int num : numbers) {
System.out.println(num);
}

Multidimensional Arrays
java

// 2D Array declaration
int[][] matrix = new int[3][4]; // 3 rows, 4 columns

// 2D Array initialization
int[][] matrix2 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Accessing 2D array elements


matrix2[1][2] = 10; // Set element at row 1, column 2

// Iterating through 2D array


for (int i = 0; i < matrix2.length; i++) {
for (int j = 0; j < matrix2[i].length; j++) {
System.out.print(matrix2[i][j] + " ");
}
System.out.println();
}

// Enhanced for loop for 2D array


for (int[] row : matrix2) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}

Array Utility Methods

java
import java.util.Arrays;

int[] numbers = {5, 2, 8, 1, 9};

// Sorting
Arrays.sort(numbers); // Sorts in ascending order

// Searching (array must be sorted)


int index = Arrays.binarySearch(numbers, 5);

// Converting to String
String arrayString = Arrays.toString(numbers);

// Copying arrays
int[] copy = Arrays.copyOf(numbers, numbers.length);
int[] partialCopy = Arrays.copyOfRange(numbers, 1, 4);

// Filling array
int[] filled = new int[5];
Arrays.fill(filled, 7); // All elements become 7

Strings

String Creation

java

// String literals
String str1 = "Hello";
String str2 = "World";

// Using new keyword


String str3 = new String("Hello");

// From character array


char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str4 = new String(chars);

String Methods

java
String text = "Hello World";

// Length
int length = text.length(); // 11

// Character at index
char ch = text.charAt(0); // 'H'

// Substring
String sub1 = text.substring(6); // "World"
String sub2 = text.substring(0, 5); // "Hello"

// Index of character/substring
int index1 = text.indexOf('o'); // 4 (first occurrence)
int index2 = text.lastIndexOf('o'); // 7 (last occurrence)
int index3 = text.indexOf("World"); // 6

// Case conversion
String upper = text.toUpperCase(); // "HELLO WORLD"
String lower = text.toLowerCase(); // "hello world"

// Trimming whitespace
String padded = " Hello World ";
String trimmed = padded.trim(); // "Hello World"

// Replacing characters/substrings
String replaced = text.replace('o', '0'); // "Hell0 W0rld"
String replacedAll = text.replaceAll("o", "0"); // "Hell0 W0rld"

// Splitting string
String[] words = text.split(" "); // ["Hello", "World"]

// Checking string properties


boolean isEmpty = text.isEmpty(); // false
boolean isBlank = text.isBlank(); // false (Java 11+)
boolean startsWith = text.startsWith("Hello"); // true
boolean endsWith = text.endsWith("World"); // true
boolean contains = text.contains("llo"); // true

// Comparing strings
boolean equals = text.equals("Hello World"); // true
boolean equalsIgnoreCase = text.equalsIgnoreCase("hello world"); // true
int compareResult = text.compareTo("Hello World"); // 0

StringBuilder and StringBuffer


java

// StringBuilder (not thread-safe, faster)


StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
sb.insert(5, ","); // "Hello, World"
sb.delete(5, 6); // "Hello World"
sb.reverse(); // "dlroW olleH"
String result = sb.toString();

// StringBuffer (thread-safe, slower)


StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World");
String result2 = sbf.toString();

String Formatting

java

// Using String.format()
String formatted = String.format("Name: %s, Age: %d, GPA: %.2f", "Alice", 20, 3.85);

// Using printf()
System.out.printf("Name: %s, Age: %d, GPA: %.2f%n", "Alice", 20, 3.85);

// Common format specifiers


// %s - String
// %d - Integer
// %f - Float/Double
// %.2f - Float with 2 decimal places
// %n - Newline

Exception Handling

Types of Exceptions
Checked Exceptions: Must be handled (IOException, SQLException)

Unchecked Exceptions: Runtime exceptions (NullPointerException,


ArrayIndexOutOfBoundsException)
Errors: System-level problems (OutOfMemoryError)

try-catch-finally
java

public class ExceptionHandling {


public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
} catch (Exception e) {
System.out.println("General exception: " + e.getMessage());
} finally {
System.out.println("This block always executes");
}
}
}

Multiple Catch Blocks

java

try {
String str = null;
int length = str.length(); // NullPointerException
int result = 10 / 0; // ArithmeticException
} catch (NullPointerException e) {
System.out.println("Null pointer exception occurred");
} catch (ArithmeticException e) {
System.out.println("Arithmetic exception occurred");
} catch (Exception e) {
System.out.println("Some other exception occurred");
}

Multi-catch Block (Java 7+)

java

try {
// Some code that might throw exceptions
} catch (IOException | SQLException e) {
System.out.println("IO or SQL exception occurred: " + e.getMessage());
}

Throwing Exceptions

java
public class CustomException {
public static void validateAge(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
if (age > 150) {
throw new IllegalArgumentException("Age cannot be greater than 150");
}
}

public static void main(String[] args) {


try {
validateAge(-5);
} catch (IllegalArgumentException e) {
System.out.println("Invalid age: " + e.getMessage());
}
}
}

Custom Exceptions

java
// Custom checked exception
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}

// Custom unchecked exception


class InvalidAccountException extends RuntimeException {
public InvalidAccountException(String message) {
super(message);
}
}

public class BankAccount {


private double balance;

public void withdraw(double amount) throws InsufficientFundsException {


if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds. Balance: " + balance);
}
balance -= amount;
}
}

try-with-resources (Java 7+)

java

import java.io.*;

public class FileHandling {


public static void readFile(String filename) {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
// Reader is automatically closed
}
}
Collections Framework

List Interface

java

import java.util.*;

// ArrayList - Dynamic array


List<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
arrayList.add(1, "Apricot"); // Insert at index 1

// LinkedList - Doubly linked list


List<String> linkedList = new LinkedList<>();
linkedList.add("First");
linkedList.add("Second");

// Vector - Synchronized ArrayList


List<String> vector = new Vector<>();
vector.add("Item1");
vector.add("Item2");

// Common List operations


String first = arrayList.get(0); // Get element at index 0
arrayList.set(0, "Avocado"); // Replace element at index 0
arrayList.remove(2); // Remove element at index 2
boolean contains = arrayList.contains("Banana"); // Check if exists
int size = arrayList.size(); // Get size

Set Interface

java
// HashSet - No duplicates, no order
Set<String> hashSet = new HashSet<>();
hashSet.add("Red");
hashSet.add("Green");
hashSet.add("Blue");
hashSet.add("Red"); // Duplicate, won't be added

// LinkedHashSet - No duplicates, maintains insertion order


Set<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("First");
linkedHashSet.add("Second");
linkedHashSet.add("Third");

// TreeSet - No duplicates, sorted order


Set<String> treeSet = new TreeSet<>();
treeSet.add("Zebra");
treeSet.add("Apple");
treeSet.add("Mango");
// Elements will be in alphabetical order

// Common Set operations


boolean added = hashSet.add("Yellow"); // Returns true if added
boolean removed = hashSet.remove("Red"); // Returns true if removed
boolean isEmpty = hashSet.isEmpty();

Map Interface

java
// HashMap - Key-value pairs, no order
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Alice", 25);
hashMap.put("Bob", 30);
hashMap.put("Charlie", 35);

// LinkedHashMap - Maintains insertion order


Map<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("First", 1);
linkedHashMap.put("Second", 2);

// TreeMap - Sorted by keys


Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Zebra", 1);
treeMap.put("Apple", 2);
treeMap.put("Mango", 3);

// Common Map operations


Integer age = hashMap.get("Alice"); // Get value for key
Integer defaultAge = hashMap.getOrDefault("David", 0); // Get with default
boolean hasKey = hashMap.containsKey("Bob");
boolean hasValue = hashMap.containsValue(25);
Set<String> keys = hashMap.keySet(); // Get all keys
Collection<Integer> values = hashMap.values(); // Get all values

// Iterating through Map


for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

Queue Interface

java
// LinkedList as Queue
Queue<String> queue = new LinkedList<>();
queue.offer("First"); // Add to rear
queue.offer("Second");
queue.offer("Third");

String front = queue.poll(); // Remove and return front element


String peek = queue.peek(); // Return front element without removing

// PriorityQueue - Elements sorted by natural order or comparator


Queue<Integer> priorityQueue = new PriorityQueue<>();
priorityQueue.offer(5);
priorityQueue.offer(1);
priorityQueue.offer(3);
// Elements will be retrieved in sorted order: 1, 3, 5

Collections Utility Class

java

List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 9);

// Sorting
Collections.sort(numbers); // Ascending order
Collections.sort(numbers, Collections.reverseOrder()); // Descending order

// Searching (list must be sorted)


int index = Collections.binarySearch(numbers, 5);

// Min and Max


int min = Collections.min(numbers);
int max = Collections.max(numbers);

// Shuffling
Collections.shuffle(numbers);

// Reversing
Collections.reverse(numbers);

// Frequency
int frequency = Collections.frequency(numbers, 5);

// Synchronization
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
File I/O

File Class

java

import java.io.File;

File file = new File("example.txt");

// File properties
boolean exists = file.exists();
boolean isFile = file.isFile();
boolean isDirectory = file.isDirectory();
boolean canRead = file.canRead();
boolean canWrite = file.canWrite();
long fileSize = file.length();
String fileName = file.getName();
String absolutePath = file.getAbsolutePath();

// File operations
boolean created = file.createNewFile(); // Create if doesn't exist
boolean deleted = file.delete(); // Delete file
boolean renamed = file.renameTo(new File("newname.txt"));

// Directory operations
File dir = new File("myDirectory");
boolean dirCreated = dir.mkdir(); // Create single directory
boolean dirsCreated = dir.mkdirs(); // Create directory path

// List files in directory


File[] files = dir.listFiles();
String[] fileNames = dir.list();

Reading Files

java

import java.io.*;
import java.util.Scanner;

// Using FileReader and BufferedReader


public void readWithBufferedReader(String filename) {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = reader.readLine()) !=

You might also like