0% found this document useful (0 votes)
3 views122 pages

Java Module1

The document provides an overview of Object-Oriented Programming (OOP) in Java, explaining its key concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It also covers the history and evolution of Java, including its development, public releases, and the significance of the Java Virtual Machine (JVM) in enabling platform independence. Additionally, it discusses data types in Java, differentiating between primitive and non-primitive types.

Uploaded by

apnodtest
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)
3 views122 pages

Java Module1

The document provides an overview of Object-Oriented Programming (OOP) in Java, explaining its key concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It also covers the history and evolution of Java, including its development, public releases, and the significance of the Java Virtual Machine (JVM) in enabling platform independence. Additionally, it discusses data types in Java, differentiating between primitive and non-primitive types.

Uploaded by

apnodtest
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

Overview of OOPs in Java

• OOP (Object-Oriented Programming) is a programming approach that organizes programs using


objects and classes.

• Java is an Object-Oriented Programming language that helps develop software that is:
Ø Reusable
Ø Secure
Ø Easy to maintain
Ø Easy to understand

Why OOP?

• Imagine managing a college manually:


Ø Student details
Ø Teacher details
Ø Course details

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

Real-Life Example Real-Life Example

• Blueprint of a house. • Actual house built from a blueprint.

Example Example

class Student { Student s1 = new Student();


String name;
int age; • s1 is an object.
}

• Here, Student is a class.


Difference Between Class and Object

Class Object

Blueprint Real entity

No memory allocated Memory allocated

Template Instance of class


3. Encapsulation
• Encapsulation means wrapping data and methods together into a single unit and protecting data
from direct access.
Example
Real-Life Example
class BankAccount {
ATM Machine
private int balance = 5000;
public int getBalance() {
You cannot directly access your account balance.
return balance;
You use ATM options like:
}
}
Withdraw
public class Main {
Deposit
public static void main(String[] args) {
Check balance
BankAccount b = new BankAccount();
[Link]([Link]());
The data remains protected.
}
}
4. Inheritance
• Inheritance allows one class to inherit properties and methods from another class.

Real-Life Example Usage

• Child inherits characteristics from parents. Dog d = new Dog();


[Link]();
Example [Link]();

class Animal { Output


void eat() {
[Link]("Eating"); Eating
} Barking
}
class Dog extends Animal { Advantages
void bark() {
[Link]("Barking"); • Code Reusability
} • Less Coding
} • Easier Maintenance
5. Polymorphism
Method Overloading
• Polymorphism means "One Name, Many Forms."
• Same method name with different parameters.
Real-Life Example
Example
A person can act as:
class Calculator {
• Student in college int add(int a, int b) {
• Daughter/Son at home return a + b;
• Employee at work }
int add(int a, int b, int c) {
Same person, different roles. return a + b + c;
}
}

Output

add(2,3) = 5
add(2,3,4) = 9
Method Overriding

• Child class changes parent class method.

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

• A constructor is a special method used to initialize objects.

Example

class Student {

String name;

Student(String n) {
name = n;
}
}

Real-Life Example

• When a student joins a college, details are entered immediately.


this Keyword super Keyword

• Refers to the current object. • Refers to the parent class.

Example Example

class Student { class Animal {


String color = "White";
String name; }

Student(String name) { class Dog extends Animal {


[Link] = name;
} void display() {
} [Link]([Link]);
}
Real-Life Example }

"This book is mine." Output

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.

• Java is a programming language and computing platform used for developing:


Ø Desktop Applications
Ø Web Applications
Ø Mobile Applications
Ø Enterprise Software
Ø Cloud Applications

Why was Java Developed?

• 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

The Green Project

• In 1991, a team at Sun Microsystems started a project called the Green Project.

Team Members

• The project was led by:

Ø James Gosling
Ø Mike Sheridan
Ø Patrick Naughton

• Their goal was to create software for electronic devices such as:

Ø Television set-top boxes


Ø Home appliances
Ø Embedded systems
From Oak to Java

First Name: Oak

• The language was initially named Oak because there was an oak tree outside James Gosling's office.

• However, another company had already registered the name "Oak."

• Therefore, a new name was needed.

• Final Name: Java

• The team selected the name Java, inspired by Java coffee.

• Thus, Oak became Java.


First Public Release

• Java was officially released in 1995 by Sun Microsystems.

• Its slogan became:

"Write Once, Run Anywhere (WORA)"

Meaning:

• Write the program once.

• Run it on any platform supporting Java.

Ø In 2010, Oracle corporation acquired Sun Microsystems

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

6 JDK 1.3 May 2000 Improved performance and reliability.


7 JDK 1.4 February 2002 Added Assertions, NIO, and XML support.
Added Generics, Enhanced for-loop, Autoboxing,
8 JDK 5.0 September 2004
Annotations.

9 JDK 6 December 2006 Improved performance and web services support.

10 JDK 7 July 2011 Added Try-with-Resources and Diamond Operator.


Sl. No. Version Release Date Description
11 JDK 8 March 2014 Added Lambda Expressions and Stream API.
12 JDK 9 September 2017 Introduced Module System (Project Jigsaw).

13 JDK 10 March 2018 Introduced Local Variable Type Inference (var).

14 JDK 11 (LTS) September 2018 Long-Term Support version; added HTTP Client API.

15 JDK 12 March 2019 Added switch expression preview.


16 JDK 13 September 2019 Improved text blocks (preview).

17 JDK 14 March 2020 Added Records (preview) and pattern matching.

18 JDK 15 September 2020 Added Text Blocks and hidden classes.


19 JDK 16 March 2021 Records became standard feature.

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.

25 JDK 22 March 2024 Language and performance enhancements.


26 JDK 23 September 2024 Further improvements and preview features.

27 JDK 24 March 2025 Performance and developer productivity updates.

28 JDK 25 (LTS) September 2025 Current Long-Term Support release.

29 JDK 26 March 2026 Current latest Java release.


Java Virtual Machine (JVM)
• When we write and run a Java program , the program does not directly communicate with the
operating system. Instead, it is executed through the Java Virtual Machine (JVM).

• JVM (Java Virtual Machine) is a virtual machine that executes Java bytecode and enables Java
programs to run on different operating systems.

Program Execution in NetBeans

Consider the following Java program:

public class Hello {


public static void main(String[] args) {
[Link]("Hello Java");
}
}

Step 1: Writing the Program


The programmer writes the code in NetBeans.
File:[Link]
Step 2: Compilation

• When you click Run (or press Shift + F6) in NetBeans:

[Link]

Java Compiler (javac)

[Link]

• The Java compiler converts the source code into bytecode.

What is Bytecode?

• Bytecode is an intermediate code stored in a .class file.

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

appears in the NetBeans Output Window.


Why JVM is Important

Without JVM:
Java Program → Opera ng System

• Different operating systems would require different versions of the program.

With JVM:
Java Program

Bytecode

JVM

Operating System

• The same program can run on:


Ø Windows
Ø Linux
Ø macOS
• This is called: Write Once, Run Anywhere (WORA)
JVM Architecture
1. Class Loader

Function

• The Class Loader loads the .class files into JVM memory.

Responsibilities

• Loads class files


• Verifies bytecode
• Allocates memory for classes

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;
}

• The static variable count is stored in the Method Area.


C) Stack Area
B) Heap Area
Function
Function
Stores:
• Stores all objects created during program
Ø Local variables
execution.
Ø Method calls
Example
• Each thread has its own stack.
Student s = new Student();
Example
void display() {
• The object s is stored in the Heap.
int x = 10;
}
Real-Life Example
• The variable x is stored in the Stack.
A warehouse where all newly created items are
stored.
Real-Life Example

• A stack of plates where the last plate placed is


removed first (LIFO).
D) PC Register (Program Counter
E) Native Method Stack
Register)
Function
Function
• Stores information related to native (non-Java)
• Stores the address of the current instruction
methods.
being executed.
Example
• It tells the JVM which instruction to execute
next.
Methods written in:
Real-Life Example
Ø C
Ø C++
• A bookmark in a book showing the current
reading position.
Real-Life Example

• A translator helping two people who speak


different languages communicate.
3. Execution Engine

Function

• Executes the bytecode loaded into memory.

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.

• Improves execution speed.


4. Native Method Interface (JNI) 5. Native Method Libraries
• JNI – Java Native Interface
Function
Function
• Contains libraries written in native languages
• Allows Java programs to communicate with such as:
programs written in:
Ø C
Ø C Ø C++
Ø C++
• These libraries are accessed through JNI.
Real-Life Example
Real-Life Example
• An interpreter helping people speaking
different languages communicate. • A toolbox containing special tools that Java
can use when needed.
Working of JVM Architecture

Step 1
• Java source code is compiled: Step 4

[Link] • Execution Engine executes the bytecode.



javac Step 5

[Link] • If native code is needed:

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

*PC Register *Native Method Stack


Basic Structure of Java Programming

Eg

class HelloWorld { Output


public static void main(String[] args) {
[Link]("Hello World"); Hello World
}
}
Structure of Java Program
Statement Purpose Class Declaration

class HelloWorld Defines a class
Main Method
main() Starting point of execution ↓
Statements
[Link]() Displays output ↓
Output
{} Block of code
Data Types
• A data type specifies what kind of value a variable can store.
Primitive Data Types

Data Type Size Example

byte 1 Byte byte a = 10;

short 2 Bytes short b = 100;

int 4 Bytes int age = 20;

long 8 Bytes long pop = 100000L;

float 4 Bytes float mark = 85.5f;

double 8 Bytes double pi = 3.14;

char 2 Bytes char grade = 'A';

boolean 1 Bit boolean pass = true;


Example

public class DataTypeDemo {

public static void main(String[] args) {

int age = 20;


double mark = 89.5;
char grade = 'A';
boolean pass = true;
Output
[Link](age);
[Link](mark); 20
[Link](grade); 89.5
[Link](pass); A
} true
}
Non-Primitive Data Types
• Non-Primitive Data Types are data types created by programmers or provided by Java. They are used
to store multiple values, objects, and complex data.

• Unlike primitive data types, non-primitive data types:

Ø Can store multiple values


Ø Have methods (functions)
Ø Can be null
Ø Are also called Reference Data Types

Types of Non-Primitive Data Types

1. String

• A String is a sequence of characters enclosed in double quotes.

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

• An Array stores multiple values of the same type in a single variable.

Example

class Main{
public static void main(String[] args){

int[] arr = {2, 4, 8, 12, 16}; Output

[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) {

4. Object Student s = new Student(); // Object creation


[Link](); // Method call
• An object is an instance of a class. }
}
Example
Output
Student s = new Student();
Name: John
5. Interface

• An interface contains method declarations that must be implemented by a class.

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

• A variable is a named memory location used to store data.

Syntax Example
datatype variableName = value; int age = 20;

Difference Between print() and println() in Java

• print(): Displays output without moving the cursor to the next line.
• println(): Displays output and moves the cursor to the next line.

Eg:

public class Demo { Output


public static void main(String[] args) {
Name: Sonu
[Link]("Name: ");
Age: 21
[Link]("Sonu");
[Link]("Age: 21");
}
}
Java Operators Example

1. Arithmetic Operators public class ArithmeticDemo {


public static void main(String[] args) {
int a = 10, b = 5;
• Used to perform mathematical calculations.
[Link]("Addition = " + (a + b));
[Link]("Subtraction = " + (a - b));
Operator Meaning Example [Link]("Multiplication = " + (a * b));
[Link]("Division = " + (a / b));
+ Addition a+b [Link]("Modulus = " + (a % b));
}
- Subtraction a-b }

* Multiplication a*b Output

/ Division a/b Addition = 15


Subtraction = 5
% Modulus a%b Multiplication = 50
Division = 2
Modulus = 0
2. Relational Operators Example

• Used to compare two values. public class RelationalDemo {


public static void main(String[] args) {

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

• Used to combine conditions. Example

public class LogicalDemo {


public static void main(String[] args) {
Operator Meaning
int age = 20;

&& AND [Link](age > 18 && age < 60);


[Link](age < 18 || age > 60);
|| OR [Link](!(age < 18));
}
}
! NOT
Output

true
false
true
4. Assignment Operators Example

• Used to assign values to variables. public class AssignmentDemo {


public static void main(String[] args) {
int x = 10;
Operator Example
x += 5;
[Link](x);
= x=5
x -= 3;
+= x+=5 [Link](x);

-= x-=5 x *= 2;
[Link](x);
*= x*=5 }
}
/= x/=5
Output
15
12
24
5. Increment Operator (++) 6. Decrement Operator (--)

• Increases value by 1. • Decreases value by 1.

Example Example

public class IncrementDemo { public class DecrementDemo {


public static void main(String[] args) { public static void main(String[] args) {

int x = 5; int x = 5;

x++; x--;

[Link](x); [Link](x);
} }
} }

Output Output

6 4
7. Bitwise Operators

• Operate on binary values.


Explanation
Example
a = 5 = 0101
b = 3 = 0011
public class BitwiseDemo {
public static void main(String[] args) {
AND (&)
0101
int a = 5;
0011
int b = 3;
-------
0001 = 1
[Link](a & b);
[Link](a | b);
OR (|)
}
0101
}
0011
-------
Output
0111 = 7
1
7
8. Ternary Operator

• A shortcut for if-else.

Example

public class TernaryDemo {


public static void main(String[] args) {

int age = 20;

String result = (age >= 18) ? "Eligible" : "Not Eligible";

[Link](result);
}
}

Output

Eligible
Expressions
• An expression is a combination of variables, constants, and operators that produces a value.

Example

int result = 10 + 20;


Here: 10 + 20 is an expression.

Eg:

public class ExpressionDemo { Output


public static void main(String[] args) {
int a = 10; 15
int b = 5; true
int sum = a + b;
boolean check = a > b;
[Link](sum);
[Link](check);
}
}
Control Statements in Java
• Control Statements are used to control the flow of execution of a program.

Types of Control Statements

I. Decision Making Statements

1. if Statement

• Used to execute a block of code when a condition is true.

Example

int age = 20;


if(age >= 18)
{
[Link]("Eligible to Vote");
}
2. if-else Statement

• Used to choose between two alternatives based on a condition.

Example

int age = 15;


if(age >= 18) 3. Nested if Statement
{
[Link]("Eligible to Vote");
• An if statement inside another if statement.
}
else
Example
{
[Link]("Not Eligible");
if(age > 18)
}
{
if(age < 60)
{
[Link]("Adult");
}
}
4. switch Statement

• Used to select one block of code from multiple options.

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

• Similar to while, but executes at least once.

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:

int mark1 = 80;


int mark2 = 85;
int mark3 = 90;
int mark4 = 75;
int mark5 = 95;

With Array:

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


One-Dimensional Array
• A one-dimensional array stores elements in a single row.

Syntax Program: Display Array Elements


datatype arrayName[] = new datatype[size];
public class ArrayDemo {
Example public static void main(String[] args) {
int marks[] = new int[5]; int marks[] = {80,85,90,75,95};
for(int i=0;i<5;i++) {
Initializing Array [Link](marks[i]);
int marks[] = {80,85,90,75,95}; }
}
Accessing Array Elements }
[Link](marks[0]);
Output
Output 80
80 85
90
75
95
Finding Sum of Array Elements

public class SumArray {


public static void main(String[] args) {

int arr[] = {10,20,30,40,50};

int sum = 0;

for(int i=0;i<[Link];i++) {
sum += arr[i];
}

[Link]("Sum = " + sum);


}
}

Output
Sum = 150
Multi-Dimensional Array
• An array containing another array is called a
multidimensional array.

• Most commonly used: 2D Array


Syntax
Real-Life Example int arr[][] = new int[2][2];
Student marks table: Initialization
int arr[][] = {
Student Maths Science {10,20},
{30,40}
Anu 80 90 };
Arun 75 85
Accessing Elements
[Link](arr[0][1]);
Stored as:
Output
80 90 20
75 85
Program: Display 2D Array

public class TwoDArray {


public static void main(String[] args) {

int arr[][] = { Output


{10,20},
{30,40} 10 20
}; 30 40

for(int i=0;i<2;i++) {
for(int j=0;j<2;j++) {
[Link](arr[i][j] + " ");
}
[Link]();
}
}
}
Program – Addition of Two Matrices

public class MatrixAddition {


public static void main(String[] args) { [Link]("Result Matrix:");
int a[][] = { for(int i = 0; i < 2; i++) {
{1, 2}, for(int j = 0; j < 2; j++) {
{3, 4} [Link](c[i][j] + " ");
}; }
[Link]();
int b[][] = { }
{5, 6}, }
{7, 8} }
};
Output
int c[][] = new int[2][2];
Result Matrix:
for(int i = 0; i < 2; i++) { 68
for(int j = 0; j < 2; j++) { 10 12
c[i][j] = a[i][j] + b[i][j];
}
}
Strings in Java
• A String is a sequence of characters enclosed in double quotes.

Example

String name = "Mary";

Creating Strings

Method 1

String name = "Mary";

Method 2

String name = new String("Mary");


String Operations

1. length()

• Returns the number of characters.

Example

String name = "Rone"; Output


[Link]([Link]()); 4

2. toUpperCase()

• Converts to uppercase.

Example
Output
String name = "Rone";
RONE
[Link]([Link]());
3. toLowerCase()

• Converts to lowercase.

Example

String name = "Dora"; Output


[Link]([Link]()); dora

4. charAt()

• Returns character at a specified position.

Example
Output
String name = "Jack";
c
[Link]([Link](2));
5. concat()

• Joins two strings.

Example

String a = "Hello";
String b = "Java"; Output
[Link]([Link](" " + b)); Hello Java

6. equals()

• Compares two strings.

Example

String s1 = "Java";
Output
String s2 = "Java";
true
[Link]([Link](s2));
7. contains()

• Checks whether a string contains another string.

Example

String str = "Welcome to Java"; Output


[Link]([Link]("Java")); true

8. substring()

• Extracts part of a string.

Example

String str = "Programming"; Output


[Link]([Link](0,4)); Prog
Program

public class StringDemo {


public static void main(String[] args) {

String name = "James";


String lastname = "Gosling"; Output

[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:

int age = 20;

• Value is fixed.

With Scanner:

Enter Age: 21

• User can enter values during program execution.


Creating a Scanner Object
Program: Read Integer
Syntax
import [Link];
Scanner sc = new Scanner([Link]);
public class ScannerDemo {
public static void main(String[] args) {
Part Meaning
Scanner sc = new Scanner([Link]);
Scanner Class name
[Link]("Enter Age: ");
sc Object name
int age = [Link]();
new Creates object
[Link]("Age = " + age);
[Link] Keyboard input }
}

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

Character nextFloat() Reads float


char grade = [Link]().charAt(0); nextDouble() Reads double

nextBoolean() Reads boolean


Program: Student Details

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]();

[Link]("Enter Age: ");


int age = [Link]();

[Link]("Name: " + name);


[Link]("Age: " + age);
}
}
Type Conversion
• Type Conversion is the automatic conversion of one data type into another by Java.

Also called:

Ø Implicit Conversion
Ø Automatic Conversion
Ø Widening Conversion

Why Does It Happen?

• When a smaller data type is assigned to a larger data type.

Example

int num = 100;


double d = num;

• Java automatically converts: int → double


Program
Similarly:
public class ConversionDemo {
public static void main(String[] args) {
int → long
int → float
int num = 100;
int → double
double d = num;
Widening Conversion Order
[Link](num);
[Link](d);
byte
} ↓
}
short

Output int
100

100.0
long

Real-Life Example
float

Small Cup → Large Bucket double
Water can be poured without loss.
Type Casting
• Type Casting is the manual conversion of one data type into another.

Also called:

Ø Explicit Conversion
Ø Narrowing Conversion

Why Needed?

• When converting a larger data type to a smaller data type.


• Java does not do this automatically.

Syntax
datatype variable = (datatype)value;

Example

double d = 10.75;
int num = (int)d;
Program

public class CastingDemo { Program2


public static void main(String[] args) {
public class CastingDemo2 {
double d = 10.75; public static void main(String[] args) {
int num = (int)d;
int num = 65;
[Link](d);
[Link](num); char ch = (char)num;
}
} [Link](ch);
}
Output }
10.75
10 Output
A
Real-Life Example
• Because ASCII value of 65 is A.
Large Bucket → Small Cup
Some water may be lost.
Difference Between Type Conversion and Type Casting

Type Conversion Type Casting

Automatic Manual

Smaller → Larger Larger → Smaller

No data loss Possible data loss

Done by Java Done by programmer

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

[Link]("Enter Integer: ");

int num = [Link]();

double d = num;

[Link]("Converted to Double: " + d);

int value = (int)d;

[Link]("After Casting: " + value);


}
}
Introduction to Classes and Objects
Class
• A Class is a blueprint or template used to create objects.

• A class is a user-defined data type that contains variables and methods.

Real-Life Example

House Blueprint

Blueprint → Class
Actual House → Object

• A blueprint describes the house but is not the actual house.

• Similarly, a class describes objects but is not an object itself.


Example
class Student {
String name;
int age;
void display() {
[Link]("Student Details");
}
}

Components of a Class

Variables (Data Members)


String name;
int age;
• Store data.

Methods (Member Functions)


void display() {
[Link]("Student Details");
}
• Perform actions.
Object
• An Object is an instance of a class.

• An object is a real-world entity created from a class.

Real-Life Example
Class → Student

Objects: Abinav, Anush, Achuth,.....

• All students are objects created from the Student class.

Creating an Object Accessing Variables and Methods

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
}
}

public class Main {


public static void main(String[] args) {

Student s = new Student();


[Link] = "Manu";
[Link] = 21;
[Link]();
}
}
Multiple Objects Example

class Student {
String name;
void display() { Output
[Link](name);
} Nandhu
} Shidu
public class Main {
public static void main(String[] args) {

Student s1 = new Student();


Student s2 = new Student();

[Link] = "Nandhu";
[Link] = "Shidu";

[Link]();
[Link]();
}
}
Access Modifiers
• Access Modifiers control the visibility and accessibility of classes, variables, and methods.

Why Use Access Modifiers?


• To protect data and control access.

Types of Access Modifiers

1. Public

• Accessible from anywhere.

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

• ATM PIN. Student s = new Student();


[Link]();
• Only the owner can access it. }
}

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 }

• protected int marks; • Accessible only within the same package.

Real-Life Example Real-Life Example

• Family property. • Department notice.

• Accessible only to family members. • Visible only inside the department.


Program Demonstrating Public, Private, Protected, and Default

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

• Constructor name must be the same as the class name.


• It has no return type (not even void).
• It is called automatically when an object is created.

Why Constructor?

• To initialize object data when the object is created.


Real-Life Example

When you buy a new mobile phone:

Mobile Purchased

Initial Setup Happens Automatically

Similarly:

Student s = new Student();

• The constructor runs automatically.


Types of Constructor
Default Constructor

• A constructor with no parameters.

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.

Output Ø Constructor is called automatically.


Student Object Created Ø Message is displayed.
Parameterized Constructor

• A constructor that accepts parameters.

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

• The value "Negha" is passed to the constructor.


Constructor Overloading

• Multiple constructors with different parameters.

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

• Used to establish inheritance.

Syntax

class Child extends Parent


{
}
Program

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.

Using super to Call Parent Method

class Animal { public class Main {


void sound() { public static void main(String[] args) {
[Link]("Animal Sound");
} Dog d = new Dog();
}
class Dog extends Animal { [Link]();
void sound() { }
[Link]("Dog Bark"); }
}
void display() { Output
[Link]();
} Animal Sound
}
• [Link]() calls the parent class method.
Using super to Call Parent Constructor

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.

Problem Without this

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

public class Main {

public static void main(String[] args) {

final int AGE = 21;

[Link](AGE);
}
}

Output

21
If you write:

public class Main {


public static void main(String[] args) {
final int AGE = 21;
[Link]("Age = " + AGE);
AGE = 25; // Error
}
}

Compilation Error

error: cannot assign a value to final variable AGE

• Once a variable is declared as final, its value cannot be changed.

So:

AGE = 25; is not allowed.


Final Method

class Animal {
final void sound() {
[Link]("Animal Sound");
}
}

• Cannot be overridden by child classes.

Final Class

final class Animal {


}
class Dog extends Animal {
}

Output
Compilation Error

• Because a final class cannot be inherited.


Polymorphism
• Polymorphism means "many forms".

• In Java, the same method name can behave differently in different situations.

Types of Polymorphism

1. Compile-Time Polymorphism → Method Overloading


2. Run-Time Polymorphism → Method Overriding / Dynamic Method Dispatch

Method Overloading
• Method Overloading is the process of defining multiple methods with the same name but different
parameters.

Why Use Method Overloading?


Instead of creating: addTwoNumbers(), addThreeNumbers(), addDecimalNumbers()

we can simply use: add() with different parameters.


Real-Life Example

Think of a calculator.

add(10,20)
add(10,20,30)
add(10.5,20.5)

• The operation is the same (addition), but the inputs differ.

Rules for Method Overloading

Methods must differ by:

• Number of parameters
• Type of parameters
• Order of parameters
Program 1: Different Number of Parameters Program 2: Different Data Types

class Addition { class Display {


void add(int a, int b) { void show(int a) {
[Link]("Sum = " + (a + b)); [Link]("Integer: " + a);
} }
void add(int a, int b, int c) { void show(double a) {
[Link]("Sum = " + (a + b + c)); [Link]("Double: " + a);
} }
} }
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
Addition obj = new Addition(); Display d = new Display();
[Link](10, 20); [Link](10);
[Link](10, 20, 30); [Link](10.5);
} }
} }

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.

Why Use Method Overriding?

• To provide a specific implementation in the child class.

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

• The child class method replaces the parent class method.


Parent and Child Method Example

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.

• Dynamic Method Dispatch is the process of resolving overridden methods at runtime.

Syntax

Parent ref = new Child();

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.

• An interface is a collection of abstract methods that a class must implement.

Why do we use an Interface?

• To achieve 100% abstraction


• To support multiple inheritance
• To define a common standard for different classes

Syntax
interface Animal{
void sound();
}
Rules of Interface

• Cannot create objects of an interface.

• Methods are public and abstract by default.

• Variables are public static final by default.

• A class uses the implements keyword.

Using implements Keyword

class Dog implements Animal


{ Advantages of Interface
}
• Achieves abstraction.
• Supports multiple inheritance.
• Improves code reusability.
Program 1: Interface Example

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.

Why Use an Abstract Class?

• 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

abstract class Vehicle {


abstract void start();
}
class Car extends Vehicle {
void start() {
[Link]("Car Started");
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car();
[Link]();
}
}

Output

Car Started
Program 2: Abstract Method + Normal Method

abstract class Vehicle {


abstract void start();
void stop() {
[Link]("Vehicle Stopped");
}
}
class Bike extends Vehicle {
void start() {
[Link]("Bike Started");
}
}
public class Main {
public static void main(String[] args) { Output
Bike b = new Bike();
[Link](); Bike Started
[Link](); Vehicle Stopped
}
}
Package
• A Package is a collection of related classes and interfaces.

Why Use Packages?


• Organizes classes.
• Avoids name conflicts.
• Improves code management.
• Provides access protection.

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");
}
}

• Save this file inside a folder named college.

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

[Link] Core Java classes

[Link] Scanner, ArrayList, Collections

[Link] File handling

[Link] Database connectivity


Interface vs Abstract Class vs Package

Feature Interface Abstract Class Package

Object Creation Not allowed Not allowed Not applicable

Constructors No Yes No

Contains
Methods Abstract by default Abstract + Normal
classes/interfaces

Keyword interface abstract class package

Abstraction & Multiple


Used for Partial Abstraction Organizing classes
Inheritance

You might also like