Java Unit 1
Java Unit 1
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.
This means a Java program can run on any system that has a Java Virtual Machine (JVM).
For example:
• TVs
• Set-top boxes
• Home appliances
Requirements:
• Portable
• Secure
• Reliable
• Easy to use
3. History of Java
1991 – The Green Project
Oak
Java
Sun Microsystems realized Java was ideal for web applications because:
• Platform independent
• Secure
• Network-oriented
Java Applets
Advantages:
• 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
Added:
• Event handling
• JDBC
• Inner classes
Major update:
• Swing GUI
• Collections Framework
Editions introduced:
• J2SE
• J2EE
• J2ME
Important features:
• Generics
• Enhanced for-loop
• Autoboxing
• Annotations
• Enumerations
Java 8 (2014)
• Lambda Expressions
• Stream API
• Functional Programming
Java 9 (2017)
Java 11 (2018)
Java 17 (2021)
LTS Release
• Better performance
• Security improvements
Java 21 (2023)
Features:
• Virtual Threads
• Pattern Matching
• Performance improvements
6. Why Java Became Popular?
Platform Independent
Compiler
Bytecode (.class)
JVM
Object-Oriented
Supports:
• Class
• Object
• Inheritance
• Polymorphism
• Encapsulation
• Abstraction
Secure
• No pointers
• Sandboxing
Robust
• Exception Handling
• Garbage Collection
7. Java Editions
Java SE
Standard Edition
Used for:
• Desktop applications
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
• Scienti c Applications
Examples:
• Apache Hadoop
• Spring Framework
9. Interview Questions
Q1. Who invented Java?
Answer: Oak.
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
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.
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.
• Assembly Language
• B Language
These languages had limitations:
• Powerful
• Ef cient
• Portable
• Easier than Assembly Language
UNIX
UNIX was largely rewritten in C, proving that a high-level language could be used for system
programming.
if
else
for
while
switch
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
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#
Key Contributions of C
• Structured Programming
• Portable Software Development
• System Programming
• Ef cient Execution
• In uence on Modern Languages
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.
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.
class Student {
int id;
};
2. Encapsulation
fi
fi
fl
Data can be hidden and protected from unauthorized access.
3. Inheritance
class A { };
class B : public A { };
4. Polymorphism
5. Function Overloading
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.
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.
• 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
• Windows
• Linux
• Macintosh
• Different hardware platforms
Writing separate programs for each platform was expensive and time-consuming.
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.
Java combined the best features of C and C++ while eliminating many of their weaknesses.
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.
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.
Role of JVM
The Java Virtual Machine reads the Bytecode and converts it into machine instructions that the
computer can execute.
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]
java Test
Advantages of Bytecode
1. Platform Independence
2. Security
3. Portability
4. Performance
Modern JVMs use JIT (Just-In-Time) Compilation to convert Bytecode into optimized machine
code.
• 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.
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.
1. Simple
Java is easy to learn because:
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.
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++.
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
11. Dynamic
Java adapts to changing environments.
Features:
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.
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
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);
}
}
OOP introduced:
Encapsulation
Inheritance
Polymorphism
• Reusable
• Maintainable
• Scalable
Real-Life Example
Procedural Approach
Student Data
↓
Functions
↓
Process Data
Object-Oriented Approach
Student Object
├─ id
├─ name
└─ display()
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
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);
}
}
OOP introduced:
Encapsulation
Inheritance
Polymorphism
Abstraction
• Reusable
• Maintainable
• Scalable
Real-Life Example
fi
fi
Procedural Approach
Student Data
↓
Functions
↓
Process Data
Object-Oriented Approach
Student Object
├─ id
├─ name
└─ display()
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;
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
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");
}
}
• Code reusability
• Easy maintenance
• Reduces redundancy
4. Polymorphism
De nition: One interface, many forms.
class MathOp {
int add(int a, int b) {
return a + b;
}
class Animal {
void sound() {
[Link]("Animal Sound");
}
}
Advantages
• Flexibility
• Extensibility
• Better code design
fi
OOP Principles Diagram
Object-Oriented Programming
|
-----------------
| | |
Encapsulation
Abstraction
Inheritance
Polymorphism
Abstraction
Inheritance
Polymorphism
What happens?
[Link]();
Result: Simplicity.
What happens?
Account acc;
[Link]();
Different behavior:
Savings Interest
Current Interest
Result: Flexibility.
Account
|
----------------
| |
SavingsAccount CurrentAccount
| |
Encapsulation Encapsulation
|
Abstraction
|
Polymorphism
Flow
Abstraction
You use the steering wheel and pedals without knowing engine mechanics.
Inheritance
Vehicle
|
-----------------
| |
Car Bike
Polymorphism
[Link]();
class Hello {
public static void main(String args[]) {
[Link]("Hello World");
}
}
class Hello
2. Main Method
• Returns no value.
main
3. Method Body
{
[Link]("Hello World");
}
4. Output Statement
[Link]("Hello World");
Breakdown
System
Hello World
[Link]
Step 2: Compile
javac [Link]
Compiler generates:
[Link]
Step 3: Run
java Hello
Output:
Hello World
Example:
fi
public class Test
File name:
[Link]
Rule 2
Java is case-sensitive.
Main
and
main
are different.
Rule 3
class ClassName {
// Variables
// Methods
// Statements
}
}
Elements (Tokens) in Java
A token is the smallest individual unit in a Java program that has meaning to the compiler.
Example:
int a = 10;
Tokens are:
int
a
=
10
;
Examples:
class
public
static
void
if
else
for
while
return
Example:
public
class
are keywords.
2. Identi ers
Identi ers are names given to:
• Classes
• Variables
• Methods
• Objects
Example:
int age;
✅ Can contain:
• Letters
• Digits
• _
• $
✅ Cannot:
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
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;
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.
int a;
double salary;
String name;
Example:
2. Expression Statements
a = 10;
b = a + 5;
count++;
Example:
int sum = a + b;
fi
fi
3. Control Statements
Selection Statements
if
if-else
switch
Example:
Iteration Statements
for
while
do-while
Example:
Jump Statements
break
continue
return
Example:
break;
4. Block Statements
5. Empty Statement
Example:
while(condition);
Although valid, it is usually used carefully because it can cause logical errors.
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[]) {
x = x + 5; // Expression statement
These arguments are stored in the String args[] parameter of the main() method.
or
java Test 10 20
Here:
• 10 → First argument
• 20 → Second argument
class Test {
public static void main(String args[]) {
[Link](args[0]);
[Link](args[1]);
}
}
Compile
javac [Link]
Run
Output
Hello
Java
java Test A B C
Array contents:
args[0] = "A"
args[1] = "B"
args[2] = "C"
args
|
----------------
| | |
"A" "B" "C"
0 1 2
class Add {
public static void main(String args[]) {
int a = [Link](args[0]);
int b = [Link](args[1]);
Run
java Add 10 20
Output
Sum = 30
Important Points
1. Arguments Are Strings
args[0]
is always a String.
[Link]()
[Link]()
[Link]()
args[0]
args[1]
args[2]
3. Runtime Error
java Test
args[0]
an exception occurs:
ArrayIndexOutOfBoundsException
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
Program
import [Link];
class InputDemo {
public static void main(String args[]) {
Output
Enter your name: Uday
Hello Uday
Method Reads
nextInt() Integer
nextFloat() Float
nextDouble() Double
next() Single word
nextLine() Entire line
nextBoolean( Boolean
) value
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]));
[Link](name);
}
}
Advantages
• Fast input
• Common in older Java programs
Keyboard
↓
[Link]
↓
Scanner / BufferedReader
↓
Java Program
import [Link];
class Add {
public static void main(String args[]) {
Output
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]();
[Link](name);
}
}
Advantage
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.
import [Link];
class Test {
public static void main(String args[]) {
String name =
[Link]("Enter Name");
[Link](name);
}
}
import [Link].*;
import [Link];
Socket socket;
InputStream in =
[Link]();
Console Medium
JOptionPane Medium
DataInputStream Low
File Input Advanced
They are used inside character and string literals to represent special characters.
Escape
Meaning
Sequence
\n New Line
\t Horizontal Tab
\b Backspace
Carriage
\r Return
\f Form Feed
\' Single Quote
\" Double Quote
\\ Backslash
[Link]("Java\nProgramming");
Output:
Java
Programming
[Link]("Name\tAge");
Output:
Name Age
Output:
He said "Hello"
[Link]("C:\\Java\\Programs");
Output:
C:\Java\Programs
2. Comments in Java
Comments are non-executable statements used to explain code.
Advantages
• Improves readability
• Helps documentation
• Makes maintenance easier
Types of Comments
1. Single-Line Comment
Begins with //
2. Multi-Line Comment
/*
This is a
multi-line comment
*/
/**
* This method displays a message.
*/
void display() {
}
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
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
Bad
int x;
int y;
Good
int studentAge;
int totalMarks;
2. Proper Indentation
Indent code blocks consistently.
Good
Bad
if(age>=18){
[Link]("Eligible");
}
3. Use Comments
fi
Comments explain the purpose of code.
Use PascalCase.
class StudentRecord
Variable Names
Use camelCase.
int totalMarks;
Constants
void displayResult() {
[Link]("Pass");
}
Bad
int sum=a+b;
Use:
class Student {
In Java, you must declare the type of a variable before using it.
1. Compile Time
2. Run Time (to some extent)
The compiler ensures that data is used according to its declared type.
int sum = a + b;
int a = "Hello";
Compiler Error:
incompatible types
double d = 10.5;
int x = (int)d;
Output:
10
int x = "Java";
3. Improved Security
4. Easier Maintenance
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:
Data Types
|
|-------------------|
| |
Primitive Non-Primitive
(Basic) (Reference)
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
short
int
long
Floating-Point Types
oat
f or F is required.
double
fl
double pi = 3.1415926535;
Character Type
char
Boolean Type
Stores logical values.
Possible values:
true
false
Examples:
String
Array
Interface
interface Vehicle {
}
Example Program
class DataTypeDemo {
public static void main(String args[]) {
[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
Examples:
10
3.14
'A'
"Hello"
true
These values are called literals because their values are xed.
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
Pre x: 0x or 0X
0xA
Value = 10
Add suf x L or l
100000L
Example:
3.14
10.5
Float Literal
Add suf x F or f
3.14F
Example:
Scienti c Notation
1.2e3
Means:
Example:
3. Character Literals
A single character enclosed in single quotes.
fi
fi
'A'
'B'
'9'
'@'
Example:
'\n'
'\t'
'\\'
'\"'
Example:
char ch = '\n';
4. String Literals
A sequence of characters enclosed in double quotes.
"Java"
"Hello World"
Example:
5. Boolean Literals
Only two values:
true
false
Example:
Example Program
class LiteralDemo {
public static void main(String args[]) {
float f = 3.14F;
double d = 3.14;
char ch = 'A';
[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.
Syntax
fi
dataType variableName;
Example:
int marks;
or
• 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.
class Test {
public static void main(String args[]) {
[Link](x);
}
}
Characteristics
2. Instance Variables
Declared inside a class but outside methods.
class Student {
Characteristics
• Belong to an object.
• Each object gets its own copy.
3. Static Variables
Declared using the static keyword.
class Student {
Characteristics
Example
class Student {
[Link](marks);
}
}
Naming Rules
Valid
student
studentName
_age
$salary
Invalid
1student
student name
class
Rules:
Variable Scope
class Test {
int x = 10;
[Link](x);
}
}
Example Program
class VariableDemo {
[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
class DynamicInit {
fi
fi
public static void main(String args[]) {
int a = 10;
int b = 20;
[Link](sum);
}
}
Output
30
class Test {
[Link](result);
}
}
Output
25
class Demo {
public static void main(String args[]) {
[Link](num);
}
}
The value of num is not known until the user enters it at runtime.
int x = 100;
Dynamic Initialization
int x = a + b;
Real-Life Example
1. Scope of a Variable
Scope is the region of a program where a variable is visible and can be used.
class Test {
public static void main(String args[]) {
int x = 10;
[Link](x);
}
}
Invalid Example
class Test {
public static void main(String args[]) {
int x = 10;
}
void display() {
[Link](x); // Error
}
}
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
}
}
class Student {
int rollNo;
void display() {
[Link](rollNo);
}
}
rollNo can be accessed by all instance methods of the class.
class Student {
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.
void show() {
int x = 10;
}
Lifetime
Method Starts
↓
Variable Created
↓
Method Ends
↓
Variable Destroyed
class Student {
int rollNo;
}
Lifetime
class Student {
static int count;
}
Lifetime
Example
class Demo {
[Link](c);
}
}
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
Example:
fi
int x = 10;
double y = x;
int a = 10;
double b = 20.5;
Type Casting
|
|-------------------|
| |
Implicit Explicit
(Widening) (Narrowing)
Example
class Test {
public static void main(String args[]) {
int x = 100;
double y = x;
[Link](y);
}
}
Output:
100.0
Another Example
char ch = 'A';
int x = ch;
[Link](x);
Output:
65
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
byte b = (byte)num;
[Link](b);
Output:
-126
Real Example
[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;
double d = 20.5;
int x = (int)d;
Promotion
int a = 10;
double b = 20.5;
double c = a + b;
byte a = 10;
byte b = 20;
a + b
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
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
Example 2
float x = 10.5F;
double y = 20.5;
double z = x + y;
Promotion:
float → 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:
or
int c = a + b;
byte b = 10;
short s = 20;
int i = 30;
long l = 40;
long result = b + s + i + l;
Promotion:
byte → int
short → int
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
Examples:
10
3.14
'A'
"Java"
true
These are called literal constants because they represent constant values literally written in the
source code.
Decimal
fi
fi
10
25
100
Binary
0b1010
Octal
012
Hexadecimal
0xA
100000L
Example:
2. Floating-Point Constants
Numbers containing a decimal point.
3.14
25.5
Float Constant
3.14F
Example:
Scienti c Notation
1.2e3
Means:
3. Character Constants
A single character enclosed in single quotes.
'A'
'B'
'9'
'@'
Example:
'\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:
5. Boolean Constants
Only two values are allowed:
true
false
Example:
Example Program
class LiteralDemo {
public static void main(String args[]) {
Output:
100
3.14
A
Java
true
Example:
int x = 10;
• x → Variable
• 10 → Literal Constant
De nition
A Symbolic Constant is a constant value represented by a name (symbol) instead of writing the
literal value repeatedly in the program.
use:
double area = PI * r * r;
Bene ts:
• Improves readability
• Easier maintenance
• Prevents accidental modi cation
Syntax
Example:
Example 1
class Test {
public static void main(String args[]) {
[Link](MAX_MARKS);
}
}
Output:
fi
fi
100
class Circle {
public static void main(String args[]) {
double radius = 7;
[Link](area);
}
}
Cannot Be Changed
Compiler Error:
Naming Convention
Symbolic constants are usually written in UPPERCASE.
Example:
Here:
Advantages
1. Improves program readability
2. Makes code easier to modify
3. Prevents accidental changes
4. Reduces errors
5. Follows good programming style
[Link]();
Unlike print() and println(), printf() allows you to control:
• Width
• Precision
• Alignment
• Data format
Syntax
Example:
Output:
Age = 25
Example 1: Integer
Output:
fi
fi
Marks = 90
Output:
Price = 99.990000
Example 3: Character
Output:
Grade = A
Example 4: String
Output:
Name = Uday
Example 5: Boolean
Output:
Result = true
Precision
Two Decimal Places
double pi = 3.141592;
[Link]("%.2f", pi);
Output:
3.14
[Link]("%.3f", pi);
Output:
3.142
Field Width
[Link]("%5d", 10);
Output:
10
Left Alignment
[Link]("%-10s", "Java");
Output:
Java
Multiple Values
Output:
Output:
Name Marks
Uday 95
Ravi 88
Example:
[Link]("Java");
[Link](" Programming");
[Link]("Marks = %d", 90);
Complete Example
class PrintfDemo {
public static void main(String args[]) {
Output:
Name: Uday
Marks: 95
Percentage: 92.75
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
Example
class Student {
String name;
}
Memory Concept
Student Class
|
|---- college = "JNTUK" (one copy)
Student s1
|
|---- name = "Uday"
Student s2
|
|---- name = "Ravi"
Example Program
class Student {
static String college = "JNTUK";
String name;
Student(String n) {
name = n;
}
void display() {
[Link](name + " " + college);
}
[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
Example
class Demo {
[Link]();
}
}
Output
Static Method
✅ Static variables
❌ Instance variables
❌ Instance methods
Example
class Test {
int x = 10;
static int y = 20;
[Link](y);
// [Link](x); // Error
}
}
Static Block
A static block executes when the class is loaded.
class Demo {
static {
[Link]("Static Block Executed");
}
Output
Example: Counter
class Counter {
Counter() {
count++;
}
new Counter();
new Counter();
new Counter();
Output
fi
Objects = 3
Syntax
Example:
class Test {
public static void main(String args[]) {
[Link](MAX);
}
}
Output:
100
class Test {
public static void main(String args[]) {
Compiler Error:
class Student {
void display() {
[Link](COLLEGE);
}
}
class Test {
final int x;
fi
fi
fi
fi
Test() {
x = 10;
}
}
class Circle {
Naming Convention
Final constants are usually written in uppercase.
Example:
Example
int a = 10;
int b = 20;
int c = a + b;
Here:
30
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;
Output:
true
3. Logical Operators
Used with boolean values.
Operato
Meaning
r
Logical
&& AND
`
Logical
! NOT
Example
boolean a = true;
boolean b = false;
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
int a = 5;
a++;
Result:
6
Decrement (--)
int a = 5;
a--;
Result:
Example:
int a = 10;
int b = 20;
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;
Output:
Example Program
class OperatorDemo {
public static void main(String args[]) {
int a = 10;
int b = 5;
Output:
Addition = 15
Greater = true
AND = true
Introduction
Assignment Operators are used to assign values to variables.
Java also provides compound assignment operators, which combine an arithmetic or bitwise
operation with assignment.
int a = 10;
Here, 10 is assigned to a.
int a = 10;
a += 5;
Equivalent to:
a = a + 5;
Output:
15
int a = 10;
a -= 3;
Equivalent to:
a = a - 3;
Output:
a *= 2;
Equivalent to:
a = a * 2;
Output:
20
int a = 20;
a /= 4;
Equivalent to:
a = a / 4;
Output:
int a = 10;
a %= 3;
Equivalent to:
a = a % 3;
Output:
int a = 5;
a &= 3;
Equivalent to:
a = a & 3;
Output:
a = 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;
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
= 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
Introduction
Arithmetic Operators are used to perform mathematical calculations on numeric values.
Example:
int a = 10;
int b = 5;
int c = a + b;
Here:
int a = 10;
int b = 20;
[Link](a + b);
Output:
30
int a = 20;
int b = 10;
[Link](a - b);
Output:
10
int a = 10;
int b = 5;
[Link](a * b);
Output:
50
int a = 20;
int b = 5;
[Link](a / b);
Output:
Integer Division
[Link](10 / 3);
Output:
3
[Link](10 % 3);
Output:
Calculation:
10 ÷ 3 = 3 remainder 1
int a = 5;
a++;
[Link](a);
Output:
Equivalent to:
a = a + 1;
int a = 5;
a--;
[Link](a);
Output:
Equivalent to:
a = a - 1;
Special Use of +
For Strings, + performs concatenation.
Output:
Hello Uday
Example Program
class ArithmeticDemo {
public static void main(String args[]) {
int a = 10;
int b = 3;
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.
Introduction
The Increment (++) and Decrement (--) operators are unary operators because they operate on
only one operand.
variable++;
or
++variable;
Example
int a = 10;
a++;
[Link](a);
Output:
11
Equivalent to:
a = a + 1;
variable--;
or
--variable;
Example
int a = 10;
a--;
[Link](a);
Output:
Equivalent to:
a = a - 1;
1. Pre x
2. Post x
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
int a = 5;
int b = --a;
Output:
a = 4
b = 4
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;
Step-by-Step
x = 5
++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:
Introduction
The Ternary Operator is a shorthand form of the if-else statement.
Syntax
Meaning
Basic Example
int a = 10;
int b = 20;
[Link](max);
Output:
20
int max;
if(a > b)
max = a;
else
max = b;
The ternary operator performs the same task in a shorter form.
int a = 50;
int b = 30;
Output:
Largest = 50
int num = 8;
[Link](result);
Output:
Even
[Link](result);
Output:
Pass
int a = 10;
int b = 20;
int c = 15;
[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[]) {
[Link](status);
}
}
Output:
Eligible to Vote
Ternary
true
or
false
• if statements
• Loops (for, while)
• Conditional expressions
• Decision-making programs
1. Equal To (==)
Checks whether two values are equal.
int a = 10;
int b = 10;
[Link](a == b);
Output:
true
int a = 10;
int b = 20;
[Link](a != b);
Output:
true
int a = 20;
int b = 10;
Output:
true
int a = 10;
int b = 20;
true
int a = 20;
int b = 20;
Output:
true
Because a is equal to b.
int a = 10;
int b = 20;
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
Output:
Pass
Important Difference
Assignment Operator (=)
a = 10;
Means:
Assign 10 to a
a == 10
Means:
Comparison Example
int x = 5;
int y = 8;
[Link](result);
Output:
true
• if statements
• Loops
• Decision-making
• Conditional expressions
The result of a logical operation is always:
true
or
false
Truth Table
A &&
A B
B
TRUETRUETRUE
TRUEFALSE
FALSE
FALSE
TRUEFALSE
FALSE
FALSE
FALSE
Example
boolean a = true;
boolean b = false;
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
boolean a = true;
boolean b = false;
Output:
false
boolean a = true;
boolean b = false;
[Link](a | b);
Output:
true
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 the rst condition is false, Java does not evaluate the second condition.
|| (Short-Circuit OR)
boolean a = true;
if(a || someMethod())
{
[Link]("Executed");
}
Example Program
class LogicalDemo {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
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
13 ÷ 2 = 6 remainder 1
6 ÷ 2 = 3 remainder 0
3 ÷ 2 = 1 remainder 1
1 ÷ 2 = 0 remainder 1
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
25₁₀ = 11001₂
10 = 8 + 2
8 4 2 1
1 0 1 0
Therefore:
10₁₀ = 1010₂
Introduction
Bitwise Operators perform operations directly on the binary (bit) representation of integer values.
Example:
int a = 5;
int b = 3;
Binary values:
5 = 0101
3 = 0011
Example
int a = 5;
int b = 3;
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:
Example
int a = 5;
int b = 3;
[Link](a ^ b);
Binary:
0101
^ 0011
-------
0110
Output:
Example
int a = 5;
[Link](~a);
5 = 00000101
~5 = 11111010
Output:
-6
Formula
~n = -(n + 1)
Example:
~5 = -(5 + 1)
= -6
Truth Tables
Bitwise OR (|)
A|
AB
B
0 0 0
0 1 1
1 0 1
1 1 1
Example Program
class BitwiseDemo {
public static void main(String args[]) {
int a = 5;
int b = 3;
AND = 1
OR = 7
XOR = 6
NOT = -6
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
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
Java provides:
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
Syntax
number << n
Example: 5 << 1
Step 1: Convert 5 to Binary
5 = 00000101
00000101
<< 1
---------
00001010
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
Syntax
number >> n
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
Java Program
class ShiftDemo {
public static void main(String args[]) {
Output:
10
20
10
5
Example:
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ᵏ
Syntax
number >>> n
int x = 20;
Binary:
20 = 00010100
00000101
Output:
5
5
fi
fi
fi
For positive numbers, >> and >>> usually produce the same result.
int x = -8;
Using >> 1
Result:
-4
Using >>> 1
Result:
2147483644
Java Program
fi
class ShiftDemo {
public static void main(String args[]) {
int x = -8;
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:
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
Using Parentheses
Parentheses have the highest precedence.
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
Example 1
int x = 10 + 5 * 2;
Evaluation:
5 * 2 = 10
10 + 10 = 20
Output:
20
Example 2
Evaluation:
10 > 5 → true
20 > 15 → 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
Statement 1
Statement 2
Statement 3
• 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");
Example:
Control Statements
|
-------------------
| | |
Selection Iteration Jump
Types
if
if-else
if-else-if ladder
switch
Example
Output:
Adult
Types
while
do-while
for
Example
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
[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[]) {
Output:
Pass
1
2
3
Summary Table
Categor
Statements
y
Selection if, if-else, switch
Iteration for, while, do-while
break, continue,
Jump
return
Syntax
if(condition)
{
// statements
}
Working
Flowchart
Condition
|
True / \ False
/ \
Statements Skip
Output:
Eligible to Vote
Because:
20 >= 18 → true
class Test {
public static void main(String args[]) {
Output:
No Output
Output:
Pass
Output:
Eligible
Single Statement if
Braces are optional when there is only one statement.
Multiple Statements
if(age >= 18)
{
[Link]("Adult");
[Link]("Can Vote");
}
Output:
Adult
Can Vote
Nested if
An if statement inside another if statement.
Output:
Eligible to Vote
Common Mistake
Wrong
if(age = 18)
{
}
if(age == 18)
{
}
Example Program
class IfDemo {
public static void main(String args[]) {
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.
Syntax
if(condition)
{
// statements if condition is true
}
else
{
// statements if condition is false
}
Flowchart
Condition
|
True / \ False
/ \
if Block else Block
class Test {
public static void main(String args[]) {
if(num % 2 == 0)
{
[Link]("Even Number");
}
else
{
[Link]("Odd Number");
}
}
}
Output
Even Number
class Test {
public static void main(String args[]) {
Output
Fail
if(num > 0)
{
[Link]("Positive");
}
else
{
[Link]("Negative");
}
Output
Negative
Output
Adult
Eligible to Vote
Output
Eligible
Nested if-else
Output:
Minor
Example Program
class IfElseDemo {
public static void main(String args[]) {
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.
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
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
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
int n = 2;
switch(n)
{
case 1:
[Link]("One");
case 2:
[Link]("Two");
case 3:
[Link]("Three");
}
Output:
Two
Three
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
byte
short
int
char
String
enum
Example:
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.
Why Loops?
Without loops:
[Link]("Java");
[Link]("Java");
[Link]("Java");
With loops:
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
while(false)
{
[Link]("Java");
}
Output:
No Output
do-while
do
{
[Link]("Java");
}
while(false);
Output:
Java
3. for Loop
Most commonly used loop.
Syntax
Example
Output
1
2
3
4
5
Initialization
int i = 1;
Executed once.
Condition
i <= 5
Update
i++
Syntax
for(...)
{
for(...)
{
}
}
Example
Output
1 1
1 2
2 1
2 2
3 1
3 2
Pattern Example
Output:
* * *
* * *
* * *
Syntax
Example
for(int x : arr)
{
[Link](x);
}
Output
10
20
30
40
For-Each
for(int x : arr)
{
[Link](x);
}
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[]) {
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.
1. break
2. continue
3. return
1. break Statement
The break statement immediately terminates a loop or switch statement.
Syntax
break;
Example
[Link](i);
}
Output
1
2
3
4
break in switch
fl
int day = 2;
switch(day)
{
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
}
Output:
Tuesday
2. continue Statement
The continue statement skips the current iteration and moves to the next iteration of the loop.
Syntax
continue;
Example
[Link](i);
}
Output
1
2
4
5
3. return Statement
The return statement terminates a method and optionally returns a value.
Syntax
return;
or
return value;
class Test {
public static void main(String args[]) {
[Link]("Start");
return;
// [Link]("End");
}
}
class Test {
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;
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;
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[]) {
if(i == 5)
break;
[Link](i);
}
}
}
Output:
1
2
4
Syntax
Without Value
return;
With Value
return value;
fi
Example 1: Return a Value
class Test {
Output:
25
class Test {
static void show()
{
[Link]("Start");
return;
// [Link]("End");
}
}
for(int i=1;i<=4;i++)
{
for(int j=1;j<=4;j++)
{
[Link]("* ");
}
[Link]();
}
Output:
* * * *
* * * *
* * * *
* * * *
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
[Link]("* ");
}
[Link]();
}
Output:
*
* *
* * *
* * * *
* * * * *
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
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
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.
return value;
labeled break
break outer;
labeled continue
continue outer;
Nested Loop
fi
fi
for(...)
{
for(...)
{
}
}