Object Oriented Programming with JAVA
Dr. M. Sudhakara
Prerequisites
• The students should have knowledge of
● Basic Programming Skills:
● Knowledge of C & C++
10-09-2025 VMS CLASS 2
Course Objectives
• To learn primitive constructs JAVA programming language.
• To understand Object Oriented Programming Features of JAVA.
• To gain knowledge on: packages, multithreaded programing and
exceptions
10-09-2025 VMS CLASS 3
Module 1: Section 1
• An Overview of Java: Object-Oriented Programming (Two Paradigms,
Abstraction, The Three OOP Principles), Using Blocks of Code, Lexical
Issues (Whitespace, Identifiers, Literals, Comments, Separators, The
Java Keywords).
10-09-2025 VMS CLASS 4
What is OOP?
• Object Oriented Programming (OOP) is one of the most widely used
programming paradigm.
Definition:
OOP is a way of writing programs by organizing code into objects that
represent real-world or imaginary things.
10-09-2025 VMS CLASS 5
What is an object ?
• An object has:
• Data (Attributes/Properties) → what it has.
• Methods (Functions/Behaviors) → what it can do.
10-09-2025 VMS CLASS 6
Example: Object (Dog)
• Data: name, breed, age.
• Methods: bark(), eat(), run().
• You can create many Dog objects, each with its own data but using
the same methods.
10-09-2025 VMS CLASS 7
Why OOP is extensively used?
• Well-suited for building trivial and complex applications
• Allows re-use of code, thereby increasing productivity
• New features can be easily built into the existing code
• Reduced production cost and maintenance cost
10-09-2025 VMS CLASS 8
Examples:
Common programming languages used for OOP include :
10-09-2025 VMS CLASS 9
What is Java?
• Java is a widely used programming language that was created in 1995.
• It is owned by Oracle, and it runs on over 3 billion devices.
• Java is used for many things, such as:
• Android mobile apps
• Desktop software
• Websites and web apps
• Web servers and app servers
• Games
• Connecting to databases
• And many other uses!
10-09-2025 VMS CLASS 10
Java Buzzwords
• The buzzwords are special features or characteristics that make Java unique
and popular.
✓Simple
✓Secure
✓Portable
✓Object-oriented
✓Robust
✓Multithreaded
✓Architecture-neutral
✓Interpreted
✓High performance
✓Distributed
✓Dynamic
10-09-2025 VMS CLASS 11
Java Buzzwords : Simple
• Java is designed to be easy to learn and use for professional programmers.
• If you have prior programming knowledge, Java is straightforward and quick to
master.
• Knowing Object-Oriented Programming concepts makes Java learning even
simpler.
• For C/C++ programmers, Java’s syntax and features feel familiar and natural.
• Java eliminates complexities found in older languages, providing a clear, efficient
coding experience.
10-09-2025 VMS CLASS 12
Java Buzzwords : Secure
• Java helps protect your computer from viruses and harmful code.
• It checks code carefully before running it to keep your system safe.
10-09-2025 VMS CLASS 13
Java Buzzwords : Portable
• Java code works on any device or platform (Windows, Linux, Mac).
• "Write Once, Run Anywhere"—you write code once, and it runs
everywhere.
10-09-2025 VMS CLASS 14
Java Buzzwords : Object Oriented
• Java is fundamentally built around objects, combining data and behavior.
• Although influenced by earlier languages, Java was designed fresh, without compatibility
constraints.
• Java achieves a practical balance:
• It emphasizes objects, but not everything is forced into being an object.
• Primitive types (like integers) are kept separate for high performance.
• Java’s object model is clean, practical, and easy to extend, simplifying code organization
and reuse.
10-09-2025 VMS CLASS 15
Java Buzzwords : Robust
• Java is designed to create reliable programs that run smoothly on various
systems.
• It helps programmers detect and fix errors early by enforcing strict type checking:
• Compile-time checks detect many errors before your program runs.
• Run-time checks catch errors that occur while your program is executing.
• Two common issues Java solves effectively:
1. Memory Management Errors:
• Automatically manages memory through garbage collection.
• Eliminates issues like memory leaks and accidental memory corruption found in languages like C/C++.
2. Exception Handling (Run-time Errors):
• Provides structured, easy-to-use exception handling.
• Helps manage unexpected situations clearly (e.g., division by zero, file-not-found errors).
• Java ensures your program behaves predictably across diverse environments,
enhancing reliability and stability.
10-09-2025 VMS CLASS 16
Java Buzzwords : Multithreaded
• Supports simultaneous execution of multiple tasks.
• Ideal for interactive and networked applications.
• Built-in support for thread creation and synchronization.
• Simplifies handling of concurrent tasks (e.g., background processing, UI
updates).
• Improves performance and responsiveness of programs.
10-09-2025 VMS CLASS 17
Java Buzzwords : Architecture Neutral
• Designed for long-lasting and portable code.
• Java programs are not dependent on hardware or the operating system.
• Eliminates issues caused by system upgrades or architecture differences.
• Runs consistently across different platforms using the Java Virtual Machine
(JVM).
• Supports the principle: “Write once, run anywhere”.
10-09-2025 VMS CLASS 18
Java Buzzwords : Interpreted
• Java translates your code into an intermediate format called
bytecode.
• Bytecode runs inside a Java Virtual Machine (JVM), which means you
can run your code easily on different computers without needing to
rewrite it.
10-09-2025 VMS CLASS 19
Java Buzzwords : High Performance
• Java is designed to be fast and efficient.
• Modern JVMs optimize your code automatically, making Java very
fast—close to native languages like C++.
10-09-2025 VMS CLASS 20
Java Buzzwords : Distributed
• Designed for networked (Internet-based) environments.
• Supports TCP/IP protocols for easy communication over networks.
• Allows access to remote resources using URLs, similar to local files.
• Supports Remote Method Invocation (RMI) for calling methods
across systems.
10-09-2025 VMS CLASS 21
Java Buzzwords : Dynamic
• Java uses run-time type information to manage objects safely.
• Supports dynamic linking of classes and libraries while the program is
running.
• Enables code updates during execution without restarting the entire
system.
• Contributes to Java’s flexibility and robustness.
10-09-2025 VMS CLASS 22
Why Use Java?
• Java works on many platforms like Windows, Mac, Linux, and Raspberry Pi.
• It is one of the most popular programming languages in the world.
• There are many job opportunities for people who know Java.
• Java is easy to learn and simple to use.
• It is open-source and free to use.
• Java is secure, fast, and powerful.
• It has a big community with millions of developers for support.
• Java is an object-oriented language, which means it helps organize code
clearly and reuse it, saving time and money.
• Since Java is similar to C++ and C#, it’s easy for programmers to switch
between them.
10-09-2025 VMS CLASS 23
Getting Started
• To check if you have Java installed on a Windows PC, search in the start bar
for Java or type the following in Command Prompt ([Link]):
C:\Users\Your Name>java -version
• If Java is installed, you will see something like this (depending on version):
If you do not have Java installed on your computer, you can download it at
[Link].
10-09-2025 VMS CLASS 24
A First Simple Program
/*
This is a simple Java program.
Call this file "[Link]".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
[Link]("This is a simple Java program.");
}
}
10-09-2025 VMS CLASS 25
Program 2:
/*
Here is another short example.
Call this file "[Link]".
*/
class Example2 {
public static void main(String args[]) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
[Link]("This is num: " + num);
num = num * 2;
[Link]("The value of num * 2 is ");
[Link](num);
}
}
10-09-2025 VMS CLASS 26
Object Oriented Programming
• Java is built around Object-Oriented Programming.
• In OOP, we focus on objects — things that have data and actions.
• Almost every Java program uses OOP to some extent.
• Before we write programs, we need to understand the idea of OOP.
10-09-2025 VMS CLASS 27
Object Oriented Programming
• Two Ways to Organize a Program (Two Paradigms).
• All programs have two things:
• Code – the instructions (what the program does)
• Data – the information the program works with
• You can organize these in two main ways:
1. Process-Oriented Model
2. Object-Oriented Model
10-09-2025 VMS CLASS 28
Process-Oriented Model
• Program is built around steps (code first).
• Functions or procedures act on data stored somewhere else.
• This is like following a recipe step-by-step.
• Example: C language mostly works this way.
Think: “What is happening?” → Focus is on the actions.
10-09-2025 VMS CLASS 29
Object-Oriented Model
• Program is built around data (objects first).
• Each object contains data and the methods to work on that data.
• This is like a self-contained machine — you don’t need to know how
it works inside, you just use its buttons (methods).
Example: Java uses this approach.
Think: “Who is being affected?” → Focus is on the objects
10-09-2025 VMS CLASS 30
Key Difference
• Process-Oriented: Code controls data (code is the main boss).
• Object-Oriented: Data controls access to code (data is the main boss).
10-09-2025 VMS CLASS 31
Real Life Example
• Process-Oriented: You keep your money in a box, and anyone can
take or add money as they wish if they know the steps — risky!
• Object-Oriented: You keep money in a bank account object. To
interact with it, you must use proper methods like deposit() or
withdraw() — safe and organized.
10-09-2025 VMS CLASS 32
10-09-2025 VMS CLASS 33
Process-Oriented Example (Code acts on data)
// [Link]
public class ProcessOriented {
public static void main(String[] args) {
int length = 5;
int width = 3;
// A separate function calculates the area
int area = calculateArea(length, width);
• Data (length and width) are separate.
[Link]("Area: " + area);
• Code (the function) directly uses them without belonging to
}
any “object.”
static int calculateArea(int l, int w) {
• This is procedure-oriented.
return l * w; // Code directly works with the data
}
}
10-09-2025 VMS CLASS 34
Object-Oriented Example (Data + Code together)
// [Link] public class ObjectOriented {
class Rectangle { public static void main(String[] args) {
int length; Rectangle rect = new Rectangle(5, 3); // Object with data
int width; [Link]("Area: " + [Link]());
Rectangle(int l, int w) { // Constructor }
length = l; }
width = w;
} Explanation:
int calculateArea() { // Method belongs to the object • Data (length, width) and the code (calculateArea()) live
inside the object.
return length * width;
• We don’t just throw data into a random function — we
} ask the object itself to do the work.
} • This is object-oriented.
10-09-2025 VMS CLASS 35
Key Difference
• Process-Oriented:
“I give the data to a free function, it calculates for me.”
• Object-Oriented:
“I ask the object itself to do the calculation — it knows how.”
10-09-2025 VMS CLASS 36
Data Types
• The students should have knowledge of
● Basic Programming Skills:
● Knowledge of C & C++
10-09-2025 VMS CLASS 37
Course Objectives
• To learn primitive constructs JAVA programming language.
• To understand Object Oriented Programming Features of JAVA.
• To gain knowledge on: packages, multithreaded programing and
exceptions
10-09-2025 VMS CLASS 38
Data Types
• An Overview of Java: Object-Oriented Programming (Two Paradigms,
Abstraction, The Three OOP Principles), Using Blocks of Code, Lexical
Issues (Whitespace, Identifiers, Literals, Comments, Separators, The
Java Keywords).
10-09-2025 VMS CLASS 39
What is OOP?
• Object Oriented Programming (OOP) is one of the most widely used
programming paradigm.
Definition:
OOP is a way of writing programs by organizing code into objects that
represent real-world or imaginary things.
10-09-2025 VMS CLASS 40
What is an object ?
• An object has:
• Data (Attributes/Properties) → what it has.
• Methods (Functions/Behaviors) → what it can do.
10-09-2025 VMS CLASS 41
Example: Object (Dog)
• Data: name, breed, age.
• Methods: bark(), eat(), run().
• You can create many Dog objects, each with its own data but using
the same methods.
10-09-2025 VMS CLASS 42
Why OOP is extensively used?
• Well-suited for building trivial and complex applications
• Allows re-use of code, thereby increasing productivity
• New features can be easily built into the existing code
• Reduced production cost and maintenance cost
10-09-2025 VMS CLASS 43
Examples:
Common programming languages used for OOP include :
10-09-2025 VMS CLASS 44
What is Java?
• Java is a widely used programming language that was created in 1995.
• It is owned by Oracle, and it runs on over 3 billion devices.
• Java is used for many things, such as:
• Android mobile apps
• Desktop software
• Websites and web apps
• Web servers and app servers
• Games
• Connecting to databases
• And many other uses!
10-09-2025 VMS CLASS 45
Java Buzzwords
• The buzzwords are special features or characteristics that make Java unique
and popular.
✓Simple
✓Secure
✓Portable
✓Object-oriented
✓Robust
✓Multithreaded
✓Architecture-neutral
✓Interpreted
✓High performance
✓Distributed
✓Dynamic
10-09-2025 VMS CLASS 46
Java Buzzwords : Simple
• Java is designed to be easy to learn and use for professional programmers.
• If you have prior programming knowledge, Java is straightforward and quick to
master.
• Knowing Object-Oriented Programming concepts makes Java learning even
simpler.
• For C/C++ programmers, Java’s syntax and features feel familiar and natural.
• Java eliminates complexities found in older languages, providing a clear, efficient
coding experience.
10-09-2025 VMS CLASS 47
Java Buzzwords : Secure
• Java helps protect your computer from viruses and harmful code.
• It checks code carefully before running it to keep your system safe.
10-09-2025 VMS CLASS 48
Java Buzzwords : Portable
• Java code works on any device or platform (Windows, Linux, Mac).
• "Write Once, Run Anywhere"—you write code once, and it runs
everywhere.
10-09-2025 VMS CLASS 49
Java Buzzwords : Object Oriented
• Java is fundamentally built around objects, combining data and behavior.
• Although influenced by earlier languages, Java was designed fresh, without compatibility
constraints.
• Java achieves a practical balance:
• It emphasizes objects, but not everything is forced into being an object.
• Primitive types (like integers) are kept separate for high performance.
• Java’s object model is clean, practical, and easy to extend, simplifying code organization
and reuse.
10-09-2025 VMS CLASS 50
Java Buzzwords : Robust
• Java is designed to create reliable programs that run smoothly on various
systems.
• It helps programmers detect and fix errors early by enforcing strict type checking:
• Compile-time checks detect many errors before your program runs.
• Run-time checks catch errors that occur while your program is executing.
• Two common issues Java solves effectively:
1. Memory Management Errors:
• Automatically manages memory through garbage collection.
• Eliminates issues like memory leaks and accidental memory corruption found in languages like C/C++.
2. Exception Handling (Run-time Errors):
• Provides structured, easy-to-use exception handling.
• Helps manage unexpected situations clearly (e.g., division by zero, file-not-found errors).
• Java ensures your program behaves predictably across diverse environments,
enhancing reliability and stability.
10-09-2025 VMS CLASS 51
Java Buzzwords : Multithreaded
• Supports simultaneous execution of multiple tasks.
• Ideal for interactive and networked applications.
• Built-in support for thread creation and synchronization.
• Simplifies handling of concurrent tasks (e.g., background processing, UI
updates).
• Improves performance and responsiveness of programs.
10-09-2025 VMS CLASS 52
Java Buzzwords : Architecture Neutral
• Designed for long-lasting and portable code.
• Java programs are not dependent on hardware or the operating system.
• Eliminates issues caused by system upgrades or architecture differences.
• Runs consistently across different platforms using the Java Virtual Machine
(JVM).
• Supports the principle: “Write once, run anywhere”.
10-09-2025 VMS CLASS 53
Java Buzzwords : Interpreted
• Java translates your code into an intermediate format called
bytecode.
• Bytecode runs inside a Java Virtual Machine (JVM), which means you
can run your code easily on different computers without needing to
rewrite it.
10-09-2025 VMS CLASS 54
Java Buzzwords : High Performance
• Java is designed to be fast and efficient.
• Modern JVMs optimize your code automatically, making Java very
fast—close to native languages like C++.
10-09-2025 VMS CLASS 55
Java Buzzwords : Distributed
• Designed for networked (Internet-based) environments.
• Supports TCP/IP protocols for easy communication over networks.
• Allows access to remote resources using URLs, similar to local files.
• Supports Remote Method Invocation (RMI) for calling methods
across systems.
10-09-2025 VMS CLASS 56
Java Buzzwords : Dynamic
• Java uses run-time type information to manage objects safely.
• Supports dynamic linking of classes and libraries while the program is
running.
• Enables code updates during execution without restarting the entire
system.
• Contributes to Java’s flexibility and robustness.
10-09-2025 VMS CLASS 57
Why Use Java?
• Java works on many platforms like Windows, Mac, Linux, and Raspberry Pi.
• It is one of the most popular programming languages in the world.
• There are many job opportunities for people who know Java.
• Java is easy to learn and simple to use.
• It is open-source and free to use.
• Java is secure, fast, and powerful.
• It has a big community with millions of developers for support.
• Java is an object-oriented language, which means it helps organize code
clearly and reuse it, saving time and money.
• Since Java is similar to C++ and C#, it’s easy for programmers to switch
between them.
10-09-2025 VMS CLASS 58
Getting Started
• To check if you have Java installed on a Windows PC, search in the start bar
for Java or type the following in Command Prompt ([Link]):
C:\Users\Your Name>java -version
• If Java is installed, you will see something like this (depending on version):
If you do not have Java installed on your computer, you can download it at
[Link].
10-09-2025 VMS CLASS 59
A First Simple Program
/*
This is a simple Java program.
Call this file "[Link]".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
[Link]("This is a simple Java program.");
}
}
10-09-2025 VMS CLASS 60
Program 2:
/*
Here is another short example.
Call this file "[Link]".
*/
class Example2 {
public static void main(String args[]) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
[Link]("This is num: " + num);
num = num * 2;
[Link]("The value of num * 2 is ");
[Link](num);
}
}
10-09-2025 VMS CLASS 61
Object Oriented Programming
• Java is built around Object-Oriented Programming.
• In OOP, we focus on objects — things that have data and actions.
• Almost every Java program uses OOP to some extent.
• Before we write programs, we need to understand the idea of OOP.
10-09-2025 VMS CLASS 62
Object Oriented Programming
• Two Ways to Organize a Program (Two Paradigms).
• All programs have two things:
• Code – the instructions (what the program does)
• Data – the information the program works with
• You can organize these in two main ways:
1. Process-Oriented Model
2. Object-Oriented Model
10-09-2025 VMS CLASS 63
Process-Oriented Model
• Program is built around steps (code first).
• Functions or procedures act on data stored somewhere else.
• This is like following a recipe step-by-step.
• Example: C language mostly works this way.
Think: “What is happening?” → Focus is on the actions.
10-09-2025 VMS CLASS 64
Object-Oriented Model
• Program is built around data (objects first).
• Each object contains data and the methods to work on that data.
• This is like a self-contained machine — you don’t need to know how
it works inside, you just use its buttons (methods).
Example: Java uses this approach.
Think: “Who is being affected?” → Focus is on the objects
10-09-2025 VMS CLASS 65
Key Difference
• Process-Oriented: Code controls data (code is the main boss).
• Object-Oriented: Data controls access to code (data is the main boss).
10-09-2025 VMS CLASS 66
Real Life Example
• Process-Oriented: You keep your money in a box, and anyone can
take or add money as they wish if they know the steps — risky!
• Object-Oriented: You keep money in a bank account object. To
interact with it, you must use proper methods like deposit() or
withdraw() — safe and organized.
10-09-2025 VMS CLASS 67
10-09-2025 VMS CLASS 68
Process-Oriented Example (Code acts on data)
// [Link]
public class ProcessOriented {
public static void main(String[] args) {
int length = 5;
int width = 3;
// A separate function calculates the area
int area = calculateArea(length, width);
• Data (length and width) are separate.
[Link]("Area: " + area);
• Code (the function) directly uses them without belonging to
}
any “object.”
static int calculateArea(int l, int w) {
• This is procedure-oriented.
return l * w; // Code directly works with the data
}
}
10-09-2025 VMS CLASS 69
Object-Oriented Example (Data + Code together)
// [Link] public class ObjectOriented {
class Rectangle { public static void main(String[] args) {
int length; Rectangle rect = new Rectangle(5, 3); // Object with data
int width; [Link]("Area: " + [Link]());
Rectangle(int l, int w) { // Constructor }
length = l; }
width = w;
} Explanation:
int calculateArea() { // Method belongs to the object • Data (length, width) and the code (calculateArea()) live
inside the object.
return length * width;
• We don’t just throw data into a random function — we
} ask the object itself to do the work.
} • This is object-oriented.
10-09-2025 VMS CLASS 70
Key Difference
• Process-Oriented:
“I give the data to a free function, it calculates for me.”
• Object-Oriented:
“I ask the object itself to do the calculation — it knows how.”
10-09-2025 VMS CLASS 71
Identifiers
• An identifier is the name you give to things in Java:
• classes (HelloWorld)
• methods (printSum)
• variables (totalMarks)
• constants (MAX_SIZE)
• packages ([Link])
• labels (rarely used)
10-09-2025 VMS CLASS 72
Identifiers: rules
• First character must be a letter, underscore _, or currency symbol $.
• A “letter” includes Unicode letters (not just A–Z).
• Next characters can be letters, digits, _, or $.
• Cannot start with a digit (e.g., 2count - Invalid).
• No spaces and no punctuation like -, @, #, !, ., etc.
• Cannot be a Java keyword (e.g., class, if, switch, enum, record, sealed, …).
• Case-sensitive: total, Total, and TOTAL are three different names.
• _ (single underscore) cannot be used as an identifier in Java 9+ (it’s reserved).
• _ (Invalid) but __value (Valid)
• true, false, and null are literals, not keywords—you can’t use them as identifiers.
• Length is (practically) unlimited.
10-09-2025 VMS CLASS 73
Identifiers: Examples
Valid:
int count;
int _index;
int $cache;
int value2;
int café; // Unicode allowed
double π = 3.14; // Unicode letter
int ₹amount = 100;
10-09-2025 VMS CLASS 74
Identifiers: Examples
Invalid:
int 2count; // starts with digit
int first-name; // hyphen not allowed
int class; // keyword
int null; // literal, not allowed
int _; // single underscore (Java 9+)
10-09-2025 VMS CLASS 75
Identifiers: Unicode
• Java source code is based on Unicode from the start, which means you can
use letters from almost any language (e.g., Hindi, Japanese, Greek) in
identifiers.
Examples:
• int // ;25 = عمرArabic letters
• String имя = "Alex"; // Cyrillic letters
• double π = 3.14159; // Greek letter pi
However, best practice in professional code is to stick to ASCII letters (A–Z, a–
z), digits, _, and $ for identifiers. This makes code more readable and
portable.
10-09-2025 VMS CLASS 76
Identifiers: Naming Conventions
• (These aren’t compiler rules, but strong community standards.)
Classes/Interfaces: PascalCase
class StudentRecord {}
interface PaymentService {}
Methods/Variables: camelCase
int totalMarks;
void calculateAverage() {}
10-09-2025 VMS CLASS 77
Identifiers: Naming Conventions
Constants (static final): UPPER_CASE_WITH_UNDERSCORES
• static final int MAX_SCORE = 100;
Packages: all lowercase, dotted
• package [Link];
Tip: Avoid $ in your own names—Java tools sometimes use it for generated
code (e.g., inner classes).
10-09-2025 VMS CLASS 78
Identifiers: How many identifiers are there?
class Example
{
public static void main (String [] args)
{
int a=100;
}
}
10-09-2025 VMS CLASS 79
Identifiers: How many identifiers are there?
class Example
{
public static void main (String [] args)
{
[Link] – Class name
int a=100;
[Link] - method name
}
3. String – Class name
}
4. args – array name
5. a – variable name
10-09-2025 VMS CLASS 80
Identifiers: Example Program
class Example {
public static void main(String[] args) {
int count = 10;
int _index = 1;
int $cache = 5;
int value2 = 42;
int café = 7; // Unicode OK
double π = 3.14159;
[Link](count + _index + $cache + value2 + café);
[Link]("π = " + π);
}
}
10-09-2025 VMS CLASS 81
Identifiers: Example Program
class Example {
public static void main(String[] args) {
// int 2count = 5; // ERROR: cannot start with digit
// int first-name = 1; // ERROR: '-' not allowed
// int class = 3; // ERROR: 'class' is a keyword
// int null = 0; // ERROR: 'null' is not an identifier
// int _ = 1; // ERROR (Java 9+): '_' is a reserved identifier
[Link]("Uncomment lines one by one to see compiler errors.");
}
}
10-09-2025 VMS CLASS 82
Identifiers: Example Program
class Example {
public static void main(String[] args) {
int total = 10;
int Total = 20;
int TOTAL = 30;
[Link](total); // 10
[Link](Total); // 20
[Link](TOTAL); // 30
}
}
10-09-2025 VMS CLASS 83
Identifiers: Summary
• An identifier is the name given to a variable, method, class, package, interface,
etc., to identify it in the program.
• Allowed characters:
•Letters (A–Z, a–z)
•Digits (0–9)
•Underscore (_)
•Dollar sign ($)
•Unicode characters (letters from other languages, symbols like π)
• Cannot start with a digit — e.g., 1value (Invalid).
• No special characters like @, #, %, & (except _ and $).
• Cannot be a Java keyword or reserved word — e.g., class, public, int (Invalid).
• Case-sensitive — age, Age, and AGE are different identifiers.
• Can be of any length, but must be reasonable for readability.
10-09-2025 VMS CLASS 84
Reserved Words
• Reserved words in Java are predefined, special-purpose words that
have a fixed meaning and cannot be used as identifiers (variable
names, class names, method names, etc.).
• These words are part of the Java syntax and are recognized by the
compiler to perform specific tasks.
10-09-2025 VMS CLASS 85
Characteristics of Reserved Words
Predefined Meaning: Each reserved word has a specific purpose.
Case-Sensitive: All must be in lowercase (e.g., class is valid, but Class is
not a keyword unless used as a predefined class).
Not for Naming: Cannot be used to name variables, classes, methods, or
objects.
Part of Syntax: Used in writing Java programs, controlling flow, defining
data types, etc.
10-09-2025 VMS CLASS 86
Reserved Words : Categories
Java has two types of reserved words:
A. Keywords
• Used by Java to define syntax and structure. These have a fixed meaning that the compiler
understands.
Examples: class, if, while, public, static.
B. Reserved Literals
• Special constant values that are also reserved.
• Examples: true, false, null.
10-09-2025 VMS CLASS 87
Reserved Words : Important Points
• Case-sensitive → All reserved words are in lowercase.
Example: class is valid, but Class is not a keyword.
• Cannot be used as names → They cannot be used for variables, classes, or methods.
❌ int public = 5; → Error
• Fixed meaning → You cannot change their purpose.
• Reserved for compiler use only.
10-09-2025 VMS CLASS 88
Reserved Words : Complete list
abstract assert boolean break
byte case catch char
class const* continue default
do double else enum Total keywords: 50 (as per Java 17; older versions may vary slightly)
extends final finally float
for goto* if implements (* const and goto are reserved but not used in Java.*)
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while true false
null
10-09-2025 VMS CLASS 89
Keywords and Purpose
Keyword Purpose
Data Types byte, short, int, long, float, double, char, boolean
Access Control public, private, protected
Class/Interface Related class, interface, enum, abstract, extends, implements
Control Statements if, else, switch, case, default, for, while, do, break, continue, return
Exception Handling try, catch, finally, throw, throws
Modifiers static, final, synchronized, volatile, transient, native, strictfp
Object Handling new, this, super, instanceof
Others import, package, assert
Boolean Literals true, false
Null Literal null
Unused (Reserved) goto, const
10-09-2025 VMS CLASS 90
Reserved Words : Categories
• Cannot be used as identifiers.
• Must be written in lowercase (Java’s keywords are all lowercase).
• If you try to use them as variable names, you get a compile-time error.
10-09-2025 VMS CLASS 91
Example: Program
class Example {
public static void main(String[] args) {
int class = 10; // ERROR: 'class' is a reserved word
}
}
10-09-2025 VMS CLASS 92
How to print the text in the output console
• println()
• print()
• printf()
10-09-2025 VMS CLASS 93
[Link]()
• [Link] — “print a line, then go to next line”.
• It prints whatever you pass, then moves the cursor to a new line.
Syntax:
[Link](value);
10-09-2025 VMS CLASS 94
[Link]()
• [Link]("Hello"); // prints Hello and moves to next line
• [Link](42); // prints an int
• [Link](3.14); // prints a double
• [Link](true); // prints a boolean
• [Link]('A'); // prints a char
10-09-2025 VMS CLASS 95
[Link](): Program
class Example {
public static void main(String[] args) {
[Link]("Hello"); // prints Hello and moves to next line
[Link](42); // prints an int
[Link](3.14); // prints a double
[Link](true); // prints a boolean
[Link]('A'); // prints a char
}
}
10-09-2025 VMS CLASS 96
[Link]()
• [Link]("First line\nSecond line"); // \n = newline
• [Link]("Tab\tSeparated");
• [Link]("Quote: \"Java\"");
10-09-2025 VMS CLASS 97
[Link]()
• [Link] — “print, but stay on the same line”.
• prints without adding a newline.
• Use it when you want to build a line piece by piece.
Syntax:
[Link](value);
10-09-2025 VMS CLASS 98
[Link]()
• [Link]("Hello ");
• [Link]("World"); // output: Hello World (single line)
10-09-2025 VMS CLASS 99
[Link]()
• [Link]("Number: ");
• [Link](10);
• [Link]("\n"); // or:
• [Link]([Link]()); // portable newline
10-09-2025 VMS CLASS 100
[Link](): Program
class Example {
public static void main(String[] args) {
[Link]("Number: ");
[Link]("\n");
[Link](10);
}
}
10-09-2025 VMS CLASS 101
[Link](): Program
class Example {
public static void main(String[] args) {
[Link]("Number: ");
[Link]([Link]()); // portable newline
[Link](10);
}
}
10-09-2025 VMS CLASS 102
[Link](): Program
// Typical usage when we can use:
class Example {
public static void main(String[] args) {
[Link]("Name: ");
[Link]("Sudhakara"); // finish the line with println
}
}
10-09-2025 VMS CLASS 103
[Link]()
• [Link] — “print with formatting (like C’s printf)”.
• prints a formatted string.
• You write a format string with placeholders, then give the values.
Syntax:
[Link]("format text with %placeholders", values...);
10-09-2025 VMS CLASS 104
[Link]()
Basic placeholders:
• %s → string
• %d → integer
• %f → floating-point
• %c → character
• %b → boolean
• %n → newline (use this instead of \n for portability)
10-09-2025 VMS CLASS 105
[Link]()
[Link]("Name: %s, Age: %d%n", "Ravi", 21);
// Name: Ravi, Age: 21
[Link]("Pi ≈ %.2f%n", [Link]); // 2 decimal places
[Link]("Padded: %05d%n", 42); // 00042
[Link]("Width 10: |%10s|%n", "Java"); // right-aligned
[Link]("Left align: |%-10s|%n", "Java");// left-aligned
10-09-2025 VMS CLASS 106
[Link]()
[Link]("Pi ≈ %.2f%n", [Link]);
%.2f → float with 2 digits after the decimal, rounded.
[Link] → 3.141592653589793 becomes 3.14.
%n → newline after printing.
Output:
Pi ≈ 3.14
10-09-2025 VMS CLASS 107
[Link]()
[Link]("Padded: %05d%n", 42);
%05d → integer (d) with width 5, zero-padded on the left.
The number 42 becomes 00042.
%n newline.
Output:
Padded: 00042
10-09-2025 VMS CLASS 108
[Link]()
[Link]("Width 10: |%10s|%n", "Java");
%10s → string in a field of width 10 (default is right-aligned).
"Java" (length 4) is printed with 6 leading spaces so the total is 10.
The vertical bars help you see the padding.
Output:
Width 10: | Java|
10-09-2025 VMS CLASS 109
[Link]()
[Link]("Left align: |%-10s|%n", "Java");
%-10s → width 10, left-aligned because of -.
"Java" printed first, then 6 trailing spaces.
Output:
Left align: |Java |
10-09-2025 VMS CLASS 110
[Link](): Program
class Example {
public static void main(String[] args) {
[Link]("Name: %s, Age: %d%n", "Ravi", 21);
// Name: Ravi, Age: 21
[Link]("Pi ≈ %.2f%n", [Link]); // 2 decimal places
[Link]("Padded: %05d%n", 42); // 00042
[Link]("Width 10: |%10s|%n", "Java"); // right-aligned
[Link]("Left align: |%-10s|%n", "Java");// left-aligned
}
}
10-09-2025 VMS CLASS 111
[Link](): Program
//Table-Style Example
class Example {
public static void main(String[] args) {
[Link]("%-10s %5s %8s%n", "Item", "Qty", "Price");
[Link]("%-10s %5d %8.2f%n", "Pen", 3, 12.5);
[Link]("%-10s %5d %8.2f%n", "Notebook", 1, 99.99);
}
}
10-09-2025 VMS CLASS 112
[Link](): Header Info
[Link]("%-10s %5s %8s%n", "Item", "Qty", "Price");
%-10s → Item left-aligned in 10-wide column.
%5s → Qty right-aligned in width 5.
%8s → Price right-aligned in width 8.
Note the single spaces between the columns in the format string.
Output:
Item Qty Price
10-09-2025 VMS CLASS 113
[Link](): First row
[Link]("%-10s %5d %8.2f%n", "Pen", 3, 12.5);
%-10s → "Pen" left-aligned, padded to width 10 → "Pen ".
%5d → integer 3 right-aligned in width 5 → " 3".
%8.2f → floating 12.5 as 8-wide, 2 decimals → " 12.50".
Width 8 counts everything (spaces + digits + decimal point).
Output:
Pen 3 12.50
10-09-2025 VMS CLASS 114
[Link](): Second row
[Link]("%-10s %5d %8.2f%n", "Notebook", 1, 99.99);
%-10s → "Notebook" (8 chars) + 2 trailing spaces to make 10.
%5d → " 1".
%8.2f → " 99.99" (already has 2 decimals).
Output:
Notebook 1 99.99
10-09-2025 VMS CLASS 115
[Link]():
Final Output:
Item Qty Price
Pen 3 12.50
Notebook 1 99.99
10-09-2025 VMS CLASS 116
Practice Program
class Example {
public static void main(String[] args) {
// print vs println
[Link]("A");
[Link]("B");
[Link]("C"); // prints ABC then newline
[Link]("D"); // prints D on its own line
// printf basics
String name = "Anita";
int score = 98;
double pct = 0.9753;
[Link]("Name: %s, Score: %d, Percent: %.2f%%%n", name, score, pct * 100);
}
}
10-09-2025 VMS CLASS 117
Variable
• A variable in Java is a named memory location used to store data during
program execution.
• Think of it like a box with a label – the box stores data, and the label is the
variable name.
Syntax:
dataType variableName = value;
dataType → Specifies the type of data (int, float, char, String, etc.)
variableName → Name of the variable (follows identifier rules)
value → Optional initial value
10-09-2025 VMS CLASS 118
Variable
Example:
int age = 20;
int → Data type (tells what kind of value this variable can hold)
age → Variable name (label on the box)
20 → Value stored in the variable
10-09-2025 VMS CLASS 119
Variable Declaration Vs Initialization
Declaration: Specifying data type and variable name.
int number; // declaration
Initialization: Assigning a value to the variable.
number = 10; // initialization
You can also do both in one step:
int number = 10; // declaration + initialization
10-09-2025 VMS CLASS 120
Changing a variable value
int count = 5;
[Link](count); // prints 5
count = 10; // value changed
[Link](count); // prints 10
10-09-2025 VMS CLASS 121
Variables : Program
// Demonstarting how to declare and use a variable in Java
class Example {
public static void main(String[] args) {
// Declaring and initializing variables
// Integer variable
int age = 25; Output:
// String variable
String name = "Raju"; Age: 25
// Double variable Name: Raju
double salary = 40000.50; Salary: 40000.5
// Displaying the values of variables
[Link]("Age: " + age);
[Link]("Name: " + name);
[Link]("Salary: " + salary);
}
}
10-09-2025 VMS CLASS 122
Data Types
• In Java, data types tell the compiler what kind of data a variable can
hold.
For example:
• If you want to store a number → you use int
• If you want to store a decimal value → you use float or double
• If you want to store text → you use char or String
Think of it like boxes of different shapes. Each type of box can only hold a
specific kind of item.
10-09-2025 VMS CLASS 123
Data Types
10-09-2025 VMS CLASS 124
Datatypes
Data Type Default Value Default size Range
byte 0 1 byte or 8 bits -128 to 127
short 0 2 bytes or 16 bits -32,768 to 32,767
int 0 4 bytes or 32 bits 2,147,483,648 to 2,147,483,647
9,223,372,036,854,775,808 to
long 0 8 bytes or 64 bits
9,223,372,036,854,775,807
float 0.0f 4 bytes or 32 bits 1.4e-045 to 3.4e+038
double 0.0d 8 bytes or 64 bits 4.9e-324 to 1.8e+308
char ‘u0000’ 2 bytes or 16 bits 0 to 65536
boolean FALSE 1 byte or 2 bytes 0 or 1
10-09-2025 VMS CLASS 125
Primitive Data Types
• Integers This group includes byte, short, int, and long, which are for
whole-valued signed numbers.
• Floating-point numbers – This group includes float and double, which
represent numbers with fractional precision.
• Characters This group includes char, which represents symbols in a
character set, like letters and numbers.
• Boolean This group includes boolean, which is a special type for
representing true/false values.
10-09-2025 VMS CLASS 126
byte
Definition:
8-bit signed integer. Used to save memory in large arrays.
Example:
• byte b = 100;
10-09-2025 VMS CLASS 127
byte: Program
public class ByteExample {
public static void main(String[] args) {
byte age = 25;
[Link]("Age: " + age);
}
}
10-09-2025 VMS CLASS 128
short
Definition:
16-bit signed integer. Larger range than byte.
Example:
short s = 32000;
10-09-2025 VMS CLASS 129
short: Program
public class ShortExample {
public static void main(String[] args) {
short distance = 15000;
[Link]("Distance: " + distance);
}
}
10-09-2025 VMS CLASS 130
int
Definition:
32-bit signed integer. Most commonly used for whole numbers.
Example:
int num = 100000;
10-09-2025 VMS CLASS 131
int: Program
public class IntExample {
public static void main(String[] args) {
int salary = 50000;
[Link]("Salary: " + salary);
}
}
10-09-2025 VMS CLASS 132
long
Definition:
64-bit signed integer. Used when a wider range is needed.
Example:
long l = 10000000000L; // Note the 'L'
10-09-2025 VMS CLASS 133
long: Program
public class LongExample {
public static void main(String[] args) {
long population = 7800000000L;
[Link]("World Population: " + population);
}
}
10-09-2025 VMS CLASS 134
float
Definition:
32-bit floating-point (decimal numbers). Ends with f or F.
Example:
float pi = 3.14f;
10-09-2025 VMS CLASS 135
float: Program
public class FloatExample {
public static void main(String[] args) {
float price = 19.99f;
[Link]("Price: " + price);
}
}
10-09-2025 VMS CLASS 136
double
Definition:
64-bit floating-point. More precise than float.
Example:
double d = 3.14159265358979;
10-09-2025 VMS CLASS 137
double: Program
public class DoubleExample {
public static void main(String[] args) {
double pi = 3.14159265358979;
[Link]("Value of PI: " + pi);
}
}
10-09-2025 VMS CLASS 138
char
Definition:
16-bit Unicode character. Enclosed in single quotes ' '.
Example:
char c = 'A';
10-09-2025 VMS CLASS 139
char: Program
public class CharExample {
public static void main(String[] args) {
char grade = 'A';
[Link]("Grade: " + grade);
}
}
10-09-2025 VMS CLASS 140
boolean
Definition:
Represents one of two values: true or false.
Example:
boolean flag = true;
10-09-2025 VMS CLASS 141
boolean: Program
public class BooleanExample {
public static void main(String[] args) {
boolean isJavaFun = true;
[Link]("Is Java fun? " + isJavaFun);
}
}
10-09-2025 VMS CLASS 142
When to use?
• Use byte/short/int/long for whole numbers.
• Use float/double for decimal numbers.
• Use char for single characters.
• Use boolean for true/false logic.
10-09-2025 VMS CLASS 143
String
Definition:
Unlike primitive data types, String is not a primitive type — it is a class in
Java (from [Link] package). However, it is so commonly used that it
behaves like a special data type for storing sequences of characters (text).
A String is a collection of characters enclosed within double quotes (" ").
Example:
String variableName = "value";
10-09-2025 VMS CLASS 144
String
Example:
String variableName = "value";
String → Data type (class)
variableName → Identifier (name of the variable)
"value" → Sequence of characters enclosed in double quotes
10-09-2025 VMS CLASS 145
String: Program
public class StringExample {
public static void main(String[] args) {
String name = "Java Programming"; // String variable
[Link](name); // Prints: Java Programming
}
}
10-09-2025 VMS CLASS 146
String: Program
public class StringOperations {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
// Concatenation
String result = str1 + " " + str2;
[Link](result); // Output: Hello World
// Length of string
[Link]("Length: " + [Link]()); // Output: 5
// Uppercase
[Link]([Link]()); // Output: WORLD
}
}
10-09-2025 VMS CLASS 147
Operators
Operators: Arithmetic Operators, Relational Operators, Boolean Logical
Operators, The Assignment Operator, The ? Operator, Operator
Precedence, Using Parentheses.
10-09-2025 VMS CLASS 148
What is Operator
• Arithmetic Operators
• Unary Operators
• Assignment Operator
• Relational Operators
• Logical Operators
• Ternary Operator
• Bitwise Operators
• Shift Operators
• instance of operator
10-09-2025 VMS CLASS 149
Arithmetic Operators
Operator Description Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2
% Modulus (remainder) 10 % 3 1
10-09-2025 VMS CLASS 150
Arithmetic Operators: Program
class ArithmeticExample {
public static void main(String[] args) {
int a = 10, b = 3;
[Link]("a + b = " + (a + b));
[Link]("a - b = " + (a - b));
[Link]("a * b = " + (a * b));
[Link]("a / b = " + (a / b)); // integer division
[Link]("a % b = " + (a % b));
}
}
10-09-2025 VMS CLASS 151
Relational Operators
Used to compare values. They always return a boolean (true or false).
Operator Description Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 5>3 true
< Less than 5<3 false
>= Greater or equal 5 >= 5 true
<= Less or equal 3 <= 5 true
10-09-2025 VMS CLASS 152
Relational Operators: Program
class RelationalExample {
public static void main(String[] args) {
int a = 10, b = 20;
[Link](a == b); // false
[Link](a != b); // true
[Link](a > b); // false
[Link](a < b); // true
}
}
10-09-2025 VMS CLASS 153
Logical Operators
Logical operators are used to combine multiple conditions (boolean
expressions). They always return either true or false.
Operator Description Example Result
Returns true if both
&& (AND) (5 > 2) && (8 > 5) true
conditions are true
Returns true if any one
|| (OR) (5 > 2) || (8 < 5) true
condition is true
Reverses the result, true
! (NOT) becomes false, false !(5 > 2) false
becomes true
10-09-2025 VMS CLASS 154
Logical Operators
Logical operators are used to combine multiple conditions (boolean
expressions). They always return either true or false.
Condition A Condition B A && B
true true true
true false false
false true false
false false false
10-09-2025 VMS CLASS 155
Logical Operators
Logical operators are used to combine multiple conditions (boolean
expressions). They always return either true or false.
Condition A Condition B A || B
true true true
true false true
false true true
false false false
10-09-2025 VMS CLASS 156
Logical Operators
Logical operators are used to combine multiple conditions (boolean
expressions). They always return either true or false.
Condition A !A
true false
false true
10-09-2025 VMS CLASS 157
Logical Operators: Program
public class LogicalOperatorsDemo {
public static void main(String[] args) {
boolean A = true;
boolean B = false;
[Link]("A && B = " + (A && B)); // AND
[Link]("A || B = " + (A || B)); // OR
[Link]("!A = " + (!A)); // NOT
[Link]("!B = " + (!B)); // NOT
}
}
10-09-2025 VMS CLASS 158
Logical Operators: Program
public class LogicalAndExample {
public static void main(String[] args) {
int a = 10, b = 20;
// Both conditions must be true
if (a > 5 && b > 15) {
[Link]("Both conditions are true");
} else {
[Link]("At least one condition is false");
}
}
}
10-09-2025 VMS CLASS 159
Logical Operators: Program
public class LogicalOrExample {
public static void main(String[] args) {
int x = 5, y = 3;
// At least one condition should be true
if (x > 10 || y < 5) {
[Link]("At least one condition is true");
} else {
[Link]("Both conditions are false");
}
}
}
10-09-2025 VMS CLASS 160
Logical Operators: Program
public class LogicalNotExample {
public static void main(String[] args) {
boolean isJavaFun = true;
[Link]("Original value: " + isJavaFun);
[Link]("After applying ! operator: " + !isJavaFun);
}
}
10-09-2025 VMS CLASS 161
Assignment Operators
Assignment operators are used to assign values to variables.
Operator Meaning Example Result
= Assign value a = 10 a = 10
+= Add and assign a = 5; a += 3; a=8
-= Subtract and assign a = 10; a -= 4; a=6
*= Multiply and assign a = 4; a *= 2; a=8
/= Divide and assign a = 20; a /= 5; a=4
Modulus (remainder) and
%= a = 15; a %= 4; a=3
assign
10-09-2025 VMS CLASS 162
Assignment Operators: Program
class AssignmentOperatorsDemo {
public static void main(String[] args) { a *= 2; // a = a * 2
int a = 10; [Link]("After a *= 2: " + a);
[Link]("a = " + a); a /= 4; // a = a / 4
[Link]("After a /= 4: " + a);
a += 5; // a = a + 5
[Link]("After a += 5: " + a); a %= 3; // a = a % 3
[Link]("After a %= 3: " + a);
a -= 3; // a = a - 3 }
[Link]("After a -= 3: " + a); }
10-09-2025 VMS CLASS 163
The ? Operator
What is the ?: Operator?
• It is called the Ternary Operator (because it works on 3 operands).
• It is a shorthand of if-else statement.
10-09-2025 VMS CLASS 164
The ? Operator
Syntax:
variable = (condition) ? expression_if_true : expression_if_false;
How it works:
• The condition is checked.
• If condition is true → the first expression is chosen.
• If condition is false → the second expression is chosen.
10-09-2025 VMS CLASS 165
The ? Operator: Program
class TernaryExample1 {
public static void main(String[] args) {
int number = 10;
// Using ternary operator
String result = (number % 2 == 0) ? "Even" : "Odd";
[Link]("The number is: " + result);
}
}
10-09-2025 VMS CLASS 166
The ? Operator: Program
public class TernaryExample2 {
public static void main(String[] args) {
int a = 15, b = 20;
// Find maximum
int max = (a > b) ? a : b;
[Link]("Maximum is: " + max);
}
}
10-09-2025 VMS CLASS 167
The ? Operator: Program
public class TernaryExample1 {
public static void main(String[] args) {
int number = 10;
// Using ternary operator
String result = (number % 2 == 0) ? "Even" : "Odd";
[Link]("The number is: " + result);
}
}
10-09-2025 VMS CLASS 168
The ? Operator: Program
// Program to print the absolute value of a number.
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
[Link]("Absolute value of ");
[Link](i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
[Link]("Absolute value of ");
[Link](i + " is " + k);
}
}
10-09-2025 VMS CLASS 169
The ? Operator: Program
public class TernaryExample3 {
public static void main(String[] args) {
int marks = 75;
String grade = (marks >= 90) ? "A" :
(marks >= 75) ? "B" :
(marks >= 50) ? "C" : "Fail";
[Link]("Grade: " + grade);
}
}
10-09-2025 VMS CLASS 170
The ? Operator: Program
public class TernaryExample3 {
public static void main(String[] args) {
if (marks >= 90)
int marks = 75; grade = "A";
else if (marks >= 75)
grade = "B";
String grade = (marks >= 90) ? "A" : else if (marks >= 50)
(marks >= 75) ? "B" : grade = "C";
(marks >= 50) ? "C" : "Fail"; else
grade = "Fail";
[Link]("Grade: " + grade);
}
}
10-09-2025 VMS CLASS 171
The ? Operator: When to Use?
• Use ternary operator for short, simple decisions.
• If the logic is complex, better use if-else (to keep code readable).
10-09-2025 VMS CLASS 172
Operator Precedence and Associativity
• Precedence and associative rules are applied when dealing with
hybrid equations that involve more than one type of operator.
• In such cases, these rules determine which part of the equation to
consider first, as there can be many different valuations for the same
equation.
10-09-2025 VMS CLASS 173
Operator Precedence
• In Java, operator precedence specifies the order in which operations
are performed within an expression.
• When an expression contains multiple operators, those with higher
precedence are evaluated before those with lower precedence.
10-09-2025 VMS CLASS 174
Operator Precedence: Example
Expression:
10+20*30
• The expression contains two operators, + (addition) and *
(multiplication). According to operator precedence, multiplication (*)
has higher precedence than addition (+), so multiplication is checked
first.
• After evaluating multiplication, the addition operator is then
evaluated to give the final result.
10-09-2025 VMS CLASS 175
Operator Precedence: Example
class OperatorPrecedenceExample {
public static void main(String[] args)
{
// Multiplication has higher precedence than
// addition
int result = 10 + 20 * 30;
[Link]("Result: " + result);
20 * 30 = 600 // first execute this expression
} 10 + 600 = 610// next execute this
} expression
10-09-2025 VMS CLASS 176
10-09-2025 VMS CLASS 177
Operator Associativity
• Operator associativity in Java determines the order of evaluation
when multiple operators of the same precedence appear in an
expression.
Two Types of Associativity:
1. Left-to-Right Associativity
2. Right-to-Left Associativity
10-09-2025 VMS CLASS 178
Left-to-Right Associativity
• When multiple operators of the same precedence appear in an
expression, they are evaluated from left to right.
For example, in the expression a + b - c, addition and subtraction have
the same precedence and are left-associative, so the expression is
evaluated as (a + b) - c.
10-09-2025 VMS CLASS 179
Left-to-Right Associativity
Operators with left-to-right associativity include:
• Arithmetic operators: +, -, *, /, %
• Relational operators: >, <, >=, <=
• Logical AND/OR: &&, ||
• Bitwise operators: &, |, ^, <<, >>
10-09-2025 VMS CLASS 180
Left-to-Right Associativity: Program
class LeftToRight {
public static void main(String[] args)
{
int a = 10, b = 5, c = 2;
int result = a - b + c; // evaluated as (10 - 5) + 2 = 7
[Link]("Final output " + result);
}
Explanation: Here, - and + have the same precedence and are
} left-associative, so evaluation happens left to right.
10-09-2025 VMS CLASS 181
Right-to-Left Associativity
• Right-to-Left Associativity means that operators are evaluated from
right to left when they have the same precedence.
• Operators with right-to-left associativity include:
• Assignment operators: =, +=, -=, etc.
• Unary operators: ++, --, !, ~
10-09-2025 VMS CLASS 182
Right-to-Left Associativity
class RightToLeftAssociativity {
public static void main(String[] args)
{
int a, b;
a = b = 4; // evaluated as a = (b = 4)
[Link]("a: " + a); // 4
[Link]("b: " + b); // 4
}
} Explanation: The assignment = is right-associative, so b = 4 is
evaluated first, then a = b.
10-09-2025 VMS CLASS 183
Example:
10-09-2025 VMS CLASS 184
Example: Precedence and Associativity
• In general, operator precedence and associativity are applied
together in expressions.
Example:
exp = 100 + 200 / 10 - 3 * 10
where the division (/) and multiplication (*) operators have the same precedence
but are evaluated before addition (+) and subtraction (-). Due to left-to-right
associativity, the division is evaluated first, followed by multiplication. After
evaluating the division and multiplication, the addition and subtraction are
evaluated from left to right, giving the final result.
10-09-2025 VMS CLASS 185
Example: Precedence and Associativity
10-09-2025 VMS CLASS 186
Right-to-Left Associativity
class OperatorPrecedence {
public static void main(String[] args)
{
int result = 100 + 200 / 10 - 3 * 10;
// Verifying the result of the same expression
[Link]("Final Output: " + result);
}
}
10-09-2025 VMS CLASS 187
Program:
Write a Java program to compute the distance that light will travel in a given number of
days.
• The speed of light is approximately 186,000 miles per second.
• Since the number of seconds in 1000 days is very large, the calculation requires the use
of long variables.
• The program should compute the total distance traveled by light in 1000 days and display
the result.
• It should also demonstrate that such a large value cannot be stored in an int variable.
10-09-2025 VMS CLASS 188
Program:
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
[Link]("In " + days);
[Link](" days light will travel about ");
[Link](distance + " miles.");
} In 1000 days light will travel about 16070400000000 miles.
}
10-09-2025 VMS CLASS 189
Using Parenthesis
“Parentheses increase the priority of the operations inside them. Using
them is often necessary to ensure the expression produces the
intended result.”
Expression 1: 4+5*6
Expression 2: (4+5)*6
10-09-2025 VMS CLASS 190
Using Parenthesis
Example:
Case 1: Without Parenthesis
a >> b + 3;
Here, + has higher precedence than >>.
So, it is treated as:
a >> (b + 3);
First b + 3 is done, then shift a right.
10-09-2025 VMS CLASS 191
Using Parenthesis
Example:
Case 1: Without Parenthesis
a >> b + 3;
Here, + has higher precedence than >>.
So, it is treated as:
a >> (b + 3); First b + 3 is done, then shift a right.
10-09-2025 VMS CLASS 192
Using Parenthesis
Example:
Case 1: With Parenthesis
(a >> b) + 3;
Now, a is first shifted right by b, and then 3 is added.
So the meaning changes completely!
10-09-2025 VMS CLASS 193
Complex Expressions
Expression:
a | 4 + c >> b & 7
Confusing ?
This is hard to read because many operators are mixed.
10-09-2025 VMS CLASS 194
Complex Expressions
Expression:
a | 4 + c >> b & 7
Adding parentheses makes it clear:
(a | (((4 + c) >> b) & 7))
Now anyone can immediately see the order of execution.
10-09-2025 VMS CLASS 195
Conditional Statements
• If
• If else
• If else if ladder
• Nested if
• While loop
• Do while loop
• For loop
10-09-2025 VMS CLASS 196
Simple if statement:
• The if statement is used when you want to execute a block of code
only if a certain condition is true.
Syntax:
if (condition) {
// code executes if the condition is true
}
10-09-2025 VMS CLASS 197
Example:
class Example {
public static void main(String[] args) {
boolean isJavaFun = true;
if (isJavaFun) {
[Link]("Yes, Java is fun!");
}
}
}
10-09-2025 VMS CLASS 198
Example:
class Example {
public static void main(String[] args) {
boolean isLightOn = true;
if (isLightOn) {
[Link]("The light is on.");
}
}
}
10-09-2025 VMS CLASS 199
Example:
class Example {
public static void main(String[] args) {
boolean isLightOn = true;
if (isLightOn) {
[Link]("The light is on.");
}
}
}
Note: Writing if (isLightOn) is the same as writing if (isLightOn == true), but shorter and easier to read.
10-09-2025 VMS CLASS 200
Example:
class Main {
public static void main(String[] args) {
boolean isLightOn = false;
if (isLightOn) {
[Link]("The light is on."); // This will not be printed
}
[Link]("This line always runs.");
}
}
10-09-2025 VMS CLASS 201
Example:
class Main {
public static void main(String[] args) {
if (20 > 18) {
[Link]("20 is greater than 18"); // obviously
}
}
}
10-09-2025 VMS CLASS 202
Example:
class Main {
public static void main(String[] args) {
int x = 20;
int y = 18;
if (x > y) {
[Link]("x is greater than y");
}
}
}
10-09-2025 VMS CLASS 203
Example:
class Main {
public static void main(String[] args) {
int x = 20;
int y = 20;
if (x == y) {
[Link]("x is equal to y");
}
}
}
10-09-2025 VMS CLASS 204
Example:
class IfExample {
public static void main(String[] args) {
int marks = 80;
if (marks >= 50) {
[Link]("You passed!");
}
}
}
10-09-2025 VMS CLASS 205
if-else statement:
• Executes one block if condition is true, another if it is false.
Syntax:
if (condition) {
// executes if true
} else {
// executes if false
}
10-09-2025 VMS CLASS 206
Example:
class IfElseExample {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
[Link]("Even");
} else {
[Link]("Odd");
}
}
}
10-09-2025 VMS CLASS 207
if-else-if Ladder:
• Used when you have multiple conditions.
Syntax:
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// default block
}
10-09-2025 VMS CLASS 208
Example:
public class IfElseIfExample {
public static void main(String[] args) {
int marks = 65;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else if (marks >= 50) {
[Link]("Grade C");
} else {
[Link]("Fail");
}
}
}
10-09-2025 VMS CLASS 209
Traditional switch Statement:
• The switch statement executes one block of code among many options, based on the value of an expression.
Syntax:
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
...
default:
// default block
}
10-09-2025 VMS CLASS 210
class SwitchExample {
public static void main(String[] args) {
Example: int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
case 4: [Link]("Thursday"); break;
case 5: [Link]("Friday"); break;
case 6: [Link]("Saturday"); break;
case 7: [Link]("Sunday"); break;
default: [Link]("Invalid day");
}
}
}
10-09-2025 VMS CLASS 211
break keyword:
• When Java reaches a break keyword, it breaks out of the switch block.
• This will stop the execution of more code and case testing inside the
block.
• When a match is found, and the job is done, it's time for a break.
There is no need for more testing.
Advantage: A break can save a lot of execution time because it
"ignores" the execution of all the rest of the code in the switch block.
10-09-2025 VMS CLASS 212
default keyword:
• The default keyword specifies some code to run if there is no case
match.
• if the default statement is used as the last statement in a switch
block, it does not need a break.
10-09-2025 VMS CLASS 213
public class Main {
Example: public static void main(String[] args) {
(default) int day = 4;
switch (day) {
case 6:
[Link]("Today is Saturday");
break;
case 7:
[Link]("Today is Sunday");
break;
default:
[Link]("Looking forward to the Weekend");
}
}
}
10-09-2025 VMS CLASS 214
Real-Life Example: "open a door" if the user enters the correct code:
class Main {
public static void main(String[] args) {
int doorCode = 1337;
if (doorCode == 1337) {
[Link]("Correct code. The door is now open.");
} else {
[Link]("Wrong code. The door remains closed.");
}
}
}
10-09-2025 VMS CLASS 215
Real-Life Example: Positive/Negative/Zero
class Main {
public static void main(String[] args) {
int myNum = 10; // Is this a positive or negative number?
if (myNum > 0) {
[Link]("The value is a positive number.");
} else if (myNum < 0) {
[Link]("The value is a negative number.");
} else {
[Link]("The value is 0.");
}
}
}
10-09-2025 VMS CLASS 216
Real-Life Example: Positive/Negative/Zero
class Main {
public static void main(String[] args) {
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
[Link]("Old enough to vote!");
} else {
[Link]("Not old enough to vote.");
}
}
}
10-09-2025 VMS CLASS 217
Loops
• Loops can execute a block of code as long as a specified
condition is reached.
• Loops are handy because they save time, reduce errors, and
they make code more readable.
10-09-2025 VMS CLASS 218
While loop
• The while loop loops through a block of code as long as a
specified condition is true:
Syntax:
while (condition) {
// code block to be executed
}
10-09-2025 VMS CLASS 219
While loop: Program
class Main {
public static void main(String[] args) {
int i = 0;
while (i < 20) {
[Link](i);
i++;
}
}
}
10-09-2025 VMS CLASS 220
While loop: Program
class Main {
public static void main(String[] args) {
int countdown = 3;
while (countdown > 0) {
[Link](countdown);
countdown--;
}
[Link]("Happy New Year!!");
}
}
10-09-2025 VMS CLASS 221
Do while loop
• The do/while loop is a variant of the while loop.
• This loop will execute the code block once, before checking if the
condition is true.
• Then it will repeat the loop as long as the condition is true.
Syntax:
do {
// code block to be executed
}
while (condition); Note: The semicolon ; after the while condition is required!
10-09-2025 VMS CLASS 222
Do While loop: Program
class Main {
public static void main(String[] args) {
int i = 10;
do {
[Link]("i is " + i);
i++;
} while (i < 5);
}
}
10-09-2025 VMS CLASS 223
Difference
• The do/while loop always runs at least once, even if the
condition is already false. This is different from a regular while
loop, which would skip the loop entirely if the condition is false
at the start.
This behavior makes do/while useful when you want to ensure
something happens at least once, like showing a message or
asking for user input.
10-09-2025 VMS CLASS 224
Example Programs
class Main {
public static void main(String[] args) {
int i = 10;
do {
[Link]("i is " + i);
i++;
} while (i < 5);
}
}
10-09-2025 VMS CLASS 225
for loop
• When you know exactly how many times you want to loop
through a block of code, use the for loop instead of a while
loop:
Syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
10-09-2025 VMS CLASS 226
for loop
Syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
10-09-2025 VMS CLASS 227
for loop: Program
class Main {
public static void main(String[] args) {
for (int i = 0; i <6; i++) {
[Link](i);
}
}
}
10-09-2025 VMS CLASS 228
for loop: Program (Print Even numbers)
class Main {
public static void main(String[] args) {
for (int i = 0; i <= 10; i = i + 2) {
[Link](i);
}
}
}
10-09-2025 VMS CLASS 229
for loop: Program (Sum of numbers)
class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum = sum + i;
}
[Link]("Sum is " + sum);
}
}
10-09-2025 VMS CLASS 230
for loop: Program (Countdown)
class Main {
public static void main(String[] args) {
for (int i = 5; i > 0; i--) {
[Link](i);
}
}
}
10-09-2025 VMS CLASS 231
Nested Loops
• It is also possible to place a loop inside another loop. This is
called a nested loop.
• The "inner loop" will be executed one time for each iteration of
the "outer loop":
10-09-2025 VMS CLASS 232
Nested Loops
public class Main {
public static void main(String[] args) {
// Outer loop.
for (int i = 1; i <= 2; i++) {
[Link]("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
[Link](" Inner: " + j); // Executes 6 times (2 * 3)
}
}
}
}
10-09-2025 VMS CLASS 233
Multiplication Table : Example
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
[Link](i * j + " ");
}
[Link]();
}
}
}
10-09-2025 VMS CLASS 234
Jump Statements
In Java, jump statements are used to transfer control from one
part of the program to another. The three main jump statements
are:
1. break
2. continue
3. return
10-09-2025 VMS CLASS 235
break
• Break is used to exit a loop or switch statement immediately.
• Control jumps out of the loop and continues after it.
10-09-2025 VMS CLASS 236
Break: Example
public class Example {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // exit the loop when i = 3
}
[Link](i);
}
}
}
10-09-2025 VMS CLASS 237
continue
• Skips the current iteration of the loop and jumps to the next
iteration.
• Control moves to the loop’s next cycle.
10-09-2025 VMS CLASS 238
Continue: example
public class Example {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // skip printing when i = 3
}
[Link](i);
}
}
}
10-09-2025 VMS CLASS 239
return
• Used to exit from a method and return a value (if method type is
not void).
• Immediately ends the method execution.
10-09-2025 VMS CLASS 240
return
public class Example {
public static void main(String[] args) {
[Link]("Before return statement");
if (true) {
return; // exit from main method
}
// This line will never be executed
[Link]("After return statement");
}
} Once return is executed, the method ends.
10-09-2025 VMS CLASS 241
Summary
Statement Where Used Effect
break Loops, switch Exits the loop/switch immediately
Skips current iteration, continues
continue Loops only
with next
Ends method execution, may
return Methods
return a value
10-09-2025 VMS CLASS 242
Break: Real-life Example (Searching)
public class BreakRealTime {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int search = 30;
for (int num : numbers) {
if (num == search) {
[Link]("Found: " + num);
break; // Stop searching once found
}
}
}
} Use case: Searching in an array or list (stop early once found).
10-09-2025 VMS CLASS 243
continue: Real-life Example (Filtering)
//Skip unwanted values but keep looping.
public class Example {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
[Link]("Odd number: " + i);
}
}
}
Use case: Filtering odd/even numbers, skipping invalid user input, etc.
10-09-2025 VMS CLASS 244
return: Real-life Example (Example in Input Validation)
//Exit from a method when the result is already known..
public class Example {
public static void main(String[] args) {
checkAge(15);
checkAge(20);
}
static void checkAge(int age) {
if (age < 18) {
[Link]("Access Denied!");
return; // Exit method early
}
[Link]("Access Granted!");
}
} Use case: Validating inputs, ending execution when conditions are not met.
10-09-2025 VMS CLASS 245
Quick Real-World Analogies
• break → Like pressing the stop button in a search; once found,
no need to continue.
• continue → Like skipping one student in attendance but
continuing with the next.
• return → Like finishing a task early when you already know the
result, and exiting.
Use case: Validating inputs, ending execution when conditions are not met.
10-09-2025 VMS CLASS 246
Scanner class
• The Scanner class (in [Link] package) is used to take input
from the user.
• It can read different types of input: integers, floats, strings,
characters, etc.
• Before using, you must import it:
import [Link];
10-09-2025 VMS CLASS 247
Scanner class
• Creating Scanner Object:
Scanner sc = new Scanner([Link]);
[Link] → standard input stream (keyboard).
sc → reference to the Scanner object.
10-09-2025 VMS CLASS 248
Scanner class: Common Scanner Methods
Method Description Example
nextInt() Reads an integer int a = [Link]();
nextDouble() Reads a double double d = [Link]();
nextFloat() Reads a float float f = [Link]();
nextLong() Reads a long long l = [Link]();
nextBoolean() Reads a boolean (true/false) boolean b = [Link]();
Reads a single word (string without
next() String s = [Link]();
spaces)
nextLine() Reads a full line (including spaces) String line = [Link]();
next().charAt(0) Reads a single character char c = [Link]().charAt(0);
10-09-2025 VMS CLASS 249
Example Program: Calculator
import [Link]; if (op == '+') result = a + b;
public class Calculator { else if (op == '-') result = a - b;
public static void main(String[] args) { else if (op == '*') result = a * b;
Scanner sc = new Scanner([Link]); else if (op == '/') result = a / b;
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Result: " + result);
[Link]("Enter second number: ");
int b = [Link]();
[Link]();
[Link]("Enter operation (+, -, *, /): ");
char op = [Link]().charAt(0); }
}
10-09-2025 VMS CLASS 250
Arrays
• An array is a collection of elements of the same data type stored in
contiguous memory locations.
• It allows us to store multiple values under a single name, instead of
declaring separate variables for each value.
10-09-2025 VMS CLASS 251
Why Arrays?
• Imagine you need to store marks of 100 students.
• Without arrays → you’d write 100 variables like mark1, mark2, …,
mark100.
• With arrays → you just write:
int marks[] = new int[100];
10-09-2025 VMS CLASS 252
Arrays
10-09-2025 VMS CLASS 253
Declaration of Arrays
There are three steps:
• Declare → define the array reference
• Allocate memory → create array object in memory
• Initialize values
Syntax:
dataType[] arrayName; // preferred way
dataType arrayName[]; // also valid
10-09-2025 VMS CLASS 254
How elements are stored?
10-09-2025 VMS CLASS 255
Example 1: Declare, Allocate, and Initialize
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = new int[5]; // Step 1+2: Declare & allocate memory
// Step 3: Initialize values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Accessing values
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
}
}
}
10-09-2025 VMS CLASS 256
Example 1: Declare, Allocate, and Initialize
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = new int[5]; // Step 1+2: Declare & allocate memory
// Step 3: Initialize values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
Output:
// Accessing values
for (int i = 0; i < [Link]; i++) { Element at index 0: 10
[Link]("Element at index " + i + ": " + numbers[i]); Element at index 1: 20
} Element at index 2: 30
} Element at index 3: 40
}
Element at index 4: 50
10-09-2025 VMS CLASS 257
Shortcut Initialization
int[] nums = {1, 2, 3, 4, 5};
10-09-2025 VMS CLASS 258
Array Properties
• Fixed size → cannot grow/shrink after creation.
• Index-based → first element at index 0.
• Homogeneous elements → all elements of the same type.
• Length property → use [Link] to get size.
10-09-2025 VMS CLASS 259
Example 2: Sum of Array Elements
public class SumArray {
public static void main(String[] args) {
int[] marks = {90, 85, 70, 95, 80};
int sum = 0;
for (int i = 0; i < [Link]; i++) {
sum += marks[i];
}
[Link]("Total marks = " + sum);
}
}
10-09-2025 VMS CLASS 260
Example 2: For-each loop
public class ForEachExample {
public static void main(String[] args) {
String[] names = {"Java", "Python", "C++", "C"};
for (String lang : names) {
[Link](lang);
}
}
}
10-09-2025 VMS CLASS 261
Types of Arrays
• Single-dimensional arrays → like a list (1D).
• Multi-dimensional arrays → like a table (2D, 3D…).
10-09-2025 VMS CLASS 262
Types of Arrays
public class MatrixExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}
10-09-2025 VMS CLASS 263
Advantages of Arrays
• Easy to manage multiple values of the same type.
• Supports loops for faster processing.
• Random access using index.
10-09-2025 VMS CLASS 264
disadvantages of Arrays
• Fixed size (cannot resize dynamically).
• Only holds elements of the same type.
• Insertion/deletion in the middle is costly.
10-09-2025 VMS CLASS 265
Question
1. Using new Keyword
int[] numbers = new int[5];
2. Using Array Literal
int[] numbers = {1, 2, 3, 4, 5};
What is the difference between these two ?
10-09-2025 VMS CLASS 266
Answer:
1. Using new Keyword
int[] numbers = new int[5];
Step 1: Declare the array reference numbers.
Step 2: Allocate memory for 5 integers using new.
Default values: Each element is initialized to 0 (default for int).
At this point:
numbers = [0, 0, 0, 0, 0]
10-09-2025 VMS CLASS 267
Answer:
1. Using new Keyword
numbers = [0, 0, 0, 0, 0]
You still need to assign values later:
numbers[0] = 10;
numbers[1] = 20;
// and so on...
10-09-2025 VMS CLASS 268
Answer:
2. Using Array Literal
int[] numbers = {1, 2, 3, 4, 5};
This is shorthand for creating and initializing the array in a single step.
Here, the new int[] part is implicit.
The compiler automatically converts it into:
int[] numbers = new int[]{1, 2, 3, 4, 5};
10-09-2025 VMS CLASS 269
Answer:
1. Using Array Literal
int[] numbers = {1, 2, 3, 4, 5};
The size is determined by the number of elements inside {} (in this case
5).
10-09-2025 VMS CLASS 270
ERROR:
You cannot do this:
int[] numbers;
numbers = {1,2,3,4,5}; // ❌ Error
Because array literals can only be used at declaration time. If you want to
assign later, you must use new:
int[] numbers;
numbers = new int[]{1,2,3,4,5}; // ✅ Valid
10-09-2025 VMS CLASS 271
Difference
Statement What Happens Size Initialization
int[] numbers = new Creates an empty array
Fixed (5) Must assign later
int[5]; with default values (0s)
int[] numbers = Creates and initializes Values assigned
Fixed (5)
{1,2,3,4,5}; array in one step immediately
10-09-2025 VMS CLASS 272