Introduction to Java

Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle) in 1995. It follows the principle of "Write Once, Run Anywhere" (WORA), meaning compiled Java code can run on all platforms without recompilation.

History of Java

  • 1991: Project Oak started by James Gosling
  • 1995: Java 1.0 released publicly
  • 2006: Java made open source
  • 2010: Oracle acquired Sun Microsystems
  • 2014: Java 8 released with lambda expressions
  • 2018: Java 11 released as LTS version

First Java Program

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

Java Features

Java has several distinctive features that make it popular for various applications.

Key Features of Java

  • Platform Independent: Write Once, Run Anywhere (WORA)
  • Object-Oriented: Based on objects and classes
  • Simple: Easy to learn and use
  • Secure: Provides security features
  • Robust: Strong memory management and exception handling
  • Multithreaded: Supports multiple threads of execution
  • Architecture Neutral: Not tied to specific hardware architecture
  • Dynamic: Supports dynamic loading of classes
Note: Java is both compiled and interpreted. Source code is compiled to bytecode, which is then interpreted by JVM.

Java Virtual Machine (JVM) Architecture

JVM is the heart of Java programming language that provides platform independence.

JVM Components

  • ClassLoader: Loads class files
  • Method Area: Stores class structure
  • Heap: Runtime data area for objects
  • Stack: Stores frames for method calls
  • PC Registers: Stores address of current instruction
  • Native Method Stack: Supports native methods
  • Execution Engine: Executes bytecode

Java Execution Process

  1. Java source code (.java) is compiled to bytecode (.class)
  2. ClassLoader loads the bytecode into JVM
  3. Bytecode verifier checks code validity
  4. Interpreter/JIT compiler converts bytecode to machine code
  5. Execution engine runs the machine code
Exam Tip: Understand the difference between JVM, JRE, and JDK. JVM executes bytecode, JRE = JVM + Libraries, JDK = JRE + Development Tools.

Data Types and Variables

Java is a strongly typed language, meaning every variable must be declared with a data type.

Primitive Data Types

Data Type Size Range Default Value
byte 1 byte -128 to 127 0
short 2 bytes -32,768 to 32,767 0
int 4 bytes -2^31 to 2^31-1 0
long 8 bytes -2^63 to 2^63-1 0L
float 4 bytes ±3.4e^38 0.0f
double 8 bytes ±1.7e^308 0.0d
char 2 bytes 0 to 65,535 '\u0000'
boolean 1 bit true/false false

Variable Declaration and Initialization

// Variable declaration and initialization int age = 25; double salary = 50000.50; char grade = 'A'; boolean isActive = true; String name = "John Doe";
Note: Java has 8 primitive data types and non-primitive data types (classes, interfaces, arrays).

Operators in Java

Operators are special symbols that perform operations on operands.

Types of Operators

  • Arithmetic Operators: +, -, *, /, %
  • Relational Operators: ==, !=, >, <,>=, <=
  • Logical Operators: &&, ||, !
  • Assignment Operators: =, +=, -=, *=, /=
  • Unary Operators: ++, --
  • Bitwise Operators: &, |, ^, ~, <<,>>, >>>
  • Ternary Operator: ? :
// Examples of operators int a = 10, b = 5; int sum = a + b; // Arithmetic boolean result = (a > b); // Relational boolean logic = (a > 0 && b > 0); // Logical a += 5; // Assignment

Control Statements

Control statements determine the flow of execution in a Java program.

Decision Making Statements

  • if statement: Executes block if condition is true
  • if-else statement: Executes one block if true, another if false
  • switch statement: Selects one of many code blocks to execute
// if-else example int marks = 85; if (marks >= 90) { System.out.println("Grade A"); } else if (marks >= 75) { System.out.println("Grade B"); } else { System.out.println("Grade C"); }

Looping Statements

  • for loop: Executes block for specific number of times
  • while loop: Executes block while condition is true
  • do-while loop: Executes block at least once, then repeats while condition is true
// for loop example for (int i = 0; i < 5; i++) { System.out.println(i + " "); } // Output: 0 1 2 3 4

Object-Oriented Programming (OOP) Concepts

Java is a pure object-oriented programming language that supports all OOP principles.

Four Pillars of OOP

  • Encapsulation: Wrapping data and methods into a single unit
  • Inheritance: Creating new classes from existing ones
  • Polymorphism: Ability to take many forms
  • Abstraction: Hiding implementation details

Class and Object

A class is a blueprint for objects, and an object is an instance of a class.

// Class and Object example class Student { // Instance variables private String name; private int age; // Constructor public Student(String name, int age) { this.name = name; this.age = age; } // Method public void display() { System.out.println("Name: " + name + ", Age: " + age); } } // Creating object Student s1 = new Student("John", 20); s1.display();

Inheritance

Inheritance allows a class to inherit properties and behaviors from another class.

Types of Inheritance

  • Single Inheritance: A class inherits from one base class
  • Multilevel Inheritance: A class inherits from a derived class
  • Hierarchical Inheritance: Multiple classes inherit from a single base class
// Single Inheritance example class Animal { // Base class void eat() { System.out.println("Eating..."); } } class Dog extends Animal { // Derived class void bark() { System.out.println("Barking..."); } } // Using inheritance Dog d = new Dog(); d.eat(); // Inherited from Animal d.bark(); // Defined in Dog
Note: Java doesn't support multiple inheritance with classes to avoid complexity, but it supports multiple inheritance with interfaces.

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common super class.

Types of Polymorphism

  • Compile-time Polymorphism (Static): Achieved through method overloading
  • Runtime Polymorphism (Dynamic): Achieved through method overriding
// Method Overloading example class MathOperations { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } }
// Method Overriding example class Animal { void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { void sound() { // Method overriding System.out.println("Dog barks"); } }

Abstraction

Abstraction hides implementation details and shows only essential features.

Abstract Classes

  • Cannot be instantiated
  • Can have abstract and concrete methods
  • Subclasses must implement abstract methods
// Abstract class example abstract class Shape { abstract void draw(); // Abstract method void display() { // Concrete method System.out.println("Displaying shape"); } } class Circle extends Shape { void draw() { // Implementing abstract method System.out.println("Drawing Circle"); } }

Interfaces

  • All methods are abstract by default (before Java 8)
  • Supports multiple inheritance
  • Can have default and static methods (Java 8+)
// Interface example interface Vehicle { void start(); // Abstract method void stop(); // Abstract method default void honk() { // Default method (Java 8+) System.out.println("Honking horn"); } } class Car implements Vehicle { public void start() { System.out.println("Car started"); } public void stop() { System.out.println("Car stopped"); } }

Encapsulation

Encapsulation is the technique of making fields private and providing public methods to access them.

Access Modifiers

Modifier Same Class Same Package Subclass Other Packages
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
// Encapsulation example class BankAccount { private double balance; // Private field // Public getter method public double getBalance() { return balance; } // Public setter method public void setBalance(double balance) { if (balance >= 0) { this.balance = balance; } } }
Exam Tip: Remember the order of access modifiers from most restrictive to least: private → default → protected → public.

Exception Handling

Exception handling allows programs to handle runtime errors gracefully.

Exception Hierarchy

  • Throwable: Superclass of all errors and exceptions
  • Error: Serious problems that applications should not try to catch
  • Exception: Problems that can be caught and handled
  • RuntimeException: Unchecked exceptions
  • Other Exceptions: Checked exceptions

Exception Handling Keywords

  • try: Block of code to test for errors
  • catch: Block of code to handle the error
  • finally: Block of code that always executes
  • throw: Throws an exception explicitly
  • throws: Declares exceptions that a method might throw
// Exception handling example public class ExceptionExample { public static void main(String[] args) { try { int result = 10 / 0; // This will throw ArithmeticException } catch (ArithmeticException e) { System.out.println("Cannot divide by zero: " + e.getMessage()); } finally { System.out.println("This block always executes"); } } }

Multithreading

Multithreading allows concurrent execution of two or more threads for maximum utilization of CPU.

Thread Creation Methods

  • Extending Thread class
  • Implementing Runnable interface
// Thread by extending Thread class class MyThread extends Thread { public void run() { System.out.println("Thread is running"); } } // Thread by implementing Runnable interface class MyRunnable implements Runnable { public void run() { System.out.println("Runnable is running"); } } // Using threads MyThread t1 = new MyThread(); t1.start(); Thread t2 = new Thread(new MyRunnable()); t2.start();

Thread States

  • New
  • Runnable
  • Running
  • Blocked/Waiting
  • Terminated

Collections Framework

Collections framework provides architecture to store and manipulate groups of objects.

Main Collection Interfaces

  • List: Ordered collection, allows duplicates
  • Set: Unordered collection, no duplicates
  • Queue: FIFO ordering
  • Map: Key-value pairs, no duplicate keys

Common Collection Classes

Interface Implementation Classes Characteristics
List ArrayList, LinkedList, Vector Ordered, indexed, allows duplicates
Set HashSet, LinkedHashSet, TreeSet No duplicates, unordered (except LinkedHashSet)
Queue PriorityQueue, LinkedList FIFO, priority-based ordering
Map HashMap, LinkedHashMap, TreeMap, Hashtable Key-value pairs, no duplicate keys
// Collections example import java.util.*; public class CollectionExample { public static void main(String[] args) { // List example List list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); // Set example Set set = new HashSet<>(); set.add(1); set.add(2); // Map example Map map = new HashMap<>(); map.put(1, "One"); map.put(2, "Two"); } }
Important: ArrayList is faster for random access, LinkedList is faster for insertions/deletions. HashMap is not synchronized, while Hashtable is synchronized.