0% found this document useful (0 votes)
1 views219 pages

Java Unit 1

Java is a high-level, object-oriented programming language developed by James Gosling and his team at Sun Microsystems in 1991, designed for platform independence with the principle of 'Write Once, Run Anywhere.' It evolved through several versions, introducing features such as applets, generics, and lambda expressions, and became popular for its security, robustness, and versatility in applications ranging from web to enterprise software. Java's lineage traces back to earlier languages like C and C++, inheriting their syntax while removing complex features, making it simpler and more secure.

Uploaded by

udaysankartec
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)
1 views219 pages

Java Unit 1

Java is a high-level, object-oriented programming language developed by James Gosling and his team at Sun Microsystems in 1991, designed for platform independence with the principle of 'Write Once, Run Anywhere.' It evolved through several versions, introducing features such as applets, generics, and lambda expressions, and became popular for its security, robustness, and versatility in applications ranging from web to enterprise software. Java's lineage traces back to earlier languages like C and C++, inheriting their syntax while removing complex features, making it simpler and more secure.

Uploaded by

udaysankartec
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

History and Evolution of Java

1. Introduction to Java
Java is a high-level, object-oriented, platform-independent programming language developed by
James Gosling and his team at Sun Microsystems in 1991.

Java was designed with the principle:

"Write Once, Run Anywhere (WORA)"

This means a Java program can run on any system that has a Java Virtual Machine (JVM).

2. Why Was Java Created?


Before Java, most software was platform-dependent.

For example:

• C programs compiled on Windows could not run directly on Linux.

• Different hardware required different executable les.

Sun Microsystems wanted a language for electronic devices such as:

• TVs

• Set-top boxes

• Home appliances

Requirements:

• Portable

• Secure

• Reliable

• Easy to use

3. History of Java
1991 – The Green Project

A team led by James Gosling started the Green Project.


fi
Goal:
Develop software for consumer electronic devices.

The language was initially called:

Oak

Named after an oak tree outside Gosling's of ce.

Why Oak Was Renamed?

The name "Oak" was already trademarked.

Therefore, in 1995 it was renamed:

Java

The name was inspired by Java coffee.

4. The Internet Revolution


During the mid-1990s, the Internet became popular.

Sun Microsystems realized Java was ideal for web applications because:

• Platform independent

• Secure

• Network-oriented

Java became famous through:

Java Applets

Small Java programs embedded in web pages.

Advantages:

• Interactive web pages

• Dynamic content

Although applets are now obsolete, they helped Java become popular.

5. Evolution of Java
fi
Java 1.0 (1996)

Features:

• JVM

• Applets

• Basic libraries

• AWT GUI

Java 1.1 (1997)

Added:

• Event handling

• JDBC

• Inner classes

Java 2 (JDK 1.2) – 1998

Major update:

• Swing GUI

• Collections Framework

Editions introduced:

• J2SE

• J2EE

• J2ME

J2SE 5.0 (2004)

Important features:

• Generics

• Enhanced for-loop

• Autoboxing
• Annotations

• Enumerations

Java 8 (2014)

Most revolutionary release:

• Lambda Expressions

• Stream API

• Functional Programming

• Date and Time API

Java 9 (2017)

• Module System (Project Jigsaw)

Java 11 (2018)

Long-Term Support (LTS)

Java 17 (2021)

LTS Release

• Better performance

• Security improvements

Java 21 (2023)

Latest LTS generation widely adopted.

Features:

• Virtual Threads

• Pattern Matching

• Performance improvements
6. Why Java Became Popular?
Platform Independent

Compile Once → Run Anywhere

Source Code (.java)

Compiler

Bytecode (.class)

JVM

Any Operating System

Object-Oriented

Supports:

• Class

• Object

• Inheritance

• Polymorphism

• Encapsulation

• Abstraction

Secure
• No pointers

• Bytecode veri cation

• Sandboxing

Robust

• Exception Handling

• Garbage Collection

• Strong Type Checking

7. Java Editions
Java SE

Standard Edition

Used for:

• Desktop applications

• Core Java development

Java EE (Jakarta EE)

Used for:

• Enterprise applications

• Web applications

Java ME

Used for:

• Embedded devices

• Mobile devices

8. Applications of Java
• Web Applications
fi
• Android Applications

• Banking Systems

• Enterprise Software

• Cloud Applications

• Big Data Technologies

• Scienti c Applications

Examples:

• Oracle Java Platform

• Apache Hadoop

• Spring Framework

9. Interview Questions
Q1. Who invented Java?

Answer: James Gosling.

Q2. What was Java originally called?

Answer: Oak.

Q3. What is WORA?

Answer: Write Once, Run Anywhere.

Q4. Why is Java platform independent?

Answer: Because Java programs run on the JVM.

Q5. What is bytecode?

Answer: The intermediate code generated by the Java compiler.

10. Exam Point (JNTUK – 10 Marks)


History and Evolution of Java
fi
Java was developed by James Gosling and his team at Sun Microsystems in 1991 under the Green
Project. It was initially named Oak and later renamed Java in 1995. Java gained popularity because
of its platform independence, security, robustness, and object-oriented features. The slogan "Write
Once, Run Anywhere" became possible through the JVM. Over time, Java evolved through versions
such as Java 1.0, Java 2, Java 5, Java 8, Java 11, Java 17, and Java 21, adding features like
Generics, Collections, Lambda Expressions, Streams, Modules, and Virtual Threads. Today Java is
widely used for web, enterprise, cloud, and mobile applications.

Java's Lineage
Lineage means the ancestry or family tree of a programming language.

Java did not appear suddenly. It evolved from several earlier languages.

BCPL

B

C

C++

Java

1. BCPL (Basic Combined Programming Language)


• Developed by Martin Richards in 1967.
• Designed for system programming.
• In uenced the development of B.
2. B Language
• Developed by Ken Thompson at Bell Labs.
• Simpler version of BCPL.
• In uenced the development of C.
3. C Language
• Developed by Dennis Ritchie in 1972.
• Powerful and ef cient.
• Used for operating systems and system software.
• Java inherits:
◦ Syntax (if, for, while, switch)
◦ Operators
◦ Data types
4. C++
fl
fl
fi
• Developed by Bjarne Stroustrup.
• Added Object-Oriented Programming to C.
• Java borrowed:
◦ Classes
◦ Objects
◦ Inheritance
◦ Polymorphism
5. Java
• Developed by James Gosling in 1991.
• Removed complex features of C++ such as:
◦ Pointers
◦ Multiple inheritance of classes
◦ Operator overloading
• Added:
◦ JVM
◦ Garbage Collection
◦ Bytecode
◦ Platform Independence
Features Java Inherited
From C From C++ Java Added
Syntax Classes JVM
Operators Objects Bytecode
Control
Inheritance Garbage Collection
Statements
Polymorphis Platform
Data Types
m Independence

Exam Answer (Short)

Java's lineage can be traced as BCPL → B → C → C++ → Java. Java inherited its basic syntax
and control structures from C and object-oriented concepts from C++. Java improved upon these
languages by introducing platform independence through the JVM, automatic garbage collection,
and enhanced security. This combination made Java a robust and portable programming language.

The Birth of Modern Programming: C Language

Introduction
The C programming language is often called the birth of modern programming because it
greatly in uenced many modern languages such as Java, C++, C#, JavaScript, and Python.

C was developed in 1972 by Dennis Ritchie at Bell Labs.


fl
Why Was C Developed?
Before C, programmers mainly used:

• Assembly Language
• B Language
These languages had limitations:

• Dif cult to write large programs


• Machine-dependent
• Hard to maintain
Dennis Ritchie developed C to create a language that was:

• Powerful
• Ef cient
• Portable
• Easier than Assembly Language

The UNIX Connection


One of the biggest achievements of C was the development of the operating system:

UNIX

UNIX was largely rewritten in C, proving that a high-level language could be used for system
programming.

This revolutionized software development.

Why Is C Called the Birth of Modern Programming?


1. Structured Programming

C introduced structured programming concepts:

if
else
for
while
switch

Programs became easier to understand and maintain.

2. Portability
fi
fi
A C program can be compiled on different computers with minimal changes.

This idea later in uenced Java's "Write Once, Run Anywhere" philosophy.

3. Ef ciency

C produces fast and ef cient programs, close to machine-level performance.

4. Foundation for Modern Languages

Many popular languages borrowed C syntax:

if(condition)
{
statement;
}

Used in:

• C++
• Java
• C#
• JavaScript
• PHP

In uence on Java
Java inherited many features from C:

Syntax

if(condition){
// code
}

Operators

+
-
*
/
%
fl
fi
fl
fi
Control Statements

if
else
for
while
switch

Because of this, programmers familiar with C can learn Java more easily.

Legacy of C
Languages Derived from C

BCPL

B

C

C++

Java

C#

C became the foundation of modern software development.

Key Contributions of C
• Structured Programming
• Portable Software Development
• System Programming
• Ef cient Execution
• In uence on Modern Languages

JNTUK Exam Answer (5 Marks)


The Birth of Modern Programming: C

The C programming language was developed by Dennis Ritchie in 1972 at Bell Labs. It is
considered the birth of modern programming because it introduced structured programming,
fl
fi
portability, and ef ciency. C was used to develop the UNIX operating system and became the
foundation for many modern languages such as C++, Java, and C#. Its simple syntax, powerful
features, and machine-independent nature made it one of the most in uential programming
languages in computer science.

C++: The Next Step


After the success of C, programmers needed a way to manage large and complex software projects.
This led to the development of C++.

History
C++ was developed by Bjarne Stroustrup at Bell Labs in 1979.

Initially, it was called "C with Classes" because it added Object-Oriented Programming (OOP)
features to C.

In 1983, the language was renamed C++.

The operator ++ in C means increment by 1, symbolizing that C++ is an improved version of C.

Why Was C++ Developed?


C had some limitations when developing large software systems:

• Dif cult to manage large code bases


• Poor data security
• Lack of object-oriented features
C++ solved these problems by introducing OOP concepts.

Major Features Added by C++


1. Classes and Objects

class Student {
int id;
};

Classes allow data and methods to be grouped together.

2. Encapsulation
fi
fi
fl
Data can be hidden and protected from unauthorized access.

3. Inheritance

class A { };
class B : public A { };

A new class can inherit properties of an existing class.

4. Polymorphism

The same function can behave differently in different situations.

5. Function Overloading

add(int a, int b);


add(double a, double b);

Multiple functions can have the same name with different parameters.

C vs C++
C C++
Procedure-oriented Object-oriented
Functions are
Objects are central
central
No classes Supports classes
No inheritance Supports inheritance
Supports
No polymorphism
polymorphism

In uence on Java
Java borrowed many OOP concepts from C++:

• Classes
• Objects
• Inheritance
• Polymorphism
• Encapsulation
However, Java removed some complex C++ features:
fl
• Pointers
• Multiple inheritance of classes
• Operator overloading
• Manual memory management
This made Java simpler, safer, and more portable.

JNTUK Exam Answer (5 Marks)


C++: The Next Step

C++ was developed by Bjarne Stroustrup at Bell Labs as an extension of the C language. Initially
called "C with Classes," it introduced Object-Oriented Programming concepts such as classes,
objects, inheritance, encapsulation, and polymorphism. C++ helped programmers develop large and
complex software systems more ef ciently. Its object-oriented features greatly in uenced the design
of Java, making C++ an important step in the evolution of modern programming languages.

The Stage Is Set for Java


By the early 1990s, the computing world was changing rapidly. C and C++ were powerful, but new
challenges required a different kind of programming language.

Problems with Existing Languages


C

• Platform dependent
• Manual memory management
• Less secure
• Dif cult for large network applications
C++

• Complex syntax
• Pointers caused memory errors
• Multiple inheritance increased complexity
• Programs had to be recompiled for different platforms
As computers became connected through networks and the Internet, developers needed a language
that was:

• Simple
• Secure
• Portable
• Robust
• Network-oriented
fi
fi
fl
The Rise of the Internet
The early 1990s saw the rapid growth of the:

Internet

People wanted software that could run on:

• Windows
• Linux
• Macintosh
• Different hardware platforms
Writing separate programs for each platform was expensive and time-consuming.

The Green Project


In 1991, James Gosling and his team at Sun Microsystems started the Green Project.

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

• Televisions
• Set-top boxes
• Home appliances
They needed a language that could run on many different devices.

Birth of Java
The team created a new language called Oak.

Later, it was renamed Java in 1995.

Java combined the best features of C and C++ while eliminating many of their weaknesses.

What Made Java Different?


Platform Independence

Java Source Code



Compiler

Bytecode

JVM

Any Operating System

Write Once, Run Anywhere (WORA)

Security

• No pointers
• Bytecode veri cation
• Secure execution environment

Robustness

• Exception handling
• Garbage collection
• Strong type checking

Object-Oriented Design

Java adopted:

• Classes
• Objects
• Inheritance
• Polymorphism
from C++ while keeping the language simpler.

Evolution Summary

BCPL

B

C

C++

Java

Each language solved some problems of its predecessor, and Java emerged as a language designed
for the Internet age.

JNTUK Exam Answer (5 Marks)


The Stage Is Set for Java
fi
By the early 1990s, the limitations of C and C++ became evident, especially for networked and
Internet-based applications. Developers needed a language that was portable, secure, robust, and
easy to use across different platforms. In 1991, James Gosling and his team at Sun Microsystems
initiated the Green Project and developed a new language called Oak, later renamed Java. Java
combined the strengths of C and C++ while introducing platform independence through the JVM,
automatic garbage collection, and enhanced security. These features made Java ideal for the Internet
era and established it as one of the most popular programming languages in the world.

Java's Magic: The Bytecode


One of the most important reasons for Java's success is Bytecode.

Bytecode is the secret behind Java's famous slogan:

"Write Once, Run Anywhere (WORA)"

What is Bytecode?
When a Java program is compiled, it is not converted directly into machine code.

Instead, the Java compiler (javac) converts the source code into an intermediate code called
Bytecode.

Java Source Code (.java)



javac

Bytecode (.class)

JVM

Machine Code

Why is Bytecode Important?


Different computers have different processors:
• Intel
• AMD
• ARM
• Apple Silicon
Normally, machine code generated for one processor cannot run on another.

Java solves this problem using Bytecode.

The compiler generates the same .class le for all platforms.

Only the JVM changes according to the operating system.

Role of JVM
The Java Virtual Machine reads the Bytecode and converts it into machine instructions that the
computer can execute.

Windows JVM → Runs Bytecode


Linux JVM → Runs Bytecode
macOS JVM → Runs Bytecode

Thus, the same Bytecode can run on any system that has a JVM.

Example
Source Program

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

Compilation

javac [Link]

Output:

[Link]

The .class le contains Bytecode.


fi
fi
Execution

java Test

The JVM loads and executes the Bytecode.

Advantages of Bytecode
1. Platform Independence

Compile once and run anywhere.

2. Security

The JVM veri es Bytecode before execution.

3. Portability

The same .class le works on different operating systems.

4. Performance

Modern JVMs use JIT (Just-In-Time) Compilation to convert Bytecode into optimized machine
code.

Bytecode vs Machine Code


Bytecode Machine Code
Platform-independent Platform-dependent
Executed directly by
Executed by JVM
CPU
Stored in .class
Stored in executable les
les
Portable Not portable

Why is Bytecode Called Java's Magic?


Because Bytecode allows:

• Platform independence
• Portability
• Security
• Easy distribution of programs
fi
fi
fi
fi
Without Bytecode, Java would be just another programming language.

Bytecode is the key technology that made Java unique and popular.

JNTUK Exam Answer (5 Marks)


Java's Magic: The Bytecode

Bytecode is the intermediate code generated by the Java compiler after compiling a Java source
program. It is stored in .class les and is independent of any speci c hardware or operating
system. The Java Virtual Machine (JVM) interprets or compiles the Bytecode into machine code for
the target platform. This enables Java's "Write Once, Run Anywhere" capability. Bytecode also
improves security, portability, and performance, making it one of the most important features of
Java.

The Java Buzzwords


The creators of Java identi ed a set of key features, commonly called the Java Buzzwords, that
distinguish Java from other programming languages.

1. Simple
Java is easy to learn because:

• Syntax is similar to C/C++


• Removes complex features like:
◦ Pointers
◦ Operator overloading
◦ Multiple inheritance of classes
Example:
fi
fi
fi
[Link]("Hello Java");

2. Object-Oriented
Everything in Java is based on:

• Classes
• Objects
Main OOP concepts:

• Encapsulation
• Inheritance
• Polymorphism
• Abstraction

3. Distributed
Java is designed for network applications.

Features:

• URL handling
• Socket programming
• Remote Method Invocation (RMI)
Java makes it easier to build distributed systems.

4. Robust
Robust means strong and reliable.

Java provides:

• Exception handling
• Garbage collection
• Strong type checking
These features reduce program crashes.

5. Secure
Java was designed with security in mind.

Security features:

• No pointers
• Bytecode veri cation
• JVM security checks
fi
Java programs run in a controlled environment.

6. Architecture-Neutral
Java programs are not tied to any particular CPU architecture.

The compiler generates Bytecode, not machine code.

7. Portable
Java programs can move from one platform to another without modi cation.

Write Once

Run Anywhere

8. High Performance
Initially Java was slower than C/C++.

Modern JVMs use:

• JIT (Just-In-Time) Compilation


• Runtime optimization
This greatly improves performance.

9. Multithreaded
Java supports multiple threads.

Example uses:

• Games
• Web servers
• Download managers
A program can perform several tasks simultaneously.

10. Interpreted
Java Bytecode is executed by the JVM.

Source Code
fi

Compiler

Bytecode

JVM

Execution

The JVM interprets or compiles Bytecode at runtime.

11. Dynamic
Java adapts to changing environments.

Features:

• Dynamic class loading


• Runtime linking
• Re ection
Classes can be loaded when needed.

Summary Table
Buzzword Meaning
Simple Easy to learn and use
Object-Oriented Based on classes and objects
Distributed Supports network applications
Robust Reliable and error-resistant
Protected execution
Secure
environment
Architecture- Independent of CPU
Neutral architecture
Portable Runs on different platforms
High Performance Fast execution with JIT
Multithreaded Supports concurrent tasks
Interpreted Runs through JVM
Dynamic Adapts during runtime
fl
Object-Oriented Programming: Two
Paradigms
A programming paradigm is a style or approach to writing programs.

There are two major paradigms commonly discussed in Java textbooks:

1. Procedural-Oriented Programming (POP)


In procedural programming, the focus is on functions (procedures).

Programs are divided into a collection of functions that operate on data.

Characteristics

• Top-down approach
• Functions are more important than data
• Data is often shared globally
• Less secure for large applications
Example Languages

• C
• Pascal
• FORTRAN
Example

int add(int a, int b) {


return a + b;
}

The emphasis is on how the task is performed.

2. Object-Oriented Programming (OOP)


In object-oriented programming, the focus is on objects and data.

Data and the methods that operate on that data are combined into a single unit called an object.

Characteristics

• Bottom-up approach
• Objects are the basic building blocks
• Better security through encapsulation
• Easy to maintain and reuse code
Example Languages
• Java
• C++
• C#
Example

class Student {
int id;

void display() {
[Link](id);
}
}

The emphasis is on objects and their interactions.

Comparison of the Two Paradigms


Procedural Object-Oriented
Programming Programming
Focus on functions Focus on objects
Top-down approach Bottom-up approach
Data is less secure Data is more secure
Dif cult for large projects Suitable for large projects
Code reuse is limited Supports code reuse
Example: C Example: Java

Why OOP Became Popular?


As software systems became larger, procedural programming became dif cult to manage.

OOP introduced:

Encapsulation

Combines data and methods into a single unit.

Inheritance

Allows one class to acquire properties of another class.

Polymorphism

One interface, many forms.


fi
fi
Abstraction

Shows only essential details and hides complexity.

These features make software:

• Reusable
• Maintainable
• Scalable

Real-Life Example
Procedural Approach

Student Data

Functions

Process Data

Object-Oriented Approach

Student Object
├─ id
├─ name
└─ display()

Data and behavior stay together.

Object-Oriented Programming: Two


Paradigms
A programming paradigm is a style or approach to writing programs.

There are two major paradigms commonly discussed in Java textbooks:

1. Procedural-Oriented Programming (POP)


In procedural programming, the focus is on functions (procedures).
Programs are divided into a collection of functions that operate on data.

Characteristics

• Top-down approach
• Functions are more important than data
• Data is often shared globally
• Less secure for large applications
Example Languages

• C
• Pascal
• FORTRAN
Example

int add(int a, int b) {


return a + b;
}

The emphasis is on how the task is performed.

2. Object-Oriented Programming (OOP)


In object-oriented programming, the focus is on objects and data.

Data and the methods that operate on that data are combined into a single unit called an object.

Characteristics

• Bottom-up approach
• Objects are the basic building blocks
• Better security through encapsulation
• Easy to maintain and reuse code
Example Languages

• Java
• C++
• C#
Example

class Student {
int id;

void display() {
[Link](id);
}
}

The emphasis is on objects and their interactions.

Comparison of the Two Paradigms


Procedural Object-Oriented
Programming Programming
Focus on functions Focus on objects
Top-down approach Bottom-up approach
Data is less secure Data is more secure
Dif cult for large projects Suitable for large projects
Code reuse is limited Supports code reuse
Example: C Example: Java

Why OOP Became Popular?


As software systems became larger, procedural programming became dif cult to manage.

OOP introduced:

Encapsulation

Combines data and methods into a single unit.

Inheritance

Allows one class to acquire properties of another class.

Polymorphism

One interface, many forms.

Abstraction

Shows only essential details and hides complexity.

These features make software:

• Reusable
• Maintainable
• Scalable

Real-Life Example
fi
fi
Procedural Approach

Student Data

Functions

Process Data

Object-Oriented Approach

Student Object
├─ id
├─ name
└─ display()

Data and behavior stay together.

OOP Principles (Object-Oriented


Programming Principles)
The four fundamental principles of OOP are:

1. Encapsulation
De nition: Wrapping data (variables) and methods (functions) into a single unit called a class and
restricting direct access to data.

Example

class Student {
private int id;

public void setId(int id) {


[Link] = id;
}

public int getId() {


return id;
fi
}
}

Advantages

• Data security
• Data hiding
• Better control over data

2. Abstraction
De nition: Hiding implementation details and showing only essential features to the user.

Example

abstract class Vehicle {


abstract void start();
}

When you drive a car, you use the steering wheel and pedals without knowing the engine's internal
details.

Advantages

• Reduces complexity
• Improves maintainability
• Enhances security

3. Inheritance
De nition: One class acquires the properties and methods of another class.

Example

class Animal {
void eat() {
[Link]("Eating");
}
}

class Dog extends Animal {


void bark() {
[Link]("Barking");
}
}
fi
fi
Advantages

• Code reusability
• Easy maintenance
• Reduces redundancy

4. Polymorphism
De nition: One interface, many forms.

A method can perform different actions depending on the object.

Method Overloading (Compile-Time Polymorphism)

class MathOp {
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

Method Overriding (Runtime Polymorphism)

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

class Dog extends Animal {


void sound() {
[Link]("Bark");
}
}

Advantages

• Flexibility
• Extensibility
• Better code design
fi
OOP Principles Diagram

Object-Oriented Programming
|
-----------------
| | |
Encapsulation
Abstraction
Inheritance
Polymorphism

Real-Life Example: Mobile Phone


Encapsulation

Phone data and functions are bundled together.

Abstraction

You press a call button without knowing internal circuitry.

Inheritance

Smartphone inherits features of a basic phone.

Polymorphism

The same "Call" feature works differently in various apps.

How Encapsulation, Abstraction, Inheritance,


and Polymorphism Work Together
These four OOP principles are not separate concepts. They work together to create secure, reusable,
and exible software.

Let's use a Bank Account System example.

Step 1: Encapsulation (Protect the Data)


fl
class Account {
private double balance;

public void deposit(double amount) {


balance += amount;
}

public double getBalance() {


return balance;
}
}

What happens?

• balance is hidden using private.


• Users cannot directly modify the balance.
• Access is controlled through methods.
Result: Data security.

Step 2: Abstraction (Hide Complexity)

abstract class Account {


abstract void calculateInterest();
}

The user only knows:

[Link]();

They don't need to know the internal formula.

Result: Simplicity.

Step 3: Inheritance (Reuse Code)

class SavingsAccount extends Account {


void calculateInterest() {
[Link]("Savings Interest");
}
}
class CurrentAccount extends Account {
void calculateInterest() {
[Link]("Current Interest");
}
}

What happens?

• Both accounts inherit common features from Account.


• No need to rewrite code.
Result: Code reusability.

Step 4: Polymorphism (One Interface, Many Forms)

Account acc;

acc = new SavingsAccount();


[Link]();

acc = new CurrentAccount();


[Link]();

Same method call:

[Link]();

Different behavior:

Savings Interest
Current Interest

Result: Flexibility.

How They Work Together

Account
|
----------------
| |
SavingsAccount CurrentAccount
| |
Encapsulation Encapsulation
|
Abstraction
|
Polymorphism

Flow

1. Encapsulation protects account data.


2. Abstraction hides implementation details.
3. Inheritance reuses common account features.
4. Polymorphism allows different account types to behave differently through the same
interface.

Real-Life Example: Car


Encapsulation

Engine details are hidden inside the car.

Abstraction

You use the steering wheel and pedals without knowing engine mechanics.

Inheritance

Vehicle
|
-----------------
| |
Car Bike

Polymorphism

[Link]();

• Car starts one way.


• Bike starts another way.
Same command, different behavior.

Easy Memory Trick


E-A-I-P

• E → Encapsulation = Protect Data


• A → Abstraction = Hide Complexity
• I → Inheritance = Reuse Code
• P → Polymorphism = Flexible Behavior

Program Structure in Java: Introduction


A Java program is organized in a speci c structure. Understanding this structure is the rst step in
learning Java programming.

Basic Structure of a Java Program

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

Components of a Java Program


1. Class Declaration

class Hello

• Every Java program contains at least one class.


• class is a keyword used to create a class.
• Hello is the class name.
A class is a blueprint for creating objects.

2. Main Method

public static void main(String args[])

This is the starting point of every Java application.

Meaning of Each Keyword


fi
fi
public

• Accessible from anywhere.


• JVM can call it.
static

• Can be called without creating an object.


void

• Returns no value.
main

• Special method name recognized by JVM.


String args[]

• Stores command-line arguments.

3. Method Body

{
[Link]("Hello World");
}

Contains the statements that will be executed.

4. Output Statement

[Link]("Hello World");

Breakdown

System

• Prede ned class in Java.


out

• Standard output stream.


println()

• Prints text and moves to the next line.


Output:

Hello World

Program Execution Process


fi
[Link]
|
| javac

[Link]
(Bytecode)
|
| JVM

Output

Step 1: Write Program

[Link]

Step 2: Compile

javac [Link]

Compiler generates:

[Link]

Step 3: Run

java Hello

Output:

Hello World

Rules for Java Program Structure


Rule 1

The le name must match the public class name.

Example:
fi
public class Test

File name:

[Link]

Rule 2

Java is case-sensitive.

Main

and

main

are different.

Rule 3

Execution starts from the main() method.

Skeleton of a Java Program

class ClassName {

// Variables

// Methods

public static void main(String args[]) {

// Statements

}
}
Elements (Tokens) in Java
A token is the smallest individual unit in a Java program that has meaning to the compiler.

Just as a sentence is made up of words, a Java program is made up of tokens.

Example:

int a = 10;

Tokens are:

int
a
=
10
;

Types of Tokens in Java


1. Keywords
Keywords are reserved words that have prede ned meanings in Java.

Examples:

class
public
static
void
if
else
for
while
return

Example:

public class Test {


}
fi
Here:

public
class

are keywords.

2. Identi ers
Identi ers are names given to:

• Classes
• Variables
• Methods
• Objects
Example:

int age;

age is an identi er.

Rules for Identi ers

✅ Can contain:

• Letters
• Digits
• _
• $
✅ Cannot:

• Start with a digit


• Be a keyword
• Contain spaces
Valid:

student
_age
emp1
$salary

Invalid:
fi
fi
fi
fi
1student
class
student name

3. Literals
Literals are xed values assigned to variables.

Example:

int x = 100;

100 is a literal.

Types of Literals

Integer Literal

10
25
100

Floating Point Literal

3.14
12.5

Character Literal

'A'
'B'

String Literal

"Hello"
"Java"

Boolean Literal
fi
true
false

4. Operators
Operators perform operations on operands.

Examples:

+
-
*
/
%
=
==
>
<

Example:

a + b

+ is an operator.

5. Separators
Separators separate program elements.

Examples:

;
,
.
(
)
{
}
[
]

Example:
int a, b;

, and ; are separators.

Example Program

class Demo {
public static void main(String args[]) {
int x = 10;
[Link](x);
}
}

Tokens Used

Toke
Type
n

class Keyword

Demo Identi er

public Keyword

static Keyword

void Keyword

main Identi er

int Keyword

x Identi er
10 Literal
= Operator
Separato
;
r

Memory Trick
fi
fi
fi
KILOS

• K → Keywords
• I → Identi ers
• L → Literals
• O → Operators
• S → Separators

Java Statements
A statement in Java is an instruction that tells the computer to perform a speci c action.

A Java program is made up of one or more statements.

Types of Java Statements


1. Declaration Statements

Used to declare variables.

int a;
double salary;
String name;

Example:

int age = 25;

2. Expression Statements

Statements that perform calculations or assignments.

a = 10;
b = a + 5;
count++;

Example:

int sum = a + b;
fi
fi
3. Control Statements

Control the ow of program execution.

Selection Statements

if
if-else
switch

Example:

if(age >= 18)


[Link]("Eligible");

Iteration Statements

for
while
do-while

Example:

for(int i=1; i<=5; i++)


[Link](i);

Jump Statements

break
continue
return

Example:

break;

4. Block Statements

A group of statements enclosed within { }.


fl
{
int a = 10;
int b = 20;
[Link](a+b);
}

This entire section is called a block.

5. Empty Statement

A statement containing only a semicolon.

Example:

while(condition);

Although valid, it is usually used carefully because it can cause logical errors.

Importance of Semicolon (;)


In Java, most statements end with a semicolon.

int a = 10;
[Link](a);

The semicolon tells the compiler that the statement has ended.

Example Program

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

int x = 10; // Declaration statement

x = x + 5; // Expression statement

if(x > 10) { // Control statement


[Link](x);
}
}
}

Classi cation Summary


Statement
Purpose
Type
Declaration Declares variables
Performs calculations/
Expression
assignments
Control Changes program ow
Block Groups statements
Empty Contains only ;

Command Line Arguments in Java


Introduction
Command Line Arguments are values passed to a Java program when it is executed from the
command prompt (terminal).

These arguments are stored in the String args[] parameter of the main() method.

public static void main(String args[])

or

public static void main(String[] args)

Both are equivalent.

Why Use Command Line Arguments?


They allow users to provide input while running the program without using a keyboard input
class like Scanner.
fi
fl
Example:

java Test 10 20

Here:

• 10 → First argument
• 20 → Second argument

Example 1: Display Arguments

class Test {
public static void main(String args[]) {
[Link](args[0]);
[Link](args[1]);
}
}

Compile

javac [Link]

Run

java Test Hello Java

Output

Hello
Java

How Arguments Are Stored


Command:

java Test A B C

Array contents:
args[0] = "A"
args[1] = "B"
args[2] = "C"

args
|
----------------
| | |
"A" "B" "C"
0 1 2

Example 2: Add Two Numbers


Since command-line arguments are strings, they must be converted to integers.

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

int a = [Link](args[0]);
int b = [Link](args[1]);

[Link]("Sum = " + (a+b));


}
}

Run

java Add 10 20

Output

Sum = 30

Important Points
1. Arguments Are Strings
args[0]

is always a String.

Convert when necessary:

[Link]()
[Link]()
[Link]()

2. Array Index Starts at 0

args[0]
args[1]
args[2]

3. Runtime Error

If insuf cient arguments are supplied:

java Test

and the program accesses:

args[0]

an exception occurs:

ArrayIndexOutOfBoundsException

Example 3: Count Arguments

class Count {
public static void main(String args[]) {
[Link]("Number of Arguments = " +
[Link]);
}
}
fi
Run

java Count A B C D

Output

Number of Arguments = 4

User Input to Programs in Java


A program often needs data from the user while it is running. This process is called user input.

Java provides several ways to accept input from the user.

1. Using Scanner Class (Most Common


Method)
The Scanner class is available in the [Link] package.

Program

import [Link];

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

Scanner sc = new Scanner([Link]);

[Link]("Enter your name: ");


String name = [Link]();

[Link]("Hello " + name);


}
}

Output
Enter your name: Uday
Hello Uday

Reading Different Data Types

Scanner sc = new Scanner([Link]);

int age = [Link]();

float salary = [Link]();

double marks = [Link]();

String name = [Link]();

Common Scanner Methods

Method Reads
nextInt() Integer
nextFloat() Float
nextDouble() Double
next() Single word
nextLine() Entire line
nextBoolean( Boolean
) value

2. Using Command-Line Arguments


Input can be provided while running the program.

Program

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

[Link](args[0]);
}
}

Run
java Test Hello

Output

Hello

3. Using BufferedReader
A traditional method for reading input.

Program

import [Link].*;

class Test {
public static void main(String args[]) throws Exception {

BufferedReader br =
new BufferedReader(
new InputStreamReader([Link]));

String name = [Link]();

[Link](name);
}
}

Advantages

• Fast input
• Common in older Java programs

Input Stream in Java

Keyboard

[Link]

Scanner / BufferedReader

Java Program

[Link] represents the standard input stream (keyboard).

Example: Add Two Numbers Using Scanner

import [Link];

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

Scanner sc = new Scanner([Link]);

[Link]("Enter first number: ");


int a = [Link]();

[Link]("Enter second number: ");


int b = [Link]();

[Link]("Sum = " + (a+b));


}
}

Output

Enter first number: 10


Enter second number: 20
Sum = 30

Comparison
Method Usage
Scanner Most commonly used
BufferedReader Faster, older approach
Command-Line Input at execution
Arguments time
Yes. Besides Scanner, BufferedReader, and Command-Line Arguments, Java provides several
other ways to take input.

1. Console Class
Available in the [Link] package.

import [Link];

class Test {
public static void main(String args[]) {
Console c = [Link]();

String name = [Link]("Enter Name: ");

[Link](name);
}
}

Advantage

• Can securely read passwords using readPassword().

2. DataInputStream
Older method of input.

import [Link].*;

class Test {
public static void main(String args[]) throws Exception {

DataInputStream dis =
new DataInputStream([Link]);

String s = [Link]();

[Link](s);
}
}

Note
• Mostly obsolete.
• Scanner and BufferedReader are preferred.

3. JOptionPane (GUI Input)


Using the Swing library.

import [Link];

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

String name =
[Link]("Enter Name");

[Link](name);
}
}

A dialog box appears for user input.

4. Reading from a File

import [Link].*;
import [Link];

File file = new File("[Link]");


Scanner sc = new Scanner(file);

Input comes from a le instead of the keyboard.

5. Reading from Network Streams


For client-server applications:

Socket socket;
InputStream in =
[Link]();

Input is received from another computer over a network.


fi
Methods Asked in Most Exams
Method Importance
Very High
Scanner

BufferedReader High ⭐
Command-Line
Arguments High ⭐

Console Medium
JOptionPane Medium
DataInputStream Low
File Input Advanced

Escape Sequences and Comments in Java


1. Escape Sequences
Escape sequences are special character combinations that begin with a backslash (\).

They are used inside character and string literals to represent special characters.

Common Escape Sequences

Escape
Meaning
Sequence
\n New Line
\t Horizontal Tab
\b Backspace
Carriage
\r Return
\f Form Feed
\' Single Quote
\" Double Quote
\\ Backslash

Example 1: New Line (\n)

[Link]("Java\nProgramming");
Output:

Java
Programming

Example 2: Tab (\t)

[Link]("Name\tAge");

Output:

Name Age

Example 3: Double Quote (\")

[Link]("He said \"Hello\"");

Output:

He said "Hello"

Example 4: Backslash (\\)

[Link]("C:\\Java\\Programs");

Output:

C:\Java\Programs

2. Comments in Java
Comments are non-executable statements used to explain code.

The compiler ignores comments.

Advantages
• Improves readability
• Helps documentation
• Makes maintenance easier

Types of Comments
1. Single-Line Comment

Begins with //

// This is a single-line comment


int x = 10;

2. Multi-Line Comment

Begins with /* and ends with */

/*
This is a
multi-line comment
*/

3. Documentation Comment (JavaDoc)

Begins with /** and ends with */

/**
* This method displays a message.
*/
void display() {
}

JavaDoc comments can be used to generate program documentation.

Example Program

class Demo {
public static void main(String args[]) {
// Display message

[Link]("Java\nProgramming");

/*
Multi-line
Comment
*/

[Link]("Name\tAge");
}
}

Output:

Java
Programming
Name Age

Difference Between Escape Sequences and Comments


Escape Sequences Comments
Used inside strings/
Used to explain code
characters
Affect program output Ignored by compiler
Start with //, /*, or /
Start with \
**
Example: \n, \t Example: // comment

rogramming Style in Java


Programming Style refers to the way a programmer writes and organizes code to make it readable,
understandable, and maintainable.

A good programming style does not change the program's output, but it makes the code easier to
read and debug.
Importance of Programming Style
• Improves readability
• Makes maintenance easier
• Helps teamwork
• Reduces errors
• Makes debugging simpler

1. Meaningful Identi ers


Use meaningful names for variables, methods, and classes.

Bad

int x;
int y;

Good

int studentAge;
int totalMarks;

2. Proper Indentation
Indent code blocks consistently.

Good

if(age >= 18) {


[Link]("Eligible");
}

Bad

if(age>=18){
[Link]("Eligible");
}

3. Use Comments
fi
Comments explain the purpose of code.

// Calculate total marks


total = m1 + m2 + m3;

4. Follow Naming Conventions


Class Names

Use PascalCase.

class StudentRecord

Variable Names

Use camelCase.

int totalMarks;

Constants

Use uppercase letters.

final double PI = 3.14159;

5. Keep Methods Small


Each method should perform one speci c task.

void displayResult() {
[Link]("Pass");
}

6. Use White Spaces Properly


Good
fi
int sum = a + b;

Bad

int sum=a+b;

7. Avoid Magic Numbers


Instead of:

if(marks >= 35)

Use:

final int PASS_MARKS = 35;

if(marks >= PASS_MARKS)

Example of Good Programming Style

class Student {

private int marks;

public void setMarks(int marks) {


[Link] = marks;
}

public void displayResult() {

if(marks >= 35) {


[Link]("Pass");
} else {
[Link]("Fail");
}
}
}
Programming Style Guidelines Summary
Guideline Purpose
Meaningful names Improves readability
Indentation Makes structure clear
Comments Explains code
Naming
Maintains consistency
conventions
Small methods Easier maintenance
White spaces Better readability
Avoids magic
Constants
numbers

Java is a Strongly Typed Language


De nition
A strongly typed language is a language in which every variable must have a speci c data type,
and the compiler strictly checks type compatibility.

In Java, you must declare the type of a variable before using it.

int age = 25;


String name = "Uday";
double salary = 50000.0;

Why is Java Strongly Typed?


Java enforces strict type checking at:

1. Compile Time
2. Run Time (to some extent)
The compiler ensures that data is used according to its declared type.

Example 1: Correct Usage


fi
fi
int a = 10;
int b = 20;

int sum = a + b;

This is valid because all variables are of type int.

Example 2: Type Mismatch

int a = "Hello";

Compiler Error:

incompatible types

Because a String cannot be stored in an integer variable.

Example 3: Explicit Type Conversion

double d = 10.5;

int x = (int)d;

Output:

10

Java requires explicit casting because it is strongly typed.

Bene ts of Strong Typing


1. Error Detection

Many errors are detected during compilation.

int x = "Java";

The compiler immediately reports an error.


fi
2. Better Reliability

Programs behave more predictably.

3. Improved Security

Prevents invalid operations on data.

4. Easier Maintenance

Type information makes code easier to understand.

Strongly Typed vs Weakly Typed


Strongly Typed
Weakly Typed
(Java)
Strict type checking Flexible type conversion
Fewer runtime errors More runtime surprises
Requires declarations Often allows implicit conversions
Example: JavaScript (in many
Example: Java, C#
cases)

Example

int a = 10;
double b = 20.5;

double result = a + b;

Java automatically promotes int to double in a well-de ned way, maintaining type safety.

Key Point
Java knows the type of every:

• Variable
• Expression
• Method parameter
• Return value
Because of this strict type checking, Java is called a Strongly Typed Language.
fi
Data Types in Java

De nition
A data type speci es:

• What kind of data a variable can store


• How much memory is allocated
• What operations can be performed on the data
Example:

int age = 25;

Here, int is the data type and 25 is the value.

Classi cation of Data Types

Data Types
|
|-------------------|
| |
Primitive Non-Primitive
(Basic) (Reference)

1. Primitive Data Types


Java provides 8 primitive data types.

Data
Size Range
Type
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2³¹ to 2³¹-1
long 8 bytes -2⁶³ to 2⁶³-1
oat 4 bytes Approx. 6–7 decimal digits
Approx. 15–16 decimal
double 8 bytes
digits
char 2 bytes Unicode character
JVM
boolean true or false
dependent
fl
fi
fi
fi
Integer Types
byte

byte age = 25;

Used to save memory.

short

short year = 2025;

int

Most commonly used integer type.

int salary = 50000;

long

long population = 1400000000L;

L indicates a long literal.

Floating-Point Types
oat

float price = 99.99f;

f or F is required.

double
fl
double pi = 3.1415926535;

Default type for decimal values.

Character Type
char

Stores a single Unicode character.

char grade = 'A';

char symbol = '@';

Boolean Type
Stores logical values.

boolean result = true;

Possible values:

true
false

2. Non-Primitive (Reference) Data Types


These store references (addresses) to objects.

Examples:

String

String name = "Uday";

Array

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


Class

Student s = new Student();

Interface

interface Vehicle {
}

Example Program

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

int age = 25;


double salary = 50000.50;
char grade = 'A';
boolean pass = true;

[Link](age);
[Link](salary);
[Link](grade);
[Link](pass);
}
}

Output:

25
50000.5
A
true

Memory Trick
Primitive Types
byte
short
int
long
float
double
char
boolean

BSILFDCB

(Best Students In Labs Find Data Carefully, Boss!)

A Closer Look at Literals in Java


What is a Literal?
A literal is a constant value written directly in a Java program.

Examples:

10
3.14
'A'
"Hello"
true

These values are called literals because their values are xed.

Types of Literals in Java

Literals
|
|-----------------------------|
| | | | |
Integer Float Character String Boolean

1. Integer Literals
Integer literals represent whole numbers.
fi
Decimal (Base 10)

10
25
100

Binary (Base 2)

Pre x: 0b or 0B

0b1010

Value = 10

Octal (Base 8)

Pre x: 0

012

Value = 10

Hexadecimal (Base 16)

Pre x: 0x or 0X

0xA

Value = 10

Long Integer Literal

Add suf x L or l

100000L

Example:

long population = 1400000000L;


fi
fi
fi
fi
2. Floating-Point Literals
Represent numbers with decimal points.

Double Literal (Default)

3.14
10.5

Java treats decimal numbers as double by default.

Float Literal

Add suf x F or f

3.14F

Example:

float price = 99.99F;

Scienti c Notation

1.2e3

Means:

1.2 × 10³ = 1200

Example:

double num = 1.2e3;

3. Character Literals
A single character enclosed in single quotes.
fi
fi
'A'
'B'
'9'
'@'

Example:

char grade = 'A';

Escape Sequence Characters

'\n'
'\t'
'\\'
'\"'

Example:

char ch = '\n';

4. String Literals
A sequence of characters enclosed in double quotes.

"Java"
"Hello World"

Example:

String name = "Uday";

5. Boolean Literals
Only two values:

true
false
Example:

boolean result = true;

Example Program

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

int decimal = 10;


int binary = 0b1010;
int octal = 012;
int hex = 0xA;

float f = 3.14F;
double d = 3.14;

char ch = 'A';

String str = "Java";

boolean flag = true;

[Link](decimal);
[Link](binary);
[Link](octal);
[Link](hex);
}
}

Important Points
Integer Literals

10 // Decimal
0b1010 // Binary
012 // Octal
0xA // Hexadecimal
Floating Literals

3.14
3.14F
1.2e3

Character Literals

'A'
'\n'
'\t'

String Literals

"Java"

Boolean Literals

true
false

Variables in Java
De nition
A variable is a named memory location used to store data that can change during program
execution.

Think of a variable as a container that holds a value.

int age = 25;

• int → Data type


• age → Variable name
• 25 → Value stored in the variable

Syntax
fi
dataType variableName;

Example:

int marks;

or

int marks = 90;

Why Do We Need Variables?


Variables allow us to:

• Store data
• Modify data
• Perform calculations
• Reuse values
Example:

int a = 10;
int b = 20;

int sum = a + b;

Variable Declaration
Declaring a variable means specifying its data type and name.

int age;

double salary;

char grade;
Variable Initialization
Assigning a value to a variable.

int age = 25;

char grade = 'A';

boolean result = true;

Types of Variables in Java


1. Local Variables
Declared inside a method, constructor, or block.

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

int x = 10; // Local Variable

[Link](x);
}
}

Characteristics

• Created when the method starts.


• Destroyed when the method ends.
• Must be initialized before use.

2. Instance Variables
Declared inside a class but outside methods.

class Student {

int rollNo; // Instance Variable


}

Characteristics

• Belong to an object.
• Each object gets its own copy.

3. Static Variables
Declared using the static keyword.

class Student {

static String college = "JNTUK";

Characteristics

• Shared by all objects.


• Only one copy exists.

Example

class Student {

int rollNo; // Instance Variable

static String college = "JNTUK"; // Static Variable

public static void main(String args[]) {

int marks = 90; // Local Variable

[Link](marks);
}
}

Naming Rules
Valid

student
studentName
_age
$salary

Invalid

1student
student name
class

Rules:

• Cannot start with a digit.


• Cannot contain spaces.
• Cannot be a keyword.
• Can contain letters, digits, _, and $.

Variable Scope

class Test {

public static void main(String args[]) {

int x = 10;

[Link](x);
}
}

The variable x is accessible only inside main().

Example Program

class VariableDemo {

public static void main(String args[]) {


int age = 25;
double salary = 50000.50;
char grade = 'A';

[Link](age);
[Link](salary);
[Link](grade);
}
}

Output

25
50000.5
A

Summary
Type Declared In Scope
Local Method/Block Within method
Instanc
Class Object level
e
Class with Shared by all
Static
static objects

Dynamic Initialization in Java


De nition
Dynamic Initialization means initializing a variable at runtime using an expression, calculation,
method call, or user input instead of assigning a xed constant value.

The value is determined when the program executes.

Example 1: Using an Expression

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

int a = 10;
int b = 20;

int sum = a + b; // Dynamic Initialization

[Link](sum);
}
}

Output

30

Here, sum is initialized using the expression a + b.

Example 2: Using a Method Call

class Test {

static int square(int n) {


return n * n;
}

public static void main(String args[]) {

int result = square(5);

[Link](result);
}
}

Output

25

The value of result is determined during execution.

Example 3: Using User Input


import [Link];

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

Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");

int num = [Link]();

[Link](num);
}
}

The value of num is not known until the user enters it at runtime.

Static Initialization vs Dynamic Initialization


Static Initialization

int x = 100;

The value is xed in the source code.

Dynamic Initialization

int x = a + b;

The value is computed during execution.

Real-Life Example

double radius = 7.0;

double area = 3.14159 * radius * radius;

The value of area is calculated at runtime based on the value of radius.


fi
Advantages
• Flexible
• Supports runtime calculations
• Allows user-dependent values
• Makes programs more dynamic and interactive

Scope and Lifetime of Variables in Java


Introduction
Every variable in Java has:

1. Scope → Where the variable can be accessed.


2. Lifetime → How long the variable exists in memory.
Understanding scope and lifetime helps avoid errors and write better programs.

1. Scope of a Variable
Scope is the region of a program where a variable is visible and can be used.

If a variable is outside its scope, it cannot be accessed.

Local Variable Scope


A local variable is declared inside a method or block.

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

int x = 10;

[Link](x);
}
}

Here, x can only be used inside main().

Invalid Example

class Test {
public static void main(String args[]) {
int x = 10;
}

void display() {
[Link](x); // Error
}
}

x is out of scope in display().

Block Scope
Variables declared inside a block {} exist only within that block.

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

if(true) {
int y = 20;
[Link](y);
}

// [Link](y); // Error
}
}

y is visible only inside the if block.

Instance Variable Scope


Instance variables are declared inside a class but outside methods.

class Student {

int rollNo;

void display() {
[Link](rollNo);
}
}
rollNo can be accessed by all instance methods of the class.

Static Variable Scope

class Student {

static String college = "JNTUK";


}

college can be accessed throughout the class and shared by all objects.

2. Lifetime of a Variable
Lifetime refers to the period during which a variable occupies memory.

Lifetime of Local Variables

void show() {
int x = 10;
}

Lifetime

• Created when the method starts.


• Destroyed when the method ends.

Method Starts

Variable Created

Method Ends

Variable Destroyed

Lifetime of Instance Variables

class Student {
int rollNo;
}

Lifetime

• Created when an object is created.


• Exists as long as the object exists.
• Destroyed when the object is garbage collected.

Lifetime of Static Variables

class Student {
static int count;
}

Lifetime

• Created when the class is loaded by the JVM.


• Exists until the program terminates or the class is unloaded.

Example

class Demo {

int a = 10; // Instance Variable

static int b = 20; // Static Variable

public static void main(String args[]) {

int c = 30; // Local Variable

[Link](c);
}
}

Scope and Lifetime

Variabl
Type Scope Lifetime
e
Instanc Until object is
a Entire object
e destroyed
b Static Entire class Until program ends
Inside main()
c Local Until main() ends
only

Memory Diagram

Class Loaded
|
|---- Static Variable (b)
|
Object Created
|
|---- Instance Variable (a)
|
Method Called
|
|---- Local Variable (c)

Important Points
Scope

• Determines where a variable can be used.


Lifetime

• Determines how long a variable exists.


Scope and Lifetime are Different

A variable may have:

• Small scope and short lifetime (local variable)


• Large scope and long lifetime (static variable)

Type Casting in Java


De nition
Type Casting is the process of converting a value from one data type to another data type.

Example:
fi
int x = 10;
double y = x;

Here, int is converted to double.

Why Type Casting?


Different variables may have different data types.

int a = 10;
double b = 20.5;

Sometimes conversion is necessary to perform operations or store values.

Types of Type Casting

Type Casting
|
|-------------------|
| |
Implicit Explicit
(Widening) (Narrowing)

1. Implicit Type Casting (Widening)


Performed automatically by Java.

Smaller → Larger Data Type

byte → short → int → long → float → double



char

Example

class Test {
public static void main(String args[]) {
int x = 100;

double y = x;

[Link](y);
}
}

Output:

100.0

No cast operator is needed.

Another Example

char ch = 'A';

int x = ch;

[Link](x);

Output:

65

Because the Unicode value of 'A' is 65.

2. Explicit Type Casting (Narrowing)


Performed manually by the programmer.

Larger → Smaller Data Type

double → float → long → int → short → byte

Syntax
targetType variable = (targetType)value;

Example

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

double d = 10.75;

int x = (int)d;

[Link](x);
}
}

Output:

10

The fractional part is lost.

Example: int to byte

int num = 130;

byte b = (byte)num;

[Link](b);

Output:

-126

This happens because byte ranges from -128 to 127.

Type Conversion Table


Conversio
From To
n
doubl
int Automatic
e
char int Automatic
doubl
oat Automatic
e
doubl
int Explicit
e
long short Explicit
int byte Explicit

Real Example

float price = 99.99F;

int amount = (int)price;

[Link](amount);

Output:

99

Important Points
Widening Conversion

int x = 50;
double d = x;

Safe conversion.

Narrowing Conversion

double d = 50.5;
int x = (int)d;

Possible loss of data.


fl
Type Casting vs Automatic Promotion
Casting

double d = 20.5;
int x = (int)d;

Programmer forces conversion.

Promotion

int a = 10;
double b = 20.5;

double c = a + b;

Java automatically promotes a to double.

Automatic Type Promotion in Expressions


De nition
Automatic Type Promotion is the process by which Java automatically converts smaller data types
into larger data types when evaluating an expression.

This ensures that calculations are performed without losing data.

Why is Type Promotion Needed?


Consider:

byte a = 10;
byte b = 20;

When Java evaluates:

a + b

the result may be larger than what a byte can store.


fi
Therefore, Java automatically promotes smaller types before performing the operation.

Promotion Rules
Rule 1

All byte, short, and char values are automatically promoted to int when used in
expressions.

byte a = 10;
byte b = 20;

int c = a + b;

Here:

byte → int
byte → int

Result type = int

Rule 2

If one operand is larger, the smaller operand is promoted to the larger type.

byte

short

int

long

float

double

Example 1
int a = 10;
long b = 20;

long c = a + b;

Promotion:

int → long

Result type = long

Example 2

float x = 10.5F;
double y = 20.5;

double z = x + y;

Promotion:

float → double

Result type = double

Example 3

char ch = 'A';

int x = ch + 1;

Promotion:

char → int

Calculation:

65 + 1 = 66

Output:
66

Important Example

byte a = 10;
byte b = 20;

byte c = a + b;

Compiler Error!

Reason:

a → int
b → int

Result = int

Java does not automatically convert the int result back to byte.

Correct:

byte c = (byte)(a + b);

or

int c = a + b;

Mixed-Type Expression Example

byte b = 10;
short s = 20;
int i = 30;
long l = 40;

long result = b + s + i + l;

Promotion:
byte → int
short → int

int + int + int + long



long

Result type = long

Evaluation Order

int a = 5;
double b = 2.5;

double c = a * b;

Promotion:

int → double

5.0 × 2.5

Result:

12.5

Summary Table
Operand Result
Types Type
byte + byte int
short + short int
char + char int
int + long long
long + oat oat
oat + double double
fl
fl
fl
Memory Trick

byte

short

int

long

float

double

"Small types climb upward to the largest type in the expression."

Literal Constants in Java


De nition
A Literal Constant is a xed value written directly in a Java program whose value does not change
during execution.

Examples:

10
3.14
'A'
"Java"
true

These are called literal constants because they represent constant values literally written in the
source code.

Types of Literal Constants


1. Integer Constants
Whole numbers without a decimal point.

Decimal
fi
fi
10
25
100

Binary

0b1010

Octal

012

Hexadecimal

0xA

Long Integer Constant

100000L

Example:

long population = 1400000000L;

2. Floating-Point Constants
Numbers containing a decimal point.

Double Constant (Default)

3.14
25.5

Float Constant

3.14F
Example:

float price = 99.99F;

Scienti c Notation

1.2e3

Means:

1.2 × 10³ = 1200

3. Character Constants
A single character enclosed in single quotes.

'A'
'B'
'9'
'@'

Example:

char grade = 'A';

Escape Character Constants

'\n'
'\t'
'\\'
'\"'

Example:

[Link]("Hello\nJava");

Output:
fi
Hello
Java

4. String Constants
A sequence of characters enclosed in double quotes.

"Java"
"Hello World"

Example:

String name = "Uday";

5. Boolean Constants
Only two values are allowed:

true
false

Example:

boolean pass = true;

Example Program

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

int num = 100;


double pi = 3.14;
char grade = 'A';
String name = "Java";
boolean flag = true;
[Link](num);
[Link](pi);
[Link](grade);
[Link](name);
[Link](flag);
}
}

Output:

100
3.14
A
Java
true

Difference: Literal Constant vs Variable


Literal Constant Variable
Fixed value Value can change
Written directly in Stored in a named memory
code location
Example: 10 Example: int x = 10;

Example:

int x = 10;

• x → Variable
• 10 → Literal Constant

Symbolic Constants in Java

De nition
A Symbolic Constant is a constant value represented by a name (symbol) instead of writing the
literal value repeatedly in the program.

In Java, symbolic constants are created using the final keyword.


fi
Why Use Symbolic Constants?
Instead of writing:

double area = 3.14159 * r * r;

use:

final double PI = 3.14159;

double area = PI * r * r;

Bene ts:

• Improves readability
• Easier maintenance
• Prevents accidental modi cation

Syntax

final dataType CONSTANT_NAME = value;

Example:

final int MAX_MARKS = 100;

Example 1

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

final int MAX_MARKS = 100;

[Link](MAX_MARKS);
}
}

Output:
fi
fi
100

Example 2: Area of Circle

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

final double PI = 3.14159;

double radius = 7;

double area = PI * radius * radius;

[Link](area);
}
}

Cannot Be Changed

final int MAX = 100;

MAX = 200; // Error

Compiler Error:

cannot assign a value to final variable MAX

Once assigned, a symbolic constant cannot be modi ed.

Naming Convention
Symbolic constants are usually written in UPPERCASE.

final int MAX_SIZE = 50;


final double PI = 3.14159;
final String COLLEGE_NAME = "JNTUK";
fi
Literal Constant vs Symbolic Constant
Literal Constant Symbolic Constant
100 MAX_MARKS
3.14 PI
Value written Value represented by a
directly name
Harder to maintain Easier to maintain

Example:

final int MAX_MARKS = 100;

int marks = MAX_MARKS;

Here:

• 100 → Literal Constant


• MAX_MARKS → Symbolic Constant

Advantages
1. Improves program readability
2. Makes code easier to modify
3. Prevents accidental changes
4. Reduces errors
5. Follows good programming style

Formatted Output with printf() Method


in Java
Introduction
The printf() method is used to display output in a formatted manner.

It belongs to the standard output stream:

[Link]();
Unlike print() and println(), printf() allows you to control:

• Width
• Precision
• Alignment
• Data format

Syntax

[Link]("format string", values);

Example:

[Link]("Age = %d", 25);

Output:

Age = 25

Common Format Speci ers


Speci e
Meaning
r
%d Integer
Floating-point
%f number
%c Character
%s String
%b Boolean
%n New line
%% Prints %

Example 1: Integer

[Link]("Marks = %d", 90);

Output:
fi
fi
Marks = 90

Example 2: Floating Point

[Link]("Price = %f", 99.99);

Output:

Price = 99.990000

By default, %f prints 6 digits after the decimal point.

Example 3: Character

[Link]("Grade = %c", 'A');

Output:

Grade = A

Example 4: String

[Link]("Name = %s", "Uday");

Output:

Name = Uday

Example 5: Boolean

[Link]("Result = %b", true);

Output:
Result = true

Precision
Two Decimal Places

double pi = 3.141592;

[Link]("%.2f", pi);

Output:

3.14

Three Decimal Places

[Link]("%.3f", pi);

Output:

3.142

Field Width

[Link]("%5d", 10);

Output:

10

The number occupies a total width of 5 characters.

Left Alignment

[Link]("%-10s", "Java");
Output:

Java

- means left-align within the eld width.

Multiple Values

String name = "Uday";


int age = 25;

[Link]("Name: %s Age: %d", name, age);

Output:

Name: Uday Age: 25

Table Format Example

[Link]("%-10s %5s%n", "Name", "Marks");


[Link]("%-10s %5d%n", "Uday", 95);
[Link]("%-10s %5d%n", "Ravi", 88);

Output:

Name Marks
Uday 95
Ravi 88

Difference Between print(), println(), and


printf()
Method Description
print() Prints output on the same line
fi
println( Prints output and moves to the next
) line
printf() Prints formatted output

Example:

[Link]("Java");
[Link](" Programming");
[Link]("Marks = %d", 90);

Complete Example

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

String name = "Uday";


int marks = 95;
double percentage = 92.75;

[Link]("Name: %s%n", name);


[Link]("Marks: %d%n", marks);
[Link]("Percentage: %.2f%n", percentage);
}
}

Output:

Name: Uday
Marks: 95
Percentage: 92.75

Static Variables and Methods in Java


Introduction
The static keyword is used to create variables and methods that belong to the class rather than
to individual objects.

Normally, instance variables belong to each object, but static members are shared by all objects of
the class.
1. Static Variables
A static variable is declared using the static keyword.

Syntax

static dataType variableName;

Example

class Student {

static String college = "JNTUK";

String name;
}

Here, college is shared by all Student objects.

Memory Concept

Student Class
|
|---- college = "JNTUK" (one copy)

Student s1
|
|---- name = "Uday"

Student s2
|
|---- name = "Ravi"

Only one copy of college exists.

Example Program

class Student {
static String college = "JNTUK";

String name;

Student(String n) {
name = n;
}

void display() {
[Link](name + " " + college);
}

public static void main(String args[]) {

Student s1 = new Student("Uday");


Student s2 = new Student("Ravi");

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

Output

Uday JNTUK
Ravi JNTUK

2. Static Methods
A static method belongs to the class and can be called without creating an object.

Syntax

static returnType methodName() {


// code
}

Example
class Demo {

static void show() {


[Link]("Static Method");
}

public static void main(String args[]) {

[Link]();
}
}

Output

Static Method

Why is main() Static?

public static void main(String args[])

The JVM calls main() before creating any objects.

Therefore, main() must be static.

Static Method Restrictions


A static method can directly access:

✅ Static variables

✅ Other static methods

A static method cannot directly access:

❌ Instance variables

❌ Instance methods

Example
class Test {

int x = 10;
static int y = 20;

static void show() {

[Link](y);

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

Static Block
A static block executes when the class is loaded.

class Demo {

static {
[Link]("Static Block Executed");
}

public static void main(String args[]) {


[Link]("Main Method");
}
}

Output

Static Block Executed


Main Method

Static Variable vs Instance Variable


Static Variable Instance Variable
Belongs to class Belongs to object
One copy shared by all
Separate copy for each object
objects
Created when object is
Loaded when class loads
created
Accessed using class name Accessed using object

Static Method vs Instance Method


Static Method Instance Method
Belongs to class Belongs to object
Called without object Requires object
Can access only static members Can access both static and instance
directly members
Memory ef cient Object dependent

Advantages of Static Members


1. Memory saving
2. Shared data among all objects
3. Utility methods can be called directly
4. No need to create unnecessary objects

Example: Counter

class Counter {

static int count = 0;

Counter() {
count++;
}

public static void main(String args[]) {

new Counter();
new Counter();
new Counter();

[Link]("Objects = " + count);


}
}

Output
fi
Objects = 3

The static variable count is shared by all objects.

Final Attribute (Final Variable) in Java


Introduction
The final keyword is used to make a variable constant.

Once a value is assigned to a final variable, it cannot be changed.

Such variables are called Final Attributes or Constants.

Syntax

final dataType variableName = value;

Example:

final int MAX_MARKS = 100;

Example 1: Final Variable

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

final int MAX = 100;

[Link](MAX);
}
}

Output:
100

Example 2: Modi cation Not Allowed

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

final int MAX = 100;

MAX = 200; // Error


}
}

Compiler Error:

cannot assign a value to final variable MAX

Final Instance Attribute

class Student {

final String COLLEGE = "JNTUK";

void display() {
[Link](COLLEGE);
}
}

Every object has the same xed value for COLLEGE.

Blank Final Variable


A nal variable can be declared rst and initialized later, but only once.

class Test {

final int x;
fi
fi
fi
fi
Test() {
x = 10;
}
}

After assignment, x cannot be changed.

Final and Static Together

class Circle {

static final double PI = 3.14159;


}

• static → One copy for the entire class.


• final → Value cannot change.
This is the common way to de ne constants.

Naming Convention
Final constants are usually written in uppercase.

final int MAX_SIZE = 100;


final double PI = 3.14159;
final String COLLEGE_NAME = "JNTUK";

Advantages of Final Attributes


1. Prevent accidental modi cation.
2. Improve program reliability.
3. Make code easier to understand.
4. Useful for xed values such as:
◦ PI
◦ Maximum marks
◦ Tax rate
◦ Company name

Final Variable vs Normal Variable


Normal Variable Final Variable
fi
fi
fi
Value can change Value cannot change
Mutable Constant
No final Declared using
keyword final

Example:

int age = 25;


age = 26; // Allowed

final int MAX = 100;


// MAX = 200; // Not Allowed

Introduction to Operators in Java


What is an Operator?
An Operator is a special symbol that performs a speci c operation on one or more operands
(values or variables).

Example

int a = 10;
int b = 20;

int c = a + b;

Here:

• a and b are operands


• + is the operator
Result:

30

Types of Operators in Java

Operators
fi
|
|----------------------------------|
| | | | |
Arithmetic Relational Logical Bitwise Assignment
|
Conditional

1. Arithmetic Operators
Used for mathematical calculations.

Operato
Meaning
r
+ Addition
- Subtraction
* Multiplication
/ Division
Modulus
% (Remainder)

Example

int a = 10;
int b = 3;

[Link](a + b); // 13
[Link](a - b); // 7
[Link](a * b); // 30
[Link](a / b); // 3
[Link](a % b); // 1

2. Relational Operators
Used to compare values.
Operato
Meaning
r
Equal to
!= Not Equal to
> Greater than
< Less than
Greater than or
>= Equal
<= Less than or Equal

Example

int a = 10;
int b = 20;

[Link](a < b);

Output:

true

3. Logical Operators
Used with boolean values.

Operato
Meaning
r
Logical
&& AND
`
Logical
! NOT

Example

boolean a = true;
boolean b = false;

[Link](a && b);

Output:
false

4. Assignment Operators
Used to assign values.

Operato Exampl
r e
= a = 10
+= a += 5
-= a -= 5
*= a *= 5
/= a /= 5
%= a %= 5

Example

int a = 10;

a += 5;

[Link](a);

Output:

15

5. Increment and Decrement Operators


Increment (++)

int a = 5;
a++;

Result:

6
Decrement (--)

int a = 5;
a--;

Result:

6. Conditional (Ternary) Operator


Syntax:

condition ? value1 : value2

Example:

int a = 10;
int b = 20;

int max = (a > b) ? a : b;

Output:

20

7. Bitwise Operators
Operate on individual bits.

Operato
Meaning
r
& Bitwise AND
` `
^ Bitwise XOR
Bitwise
~ Complement
<< Left Shift
>> Right Shift
Unsigned Right
>>> Shift

Example:

int a = 5;
int b = 3;

[Link](a & b);

Output:

Example Program

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

int a = 10;
int b = 5;

[Link]("Addition = " + (a+b));


[Link]("Greater = " + (a>b));
[Link]("AND = " + (a>b && b>0));
}
}

Output:

Addition = 15
Greater = true
AND = true

Operator Categories Summary


Category Operators
Arithmetic + - * / %
Relational
Logical `&&
Assignment
Increment/
Decrement
++ --
Conditional ?:
Bitwise `&

Assignment Operators in Java

Introduction
Assignment Operators are used to assign values to variables.

The basic assignment operator is:

Java also provides compound assignment operators, which combine an arithmetic or bitwise
operation with assignment.

1. Simple Assignment Operator (=)


Assigns a value to a variable.

int a = 10;

Here, 10 is assigned to a.

2. Compound Assignment Operators


Operato
Meaning Example
r
a +=
+= Add and assign
5
a -=
-= Subtract and assign
5
Multiply and a *=
*= assign 5
a /=
/= Divide and assign
5
Modulus and a %=
%= assign 5

Addition Assignment (+=)

int a = 10;

a += 5;

Equivalent to:

a = a + 5;

Output:

15

Subtraction Assignment (-=)

int a = 10;

a -= 3;

Equivalent to:

a = a - 3;

Output:

Multiplication Assignment (*=)


int a = 10;

a *= 2;

Equivalent to:

a = a * 2;

Output:

20

Division Assignment (/=)

int a = 20;

a /= 4;

Equivalent to:

a = a / 4;

Output:

Modulus Assignment (%=)

int a = 10;

a %= 3;

Equivalent to:

a = a % 3;
Output:

Bitwise Assignment Operators


Operato
Equivalent To
r
&= a = a & b
`
^= a = a ^ b
<<= a = a << n
>>= a = a >> n
a = a >>>
>>>=
n

Example: Bitwise AND Assignment

int a = 5;

a &= 3;

Equivalent to:

a = a & 3;

Output:

Advantage of Compound Assignment


Instead of writing:

a = a + 10;

you can write:


a += 10;

Bene ts:

• Shorter code
• Better readability
• Faster to write

Special Feature

byte b = 10;

b += 5;

This is valid.

But:

byte b = 10;

b = b + 5;

causes a compile-time error because b + 5 is promoted to int.

Compound assignment automatically performs the required cast.

Example Program

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

int a = 10;

a += 5;
[Link](a);

a *= 2;
[Link](a);

a -= 10;
[Link](a);
}
fi
}

Output:

15
30
20

Summary Table

Operator Example Equivalent

= a = 10 Assign value

+= a += 5 a = a + 5

-= a -= 5 a = a - 5

*= a *= 5 a = a * 5

/= a /= 5 a = a / 5

%= a %= 5 a = a % 5

Arithmetic Operators in Java

Introduction
Arithmetic Operators are used to perform mathematical calculations on numeric values.

They operate on operands (variables or constants) and produce a result.

Example:

int a = 10;
int b = 5;
int c = a + b;

Here:

• a and b are operands


• + is the arithmetic operator

Types of Arithmetic Operators


Operato Exampl
Meaning
r e
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
Modulus
% (Remainder)
a % b
++ Increment a++
-- Decrement a--

1. Addition Operator (+)


Adds two operands.

int a = 10;
int b = 20;

[Link](a + b);

Output:

30

2. Subtraction Operator (-)


Subtracts one operand from another.

int a = 20;
int b = 10;
[Link](a - b);

Output:

10

3. Multiplication Operator (*)


Multiplies two operands.

int a = 10;
int b = 5;

[Link](a * b);

Output:

50

4. Division Operator (/)


Divides one operand by another.

int a = 20;
int b = 5;

[Link](a / b);

Output:

Integer Division

[Link](10 / 3);

Output:
3

The fractional part is discarded because both operands are integers.

5. Modulus Operator (%)


Returns the remainder after division.

[Link](10 % 3);

Output:

Calculation:

10 ÷ 3 = 3 remainder 1

6. Increment Operator (++)


Increases a variable's value by 1.

int a = 5;

a++;

[Link](a);

Output:

Equivalent to:

a = a + 1;

7. Decrement Operator (--)


Decreases a variable's value by 1.

int a = 5;

a--;

[Link](a);

Output:

Equivalent to:

a = a - 1;

Special Use of +
For Strings, + performs concatenation.

String name = "Uday";

[Link]("Hello " + name);

Output:

Hello Uday

Example Program

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

int a = 10;
int b = 3;

[Link]("Addition = " + (a+b));


[Link]("Subtraction = " + (a-b));
[Link]("Multiplication = " + (a*b));
[Link]("Division = " + (a/b));
[Link]("Remainder = " + (a%b));
}
}

Output:

Addition = 13
Subtraction = 7
Multiplication = 30
Division = 3
Remainder = 1

Important Points
1. Arithmetic operators work on numeric data types.
2. / performs integer division when both operands are integers.
3. % returns the remainder.
4. ++ and -- change the value by one.
5. + is also used for string concatenation.

Increment (++) and Decrement (--) Operators in Java

Introduction
The Increment (++) and Decrement (--) operators are unary operators because they operate on
only one operand.

• ++ increases a variable's value by 1


• -- decreases a variable's value by 1

Increment Operator (++)


Syntax

variable++;
or

++variable;

Example

int a = 10;

a++;

[Link](a);

Output:

11

Equivalent to:

a = a + 1;

Decrement Operator (--)


Syntax

variable--;

or

--variable;

Example

int a = 10;

a--;

[Link](a);
Output:

Equivalent to:

a = a - 1;

Types of Increment and Decrement


There are two forms:

1. Pre x
2. Post x

1. Pre x Increment (++a)


First increment the value, then use it.

Example

int a = 5;

int b = ++a;

[Link](a);
[Link](b);

Execution

a = 5
++a → 6
b = 6

Output:

6
6
fi
fi
fi
2. Post x Increment (a++)
First use the value, then increment it.

Example

int a = 5;

int b = a++;

[Link](a);
[Link](b);

Execution

a = 5
b = 5
a becomes 6

Output:

6
5

Pre x Decrement (--a)


First decrement the value, then use it.

int a = 5;

int b = --a;

Output:

a = 4
b = 4

Post x Decrement (a--)


fi
fi
fi
First use the value, then decrement it.

int a = 5;

int b = a--;

Output:

a = 4
b = 5

Comparison Table
Operato
Action
r
++a Increment rst, then use
a++ Use rst, then increment
Decrement rst, then
--a use
Use rst, then
a-- decrement

Example Program

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

int a = 10;

[Link](++a); // 11

[Link](a++); // 11

[Link](a); // 12
}
}

Output:

11
fi
fi
fi
fi
11
12

Trace Example

int x = 5;

int y = x++ + ++x;

Step-by-Step

x = 5

x++ → use 5, then x = 6

++x → x = 7, use 7

y = 5 + 7 = 12

Final Values:

x = 7
y = 12

Important Points
1. ++ increases by 1.
2. -- decreases by 1.
3. Pre x changes the value before use.
4. Post x changes the value after use.
5. Frequently used in loops.
Example:

for(int i = 1; i <= 5; i++)


{
[Link](i);
}
fi
fi
Ternary Operator (?:) in Java

Introduction
The Ternary Operator is a shorthand form of the if-else statement.

It is the only operator in Java that takes three operands.

Syntax

condition ? expression1 : expression2;

Meaning

• If the condition is true, expression1 is executed.


• If the condition is false, expression2 is executed.

Basic Example

int a = 10;
int b = 20;

int max = (a > b) ? a : b;

[Link](max);

Output:

20

Equivalent if-else Statement

int max;

if(a > b)
max = a;
else
max = b;
The ternary operator performs the same task in a shorter form.

Example 1: Find Largest Number

int a = 50;
int b = 30;

int largest = (a > b) ? a : b;

[Link]("Largest = " + largest);

Output:

Largest = 50

Example 2: Even or Odd

int num = 8;

String result = (num % 2 == 0) ? "Even" : "Odd";

[Link](result);

Output:

Even

Example 3: Pass or Fail

int marks = 40;

String result = (marks >= 35) ? "Pass" : "Fail";

[Link](result);

Output:
Pass

Nested Ternary Operator


Used for multiple conditions.

int a = 10;
int b = 20;
int c = 15;

int max = (a > b)


? ((a > c) ? a : c)
: ((b > c) ? b : c);

[Link](max);

Output:

20

Flow Diagram

Condition
|
True / \ False
/ \
Expression1 Expression2

Advantages
1. Shorter than if-else
2. Improves code compactness
3. Useful for simple decisions
4. Returns a value directly

Disadvantages
1. Can reduce readability when nested deeply.
2. Not suitable for complex logic.
Example Program

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

int age = 20;

String status = (age >= 18)


? "Eligible to Vote"
: "Not Eligible";

[Link](status);
}
}

Output:

Eligible to Vote

Comparison: if-else vs Ternary


if-else

if(age >= 18)


status = "Eligible";
else
status = "Not Eligible";

Ternary

status = (age >= 18)


? "Eligible"
: "Not Eligible";

Relational Operators in Java


Introduction
Relational Operators are used to compare two values or expressions.

The result of a relational operation is always a boolean value:

true

or

false

They are commonly used in:

• if statements
• Loops (for, while)
• Conditional expressions
• Decision-making programs

Types of Relational Operators


Operato
Meaning
r
Equal to
!= Not Equal to
> Greater Than
< Less Than
Greater Than or Equal
>= To
<= Less Than or Equal To

1. Equal To (==)
Checks whether two values are equal.

int a = 10;
int b = 10;

[Link](a == b);

Output:
true

2. Not Equal To (!=)


Checks whether two values are different.

int a = 10;
int b = 20;

[Link](a != b);

Output:

true

3. Greater Than (>)


Checks whether the left operand is greater than the right operand.

int a = 20;
int b = 10;

[Link](a > b);

Output:

true

4. Less Than (<)


Checks whether the left operand is less than the right operand.

int a = 10;
int b = 20;

[Link](a < b);


Output:

true

5. Greater Than or Equal To (>=)

int a = 20;
int b = 20;

[Link](a >= b);

Output:

true

Because a is equal to b.

6. Less Than or Equal To (<=)

int a = 10;
int b = 20;

[Link](a <= b);

Output:

true

Example Program

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

int a = 10;
int b = 20;
[Link](a == b);
[Link](a != b);
[Link](a > b);
[Link](a < b);
[Link](a >= b);
[Link](a <= b);
}
}

Output:

false
true
false
true
false
true

Using Relational Operators in if Statement

int marks = 40;

if(marks >= 35)


{
[Link]("Pass");
}

Output:

Pass

Important Difference
Assignment Operator (=)

a = 10;

Means:
Assign 10 to a

Relational Operator (==)

a == 10

Means:

Check whether a equals 10

This is a very common exam and interview question.

Comparison Example

int x = 5;
int y = 8;

boolean result = x < y;

[Link](result);

Output:

true

Boolean Logical Operators in Java


Introduction
Boolean Logical Operators are used to perform logical operations on boolean values (true or
false).

They are commonly used in:

• if statements
• Loops
• Decision-making
• Conditional expressions
The result of a logical operation is always:

true

or

false

Types of Boolean Logical Operators


Operato
Meaning
r
&& Logical AND
`
! Logical NOT
& Boolean AND
` `
Boolean XOR (Exclusive
^ OR)

1. Logical AND (&&)


Returns true only if both operands are true.

Truth Table

A &&
A B
B
TRUETRUETRUE
TRUEFALSE
FALSE
FALSE
TRUEFALSE
FALSE
FALSE
FALSE

Example

boolean a = true;
boolean b = false;

[Link](a && b);

Output:

false

2. Logical OR (||)
Returns true if at least one operand is true.

Truth Table

A ||
A B
B
TRUETRUETRUE
TRUEFALSE
TRUE
FALSE
TRUETRUE
FALSE
FALSE
FALSE

Example

boolean a = true;
boolean b = false;

[Link](a || b);

Output:

true
3. Logical NOT (!)
Reverses the boolean value.

Truth Table

A !A
TRUEFALSE
FALSE
TRUE

Example

boolean a = true;

[Link](!a);

Output:

false

4. Boolean AND (&)


When used with boolean values, it behaves like logical AND.

boolean a = true;
boolean b = false;

[Link](a & b);

Output:

false

Difference from &&

• && uses short-circuit evaluation


• & evaluates both operands always
5. Boolean OR (|)
When used with booleans, it behaves like logical OR.

boolean a = true;
boolean b = false;

[Link](a | b);

Output:

true

6. Boolean XOR (^)


Returns true only when operands are different.

Truth Table

A^
A B
B
TRUETRUEFALSE
TRUEFALSE
TRUE
FALSE
TRUETRUE
FALSE
FALSE
FALSE

Example

boolean a = true;
boolean b = false;

[Link](a ^ b);

Output:

true
Short-Circuit Logical Operators
&& (Short-Circuit AND)

int x = 10;

if(x != 0 && (20 / x) > 1)


{
[Link]("Valid");
}

If the rst condition is false, Java does not evaluate the second condition.

|| (Short-Circuit OR)

boolean a = true;

if(a || someMethod())
{
[Link]("Executed");
}

Since a is already true, Java skips evaluating someMethod().

Example Program

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

boolean a = true;
boolean b = false;

[Link]("AND = " + (a && b));


[Link]("OR = " + (a || b));
[Link]("NOT = " + (!a));
[Link]("XOR = " + (a ^ b));
}
}
fi
Output:

AND = false
OR = true
NOT = false
XOR = true

Summary Table
Operato
Meaning Result
r
&& Logical AND True if both are true
` `
! Logical NOT Reverses value
Boolean Evaluates both
& AND operands
` ` Boolean OR
Boolean
^ XOR
True if operands differ

How to Convert a Decimal Number to Binary


Method 1: Repeated Division by 2
Divide the number by 2 repeatedly and write down the remainders.

Example: Convert 13 to Binary

13 ÷ 2 = 6 remainder 1
6 ÷ 2 = 3 remainder 0
3 ÷ 2 = 1 remainder 1
1 ÷ 2 = 0 remainder 1

Read the remainders from bottom to top:

13₁₀ = 1101₂
Example: Convert 25 to Binary

25 ÷ 2 = 12 remainder 1
12 ÷ 2 = 6 remainder 0
6 ÷ 2 = 3 remainder 0
3 ÷ 2 = 1 remainder 1
1 ÷ 2 = 0 remainder 1

Read bottom to top:

25₁₀ = 11001₂

Shortcut Using Powers of 2


Convert 10 to binary:

10 = 8 + 2

8 4 2 1
1 0 1 0

Therefore:

10₁₀ = 1010₂

Bitwise Logical Operators in Java

Introduction
Bitwise Operators perform operations directly on the binary (bit) representation of integer values.

They operate bit by bit.

Example:

int a = 5;
int b = 3;
Binary values:

5 = 0101
3 = 0011

Bitwise operations are performed on these bits.

Types of Bitwise Logical Operators


Operato
Name
r
& Bitwise AND
` `
^ Bitwise XOR
Bitwise Complement
~ (NOT)

1. Bitwise AND (&)


Returns 1 only if both bits are 1.

Example

int a = 5;
int b = 3;

[Link](a & b);

Binary:

0101 (5)
& 0011 (3)
-------
0001 (1)

Output:

1
2. Bitwise OR (|)
Returns 1 if at least one bit is 1.

Example

int a = 5;
int b = 3;

[Link](a | b);

Binary:

0101
| 0011
-------
0111

Output:

3. Bitwise XOR (^)


Returns 1 when bits are different.

Example

int a = 5;
int b = 3;

[Link](a ^ b);

Binary:

0101
^ 0011
-------
0110
Output:

4. Bitwise Complement (~)


Reverses all bits.

Example

int a = 5;

[Link](~a);

Binary (32-bit representation simpli ed):

5 = 00000101

~5 = 11111010

Output:

-6

Formula

~n = -(n + 1)

Example:

~5 = -(5 + 1)
= -6

Truth Tables

Bitwise AND (&)


fi
A&
AB
B
0 0 0
0 1 0
1 0 0
1 1 1

Bitwise OR (|)
A|
AB
B
0 0 0
0 1 1
1 0 1
1 1 1

Bitwise XOR (^)


A^
AB
B
0 0 0
0 1 1
1 0 1
1 1 0

Example Program

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

int a = 5;
int b = 3;

[Link]("AND = " + (a & b));


[Link]("OR = " + (a | b));
[Link]("XOR = " + (a ^ b));
[Link]("NOT = " + (~a));
}
}
Output:

AND = 1
OR = 7
XOR = 6
NOT = -6

Applications of Bitwise Operators


• Masking bits
• Setting and clearing ags
• Encryption algorithms
• Device drivers
• Low-level system programming
• Performance optimization

Difference: Logical vs Bitwise Operators


Logical Operators Bitwise Operators
Work on boolean Work on bits of
values integers
&&, `
Result is boolean Result is numeric

Common Conversions
Decimal Binary
fl
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010
11 1011
12 1100
13 1101
14 1110
15 1111

In Java
Convert a decimal number to binary:

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

int n = 13;

[Link]([Link](n));
}
}

Output:

1101

Exam Tip

For bitwise operators, remember:

5 = 0101
3 = 0011
5 & 3 = 0001 = 1
5 | 3 = 0111 = 7
5 ^ 3 = 0110 = 6

Summary Table
Operator Example Result
10 == 10 TRUE
!= 10 != 20 TRUE
> 20 > 10 TRUE
< 10 < 20 TRUE
>= 20 >= 20 TRUE
<= 10 <= 20 TRUE

Left Shift (<<) and Right Shift (>>) Operators


in Java
Introduction
Shift operators move the bits of a number to the left or right.

Java provides:
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift

1. Left Shift Operator (<<)


Moves all bits to the left by the speci ed number of positions.

Syntax

number << n

Means: shift bits left by n positions.

Example: 5 << 1
Step 1: Convert 5 to Binary

5 = 00000101

Step 2: Shift Left by 1

00000101
<< 1
---------
00001010

Step 3: Convert Back to Decimal

00001010 = 10

Result:

5 << 1 = 10

Example: 5 << 2
fi
00000101
<< 2
---------
00010100

Decimal:

20

Result:

5 << 2 = 20

Shortcut

n << k = n × 2ᵏ

Examples:

5 << 1 = 5 × 2 = 10
5 << 2 = 5 × 4 = 20
5 << 3 = 5 × 8 = 40

2. Right Shift Operator (>>)


Moves all bits to the right.

Syntax

number >> n

Means: shift bits right by n positions.

Example: 20 >> 1
Binary of 20
20 = 00010100

Shift Right by 1

00010100
>> 1
---------
00001010

Decimal:

10

Result:

20 >> 1 = 10

Example: 20 >> 2

00010100
>> 2
---------
00000101

Decimal:

Result:

20 >> 2 = 5

Shortcut

n >> k = n ÷ 2ᵏ
Examples:

20 >> 1 = 20 ÷ 2 = 10
20 >> 2 = 20 ÷ 4 = 5
20 >> 3 = 20 ÷ 8 = 2

(Integer division applies.)

Java Program

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

[Link](5 << 1);


[Link](5 << 2);

[Link](20 >> 1);


[Link](20 >> 2);
}
}

Output:

10
20
10
5

Unsigned Right Shift (>>>)


Shifts bits right and lls leftmost positions with 0.

Example:

[Link](20 >>> 2);

Output:

5
fi
For positive numbers, >> and >>> usually give the same result.

Summary Table
Expression Result
5 << 1 10
5 << 2 20
5 << 3 40
20 >> 1 10
20 >> 2 5
20 >> 3 2

Memory Trick
Left Shift

<<
Multiply by 2

n << k = n × 2ᵏ

Right Shift

>>
Divide by 2

n >> k = n ÷ 2ᵏ

Unsigned Right Shift Operator (>>>) in Java


Introduction
The Unsigned Right Shift Operator (>>>) shifts the bits of a number to the right.
Unlike the normal right shift operator (>>), it always lls the leftmost positions with 0s.

Syntax

number >>> n

where n is the number of bit positions to shift.

Difference Between >> and >>>


Signed Right Shift (>>)

• Preserves the sign bit.


• If the number is negative, leftmost bits are lled with 1.
Unsigned Right Shift (>>>)

• Does not preserve the sign.


• Leftmost bits are always lled with 0.

Example with Positive Number

int x = 20;

[Link](x >> 2);


[Link](x >>> 2);

Binary:

20 = 00010100

After shifting right by 2:

00000101

Output:

5
5
fi
fi
fi
For positive numbers, >> and >>> usually produce the same result.

Example with Negative Number

int x = -8;

[Link](x >> 1);


[Link](x >>> 1);

Binary Representation of -8 (32-bit)

11111111 11111111 11111111 11111000

Using >> 1

11111111 11111111 11111111 11111100

Result:

-4

The sign bit (1) is preserved.

Using >>> 1

01111111 11111111 11111111 11111100

Result:

2147483644

The leftmost bit is lled with 0, making the number positive.

Java Program
fi
class ShiftDemo {
public static void main(String args[]) {

int x = -8;

[Link](">> = " + (x >> 1));


[Link](">>> = " + (x >>> 1));
}
}

Output:

>> = -4
>>> = 2147483644

Visual Comparison

x = -8

Binary:
11111111 11111111 11111111 11111000

x >> 1
11111111 11111111 11111111 11111100
(Sign bit preserved)

x >>> 1
01111111 11111111 11111111 11111100
(Zero filled)

Key Points
1. >> = Signed Right Shift.
2. >>> = Unsigned Right Shift.
3. >>> always inserts 0 on the left.
4. Difference is noticeable mainly for negative numbers.
5. Used in low-level bit manipulation and networking applications.

Memory Trick
>>
Keeps Sign

>>>
Zeros on Left

Think:

>>> = Zero-fill Right Shift

Precedence and Associativity of Operators in


Java
Introduction
When an expression contains multiple operators, Java needs rules to decide:

1. Which operator is evaluated rst → Precedence


2. In which direction operators of the same precedence are evaluated → Associativity

1. Operator Precedence
Precedence determines the priority of operators.

Operators with higher precedence are evaluated before operators with lower precedence.

Example

int result = 10 + 20 * 3;

Evaluation

10 + 20 * 3

20 * 3 = 60

10 + 60 = 70
fi
Output:

70

Because * has higher precedence than +.

Using Parentheses
Parentheses have the highest precedence.

int result = (10 + 20) * 3;

Evaluation

(10 + 20) = 30

30 * 3 = 90

Output:

90

2. Associativity
When operators have the same precedence, associativity decides the order of evaluation.

Left-to-Right Associativity
Example:

20 / 5 * 2

Evaluation:

20 / 5 = 4

4 * 2 = 8
Output:

Because / and * have the same precedence and are evaluated left to right.

Right-to-Left Associativity
Assignment operators use right-to-left associativity.

int a, b, c;

a = b = c = 10;

Evaluation:

c = 10

b = 10

a = 10

Precedence Table (High to Low)


Associativit
Precedence Operators
y
Highest () [] . Left to Right
Unary ++ -- + - ! ~ Right to Left
Multiplicativ
e
* / % Left to Right

Additive + - Left to Right


Shift << >> >>> Left to Right
< > <= >=
Relational Left to Right
instanceof
Equality Left to Right
Bitwise AND & Left to Right
Bitwise XOR ^ Left to Right
Bitwise OR ` `
Logical AND && Left to Right
Logical OR `
Ternary ?: Right to Left
Assignment Right to Left

Example 1

int x = 10 + 5 * 2;

Evaluation:

5 * 2 = 10

10 + 10 = 20

Output:

20

Example 2

boolean result = 10 > 5 && 20 > 15;

Evaluation:

10 > 5 → true

20 > 15 → true

true && true → true

Output:

true
Example 3

int x = 10;

int y = ++x * 2;

Evaluation:

++x → 11

11 * 2 = 22

Output:

22

Memory Trick

P → Precedence = Priority

A → Associativity = Direction

Priority Order

()
Unary
* / %
+ -
<< >>
< >
==
&
^
|
&&
||
?:
=
Important Exam Point
Expression

int x = 10 + 20 * 5;

Output:

110

Because:

20 * 5 = 100

10 + 100 = 110

Control Statements: Introduction


What are Control Statements?
Control Statements determine the order in which program statements are executed.

Normally, Java executes statements sequentially:

Statement 1
Statement 2
Statement 3

Sometimes we need to:

• Make decisions
• Repeat statements
• Jump to another part of the program
For this purpose, Java provides Control Statements.
Why Control Statements?
Without control statements:

[Link]("Step 1");
[Link]("Step 2");
[Link]("Step 3");

Execution is always sequential.

With control statements, execution can change based on conditions.

Example:

if(age >= 18)


{
[Link]("Eligible to Vote");
}

Categories of Control Statements

Control Statements
|
-------------------
| | |
Selection Iteration Jump

1. Selection Statements (Decision Making)


Used to choose one path from multiple alternatives.

Types

if
if-else
if-else-if ladder
switch
Example

int age = 20;

if(age >= 18)


{
[Link]("Adult");
}

Output:

Adult

2. Iteration Statements (Looping)


Used to execute a block of code repeatedly.

Types

while
do-while
for

Example

for(int i = 1; i <= 5; i++)


{
[Link](i);
}

Output:

1
2
3
4
5

3. Jump Statements
Used to transfer control from one part of the program to another.

Types

break
continue
return

Example

for(int i = 1; i <= 10; i++)


{
if(i == 5)
break;

[Link](i);
}

Output:

1
2
3
4

Flow of Control
Sequential Execution

Statement 1

Statement 2

Statement 3

Selection Execution

Condition
|
True/False
/ \
Block1 Block2

Iteration Execution

Condition
|
True
|
Statements
|

False
|
Exit

Example Program

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

int marks = 70;

if(marks >= 35)


[Link]("Pass");

for(int i = 1; i <= 3; i++)


[Link](i);
}
}

Output:

Pass
1
2
3
Summary Table
Categor
Statements
y
Selection if, if-else, switch
Iteration for, while, do-while
break, continue,
Jump
return

The if Statement in Java


Introduction
The if statement is the simplest decision-making statement in Java.

It is used to execute a block of code only when a condition is true.

Syntax

if(condition)
{
// statements
}

Working

• If the condition is true → statements execute.


• If the condition is false → statements are skipped.

Flowchart

Condition
|
True / \ False
/ \
Statements Skip

Example 1: Check Eligibility


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

int age = 20;

if(age >= 18)


{
[Link]("Eligible to Vote");
}
}
}

Output:

Eligible to Vote

Because:

20 >= 18 → true

Example 2: Condition False

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

int age = 15;

if(age >= 18)


{
[Link]("Eligible to Vote");
}
}
}

Output:

No Output

The condition is false, so the block is skipped.


Using Relational Operators

int marks = 40;

if(marks >= 35)


{
[Link]("Pass");
}

Output:

Pass

Using Logical Operators

int age = 20;


boolean citizen = true;

if(age >= 18 && citizen)


{
[Link]("Eligible");
}

Output:

Eligible

Single Statement if
Braces are optional when there is only one statement.

if(age >= 18)


[Link]("Adult");

However, using braces is considered good programming practice.

Multiple Statements
if(age >= 18)
{
[Link]("Adult");
[Link]("Can Vote");
}

Output:

Adult
Can Vote

Nested if
An if statement inside another if statement.

int age = 20;


boolean citizen = true;

if(age >= 18)


{
if(citizen)
{
[Link]("Eligible to Vote");
}
}

Output:

Eligible to Vote

Common Mistake
Wrong

if(age = 18)
{
}

Error because = is the assignment operator.


Correct

if(age == 18)
{
}

== is the equality operator.

Example Program

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

int num = 10;

if(num > 0)
{
[Link]("Positive Number");
}
}
}

Output:

Positive Number

Key Points
1. if is a selection (decision-making) statement.
2. The condition must evaluate to a boolean value (true or false).
3. Statements execute only when the condition is true.
4. Braces {} are recommended even for a single statement.
5. if can be nested.

if-else Statement in Java


Introduction
The if-else statement is a decision-making statement used when a program must choose
between two alternatives.

• If the condition is true → execute the if block.


• If the condition is false → execute the else block.

Syntax

if(condition)
{
// statements if condition is true
}
else
{
// statements if condition is false
}

Flowchart

Condition
|
True / \ False
/ \
if Block else Block

Example 1: Even or Odd

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

int num = 10;

if(num % 2 == 0)
{
[Link]("Even Number");
}
else
{
[Link]("Odd Number");
}
}
}

Output

Even Number

Example 2: Pass or Fail

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

int marks = 30;

if(marks >= 35)


{
[Link]("Pass");
}
else
{
[Link]("Fail");
}
}
}

Output

Fail

Example 3: Positive or Negative

int num = -5;

if(num > 0)
{
[Link]("Positive");
}
else
{
[Link]("Negative");
}

Output

Negative

Using Multiple Statements

int age = 20;

if(age >= 18)


{
[Link]("Adult");
[Link]("Eligible to Vote");
}
else
{
[Link]("Minor");
[Link]("Not Eligible to Vote");
}

Output

Adult
Eligible to Vote

Example with Logical Operators

int age = 20;


boolean citizen = true;

if(age >= 18 && citizen)


{
[Link]("Eligible");
}
else
{
[Link]("Not Eligible");
}

Output

Eligible

Nested if-else

int age = 17;

if(age >= 18)


{
[Link]("Adult");
}
else
{
[Link]("Minor");
}

Output:

Minor

Difference Between if and if-else


if if-else
Executes code only when condition is Chooses between two
true alternatives
No false block Has a false block (else)
Single decision Two-way decision

Example Program

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

int number = 15;


if(number % 2 == 0)
{
[Link]("Even");
}
else
{
[Link]("Odd");
}
}
}

Output

Odd

Key Points
1. if-else is a two-way decision statement.
2. Exactly one block executes.
3. The condition must be boolean.
4. else has no condition.
5. Useful for comparing values and making decisions.

Switch Statement in Java


Introduction
The switch statement is a multi-way decision-making statement.

It allows a variable or expression to be tested against multiple values and executes the matching
block of code.

Instead of writing many if-else-if statements, we can use a switch statement for better
readability.

Syntax

switch(expression)
{
case value1:
statements;
break;

case value2:
statements;
break;

case value3:
statements;
break;

default:
statements;
}

How it Works
1. The expression is evaluated.
2. Its value is compared with each case.
3. If a match is found, that case executes.
4. break terminates the switch.
5. If no match is found, the default block executes.

Flowchart

Expression
|
-----------------------
| | | | |
Case1 Case2 Case3 ... Default

Example 1: Day Number

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

int day = 3;

switch(day)
{
case 1:
[Link]("Monday");
break;

case 2:
[Link]("Tuesday");
break;

case 3:
[Link]("Wednesday");
break;

default:
[Link]("Invalid Day");
}
}
}

Output

Wednesday

Example 2: Character Switch

char grade = 'A';

switch(grade)
{
case 'A':
[Link]("Excellent");
break;

case 'B':
[Link]("Good");
break;

default:
[Link]("Average");
}

Output
Excellent

Role of break
With break

int n = 2;

switch(n)
{
case 1:
[Link]("One");
break;

case 2:
[Link]("Two");
break;
}

Output:

Two

Without break (Fall-Through)

int n = 2;

switch(n)
{
case 1:
[Link]("One");

case 2:
[Link]("Two");

case 3:
[Link]("Three");
}

Output:
Two
Three

This is called fall-through.

Default Case
The default case executes when no case matches.

int n = 10;

switch(n)
{
case 1:
[Link]("One");
break;

default:
[Link]("Invalid Number");
}

Output:

Invalid Number

Multiple Cases

char ch = 'A';

switch(ch)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
[Link]("Vowel");
break;

default:
[Link]("Consonant");
}

Output:

Vowel

Data Types Allowed in Switch


Java supports:

byte
short
int
char
String
enum

Example:

String day = "MON";

switch(day)
{
case "MON":
[Link]("Monday");
break;
}

switch vs if-else-if
switch if-else-if
Multiple xed values Complex conditions
Faster for many
More exible
options
Can become
Cleaner code
lengthy

Example Program
fl
fi
class Menu {
public static void main(String args[]) {

int choice = 2;

switch(choice)
{
case 1:
[Link]("Tea");
break;

case 2:
[Link]("Coffee");
break;

case 3:
[Link]("Milk");
break;

default:
[Link]("Invalid Choice");
}
}
}

Output

Coffee

Key Points
1. switch is a multi-way selection statement.
2. break prevents fall-through.
3. default is optional but recommended.
4. Case labels must be unique constants.
5. Useful when comparing one variable against many xed values.

Iteration Statements (Loops) in Java


fi
Introduction
Iteration Statements (Loops) are used to execute a block of code repeatedly until a condition
becomes false.

Why Loops?

Without loops:

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

With loops:

for(int i = 1; i <= 3; i++)


{
[Link]("Java");
}

Types of Iteration Statements

Iteration Statements
|
-------------------------
| | |
while do-while for
|
for-each

1. while Loop
The while loop checks the condition rst and then executes the body.

Syntax

while(condition)
{
statements;
fi
}

Flowchart

Condition
|
True
|
Statements
|

False
|
Exit

Example

int i = 1;

while(i <= 5)
{
[Link](i);
i++;
}

Output

1
2
3
4
5

2. do-while Loop
The do-while loop executes the body rst and checks the condition later.

Syntax

do
fi
{
statements;
}
while(condition);

Example

int i = 1;

do
{
[Link](i);
i++;
}
while(i <= 5);

Output

1
2
3
4
5

Difference: while vs do-while


while

while(false)
{
[Link]("Java");
}

Output:

No Output

do-while
do
{
[Link]("Java");
}
while(false);

Output:

Java

do-while executes at least once.

3. for Loop
Most commonly used loop.

Syntax

for(initialization; condition; update)


{
statements;
}

Example

for(int i = 1; i <= 5; i++)


{
[Link](i);
}

Output

1
2
3
4
5

Components of for Loop


for(int i = 1; i <= 5; i++)

Initialization

int i = 1;

Executed once.

Condition

i <= 5

Checked before each iteration.

Update

i++

Executed after every iteration.

4. Nested for Loop


A loop inside another loop.

Syntax

for(...)
{
for(...)
{
}
}

Example

for(int i = 1; i <= 3; i++)


{
for(int j = 1; j <= 2; j++)
{
[Link](i + " " + j);
}
}

Output

1 1
1 2
2 1
2 2
3 1
3 2

Pattern Example

for(int i = 1; i <= 3; i++)


{
for(int j = 1; j <= 3; j++)
{
[Link]("* ");
}
[Link]();
}

Output:

* * *
* * *
* * *

5. For-Each Loop (Enhanced for Loop)


Used to traverse arrays and collections.

Syntax

for(dataType variable : array)


{
statements;
}

Example

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

for(int x : arr)
{
[Link](x);
}

Output

10
20
30
40

Traditional for vs For-Each


Traditional for

for(int i = 0; i < [Link]; i++)


{
[Link](arr[i]);
}

For-Each

for(int x : arr)
{
[Link](x);
}

For-each is simpler and more readable.

Comparison Table
Condition Executes At Least
Loop
Check Once
while Before loop body No
do-
After loop body Yes
while
for Before loop body No

Example Program

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

for(int i = 1; i <= 5; i++)


{
[Link](i);
}
}
}

Output:

1
2
3
4
5

Key Points
1. while → Entry-controlled loop.
2. do-while → Exit-controlled loop.
3. for → Best when the number of iterations is known.
4. Nested loops are used for patterns and tables.
5. For-each loops are used for arrays and collections.

Jump Statements in Java


Introduction
Jump Statements are used to transfer control from one part of a program to another.

They alter the normal ow of execution.

Java provides three jump statements:

1. break
2. continue
3. return

1. break Statement
The break statement immediately terminates a loop or switch statement.

Syntax

break;

Example

for(int i = 1; i <= 10; i++)


{
if(i == 5)
break;

[Link](i);
}

Output

1
2
3
4

When i becomes 5, the loop stops.

break in switch
fl
int day = 2;

switch(day)
{
case 1:
[Link]("Monday");
break;

case 2:
[Link]("Tuesday");
break;
}

Output:

Tuesday

Without break, execution falls through to the next case.

2. continue Statement
The continue statement skips the current iteration and moves to the next iteration of the loop.

Syntax

continue;

Example

for(int i = 1; i <= 5; i++)


{
if(i == 3)
continue;

[Link](i);
}

Output

1
2
4
5

The value 3 is skipped.

Difference Between break and continue


break continue
Terminates loop Skips current iteration
Exits loop Continues with next
completely iteration

3. return Statement
The return statement terminates a method and optionally returns a value.

Syntax

return;

or

return value;

Example 1: return without Value

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

[Link]("Start");

return;

// [Link]("End");
}
}

Execution stops at return.


Example 2: return with Value

class Test {

static int square(int n)


{
return n * n;
}

public static void main(String args[])


{
[Link](square(5));
}
}

Output:

25

Labeled break
Used to exit multiple nested loops.

Example

outer:
for(int i = 1; i <= 3; i++)
{
for(int j = 1; j <= 3; j++)
{
if(i == 2 && j == 2)
break outer;

[Link](i + " " + j);


}
}

Output:
1 1
1 2
1 3
2 1

Labeled continue
Used to continue the next iteration of an outer loop.

Example

outer:
for(int i = 1; i <= 3; i++)
{
for(int j = 1; j <= 3; j++)
{
if(j == 2)
continue outer;

[Link](i + " " + j);


}
}

Output:

1 1
2 1
3 1

Summary Table
Statement Purpose
break Terminates loop or switch
continu
Skips current iteration
e
Exits method and optionally returns a
return value

Example Program
class JumpDemo {
public static void main(String args[]) {

for(int i = 1; i <= 5; i++)


{
if(i == 3)
continue;

if(i == 5)
break;

[Link](i);
}
}
}

Output:

1
2
4

Return Statement in Java


De nition
The return statement is used to:

1. Exit a method immediately.


2. Return a value to the calling method.

Syntax
Without Value

return;

With Value

return value;
fi
Example 1: Return a Value

class Test {

static int square(int n)


{
return n * n;
}

public static void main(String args[])


{
[Link](square(5));
}
}

Output:

25

Example 2: Exit a Method

class Test {
static void show()
{
[Link]("Start");

return;

// [Link]("End");
}
}

Execution stops at return.

2. Nested Loops (Advanced Patterns)


A loop inside another loop.
Pattern 1: Square Pattern

for(int i=1;i<=4;i++)
{
for(int j=1;j<=4;j++)
{
[Link]("* ");
}
[Link]();
}

Output:

* * * *
* * * *
* * * *
* * * *

Pattern 2: Triangle Pattern

for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link]("* ");
}
[Link]();
}

Output:

*
* *
* * *
* * * *
* * * * *

Pattern 3: Number Triangle


for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link](j+" ");
}
[Link]();
}

Output:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

3. Labeled break Statement


Normally, break exits only the nearest loop.

A labeled break can exit an outer loop directly.

Syntax

label:
for(...)
{
for(...)
{
break label;
}
}

Example

outer:
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
if(i==2 && j==2)
break outer;

[Link](i+" "+j);
}
}

Output:

1 1
1 2
1 3
2 1

When i=2 and j=2, both loops terminate.

4. Labeled continue Statement


Normally, continue skips the current iteration.

A labeled continue skips to the next iteration of an outer loop.

Example

outer:
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
if(j==2)
continue outer;

[Link](i+" "+j);
}
}

Output:
1 1
2 1
3 1

Explanation:

• When j=2, control jumps to the next iteration of the outer loop.

Difference Between break and continue


Statement Action
break Terminates loop
Skips current
continue
iteration
break label Terminates outer loop
continue
Continues outer loop
label

JNTUK Exam Quick Notes


return

return value;

Returns a value and exits the method.

labeled break

break outer;

Exits the speci ed outer loop.

labeled continue

continue outer;

Starts the next iteration of the speci ed outer loop.

Nested Loop
fi
fi
for(...)
{
for(...)
{
}
}

Used for patterns, matrices, and tables.

You might also like