0% found this document useful (0 votes)
4 views60 pages

Unit 1

This document is a detailed study material for Java programming, covering fundamental concepts such as Object-Oriented Programming, the history of Java, and its advantages over other languages. It includes sections on Java applications, environment setup, program structure, variables, operators, data types, comments, control flow, and arrays. The material is structured to provide a comprehensive understanding of Java programming fundamentals.

Uploaded by

DARK NIGHT
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)
4 views60 pages

Unit 1

This document is a detailed study material for Java programming, covering fundamental concepts such as Object-Oriented Programming, the history of Java, and its advantages over other languages. It includes sections on Java applications, environment setup, program structure, variables, operators, data types, comments, control flow, and arrays. The material is structured to provide a comprehensive understanding of Java programming fundamentals.

Uploaded by

DARK NIGHT
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

Java Programming – Unit 1: Fundamentals of Java

E. Balaguruswami’s Programming with Java

Detailed Study Material

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

3 Advantages of Java over C/C++ 7

4 Types of Java Applications 7

5 Editions of Java 8

6 Features of Java (Detailed) 8

7 Java Environment: JVM, JRE, JDK 9


7.1 Java Virtual Machine (JVM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
7.1.1 Internal Architecture of JVM . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
7.2 Java Runtime Environment (JRE) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
7.3 Java Development Kit (JDK) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
7.4 Relationship Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

8 Java Program Structure and Compilation Process 10


8.1 Source File Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
8.2 Compilation and Execution Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
8.3 First Java Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

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

11 Data Types in Java 16


11.1 Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
11.2 Example Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
11.3 Non-Primitive (Reference) Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
11.4 Difference Between Primitive and Non-Primitive Types . . . . . . . . . . . . . . . . 18
11.5 Default Values of Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . 18

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

13 Control Flow in Java 19


13.1 Selection Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
13.1.1 if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
13.1.2 if-else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
13.1.3 switch Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
13.2 Iteration Statements (Loops) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
13.2.1 for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
13.2.2 while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
13.2.3 do-while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
13.3 Jump Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
13.3.1 break Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
13.3.2 continue Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
13.3.3 return Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

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

17 Class and Object in Java 31


17.1 Class in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
17.2 Object in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
17.3 Example: Class and Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
17.4 Multiple Objects Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
17.5 Characteristics of a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
17.6 Real-Life Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
17.7 Key Differences Between Class and Object . . . . . . . . . . . . . . . . . . . . . . . . 33

18 Four Pillars of Java (Object-Oriented Programming) 33


18.1 Diagram of Four Pillars of OOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
18.2 Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
18.3 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
18.4 Types of Inheritance in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
18.4.1 Inheritance Types Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
18.4.2 Single Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
18.4.3 Multilevel Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

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

19 Method Overloading and Method Overriding in Java 38


19.1 Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
19.2 Method Overriding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
19.3 Difference Between Method Overloading and Method Overriding . . . . . . . . . . 39

20 Interfaces and Abstract Classes in Java 40


20.1 Abstract Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
20.2 Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
20.3 Multiple Interfaces Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
20.4 Difference Between Abstract Class and Interface . . . . . . . . . . . . . . . . . . . . 41

21 This Keyword in Java 41


21.1 Using this to Refer Instance Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
21.2 Calling Current Class Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
21.3 Calling Current Class Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
21.4 Passing this as an Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
21.5 Returning Current Class Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
21.6 Summary of Uses of this Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

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

25 Difference Between Abstraction and Encapsulation 50

Appendix: In-Depth Examples 51

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.

1.2 Fundamental Features of OOP


1. Encapsulation: Wrapping up of data and methods into a single unit (class). It hides the
internal state and provides controlled access.

2. Abstraction: Hiding implementation details and showing only essential features.

3. Polymorphism: Ability to take many forms (e.g., method overloading and overriding).

4. Inheritance: Deriving new classes from existing ones, promoting reusability.

5. Class and Object based: Programs are organized around objects that contain both data
and behavior.

1.3 Object-Based vs. Fully Object-Oriented Languages


• Object-Based Language (OBL): Supports objects and encapsulation but does not support
inheritance or polymorphism. (e.g., JavaScript, Visual Basic)

• 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

Year Version Major Features


1996 JDK 1.0 First official version
1998 JDK 1.2 Swing GUI, Collections Framework
2000 J2SE 1.3 Performance improvements
2002 J2SE 1.4 Assertions, NIO
2004 Java 5 Generics, Annotations, Autoboxing, Enums
2014 Java 8 Lambda expressions, Streams API, Date/Time API
2018 Java 11 Long-Term Support (LTS)
2021 Java 17 LTS (sealed classes, pattern matching)
2023 Java 21 LTS (virtual threads, record patterns)
2025 Java 25 LTS (Compact Source, Flexible Constructors)

Table 1: History of Java Versions (based on Balaguruswami and recent releases)

3 Advantages of Java over C/C++


• Platform Independent: Java compiles to bytecode, which runs on any JVM (WORA). C/C++
are platform-dependent; they need recompilation for each platform.
• Object-Oriented: Java is designed from ground up as OOP, whereas C++ added OOP to C.
• Secure: No pointers, bytecode verification, security manager, and runtime sandbox pre-
vent unauthorized memory access.
• Robust: Strong memory management, exception handling, garbage collection, type check-
ing.
• Multithreaded: Built-in support for concurrent programming; C/C++ require platform-
specific threading libraries.
• Portable: Bytecode is architecture-neutral; same bytecode runs anywhere.
• High Performance: Just-In-Time (JIT) compilation improves execution speed.
• Dynamic: Classes are loaded on demand; supports reflection and dynamic linking.

4 Types of Java Applications


1. Stand-alone Application: Desktop applications (e.g., media player, antivirus, Acrobat Reader)
using AWT/Swing/JavaFX.
2. Web Application: Runs on server side and generates dynamic web pages (e.g., e-commerce
sites) using Servlets, JSP, JSF.
3. Enterprise Application: Distributed applications like banking systems, using Enterprise
JavaBeans (EJB), JPA, etc.
4. Mobile Application: Android apps using Android SDK (Java-based) and Java ME for older
mobile devices.
5. Other Applications: Robotics, embedded systems, smart cards, games, etc.

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.

6 Features of Java (Detailed)


According to Balaguruswami, Java has the following features:

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.

2. Object-Oriented: Java supports all OOP concepts: encapsulation, inheritance, polymor-


phism, abstraction.

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:

• Loading, verifying, and executing bytecode.

• Managing memory (heap, stack, method area).

• Providing garbage collection.

• Providing security through bytecode verification and security manager.

7.1.1 Internal Architecture of JVM

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.

4. Execution Engine: Executes bytecode. Contains an interpreter and a Just-In-Time (JIT)


compiler. It also handles garbage collection.

7.2 Java Runtime Environment (JRE)


The JRE provides the environment needed to run Java programs. It consists of:

• JVM

• Core class libraries (Java API)

• Supporting files (e.g., properties files, font files)

JRE = JVM + Core Libraries + Supporting Files

7.3 Java Development Kit (JDK)


The JDK is a software development kit used to develop Java applications. It includes:

• JRE

• Development tools: javac (compiler), java (interpreter), javadoc (documentation genera-


tor), jar (archiver), jdb (debugger), appletviewer, etc.

JDK = JRE + Development Tools

9
7.4 Relationship Diagram
+---------------------+
| JDK |
| +---------------+ |
| | JRE | |
| | +---------+ | |
| | | JVM | | |
| | +---------+ | |
| | Libraries | |
| +---------------+ |
| Tools (javac, etc.)|
+---------------------+

8 Java Program Structure and Compilation Process


8.1 Source File Structure
A Java source file can contain:

1. An optional package statement (must be the first line).

2. Zero or more import statements.

3. One or more class/interface definitions.

Example:
1 package mypackage ;
2 import [Link]. Scanner ;
3 public class MyClass {
4 // class body
5 }
6

8.2 Compilation and Execution Steps


1. Write the source code in a file with .java extension.

2. Compile the program using the Java compiler:

javac [Link]

This produces a bytecode file [Link].

3. Execute the program using the Java interpreter:

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

9.1 Example Program

1 public class VariableExample {


2 public static void main( String [] args) {
3 int number = 10;
4 double price = 99.5;
5 char grade = 'A';
6 boolean status = true;
7 System .out. println (" Number : " + number );
8 System .out. println (" Price: " + price);
9 System .out. println (" Grade: " + grade);
10 System .out. println (" Status : " + status );
11 }
12 }
13

9.2 Types of Variables in Java


Java mainly has three types of variables:
1. Local Variable
2. Instance Variable
3. Static Variable

11
9.3 Local Variable
A local variable is declared inside a method, constructor, or block. Characteristics

• Declared inside a method

• Accessible only within that method

• Must be initialized before use

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

9.4 Instance Variable


An instance variable is declared inside a class but outside any method. Characteristics

• Belongs to an object

• Each object has its own copy

• Gets default value if not initialized

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

9.5 Static Variable


A static variable is declared using the static keyword and is shared among all objects of the
class. Characteristics

• Shared by all objects

• Only one copy exists

• Stored in class memory

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

9.6 Rules for Naming Variables in Java


• Must begin with a letter, underscore _ or dollar sign $.

• Cannot start with a number.

• Cannot use Java reserved keywords.

• Java is case-sensitive.

• Variable names usually follow camelCase convention.

9.7 Examples of Valid and Invalid Variables


Valid
1 int age;
2 double salary ;
3 String studentName ;
4

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

Java operators are broadly classified into the following categories:

13
• Arithmetic Operators

• Relational (Comparison) Operators

• Logical Operators

• Assignment Operators

• Unary Operators

• Bitwise Operators

• Ternary Operator

10.1 Arithmetic Operators


Arithmetic operators are used to perform mathematical operations.

Operator Meaning Example


+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (remainder) a%b

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

10.2 Relational (Comparison) Operators


These operators compare two values and return a boolean result.

Operator Meaning Example


== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

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

10.4 Assignment Operators


Assignment operators are used to assign values to variables.
Operator Example
= a = 10
+= a += 5
-= a -= 5
*= a *= 5
/= a /= 5
%= a %= 5
Example:
1 int a = 10;
2 a += 5; // a = a + 5
3 System .out. println (a);
4

10.5 Unary Operators


Unary operators operate on a single operand.
Operator Meaning
+ Unary plus
- Unary minus
++ Increment
– Decrement
! Logical NOT
Example:
1 int a = 5;
2 a++;
3 System .out. println (a);
4 a--;
5 System .out. println (a);
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

10.7 Ternary Operator


The ternary operator is a shorthand for an if-else statement. Syntax:
1 condition ? expression1 : expression2 ;
2

Example:
1 int a = 10;
2 int b = 20;
3 int max = (a > b) ? a : b;
4 System .out. println (" Maximum value: " + max);
5

10.7.1 Operator Precedence Table

Precedence Level Operators Description


1 () [] . Parentheses, array access, member access
2 ++ -- Unary increment, decrement
3 + - ! ~ Unary plus, minus, logical NOT, bitwise NOT
4 * / % Multiplication, division, modulus
5 + - Addition, subtraction
6 << >> >>> Bitwise shift operators
7 < <= > >= Relational operators
8 == != Equality operators
9 & Bitwise AND
10 ^ Bitwise XOR
11 | Bitwise OR
12 && Logical AND
13 || Logical OR
14 ?: Ternary operator
15 = += -= *= /= %= Assignment operators

11 Data Types in Java


A data type specifies the type of data that a variable can store in a program. Java is a strongly
typed language, which means every variable must be declared with a specific data type before
it is used. Java data types are broadly classified into two categories:
1. Primitive Data Types
2. Non-Primitive (Reference) Data Types

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.

Data Type Size Description Example


byte 1 byte Stores small integers byte a = 10;
short 2 bytes Stores small integer values short s = 200;
int 4 bytes Stores integer values int num = 1000;
long 8 bytes Stores large integers long l = 100000L;
float 4 bytes Stores decimal numbers float f = 10.5f;
double 8 bytes Stores large decimal numbers double d = 20.99;
char 2 bytes Stores single character char ch = ’A’;
boolean 1 bit Stores true or false boolean flag = true;

11.2 Example Program

1 public class DataTypesExample {


2 public static void main( String [] args) {
3 int number = 100;
4 float price = 10.5f;
5 double value = 25.789;
6 char grade = 'A';
7 boolean status = true;
8 System .out. println (" Integer : " + number );
9 System .out. println (" Float: " + price);
10 System .out. println (" Double : " + value);
11 System .out. println (" Character : " + grade);
12 System .out. println (" Boolean : " + status );
13 }
14 }
15

11.3 Non-Primitive (Reference) Data Types


Non-primitive data types are also known as reference types because they store the reference
(address) of objects. Examples include:

• 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

11.5 Default Values of Primitive Data Types


Data Type Default Value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char ’\u0000’
boolean false

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

12.1 Single-line Comment


A single-line comment begins with //. Everything written after // on the same line is treated as
a comment. Example:
1 public class CommentExample {
2 public static void main( String [] args) {
3 int a = 10; // variable declaration
4 System .out. println (a); // printing value
5 }
6 }
7

12.2 Multi-line Comment


A multi-line comment begins with /* and ends with */. It can span multiple lines and is often
used to explain longer sections of code. Example:
1 /*
2 This program demonstrates
3 multi -line comments in Java

18
4 */
5 public class Test {
6 public static void main( String [] args) {
7 System .out. println (" Java Comments ");
8 }
9 }
10

12.3 Documentation Comment


Documentation comments begin with /** and end with */. They are used to generate docu-
mentation using the javadoc tool. Example:
1 /**
2 * This program prints a message .
3 * Author : Student
4 */
5 public class Demo {
6 public static void main( String [] args) {
7 System .out. println (" Documentation Comment Example ");
8 }
9 }
10

12.4 Advantages of Comments


• Improve readability of the code.

• Help in understanding complex logic.

• Useful for debugging and maintaining programs.

• Provide documentation for other programmers.

13 Control Flow in Java


Control flow statements determine the order in which the statements in a program are exe-
cuted. Normally, Java executes statements sequentially from top to bottom. However, control
flow statements allow the program to make decisions, repeat actions, or jump to different parts
of the code. Control flow in Java is mainly divided into the following categories:

1. Selection (Decision-Making) Statements

2. Iteration (Looping) Statements

3. Jump Statements

13.1 Selection Statements


Selection statements are used to execute certain parts of code based on conditions.

19
13.1.1 if Statement

The if statement executes a block of code if a specified condition is true.


1 int age = 18;
2 if(age >= 18) {
3 System .out. println (" Eligible to vote ");
4 }
5

13.1.2 if-else 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

13.1.3 switch Statement

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

13.2 Iteration Statements (Loops)


Loops are used to execute a block of code repeatedly as long as a specified condition is true.

13.2.1 for Loop

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

13.2.3 do-while Loop

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

13.3 Jump Statements


Jump statements are used to transfer control to another part of the program.

13.3.1 break Statement

The break statement is used to terminate a loop or switch statement.


1 for(int i = 1; i <= 10; i++) {
2 if(i == 5) {
3 break;
4 }
5 System .out. println (i);
6 }
7

13.3.2 continue Statement

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.

14.1 Declaration of an Array


An array is declared by specifying the data type followed by square brackets.
1 dataType [] arrayName ;
2

Example:
1 int [] numbers ;
2

14.2 Array Creation


After declaration, memory for the array must be allocated using the new keyword.
1 numbers = new int [5];
2

This creates an array that can store 5 integer values.

14.3 Array Declaration and Initialization


An array can also be declared and initialized in a single statement.
1 int [] numbers = {10, 20, 30, 40, 50};
2

14.4 Accessing Array Elements


Array elements are accessed using their index number.
1 int [] numbers = {10, 20, 30, 40, 50};
2 System .out. println ( numbers [0]); // prints 10
3 System .out. println ( numbers [2]); // prints 30
4

22
14.5 Example Program

1 public class ArrayExample {


2 public static void main( String [] args) {
3 int [] numbers = {10, 20, 30, 40, 50};
4 for(int i = 0; i < numbers . length ; i++) {
5 System .out. println ( numbers [i]);
6 }
7 }
8 }
9

14.6 Types of Arrays in Java


Arrays in Java are mainly of two types:

1. One-Dimensional Array

2. Multi-Dimensional Array

14.6.1 One-Dimensional Array

A one-dimensional array stores elements in a single row.


1 int [] marks = {80, 85, 90, 75};
2

14.6.2 Two-Dimensional Array

A two-dimensional array stores data in rows and columns.


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

Accessing elements:
1 System .out. println ( matrix [0][1]) ; // prints 2
2

14.7 Advantages of Arrays


• Allows storing multiple values using a single variable.

• Easy access using index numbers.

• Efficient for handling large amounts of similar data.

14.8 Limitations of Arrays


• Arrays have a fixed size once created.

• All elements must be of the same data type.

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.

15.1 Creating Strings


There are two common ways to create strings in Java.

15.1.1 Using String Literal

A string can be created directly using double quotation marks.


1 String name = "Java Programming ";
2

15.1.2 Using the new Keyword

A string can also be created using the new keyword.


1 String name = new String (" Java Programming ");
2

15.2 Example Program

1 public class StringExample {


2 public static void main( String [] args) {
3 String message = "Hello Java ";
4 System .out. println ( message );
5 }
6 }
7

15.3 Common String Methods


The String class provides several useful methods for string manipulation.

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

1 public class StringMethods {


2 public static void main( String [] args) {
3 String str = "Java ";
4 System .out. println (str. length ());
5 System .out. println (str. toUpperCase ());
6 System .out. println (str. charAt (2));
7 System .out. println (str. concat (" Programming "));
8 }
9 }
10

15.5 String Immutability


Strings in Java are immutable. This means that once a string object is created, its value cannot
be modified. Example:
1 String s = "Java ";
2 s. concat (" Programming ");
3 System .out. println (s);
4

Output:
1 Java
2

The original string remains unchanged.

15.6 Advantages of Using Strings


• Easy manipulation of text data.

• Provides many built-in methods.

• Immutable nature improves security and performance.

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.

16.1 Syntax of a Method


The general syntax for defining a method in Java is:
1 returnType methodName ( parameters ) {
2 // method body
3 }
4

Where:

• returnType – The data type of the value returned by the method.

25
• methodName – The name of the method.

• parameters – Inputs passed to the method.

16.2 Example of a Method

1 public class MethodExample {


2 void display () {
3 System .out. println (" Hello Java ");
4 }
5 public static void main( String [] args) {
6 MethodExample obj = new MethodExample ();
7 obj. display ();
8 }
9 }
10

16.3 Method with Parameters


A method can accept parameters to perform operations on given inputs.
1 public class AddNumbers {
2 int add(int a, int b) {
3 return a + b;
4 }
5 public static void main( String [] args) {
6 AddNumbers obj = new AddNumbers ();
7 int result = [Link] (5, 10);
8 System .out. println ( result );
9 }
10 }
11

16.4 Method with Return Value


A method can return a value using the return statement.
1 public class Square {
2 int square (int n) {
3 return n * n;
4 }
5 public static void main( String [] args) {
6 Square obj = new Square ();
7 System .out. println (obj. square (4));
8 }
9 }
10

16.5 Types of Methods


Methods in Java are generally classified into two types:
1. Predefined Methods

2. User-defined Methods

26
16.5.1 Predefined Methods

These methods are already defined in Java libraries. Example:


1 System .out. println (" Hello Java ");
2

16.5.2 User-defined 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

16.6 Advantages of Methods


• Improves code reusability.

• Reduces code duplication.

• Makes programs easier to understand.

• Helps in modular programming.

16.7 Method Overloading in Java


Method Overloading is a feature that allows a class to have more than one method with the
same name but different parameter lists. The difference may be in:

• Number of parameters

• Type of parameters

• Order of parameters

Method overloading helps achieve compile-time polymorphism.

16.7.1 Example of Method Overloading

1 public class OverloadExample {


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 public static void main( String [] args) {
9 OverloadExample obj = new OverloadExample ();
10 System .out. println ([Link] (5, 10));
11 System .out. println ([Link] (5, 10, 15));
12 }
13 }
14

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

16.8 Static vs Non-Static Methods


Methods in Java can be classified into static methods and non-static (instance) methods.

16.8.1 Static Methods

A static method belongs to the class rather than an object. It is declared using the static key-
word.

• Can be called without creating an object.

• Accessed using the class name.

• Cannot directly access non-static variables or methods.

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

16.8.2 Non-Static Methods

Non-static methods belong to objects of a class.

• Require an object to be called.

• Can access both static and non-static members.

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

16.8.3 Difference Between Static and Non-Static Methods


Feature Static Method Non-Static Method
Belongs to Class Object
Object required No Yes
Access Using class name Using object

16.9 Call by Value in Java


In Java, arguments are passed to methods using call by value. This means a copy of the vari-
able’s value is passed to the method, not the original variable itself. Any changes made to the
parameter inside the method do not affect the original value.

16.9.1 Example of Call by Value

1 public class CallByValueExample {


2 void change (int x) {
3 x = x + 10;
4 System .out. println (" Inside method : " + x);
5 }
6 public static void main( String [] args) {
7 int num = 20;
8 CallByValueExample obj = new CallByValueExample ();
9 obj. change (num);
10 System .out. println (" Outside method : " + num);
11 }
12 }
13

Output:
1 Inside method : 30
2 Outside method : 20
3

The original value remains unchanged because Java uses call by value.

16.10 Recursion in Java


Recursion is a programming technique in which a method calls itself repeatedly until a spec-
ified condition is met. The condition that stops the recursive calls is known as the base case.
Recursion is commonly used to solve problems that can be broken down into smaller subprob-
lems.

29
16.10.1 Structure of Recursion

A recursive function must have two important parts:

• Base Case – The condition that stops the recursion.

• Recursive Call – The method calling itself with a smaller problem.

16.10.2 Example: Factorial Using Recursion

The factorial of a number n is defined as:

n! = n × (n − 1)!

with the base condition:


0! = 1
Example program:
1 public class FactorialRecursion {
2 int factorial (int n) {
3 if(n == 0) {
4 return 1; // base case
5 }
6 return n * factorial (n - 1); // recursive call
7 }
8 public static void main( String [] args) {
9 FactorialRecursion obj = new FactorialRecursion ();
10 int result = obj. factorial (5);
11 System .out. println (" Factorial = " + result );
12 }
13 }
14

16.10.3 Example: Fibonacci Series Using Recursion

The Fibonacci sequence is defined as:

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

• Makes code simpler and easier to understand for complex problems.

• Useful for problems involving trees, graphs, and divide-and-conquer algorithms.

16.10.5 Disadvantages of Recursion

• Requires more memory due to function call stack.

• May lead to slower execution compared to iterative solutions.

• Risk of stack overflow if the base condition is not defined properly.

17 Class and Object in Java


17.1 Class in Java
In Java, a Class is a blueprint or template used to create objects. It defines the properties
(variables) and behaviors (methods) of objects. A class does not occupy memory until an
object of that class is created. Syntax
1 class ClassName {
2 // variables (data members )
3 datatype variableName ;
4 // methods ( member functions )
5 void methodName () {
6 // code
7 }
8 }
9

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

• id, name � Data members (variables)

• display() � Member method

17.2 Object in Java


An Object is an instance of a class. It represents a real-world entity and occupies memory.
Objects are used to access the properties and methods of a class. Syntax for Creating Object
1 ClassName objectName = new ClassName ();
2

31
Where
• new � Keyword used to allocate memory
• objectName � Reference variable

17.3 Example: Class and Object

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

17.4 Multiple Objects Example

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:

• Variables (Instance variables)

• Methods (Functions)

• Constructors

• Blocks

• Nested Classes

17.6 Real-Life Example


Real World Java
Car design Class
Actual car Object
Student template Class
Particular student Object

Example:

• Class � Car

• Objects � BMW, Audi, Tesla

17.7 Key Differences Between Class and Object


Class Object
Blueprint Instance of class
Logical entity Physical entity
Does not occupy memory Occupies memory
Used to create objects Used to access class members

18 Four Pillars of Java (Object-Oriented Programming)


Object-Oriented Programming (OOP) in Java is based on four fundamental principles known as
the Four Pillars of Java. These concepts help in building modular, reusable, and maintainable
software systems.

• 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.

• Parent class � Super Class

• Child class � Sub 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

18.4 Types of Inheritance in Java


Inheritance in Java can be classified into different types based on how classes are derived from
one another.

1. Single Inheritance

2. Multilevel Inheritance

3. Hierarchical Inheritance

4. Multiple Inheritance (through Interfaces)

5. Hybrid Inheritance (combination using Interfaces)

18.4.1 Inheritance Types Diagram

Multilevel Hierarchical

A A A

B C
Single B B

18.4.2 Single Inheritance

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

In Multilevel Inheritance, a class is derived from another derived class. Example


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 class Puppy extends Dog {
12 void weep () {
13 System .out. println (" Puppy weeps ");
14 }
15 }
16

18.4.4 Hierarchical Inheritance

In Hierarchical Inheritance, multiple classes inherit from a single superclass. Example


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 class Cat extends Animal {
12 void meow () {
13 System .out. println ("Cat meows ");
14 }
15 }
16

18.4.5 Multiple 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

18.4.6 Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of inheritance. In Java, hybrid inheri-
tance can also be implemented using interfaces.

18.5 Summary of Types of Inheritance


Type Description
Single Inheritance One subclass inherits from one superclass
Multilevel Inheritance A class inherits from another derived class
Hierarchical Inheritance Multiple subclasses inherit from one superclass
Multiple Inheritance One class inherits from multiple interfaces
Hybrid Inheritance Combination of multiple inheritance types

18.6 Polymorphism
Polymorphism means many forms. It allows a single method name to perform different oper-
ations. Types of polymorphism:

• Compile-time polymorphism (Method Overloading)

• Runtime polymorphism (Method Overriding)

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

18.8 Summary of Four Pillars


Concept Description
Encapsulation Wrapping data and methods into a class
Inheritance Acquiring properties from another class
Polymorphism One method with multiple forms
Abstraction Hiding implementation details

19 Method Overloading and Method Overriding in Java


19.1 Method Overloading
Method Overloading is a feature in Java where multiple methods in the same class have the
same name but different parameter lists. It is an example of compile-time polymorphism.
The methods can differ in:
• Number of parameters

• 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

19.2 Method Overriding


Method Overriding occurs when a subclass provides a specific implementation of a method that
is already defined in its superclass. It is an example of runtime polymorphism. The method in
the subclass must have:

• The same method name

• The same parameters

• The same return type

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

19.3 Difference Between Method Overloading and Method Overriding

Feature Method Overloading Method Overriding


Definition Same method name with different parameters Redefining method of parent cla
Polymorphism Type Compile-time polymorphism Runtime polymorphism
Inheritance Required Not required Required
Method Signature Must be different Must be same
Class Relationship Usually in same class Parent-child class relationship

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.

20.1 Abstract Class


An abstract class is a class that cannot be instantiated (cannot create objects directly). It may
contain both abstract methods (without implementation) and concrete methods (with imple-
mentation). An abstract class is declared using the keyword abstract. Example
1 abstract class Shape {
2 abstract void draw ();
3 void display () {
4 System .out. println ("This is a shape ");
5 }
6 }
7 class Circle extends Shape {
8 void draw () {
9 System .out. println (" Drawing Circle ");
10 }
11 }
12 public class Main {
13 public static void main( String [] args) {
14 Circle c = new Circle ();
15 [Link] ();
16 c. display ();
17 }
18 }
19

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

20.3 Multiple Interfaces Example


A class can implement multiple interfaces.
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 }
11 public void display () {
12 System .out. println (" Interface B");
13 }
14 }
15

20.4 Difference Between Abstract Class and Interface


Feature Abstract Class Interface
Methods Abstract and concrete methods Only abstract methods (before Java 8)
Variables Can have instance variables Only constants
Constructors Allowed Not allowed
Inheritance Single inheritance Multiple inheritance possible
Keyword extends implements

21 This Keyword in Java


The this keyword in Java is a reference variable that refers to the current object of a class. It
is used to access the current object’s variables and methods. The this keyword helps remove
ambiguity between instance variables and parameters with the same name.

21.1 Using this to Refer Instance Variables


When local variables and instance variables have the same name, the this keyword is used to
distinguish them. Example
1 class Student {
2 int id;
3 String name;
4 Student (int id , String name) {
5 [Link] = id;
6 [Link] = name;

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

21.2 Calling Current Class Method


The this keyword can also be used to call a method of the current class.
1 class Test {
2 void display () {
3 System .out. println (" Hello ");
4 }
5 void show () {
6 this. display ();
7 }
8 }
9

21.3 Calling Current Class Constructor


The this() keyword can be used to call another constructor of the same class.
1 class Student {
2 int id;
3 String name;
4 Student () {
5 this (101 , "Ali");
6 }
7 Student (int id , String name) {
8 [Link] = id;
9 [Link] = name;
10 }
11 void display () {
12 System .out. println (id + " " + name);
13 }
14 }
15

21.4 Passing this as an Argument


The this keyword can be passed as an argument to methods or constructors.
1 class Test {
2 void display (Test obj) {
3 System .out. println (" Method called ");
4 }
5 void show () {

42
6 display (this);
7 }
8 }
9

21.5 Returning Current Class Object


The this keyword can also be used to return the current class object.
1 class Test {
2 Test getObject () {
3 return this;
4 }
5 }
6

21.6 Summary of Uses of this Keyword


Use Description
Refer instance variable Distinguish instance variable from local variable
Call current class method Invoke another method of same class
Call constructor Invoke another constructor of same class
Pass as argument Pass current object to method/constructor
Return current object Return reference of current object

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).

• Final method: Cannot be overridden by subclasses.

• Final class: Cannot be extended (inherited).

22.1 Examples

1 final int SPEED = 90; // constant


2 // SPEED = 100; // Error
3 class Bike {
4 final void run () { System .out. println (" Running "); }
5 }
6 class Honda extends Bike {
7 // void run () { } // Error : cannot override final method
8 }
9 final class Bike { }
10 // class Honda extends Bike { } // Error : cannot inherit from final class
11

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

23.1 Types of Packages in Java


There are two types of packages in Java:
1. Built-in Packages
2. User-defined Packages

23.1.1 Built-in Packages

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

23.1.2 User-defined Packages

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.3 Advantages of Packages


• Avoids naming conflicts
• Provides access protection
• Improves code organization
• Makes programs easier to maintain

23.4 Summary
Package Type Description
Built-in Package Predefined packages provided by Java
User-defined Package Packages created by programmers

23.5 Classpath Setting for Packages


The classpath in Java is a parameter that tells the Java compiler and Java Virtual Machine (JVM)
where to find user-defined classes and packages. When working with packages, the classpath
must be set correctly so that Java can locate the compiled classes.

23.5.1 Setting Classpath Temporarily

The classpath can be set temporarily using the command line. For Windows
1 set classpath =.;
2

For Linux / Mac


1 export 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)

1. Open Control Panel

2. Go to System and Security � System

3. Click Advanced System Settings

4. Click Environment Variables

5. Under System Variables, click New

6. Variable Name: CLASSPATH

7. Variable Value: .;

23.5.3 Example: Using Package with Classpath

Step 1: Create Package


1 package mypackage ;
2 public class Test {
3 public void show () {
4 System .out. println (" Hello from package ");
5 }
6 }
7

Step 2: Compile the Program


1 javac -d . [Link]
2

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

Step 4: Compile and Run


1 javac [Link]
2 java Main
3

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.

• To create a JAR: jar -cf [Link] package/

• Example: jar -cf [Link] com/mypackage/*.class

23.7 Import and Static Import in Java


In Java, the import statement is used to access classes and interfaces from other packages. It
allows the programmer to use classes without writing the full package name.

23.7.1 Import Statement

The general syntax of the import statement is:


1 import packageName . className ;
2

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

Here, the class Scanner is imported from the [Link] package.

23.7.2 Static Import

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 Naming Convention for Packages


Java packages follow specific naming conventions to maintain uniqueness and readability.

23.8.1 Rules for Package Naming

• Package names should be written in lowercase letters.

• Use meaningful names related to the functionality of the package.

• Avoid using reserved keywords.

• Use reverse domain name notation for uniqueness.

23.8.2 Examples

• [Link]

• [Link]

• [Link]

23.8.3 Example of Package Declaration

1 package com. company .math;


2 public class Calculator {
3 public int add(int a, int b) {
4 return a + b;
5 }
6 }
7

23.8.4 Advantages of Proper Package Naming

• Avoids naming conflicts

• Improves code organization

• Makes packages easier to identify

• Helps maintain large projects

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

24.1 Public Access Modifier


The public modifier allows access from any class, whether it is in the same package or a different
package. Example
1 class Test {
2 public int number = 10;
3 public void display () {
4 System .out. println (" Public method ");
5 }
6 }
7

24.2 Private Access Modifier


The private modifier restricts access to the same class only. It cannot be accessed from outside
the class. Example
1 class Test {
2 private int number = 10;
3 private void show () {
4 System .out. println (" Private method ");
5 }
6 }
7

Private members are usually accessed using getter and setter methods.

24.3 Protected Access Modifier


The protected modifier allows access within the same package and also in subclasses (child
classes) located in different packages. Example
1 class Animal {
2 protected void eat () {
3 System .out. println (" Animal eats");
4 }
5 }
6 class Dog extends Animal {
7 void bark () {
8 eat ();
9 }
10 }
11

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

24.5 Access Modifier Visibility Table


Modifier Same Class Same Package Subclass Other Package
public Yes Yes Yes Yes
protected Yes Yes Yes No*
default Yes Yes No No
private Yes No No No

Note: Protected members can be accessed in subclasses even if they are in different packages.

24.6 Summary
• public – accessible everywhere

• protected – accessible within package and subclasses

• default – accessible only within same package

• private – accessible only within the same class

25 Difference Between Abstraction and Encapsulation

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.

Table 2: Abstraction vs Encapsulation

50
Appendix: In-Depth Examples for Each Topic

51
The following examples provide deeper insight into the core concepts discussed above.

A.1 Encapsulation with Validation

1 public class BankAccount {


2 private String accountNumber ;
3 private double balance ;
4 public BankAccount ( String accountNumber , double initialBalance ) {
5 this. accountNumber = accountNumber ;
6 if ( initialBalance >= 0) {
7 this. balance = initialBalance ;
8 } else {
9 this. balance = 0;
10 System .out. println (" Initial balance cannot be negative . Set to 0.");
11 }
12 }
13 public double getBalance () {
14 return balance ;
15 }
16 public void deposit ( double amount ) {
17 if ( amount > 0) {
18 balance += amount ;
19 } else {
20 System .out. println (" Deposit amount must be positive .");
21 }
22 }
23 public void withdraw ( double amount ) {
24 if ( amount > 0 && amount <= balance ) {
25 balance -= amount ;
26 } else {
27 System .out. println (" Insufficient funds or invalid amount .");
28 }
29 }
30 public String getAccountNumber () {
31 return accountNumber ;
32 }
33 }
34 public class TestEncapsulation {
35 public static void main( String [] args) {
36 BankAccount acc = new BankAccount ("12345 ", 1000);
37 acc. withdraw (500);
38 acc. withdraw (600);
39 acc. deposit ( -200);
40 System .out. println (" Final balance : " + acc. getBalance ());
41 }
42 }
43

Listing 2: [Link]

A.2 Abstraction – Abstract Class vs Interface

1 abstract class Shape {


2 protected String color;
3 public Shape( String color) {
4 [Link] = color;

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

Listing 3: Shape and Drawable

A.3 Polymorphism – Runtime with Payment System

1 abstract class Payment {


2 protected double amount ;
3 public Payment ( double amount ) {
4 this. amount = amount ;
5 }
6 public abstract void process ();
7 }
8 class CreditCardPayment extends Payment {
9 private String cardNumber ;
10 public CreditCardPayment ( double amount , String cardNumber ) {
11 super ( amount );
12 this. cardNumber = cardNumber ;
13 }
14 @Override
15 public void process () {

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]

A.4 Inheritance – Constructor Chaining with super

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

Listing 5: Animal and Dog

A.5 Java Environment – Class Loading

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]

A.6 Variables – Default Values and Static vs Instance

1 public class VariableDemo {


2 int instanceInt ;
3 boolean instanceBool ;
4 String instanceStr ;
5 static int staticCounter = 0;
6 public VariableDemo () {
7 staticCounter ++;
8 }
9 public void demonstrateLocalVariable () {
10 int localVar ;
11 // System .out. println ( localVar ); // error
12 localVar = 10;
13 System .out. println (" Local variable : " + localVar );
14 }
15 public static void main( String [] args) {
16 System .out. println (" Static counter before objects : " + staticCounter );
17 VariableDemo obj1 = new VariableDemo ();
18 VariableDemo obj2 = new VariableDemo ();
19 System .out. println (" Static counter after two objects : " + staticCounter )
;
20 System .out. println ("obj1 instance : int=" + obj1. instanceInt

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]

A.7 Bitwise and Shift Operators

1 public class BitwiseDemo {


2 public static void main( String [] args) {
3 int a = 60; // 0011 1100
4 int b = 13; // 0000 1101
5 System .out. println ("a & b = " + (a & b)); // 12
6 System .out. println ("a | b = " + (a | b)); // 61
7 System .out. println ("a ^ b = " + (a ^ b)); // 49
8 System .out. println ("~a = " + (~a)); // -61
9 System .out. println ("a << 2 = " + (a << 2)); // 240
10 System .out. println ("a >> 2 = " + (a >> 2)); // 15
11 System .out. println ("a >>> 2= " + (a >>> 2)); // 15
12 }
13 }
14

Listing 8: [Link]

A.8 Ternary Operator

1 int score = 85;


2 String grade = (score >= 90) ? "A" :
3 (score >= 80) ? "B" :
4 (score >= 70) ? "C" :
5 (score >= 60) ? "D" : "F";
6 System .out. println (" Grade : " + grade); // Grade : B
7

A.9 Labeled Break and Continue

1 public class LabelDemo {


2 public static void main( String [] args) {
3 outer:
4 for (int i = 1; i <= 3; i++) {
5 for (int j = 1; j <= 3; j++) {
6 if (i == 2 && j == 2) {
7 System .out. println (" Breaking outer loop");
8 break outer;
9 }
10 System .out. println ("i=" + i + ", j=" + j);
11 }
12 }
13 System .out. println (" After outer loop");

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]

A.10 Switch with Strings (Java 7+)

1 String day = " TUESDAY ";


2 switch (day. toLowerCase ()) {
3 case " monday ":
4 System .out. println ("Start of work week");
5 break ;
6 case " tuesday ":
7 case " wednesday ":
8 case " thursday ":
9 System .out. println (" Midweek ");
10 break ;
11 case " friday ":
12 System .out. println ("Last work day");
13 break ;
14 default :
15 System .out. println (" Weekend !");
16 }
17

A.11 Jagged Array

1 int [][] jagged = new int [3][];


2 jagged [0] = new int []{1 , 2, 3};
3 jagged [1] = new int []{4 , 5};
4 jagged [2] = new int []{6 , 7, 8, 9};
5 for (int [] row : jagged ) {
6 for (int val : row) {
7 System .[Link](val + " ");
8 }
9 System .out. println ();
10 }
11

A.12 Array Copy – Shallow vs Deep

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

A.13 String Immutability

1 String s1 = " Hello ";


2 String s2 = s1;
3 s1 = s1 + " World ";
4 System .out. println (s2); // Hello
5 System .out. println (s1); // Hello World
6

A.14 String Pool and intern()

1 String str1 = "Java";


2 String str2 = "Java";
3 String str3 = new String ("Java");
4 String str4 = str3. intern ();
5 System .out. println (str1 == str2); // true
6 System .out. println (str1 == str3); // false
7 System .out. println (str1 == str4); // true
8

A.15 StringBuilder vs StringBuffer Performance

1 long start = System . nanoTime ();


2 StringBuilder sb = new StringBuilder ();
3 for (int i = 0; i < 100000; i++) sb. append ("a");
4 long end = System . nanoTime ();
5 System .out. println (" StringBuilder : " + (end - start) + " ns");
6 start = System . nanoTime ();
7 StringBuffer sbf = new StringBuffer ();
8 for (int i = 0; i < 100000; i++) sbf. append ("a");
9 end = System . nanoTime ();
10 System .out. println (" StringBuffer : " + (end - start) + " ns");
11

A.16 Varargs (Variable Arguments)

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

A.17 Method Overloading with Type Promotion

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

A.18 Constructor Chaining with this()

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

You might also like