Introduction to Core Java
Java is one of the most widely used, platform-independent, object-oriented programming languages in the world. Designed with the philosophy of "Write Once, Run Anywhere" (WORA), Java has become the foundation for enterprise software, Android mobile applications, web servers, embedded systems, and countless desktop tools. This chapter introduces you to the core concepts of Java — its history, architecture, object-oriented features, syntax fundamentals, and the building blocks you will use throughout this course.
1. History of Java
Java was developed by a team at Sun Microsystems led by James Gosling. Work on the language began in 1991 as a project code-named "Green", originally intended for programming consumer electronics such as interactive television set-top boxes. The initial language was called Oak (named after an oak tree outside Gosling's office), but in 1995 it was renamed Java — inspired by Java coffee from Indonesia — to avoid a trademark conflict.
The first public release, Java 1.0, came in January 1996 and was distinguished by three key promises: simplicity, portability, and security. Over the years Java has evolved through many versions, each adding important features:
- Java 1.0 (1996) — Initial release with AWT for GUI.
- Java 2 (J2SE 1.2, 1998) — Swing, Collections Framework, JIT compiler.
- Java 5 (2004) — Generics, annotations, enhanced for-loop, autoboxing.
- Java 8 (2014) — Lambda expressions, Stream API, new Date/Time API.
- Java 11 (2018) — Long-term support release; HTTP client API.
- Java 17, 21 (LTS) — Sealed classes, pattern matching, records, virtual threads.
Sun Microsystems was acquired by Oracle Corporation in 2010, and Oracle now stewards the Java platform alongside the open-source OpenJDK community.
2. Features of Java
Java's success is driven by a well-defined set of features that make it suitable for both small applications and massive distributed systems:
- Simple — Syntax derived from C/C++ but without pointers, operator overloading, or manual memory management.
- Object-Oriented — Everything in Java (except primitives) is treated as an object; the language is built on classes.
- Platform Independent — Compiled Java code (bytecode) runs on any machine with a JVM.
- Secure — No explicit pointer arithmetic; runs inside a sandboxed JVM with bytecode verification.
- Robust — Strong type-checking, automatic garbage collection, and exception handling reduce runtime errors.
- Multithreaded — Built-in support for concurrent programming through the
Threadclass andjava.util.concurrentpackage. - Architecture-Neutral — Data types have fixed sizes regardless of the underlying hardware.
- Portable — Bytecode and standard library behave identically on every platform.
- High Performance — Just-In-Time (JIT) compilation translates bytecode into native machine code at runtime.
- Distributed — Rich networking APIs (sockets, RMI, HTTP) simplify building distributed applications.
- Dynamic — Classes are loaded on demand; reflection allows runtime inspection and modification.
3. Platform Independence and the JVM
The single most important idea behind Java is platform independence. Unlike C or C++ programs, which are compiled directly into machine-specific executables, a Java program is compiled into an intermediate form called bytecode. Bytecode is stored in .class files and is not tied to any CPU architecture.
This bytecode is executed by the Java Virtual Machine (JVM) — a software abstraction of a computer that reads and runs bytecode. Because JVM implementations exist for Windows, Linux, macOS, Solaris, Android, and many embedded devices, the same .class file runs on all of them without recompilation. This is the essence of "Write Once, Run Anywhere".
JVM Architecture
The JVM consists of several tightly integrated components:
- Class Loader Subsystem — Loads
.classfiles into memory using the Bootstrap, Extension, and Application class loaders. It also verifies the bytecode for safety. - Runtime Data Areas — Memory regions used during execution:
- Method Area — stores class-level data such as fields, methods, and constant pool.
- Heap — stores all objects and arrays; managed by the garbage collector.
- JVM Stacks — each thread has its own stack holding frames for method calls.
- PC Register — holds the address of the current instruction for each thread.
- Native Method Stack — for executing native (non-Java) code.
- Execution Engine — Interprets or JIT-compiles bytecode into native instructions. It also includes the Garbage Collector that reclaims memory from unreachable objects.
- Native Method Interface (JNI) — Bridge for calling native C/C++ libraries when needed.
4. JDK, JRE, and JVM — Understanding the Difference
New Java learners often confuse these three terms. Each serves a distinct purpose:
- JVM (Java Virtual Machine) — The runtime engine that executes bytecode. It is an abstract specification plus a concrete implementation (e.g., HotSpot).
- JRE (Java Runtime Environment) — The JVM plus the standard Java class libraries (
java.lang,java.util,java.io, etc.). If you only need to run Java programs, you only need the JRE. - JDK (Java Development Kit) — The full development package: JRE + compiler (
javac) + debugger (jdb) + archiver (jar) + documentation generator (javadoc) + other development tools. You need the JDK to write and compile Java programs.
Relationship: JDK = JRE + development tools and JRE = JVM + class libraries.
5. Structure of a Java Program
A Java program is organized around classes. The simplest meaningful program prints text to the console:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}Key elements:
public class HelloWorld— declares a public class; the file must be namedHelloWorld.java.public static void main(String[] args)— the entry point for execution. The JVM looks for this exact signature.System.out.println(...)— calls theprintlnmethod of the standard output stream.
To compile and run: use javac HelloWorld.java to produce HelloWorld.class, then execute with java HelloWorld.
6. Object-Oriented Features in Java
Java is fundamentally an object-oriented language. The four pillars of OOP are all first-class citizens in Java:
(a) Encapsulation
Bundling data and the methods that operate on that data into a single unit (the class), while restricting direct access using access modifiers (private, protected, public). This protects the internal state and allows controlled access through getters and setters.
(b) Inheritance
A mechanism where one class (the subclass) acquires the fields and methods of another (the superclass) using the extends keyword. Inheritance promotes code reuse and establishes "is-a" relationships. Java supports single inheritance between classes but allows multiple inheritance of type through interfaces.
(c) Polymorphism
The ability for the same method name or reference to behave differently based on the actual object type. Java supports two forms:
- Compile-time polymorphism — method overloading (same name, different parameters).
- Runtime polymorphism — method overriding (subclass provides specific implementation).
(d) Abstraction
Hiding implementation details and exposing only essential features. In Java, abstraction is achieved through abstract classes and interfaces.
7. Classes and Objects
A class is a blueprint describing the state (fields) and behavior (methods) that its instances will have. An object is an instance of a class created at runtime using the new operator.
class Student {
String name; // field
int rollNo; // field
void display() { // method
System.out.println(rollNo + " - " + name);
}
}
public class Demo {
public static void main(String[] args) {
Student s = new Student(); // object creation
s.name = "Aarav";
s.rollNo = 12;
s.display();
}
}8. Data Types in Java
Java is strongly typed. Every variable must be declared with a type before use. Types fall into two categories:
Primitive types (8 total): byte (1 byte), short (2), int (4), long (8), float (4), double (8), char (2, Unicode), and boolean (true/false).
Reference types: classes, interfaces, arrays, and String. Reference variables store the address of the object on the heap, not the object itself.
9. Operators
Java provides a rich set of operators, grouped by function:
- Arithmetic:
+,-,*,/,% - Relational:
==,!=,<,>,<=,>= - Logical:
&&,||,! - Bitwise:
&,|,^,~,<<,>>,>>> - Assignment:
=,+=,-=,*=, etc. - Ternary:
condition ? ifTrue : ifFalse - instanceof: tests whether an object is an instance of a specific type.
10. Arrays
An array is a container object holding a fixed number of values of a single type. Arrays in Java are objects and are always allocated on the heap.
int[] marks = new int[5]; // one-dimensional array
marks[0] = 85;
int[][] matrix = { {1,2}, {3,4} }; // two-dimensional arrayArray length is accessed via the length field: marks.length. Out-of-bounds access throws an ArrayIndexOutOfBoundsException.
11. Inheritance Example
class Animal {
void eat() { System.out.println("eating..."); }
}
class Dog extends Animal {
void bark() { System.out.println("barking..."); }
}Dog inherits eat() from Animal and adds bark(). A Dog object can call both methods.
12. Interfaces
An interface is a fully abstract "contract" that a class can promise to fulfill using the implements keyword. Since Java 8, interfaces can also contain default and static methods.
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() { System.out.println("Drawing circle"); }
}13. Packages
Packages group related classes and prevent naming collisions. They also serve as access boundaries. Use the package keyword at the top of a source file, and import to use classes from other packages:
package com.notesnp.university;
import java.util.Scanner;Common built-in packages include java.lang (auto-imported), java.util, java.io, and java.net.
14. Exception Handling
An exception is an event that disrupts normal program flow. Java handles exceptions using five keywords: try, catch, finally, throw, and throws.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("Cleanup runs regardless.");
}Java distinguishes checked exceptions (must be declared or caught, e.g., IOException) from unchecked exceptions (subclasses of RuntimeException, e.g., NullPointerException).
15. Control Statements
Control statements direct the flow of execution in a program. Java provides three major categories:
- Selection statements —
if,if-else,if-else-ifladder,switch, and the enhancedswitchexpression (Java 14+). - Iteration statements —
for, enhancedfor-eachloop,while, anddo-while. - Jump statements —
break(exits a loop or switch),continue(skips the current iteration), andreturn(exits a method).
Simple example combining several of these:
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
if (i == 9) break; // stop at 9
System.out.println(i);
}16. Methods and Constructors
A method is a named block of code that performs a task and can optionally return a value. A constructor is a special method that runs automatically when an object is created; it shares the class name and has no return type. Java supports both default constructors (generated by the compiler when none is defined) and parameterized constructors. Constructor overloading lets a class offer multiple ways of initialising an object.
class Book {
String title;
double price;
Book(String t, double p) { // parameterized constructor
this.title = t;
this.price = p;
}
void show() {
System.out.println(title + " Rs. " + price);
}
}17. Strings in Java
The String class in java.lang represents sequences of characters. Strings in Java are immutable — once created, their content cannot change. For mutable strings, Java provides StringBuilder (not thread-safe, faster) and StringBuffer (thread-safe, slightly slower). Common methods include length(), charAt(i), substring(a, b), toUpperCase(), equals(), and concat().
18. Summary
In this chapter, we introduced the Java programming language — its history, the Write Once, Run Anywhere philosophy, and the three-layer platform of JVM, JRE, and JDK. We examined the JVM's internal architecture (class loader, runtime data areas, execution engine), reviewed the core object-oriented pillars Java provides (encapsulation, inheritance, polymorphism, abstraction), and walked through basic syntax including data types, operators, arrays, classes, interfaces, packages, and exception handling. These foundations will carry you through the rest of this course as we build applets, multithreaded programs, GUI applications, networked services, and database-driven systems.
Important Questions
- Explain the JVM architecture with a neat diagram.
- Differentiate between JDK, JRE, and JVM.
- Why is Java called platform-independent? Explain with the concept of bytecode.
- List and briefly explain the four OOP pillars in the context of Java.
- What are checked and unchecked exceptions? Give examples.
- Write a simple Java program that demonstrates inheritance and method overriding.
- What is the difference between a class and an interface in Java?