Introduction to Java Programming

Java is a high-level, class-based, object-oriented programming language originally developed at Sun Microsystems and released publicly in 1995. It is designed to be portable across different platforms through the Java Virtual Machine (JVM).

What is Java?

Java allows developers to write programs that are compiled into platform-independent bytecode. This bytecode can be executed on different operating systems using a compatible Java Virtual Machine.

History of Java

  • 1991: The Green Project began at Sun Microsystems, led by James Gosling and others.
  • 1995: Java was publicly released.
  • 2006: Sun began releasing Java technologies as open source.
  • 2010: Oracle completed its acquisition of Sun Microsystems.
  • 2014: Java 8 introduced important features such as lambda expressions and the Stream API.
  • 2018: Java 11 was released as a Long-Term Support (LTS) version.

First Java Program

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

The main() method is the conventional entry point of a standalone Java application. The System.out.println() statement displays text on the console.

Features of Java

Java provides several features that make it suitable for developing desktop applications, web applications, enterprise systems, Android-related software, and many other types of applications.

Key Features of Java

  • Platform Independent: Java source code is compiled into bytecode that can run on different platforms using a JVM.
  • Object-Oriented: Java supports classes, objects, encapsulation, inheritance, polymorphism, and abstraction.
  • Simple: Java was designed with a relatively simple syntax compared with several older programming languages.
  • Secure: Java provides features such as bytecode verification, strong type checking, and controlled memory access.
  • Robust: Automatic memory management, exception handling, and type checking help create reliable applications.
  • Multithreaded: Java provides built-in support for concurrent execution using threads and concurrency APIs.
  • Portable: Java bytecode is designed to behave consistently across supported platforms.
  • High Performance: Modern JVMs use techniques such as Just-In-Time (JIT) compilation to improve execution performance.
Important: Java is not purely compiled or purely interpreted. Java source code is normally compiled into bytecode, and the JVM can interpret or JIT-compile that bytecode during execution.

Java Virtual Machine (JVM)

The Java Virtual Machine (JVM) is the runtime environment that executes Java bytecode. It is an important component responsible for Java's platform-independent execution model.

Major JVM Components

  • Class Loader: Loads Java class files into memory when required.
  • Runtime Data Areas: Includes areas such as the heap, JVM stacks, method area, and program counter registers.
  • Heap: Stores objects and arrays created during program execution.
  • JVM Stack: Contains stack frames used during method execution.
  • PC Register: Keeps track of the current instruction for each thread.
  • Native Method Stack: Supports execution of native methods.
  • Execution Engine: Executes bytecode using interpretation and JIT compilation.

Java Program Execution Process

  1. A programmer writes Java source code in a .java file.
  2. The Java compiler (javac) compiles the source code.
  3. The compiler produces bytecode in a .class file.
  4. The JVM loads the required classes using the Class Loader.
  5. The JVM verifies and executes the bytecode.
  6. The execution engine may interpret bytecode or compile frequently executed code using JIT compilation.

JDK vs JRE vs JVM

Component Meaning Main Purpose
JVM Java Virtual Machine Executes Java bytecode
JRE Java Runtime Environment Provides the runtime environment for Java applications
JDK Java Development Kit Provides tools required to develop Java applications
Exam Tip: Remember the relationship as: JDK = Development Tools + Runtime Environment, while the JVM is the component responsible for executing bytecode.

Data Types and Variables in Java

Java is a statically and strongly typed language. Every variable has a declared type that determines what kind of value it can hold.

Primitive Data Types

Data Type Size Typical Value Range
byte 8 bits -128 to 127
short 16 bits -32,768 to 32,767
int 32 bits -231 to 231-1
long 64 bits -263 to 263-1
float 32 bits Approximately ±3.4 × 1038
double 64 bits Approximately ±1.7 × 10308
char 16 bits 0 to 65,535
boolean Not specified by Java language true or false
Note: Java has eight primitive types: byte, short, int, long, float, double, char, and boolean.

Variable Declaration and Initialization

int age = 25; double salary = 50000.50; char grade = 'A'; boolean isActive = true; String name = "John Doe";

In addition to primitive types, Java provides reference types such as classes, interfaces, arrays, enums, and records.

Operators in Java

Operators are symbols used to perform operations on values and variables.

Types of Java Operators

Operator Type Examples Purpose
Arithmetic +, -, *, /, % Mathematical calculations
Relational ==, !=, >, <, >=, <= Compare values
Logical &&, ||, ! Combine boolean conditions
Assignment =, +=, -=, *=, /= Assign values
Unary ++, --, +, -, ! Operate on a single operand
Bitwise &, |, ^, ~, <<, >>, >>> Perform operations on individual bits
Ternary ? : Short conditional expression
int a = 10; int b = 5; int sum = a + b; boolean result = a > b; boolean valid = (a > 0 && b > 0); a += 5;

Control Statements in Java

Control statements determine the order in which statements are executed in a Java program.

Decision-Making Statements

  • if: Executes a block when a condition is true.
  • if-else: Selects between two alternatives.
  • else-if: Tests multiple conditions.
  • switch: Selects among multiple possible cases.
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: Useful when the number of iterations is known or controlled by a loop expression.
  • while: Repeats while a condition remains true.
  • do-while: Executes the body at least once before checking the condition.
  • enhanced for: Iterates conveniently over arrays and collections.
for (int i = 0; i < 5; i++) { System.out.println(i); } // Output: 0 1 2 3 4

Object-Oriented Programming in Java

Java is a class-based object-oriented programming language. It provides mechanisms for organizing programs using classes, objects, inheritance, interfaces, and other object-oriented concepts.

Four Commonly Discussed Principles of OOP

  • Encapsulation: Combining data and related behavior while controlling access to internal state.
  • Inheritance: Creating a class based on another class.
  • Polymorphism: Allowing the same interface or method call to work with different object implementations.
  • Abstraction: Exposing essential behavior while hiding unnecessary implementation details.

Class and Object

A class defines the structure and behavior of objects. An object is an instance of a class.

class Student { private String name; private int age; public Student( String name, int age) { this.name = name; this.age = age; } public void display() { System.out.println( "Name: " + name + ", Age: " + age ); } } Student s1 = new Student( "John", 20); s1.display();

Inheritance in Java

Inheritance allows a class to acquire accessible fields and methods from another class. The class being inherited from is commonly called the superclass, while the inheriting class is called the subclass.

Common Forms of Class Inheritance

  • Single Inheritance: One subclass extends one superclass.
  • Multilevel Inheritance: A class extends another subclass, forming a chain.
  • Hierarchical Inheritance: Multiple subclasses extend the same superclass.

Java does not allow a class to directly extend multiple classes. However, a class can implement multiple interfaces.

class Animal { void eat() { System.out.println("Eating..."); } } class Dog extends Animal { void bark() { System.out.println("Barking..."); } } Dog d = new Dog(); d.eat(); d.bark();

Polymorphism in Java

Polymorphism means that a common interface or method name can represent different behavior depending on the context.

Method Overloading

Method overloading occurs when a class has multiple methods with the same name but different parameter lists.

class MathOperations { int add( int a, int b) { return a + b; } double add( double a, double b) { return a + b; } }

Method Overriding

Method overriding occurs when a subclass provides its own implementation of an inherited instance method.

class Animal { void sound() { System.out.println( "Animal makes sound"); } } class Dog extends Animal { Override void sound() { System.out.println( "Dog barks"); } }

Abstraction in Java

Abstraction focuses on exposing the essential behavior of an object while hiding implementation details.

Abstract Classes

  • An abstract class cannot be directly instantiated.
  • It can contain abstract methods.
  • It can also contain concrete methods and fields.
  • A concrete subclass generally provides implementations for inherited abstract methods.
abstract class Shape { abstract void draw(); void display() { System.out.println( "Displaying shape"); } } class Circle extends Shape { Override void draw() { System.out.println( "Drawing Circle"); } }

Interfaces

An interface defines a contract that implementing classes agree to follow. Modern Java interfaces can contain abstract methods, default methods, static methods, and other supported interface members.

interface Vehicle { void start(); void stop(); default void honk() { 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 in Java

Encapsulation is the practice of controlling access to an object's internal state and exposing operations through a suitable public interface.

Java Access Modifiers

Modifier Same Class Same Package Subclass in Other Package Other Classes
private Yes No No No
default / package-private Yes Yes No No
protected Yes Yes Yes, under inheritance access rules No
public Yes Yes Yes Yes
class BankAccount { private double balance; public double getBalance() { return balance; } public void setBalance( double balance) { if (balance >= 0) { this.balance = balance; } } }
Exam Tip: For basic accessibility, remember: private → package-private → protected → public, from more restricted to less restricted.

Exception Handling in Java

Exception handling provides a structured way to detect and handle exceptional conditions that occur during program execution.

Exception Hierarchy

  • Throwable: Root type for exceptions and errors that can be thrown.
  • Error: Represents serious conditions generally not intended to be handled by application code.
  • Exception: Represents conditions that applications may handle.
  • RuntimeException: Base class for many unchecked exceptions.

Exception Handling Keywords

  • try: Contains code that may produce an exception.
  • catch: Handles a matching exception.
  • finally: Contains cleanup code that normally executes after try/catch processing.
  • throw: Explicitly throws an exception.
  • throws: Declares exceptions that a method may propagate.
public class ExceptionExample { public static void main(String[] args) { try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println( "Cannot divide by zero."); } finally { System.out.println( "Execution completed."); } } }

Multithreading in Java

Multithreading allows a Java application to perform multiple tasks concurrently. Java provides threads and higher-level concurrency utilities for managing concurrent work.

Common Ways to Create Threads

  • Extending the Thread class.
  • Implementing the Runnable interface.
  • Using higher-level concurrency APIs such as executors.
class MyThread extends Thread { public void run() { System.out.println( "Thread is running"); } } MyThread t1 = new MyThread(); t1.start();

Important Thread States

  • NEW
  • RUNNABLE
  • BLOCKED
  • WAITING
  • TIMED_WAITING
  • TERMINATED

Java Collections Framework

The Java Collections Framework provides interfaces and classes for storing and manipulating groups of objects.

Main Collection Interfaces

  • List: Ordered collection that generally permits duplicate elements.
  • Set: Collection that does not permit duplicate elements.
  • Queue: Collection designed for holding elements before processing.
  • Map: Stores key-value associations. Keys are unique within a map.

Common Collection Classes

Interface Common Implementations Characteristics
List ArrayList, LinkedList, Vector Ordered collection; duplicates are allowed
Set HashSet, LinkedHashSet, TreeSet Does not allow duplicate elements
Queue PriorityQueue, LinkedList Useful for processing elements in a defined queue order
Map HashMap, LinkedHashMap, TreeMap Stores key-value pairs with unique keys
import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class CollectionExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); Map<Integer, String> map = new HashMap<>(); map.put(1, "One"); map.put(2, "Two"); } }
Important: ArrayList provides efficient indexed access in typical use cases, while LinkedList is a linked-list implementation and has different performance characteristics. Choosing between them should depend on the actual access and modification pattern rather than assuming that LinkedList is always faster for insertions or deletions.

Java Programming Summary

Java combines object-oriented programming, automatic memory management, exception handling, concurrency support, and a platform-independent runtime environment. Understanding the fundamentals below provides a strong foundation for learning advanced Java development.

Topic What to Remember
Java Class-based, object-oriented, strongly typed programming language
JVM Executes Java bytecode
JDK Provides tools for Java development
Data Types Eight primitive types plus reference types
OOP Encapsulation, inheritance, polymorphism, abstraction
Exception Handling try, catch, finally, throw, throws
Collections List, Set, Queue and Map
Multithreading Supports concurrent execution and concurrency APIs
Exam Tip: For programming exams, focus on the difference between JVM, JDK and JRE; primitive data types; OOP principles; inheritance; overloading vs overriding; exception handling; and Java collections.