Java Module1
Java Module1
• Java is an Object-Oriented Programming language that helps develop software that is:
Ø Reusable
Ø Secure
Ø Easy to maintain
Ø Easy to understand
Why OOP?
• Without proper organization, the program becomes difficult to manage. OOP helps organize data and
functions efficiently.
Basic Concepts of OOP
1. Class 2. Object
• A class is a blueprint used to create objects. • An object is an instance of a class.
Example Example
Class Object
Output
add(2,3) = 5
add(2,3,4) = 9
Method Overriding
Example
class Animal {
void sound() {
[Link]("Animal Sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog Barks");
}
}
Output
Dog Barks
6. Abstraction
Abstraction means hiding implementation details Example
and showing only necessary information.
abstract class Vehicle {
Real-Life Example abstract void start();
}
• Driving a car. class Car extends Vehicle {
void start() {
• You know: [Link]("Car Started");
}
Ø Brake }
Ø Accelerator
Ø Steering
Advantages
• You don't need to know how the engine works • Reduces complexity
internally. • Improves security
• Easy maintenance
Constructor
Example
class Student {
String name;
Student(String n) {
name = n;
}
}
Real-Life Example
Example Example
White
History of Java
• Java is a high-level, object-oriented, platform-independent programming language developed to
create applications that can run on different operating systems without modification.
• Before Java, programs were generally written for a specific operating system.
For example:
v A program written for Windows could not run directly on Linux.
v A program written for Linux could not run directly on Mac OS.
• There was a need for a language that could run on multiple platforms without rewriting the code.
Origin of Java
• In 1991, a team at Sun Microsystems started a project called the Green Project.
Team Members
Ø James Gosling
Ø Mike Sheridan
Ø Patrick Naughton
• Their goal was to create software for electronic devices such as:
• The language was initially named Oak because there was an oak tree outside James Gosling's office.
Meaning:
Ø Since then, Oracle has been responsible for java development, updates, and releases.
Sl. No. Version Release Date Description
1 JDK Alpha 1995 First internal testing version of Java.
2 JDK Beta 1995 Beta version released for public testing.
First official Java release. Introduced "Write Once,
3 JDK 1.0 January 1996
Run Anywhere".
4 JDK 1.1 February 1997 Added JDBC, RMI, and event handling.
5 JDK 1.2 (Java 2) December 1998 Introduced Swing GUI and Collections Framework.
14 JDK 11 (LTS) September 2018 Long-Term Support version; added HTTP Client API.
20 JDK 17 (LTS) September 2021 Long-Term Support version; sealed classes added.
Sl. No. Version Release Date Description
21 JDK 18 March 2022 Improved UTF-8 and internet addressing.
22 JDK 19 September 2022 Added Virtual Threads (preview).
23 JDK 20 March 2023 Performance and concurrency improvements.
24 JDK 21 (LTS) September 2023 Virtual Threads, Pattern Matching, Record Patterns.
• JVM (Java Virtual Machine) is a virtual machine that executes Java bytecode and enables Java
programs to run on different operating systems.
[Link]
↓
Java Compiler (javac)
↓
[Link]
What is Bytecode?
Example:
[Link]
Step 3: JVM Execution
After compilation:
[Link]
↓
JVM
↓
Operating System
The JVM reads the bytecode and converts it into machine code that the computer understands.
Output
Hello Java
Without JVM:
Java Program → Opera ng System
With JVM:
Java Program
↓
Bytecode
↓
JVM
↓
Operating System
Function
• The Class Loader loads the .class files into JVM memory.
Responsibilities
Real-Life Example
• A librarian brings the required book from the library before you can read it.
• Similarly, the Class Loader brings the required class into memory.
2. JVM Memory Area
• JVM memory is divided into five parts.
A) Method Area
Function
Stores:
• Class information
• Method information
• Static variables
Real-Life Example
Example
• A school notice board containing common
class Student { information for all students.
static int count = 0;
}
Function
Components
Real-Life Example
A) Interpreter
Interpreter:
• Reads bytecode line by line.
• Reading and translating a sentence word by word.
• Executes instructions one at a time.
JIT Compiler:
B) JIT Compiler (Just-In-Time Compiler)
• Translating the whole paragraph at once for faster
• Converts bytecode into machine code. understanding.
Step 1
• Java source code is compiled: Step 4
Step 2 JNI
• Class Loader loads the .class file. ↓
Native Libraries
Step 3
Step 6
• Memory is allocated in:
• Output is displayed.
* Method Area *Heap *Stack
Eg
1. String
Example
String name = "Manu";
Example
class Main {
public static void main(String[] args) {
String name = "Manu";
[Link](name);
[Link]([Link]());
[Link]([Link]());
}
}
Output
Manu
4
MANU
2. Array
Example
class Main{
public static void main(String[] args){
[Link](arr[3] + "\n"); 12
[Link](arr[0] + "\n"); 2
arr[1] = 90; 90
[Link](arr[1]);
}
}
Example
3. Class
class Student {
• A Class is a blueprint used to create objects. String name = "John";
void display() {
Example [Link]("Name: " + name);
}
class Student { }
String name; public class Main {
} public static void main(String[] args) {
Example
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
[Link]("Bark");
}
}
Real-Life Example
A remote control.
• Remote → Interface
• TV → Implements Remote
The remote defines buttons, and the TV performs the actions.
Variables
Syntax Example
datatype variableName = value; int age = 20;
• print(): Displays output without moving the cursor to the next line.
• println(): Displays output and moves the cursor to the next line.
Eg:
int a = 10, b = 5;
Operator Meaning
[Link](a > b);
== Equal to [Link](a < b);
[Link](a == b);
!= Not equal [Link](a != b);
}
> Greater than }
< Less than
Output
>= Greater than or equal
true
<= Less than or equal false
false
true
3. Logical Operators
true
false
true
4. Assignment Operators Example
-= x-=5 x *= 2;
[Link](x);
*= x*=5 }
}
/= x/=5
Output
15
12
24
5. Increment Operator (++) 6. Decrement Operator (--)
Example Example
int x = 5; int x = 5;
x++; x--;
[Link](x); [Link](x);
} }
} }
Output Output
6 4
7. Bitwise Operators
Example
[Link](result);
}
}
Output
Eligible
Expressions
• An expression is a combination of variables, constants, and operators that produces a value.
Example
Eg:
1. if Statement
Example
Example
Example
int day = 1;
switch(day)
{
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
default:
[Link]("Invalid");
}
II. Looping Statements 2. while Loop
1. for Loop • Executes a block of code as long as the condition is
true.
Used when the number of iterations is known.
Example
Example
int i = 1;
for(int i=1;i<=5;i++) while(i <= 5)
{ {
[Link](i); [Link](i);
} i++;
}
Output
Output
1
2 1
3 2
4 3
5 4
5
3. do-while Loop
Example
int i = 1;
do
{
[Link](i);
i++;
}
while(i <= 5);
Output
1
2
3
4
5
III. Jump Statements
2. continue
1. break Used to skip the current iteration and continue with
the next iteration of a loop.
Used to immediately terminate a loop or switch
statement. Example
Example
for(int i=1;i<=5;i++)
{
for(int i=1;i<=5;i++)
if(i==3)
{
continue;
if(i==3)
[Link](i);
break;
}
[Link](i);
}
Output
Output
1
2
1
4
2
5
Arrays in Java
• An Array is a collection of elements of the same data type stored under a single variable name.
Why Arrays?
Without Array:
With Array:
int sum = 0;
for(int i=0;i<[Link];i++) {
sum += arr[i];
}
Output
Sum = 150
Multi-Dimensional Array
• An array containing another array is called a
multidimensional array.
for(int i=0;i<2;i++) {
for(int j=0;j<2;j++) {
[Link](arr[i][j] + " ");
}
[Link]();
}
}
}
Program – Addition of Two Matrices
Example
Creating Strings
Method 1
Method 2
1. length()
Example
2. toUpperCase()
• Converts to uppercase.
Example
Output
String name = "Rone";
RONE
[Link]([Link]());
3. toLowerCase()
• Converts to lowercase.
Example
4. charAt()
Example
Output
String name = "Jack";
c
[Link]([Link](2));
5. concat()
Example
String a = "Hello";
String b = "Java"; Output
[Link]([Link](" " + b)); Hello Java
6. equals()
Example
String s1 = "Java";
Output
String s2 = "Java";
true
[Link]([Link](s2));
7. contains()
Example
8. substring()
Example
[Link]([Link]()); 5
[Link]([Link]()); JAMES
[Link]([Link]()); james
[Link]([Link](0)); J
[Link]([Link](" " + lastname)); James Gosling
[Link]([Link](lastname)); false
[Link]([Link]("Jame")); true
[Link]([Link](0,3)); Gos
}
}
Scanner Class
• The Scanner class is used to take input from the user through the keyboard.
Package
import [Link];
Why Scanner?
Without Scanner:
• Value is fixed.
With Scanner:
Enter Age: 21
Output
Enter Age: 21
Age = 21
Reading Different Types of Data
String
String name = [Link](); Common Scanner Methods
Integer
int age = [Link]();
Method Purpose
Float
next() Reads one word
float mark = [Link]();
nextLine() Reads entire line
Double
double salary = [Link](); nextInt() Reads integer
import [Link];
Output
public class StudentDemo {
public static void main(String[] args) { Enter Name: Mary
Enter Age: 21
Scanner sc = new Scanner([Link]);
Name: Mary
[Link]("Enter Name: "); Age: 21
String name = [Link]();
Also called:
Ø Implicit Conversion
Ø Automatic Conversion
Ø Widening Conversion
Example
Also called:
Ø Explicit Conversion
Ø Narrowing Conversion
Why Needed?
Syntax
datatype variable = (datatype)value;
Example
double d = 10.75;
int num = (int)d;
Program
Automatic Manual
Widening Narrowing
Program
import [Link];
Output
public class CombinedDemo {
public static void main(String[] args) { Enter Integer: 25
Converted to Double: 25.0
Scanner sc = new Scanner([Link]); After Casting: 25
double d = num;
Real-Life Example
House Blueprint
Blueprint → Class
Actual House → Object
Components of a Class
Real-Life Example
Class → Student
Syntax Example
ClassName objectName = new ClassName();
[Link] = "John";
Example [Link] = 20;
Student s = new Student(); [Link]();
Program: Class and Object
class Student {
String name;
int age;
Output
void display() {
[Link]("Name: " + name);
Name: Manu
[Link]("Age: " + age);
Age: 21
}
}
class Student {
String name;
void display() { Output
[Link](name);
} Nandhu
} Shidu
public class Main {
public static void main(String[] args) {
[Link] = "Nandhu";
[Link] = "Shidu";
[Link]();
[Link]();
}
}
Access Modifiers
• Access Modifiers control the visibility and accessibility of classes, variables, and methods.
1. Public
Example
public class Student { Real-Life Example
public String name;
public void display() { • College notice board.
[Link](name); • Everyone can see it.
}
}
2. Private Example
• Accessible only within the same class. class Student {
Example private int age = 21;
void display() {
class Student { [Link](age);
}
private int age; }
}
public class Main {
Real-Life Example public static void main(String[] args) {
Output
21
3. Protected
4. Default (No Modifier)
Accessible:
• If no modifier is specified.
• Within the same package
class Student {
• By subclasses in other packages
String name;
Example }
class Student {
public String name = "Aiswarya";
private int age = 21;
protected String course = "BCA";
String college = "YIMS";
public void showAge() {
[Link]("Age: " + age);
}
}
public class Main {
public static void main(String[] args) { Output
Student s = new Student();
[Link]("Name: " + [Link]); Name: Aiswarya
[Link]("Course: " + [Link]); Course: BCA
[Link]("College: " + [Link]); College: YIMS
[Link](); Age: 21
}
}
Constructors and Inheritance in Java
Constructor
• A constructor is a special member of a class that is automatically called when an object is created.
Characteristics
Why Constructor?
Mobile Purchased
↓
Initial Setup Happens Automatically
Similarly:
Program
class Student {
Student() {
[Link]("Student Object Created");
} Explanation
}
public class Main { Student s = new Student();
public static void main(String[] args) {
Student s = new Student(); When this statement executes:
}
} Ø Memory is allocated.
Program
class Student {
Student(String name) {
[Link]("Student Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Negha");
}
}
Output
Student Name: Negha
Program
class Student {
Student() {
[Link]("Default Constructor");
}
Student(String name) {
[Link]("Name: " + name);
}
}
Output
public class Main {
public static void main(String[] args) {
Default Constructor
Student s1 = new Student();
Name: Aswajith
Student s2 = new Student("Aswajith");
}
}
Inheritance
• Inheritance is the process by which one class acquires the properties and methods of another class.
extends Keyword
Syntax
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
}
}
Output
public class Main {
public static void main(String[] args) {
Animal makes sound
Dog d = new Dog();
Dog barks
[Link]();
[Link]();
}
}
Types of Inheritance
Program
1. Single Inheritance
class Animal {
• One child inherits one parent.
void eat() {
[Link]("Eating...");
Animal
}
↓
}
Dog
class Dog extends Animal {
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
Output
Eating...
2. Multilevel Inheritance
class Puppy extends Dog {
• Inheritance chain. void weep() {
[Link]("Weeping");
Animal }
↓ }
Dog public class Main {
↓ public static void main(String[] args) {
Puppy Puppy p = new Puppy();
[Link]();
Program [Link]();
[Link]();
class Animal { }
void eat() { }
[Link]("Eating");
} Output
}
class Dog extends Animal { Eating
void bark() { Barking
[Link]("Barking"); Weeping
}
}
3. Hierarchical Inheritance class Cat extends Animal {
void meow() {
• One parent, multiple children. [Link]("Meowing");
}
Animal }
/ \ public class Main {
Dog Cat public static void main(String[] args) {
Dog d = new Dog();
Program Cat c = new Cat();
[Link]();
class Animal { [Link]();
void eat() { [Link]();
[Link]("Eating"); [Link]();
} }
} }
class Dog extends Animal {
void bark() { Output
[Link]("Barking"); Eating
} Barking
} Eating
Meowing
super Keyword
• super refers to the immediate parent class object.
class Animal {
Animal() {
[Link]("Parent Constructor");
}
}
class Dog extends Animal {
Dog() { Output
super();
[Link]("Child Constructor"); Parent Constructor
} Child Constructor
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
}
}
this Keyword
• this refers to the current object.
class Student {
String name;
Student(String name) {
name = name;
}
}
• Java gets confused because both variables have the same name.
Solution Using this
class Student {
String name; Output
Student(String name) {
[Link] = name; Anjo
}
void display() { Explanation
[Link](name);
} • [Link] → Class variable
} • name → Constructor parameter
public class Main {
public static void main(String[] args) {
Student s = new Student("Anjo");
[Link]();
}
}
final Keyword
• The final keyword restricts modification.
Final Variable
[Link](AGE);
}
}
Output
21
If you write:
Compilation Error
So:
class Animal {
final void sound() {
[Link]("Animal Sound");
}
}
Final Class
Output
Compilation Error
• In Java, the same method name can behave differently in different situations.
Types of Polymorphism
Method Overloading
• Method Overloading is the process of defining multiple methods with the same name but different
parameters.
Think of a calculator.
add(10,20)
add(10,20,30)
add(10.5,20.5)
• Number of parameters
• Type of parameters
• Order of parameters
Program 1: Different Number of Parameters Program 2: Different Data Types
Output Output
Sum = 30 Integer: 10
Sum = 60 Double: 10.5
Method Overriding
• Method Overriding is redefining a parent class method in the child class with the same method name
and parameters.
Real-Life Example
Rules for Method Overriding
Animal → Sound
Dog → Bark
• Inheritance is required.
Cat → Meow
• Method name must be the same.
• Each animal produces a different sound.
• Parameters must be the same.
• Return type should be the same or compatible.
Program: Method Overriding
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
Output
Dog barks
class Animal {
void sound() {
[Link]("Animal Sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Animal();
Output
Dog d = new Dog();
[Link]();
Animal Sound
[Link]();
Dog Bark
}
}
Dynamic Method Dispatch
• Dynamic Method Dispatch is a mechanism where a parent class reference refers to a child class
object and the overridden method is called at runtime.
Syntax
Real-Life Example
Think of a TV remote.
Remote → Reference
TV → Object
• The remote controls different TVs, but the actual TV decides what action occurs.
Program: Dynamic Method Dispatch
Explanation
class Animal {
void sound() { Animal a = new Dog();
[Link]("Animal Sound");
} Reference --> Animal
} Object --> Dog
class Dog extends Animal {
void sound() { • At runtime, Java checks the actual object
[Link]("Dog Bark"); type (Dog)
}
} • so: [Link](); calls: Dog's sound()
public class Main { not Animal's sound().
public static void main(String[] args) {
Animal a = new Dog();
[Link]();
}
}
Output
Dog Bark
Interface
• An Interface is a blueprint of a class that contains abstract methods (and constants). It specifies what
a class should do, but not how to do it.
Syntax
interface Animal{
void sound();
}
Rules of Interface
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
[Link]("Dog Barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
Output
Dog Barks
Program 2: Multiple Classes Implementing Same Interface
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
[Link]("Dog Barks");
}
}
class Cat implements Animal {
public void sound() {
[Link]("Cat Meows");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
Cat c = new Cat(); Output
[Link]();
[Link](); Dog Barks
} Cat Meows
}
Abstract Class
• An Abstract Class is a class declared using the abstract keyword. It may contain both abstract
methods and normal methods.
• When some methods have a common implementation and some methods need different
implementations.
Real-Life Example
Rules of Abstract Class
Think of a Vehicle. • Cannot create objects.
• Can have abstract and normal methods.
Vehicle
↓ • Uses the extends keyword.
Car
Bike
Bus
• Every vehicle has a start() method, but each vehicle starts differently.
Program 1: Abstract Class
Output
Car Started
Program 2: Abstract Method + Normal Method
Types of Packages
1. Built-in Package
• Provided by Java.
• Examples: [Link], [Link], [Link], [Link]
2. User-defined Package
• Created by the programmer.
Creating a Package
File: [Link]
package college;
public class Student {
public void display() {
[Link]("Welcome to Package");
}
}
File: [Link]
import [Link];
public class Main {
public static void main(String[] args) { Output
Student s = new Student();
[Link](); Welcome to Package
}
}
Common Built-in Packages
Package Purpose
Constructors No Yes No
Contains
Methods Abstract by default Abstract + Normal
classes/interfaces