Unit 1
Unit 1
March 9, 2026
Contents
1 Introduction to Object-Oriented Programming (OOP) 6
1.1 What is OOP? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 Fundamental Features of OOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Object-Based vs. Fully Object-Oriented Languages . . . . . . . . . . . . . . . . . . . 6
2 History of Java 6
2.1 Evolution of Java Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
5 Editions of Java 8
9 Variables in Java 11
9.1 Example Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
9.2 Types of Variables in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
9.3 Local Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
9.4 Instance Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
9.5 Static Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
9.6 Rules for Naming Variables in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
9.7 Examples of Valid and Invalid Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 13
9.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1
10 Operators in Java 13
10.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
10.2 Relational (Comparison) Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
10.3 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
10.4 Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
10.5 Unary Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
10.6 Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
10.7 Ternary Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
10.7.1 Operator Precedence Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
12 Comments in Java 18
12.1 Single-line Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
12.2 Multi-line Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
12.3 Documentation Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
12.4 Advantages of Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
14 Arrays in Java 22
14.1 Declaration of an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
14.2 Array Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
14.3 Array Declaration and Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
14.4 Accessing Array Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
14.5 Example Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
14.6 Types of Arrays in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
14.6.1 One-Dimensional Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
14.6.2 Two-Dimensional Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
14.7 Advantages of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
14.8 Limitations of Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2
15 Strings in Java 24
15.1 Creating Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
15.1.1 Using String Literal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
15.1.2 Using the new Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
15.2 Example Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
15.3 Common String Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
15.4 Example of String Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
15.5 String Immutability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
15.6 Advantages of Using Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
16 Methods in Java 25
16.1 Syntax of a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
16.2 Example of a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
16.3 Method with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
16.4 Method with Return Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
16.5 Types of Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
16.5.1 Predefined Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
16.5.2 User-defined Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
16.6 Advantages of Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
16.7 Method Overloading in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
16.7.1 Example of Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . 27
16.7.2 Method Overloading with Different Data Types . . . . . . . . . . . . . . . . . 28
16.8 Static vs Non-Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
16.8.1 Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
16.8.2 Non-Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
16.8.3 Difference Between Static and Non-Static Methods . . . . . . . . . . . . . . . 29
16.9 Call by Value in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
16.9.1 Example of Call by Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
16.10Recursion in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
16.10.1Structure of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
16.10.2Example: Factorial Using Recursion . . . . . . . . . . . . . . . . . . . . . . . . 30
16.10.3Example: Fibonacci Series Using Recursion . . . . . . . . . . . . . . . . . . . 30
16.10.4Advantages of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
16.10.5Disadvantages of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3
18.4.4 Hierarchical Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
18.4.5 Multiple Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
18.4.6 Hybrid Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
18.5 Summary of Types of Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
18.6 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
18.7 Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
18.8 Summary of Four Pillars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
22 Final Keyword 43
22.1 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
23 Packages in Java 44
23.1 Types of Packages in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
23.1.1 Built-in Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
23.1.2 User-defined Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
23.2 Using a Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
23.3 Advantages of Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
23.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
23.5 Classpath Setting for Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
23.5.1 Setting Classpath Temporarily . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
23.5.2 Setting Classpath Permanently . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
23.5.3 Example: Using Package with Classpath . . . . . . . . . . . . . . . . . . . . . 46
23.5.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
23.6 JAR Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
23.7 Import and Static Import in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
23.7.1 Import Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
23.7.2 Static Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
23.8 Naming Convention for Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
23.8.1 Rules for Package Naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
23.8.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
23.8.3 Example of Package Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . 48
23.8.4 Advantages of Proper Package Naming . . . . . . . . . . . . . . . . . . . . . 48
4
24 Access Modifiers in Java 49
24.1 Public Access Modifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
24.2 Private Access Modifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
24.3 Protected Access Modifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
24.4 Default Access Modifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
24.5 Access Modifier Visibility Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
24.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
5
1 Introduction to Object-Oriented Programming (OOP)
1.1 What is OOP?
Object-Oriented Programming (OOP) is a methodology/paradigm to design a program using
classes and objects. It focuses on data rather than procedures. According to Balaguruswami,
OOP is an approach that provides a way of modularizing programs by creating partitioned mem-
ory areas for both data and functions that can be used as templates for creating copies of such
modules on demand.
3. Polymorphism: Ability to take many forms (e.g., method overloading and overriding).
5. Class and Object based: Programs are organized around objects that contain both data
and behavior.
• Fully Object-Oriented Language: Supports all four main OOP features; may have primi-
tive data types. (e.g., Java, C++, C#)
• Pure Object-Oriented Language: Everything is an object; only classes and objects exist.
Java is not a pure OOP language because it has primitive data types (int, float, etc.) and
wrapper classes.
2 History of Java
• 1991: James Gosling, Patrick Naughton, and Mike Sheridan at Sun Microsystems started
the Green Project aimed at developing software for consumer electronic devices (TV set-
top boxes, VCRs, etc.).
• The language was initially called Oak (named after an oak tree outside Gosling’s office).
Later renamed Java because Oak was already trademarked; the name Java was inspired
by the coffee consumed by the team.
• 1995: First public release with the slogan ”Write Once, Run Anywhere” (WORA) – com-
piled Java code (bytecode) can run on any platform with a Java Virtual Machine (JVM).
• 1996: JDK 1.0 released. Key features: platform independence, OOP, garbage collection,
security.
• 2010: Oracle Corporation acquired Sun Microsystems and continues to maintain Java with
a 6-month release cycle and Long-Term Support (LTS) versions every few years.
6
2.1 Evolution of Java Versions
7
5 Editions of Java
• Java Standard Edition (Java SE): Core Java platform; includes fundamental APIs like [Link],
[Link], [Link], [Link], AWT/Swing, etc. Provides the foundation for all other edi-
tions.
• Java Enterprise Edition (Java EE): Extends Java SE with specifications for enterprise fea-
tures: Servlets, JSP, EJB, JPA, JSF, etc. Used for large-scale distributed applications.
• Java Micro Edition (Java ME): For resource-constrained devices like mobile phones, PDAs,
embedded systems. Provides a small-footprint JVM and APIs.
• JavaFX: A platform for rich internet applications (RIA) and desktop GUI; intended to re-
place Swing as the standard GUI library. Used in NASA projects (GEONS), medical imaging
(FORUM), and financial applications.
1. Simple: Java syntax is derived from C++ but removed many complex and ambiguous fea-
tures like pointers, operator overloading, multiple inheritance (through classes), and ex-
plicit memory management.
3. Distributed: Java has extensive networking capabilities; it supports protocols like HTTP,
FTP, and provides classes for remote method invocation (RMI).
4. Architectural Neutral: Java compiler generates bytecode that is independent of any spe-
cific hardware architecture.
5. Portable: Bytecode can be executed on any platform with a JVM. There are no implementation-
dependent aspects (e.g., sizes of primitive types are fixed).
6. Robust: Java emphasizes early checking for possible errors, runtime checking, and excep-
tion handling. It has automatic garbage collection and strong memory management.
7. Secure: Java provides a secure environment through bytecode verification, class loading,
and a security manager. No pointers prevent illegal memory access.
8. Dynamic: Java supports dynamic loading of classes; it can adapt to an evolving environ-
ment by loading classes on demand.
9. Interpreted: Java bytecode is interpreted by the JVM, but performance is improved by JIT
compilation.
10. Multithreaded: Java provides built-in support for multithreaded programming with syn-
chronized methods and thread primitives.
11. High Performance: Although interpreted, Java’s performance is enhanced by JIT compi-
lation, which converts bytecode to native code at runtime.
12. Platform Independent: The combination of bytecode and JVM makes Java platform-independent.
8
7 Java Environment: JVM, JRE, JDK
7.1 Java Virtual Machine (JVM)
The JVM is an abstract machine that provides a runtime environment for executing Java byte-
code. It is responsible for:
1. Class Loader: Loads class files into memory. It performs three functions: loading, linking,
and initialization.
2. Native Method Loader: Loads native libraries (written in other languages like C/C++)
when native methods are invoked.
3. Heap: Runtime data area where all objects and arrays are stored. Shared among all
threads.
• JVM
• JRE
9
7.4 Relationship Diagram
+---------------------+
| JDK |
| +---------------+ |
| | JRE | |
| | +---------+ | |
| | | JVM | | |
| | +---------+ | |
| | Libraries | |
| +---------------+ |
| Tools (javac, etc.)|
+---------------------+
Example:
1 package mypackage ;
2 import [Link]. Scanner ;
3 public class MyClass {
4 // class body
5 }
6
javac [Link]
java HelloWorld
The JVM loads the class and runs the main method.
10
8.3 First Java Program
1 class HelloWorld {
2 public static void main( String [] args) {
3 System .out. println ("Hello , World !");
4 }
5 }
6
Listing 1: [Link]
9 Variables in Java
A variable in Java is a named memory location used to store data that can change during pro-
gram execution. Variables allow programs to store, retrieve, and manipulate values.
Syntax
1 datatype variableName = value;
2
Example:
1 int age = 25;
2
Here:
• int : Data type
• age : Variable name
• 25 : Value stored in the variable
11
9.3 Local Variable
A local variable is declared inside a method, constructor, or block. Characteristics
Example
1 public class Test {
2 public void show () {
3 int x = 10; // local variable
4 System .out. println (x);
5 }
6 public static void main( String [] args) {
7 Test t = new Test ();
8 [Link] ();
9 }
10 }
11
• Belongs to an object
Example
1 public class Student {
2 int id;
3 String name;
4 public static void main( String [] args) {
5 Student s1 = new Student ();
6 [Link] = 101;
7 [Link] = "Ali ";
8 System .out. println ([Link] + " " + [Link]);
9 }
10 }
11
12
Example
1 public class College {
2 static String collegeName = "ABC University ";
3 public static void main( String [] args) {
4 System .out. println ( College . collegeName );
5 }
6 }
7
• Java is case-sensitive.
Invalid
1 int 1age; // starts with number
2 int class; // reserved keyword
3 int student -name; // special character
4
9.8 Summary
Variable Type Declared In Scope
Local Variable Inside method Method only
Instance Variable Inside class Object level
Static Variable Using static keyword Class level
10 Operators in Java
Operators are special symbols used to perform operations on variables and values. For exam-
ple, arithmetic calculations, comparisons, and logical operations. Example:
1 int a = 10;
2 int b = 5;
3 int c = a + b; // + is an operator
4
13
• Arithmetic Operators
• Logical Operators
• Assignment Operators
• Unary Operators
• Bitwise Operators
• Ternary Operator
Example:
1 int a = 10;
2 int b = 3;
3 System .out. println (a + b);
4 System .out. println (a - b);
5 System .out. println (a * b);
6 System .out. println (a / b);
7 System .out. println (a % b);
8
Example:
1 int a = 10;
2 int b = 5;
3 System .out. println (a > b);
4 System .out. println (a == b);
5 System .out. println (a != b);
6
14
10.3 Logical Operators
Logical operators are used to combine multiple conditions.
Operator Meaning Example
&& Logical AND a > 5 && b < 10
|| Logical OR a > 5 || b < 10
! Logical NOT !(a > b)
Example:
1 int a = 10;
2 int b = 5;
3 System .out. println (a > 5 && b < 10);
4 System .out. println (a > 5 || b > 10);
5 System .out. println (!(a > b));
6
15
10.6 Bitwise Operators
Bitwise operators operate on binary values.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
« Left shift
» Right shift
Example:
1 int a = 10;
2 int b = 20;
3 int max = (a > b) ? a : b;
4 System .out. println (" Maximum value: " + max);
5
16
11.1 Primitive Data Types
Primitive data types are the basic built-in data types provided by Java. They store simple values
directly in memory. Java has 8 primitive data types.
• String
• Arrays
• Classes
• Interfaces
• Objects
Example:
1 String name = "Java Programming ";
2 int [] numbers = {10, 20, 30};
3
17
11.4 Difference Between Primitive and Non-Primitive Types
Feature Primitive Type Non-Primitive Type
Storage Stores actual value Stores reference to object
Memory Size Fixed size Size may vary
Examples int, float, char String, Array, Class
12 Comments in Java
Comments are explanatory notes added to the source code to improve readability and under-
standing of the program. Comments are ignored by the Java compiler and do not affect program
execution. Comments are useful for documenting code, explaining logic, and making programs
easier to maintain. Java supports three types of comments:
1. Single-line comments
2. Multi-line comments
3. Documentation comments
18
4 */
5 public class Test {
6 public static void main( String [] args) {
7 System .out. println (" Java Comments ");
8 }
9 }
10
3. Jump Statements
19
13.1.1 if Statement
The if-else statement executes one block of code if the condition is true and another block if
the condition is false.
1 int number = 5;
2 if( number % 2 == 0) {
3 System .out. println (" Even number ");
4 } else {
5 System .out. println (" Odd number ");
6 }
7
The switch statement is used to select one of many code blocks to execute.
1 int day = 2;
2 switch (day) {
3 case 1:
4 System .out. println (" Monday ");
5 break;
6 case 2:
7 System .out. println (" Tuesday ");
8 break;
9 default :
10 System .out. println (" Invalid day ");
11 }
12
The for loop is commonly used when the number of iterations is known.
1 for(int i = 1; i <= 5; i++) {
2 System .out. println (i);
3 }
4
20
13.2.2 while Loop
The while loop executes a block of code repeatedly while the condition remains true.
1 int i = 1;
2 while(i <= 5) {
3 System .out. println (i);
4 i++;
5 }
6
The do-while loop executes the block of code at least once before checking the condition.
1 int i = 1;
2 do {
3 System .out. println (i);
4 i++;
5 } while(i <= 5);
6
The continue statement skips the current iteration and moves to the next iteration of the loop.
1 for(int i = 1; i <= 5; i++) {
2 if(i == 3) {
3 continue ;
4 }
5 System .out. println (i);
6 }
7
21
13.3.3 return Statement
The return statement is used to exit from a method and optionally return a value.
1 public static int add(int a, int b) {
2 return a + b;
3 }
4
14 Arrays in Java
An array is a data structure used to store multiple values of the same data type in a single
variable. Instead of declaring separate variables for each value, an array allows storing many
values using one variable name. Each element in an array is identified by an index. In Java,
array indexing starts from 0.
Example:
1 int [] numbers ;
2
22
14.5 Example Program
1. One-Dimensional Array
2. Multi-Dimensional Array
Accessing elements:
1 System .out. println ( matrix [0][1]) ; // prints 2
2
23
15 Strings in Java
A String in Java is a sequence of characters used to store text. In Java, strings are objects of
the String class and are widely used for handling textual data. Strings are immutable, which
means once a string object is created, its value cannot be changed.
Method Description
length() Returns the length of the string
toUpperCase() Converts string to uppercase
toLowerCase() Converts string to lowercase
charAt() Returns character at a specific index
substring() Returns a part of the string
equals() Compares two strings
concat() Joins two strings
24
15.4 Example of String Methods
Output:
1 Java
2
16 Methods in Java
A method in Java is a block of code that performs a specific task. Methods are used to organize
code into reusable units, making programs easier to read, maintain, and debug. A method is
executed when it is called or invoked.
Where:
25
• methodName – The name of the method.
2. User-defined Methods
26
16.5.1 Predefined Methods
These methods are created by the programmer to perform specific tasks. Example:
1 void greet () {
2 System .out. println (" Welcome to Java Programming ");
3 }
4
• Number of parameters
• Type of parameters
• Order of parameters
27
16.7.2 Method Overloading with Different Data Types
1 class Display {
2 void show(int a) {
3 System .out. println (" Integer : " + a);
4 }
5 void show( String name) {
6 System .out. println (" String : " + name);
7 }
8 public static void main( String [] args) {
9 Display obj = new Display ();
10 [Link] (10);
11 [Link] (" Java ");
12 }
13 }
14
A static method belongs to the class rather than an object. It is declared using the static key-
word.
Example:
1 public class StaticExample {
2 static void display () {
3 System .out. println (" Static Method ");
4 }
5 public static void main( String [] args) {
6 StaticExample . display ();
7 }
8 }
9
Example:
28
1 public class InstanceExample {
2 void show () {
3 System .out. println ("Non - static Method ");
4 }
5 public static void main( String [] args) {
6 InstanceExample obj = new InstanceExample ();
7 [Link] ();
8 }
9 }
10
Output:
1 Inside method : 30
2 Outside method : 20
3
The original value remains unchanged because Java uses call by value.
29
16.10.1 Structure of Recursion
n! = n × (n − 1)!
F (n) = F (n − 1) + F (n − 2)
Example program:
1 public class FibonacciRecursion {
2 int fibonacci (int n) {
3 if(n <= 1) {
4 return n;
5 }
6 return fibonacci (n -1) + fibonacci (n -2);
7 }
8 public static void main( String [] args) {
9 FibonacciRecursion obj = new FibonacciRecursion ();
10 for(int i = 0; i < 6; i++) {
11 System .[Link](obj. fibonacci (i) + " ");
12 }
13 }
14 }
15
30
16.10.4 Advantages of Recursion
Example of Class
1 class Student {
2 int id;
3 String name;
4 void display () {
5 System .out. println (id + " " + name);
6 }
7 }
8
Explanation
• Student � Class name
31
Where
• new � Keyword used to allocate memory
• objectName � Reference variable
1 class Student {
2 int id;
3 String name;
4 void display () {
5 System .out. println (id + " " + name);
6 }
7 }
8 public class Main {
9 public static void main( String [] args) {
10 Student s1 = new Student ();
11 [Link] = 101;
12 [Link] = " Naushad ";
13 s1. display ();
14 }
15 }
16
Output
1 101 Naushad
2
1 class Student {
2 int id;
3 String name;
4 void display () {
5 System .out. println (id + " " + name);
6 }
7 }
8 public class Main {
9 public static void main( String [] args) {
10 Student s1 = new Student ();
11 Student s2 = new Student ();
12 [Link] = 101;
13 [Link] = "Ali";
14 [Link] = 102;
15 [Link] = " Rahul ";
16 s1. display ();
17 s2. display ();
18 }
19 }
20
Output
1 101 Ali
2 102 Rahul
3
32
17.5 Characteristics of a Class
A class contains:
• Methods (Functions)
• Constructors
• Blocks
• Nested Classes
Example:
• Class � Car
• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
33
18.1 Diagram of Four Pillars of OOP
Encapsulation
Object-Oriented
Inheritance Abstraction
Programming
Polymorphism
18.2 Encapsulation
Encapsulation is the process of wrapping data (variables) and methods (functions) into a single
unit called a class. It also provides data hiding using access modifiers such as private, pro-
tected, and public. Example
1 class Student {
2 private int id;
3 private String name;
4 public void setId(int id) {
5 [Link] = id;
6 }
7 public int getId () {
8 return id;
9 }
10 }
11
18.3 Inheritance
Inheritance is the mechanism by which one class acquires the properties and methods of an-
other class.
Example
1 class Animal {
2 void eat () {
3 System .out. println (" Animal eats");
4 }
5 }
6 class Dog extends Animal {
7 void bark () {
34
8 System .out. println ("Dog barks ");
9 }
10 }
11
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
Multilevel Hierarchical
A A A
B C
Single B B
In Single Inheritance, a subclass inherits the properties and methods of one superclass. Exam-
ple
1 class Animal {
2 void eat () {
3 System .out. println (" Animal eats");
4 }
5 }
6 class Dog extends Animal {
7 void bark () {
8 System .out. println ("Dog barks ");
9 }
10 }
11
35
18.4.3 Multilevel Inheritance
Java does not support multiple inheritance with classes to avoid ambiguity problems. However,
it can be achieved using interfaces. Example
1 interface A {
2 void show ();
3 }
4 interface B {
5 void display ();
6 }
7 class Test implements A, B {
8 public void show () {
9 System .out. println (" Interface A");
10 }
36
11 public void display () {
12 System .out. println (" Interface B");
13 }
14 }
15
Hybrid inheritance is a combination of two or more types of inheritance. In Java, hybrid inheri-
tance can also be implemented using interfaces.
18.6 Polymorphism
Polymorphism means many forms. It allows a single method name to perform different oper-
ations. Types of polymorphism:
Example
1 class MathOperations {
2 int add(int a, int b) {
3 return a + b;
4 }
5 int add(int a, int b, int c) {
6 return a + b + c;
7 }
8 }
9
18.7 Abstraction
Abstraction means hiding internal implementation details and showing only essential features.
It can be achieved using:
• Abstract Classes
• Interfaces
Example
37
1 abstract class Shape {
2 abstract void draw ();
3 }
4 class Circle extends Shape {
5 void draw () {
6 System .out. println (" Drawing Circle ");
7 }
8 }
9
• Type of parameters
• Order of parameters
Example
1 class MathOperations {
2 int add(int a, int b) {
3 return a + b;
4 }
5 int add(int a, int b, int c) {
6 return a + b + c;
7 }
8 double add( double a, double b) {
9 return a + b;
10 }
11 }
12 public class Main {
13 public static void main( String [] args) {
14 MathOperations m = new MathOperations ();
15 System .out. println ([Link] (5, 3));
16 System .out. println ([Link] (5, 3, 2));
17 System .out. println ([Link] (2.5 , 3.5));
18 }
19 }
20
Output
38
1 8
2 10
3 6.0
4
Example
1 class Animal {
2 void sound () {
3 System .out. println (" Animal makes sound ");
4 }
5 }
6 class Dog extends Animal {
7 void sound () {
8 System .out. println ("Dog barks ");
9 }
10 }
11 public class Main {
12 public static void main( String [] args) {
13 Dog d = new Dog ();
14 [Link] ();
15 }
16 }
17
Output
1 Dog barks
2
39
20 Interfaces and Abstract Classes in Java
Java provides Abstract Classes and Interfaces to achieve abstraction in Object-Oriented Pro-
gramming. Both are used to hide implementation details and show only essential features of
an object.
Output
1 Drawing Circle
2 This is a shape
3
20.2 Interface
An interface in Java is a blueprint of a class that contains only abstract methods (before Java
8) and constants. Interfaces are used to achieve 100% abstraction. A class implements an
interface using the keyword implements. Example
1 interface Animal {
2 void sound ();
3 }
4 class Dog implements Animal {
5 public void sound () {
6 System .out. println ("Dog barks ");
7 }
8 }
9 public class Main {
10 public static void main( String [] args) {
11 Dog d = new Dog ();
12 [Link] ();
13 }
40
14 }
15
Output
1 Dog barks
2
41
7 }
8 void display () {
9 System .out. println (id + " " + name);
10 }
11 }
12 public class Main {
13 public static void main( String [] args) {
14 Student s = new Student (101 , " Naushad ");
15 s. display ();
16 }
17 }
18
42
6 display (this);
7 }
8 }
9
22 Final Keyword
The final keyword is used to restrict the user. It can be applied to:
• Final variable: Value cannot be changed (constant). If a final variable is blank (not initial-
ized at declaration), it must be initialized in the constructor (for instance) or static block
(for static).
22.1 Examples
43
23 Packages in Java
A package in Java is a namespace that groups related classes and interfaces together. It helps
organize large programs and avoids naming conflicts. Packages are used to:
• Organize classes and interfaces
• Avoid class name conflicts
• Control access using access modifiers
• Improve code reusability and maintainability
Built-in packages are predefined packages provided by Java. Some commonly used built-in
packages are:
• [Link] – Contains fundamental classes such as String, Math, and System.
• [Link] – Contains utility classes like ArrayList, Scanner, and Date.
• [Link] – Contains classes for input and output operations.
• [Link] – Contains classes for graphical user interface components.
Example
1 import [Link]. Scanner ;
2 public class Test {
3 public static void main( String [] args) {
4 Scanner sc = new Scanner ( System .in);
5 System .out. println (" Enter a number :");
6 int num = sc. nextInt ();
7 System .out. println (" Number is: " + num);
8 }
9 }
10
User-defined packages are packages created by the programmer to organize classes. A package
is created using the package keyword. Example
1 package mypackage ;
2 public class Test {
3 public void display () {
4 System .out. println ("This is a user - defined package ");
5 }
6 }
7
44
23.2 Using a Package
Packages can be used in two ways:
• Using import packageName.*;
• Using import [Link];
Example
1 import [Link] .*;
2 public class Example {
3 public static void main( String [] args) {
4 ArrayList <String > list = new ArrayList <>();
5 [Link]("Java");
6 [Link](" Programming ");
7 System .out. println (list);
8 }
9 }
10
23.4 Summary
Package Type Description
Built-in Package Predefined packages provided by Java
User-defined Package Packages created by programmers
The classpath can be set temporarily using the command line. For Windows
1 set classpath =.;
2
Here:
• . represents the current directory
• It tells Java to search for classes in the current folder
45
23.5.2 Setting Classpath Permanently
Classpath can also be set permanently through environment variables. Steps (Windows)
7. Variable Value: .;
This command creates a directory named mypackage and stores the compiled class file in it.
Step 3: Use the Package
1 import mypackage .Test;
2 public class Main {
3 public static void main( String [] args) {
4 Test t = new Test ();
5 [Link] ();
6 }
7 }
8
23.5.4 Summary
Term Description
Classpath Path where Java searches for classes and packages
Temporary Classpath Set using command line
Permanent Classpath Set using environment variables
46
23.6 JAR Files
• JAR (Java ARchive) is a compressed file that contains class files, packages, subpackages,
resources (images, audio), and a manifest file.
or
1 import packageName .*;
2
Example
1 import [Link]. Scanner ;
2 public class Test {
3 public static void main( String [] args) {
4 Scanner sc = new Scanner ( System .in);
5 System .out. println (" Enter number :");
6 int num = sc. nextInt ();
7 System .out. println (" Number : " + num);
8 }
9 }
10
The static import feature allows static members (variables and methods) of a class to be used
directly without referencing the class name. Syntax
1 import static packageName . className . memberName ;
2
or
1 import static packageName . className .*;
2
Example
1 import static [Link] .*;
2 public class Test {
3 public static void main( String [] args) {
4 System .out. println (sqrt (16));
47
5 System .out. println (pow (2 ,3));
6 }
7 }
8
Output
1 4.0
2 8.0
3
Here, the methods sqrt() and pow() are used without writing [Link]() or [Link]().
23.8.2 Examples
• [Link]
• [Link]
• [Link]
48
24 Access Modifiers in Java
Access modifiers in Java are used to control the visibility and accessibility of classes, variables,
methods, and constructors. They help in implementing data hiding and encapsulation in
object-oriented programming. Java provides four types of access modifiers:
• public
• protected
• default (no modifier)
• private
Private members are usually accessed using getter and setter methods.
49
24.4 Default Access Modifier
If no access modifier is specified, it is considered default. Default members can be accessed
only within the same package. Example
1 class Test {
2 int number = 5;
3 void show () {
4 System .out. println (" Default access ");
5 }
6 }
7
Note: Protected members can be accessed in subclasses even if they are in different packages.
24.6 Summary
• public – accessible everywhere
Abstraction Encapsulation
Hides unnecessary details Hides code and data into a
and shows only essential in- single unit.
formation.
Focuses on external lookup Focuses on internal working
(what an object does). (how it does).
Implemented using ab- Implemented using access
stract classes and inter- modifiers (private, public,
faces. protected).
Solves issues at design Solves issues at implemen-
level. tation level.
Process of gaining informa- Process of containing infor-
tion. mation.
50
Appendix: In-Depth Examples for Each Topic
51
The following examples provide deeper insight into the core concepts discussed above.
Listing 2: [Link]
52
5 }
6 public abstract double area ();
7 public void displayColor () {
8 System .out. println (" Color : " + color);
9 }
10 }
11 interface Drawable {
12 void draw ();
13 default void print () {
14 System .out. println (" Drawing ...");
15 }
16 }
17 class Circle extends Shape implements Drawable {
18 private double radius ;
19 public Circle ( String color , double radius ) {
20 super (color);
21 this. radius = radius ;
22 }
23 @Override
24 public double area () {
25 return [Link] * radius * radius ;
26 }
27 @Override
28 public void draw () {
29 System .out. println (" Drawing a circle of radius " + radius );
30 }
31 }
32 public class TestAbstraction {
33 public static void main( String [] args) {
34 Circle c = new Circle ("Red", 5);
35 c. displayColor ();
36 System .out. println ("Area: " + [Link] ());
37 [Link] ();
38 [Link] ();
39 }
40 }
41
53
16 System .out. println (" Processing credit card payment of $" + amount
17 + " using card " + cardNumber . substring ( cardNumber . length () - 4));
18 }
19 }
20 class PayPalPayment extends Payment {
21 private String email;
22 public PayPalPayment ( double amount , String email) {
23 super ( amount );
24 [Link] = email;
25 }
26 @Override
27 public void process () {
28 System .out. println (" Processing PayPal payment of $" + amount
29 + " for account " + email);
30 }
31 }
32 public class TestPolymorphism {
33 public static void main( String [] args) {
34 Payment [] payments = {
35 new CreditCardPayment (100.50 , "1234 -5678 -9012 -3456"),
36 new PayPalPayment (75.25 , " user@example .com"),
37 new CreditCardPayment (200.00 , "1111 -2222 -3333 -4444")
38 };
39 for ( Payment p : payments ) {
40 p. process ();
41 }
42 }
43 }
44
Listing 4: [Link]
1 class Animal {
2 protected String name;
3 public Animal () {
4 System .out. println (" Animal default constructor ");
5 }
6 public Animal ( String name) {
7 [Link] = name;
8 System .out. println (" Animal parameterized constructor : " + name);
9 }
10 }
11 class Dog extends Animal {
12 private String breed;
13 public Dog () {
14 System .out. println ("Dog default constructor ");
15 }
16 public Dog( String name , String breed) {
17 super (name);
18 [Link] = breed;
19 System .out. println ("Dog parameterized constructor : " + name + ", " +
breed);
20 }
21 }
22 public class TestInheritance {
54
23 public static void main( String [] args) {
24 System .out. println (" Creating Dog with default constructor :");
25 Dog d1 = new Dog ();
26 System .out. println ("\ nCreating Dog with parameterized constructor :");
27 Dog d2 = new Dog("Buddy ", " Golden Retriever ");
28 }
29 }
30
1 class Sample {
2 static {
3 System .out. println (" Sample class loaded ");
4 }
5 public Sample () {
6 System .out. println (" Sample object created ");
7 }
8 }
9 public class ClassLoadingDemo {
10 public static void main( String [] args) throws Exception {
11 System .out. println (" Before accessing Sample class ");
12 Class <?> clazz = Class. forName (" Sample ");
13 System .out. println (" After Class . forName ()");
14 Sample obj = ( Sample ) clazz. newInstance ();
15 }
16 }
17
Listing 6: [Link]
55
21 + ", bool=" + obj1. instanceBool + ", str=" + obj1. instanceStr );
22 System .out. println ("obj2 instance : int=" + obj2. instanceInt
23 + ", bool=" + obj2. instanceBool + ", str=" + obj2. instanceStr );
24 obj1. demonstrateLocalVariable ();
25 }
26 }
27
Listing 7: [Link]
Listing 8: [Link]
56
14 outer2 :
15 for (int i = 1; i <= 3; i++) {
16 for (int j = 1; j <= 3; j++) {
17 if (i == 2 && j == 2) {
18 System .out. println (" Continuing outer loop");
19 continue outer2 ;
20 }
21 System .out. println ("i=" + i + ", j=" + j);
22 }
23 }
24 }
25 }
26
Listing 9: [Link]
57
1 int [] original = {1, 2, 3};
2 int [] shallowCopy = original ;
3 shallowCopy [0] = 100;
4 System .out. println ( original [0]); // 100
5 int [] deepCopy = original .clone ();
6 deepCopy [1] = 200;
7 System .out. println ( original [1]); // 2
8 int [][] matrix = {{1 ,2} ,{3 ,4}};
9 int [][] shallowMatrix = matrix .clone ();
10 shallowMatrix [0][0] = 99;
11 System .out. println ( matrix [0][0]) ; // 99
12
58
1 public class VarargsDemo {
2 public static int sum(int ... numbers ) {
3 int total = 0;
4 for (int n : numbers ) {
5 total += n;
6 }
7 return total;
8 }
9 public static void main( String [] args) {
10 System .out. println (sum (1, 2)); // 3
11 System .out. println (sum (1, 2, 3, 4, 5)); // 15
12 System .out. println (sum ()); // 0
13 }
14 }
15
1 class OverloadPromotion {
2 void display (int a) {
3 System .out. println ("int: " + a);
4 }
5 void display ( double a) {
6 System .out. println (" double : " + a);
7 }
8 public static void main( String [] args) {
9 OverloadPromotion obj = new OverloadPromotion ();
10 obj. display (10); // int
11 obj. display (10.5f); // double ( promotion )
12 obj. display ('A'); // int (char -> int)
13 }
14 }
15
1 class Employee {
2 int id;
3 String name;
4 double salary ;
5 Employee () {
6 this (0, " Unknown ", 0.0);
7 System .out. println (" Default constructor ");
8 }
9 Employee (int id , String name , double salary ) {
10 [Link] = id;
11 [Link] = name;
12 this. salary = salary ;
13 System .out. println (" Parameterized constructor ");
14 }
15 void display () {
16 System .out. println (id + " " + name + " " + salary );
17 }
18 public static void main( String [] args) {
59
19 Employee e1 = new Employee ();
20 e1. display ();
21 Employee e2 = new Employee (101 , " Alice ", 50000) ;
22 e2. display ();
23 }
24 }
25
References
[1] E. Balaguruswami, Programming with Java: A Primer, 6th ed. McGraw Hill Education, 2019.
60