UNIT 1 (OOPs)
UNIT 1 (OOPs)
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:
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.
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
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.
Libraries (e.g., DLLs or shared objects) that contain platform-specific native code
accessed via JNI.
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
4. Multithreading
Supports multiple threads of execution, making it ideal for interactive and high-
performance apps.
Huge set of APIs for networking, I/O, data structures, GUIs, and more.
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.
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.
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.
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.
import java.util.Scanner;
import java.util.List;
// Fields (variables)
int number;
// Constructor
public HelloWorld() {
number = 0;
// Methods
System.out.println("Hello, world!");
obj.greet();
Rules:
Step-by-step Flow:
1. Write Code
File: HelloWorld.java
2. Compile
javac HelloWorld.java
Output: HelloWorld.class
3. Run
java HelloWorld
Diagram:
[javac]
HelloWorld.class (Bytecode)
[java]
Java Fundamentals
Concept Description
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.
A concrete class is a fully implemented class in Java — it is not abstract, which means:
// Fields (variables)
String brand;
int speed;
// Constructor
this.brand = brand;
this.speed = speed;
// Method
}
}
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
void eat() {
}
}
void makeSound() {
System.out.println("Dog barks");
// Main class
OUTPUT:
Dog barks
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.
Syntax:
class Parent {
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
class Animal {
void eat() {
}
}
void bark() {
System.out.println("Dog barks.");
Output:
Dog barks.
2. ✅ Multilevel Inheritance
class Animal {
void eat() {
System.out.println("Eating...");
}
}
void bark() {
System.out.println("Barking...");
void weep() {
System.out.println("Weeping...");
Output:
Eating...
Barking...
Weeping...
3. ✅ Hierarchical Inheritance
class Animal {
void eat() {
System.out.println("Animal eats.");
void bark() {
System.out.println("Dog barks.");
void meow() {
System.out.println("Cat meows.");
d.eat();
d.bark();
c.eat();
c.meow();
Output:
Animal eats.
Dog barks.
Animal eats.
Cat meows.
class A {
class B {
Why not?
interface A {
void printA();
interface B {
void printB();
class C implements A, B {
obj.printB();
Output:
From interface A
From interface B
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).
interface Vehicle {
// Abstract method
void start();
// Implementing class
// Main class
}
OUTPUT:
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.
Can have any access modifier All variables are public static
Variables
(private, protected, etc.) final (constants) by default
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?
Key Characteristics:
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)
class Car {
Car() {
}
}
OUTPUT:
2 Parameterized Constructor
class Car {
String brand;
int year;
Car(String b, int y) {
brand = b;
year = y;
void display() {
c1.display();
OUTPUT:
Toyota – 2022
class Car {
String brand;
// Parameterized constructor
Car(String b) {
brand = b;
// Copy constructor
Car(Car c) {
brand = c.brand;
void display() {
OUTPUT:
Brand: Honda
Notes:
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.
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 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
class Person {
this.name = name;
this.name = name;
this.age = age;
public Person() {
this.name = "Unknown";
this.age = 0;
Output:
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
Parameterized Constructor Takes arguments to set custom values during object creation.
Copy Constructor (custom) Creates a new object by copying an existing object manually.
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;
void displayInfo() {
System.out.println("------------------------------");
s2.displayInfo();
Output:
Name : Alice
Email : [email protected]
------------------------------
Name : Bob
Branch : Electronics
Email : [email protected]
------------------------------
In Java, methods are blocks of code designed to perform a specific task. They improve code
reusability, readability, and structure.
2. Static Method Belongs to the class; called using the class name
// 1. Instance Method
void greet() {
// 2. Static Method
// 3. Parameterized Method
int sum = a + b;
// 5. Void Method
void sayGoodbye() {
System.out.println("Goodbye!");
// Calling methods
Output:
Hello from an instance method.
Hello from a static method.
Sum is: 30
Square: 25
Goodbye!
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:
// Concrete method
void sleep() {
System.out.println("Sleeping...");
}
}
package mypackage;
System.out.println("Public Method");
System.out.println("Private Method");
System.out.println("Protected Method");
void defaultMethod() {
System.out.println("Default Method");
System.out.println(publicVar); // ✅
System.out.println(privateVar); // ✅
System.out.println(protectedVar); // ✅
System.out.println(defaultVar); // ✅
publicMethod(); // ✅
privateMethod(); // ✅
protectedMethod(); // ✅
defaultMethod(); // ✅
package mypackage;
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(); // ✅
package otherpackage;
import mypackage.AccessExample;
System.out.println(obj.publicVar); // ✅
// System.out.println(obj.privateVar); // ❌
// 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 ✅ ❌ ❌ ❌
In Java, static members (variables and methods) belong to the class rather than to instances
(objects) of the class.
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
// Static variable
int id;
String name;
// Constructor
this.id = id;
this.name = name;
// Static method
college = newCollege;
// Instance method
void display() {
s2.display();
Student.changeCollege("XYZ Institute");
s1.display();
s2.display();
Output:
Key Points:
class Example {
static int x;
// Static block runs once when class is loaded
static {
x = 10;
Output:
x = 10
The final keyword in Java is used to declare constants or prevent modification of variables,
methods, or classes.
class Circle {
class Vehicle {
System.out.println("Vehicle is running");
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)
return x * x;
ARRAY
1D Array in Java
2D Array in Java
Complete Program
System.out.println("\n");
OUTPUT:
1D Array Elements:
10 20 30 40 50
2D Array Elements:
1 2 3
4 5 6
// 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
Java has 50 reserved keywords that are predefined and cannot be used as identifiers (like variable
names).
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
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
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
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.
byte b = 100;
short s = 30000;
int i = 100000;
long l = 10000000000L;
float f = 10.5f;
double d = 100.12345;
char c = 'A';
Output:
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.
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.
class Car {
String model;
int year;
Output:
Polymorphism in Java
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.
class Calculator {
return a + b;
return a + b + c;
return a + b;
OUTPUT:
Sum of 2 integers: 30
Sum of 3 integers: 60
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).
class Animal {
}
}
@Override
System.out.println("Dog barks");
@Override
System.out.println("Cat meows");
Runtime Polymorphism
Polymorphism Compile-time Polymorphism
Encapsulation in Java
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.
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;
Output:
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 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.
To create a package, use the package keyword at the very beginning of a Java source file. For
example:
// Package declaration
package com.mycompany;
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
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.
Example:
In this example:
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.
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.
Manifest-Version: 1.0
Main-Class: com.mycompany.MainClass
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.
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.
Scanner scanner = new Scanner(System.in); // Now you can use Scanner directly
System.out.println("Enter a number:");
In the example above, we are importing the Scanner class from the java.util package.
Here, the * wildcard imports all the classes from the java.util package (including Scanner,
ArrayList, etc.).
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.
}
}
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().
package com.mycompany.projectname;
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()
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.
numbers.add(5);
numbers.add(10);
numbers.add(15);
OUTPUT:
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.