0% found this document useful (0 votes)
1 views65 pages

UNIT 1 (OOPs)

The document provides a comprehensive overview of the Java Virtual Machine (JVM) architecture, including its key components such as the Class Loader, Runtime Data Areas, Execution Engine, and Native Interface. It also discusses the advantages of Java, its history, and the differences between JRE and JDK, as well as fundamental concepts of Java programming like classes, inheritance, and interfaces. Additionally, it explains the compilation process and the role of constructors in Java.

Uploaded by

lets.troll4u
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)
1 views65 pages

UNIT 1 (OOPs)

The document provides a comprehensive overview of the Java Virtual Machine (JVM) architecture, including its key components such as the Class Loader, Runtime Data Areas, Execution Engine, and Native Interface. It also discusses the advantages of Java, its history, and the differences between JRE and JDK, as well as fundamental concepts of Java programming like classes, inheritance, and interfaces. Additionally, it explains the compilation process and the role of constructors in Java.

Uploaded by

lets.troll4u
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/ 65

UNIT-1

The Java Virtual Machine (JVM) is the engine that runs Java applications. It provides a runtime
environment that abstracts away the underlying hardware and operating system, allowing Java
programs to be write once, run anywhere. Here's an overview of the JVM architecture:

Key Components of JVM Architecture

1. Class Loader Subsystem

 Function: Loads .class files (compiled Java code) into the JVM.
 Phases:
o Loading: Loads class files from the file system, network, or JARs.
o Linking: Verifies, prepares (allocates memory), and optionally resolves
symbolic references.
o Initialization: Initializes static variables and executes static blocks.

2. Runtime Data Areas

These are memory areas used during execution:

 Method Area: Stores class-level information such as metadata, static variables, and
method definitions.
 Heap: Stores all objects and class instances (shared memory, used by GC).
 Java Stack: Each thread has its own stack; stores frames (method calls), local
variables, and partial results.
 Program Counter (PC) Register: Holds the address of the current instruction being
executed by the thread.
 Native Method Stack: For native (non-Java) method execution using JNI (Java
Native Interface).

3. Execution Engine

Responsible for executing the bytecode loaded into memory.

 Interpreter: Reads and executes bytecode line-by-line. Slower but starts quickly.
 Just-In-Time (JIT) Compiler: Converts frequently executed bytecode into native
machine code for faster execution.
 Garbage Collector (GC): Automatically reclaims memory from unused objects in
the heap.

4. Native Interface (JNI)

 Allows Java code to call or be called by native applications (e.g., written in C or


C++).

5. Native Method Libraries

 Libraries (e.g., DLLs or shared objects) that contain platform-specific native code
accessed via JNI.

🧠 JVM Workflow Summary

1. Java source code (.java) → Compiled by javac → Bytecode (.class)


2. Class Loader loads bytecode into JVM.
3. Execution Engine interprets or compiles bytecode.
4. Runtime Data Areas manage memory and execution state.
5. Garbage Collector runs periodically to clean up unused objects.

Why Java?

Java is one of the most popular programming languages due to several key advantages:

1. Platform Independence

 Java code is compiled into bytecode, which runs on any system with a Java Virtual
Machine (JVM).
 Write once, run anywhere.

2. Object-Oriented

 Promotes modular, reusable, and maintainable code through encapsulation,


inheritance, and polymorphism.

3. Robust and Secure


 Strong memory management with automatic Garbage Collection.
 Built-in security features and a sandbox model for running untrusted code.

4. Multithreading

 Supports multiple threads of execution, making it ideal for interactive and high-
performance apps.

5. Rich Standard Library

 Huge set of APIs for networking, I/O, data structures, GUIs, and more.

6. Community and Ecosystem

 Massive open-source ecosystem, libraries, and active community support.


 Widely used in enterprise applications, Android development, big data (e.g., Hadoop),
and cloud computing.

History of Java

Year Milestone

Project Green initiated by James Gosling, Mike Sheridan, and Patrick Naughton at Sun
1991
Microsystems. Original goal: a language for interactive TVs.

Language renamed from Oak to Java (Oak was already trademarked). Java 1.0 officially
1995
released.

1996 Java Development Kit (JDK) 1.0 released. Quickly gained popularity for web applets.

Java 2 (J2SE, J2EE, J2ME) introduced, separating the platform into Standard, Enterprise,
1999
and Micro Editions.

2006 Java becomes open-source under the GNU GPL (OpenJDK).

2010 Oracle acquires Sun Microsystems and takes over Java development.

2014– Introduction of new features like Lambda expressions, Streams, Modules (Java 9), var
Present keyword (Java 10), and pattern matching, records, virtual threads in newer versions.

Java continues to evolve with regular releases every 6 months and is heavily used in
Now
enterprise, Android, backend, and cloud systems.

JVM (Java Virtual Machine)

 What it is: A virtual machine that runs Java bytecode.


 Role: Executes compiled Java programs (.class files).
 Includes:
o Class loader
o Bytecode verifier
o Runtime memory (heap, stack)
o Execution engine (interpreter + JIT compiler)
 Platform-dependent: Each OS has its own JVM implementation.
 Does not include: Tools for development (e.g., compiler).

Used for: Running Java programs.

JRE (Java Runtime Environment)

 What it is: A package that provides the environment to run Java programs.
 Includes:
o JVM
o Java class libraries (like java.lang, java.util)
o Supporting files and configurations
 Does not include: Development tools like javac (compiler) or javadoc.

Used by: End-users to run Java applications.

JDK (Java Development Kit)

 What it is: A full-featured software development kit for developing and running
Java programs.
 Includes:
o JRE (which includes JVM)
o Development tools:
 javac (Java compiler)
 javadoc (documentation tool)
 jar, javap, etc.

Used by: Developers to write, compile, and run Java code.

Java Source File Structure

A basic Java source file (.java) consists of the following elements:

1. Package Declaration (optional, top of the file):


package com.example.myapp;
2. Import Statements (optional):

import java.util.Scanner;

import java.util.List;

3. Class Declaration (mandatory):

public class HelloWorld {

// Fields (variables)
int number;

// Constructor

public HelloWorld() {

number = 0;

// Methods

public void greet() {

System.out.println("Hello, world!");

// Main method (entry point)

public static void main(String[] args) {

HelloWorld obj = new HelloWorld();

obj.greet();

Rules:

 File name must match the public class name: HelloWorld.java.


 You can have multiple classes in one file, but only one public class.

Compilation Process (How Java Code is Executed)

Step-by-step Flow:

1. Write Code

File: HelloWorld.java
2. Compile

javac HelloWorld.java

 This converts source code into bytecode.

 Output: HelloWorld.class

3. Run

java HelloWorld

Diagram:

HelloWorld.java (Source Code)

[javac]

HelloWorld.class (Bytecode)

[java]

JVM interprets or compiles → Output: Hello, world!

Java Fundamentals
Concept Description

Class Blueprint for creating objects. Contains fields and methods.

Object Instance of a class.

Method A block of code that performs a task (like a function).

Main Method Entry point: public static void main(String[] args)

Variable Types int, double, String, boolean, etc.

Access Modifiers public, private, protected, default

OOP Concepts Inheritance, Encapsulation, Abstraction, Polymorphism


Concept Description

Comments // single-line, /* multi-line */

Class

In Java, a class is a blueprint for creating objects. It defines the structure (fields) and behavior
(methods) of objects. Java supports several types of classes, each serving different purposes.

What is a Concrete Class in Java?

A concrete class is a fully implemented class in Java — it is not abstract, which means:

 It can be instantiated (i.e., you can create objects from it).


 It provides complete implementations for all of its methods.
 It may implement interfaces or extend abstract classes but must define all abstract
methods if it does.

Example of a Concrete Class(REGULAR CLASS)

public class Car {

// Fields (variables)

String brand;

int speed;

// Constructor

public Car(String brand, int speed) {

this.brand = brand;

this.speed = speed;

// Method

public void drive() {

System.out.println(brand + " is driving at " + speed + " km/h.");

}
}

public class Test {

public static void main(String[] args) {

Car myCar = new Car("Toyota", 80); // ✅ Creating an object

myCar.drive(); // Output: Toyota is driving at 80 km/h.

What is an Abstract Class in Java?

An abstract class in Java is a class that cannot be instantiated directly. It is used as a base
class to be extended by other classes.

Key Features:

 Can have both abstract methods (without implementation) and concrete methods
(with implementation).
 Used to define a common template or contract for subclasses.
 A subclass must override all abstract methods (unless it is also abstract).

Abstract Class Example in Java

// Abstract class

abstract class Animal {

// Abstract method (no body)

abstract void makeSound();

// Concrete method (has body)

void eat() {

System.out.println("This animal eats food.");

}
}

// Subclass that extends the abstract class

class Dog extends Animal {

// Implementation of abstract method

void makeSound() {

System.out.println("Dog barks");

// Main class

public class Test {

public static void main(String[] args) {

// Animal a = new Animal(); ❌ Cannot instantiate abstract class

Dog myDog = new Dog(); // ✅ Instantiate subclass

myDog.makeSound(); // Output: Dog barks

myDog.eat(); // Output: This animal eats food.

OUTPUT:

Dog barks

This animal eats food.

Why Use Abstract Classes?

 When you want to provide a partial implementation and let child classes fill in the
specific behavior.
 When multiple related classes share common code and structure.
Feature Abstract Class
Can have abstract methods? ✅ Yes
Can have concrete methods? ✅ Yes
Can be instantiated? ❌ No
Used for inheritance? ✅ Yes

What is Inheritance?

Inheritance is a core concept of Object-Oriented Programming (OOP) in Java. It allows one class to
acquire the properties and behaviors (fields and methods) of another class.

 Promotes code reusability.


 Establishes a parent-child relationship (also called superclass-subclass).

Syntax:

class Parent {

// fields and methods

class Child extends Parent {

// additional fields and methods

Types of Inheritance in Java

Java supports single, multilevel, hierarchical, and hybrid (via interfaces). It does not support
multiple inheritance with classes directly (to avoid ambiguity), but it supports it through interfaces.

1. ✅ Single Inheritance

One subclass inherits from one superclass.

class Animal {

void eat() {

System.out.println("This animal eats food.");

}
}

class Dog extends Animal {

void bark() {

System.out.println("Dog barks.");

public class Test {

public static void main(String[] args) {

Dog d = new Dog();

d.eat(); // Inherited method

d.bark(); // Dog-specific method

Output:

This animal eats food.

Dog barks.

2. ✅ Multilevel Inheritance

A class inherits from a subclass, forming a chain.

class Animal {

void eat() {

System.out.println("Eating...");

}
}

class Dog extends Animal {

void bark() {

System.out.println("Barking...");

class Puppy extends Dog {

void weep() {

System.out.println("Weeping...");

public class Test {

public static void main(String[] args) {

Puppy p = new Puppy();

p.eat(); // From Animal

p.bark(); // From Dog

p.weep(); // From Puppy

Output:

Eating...

Barking...
Weeping...

3. ✅ Hierarchical Inheritance

Multiple classes inherit from a single superclass.

class Animal {

void eat() {

System.out.println("Animal eats.");

class Dog extends Animal {

void bark() {

System.out.println("Dog barks.");

class Cat extends Animal {

void meow() {

System.out.println("Cat meows.");

public class Test {

public static void main(String[] args) {

Dog d = new Dog();


Cat c = new Cat();

d.eat();

d.bark();

c.eat();

c.meow();

Output:

Animal eats.

Dog barks.

Animal eats.

Cat meows.

4. ❌ Multiple Inheritance (Not Supported with Classes)

class A {

void msg() { System.out.println("Hello from A"); }

class B {

void msg() { System.out.println("Hello from B"); }

// ❌ Not allowed in Java


// class C extends A, B { } // Compile-time error

Why not?

 Ambiguity: If both A and B have msg(), which one does C inherit?

5. ✅ Multiple Inheritance via Interfaces (Supported)

interface A {

void printA();

interface B {

void printB();

class C implements A, B {

public void printA() {

System.out.println("From interface A");

public void printB() {

System.out.println("From interface B");

public class Test {

public static void main(String[] args) {

C obj = new C();


obj.printA();

obj.printB();

Output:

From interface A
From interface B

What is an Interface in Java?

An interface in Java is a contract that defines a set of abstract methods (method signatures
only), which implementing classes must define. Interfaces are used to achieve abstraction
and multiple inheritance (since Java doesn’t allow multiple class inheritance).

Since Java 8, interfaces can also contain:

 default methods → with body


 static methods → with body

Key Features of Interfaces:

 Used to achieve abstraction and multiple inheritance.


 A class uses implements to inherit an interface.
 All methods in an interface are public and abstract by default (except static/default
methods).
 Multiple interfaces can be implemented by a single class.

Example: Interface with Abstract, Default, and Static Methods

interface Vehicle {

// Abstract method

void start();

// Default method (with body)

default void fuelType() {

System.out.println("Uses petrol or diesel.");


}

// Static method (with body)

static void vehicleInfo() {

System.out.println("All vehicles have wheels.");

// Implementing class

class Car implements Vehicle {

public void start() {

System.out.println("Car starts with a key.");

// Main class

public class TestInterface {

public static void main(String[] args) {

Car myCar = new Car();

myCar.start(); // Implemented method

myCar.fuelType(); // Default method from interface

Vehicle.vehicleInfo(); // Static method (called with interface name)

}
OUTPUT:

Car starts with a key.

Uses petrol or diesel.

All vehicles have wheels.

Notes:

 default methods allow backward compatibility — new methods can be added to interfaces
without breaking old implementations.
 static methods in interfaces are not inherited; they must be called using the interface
name.

Difference between abstraction and interface in java

Abstraction vs Interface in Java


Feature Abstract Class Interface

Partial abstraction (can include Full abstraction (only method


Purpose
logic) signatures, mostly)

Keyword abstract class interface

Supports multiple inheritance (via


Inheritance Supports single inheritance only
implements)

Abstract (by default) + default &


Method Types Abstract + Concrete methods
static methods (since Java 8)

Constructor Can have constructors ❌ Cannot have constructors

Can have any access modifier All variables are public static
Variables
(private, protected, etc.) final (constants) by default

Access Modifiers for Can be private, protected,


Only public methods are allowed
Methods public, etc.

Multiple ❌ A class can extend only one ✅ A class can implement multiple
Implementation abstract class interfaces

When classes are closely related When unrelated classes need to follow a
When to Use?
and share code common contract
What is a Constructor in Java?

A constructor is a special method in Java used to initialize objects. It has:

 The same name as the class


 No return type (not even void)
 Is automatically called when an object is created

Key Characteristics:

 Used to set initial values for object fields


 Overloading is allowed (multiple constructors with different parameters)

Types of Constructors in Java


Type Description

No parameters, either provided by Java or defined explicitly by the


1. Default Constructor
programmer

2. Parameterized
Takes arguments to initialize object with specific values
Constructor

3. Copy Constructor (custom- Used to create a copy of an existing object (not built-in like C++, but
made) can be written manually)

1 Default Constructor (No Parameters)

class Car {

Car() {

System.out.println("Default constructor called");

public class Test {

public static void main(String[] args) {

Car c = new Car(); // Constructor automatically called

}
}

OUTPUT:

Default constructor called

2 Parameterized Constructor

class Car {

String brand;

int year;

Car(String b, int y) {

brand = b;

year = y;

void display() {

System.out.println(brand + " - " + year);

public class Test {

public static void main(String[] args) {

Car c1 = new Car("Toyota", 2022);

c1.display();

OUTPUT:
Toyota – 2022

3 Copy Constructor (Custom-made)

class Car {

String brand;

// Parameterized constructor

Car(String b) {

brand = b;

// Copy constructor

Car(Car c) {

brand = c.brand;

void display() {

System.out.println("Brand: " + brand);

public class Test {

public static void main(String[] args) {

Car car1 = new Car("Honda");

Car car2 = new Car(car1); // Using copy constructor


car2.display(); // Output: Brand: Honda

OUTPUT:

Brand: Honda

Notes:

 If no constructor is defined, Java provides a default constructor.


 Once you define any constructor, Java will not provide the default one automatically.
 Constructors can be overloaded just like methods.

What is a Copy Constructor in Java?

A copy constructor in Java is a constructor that creates a new object by copying the fields of
another object of the same class.

💡 Unlike C++, Java does not provide a built-in copy constructor — but you can define your own.

🧱 Why Use a Copy Constructor?

 To create a duplicate object with the same data.


 Useful when you want to clone an object safely (especially in immutable or defensive
copies).

✅ Syntax of a Copy Constructor

ClassName(ClassName obj) {
// copy fields from obj
}
Note:

 Java also provides a clone() method via the Cloneable interface, but it's often
considered less safe and less readable than a custom copy constructor.

Constructor Overloading in Java

Constructor overloading is a feature in Java where you can have multiple constructors in the same
class with different parameters. It allows you to create objects in different ways based on the
number or type of arguments passed to the constructor.

In constructor overloading, the constructor name remains the same (class name), but the
parameter list (number or types of parameters) must be different.
Key Points of Constructor Overloading

 Constructors in Java are not inherited.


 You can have multiple constructors with the same name but with different parameter
lists.
 The constructor is invoked when an object is created using the new keyword.

Constructor Overloading Example

class Person {

private String name;

private int age;

// Constructor with only name parameter

public Person(String name) {

this.name = name;

this.age = 0; // Default age

System.out.println("Person name: " + name + ", Age: " + age);

// Constructor with name and age parameters

public Person(String name, int age) {

this.name = name;

this.age = age;

System.out.println("Person name: " + name + ", Age: " + age);

// Constructor with no parameters

public Person() {
this.name = "Unknown";

this.age = 0;

System.out.println("Person name: " + name + ", Age: " + age);

public class ConstructorOverloadingExample {

public static void main(String[] args) {

// Creating object using constructor with only name

Person person1 = new Person("Alice");

// Creating object using constructor with name and age

Person person2 = new Person("Bob", 30);

// Creating object using constructor with no parameters

Person person3 = new Person();

Output:

Person name: Alice, Age: 0

Person name: Bob, Age: 30

Person name: Unknown, Age: 0

PYQ 2024
Illustrate Constructors and their applications in java. Describe the types of constructors used in java.
Write a class with name Student and attributes roll_number, name, branch and email.write all
argument constructor for class Student and create two objects with this constructor.

What is a Constructor?

A constructor in Java is a special method used to initialize objects. It is called automatically when an
object is created using the new keyword.

Applications of Constructors

1. Initialize object fields automatically


2. Overload constructors to handle multiple initialization cases
3. Improve code readability and reduce redundancy
4. Create copies of objects (using copy constructors)
5. Support constructor chaining

Types of Constructors in Java


Type Description

Default Constructor No arguments; initializes object with default values.

Parameterized Constructor Takes arguments to set custom values during object creation.

Copy Constructor (custom) Creates a new object by copying an existing object manually.

Example: Student Class with All-Argument Constructor

// Define the Student class

class Student {

// Attributes (fields)

int roll_number;

String name;

String branch;

String email;

// All-argument constructor
Student(int roll_number, String name, String branch, String email) {

this.roll_number = roll_number;

this.name = name;

this.branch = branch;

this.email = email;

// Method to display student information

void displayInfo() {

System.out.println("Roll Number: " + roll_number);

System.out.println("Name : " + name);

System.out.println("Branch : " + branch);

System.out.println("Email : " + email);

System.out.println("------------------------------");

// Main class to test

public class TestStudent {

public static void main(String[] args) {

// Creating two Student objects using all-argument constructor

Student s1 = new Student(101, "Alice", "Computer Science", "[email protected]");

Student s2 = new Student(102, "Bob", "Electronics", "[email protected]");

// Display their information


s1.displayInfo();

s2.displayInfo();

Output:

Roll Number: 101

Name : Alice

Branch : Computer Science

Email : [email protected]

------------------------------

Roll Number: 102

Name : Bob

Branch : Electronics

Email : [email protected]

------------------------------

Different Types of Methods in Java with Examples

In Java, methods are blocks of code designed to perform a specific task. They improve code
reusability, readability, and structure.

Types of Methods in Java


Type Description

1. Instance Method Belongs to an object; accessed through object reference

2. Static Method Belongs to the class; called using the class name

3. Parameterized Method Accepts parameters to perform tasks with inputs

4. Return Type Method Returns a value to the caller

5. Void Method Performs an action but does not return anything

6. Constructor (Special) Not a typical method, but used to initialize objects


EXAMPLE:

public class MethodExamples {

// 1. Instance Method

void greet() {

System.out.println("Hello from an instance method.");

// 2. Static Method

static void showStatic() {

System.out.println("Hello from a static method.");

// 3. Parameterized Method

void printSum(int a, int b) {

int sum = a + b;

System.out.println("Sum is: " + sum);

// 4. Method with Return Type

int square(int num) {

return num * num;

// 5. Void Method
void sayGoodbye() {

System.out.println("Goodbye!");

public static void main(String[] args) {

// Create object to call instance methods

MethodExamples obj = new MethodExamples();

// Calling methods

obj.greet(); // Instance method

MethodExamples.showStatic(); // Static method

obj.printSum(10, 20); // Parameterized method

int result = obj.square(5); // Return type method

System.out.println("Square: " + result);

obj.sayGoodbye(); // Void method

Output:
Hello from an instance method.
Hello from a static method.
Sum is: 30
Square: 25
Goodbye!

Abstract Method in Java

An abstract method in Java is a method without a body — it only has a declaration. Abstract
methods must be defined in an abstract class or an interface, and they must be overridden by the
subclass that extends or implements them.
Key Points:

 Declared using the abstract keyword.


 No body (no implementation) — ends with a semicolon ;.
 Must be in an abstract class or interface.
 Must be overridden in the first non-abstract subclass.

Example: Abstract Method in Abstract Class


abstract class Animal {
// Abstract method
abstract void makeSound();

// Concrete method
void sleep() {
System.out.println("Sleeping...");
}
}

class Dog extends Animal {


// Implementing the abstract method
void makeSound() {
System.out.println("Dog barks");
}
}

public class Test {


public static void main(String[] args) {
Dog d = new Dog();
d.makeSound(); // Output: Dog barks
d.sleep(); // Output: Sleeping...
}
}
Output:
Dog barks
Sleeping...

Why Use Abstract Methods?

 To define a template or contract for subclasses.


 Helps achieve abstraction in OOP.
 Useful in frameworks and APIs where the base class defines required behavior, but
subclasses implement the details.

Access Specifies in Java with Examples

Types of Access Specifiers in Java


Access Specifier Accessible Within Keyword

public Everywhere (all classes and packages) public

private Only within the same class private

protected Same package & subclasses (even in different packages) protected


Access Specifier Accessible Within Keyword

Default (no keyword) Same package only (no keyword)

Example Code Demonstrating All Access Specifiers

package mypackage;

public class AccessExample {

public int publicVar = 1;

private int privateVar = 2;

protected int protectedVar = 3;

int defaultVar = 4; // default access

public void publicMethod() {

System.out.println("Public Method");

private void privateMethod() {

System.out.println("Private Method");

protected void protectedMethod() {

System.out.println("Protected Method");

void defaultMethod() {
System.out.println("Default Method");

public void testAccess() {

System.out.println("Inside same class:");

System.out.println(publicVar); // ✅

System.out.println(privateVar); // ✅

System.out.println(protectedVar); // ✅

System.out.println(defaultVar); // ✅

publicMethod(); // ✅

privateMethod(); // ✅

protectedMethod(); // ✅

defaultMethod(); // ✅

Access from Another Class in Same Package

package mypackage;

public class SamePackageTest {

public static void main(String[] args) {

AccessExample obj = new AccessExample();

System.out.println(obj.publicVar); // ✅
// System.out.println(obj.privateVar); // ❌ Error

System.out.println(obj.protectedVar); // ✅

System.out.println(obj.defaultVar); // ✅

obj.publicMethod(); // ✅

// obj.privateMethod(); // ❌ Error

obj.protectedMethod(); // ✅

obj.defaultMethod(); // ✅

Access from Subclass in Another Package

package otherpackage;

import mypackage.AccessExample;

public class SubClass extends AccessExample {

public static void main(String[] args) {

SubClass obj = new SubClass();

System.out.println(obj.publicVar); // ✅

// System.out.println(obj.privateVar); // ❌

System.out.println(obj.protectedVar); // ✅ (because it's a subclass)

// System.out.println(obj.defaultVar); // ❌

obj.publicMethod(); // ✅
// obj.privateMethod(); // ❌

obj.protectedMethod(); // ✅

// obj.defaultMethod(); // ❌

Summary Table:
Modifier Class Package Subclass (Other Pkg) Other Pkg

public ✅ ✅ ✅ ✅

default ✅ ✅ ❌ ❌

protected ✅ ✅ ✅ ❌

private ✅ ❌ ❌ ❌

Static Members in Java

In Java, static members (variables and methods) belong to the class rather than to instances
(objects) of the class.

Types of Static Members


Member Type Description

static variable Shared across all objects of the class (like a global variable)

static method Belongs to the class, can be called without creating an object

static block Used for static initialization, runs once when the class is loaded

static class (nested only) A static inner class that doesn’t require outer class instance

Example of Static Members

public class Student {

// Static variable

static String college = "ABC University";


// Instance variables

int id;

String name;

// Constructor

Student(int id, String name) {

this.id = id;

this.name = name;

// Static method

static void changeCollege(String newCollege) {

college = newCollege;

// Instance method

void display() {

System.out.println(id + " " + name + " " + college);

public static void main(String[] args) {

Student s1 = new Student(101, "Alice");

Student s2 = new Student(102, "Bob");

// Display before change


s1.display();

s2.display();

// Change static variable using static method

Student.changeCollege("XYZ Institute");

// Display after change

s1.display();

s2.display();

Output:

101 Alice ABC University

102 Bob ABC University

101 Alice XYZ Institute

102 Bob XYZ Institute

Key Points:

 static variables are shared among all objects.


 static methods cannot access non-static variables directly.
 You don't need to create an object to call a static method.
 Static blocks are used to initialize static variables during class loading.

Static Block Example

class Example {

static int x;
// Static block runs once when class is loaded

static {

x = 10;

System.out.println("Static block executed");

public static void main(String[] args) {

System.out.println("x = " + x);

Output:

Static block executed

x = 10

Final Members in Java

The final keyword in Java is used to declare constants or prevent modification of variables,
methods, or classes.

Types of Final Members


Final Type Meaning

final variable Cannot be reassigned once initialized (constant)

final method Cannot be overridden by subclasses

final class Cannot be extended (no subclass can inherit it)

1. Final Variable (Constant)

class Circle {

final double PI = 3.14159; // Constant


void displayArea(double radius) {

double area = PI * radius * radius;

System.out.println("Area: " + area);

Note: If you try to reassign PI, you'll get a compile-time error.

2. Final Method (Can't Be Overridden)

class Vehicle {

final void run() {

System.out.println("Vehicle is running");

class Car extends Vehicle {

// void run() {} // ❌ Error: Cannot override final method

4. Final Class (Can't Be Extended)

final class Animal {

void makeSound() {

System.out.println("Animal sound");

// class Dog extends Animal {} // ❌ Error: Cannot inherit from final class
Additional Notes:

 Final variables must be initialized once — either during declaration or in the constructor.
 Final is often used for:
o Constants
o Security (e.g., to prevent method overriding)
o Thread safety (for immutable objects)

Example Showing All Final Members Together:

final class MathUtils {

final double E = 2.718;

final double square(final double x) {

// x = 5; // ❌ Error: Cannot assign a value to final parameter

return x * x;

public class Test {

public static void main(String[] args) {

MathUtils mu = new MathUtils();

System.out.println("Square: " + mu.square(4));

System.out.println("E: " + mu.E);

ARRAY

1D Array in Java

Declaration and Initialization:

int[] arr1D = new int[5]; // Declare 1D array of size 5


arr1D[0] = 10;
arr1D[1] = 20;
arr1D[2] = 30;
arr1D[3] = 40;
arr1D[4] = 50;

// OR declare and initialize directly


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

2D Array in Java

Declaration and Initialization:

int[][] arr2D = new int[2][3]; // 2 rows, 3 columns


arr2D[0][0] = 1;
arr2D[0][1] = 2;
arr2D[0][2] = 3;
arr2D[1][0] = 4;
arr2D[1][1] = 5;
arr2D[1][2] = 6;

Complete Program

public class ArrayExample {


public static void main(String[] args) {

// 1D Array declaration and initialization


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

System.out.println("1D Array Elements:");


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

System.out.println("\n");

// 2D Array declaration and initialization


int[][] arr2D = {
{1, 2, 3},
{4, 5, 6}
};

System.out.println("2D Array Elements:");


for (int i = 0; i < arr2D.length; i++) {
for (int j = 0; j < arr2D[i].length; j++) {
System.out.print(arr2D[i][j] + " ");
}
System.out.println(); // New line for each row
}
}
}

OUTPUT:

1D Array Elements:
10 20 30 40 50

2D Array Elements:
1 2 3
4 5 6

Java Program: String Functions with Description

public class StringFunctionsDemo {


public static void main(String[] args) {
String str = " Hello World ";
String str2 = "Java";

// 1. length()
System.out.println("1. Length: " + str.length()); // Returns number
of characters

// 2. charAt(index)
System.out.println("2. Character at index 4: " + str.charAt(4)); //
Character at index 4

// 3. substring(beginIndex)
System.out.println("3. Substring from index 6: " +
str.substring(6)); // From index 6 to end

// 4. substring(beginIndex, endIndex)
System.out.println("4. Substring from index 2 to 7: " +
str.substring(2, 7)); // From 2 to 6

// 5. equals()
System.out.println("5. Equals 'Java': " + str.equals("Java")); //
Checks content equality

// 6. equalsIgnoreCase()
System.out.println("6. EqualsIgnoreCase 'hello world': " +
str.trim().equalsIgnoreCase("hello world"));

// 7. toLowerCase()
System.out.println("7. To Lowercase: " + str.toLowerCase());

// 8. toUpperCase()
System.out.println("8. To Uppercase: " + str.toUpperCase());

// 9. trim()
System.out.println("9. Trimmed String: '" + str.trim() + "'"); //
Removes leading/trailing spaces

// 10. replace()
System.out.println("10. Replace 'l' with 'x': " + str.replace('l',
'x'));

// 11. contains()
System.out.println("11. Contains 'World': " +
str.contains("World")); // Checks if substring exists

// 12. indexOf()
System.out.println("12. Index of 'o': " + str.indexOf('o')); //
Returns first occurrence

// 13. lastIndexOf()
System.out.println("13. Last index of 'l': " +
str.lastIndexOf('l')); // Last occurrence

// 14. startsWith()
System.out.println("14. Starts with ' He': " + str.startsWith("
He"));

// 15. endsWith()
System.out.println("15. Ends with 'ld ': " + str.endsWith("ld
"));

// 16. isEmpty()
String emptyStr = "";
System.out.println("16. Is empty: " + emptyStr.isEmpty());

// 17. concat()
System.out.println("17. Concatenation: " + str.trim().concat(" - "
+ str2));

// 18. split()
String[] words = str.trim().split(" ");
System.out.print("18. Split into words: ");
for (String word : words) {
System.out.print("[" + word + "] ");
}

// 19. toCharArray()
System.out.print("\n19. To character array: ");
char[] chars = str.trim().toCharArray();
for (char c : chars) {
System.out.print(c + " ");
}

// 20. compareTo()
System.out.println("\n20. CompareTo 'Java': " +
str.trim().compareTo("Java")); // Lexicographic comparison
}
}

OUTPUT:
1. Length: 15
2. Character at index 4: l
3. Substring from index 6: World
4. Substring from index 2 to 7: Hello
5. Equals 'Java': false
6. EqualsIgnoreCase 'hello world': true
7. To Lowercase: hello world
8. To Uppercase: HELLO WORLD
9. Trimmed String: 'Hello World'
10. Replace 'l' with 'x': Hexxo Worxd
11. Contains 'World': true
12. Index of 'o': 5
13. Last index of 'l': 9
14. Starts with ' He': true
15. Ends with 'ld ': true
16. Is empty: true
17. Concatenation: Hello World - Java
18. Split into words: [Hello] [World]
19. To character array: H e l l o W o r l d
20. CompareTo 'Java': -2
Function Summary Table
Function Purpose

length() Returns number of characters

charAt(i) Returns character at index i

substring() Returns substring

equals() Compares strings (case-sensitive)

equalsIgnoreCase() Compares strings ignoring case

toLowerCase() Converts string to lowercase

toUpperCase() Converts string to uppercase

trim() Removes leading/trailing spaces

replace() Replaces character or substring

contains() Checks if string contains substring

indexOf() Returns first index of a character

lastIndexOf() Returns last index of a character

startsWith() Checks if string starts with substring

endsWith() Checks if string ends with substring

isEmpty() Checks if string is empty

concat() Joins strings

split() Splits string by delimiter

toCharArray() Converts string to array of characters

compareTo() Lexicographical comparison

All Java Keywords (as of Java 17+)

Java has 50 reserved keywords that are predefined and cannot be used as identifiers (like variable
names).

1. Control Flow Keywords

Used for conditional logic and loops.


Keyword Description

if Executes block if condition is true

else Executes block if if is false

switch Multi-way branch statement

case Defines branch in switch

default Defines default block in switch

while Loop with condition at beginning

do Loop with condition at end

for Compact loop control

break Exits current loop or switch

continue Skips to next iteration

return Exits from method and returns value

yield Used in switch expressions (Java 14+)

2. Data Type Keywords

Used to declare variable types.

Keyword Description
int Integer type
float Floating point number
double
Double-precision
number
char Character type
byte 8-bit integer
short 16-bit integer
long 64-bit integer
boolean true or false
3. Access and Non-Access Modifiers

Keyword Description
public Visible everywhere
private Visible within the class only
protected Visible in package and subclass
static Belongs to class, not object
final Can't be changed or overridden
Keyword Description
abstract No body; must be overridden
synchronized Controls thread access
native Links Java to native code (C/C++)
transient Not serialized
volatile Prevents thread caching
strictfp Ensures floating point consistency
4. Class and Object Related

Used to define and manage classes.

Keyword Description
class Defines a class
interface Defines an interface
enum Defines enumerated type
extends Inherits superclass
implements Implements interface
this Refers to current object
super Refers to superclass
new Creates new object
instanceof Tests object type
record Defines immutable data class (Java 14+)

var
Type inference for local variables
(Java 10+)
5. Exception Handling Keywords
Keyword Description
try Start block to handle exceptions
catch Catch specific exception
finally Always executes after try/catch
throw Throws an exception
Declares possible
Throws exceptions

6. Package & Import Related

Keyword Description
package
Declares
package
Imports classes from
packages
7. Special Purpose Keywords
Keyword Description
void No return value
assert Debugging tool for checking conditions
null Default value for object references
true Boolean true
false Boolean false
8. Reserved but Unused Keywords

Keyword Description
const Reserved, not used

goto
Reserved,
not used

Summary Table (All Java Keywords)


abstract assert boolean break
byte
case catch char class
const*
continue default do double
else
enum extends final finally
float
for goto* if implements
import
instanceof int interface long
native
new null package private
protected
public return short static
strictfp
super switch synchronized this
throw
throws transient try void
volatile
while true false var
record
yield

⭐ const and goto are reserved but not used.

Data Types in Java

Java has two main categories of data types: Primitive Data Types and Reference Data Types. Below
is a detailed breakdown.
✅ 1. Primitive Data Types

These are the most basic types in Java. They store simple values and have fixed sizes.

Categories of Primitive Data Types:

Data Type Size Default Value Description

byte 1 byte 0 8-bit signed integer. Range: -128 to 127

short 2 bytes 0 16-bit signed integer. Range: -32,768 to 32,767

int 4 bytes 0 32-bit signed integer. Range: -2^31 to 2^31 - 1

long 8 bytes 0L 64-bit signed integer. Range: -2^63 to 2^63 - 1

float 4 bytes 0.0f Single-precision 32-bit IEEE 754 floating point

double 8 bytes 0.0d Double-precision 64-bit IEEE 754 floating point

char 2 bytes '\u0000' 16-bit Unicode character. Range: 0 to 65,535

boolean 1 bit false Represents a value of true or false

Primitive Data Types – Examples

public class PrimitiveDataTypes {

public static void main(String[] args) {

byte b = 100;

short s = 30000;

int i = 100000;

long l = 10000000000L;

float f = 10.5f;

double d = 100.12345;

char c = 'A';

boolean isJavaFun = true;

System.out.println("Byte value: " + b);


System.out.println("Short value: " + s);

System.out.println("Int value: " + i);

System.out.println("Long value: " + l);

System.out.println("Float value: " + f);

System.out.println("Double value: " + d);

System.out.println("Char value: " + c);

System.out.println("Boolean value: " + isJavaFun);

Output:

Byte value: 100


Short value: 30000
Int value: 100000
Long value: 10000000000
Float value: 10.5
Double value: 100.12345
Char value: A
Boolean value: true
2. Reference Data Types

Reference data types store references (or memory addresses) to objects or arrays. Unlike primitive
types, reference types do not store the actual data, but rather the memory location where the data
is stored.

Categories of Reference Data Types:

Data Type Description

A class is a user-defined data type. It can contain fields, methods, constructors, and
Class
other components.

An interface in Java is similar to a class but can only contain abstract methods, default
Interface
methods, static methods, and constant variables.

An array is a collection of similar types of data, accessed using an index. Arrays can
Array
hold primitive data types or objects.

String A special class that represents a sequence of characters.

Examples of Reference Data Types


Example 1: Class Reference

class Car {
String model;
int year;

Car(String model, int year) {


this.model = model;
this.year = year;
}
}

public class ReferenceDataTypes {


public static void main(String[] args) {
// Creating an object of Car class
Car myCar = new Car("Tesla", 2023);

System.out.println("Car Model: " + myCar.model);


System.out.println("Car Year: " + myCar.year);
}
}

Output:

Car Model: Tesla


Car Year: 2023

Key Differences Between Primitive and Reference Data Types


Feature Primitive Data Types Reference Data Types

Varies (depends on object or


Size Fixed, predefined
array)

Stores a reference (address) to


Memory Stores the actual value
the value

Default values are predefined (e.g., 0 for


Default Value Default value is null
numeric types)

String, Object, Array,


Examples int, float, boolean
Class

Pass by Passed by reference (memory


Passed by value (a copy of the value)
Value/Reference address)

Polymorphism in Java

Polymorphism is one of the core principles of Object-Oriented Programming (OOP). It


allows one entity to take multiple forms. In Java, polymorphism refers to the ability of a
method or an object to behave in multiple ways. It can be achieved in two main ways:

1. Compile-time Polymorphism (also known as Method Overloading)


2. Runtime Polymorphism (also known as Method Overriding)

1. Compile-Time Polymorphism (Method Overloading)

Method Overloading occurs when two or more methods in the same class have the same name but
differ in parameters (either in number, type, or both).

Key Characteristics:

 The method name is the same, but the parameter list is different.
 It occurs at compile-time, hence the name compile-time polymorphism.
 It does not require inheritance.

Example: Method Overloading

class Calculator {

// Method for adding two integers

public int add(int a, int b) {

return a + b;

// Overloaded method for adding three integers

public int add(int a, int b, int c) {

return a + b + c;

// Overloaded method for adding two floating-point numbers

public double add(double a, double b) {

return a + b;

public class MethodOverloadingExample {


public static void main(String[] args) {

Calculator calc = new Calculator();

System.out.println("Sum of 2 integers: " + calc.add(10, 20));

System.out.println("Sum of 3 integers: " + calc.add(10, 20, 30));

System.out.println("Sum of 2 doubles: " + calc.add(10.5, 20.3));

OUTPUT:

Sum of 2 integers: 30

Sum of 3 integers: 60

Sum of 2 doubles: 30.8

2. Runtime Polymorphism (Method Overriding)

Method Overriding occurs when a subclass provides a specific implementation for a method that is
already defined in its superclass. The version of the method that gets called is determined at runtime
based on the object type.

Key Characteristics:

 The method signature (name and parameters) in the subclass must be the same as in the
superclass.
 It occurs at runtime, hence the name runtime polymorphism.
 It requires inheritance (i.e., the subclass inherits from the superclass).

Example: Method Overriding

class Animal {

// Method in the superclass

public void sound() {

System.out.println("Animal makes a sound");

}
}

class Dog extends Animal {

// Method overriding the superclass method

@Override

public void sound() {

System.out.println("Dog barks");

class Cat extends Animal {

// Method overriding the superclass method

@Override

public void sound() {

System.out.println("Cat meows");

public class MethodOverridingExample {

public static void main(String[] args) {

// Creating objects of subclasses

Animal myDog = new Dog();

Animal myCat = new Cat();

// Runtime polymorphism: method invoked at runtime based on the object type


myDog.sound(); // Calls Dog's sound()

myCat.sound(); // Calls Cat's sound()

Differences Between Method Overloading and Method Overriding

Feature Method Overloading Method Overriding

Multiple methods with the same name Subclass provides a specific


Definition
but different parameters implementation of a superclass method

Must have the same method signature


Parameters Must differ in type, number, or both
(name + parameters)

Return Type Can be different Must be the same (or a subtype)

Occurs at Compile-time (Static Polymorphism) Runtime (Dynamic Polymorphism)

Requires inheritance (Superclass and


Inheritance Not required
Subclass)

Access Must be the same or more permissive


Can be different
Modifier than superclass

To perform similar operations with To modify or extend the behavior of an


Purpose
different inputs inherited method

Runtime Polymorphism
Polymorphism Compile-time Polymorphism

Encapsulation in Java

Encapsulation is one of the four fundamental principles of Object-Oriented Programming


(OOP), the others being inheritance, polymorphism, and abstraction. It is the process of
bundling the data (variables) and the methods (functions) that operate on the data into a
single unit, called a class, and restricting direct access to some of the object's components.
This is done to protect the integrity of the object and ensure that its state is only modified in a
controlled way.

In simple terms, encapsulation is about hiding the internal state of an object and allowing
controlled access to it through getter and setter methods. This helps protect the object’s state
from unintended or harmful modifications and makes the code more maintainable and secure.
Benefits of Encapsulation

1. Data Hiding: Keeps the object's internal state private, thus preventing external code
from directly accessing and modifying it. This helps protect against unwanted changes
and ensures data consistency.
2. Improved Maintainability: By controlling how the data is accessed or modified
(through getters and setters), it becomes easier to maintain and modify the code in the
future without affecting other parts of the program.
3. Control Access: With encapsulation, you can control who gets access to the data and
how the data can be modified (via validation inside setters, for example).
4. Increased Flexibility: You can change the internal implementation of the class
without affecting other parts of the code that use the class, as long as the public
interface (methods) remains the same.

Encapsulation Example in Java

In Java, we achieve encapsulation by:

1. Making the instance variables private (so they cannot be accessed directly from
outside the class).
2. Providing getter and setter methods to allow controlled access to the private
variables.

class Employee {
// Step 1: Private fields (Data Hiding)
private String name;
private int age;
private double salary;

// Step 2: Constructor to initialize the object


public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}

// Step 3: Getter method for name


public String getName() {
return name;
}

// Step 4: Setter method for name


public void setName(String name) {
this.name = name;
}

// Getter and Setter for age


public int getAge() {
return age;
}

public void setAge(int age) {


if(age > 18) { // Example of validation
this.age = age;
} else {
System.out.println("Age must be greater than 18.");
}
}

// Getter and Setter for salary


public double getSalary() {
return salary;
}

public void setSalary(double salary) {


if(salary > 0) {
this.salary = salary;
} else {
System.out.println("Salary must be positive.");
}
}

// Method to display employee details


public void displayDetails() {
System.out.println("Employee Name: " + name);
System.out.println("Employee Age: " + age);
System.out.println("Employee Salary: " + salary);
}
}

public class EncapsulationExample {


public static void main(String[] args) {
// Step 5: Create an object of Employee
Employee emp = new Employee("John", 25, 50000);

// Accessing private fields through getters


System.out.println("Employee Name: " + emp.getName());
System.out.println("Employee Age: " + emp.getAge());
System.out.println("Employee Salary: " + emp.getSalary());

// Modifying private fields through setters


emp.setName("Alice");
emp.setAge(30);
emp.setSalary(55000);

// Displaying updated details


emp.displayDetails();

// Attempting to set invalid values


emp.setAge(15); // Invalid, will print error message
emp.setSalary(-1000); // Invalid, will print error message
}
}

Output:

Employee Name: John


Employee Age: 25
Employee Salary: 50000.0
Employee Name: Alice
Employee Age: 30
Employee Salary: 55000.0
Age must be greater than 18.
Salary must be positive.

Key Points:

 Private Data Members: By marking the fields as private, direct access from
outside the class is restricted.
 Controlled Access: Getter and setter methods are used to get and set the values of
private fields in a controlled way.
 Data Validation: You can add logic inside setter methods to ensure that only valid
data is being assigned.

When to Use Encapsulation?

 When you want to protect an object’s internal state from unauthorized changes.
 When you want to validate the data before setting it.
 When you want to improve code maintainability and flexibility by changing the
internal implementation without affecting external code that uses the class.
 When you want to follow the principle of least privilege by exposing only necessary
data and methods.

Package in Java

A package in Java is a grouping of related classes and interfaces that are bundled together
to provide modularity, easy access control, and code organization. It helps to avoid name
conflicts, provides better maintainability, and can also restrict access to certain classes or
methods.

Java provides two types of packages:

1. Built-in Packages: These are pre-defined packages in Java, such as java.util,


java.io, and java.lang.
2. User-defined Packages: These are packages that are created by the programmer to
organize their own classes.

Creating and Using Packages in Java

1. Creating a User-Defined Package

To create a package, use the package keyword at the very beginning of a Java source file. For
example:

// Package declaration
package com.mycompany;

public class MyClass {

public void display() {

System.out.println("Hello from MyClass in the com.mycompany package");

In the example above:

 We defined a class MyClass inside the package com.mycompany.


 package com.mycompany;: This declares the package at the beginning of the file.

2. Compiling and Running a Package

To compile and run a Java class that belongs to a package, follow these steps:

1. Save the class in a folder that matches the package name (e.g., save the class file
in the folder com/mycompany).
2. Compile the class using the javac command:

javac com/mycompany/MyClass.java

3. Run the class with the java command, specifying the full package name
java com.mycompany.MyClass

Built-in Packages in Java

Java has a large set of built-in packages that provide ready-made functionality. For example:

 java.lang: Contains fundamental classes like String, Math, Thread, etc. This
package is imported by default.
 java.util: Contains utility classes such as ArrayList, HashMap, Date, etc.
 java.io: Contains classes for input and output operations, such as File,
BufferedReader, FileReader, etc.

To use a class from a built-in package, you must import it.

Example:

import java.util.Scanner; // Import Scanner class from java.util package


public class PackageExample {

public static void main(String[] args) {

// Using Scanner class to read user input

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");

String name = scanner.nextLine();

System.out.println("Hello, " + name);

In this example:

 import java.util.Scanner;: The Scanner class from the java.util package is


imported.
 The Scanner class is used to take input from the user.

JAR Files in Java

A JAR (Java Archive) file is a compressed file format that contains multiple Java classes,
metadata, and resources such as images and properties files. It is used to bundle Java
applications or libraries into a single file for easier distribution and deployment.

JAR files are commonly used for:

 Distributing Java applications (standalone or web-based).


 Grouping related classes and libraries into one file.
 Reducing the number of files when deploying an application.

Creating a JAR File

1. Compile your Java classes:

javac MyClass1.java MyClass2.java

2. Create a JAR file:


You can use the jar command to create a JAR file. For example:
jar cf myapplication.jar com/mycompany/MyClass1.class
com/mycompany/MyClass2.class

 c: Create a new JAR file.


 f: Specify the output file name (myapplication.jar).

 List of .class files to include in the JAR.

3. Creating an Executable JAR File:


To create an executable JAR file, you need to specify the main class in the JAR file's manifest.
This can be done when creating the JAR file using the -e flag:
jar cfe myapplication.jar com.mycompany.MainClass com/mycompany/*.class
e: Specifies the entry point (main class) of the application.

Manifest File in JAR

A JAR file can also contain a special file called META-INF/MANIFEST.MF that contains metadata
about the JAR file, such as the main class to be executed. When you create an executable JAR, the
manifest file automatically gets updated with the entry point class.

Here is an example of the MANIFEST.MF file:

Manifest-Version: 1.0

Main-Class: com.mycompany.MainClass

Advantages of Using JAR Files

1. Bundling: JAR files make it easier to distribute a set of related class files and
resources.
2. Compression: JAR files are compressed, reducing the size of the files compared to
the original classes and resources.
3. Portability: JAR files are platform-independent and can be run on any machine with
a JVM installed.
4. Versioning: JAR files allow versioning of the application or library (e.g., library-
v1.0.jar, library-v2.0.jar).
5. Security: JAR files can be signed, ensuring that the contents are not tampered with
during transmission.

Import and Static Import in Java

In Java, the import statement is used to bring other classes or entire packages into the current
class so that you can use them without needing to specify the full package path every time. It
simplifies the code and improves readability.

Java supports two types of imports:

1. Regular Import: Importing individual classes or entire packages.


2. Static Import: Importing static members (variables or methods) of a class.

1. Regular Import in Java


A regular import is used to import specific classes or entire packages, allowing you to use them
without specifying the full path.

Importing a Specific Class

If you want to use a specific class, you import it like this:

import java.util.Scanner; // Importing a specific class

public class MyClass {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in); // Now you can use Scanner directly

System.out.println("Enter a number:");

int num = scanner.nextInt();

System.out.println("You entered: " + num);

In the example above, we are importing the Scanner class from the java.util package.

Importing an Entire Package

To import all classes from a package, use the * wildcard:

import java.util.*; // Importing all classes from the java.util package

public class MyClass {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter your name:");

String name = scanner.nextLine();

System.out.println("Hello, " + name);


}

Here, the * wildcard imports all the classes from the java.util package (including Scanner,
ArrayList, etc.).

2. Static Import in Java

A static import allows you to import static members (fields and methods) of a class directly, so you
can use them without prefixing them with the class name.

Example of Static Import

import static java.lang.Math.PI; // Importing the static constant PI

import static java.lang.Math.sqrt; // Importing the static method sqrt()

public class StaticImportExample {

public static void main(String[] args) {

System.out.println("Value of PI: " + PI); // No need to use Math.PI

System.out.println("Square root of 16: " + sqrt(16)); // No need to use Math.sqrt()

import static java.lang.Math.PI; // Importing the static constant PI

import static java.lang.Math.sqrt; // Importing the static method sqrt()

public class StaticImportExample {

public static void main(String[] args) {

System.out.println("Value of PI: " + PI); // No need to use Math.PI

System.out.println("Square root of 16: " + sqrt(16)); // No need to use Math.sqrt()

}
}

In the example above, we used the static import to directly access the PI constant and the sqrt()
method from the Math class without using Math.PI or Math.sqrt().

Naming Convention for Packages

In Java, there are some standard naming conventions for packages:

1. Lowercase Letters: Package names should be written in lowercase to avoid conflicts


with class names. This is a common convention to make it clear that they represent
packages and not classes.
2. Domain Name as Prefix: It’s common practice to start the package name with the
reversed domain name of the organization. For example, if the organization’s
domain is example.com, the package name might be com.example.
3. Use Dot Notation: Package names use dot notation to separate different levels of the
hierarchy. For example, com.mycompany.projectname.
4. Avoid Using Reserved Keywords: Package names should not use reserved Java
keywords like int, public, or static.

Example Package Naming:

package com.mycompany.projectname;

Difference between Regular Import and Static Import

Feature Regular Import Static Import


Used to import classes or entire Used to import static members (fields or
Purpose
packages. methods).
Usage import java.util.Scanner; import static java.lang.Math.PI;
You need to use the class name
You can directly access static members
Class when accessing its members
without the class name (e.g., sqrt(16) or
Reference (e.g., Math.sqrt() or
PI).
Scanner.nextLine()).
import import static
Syntax package_name.class_name; package_name.class_name.member_name;
Common Importing whole classes or Importing static members (constants,
Use Case packages for regular use. methods) for easier access.
import
Example import static java.lang.Math.sqrt;
java.util.ArrayList;
Can make code longer if
Impact on Can improve readability when multiple static
multiple classes from the same
Readability members are used.
package are used.
Use of Supports wildcard to import all
No wildcard support, you must import
Wildcard classes from a package (e.g.,
specific static members.
(*) import java.util.*;).
When to Use Which Import?

 Regular Import: Use regular import when you need to use a class or package in
your program. It is the most common form of import.
 Static Import: Use static import when you want to directly access static fields or
methods of a class. Static import is particularly useful when you are using a constant
or method from a class frequently, such as Math.PI or Math.sqrt()

Best Practices for Imports

1. Avoid Wildcard Imports (*): While it might seem convenient to import all classes
from a package, it can lead to confusion and potential conflicts if multiple classes
with the same name are imported. Import specific classes when possible.
2. Use Static Import Sparingly: Static import can make the code more readable when
used for constants and utility methods (like Math.PI or Collections.sort()).
However, overuse of static import can lead to confusion, as it removes the context of
where the method or variable comes from.
3. Package Naming: Stick to lowercase for package names, use your organization's
domain name in reverse (e.g., com.example.myapp), and make package names
meaningful and descriptive of their contents.

Example Program Using Both Imports

import java.util.*; // Regular import to use various classes from java.util


package

import static java.lang.Math.*; // Static import to use static members of Math


class

public class ImportExample {

public static void main(String[] args) {

// Regular import: using ArrayList from java.util package

ArrayList<Integer> numbers = new ArrayList<>();

numbers.add(5);

numbers.add(10);

numbers.add(15);

System.out.println("Numbers: " + numbers);


// Static import: directly using sqrt() and PI from Math class

double result = sqrt(16);

System.out.println("Square root of 16: " + result);

System.out.println("Value of PI: " + PI);

OUTPUT:

Numbers: [5, 10, 15]

Square root of 16: 4.0

Value of PI: 3.141592653589793

 Regular Import is used to import classes and packages.

 Static Import is used to import static members (fields and methods) of a class.

 Naming Conventions for packages in Java suggest using lowercase letters, and starting
with the reverse domain name (e.g., com.mycompany).

 The choice between regular import and static import depends on whether you are
importing classes or static members.

You might also like