Java_Unit_1 (1)
Java_Unit_1 (1)
Platform Independence
Java code is compiled into bytecode, which operates on the Java Virtual Machine (JVM).
“Write Once, Run Anywhere” (WORA) – Java programs can be executed on any device equipped
with a JVM.
Object-Oriented
Encourages modular, flexible, and reusable code.
Everything in Java (except primitives) is treated as an object.
Robust and Secure
Features strong memory management, exception handling, and garbage collection.
Offers built-in security features such as bytecode verification and runtime security
policies.
Simple and Familiar
The syntax is akin to C/C++, while eliminating complex features like pointers and multiple
inheritance.
Multithreaded
Java natively supports multithreaded programming, which is beneficial for gaming,
animation, and real-time applications.
Rich API and Libraries
Provides a vast standard library that encompasses everything from networking to data
structures.
Dynamic and Distributed
Crafted for use in the distributed environment of the internet, supporting remote
method invocation (RMI) and dynamic class loading.
History of Java
Early 1990s – The Birth of Java
Java was conceived by James Gosling and his team at Sun Microsystems in 1991, originally named the “Green
Project.” The first version was aimed at embedded systems for consumer electronics like set-top boxes and
televisions.
Java was officially launched as Java 1.0 in 1995, marketed as a tool for crafting interactive
web content, with applets being particularly popular.
Java 1.2 (1998) – Introduced the Swing toolkit and Collections Framework.
Java 5 (2004) – Added generics, enhanced for-loop, enums, and autoboxing.
Java 8 (2014) – Major update featuring Lambda expressions, Streams API, and a new
Date/Time API.
Java 11 (2018) – LTS version; removed Applet, added var, and introduced HTTP Client API.
Java 17 (2021) – LTS version; introduced sealed classes and pattern matching.
Java 21 (2023) – The latest LTS version with performance enhancements and new
features.
The Java Virtual Machine (JVM) is an abstract computing machine that enables a computer to
execute Java programs. It converts compiled bytecode (.class files) into machine code for
execution, ensuring Java's platform independence.
Role of JVM:
Loads the Class: The Class Loader subsystem imports .class files (bytecode) into the JVM.
Verifies the Bytecode: Ensures that the code is valid, secure, and complies with Java’s
security model.
Executes the Bytecode: Utilizes an interpreter or JIT (Just-In-Time) compiler to translate
bytecode into native machine code.
Memory Management: Allocates memory and manages Garbage Collection automatically.
Security Management: Enforces access restrictions and prevents unauthorized actions
through the Security Manager and Bytecode Verifier.
Execution Flow:
Note: “The JVM is the heart of Java’s cross-platform capabilities, allowing Java programs to
run in a controlled and secure manner.”
Important Points:
What is a Class?
1. A class in Java serves as a user-defined data type, encapsulating data (fields) and
behaviors (methods) into a single unit. Think of it as a template or blueprint for creating
individual objects.
2. A class outlines the structure and behavior of future objects.
3. No memory is allocated upon defining a class; memory is reserved when objects are
instantiated.
class ClassName {
// Fields (Instance Variables)
// Methods
}
class Car {
String model;
int year;
void displayInfo() {
System.out.println("Model: " + model + ", Year: " + year);
}
}
What is an Object?
An object is a runtime instance of a class, representing a specific implementation of the
class's structure. When a class is instantiated, an object is created with its unique copy of
instance variables and access to class methods.
Each Object:
1. Occupies memory.
2. Has its own identity and state.
myCar.model = "Tesla";
myCar.year = 2023;
myCar.displayInfo();
Instance Variables
Instance variables are non-static fields declared within a class but outside any method,
constructor, or block. Each object (instance) of the class receives its own separate copy
of these variables.
Key Characteristics:
Syntax
class Student {
String name; // instance variable
int rollNumber; // instance variable
}
Instance Methods
Instance methods are non-static methods that operate on instance variables of the class.
They require an object for invocation and can directly access all non-static members.
Key Characteristics:
Syntax
class Book {
String title;
int price;
void show() {
System.out.println("Book: " + title + ", Price: " + price);
}
}
class Employee {
String name;
double salary;
void setDetails(String empName, double empSalary) {
name = empName;
salary = empSalary;
}
void showDetails() {
System.out.println("Employee Name: " + name);
System.out.println("Salary: ₹" + salary);
}
}
Example
class Counter {
static int count = 0; // static variable
Counter() {
count++; // increments the same variable for all objects
System.out.println("Count: " + count);
}
}
Static Methods
Example:
class MathUtil {
static int square(int x) {
return x * x;
}
}
What is a Constructor?
A constructor in Java is a special method used to initialize objects upon creation. It shares
the same name as the class and lacks a return type — not even void.
Key Characteristics of Constructors:
Types of Constructors:
1.Default Constructor:
A) Automatically supplied by Java if no constructor is defined.
B) Initializes fields with default values (e.g., 0, null, false).
Example:
class Student {
String name;
int age;
// Default constructor (automatically provided if you don’t define any)
Student() {
name = "Unknown";
age = 0;
}
void show() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
2.Parameterized Constructor:
A) Used to initialize fields with custom values.
Example:
class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
}
void show() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
3.Constructor Overloading:
A) Java permits multiple constructors in the same class with varied parameter types or
counts.
Example:
class Box {
int length, width;
Box() {
length = width = 0;
}
Box(int l, int w) {
length = l;
width = w;
}
void show() {
System.out.println("Length: " + length + ", Width: " + width);
}
}
Example:
class Employee {
String name;
int id;
Employee() {
this("Default", 0); // calls parameterized constructor
}
Employee(String name, int id) {
this.name = name;
this.id = id;
}
void show() {
System.out.println("Name: " + name + ", ID: " + id);
}
}
Note:
1. If you define any constructor, Java will not provide the default one.
2. Constructor overloading offers flexibility during object creation.
3. Using this() helps avoid code duplication and ensures clean initialization.
this Keyword in Java
The this keyword is a special reference variable in Java that refers to the current object — the
object on which a method or constructor is executed. It is useful in situations where the
context may be unclear, such as when instance variable names and parameters overlap. It
also aids in method chaining, constructor chaining, and passing the current object to other
methods or constructors.
When method or constructor parameters share names with instance variables, this is used to
differentiate them.
Example:
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name; // 'this.name' refers to the instance variable
this.age = age; // 'age' refers to the parameter
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
Used for constructor chaining, where one constructor invokes another within the same class
to avoid code duplication.
Example:
class Box {
int length, width;
Box() {
this(0, 0); // Must be the first line
}
Box(int l, int w) {
this.length = l;
this.width = w;
}
}
The current object can be passed using this to methods that require an object reference as an
argument.
Example:
class A {
void show(A obj) {
System.out.println("Called with object: " + obj);
}
void call() {
show(this); // passing current object
}
}
1. Encapsulation:
Encapsulation is the practice of binding data (variables) and code (methods) into a single unit
— a class — while restricting direct access to some of the object's components.
Example:
2. Inheritance:
Note:
This mechanism promotes code reuse, hierarchical classification, and extensibility.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (via interface)
Note: Java does not support Multiple Inheritance (via class) to avoid ambiguity.
Syntax:
class SuperClass {
// fields and methods
}
class SubClass extends SuperClass {
// inherits from SuperClass
}
Key Features:
1. Subclasses inherit all accessible fields and methods from the superclass.
2. A subclass can add new members or override existing ones.
3. Inheritance supports method overriding for dynamic behavior.
Single Inheritance:
Single Inheritance is the simplest and most widely used form of inheritance in Java. In single
inheritance, a single subclass inherits the members (fields and methods) of one superclass.
NOTE:
Example:
// Superclass (Parent)
class Animal {
String name;
void eat() {
System.out.println(name + " is eating.");
}
void sleep() {
System.out.println(name + " is sleeping.");
}
}
// Subclass (Child)
class Dog extends Animal {
void bark() {
System.out.println(name + " is barking.");
}
}
Multilevel Inheritance:
Multilevel inheritance refers to a scenario where a class is derived from another class, which
itself is derived from a third class. This creates an inheritance chain of multiple levels.
Example:
Class C inherits from Class B, and Class B inherits from Class A.
// Base class
class Animal {
void eat() {
System.out.println("Animal eats food.");
}
}