PBCST304 - Object Oriented Programming
Module 1
Introduction to Java Programming
Java is a high-level, object-oriented programming language developed by Sun
Microsystems (now owned by Oracle Corporation). It is widely used for building applications
across platforms — from desktop to mobile to enterprise systems.
Key Features of Java:
Platform Independent: "Write once, run anywhere" — Java code runs on any device
with the Java Virtual Machine (JVM).
Object-Oriented: Everything in Java is an object; this promotes reusability and
modularity.
Simple and Familiar: Syntax is similar to C/C++, making it easier for students with
prior programming exposure.
Secure: Java includes built-in security features like bytecode verification.
Robust: Strong memory management and exception handling.
Multithreaded: Supports concurrent execution of two or more threads.
Structure of a Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
public class HelloWorld: Every Java program must have at least one class. Here,
it's HelloWorld.
public static void main(String[] args): The main method is the entry point of any Java
application.
System.out.println(...): Prints text to the console.
How to Run:
1. Save the file as HelloWorld.java.
2. Open a terminal/command prompt.
3. Compile using:
javac HelloWorld.java
4. Run the program:
java HelloWorld
ava Compiler and Java Virtual Machine (JVM)
Java uses a two-step process to run programs:
Step 1: Java Compiler (javac)
The Java compiler is a program that:
Converts Java source code (.java file) into bytecode (.class file).
Bytecode is an intermediate, platform-independent code.
Example:
When you write:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Save it as HelloWorld.java.
Now compile it:
javac HelloWorld.java
This creates a file called HelloWorld.class — which contains bytecode.
Step 2: Java Virtual Machine (JVM)
The JVM is a virtual engine that:
Reads and executes the bytecode (.class file).
Converts bytecode to machine-specific code using Just-In-Time (JIT) compilation.
Ensures that the same .class file can run on any device with a JVM (Windows, Mac,
Linux, etc.).
To run the program:
java HelloWorld
The JVM runs the bytecode and produces the output:
Hello, World!
Why is this important?
Component Role Output
javac Java Compiler .class bytecode file
java (JVM) Executes the bytecode on your machine Program output on console
Summary
Java Compiler (javac) ➜ Converts .java to .class (bytecode).
JVM (java) ➜ Runs the bytecode, making Java platform-independent.
Java Command Line
What is it?
The command line (or terminal) is a text-based interface where users can type commands to
compile and run Java programs using tools provided by the Java Development Kit (JDK).
Common Java Commands:
Command Description
javac Compiles Java source code to bytecode .class files
java Runs the compiled Java program using the JVM
javap Disassembles .class files (shows bytecode info)
java -version Shows the installed Java version
Example (on terminal or command prompt):
javac HelloWorld.java # Compiles the file
java HelloWorld # Runs the program
Pros:
Lightweight, fast
Helps understand the compilation and execution process
Good for beginners and scripting
Cons:
No auto-completion, debugging, or GUI support
Can be slow for large projects
IDE (Integrated Development Environment)
What is an IDE?
An IDE is a software application that provides tools to help programmers write, test, and debug
their code efficiently. It offers a graphical interface and advanced features.
Popular Java IDEs:
IDE Features
Eclipse Open-source, good for enterprise development
IDE Features
IntelliJ IDEA Smart coding assistant, widely used in industry
NetBeans Official Oracle IDE for Java, supports GUI design
BlueJ Beginner-friendly, ideal for educational use
Key Features:
Syntax highlighting
Code completion (auto-suggest)
Real-time error checking
Graphical debugging tools
Project management and build tools
Pros:
Boosts productivity
Easier debugging
Integrated GUI builders for apps
Cons:
Heavier than command-line tools
May hide internal compilation steps from learners
Summary
Feature Command Line IDE
Interface Text-based Graphical (GUI)
Best For Learning basics, scripting Large projects, GUI apps, debugging
Examples javac, java Eclipse, IntelliJ, NetBeans
Features Minimal Full-featured development tools
Primitive Data Types in Java
Java has 8 primitive data types, which are the most basic types of data built into the language.
They are not objects and are stored directly in memory for performance.
Type Size Default Value Description Example
byte 1 byte (8-bit) 0 Small integers (-128 to 127) byte a = 10;
short 2 bytes 0 Larger than byte (-32,768 to 32,767) short b = 1000;
int 4 bytes 0 Common for integers int c = 12345;
long 8 bytes 0L Very large integers long d = 100000L;
float 4 bytes 0.0f Single-precision decimal float e = 3.14f;
double 8 bytes 0.0d Double-precision decimal (default) double f = 3.14159;
char 2 bytes '\u0000' Single 16-bit Unicode character char g = 'A';
boolean 1 bit (virtual) false Logical true/false boolean h = true;
Wrapper Classes in Java
Java provides wrapper classes in the java.lang package for each primitive data type. These
allow primitives to be treated as objects.
Primitive Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Why Use Wrapper Classes?
Required when working with collections like ArrayList, which only store objects.
Useful for type conversion, parsing from strings, and using object methods.
Enable null values (primitives cannot be null).
Autoboxing and Unboxing
Java automatically converts between primitives and wrappers:
Concept Description Example
Autoboxing primitive ➝ object (wrapper class) Integer x = 10;
Unboxing object ➝ primitive int y = x;
Example Code
public class WrapperExample {
public static void main(String[] args) {
int num = 5; // primitive
Integer obj = num; // autoboxing
int num2 = obj; // unboxing
System.out.println("Primitive: " + num);
System.out.println("Wrapper: " + obj);
System.out.println("Unboxed: " + num2);
}
}
Type Casting
Type Casting in Java is the process of converting a value from one data type to another.
Java has two types of type casting:
1. Widening (Implicit) Casting – small → large type
2. Narrowing (Explicit) Casting – large → small type
1. Widening Type Casting (Automatic)
Definition: Converting a smaller data type to a larger one.
Safe conversion – done automatically by Java.
Example:
public class WideningExample {
public static void main(String[] args) {
int a = 10;
double b = a; // int → double
System.out.println("int value: " + a);
System.out.println("double value: " + b);
}
}
Output:
int value: 10
double value: 10.0
Widening Order:
byte → short → int → long → float → double
2. Narrowing Type Casting (Manual)
Definition: Converting a larger data type to a smaller one.
Not safe automatically, so explicit casting is required.
Example:
public class NarrowingExample {
public static void main(String[] args) {
double a = 9.78;
int b = (int) a; // double → int
System.out.println("double value: " + a);
System.out.println("int value: " + b);
}
}
Output:
double value: 9.78
int value: 9
Decimal part is lost during narrowing.
Example with Character
public class CharCasting {
public static void main(String[] args) {
char c = 'A';
int ascii = c; // char → int (widening)
System.out.println("ASCII of A is: " + ascii);
int n = 66;
char ch = (char) n; // int → char (narrowing)
System.out.println("Character of 66 is: " + ch);
}
}
Java Operators
In Java, operators are special symbols used to perform operations on variables and values. They
are grouped into several categories:
1. Arithmetic Operators
Used for basic mathematical operations.
Operator Description Example (a = 10, b = 5) Result
+ Addition a+b 15
- Subtraction a-b 5
Operator Description Example (a = 10, b = 5) Result
* Multiplication a*b 50
/ Division a/b 2
% Modulus (Remainder) a%b 0
2. Relational (Comparison) Operators
Used to compare two values, returning a boolean (true or false).
Operator Description Example Result
== Equal to a == b false
!= Not equal to a != b true
> Greater than a>b true
< Less than a<b false
>= Greater than or equal a >= b true
<= Less than or equal a <= b false
3. Logical Operators (used with boolean values)
OperatorName Description Example
&& Logical AND True if both conditions are true (a > 0 && b > 0) → true
|| True if any one of the conditions is true (a > 0 || b > 0) → true
Logical OR
! Logical NOT Reverses the boolean result !(a > b) → true if a < b
Note: && and || use short-circuit evaluation:
A || B: If A is true, B is not evaluated.
A && B: If A is false, B is not evaluated.
4. Bitwise Operators (used with integer types for binary operations)
OperatorName Description Example (a = 5, b = 3) Result
a & b = 0101 & 0011 =
& AND 1 if both bits are 1
0001 → 1
| OR 1 if at least one bit is 1 `a
1 if any one of bit is 1
a ^ b = 0101 ^ 0011 = 0110
^ XOR 1 if bits are different
→6
~ NOT Inverts bits ~a = ~0101 = 1010
Shifts bits to the left (×2 per
<< Left shift a << 1 = 1010 = 10
shift)
Shifts bits to the right (÷2 per
>> Right shift a >> 1 = 0010 = 2
shift)
Unsigned right
>>> Same as >> but fills left with 0 a >>> 1
shift
5. Assignment Operators
Used to assign values or update a variable using an operation.
Operator Example Meaning
= a=b Assign b to a
+= a += b a=a+b
-= a -= b a=a-b
*= a *= b a=a*b
/= a /= b a=a/b
%= a %= b a=a%b
&= a &= b a=a&b
` =` `a
^= a ^= b a=a^b
Operator Example Meaning
<<= a <<= b a = a << b
>>= a >>= b a = a >> b
>>>= a >>>= b a = a >>> b
6. Unary Operators
Operate on a single operand.
Operator Description Example
+ Unary plus +a
- Unary minus -a
++ Increment (prefix or postfix) ++a, a++
-- Decrement (prefix or postfix) --a, a--
! Logical NOT !true → false
~ Bitwise NOT ~a
7. Ternary Operator
A short-hand for if-else.
int max = (a > b) ? a : b;
This means:
If a > b → max = a, else → max = b.
8. Type Comparison Operator
Operator Description Example
instanceof Checks object type s instanceof String → true
9. Other Special Operators
Operator Description
. Member access (dot)
[] Array access
() Method call
new Object creation
:: Method reference (Java 8+)
Sample Code to Demonstrate Key Operators
public class OperatorDemo {
public static void main(String[] args) {
int a = 10, b = 5;
// Arithmetic
System.out.println("Addition: " + (a + b));
// Relational
System.out.println("a > b: " + (a > b));
// Logical
System.out.println("Logical OR: " + (a > 0 || b < 0));
// Bitwise
System.out.println("Bitwise OR: " + (a | b));
System.out.println("Bitwise XOR: " + (a ^ b));
// Assignment
a += 3;
System.out.println("After a += 3: " + a);
// Ternary
int max = (a > b) ? a : b;
System.out.println("Max = " + max);
}
}
Operator Precedence in Java
Operator precedence determines the order in which operators are evaluated in expressions.
Operators with higher precedence are evaluated before operators with lower precedence. If
operators have the same precedence, their associativity (left-to-right or right-to-left) determines
the order.
Table of Java Operator Precedence and Associativity
Precedence Level Operators Description Associativity
1 (Highest) () Parentheses (grouping) Left to right
[], ., obj.method(), a[i], x.y Array/member access, method call Left to right
2 ++, --, + (unary), - (unary), ~, ! Unary operators Right to left
3 *, /, % Multiplicative Left to right
4 +, - Additive Left to right
5 <<, >>, >>> Bitwise shift Left to right
6 <, <=, >, >=, instanceof Relational Left to right
7 ==, != Equality Left to right
8 & Bitwise AND Left to right
9 ^ Bitwise XOR Left to right
10 ` ` Bitwise OR
11 && Logical AND Left to right
Precedence Level Operators Description Associativity
12 ` `
13 ?: Ternary conditional Right to left
14 =, +=, -=, *=, /=, %= Assignment and compound assignment Right to left
&=, ` =, ^=, <<=, >>=, >>>=`
15 (Lowest) ->, :: Lambda expressions, method reference
Example Illustrating Precedence
int a = 10, b = 5, c = 2;
int result = a + b * c; // result = 10 + (5 * 2) = 20
Multiplication (*) has higher precedence than addition (+), so it's done first.
Using Parentheses for Clarity
To override precedence and make expressions easier to read, use parentheses:
int result = (a + b) * c; // Now result = (10 + 5) * 2 = 30
Logical Precedence Example
boolean res = true || false && false;
// AND has higher precedence → evaluated as: true || (false && false) → true
Control Statements in Java
In Java, control statements are used to alter the flow of execution in a program. They help
in decision-making, looping, and branching. Here's a complete overview:
Types of Control Statements in Java
Java control statements are mainly classified into:
1. Decision-Making Statements
2. Looping (Iteration) Statements
3. Branching Statements
1.Decision-Making Statements
a) if Statement
int num = 10;
if (num > 0) {
System.out.println("Positive number");
}
b) if-else Statement
int num = -5;
if (num > 0) {
System.out.println("Positive");
} else {
System.out.println("Negative or Zero");
}
c) if-else-if Ladder
int score = 85;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 75) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}
d) switch Statement
int day = 3;
switch(day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Other day");
}
2. Looping (Iteration) Statements
a) for Loop
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
b) while Loop
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
c) do-while Loop
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
d) Enhanced for-each Loop (used with arrays/collections)
int[] nums = {10, 20, 30};
for (int n : nums) {
System.out.println(n);
}
3. Branching Statements
a) break
Used to exit a loop or switch early.
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
System.out.println(i);
}
b) continue
Skips the current iteration and goes to the next.
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
c) return
Exits from the method and optionally returns a value.
public static int square(int x) {
return x * x;
}
Example Programs using Control statements in Java
1. Check if a Number is Even or Odd
Problem: Read a number and check whether it is even or odd.
import java.util.Scanner;
public class EvenOddCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (num % 2 == 0)
System.out.println(num + " is Even.");
else
System.out.println(num + " is Odd.");
}
}
2. Find the Largest of Three Numbers
Problem: Take three numbers as input and find the largest among them.
import java.util.Scanner;
public class LargestOfThree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
if (a >= b && a >= c)
System.out.println("Largest: " + a);
else if (b >= a && b >= c)
System.out.println("Largest: " + b);
else
System.out.println("Largest: " + c);
}
}
3. Print Multiplication Table of a Number
Problem: Read a number and print its multiplication table up to 10.
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
for (int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
}
}
4. Sum of Digits of a Number
Problem: Read an integer and find the sum of its digits.
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of digits: " + sum);
}
}
5. Check Whether a Number is Prime
Problem: Read a number and check if it is a prime number.
import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
boolean isPrime = true;
if (num <= 1)
isPrime = false;
else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
System.out.println(num + " is a Prime Number.");
else
System.out.println(num + " is Not a Prime Number.");
}
}
Example Programs using Control statements in Java
1. Check if a Number is Even or Odd
Problem: Read a number and check whether it is even or odd.
import java.util.Scanner;
public class EvenOddCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (num % 2 == 0)
System.out.println(num + " is Even.");
else
System.out.println(num + " is Odd.");
}
}
2. Find the Largest of Three Numbers
Problem: Take three numbers as input and find the largest among them.
import java.util.Scanner;
public class LargestOfThree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
if (a >= b && a >= c)
System.out.println("Largest: " + a);
else if (b >= a && b >= c)
System.out.println("Largest: " + b);
else
System.out.println("Largest: " + c);
}
}
3. Print Multiplication Table of a Number
Problem: Read a number and print its multiplication table up to 10.
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
for (int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
}
}
4. Sum of Digits of a Number
Problem: Read an integer and find the sum of its digits.
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of digits: " + sum);
}
}
5. Check Whether a Number is Prime
Problem: Read a number and check if it is a prime number.
import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
boolean isPrime = true;
if (num <= 1)
isPrime = false;
else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
System.out.println(num + " is a Prime Number.");
else
System.out.println(num + " is Not a Prime Number.");
}
}
Functions in Java
In Java, functions (more correctly called methods) are blocks of code that perform a specific
task. They help in code reusability, modularity, and readability.
What is a Function/Method in Java?
A method in Java is a block of code that:
Has a name
Can take input (parameters)
May return a value
Is called (invoked) when needed
Syntax of a Method
returnType methodName(parameter1, parameter2, ...) {
// Method body
return value; // if returnType is not void
}
Types of Methods in Java
1. Predefined methods – like System.out.println(), Math.sqrt()
2. User-defined methods – you define these based on your requirements
Example 1: Method without Parameters and without Return Value
public class HelloWorld {
static void greet() {
System.out.println("Hello, welcome to Java!");
}
public static void main(String[] args) {
greet(); // Method call
}
}
Example 2: Method with Parameters
public class Calculator {
static void add(int a, int b) {
int sum = a + b;
System.out.println("Sum: " + sum);
}
public static void main(String[] args) {
add(5, 7); // Output: Sum: 12
}
}
Example 3: Method with Return Value
public class Square {
static int square(int num) {
return num * num;
}
public static void main(String[] args) {
int result = square(4);
System.out.println("Square: " + result);
}
}
Key Components of a Method
Component Description
returnType Type of value the method returns (e.g., int, void)
methodName Name of the method (should be meaningful)
parameters Input values (optional)
return Used to return value from method (if not void)
Method Overloading (Same name, different parameters)
public class OverloadExample {
static void greet() {
System.out.println("Hello!");
}
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
greet(); // Output: Hello!
greet("Alice"); // Output: Hello, Alice!
}
}
Recursive Functions in Java
Recursive Functions in Java
A recursive function is a method that calls itself to solve a problem.
Key Concepts
1. Base Case – condition to stop recursion
2. Recursive Case – where the method calls itself
Recursion breaks the problem into smaller subproblems until the base case is reached.
Example 1: Factorial of a Number
Problem: Calculate n! = n × (n-1) × (n-2) × ... × 1
public class Factorial {
static int factorial(int n) {
if (n == 0) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive call
}
public static void main(String[] args) {
int result = factorial(5);
System.out.println("Factorial of 5 is " + result);
}
}
Output:
Factorial of 5 is 120
Example 2: Fibonacci Series
Problem: Print nth Fibonacci number
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, ...
public class Fibonacci {
static int fibonacci(int n) {
if (n == 0) return 0; // Base case
if (n == 1) return 1; // Base case
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}
public static void main(String[] args) {
int n = 7;
System.out.println("Fibonacci(" + n + ") = " + fibonacci(n));
}
}
Output:
Fibonacci(7) = 13
Example 3: Sum of Digits
Problem: Find the sum of digits of a number using recursion
public class SumDigits {
static int sumOfDigits(int n) {
if (n == 0)
return 0;
return n % 10 + sumOfDigits(n / 10);
}
public static void main(String[] args) {
int num = 1234;
System.out.println("Sum of digits = " + sumOfDigits(num));
}
}
Output:
Sum of digits = 10
When to Use Recursion?
Use recursion when:
The problem is naturally recursive (e.g., factorial, tree traversal)
The solution involves repeated subproblems
A loop would make the solution more complex
Caution:
Recursive functions may cause StackOverflowError if the base case is missing or
recursion is too deep.
Use iteration for efficiency when possible.
Command line arguments and Variable length arguments
1. Command-Line Arguments in Java
Command-line arguments allow you to pass information to a Java program when it starts from
the terminal or command prompt.
Syntax:
public static void main(String[] args)
args is an array of String that holds the arguments.
Arguments are space-separated words passed when running the program.
Example: Program to Print Command-Line Arguments
public class CommandLineExample {
public static void main(String[] args) {
System.out.println("You passed " + args.length + " arguments.");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
How to Run:
javac CommandLineExample.java
java CommandLineExample Hello World 123
Output:
You passed 3 arguments.
Argument 0: Hello
Argument 1: World
Argument 2: 123
2. Variable-Length Arguments (Varargs) in Java
Java allows you to define methods that accept variable numbers of arguments using ....
Syntax:
methodName(datatype... varname)
Treated as an array inside the method.
Only one vararg is allowed per method, and it must be last in the parameter list.
Example: Method to Add Numbers
public class VarargsExample {
static int add(int... numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
public static void main(String[] args) {
System.out.println(add(10, 20)); // 30
System.out.println(add(5, 15, 25, 35)); // 80
System.out.println(add()); // 0
}
}
Differences Between Command-Line Arguments and Varargs
Feature Command-Line Arguments Varargs
Where used In main(String[] args) In any user-defined method
Source of data From user via terminal/command From method call inside program
Type Always String[] Any type (e.g., int..., String...)
Example Input java Program 1 2 3 method(1, 2, 3)
Classes and Objects in Java
Let's explore the fundamentals of object-oriented programming — Classes and Objects —
in Java, with clear explanations and code examples.
What is a Class in Java?
A class is a blueprint or template that defines the structure and behavior (data and methods)
that the objects created from it will have.
Think of a class as:
A design for creating objects.
It contains fields (variables) and methods (functions).
Syntax:
class ClassName {
// Fields (variables)
// Methods (functions)
}
What is an Object in Java?
An object is an instance of a class.
It represents a real-world entity.
Each object has its own state (fields) and can perform actions (methods).
Example:
If Car is a class, then myCar and yourCar are objects of that class.
Java Program: Creating and Using a Class and Object
// Define a class
class Student {
// Fields (data members)
String name;
int age;
// Method (behavior)
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Create an object of Student class
Student s1 = new Student();
// Set values
s1.name = "Anjali";
s1.age = 20;
// Call method
s1.displayDetails();
}
}
Output:
Name: Anjali
Age: 20
Key Terminologies
Term Description
class Keyword to define a class
new Keyword used to create an object
Constructor Special method used to initialize objects (explained below)
Dot operator . Used to access members of an object (e.g., object.method())
Constructor in Java
A constructor is a special method that is automatically called when an object is created.
🔹 Example:
class Student {
String name;
int age;
// Constructor
Student(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println(name + " is " + age + " years old.");
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Rahul", 21); // Object created with values
s1.display();
}
}
Output:
Rahul is 21 years old.
Access Modifiers in Java
Access modifiers control the visibility (accessibility) of classes, variables, constructors, and
methods in Java.
Types of Access Modifiers:
Modifier Class Package Subclass World
public ✅ ✅ ✅ ✅
protected ✅ ✅ ✅ ❌
(default)* ✅ ✅ ❌ ❌
Modifier Class Package Subclass World
private ✅ ❌ ❌ ❌
*default (no modifier) means package-private — accessible only within the same package.
Explanation with Examples:
public: Accessible everywhere
public class MyClass {
public int value = 10;
public void show() {
System.out.println("Public Method");
}
}
private: Accessible only within the class
class MyClass {
private int secret = 123;
private void showSecret() {
System.out.println("Secret: " + secret);
}
public void access() {
showSecret(); // OK: accessed within class
}
}
protected: Accessible within same package and subclasses
class Parent {
protected void greet() {
System.out.println("Hello from parent!");
}
}
class Child extends Parent {
void sayHi() {
greet(); // OK
}
}
Default (no modifier): Accessible only in same package
class MyClass {
void defaultMethod() {
System.out.println("Package-private method");
}
}
this Keyword in Java
The this keyword is a reference to the current object — the object whose method or
constructor is being called.
Common Uses of this:
1. Distinguish instance variables from parameters
class Student {
String name;
// Constructor
Student(String name) {
this.name = name; // this.name refers to instance variable
}
void printName() {
System.out.println("Name: " + this.name);
}
}
2. Call another constructor (Constructor Chaining)
class Book {
String title;
int pages;
// Constructor with one parameter
Book(String title) {
this(title, 0); // Call another constructor
}
// Constructor with two parameters
Book(String title, int pages) {
this.title = title;
this.pages = pages;
}
void display() {
System.out.println(title + " - " + pages + " pages");
}
}
3. Return current object
class Demo {
Demo getObject() {
return this;
}
}
Data Abstraction
Data Abstraction is the process of hiding internal implementation details and showing only
the essential features of an object.
Purpose:
To reduce complexity.
To focus only on what an object does rather than how it does it.
Example of Data Abstraction:
abstract class Animal {
abstract void makeSound(); // abstract method - no implementation
}
class Dog extends Animal {
void makeSound() {
System.out.println("Barks");
}
}
class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.makeSound(); // Output: Barks
}
}
Explanation:
Animal is an abstract class.
makeSound() is an abstract method: only its signature is visible.
The actual implementation is hidden in the subclass (Dog).
The user (main program) only cares about the method being called, not its internal logic.
Ways to Achieve Abstraction in Java:
Technique Description
Abstract
Contains abstract methods that subclasses must implement.
Class
Define what a class must do but not how. (All methods are implicitly
Interfaces
abstract unless using default/static.)
Encapsulation
Encapsulation is the concept of binding data and methods that operate on that data into a
single unit (class) and restricting direct access to some of the object's components.
Purpose:
To protect data from unauthorized access.
To allow controlled access through getters and setters.
Example of Encapsulation:
class BankAccount {
private double balance; // private field (cannot be accessed directly)
// Constructor
BankAccount(double initialBalance) {
balance = initialBalance;
}
// Getter
public double getBalance() {
return balance;
}
// Setter with condition
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}
Explanation:
The field balance is private.
Access is only allowed via public methods like getBalance() and deposit().
This is encapsulation — data is protected from external modification.
Comparison Between Abstraction and Encapsulation
Feature Data Abstraction Encapsulation
Focus What an object does How data is hidden and accessed
Hides Implementation details Internal data using access modifiers
Achieved by Abstract classes and interfaces Classes, access modifiers, getters/setters
Goal Reduce complexity Protect data and ensure safety
Real-world Analogy
Concept Real-life Example
Using a TV remote – you press buttons (what it does), but don’t know
Abstraction
how circuits inside work.
A capsule (medicine) – the ingredients (data) are hidden inside, but you
Encapsulation
consume it as a whole.
Summary
Abstraction = Hiding internal implementation and showing only essential behavior.
Encapsulation = Hiding internal data and providing controlled access through methods.
INHERITANCE in Java
Definition:
Inheritance is the mechanism in Java by which one class acquires the properties and
behaviors (fields and methods) of another class.
The class that inherits is called the subclass (or child class).
The class from which it inherits is the superclass (or parent class).
Syntax:
class SuperClass {
// fields and methods
}
class SubClass extends SuperClass {
// additional fields and methods
}
Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // Inherited method
d.bark(); // Own method
}
}
Output:
This animal eats food.
The dog barks.
Types of Inheritance in Java:
Type Supported in Java? Example
Single Inheritance Yes class B extends A
Multilevel Yes A→B→C
Hierarchical Yes A → B, A → C
Multiple Inheritance (via classes) via interfaces class C implements A, B
POLYMORPHISM in Java
Definition:
Polymorphism means “many forms”. In Java, it allows objects to behave differently based on
the context, even if they share the same interface or method name.
There are two types:
1. Compile-time Polymorphism (Method Overloading)
Same method name with different parameters (type or number).
Resolved at compile time.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(2, 3)); // 5
System.out.println(c.add(2.5, 3.5)); // 6.0
}
}
2. Runtime Polymorphism (Method Overriding)
Same method name and signature in both superclass and subclass.
Resolved at runtime using dynamic method dispatch.
Example:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a;
a = new Dog(); a.sound(); // Bark
a = new Cat(); a.sound(); // Meow
}
}
Differences Between Inheritance and Polymorphism
Feature Inheritance Polymorphism
Meaning Reuse code from parent class Same method behaves differently
Type Is-a relationship Many forms
Use Code reuse Flexibility and dynamic behavior
Achieved by extends keyword Overloading & Overriding
Real-World Analogy
Concept Example
Inheritance A car is a type of vehicle — it inherits basic features like wheels, engine.
A remote control works for TV, AC, or fan — the button is the same,
Polymorphism
but the result differs.
Summary
Inheritance:
Enables code reuse.
Subclass inherits fields and methods from the superclass.
Polymorphism:
Enables flexibility.
Same method name can behave differently (overloading/overriding).