[Go to site: main page, start]

0% found this document useful (0 votes)
10 views40 pages

Java Study Notes

The document is a comprehensive study guide for Java programming, covering the first three chapters of the subject. It includes topics such as the introduction to Java, data types, operators, decision making, and loop statements. Each chapter is organized with detailed explanations and examples to aid in exam preparation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views40 pages

Java Study Notes

The document is a comprehensive study guide for Java programming, covering the first three chapters of the subject. It includes topics such as the introduction to Java, data types, operators, decision making, and loop statements. Each chapter is organized with detailed explanations and examples to aid in exam preparation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming

Exam Study Notes

Chapters 1 – 3

Complete & Organized Reference

Topics Covered:

Chapter 1: Introduction to Java Programming Language


Chapter 2: Data Types and Operators
Chapter 3: Decision Making and Loop Statements
Java Programming – Exam Study Notes 1

Contents

1 Chapter 1: Introduction to Java Programming Language 3


1.1 What is Java? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Why Learn Java? – Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 1. Easy to Learn for Beginners . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 2. Object-Oriented . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.3 3. Platform Independent (Portable) . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.4 4. Secure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.5 5. Widely Used in Industry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Java Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.1 Explanation of the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 The Main Method in Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4.1 Meaning of Each Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4.2 What Does String[] args Mean? . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 [Link]() in Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5.1 Breakdown of Each Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.6 How Java Code Runs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7 What is Bytecode? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.1 What Does Bytecode Contain? . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.2 Bytecode Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.3 Why is Bytecode Important? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.8 JDK, JRE, and JVM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.8.1 JDK (Java Development Kit) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.8.2 JRE (Java Runtime Environment) . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.8.3 JVM (Java Virtual Machine) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.8.4 JDK vs JRE vs JVM – Comparison Table . . . . . . . . . . . . . . . . . . . . . 9
1.9 Comments in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.10 Curly Braces and Indentation in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.11 Java Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.11.1 Rules For Naming Java Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.11.2 Examples of Valid Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.11.3 Examples of Invalid Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.12 Java Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.12.1 What Happens if We Use a Variable Name Same as Keyword? . . . . . . . . . 11
1.12.2 Complete Java Keywords List (As of Java 21) . . . . . . . . . . . . . . . . . . . 11
1.13 Chapter 1 Quiz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2 Chapter 2: Data Types and Operators in Java 15


2.1 Java Data Types – Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2.1 1. boolean Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2.2 2. byte Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2.3 3. short Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.4 4. int Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2.5 5. long Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.2.6 6. float Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.2.7 7. double Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.2.8 8. char Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.3 Non-Primitive (Reference) Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.3.1 1. String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.3.2 2. Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.3.3 3. Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Complete Study Guide


Java Programming – Exam Study Notes 2

2.3.4 4. Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.3.5 5. Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.4 Wrapper Classes in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.4.1 Example: Converting Primitive to Wrapper (Autoboxing) . . . . . . . . . . . . 20
2.4.2 Why Are Wrapper Classes Needed? . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4.3 Autoboxing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.4.4 Unboxing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.5 Java Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.5.1 1. Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.5.2 2. Unary Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.5.3 3. Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.5.4 4. Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.5.5 5. Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.5.6 6. Ternary Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.5.7 7. Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.5.8 8. instanceof Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.5.9 Common Mistakes to Avoid with Operators . . . . . . . . . . . . . . . . . . . . 25
2.6 Chapter 2 Quiz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

3 Chapter 3: Decision Making and Loop Statements in Java 28


3.1 Decision Making Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.1.1 1. Java if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.1.2 2. Java if-else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.1.3 3. Java nested-if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.1.4 4. Java if-else-if Ladder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.1.5 5. Java Switch Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.1.6 6. Ternary Operator (? :) in Java . . . . . . . . . . . . . . . . . . . . . . . . 30
3.1.7 if-else vs switch-case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.2 Java Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.1 1. for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.2 2. Enhanced for Loop (for-each) . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.3 3. while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.2.4 4. do-while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.2.5 Loop Summary Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3 Common Loop Mistakes and How to Avoid Them . . . . . . . . . . . . . . . . . . . . . 33
3.3.1 1. Infinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3.2 2. Off-by-One Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.3.3 3. Modifying Loop Variables Inside the Loop . . . . . . . . . . . . . . . . . . . 34
3.3.4 4. Empty Loop Body . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.4 Jump Statements in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.4.1 1. Continue Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.4.2 2. Break Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.4.3 3. Return Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.5 Chapter 3 Quiz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Complete Study Guide


Java Programming – Exam Study Notes 3

1 Chapter 1: Introduction to Java Programming Language


1.1 What is Java?
Java is a high-level, object-oriented programming language used to develop many types of
applications:

• Desktop applications: Software programs that run on a personal computer (desktop or laptop).

• Web applications: Software programs that run in a web browser and are accessed through the
internet.

• Mobile applications (especially Android): Software programs designed to run on smart-


phones and tablets.

• Enterprise systems: Large software systems used by organizations (companies, banks, univer-
sities, hospitals) to manage their daily operations.

• Embedded systems: Software program running on such a system for controlling a device,
monitoring sensors, or managing electronics.

Java was developed by Sun Microsystems in 1995 and is now owned by Oracle Corporation.

1.2 Why Learn Java? – Key Features


1.2.1 1. Easy to Learn for Beginners
Java syntax is easy to read and write.
int x = 10;

1.2.2 2. Object-Oriented
Java uses objects and classes. Examples: Student, Car, Account.
Each object has:

• Attributes (data)

• Methods (functions)

1.2.3 3. Platform Independent (Portable)


Portable means that a program can run on different types of computers or operating systems without
needing to change the code. Java can run on: Windows, Linux, Mac without changing the code.
Java follows the principle: “Write Once, Run Anywhere (WORA)”
This means Java programs can run on any system that has the Java Virtual Machine (JVM).

Source Code (.java) → Compiler → Bytecode (.class) → JVM → Runs on any OS

1.2.4 4. Secure
Java does not allow direct memory access, making programs safer.

Complete Study Guide


Java Programming – Exam Study Notes 4

1.2.5 5. Widely Used in Industry


Many real-world systems use Java:

• Android Apps – Most Android mobile apps are built using Java.

• Netflix – Uses Java for content delivery and backend services.

• Amazon – Java language is used for its backend systems.

• LinkedIn – Uses Java for handling high traffic and scalability.

• Minecraft – One of the world’s most popular games, built in Java.

• Spotify – Uses Java in parts of its server-side infrastructure.

• Uber – Java is used for backend services like trip management.

• NASA WorldWind – A virtual globe software built using Java.

1.3 Java Program Structure


A simple Java program:
public class Hello {
public static void main ( String [] args ) {
System . out . println ( " Hello , World ! " ) ;
}
}

Output
Hello, World!

1.3.1 Explanation of the Program

Part Explanation
public class Hello Defines a class named Hello
public static void main Main method (starting point of program)
[Link] Prints output to the screen
"Hello, World!" Message displayed

1.4 The Main Method in Detail


In Java, the main method is written as:
public static void main ( String [] args )

This is the standard entry point of every Java program. The program starts executing from this
method.

1.4.1 Meaning of Each Part

Part Meaning
public Accessible from anywhere
static Can run without creating an object

Complete Study Guide


Java Programming – Exam Study Notes 5

void Does not return a value


main Starting method
String[] args Stores input arguments

1.4.2 What Does String[] args Mean?


• String[] : an array of Strings

• args : variable name

• It stores command-line arguments

• String[] args is used to receive input values when the program starts

Important
Yes, Java requires this exact structure for the main method. Without it:
public static void main () // Program will NOT run

Because the Java Virtual Machine looks specifically for: public static void main(String[]
args)

Tip
You can change the name args. Example:
public static void main ( String [] data ) // This works fine

args is just a variable name.

Example of args being used:


public class Test {
public static void main ( String [] args ) {
System . out . println ( args [0]) ;
}
}

1.5 [Link]() in Detail


[Link]("Hello, World!"); means: Use the system output stream ([Link]) to
print “Hello, World!” on the screen, then move to a new line.

1.5.1 Breakdown of Each Part


• System – A predefined Java class in the [Link] package (automatically imported). It provides
access to system resources like input, output, and error streams.

• out – A static object of the class PrintStream inside the System class. It represents the standard
output, usually the console (screen).

• println() – A method of the PrintStream class. It prints whatever you give it inside the
parentheses and moves to a new line.

• "Hello, World!" – This is a string literal, the text that will appear on the screen. It must be
enclosed in double quotes " ".

Complete Study Guide


Java Programming – Exam Study Notes 6

System . out . println ( " Hello " ) ;


System . out . println ( " World " ) ;

Output
Hello
World

1.6 How Java Code Runs


1. Write code in a file like [Link].

2. Java Compiler javac compiles it into bytecode [Link].

3. JVM (Java Virtual Machine) reads the .class file and interprets the bytecode.

4. JVM converts bytecode to machine readable code i.e. “binary” (001001010) and then executes the
program.

1.7 What is Bytecode?


Bytecode is the intermediate code produced when a Java program is compiled.

• It is not human-readable like Java source code.

• It is not machine code for a specific processor.

• It is platform-independent – can run on any system with a JVM.

Example: If you compile [Link], you get [Link] which contains bytecode.

1.7.1 What Does Bytecode Contain?


1. Class structure information – Class name, methods, fields, access modifiers

2. Method instructions – Instructions for each method (e.g., load variable, add numbers, print
output)

3. Constants – Strings, numbers, or references used in the program

4. References to other classes or methods – To call other classes or Java APIs

5. Type information – Data types of variables and return types

1.7.2 Bytecode Example


Java code:
System . out . println ( " Hello " ) ;

Bytecode instructions (simplified view):


getstatic java / lang / System . out : PrintStream
ldc " Hello "
invokevirtual java / io / PrintStream . println : ( Ljava / lang / String ;) V
return

Explanation:

• getstatic → access the [Link] object

Complete Study Guide


Java Programming – Exam Study Notes 7

• ldc → load constant “Hello”

• invokevirtual → call the println method

• return → finish the method

1.7.3 Why is Bytecode Important?


• Portability: Runs on any OS with JVM

• Security: JVM checks bytecode before running it

• Efficiency: JVM optimizes execution

1.8 JDK, JRE, and JVM


JDK (Java Development Kit) provides tools and libraries to develop Java applications, working with
JRE and JVM. JRE (Java Runtime Environment) offers libraries and JVM needed to run Java pro-
grams. JVM (Java Virtual Machine) executes the compiled Java bytecode on the system.
Note
Java bytecode can run on any machine with a JVM, but JVM implementations are platform-
dependent for each operating system.

1.8.1 JDK (Java Development Kit)


JDK is a software development kit used to build Java applications. It contains the JRE and a set of
development tools.

• Includes compiler (javac), debugger, and utilities like jar and javadoc.

• Provides the JRE, so it also allows running Java programs.

• Required by developers to write, compile, and debug code.

Components of JDK:

• JRE (JVM + libraries)

• Development tools (compiler, jar, javadoc, debugger)

Note
• JDK is only for development (it is not needed for running Java programs).

• JDK is platform-dependent (different version for Windows, Linux, macOS).

Working of JDK:

1. Source Code (.java): Developer writes a Java program.

2. Compilation: The JDK’s compiler (javac) converts the code into bytecode stored in .class
files.

3. Execution: The JVM executes the bytecode, translating it into native instructions.

Complete Study Guide


Java Programming – Exam Study Notes 8

1.8.2 JRE (Java Runtime Environment)


JRE provides an environment to run Java programs but does not include development tools. It is
intended for end-users who only need to execute applications.

• Contains the JVM and standard class libraries.

• Provides all runtime requirements for Java applications.

• Does not support compilation or debugging.

Note
• JRE is only for running applications, not for developing them.

• It is platform-dependent (different builds for different OS).

Working of JRE:

1. Class Loading: Loads compiled .class files into memory.

2. Bytecode Verification: Ensures security and validity of bytecode.

3. Execution: Uses the JVM (interpreter + JIT compiler) to execute instructions and make system
calls.

1.8.3 JVM (Java Virtual Machine)


JVM is the core execution engine of Java. It is responsible for converting bytecode into machine-specific
instructions.

• Part of both JDK and JRE.

• Performs memory management and garbage collection.

• Provides portability by executing the same bytecode on different platforms.

Note
• JVM implementations are platform dependent.

• Bytecode is platform-independent and can run on any JVM.

• Modern JVMs rely heavily on Just-In-Time (JIT) compilation for performance.

Working of JVM:

1. Loading: Class loader loads bytecode into memory.

2. Linking: Performs verification, preparation, and resolution.

3. Initialization: Executes class constructors and static initializers.

4. Execution: Interprets or compiles bytecode into native code.

Complete Study Guide


Java Programming – Exam Study Notes 9

1.8.4 JDK vs JRE vs JVM – Comparison Table

Aspect JDK JRE JVM


Purpose Used to develop Java Used to run Java appli- Executes Java byte-
applications cations code
Platform De- Platform-dependent Platform-dependent JVM is OS-specific,
pendency (OS specific) (OS specific) but bytecode is
platform-independent
Includes JRE + Development JVM + Libraries (e.g., ClassLoader, JIT
tools (javac, debugger, [Link]) Compiler, Garbage
etc.) Collector
Use Case Writing and compiling Running a Java appli- Convert bytecode into
Java code cation on a system native machine code

1.9 Comments in Java


Comments are notes written inside the code to explain what we are doing. Comment lines are not
executed while we run the program.
Single-line comment:
// This is a comment

Multi-line comment:
/*
This is a multi - line comment .
This is useful for explaining larger sections of code .
*/

1.10 Curly Braces and Indentation in Java


In Java, curly braces {} are used to define blocks of code. For example, the body of a class or method
is enclosed within curly braces.
public class Main {
public static void main ( String [] args ) {
{
System . out . println ( " This is inside the block . " ) ;
}
System . out . println ( " This is outside the block . " ) ;
}
}

• The code block inside {} runs unconditionally and prints a message.

• Curly braces {} group multiple statements into a single block, even without conditions.

1.11 Java Identifiers


An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These
are the unique names used to identify programming elements.
class Geeks {
public static void main ( String [] args ) {

Complete Study Guide


Java Programming – Exam Study Notes 10

int x = 9;
}
}

In this program, Geeks, main, args, and x are identifiers.

1.11.1 Rules For Naming Java Identifiers


1. The only allowed characters for identifiers are all alphanumeric characters ([A-Z], [a-z], [0-9]),
$ (dollar sign) and _ (underscore). For example, sum@ is not valid as it contains @.

2. Identifiers should not start with digits ([0-9]). For example, 123sum is not valid.

3. Java identifiers are case-sensitive; sum is not the same as Sum.

4. There is no limit on the length of the identifier, but it is advisable to use an optimum length of
4–15 letters only.

5. Reserved Words can’t be used as an identifier. For example, int while = 20; is invalid as
while is a reserved word.

Note
Java has 53 reserved words (including 50 keywords and 3 literals), that are not allowed to be
used as identifiers.

1.11.2 Examples of Valid Identifiers

MyVariable MYVARIABLE myvariable x i


x1 i1 _myvariable $myvariable
sum_of_array geeks123

1.11.3 Examples of Invalid Identifiers

My Variable // contains a space


123 geeks // begins with a digit
a+c // plus sign is not alphanumeric
variable -2 // hyphen is not alphanumeric
sum_ & _difference // ampersand is not alphanumeric

1.12 Java Keywords


In Java, keywords are reserved words that have some predefined meanings and are used by the Java
compiler for some internal process or represent some predefined actions. These words cannot be used
as identifiers such as variable names, method names, class names, or object names.
class Example {
public static void main ( String [] args ) {
final int x = 10;
if ( x > 10) {
System . out . println ( " Failed " ) ;
} else {
System . out . println ( " Successful demonstration of keywords . " ) ;
}
}
}

Complete Study Guide


Java Programming – Exam Study Notes 11

Output
Successful demonstration of keywords.

1.12.1 What Happens if We Use a Variable Name Same as Keyword?

class Example {
public static void main ( String [] args ) {
String this = " Hello World ! " ; // ERROR
System . out . println ( this ) ;
}
}

Output
error: not a statement
error: ’;’ expected
2 errors

Important
• The keywords const and goto are reserved, even though they are not currently used in Java.

• true, false, and null look like keywords, but in actuality they are literals. However, they still
can’t be used as identifiers.

• In Java, keywords are case-sensitive; writing Java keywords in upper case (like IF instead of
if) will throw an error.

1.12.2 Complete Java Keywords List (As of Java 21)


As of Java 21, there are 53 keywords, categorized below:
1. Data Type Keywords

Keyword Usage
boolean Defines a variable that holds true or false
byte Defines an 8-bit signed integer
char Defines a 16-bit Unicode character
short Defines a 16-bit signed integer
int Defines a 32-bit signed integer
long Defines a 64-bit signed integer
float Defines a 32-bit floating-point number
double Defines a 64-bit floating-point number
void Specifies that a method does not return any value

2. Control Flow Keywords

Keyword Usage
if Executes code when a condition is true
else Defines an alternate block when an if condition is false
switch Selects one block of code among multiple options
case Defines an individual branch in a switch statement
default Defines the block executed if no case matches
for Starts a for loop

Complete Study Guide


Java Programming – Exam Study Notes 12

while Starts a while loop


do Starts a do-while loop
break Terminates the nearest loop or switch
continue Skips to the next iteration of a loop
return Exits from a method and optionally returns a value

3. Exception Handling Keywords

Keyword Usage
try Defines a block of code to test for exceptions
catch Defines a block to handle exceptions thrown by try
finally Defines a block that always executes after try and catch
throw Used to manually throw an exception
throws Declares the exceptions a method can throw
assert Tests assumptions during program execution for debugging

4. Object-Oriented Keywords

Keyword Usage
class Declares a class
interface Declares an interface
extends Indicates inheritance from a superclass
implements Indicates that a class implements an interface
new Creates new objects
this Refers to the current object
super Refers to the superclass of the current object
abstract Declares a class or method that must be implemented in a subclass
final Prevents inheritance, overriding, or modification
static Declares class-level variables or methods
sealed Restricts which classes can extend a given class
permits Specifies the subclasses allowed to extend a sealed class

5. Access Control Keywords

Keyword Usage
public Accessible from anywhere in the program
protected Accessible within the same package or by subclasses
private Accessible only within the same class

6. Package and Import Keywords

Keyword Usage
package Defines a namespace for classes
import Allows access to classes from other packages

7. Multithreading and Synchronization Keywords

Keyword Usage
synchronized Defines critical sections that only one thread can access at a time
volatile Indicates that a variable may change asynchronously

Complete Study Guide


Java Programming – Exam Study Notes 13

8. Memory Management and Object Serialization Keywords

Keyword Usage
transient Excludes a variable from serialization
native Specifies that a method is implemented in native (non-Java) code

9. Modifier and Utility Keywords

Keyword Usage
strictfp Ensures consistent floating-point calculations across platforms

10. Reserved (Unused) Keywords

Keyword Usage
const Reserved for future use; not currently implemented
goto Reserved for future use; not currently implemented

11. Special Literals

Keyword Usage
true Represents the boolean value true
false Represents the boolean value false
null Represents the absence of any reference value

1.13 Chapter 1 Quiz


1. What is the correct way to declare a Java main method?

A: public static void Main(String[] args)


B: public void main(String args)
C: public static void main(String[] args) ← Answer: C
D: private static void main(String args[])

2. What is the output of the following Java program?


public class Main {
public static void main ( String [] args ) {
int my_var = 20;
System . out . println ( my_var ) ;
}
}

A: 20 ← Answer: A
B: Compilation Error
C: Runtime Error
D: Undefined Behavior

3. Which of the following is NOT a Feature of Java?

A: Platform independence
B: Object-oriented

Complete Study Guide


Java Programming – Exam Study Notes 14

C: Dynamically typed language ← Answer: C


D: Robust

4. Which component is responsible for converting bytecode to machine code?

A: Java Compiler
B: JDK
C: JVM ← Answer: C
D: JRE

5. Which part of the JDK is used to run Java programs?

A: javac
B: JRE ← Answer: B
C: Javadoc
D: JAR

6. Java code is compiled into which intermediate form?

A: Assembly
B: Bytecode ← Answer: B
C: Binary
D: Machine code

7. Which Java feature ensures code written once can run anywhere?

A: Platform independence ← Answer: A


B: Multithreading
C: Security
D: Performance

Complete Study Guide


Java Programming – Exam Study Notes 15

2 Chapter 2: Data Types and Operators in Java


2.1 Java Data Types – Overview
Java is a statically typed programming language, which means the data type of every variable is
known at compile time. The compiler enforces type safety and prevents invalid assignments such as:
int x = " GfG " ; // Compile - time error

Data types in Java define the kind of data a variable can hold, and the memory required to store
it. They are broadly divided into two categories:

1. Primitive Data Types: Store simple values directly in memory.

2. Non-Primitive (Reference) Data Types: Store memory references to objects.

2.2 Primitive Data Types


Primitive data types store simple values directly in memory. Java provides eight primitive data types:

Type Description Default Size Example Range


boolean Logical values false – true, true or false
false
byte 8-bit signed integer 0 1 byte 10 −128 to 127
char 16-bit Unicode char- \u0000 2 bytes ’A’ 0 to 65,535
acter
short 16-bit signed integer 0 2 bytes 2000 −32, 768 to 32, 767
int 32-bit signed integer 0 4 bytes 1000 ±2.1 × 109
long 64-bit signed integer 0L 8 bytes 123456789L ±9.22 × 1018
float 32-bit floating point 0.0f 4 bytes 3.14f ∼6–7 digits
double 64-bit floating point 0.0d 8 bytes 3.14159d ∼15–16 digits

2.2.1 1. boolean Data Type


Represents one of two logical values: true or false. Commonly used in conditions and control
statements.
boolean booleanVar ;

public class Example {


public static void main ( String [] args ) {
boolean isJavaFun = true ;
boolean isFishTasty = false ;
System . out . println ( " Is Java fun ? " + isJavaFun ) ;
System . out . println ( " Is fish tasty ? " + isFishTasty ) ;
}
}

Output
Is Java fun? true
Is fish tasty? false

2.2.2 2. byte Data Type


An 8-bit signed integer used to save memory in large numeric arrays.

Complete Study Guide


Java Programming – Exam Study Notes 16

byte byteVar ;

public class Example {


public static void main ( String [] args ) {
byte age = 25;
byte temperature = -10;
System . out . println ( " Age : " + age ) ;
System . out . println ( " Temperature : " + temperature ) ;
}
}

Output
Age: 25
Temperature: -10

2.2.3 3. short Data Type


A 16-bit signed integer, often used when memory is limited and values are moderate in size.
short shortVar ;

public class Example {


public static void main ( String [] args ) {
short students = 1000;
short temp = -200;
System . out . println ( " Students : " + students ) ;
System . out . println ( " Temperature : " + temp ) ;
}
}

Output
Students: 1000
Temperature: -200

2.2.4 4. int Data Type


A 32-bit signed integer and the most used numeric data type. Size: 4 bytes (32 bits).
int intVar ;

public class Example {


public static void main ( String [] args ) {
int population = 2000000;
int distance = 150000000;
System . out . println ( " Population : " + population ) ;
System . out . println ( " Distance : " + distance ) ;
}
}

Output
Population: 2000000
Distance: 150000000

Complete Study Guide


Java Programming – Exam Study Notes 17

2.2.5 5. long Data Type


A 64-bit signed integer used when int is not sufficient for large values. Size: 8 bytes (64 bits).
long longVar ;

public class Example {


public static void main ( String [] args ) {
long worldPopulation = 7800000000 L ;
long lightYears = 9460730472580800 L ;
System . out . println ( " World Population : " + worldPopulation ) ;
System . out . println ( " Light Years : " + lightYears ) ;
}
}

Output
World Population: 7800000000
Light Year Distance: 9460730472580800

2.2.6 6. float Data Type


A 32-bit single-precision floating-point type used for fractional values. Size: 4 bytes (32 bits).
float floatVar ;

public class Example {


public static void main ( String [] args ) {
float pi = 3.14 f ;
float gravity = 9.81 f ;
System . out . println ( " Pi : " + pi ) ;
System . out . println ( " Gravity : " + gravity ) ;
}
}

Output
Value of Pi: 3.14
Gravity: 9.81

2.2.7 7. double Data Type


A 64-bit double-precision floating-point type and the default for decimal numbers. Size: 8 bytes (64
bits).
double doubleVar ;

public class Example {


public static void main ( String [] args ) {
double pi = 3.1 41 59 265 35 89 793 ;
double avogadro = 6.02214076 e23 ;
System . out . println ( " Pi : " + pi ) ;
System . out . println ( " Avogadro ’s Number : " + avogadro ) ;
}
}

Complete Study Guide


Java Programming – Exam Study Notes 18

Output
Value of Pi: 3.141592653589793
Avogadro’s Number: 6.02214076E23

2.2.8 8. char Data Type


A 16-bit Unicode character used to store single symbols or letters. Size: 2 bytes (16 bits).
char charVar ;

public class Example {


public static void main ( String [] args ) {
char grade = ’A ’;
char symbol = ’$ ’;
System . out . println ( " Grade : " + grade ) ;
System . out . println ( " Symbol : " + symbol ) ;
}
}

Output
Grade: A
Symbol: $

2.3 Non-Primitive (Reference) Data Types


Non-primitive data types store references (memory addresses) rather than actual values. They
are created by users and include types like String, Class, Object, Interface, and Array.

2.3.1 1. String
String represents a sequence of characters enclosed in double quotes. Unlike C/C++, Java strings are
objects and are immutable.
String str = " Hello " ;

public class Example {


public static void main ( String [] args ) {
String name = " Example1 " ;
String message = " Welcome to Java " ;
System . out . println ( " Name : " + name ) ;
System . out . println ( " Message : " + message ) ;
}
}

Output
Name: Example1
Message: Welcome to Java

Note
String cannot be modified after creation. Use StringBuilder for heavy string manipulation.

2.3.2 2. Class
A class is a user-defined blueprint that defines variables and methods. It represents a type of object
and forms the foundation of Object-Oriented Programming.

Complete Study Guide


Java Programming – Exam Study Notes 19

class Car {
String model ;
int year ;
Car ( String model , int year ) {
this . model = model ;
this . year = year ;
}
void display () {
System . out . println ( model + " " + year ) ;
}
}
public class Example {
public static void main ( String [] args ) {
Car myCar = new Car ( " Toyota " , 2020) ;
myCar . display () ;
}
}

Output
Toyota 2020

2.3.3 3. Object
An Object is an instance of a class representing real-world entities. It has state (data), behavior
(methods), and identity (unique reference).
class Car {
String model ;
int year ;
Car ( String model , int year ) {
this . model = model ;
this . year = year ;
}
}
public class Example {
public static void main ( String [] args ) {
Car myCar = new Car ( " Honda " , 2021) ;
System . out . println ( " Model : " + myCar . model ) ;
System . out . println ( " Year : " + myCar . year ) ;
}
}

Output
Car Model: Honda
Car Year: 2021

2.3.4 4. Interface
An interface defines a contract of abstract methods that implementing classes must define. It provides
a way to achieve abstraction and multiple inheritance in Java.
interface Animal {
void sound () ;
}
class Dog implements Animal {
public void sound () {

Complete Study Guide


Java Programming – Exam Study Notes 20

System . out . println ( " Woof " ) ;


}
}
public class Example {
public static void main ( String [] args ) {
Animal dog = new Dog () ;
dog . sound () ;
}
}

Output
Woof

2.3.5 5. Array
An array stores multiple elements of the same type in a single structure. Java arrays are objects,
dynamically allocated, and indexed from 0.
public class Example {
public static void main ( String [] args ) {
int [] numbers = {1 , 2 , 3 , 4 , 5};
String [] names = { " Example1 " , " Example2 " , " Example3 " };
System . out . println ( " First number : " + numbers [0]) ;
System . out . println ( " Second name : " + names [1]) ;
}
}

Output
First number: 1
Second name: Example2

2.4 Wrapper Classes in Java


In Java, wrapper classes allow primitive data types to be represented as objects. This enables primitives
to be used in object-oriented features such as collections, generics, and APIs that require objects.

• Each wrapper class encapsulates a corresponding primitive value inside an object (e.g., Integer
for int, Double for double).

• Java provides wrapper classes for all eight primitive data types.

2.4.1 Example: Converting Primitive to Wrapper (Autoboxing)

class Example {
public static void main ( String [] args ) {
int b = 357;
// Autoboxing : primitive int -> Integer object
Integer a = b ;
System . out . println ( " The primitive int b is : " + b ) ;
System . out . println ( " The Integer object a is : " + a ) ;
}
}

Complete Study Guide


Java Programming – Exam Study Notes 21

Output
The primitive int b is: 357
The Integer object a is: 357

2.4.2 Why Are Wrapper Classes Needed?


• Java collections (ArrayList, HashMap, etc.) store only objects, not primitives.

• Wrapper objects allow primitives to be used in object-oriented features like methods, synchroniza-
tion, and serialization.

• Objects support null values, while primitives do not.

• Wrapper classes provide utility methods such as compareTo(), equals(), and toString().

2.4.3 Autoboxing
The automatic conversion of primitive types to the object of their corresponding wrapper classes is
known as autoboxing. For example: conversion of int to Integer, long to Long, double to Double,
etc.
import java . util . ArrayList ;
class Example {
public static void main ( String [] args ) {
char ch = ’a ’;
// Autoboxing : char -> Character
Character c = ch ;
ArrayList < Integer > list = new ArrayList < >() ;
// Autoboxing : int -> Integer
list . add (25) ;
System . out . println ( list . get (0) ) ;
}
}

Output
25

2.4.4 Unboxing
Unboxing is the automatic conversion of a wrapper class object back into its corresponding primitive
type.
import java . util . ArrayList ;
class Example {
public static void main ( String [] args ) {
Character ch = ’a ’;
// Unboxing : Character -> char
char c = ch ;
ArrayList < Integer > list = new ArrayList < >() ;
list . add (24) ;
// Unboxing : Integer -> int
int num = list . get (0) ;
System . out . println ( num ) ;
}
}

Complete Study Guide


Java Programming – Exam Study Notes 22

Output
24

2.5 Java Operators


Java operators are special symbols that perform operations on variables or values. These operators are
essential in programming as they allow you to manipulate data efficiently.

2.5.1 1. Arithmetic Operators


Arithmetic operators are used to perform simple arithmetic operations on primitive and non-primitive
data types.
public class Example {
public static void main ( String [] args ) {
int a = 10 , b = 3;
int sum = a + b ; // Addition
int diff = a - b ; // Subtraction
int mul = a * b ; // Multiplication
int div = a / b ; // Division
int mod = a % b ; // Modulus
System . out . println ( " Sum : " + sum ) ;
System . out . println ( " Difference : " + diff ) ;
System . out . println ( " Multiplication : " + mul ) ;
System . out . println ( " Division : " + div ) ;
System . out . println ( " Modulus : " + mod ) ;
}
}

Output
Sum: 13
Difference: 7
Multiplication: 30
Division: 3
Modulus: 1

2.5.2 2. Unary Operators


Unary operators need only one operand. They are used to increment, decrement, or negate value.
import java . io .*;
class Example {
public static void main ( String [] args ) {
int a = 10;
int b = 10;
System . out . println ( " Postincrement : " + ( a ++) ) ;
System . out . println ( " Preincrement : " + (++ a ) ) ;
System . out . println ( " Postdecrement : " + (b - -) ) ;
System . out . println ( " Predecrement : " + ( - - b ) ) ;
}
}

Complete Study Guide


Java Programming – Exam Study Notes 23

Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8

2.5.3 3. Assignment Operator


The assignment operator assigns a value from the right-hand side to a variable on the left. Since it
has right-to-left associativity, the right-hand value must be declared or constant.
public class Example {
public static void main ( String [] args ) {
int n = 10;
n += 5; // n = n + 5
System . out . println ( " After += : " + n);
n *= 2; // n = n * 2
System . out . println ( " After *= : " + n);
n -= 5; // n = n - 5
System . out . println ( " After -= : " + n);
n /= 2; // n = n / 2
System . out . println ( " After /= : " + n);
n %= 3; // n = n % 3
System . out . println ( " After %= : " + n);
}
}

Output
After += : 15
After *= : 30
After -= : 25
After /= : 12
After %= : 0

Tip
Use compound assignments (+=, -=) for cleaner code.

2.5.4 4. Relational Operators


Relational operators are used to check for relations like equality, greater than, and less than. They
return boolean results after the comparison and are extensively used in looping statements as well as
conditional if-else statements.
import java . io .*;
class Example {
public static void main ( String [] args ) {
int a = 10 , b = 3 , c = 5;
System . out . println ( " a > b : " + ( a > b ) ) ;
System . out . println ( " a < b : " + ( a < b ) ) ;
System . out . println ( " a >= b : " + ( a >= b ) ) ;
System . out . println ( " a <= b : " + ( a <= b ) ) ;
System . out . println ( " a == c : " + ( a == c ) ) ;
System . out . println ( " a != c : " + ( a != c ) ) ;
}
}

Complete Study Guide


Java Programming – Exam Study Notes 24

Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true

2.5.5 5. Logical Operators


Logical operators are used to perform “logical AND” and “logical OR” operations. They have a short-
circuiting effect, meaning the second condition is not evaluated if the first determines the result.
import java . io .*;
class Example {
public static void main ( String [] args ) {
boolean x = true ;
boolean y = false ;
System . out . println ( " x && y : " + ( x && y ) ) ;
System . out . println ( " x || y : " + ( x || y ) ) ;
System . out . println ( " ! x : " + (! x ) ) ;
}
}

Output
x && y: false
x || y: true
!x: false

2.5.6 6. Ternary Operator


The Ternary Operator (?) is a shorthand version of the if-else statement. It has three operands and
hence the name Ternary.
public class Example {
public static void main ( String [] args ) {
int a = 20 , b = 10 , c = 30 , result ;
result = (( a > b ) ? ( a > c ) ? a : c : ( b > c ) ? b : c ) ;
System . out . println ( " Max of three numbers = " + result ) ;
}
}

Output
Max of three numbers = 30

2.5.7 7. Bitwise Operators


These operators perform operations at the bit level.

• Bitwise Operators manipulate individual bits using AND, OR, XOR, and NOT.

• Shift Operators move bits to the left or right, effectively multiplying or dividing by powers of
two.

Complete Study Guide


Java Programming – Exam Study Notes 25

import java . io .*;


class Example {
public static void main ( String [] args ) {
int d = 0 b1010 ;
int e = 0 b1100 ;
System . out . println ( " d & e : " + ( d & e ) ) ;
System . out . println ( " d | e : " + ( d | e ) ) ;
System . out . println ( " d ^ e : " + ( d ^ e ) ) ;
System . out . println ( " ~ d : " + (~ d ) ) ;
System . out . println ( " d << 2 : " + ( d << 2) ) ;
System . out . println ( " e >> 1 : " + ( e >> 1) ) ;
System . out . println ( " e >>> 1 : " + ( e >>> 1) ) ;
}
}

Output
d & e : 8
d | e : 14
d ˆ e : 6
˜d : -11
d « 2 : 40
e » 1 : 6
e »> 1 : 6

2.5.8 8. instanceof Operator


The instanceof operator is used for type checking. It can be used to test if an object is an instance
of a class, a subclass, or an interface.
public class Example {
public static void main ( String [] args ) {
String str = " Hello " ;
System . out . println ( str instanceof String ) ;
Object obj = new Integer (10) ;
System . out . println ( obj instanceof Integer ) ;
System . out . println ( obj instanceof String ) ;
}
}

Output
true
true
false

2.5.9 Common Mistakes to Avoid with Operators


• Confusing == with =: Using == for assignment instead of = for equality check leads to logical
errors.

• Incorrect Use of Floating Point Comparison: Comparing floating point numbers using ==
can lead to unexpected results due to precision issues.

• Integer Division Confusion: Dividing two integers will result in integer division (truncating
the result).

Complete Study Guide


Java Programming – Exam Study Notes 26

• Overusing + for String Concatenation in Loops: Using + for concatenating strings in loops
leads to performance issues because it creates new string objects on each iteration.

2.6 Chapter 2 Quiz


1. Which of the following is true about variable names in Java?

A: Variable names can start with a number


B: Variable names can contain special characters like @ or #
C: Variable names are case-sensitive ← Answer: C
D: Variable names can be a Java keyword

2. What is the correct way to declare a constant variable in Java?

A: final int MAX = 100; ← Answer: A


B: const int MAX = 100;
C: int const MAX = 100;
D: MAX = 100;

3. What will be the output of this Java program?


public class Demo {
public static void main ( String [] args ) {
int x = 10;
{
int x = 20;
System . out . println ( x ) ;
}
}
}

A: 20
B: 10
C: Compilation Error ← Answer: C
D: Runtime Error

4. Which keyword is used to declare an integer variable in Java?

A: define
B: let
C: int ← Answer: C
D: declare

5. Which of the following is a valid integer literal?

A: 12.5
B: 0x1A ← Answer: B
C: "100"
D: true

6. Which of these performs explicit type casting?

A: int z = (int) 5.9; ← Answer: A


B: double y = 3;

Complete Study Guide


Java Programming – Exam Study Notes 27

C: int x = 5.0;
D: float f = 5;

7. What is the default value of an uninitialized int variable in a class?

A: 0 ← Answer: A
B: null
C: garbage value
D: 1

8. Which type of casting happens automatically in Java?

A: Narrowing
B: Widening ← Answer: B
C: Reference
D: Explicit

Complete Study Guide


Java Programming – Exam Study Notes 28

3 Chapter 3: Decision Making and Loop Statements in Java


3.1 Decision Making Statements
Decision-making in programming is similar to real-life decision-making. We often want certain blocks
of code to be executed only when specific conditions are met. In Java, this is achieved using decision-
making statements that control the flow of execution.

3.1.1 1. Java if Statement


The if statement is the simplest decision-making statement. It executes a block of code only if a given
condition is true.
class Example {
public static void main ( String args []) {
int i = 10;
if ( i < 15) {
System . out . println ( " Condition is True " ) ;
}
}
}

Output
Condition is True

Note
If curly braces {} are omitted, only the next line after if is considered part of the block.

3.1.2 2. Java if-else Statement


The if-else statement allows you to execute one block if the condition is true and another block if it
is false.
import java . util .*;
class Example {
public static void main ( String args []) {
int i = 10;
if ( i < 15)
System . out . println ( " i is smaller than 15 " ) ;
else
System . out . println ( " i is greater than 15 " ) ;
}
}

Output
i is smaller than 15

3.1.3 3. Java nested-if Statement


A nested-if is an if statement inside another if statement. It is useful when a second condition
depends on the first.
class Example {
public static void main ( String args []) {
int i = 10;
if ( i < 15) {

Complete Study Guide


Java Programming – Exam Study Notes 29

System . out . println ( " i is smaller than 15 " ) ;


if ( i == 10) {
System . out . println ( " i is exactly 10 " ) ;
}
}
}
}

Output
i is smaller than 15
i is exactly 10

3.1.4 4. Java if-else-if Ladder


The if-else-if ladder allows multiple independent conditions to be checked in order. As soon as one
condition is true, its block executes, and the rest are skipped.
import java . util .*;
class Example {
public static void main ( String args []) {
int i = 20;
if ( i == 10)
System . out . println ( " i is 10 " ) ;
else if ( i == 15)
System . out . println ( " i is 15 " ) ;
else if ( i == 20)
System . out . println ( " i is 20 " ) ;
else
System . out . println ( " i is not present " ) ;
}
}

Output
i is 20

3.1.5 5. Java Switch Case


The switch statement is a multiway branch statement. It provides an easy way to dispatch execution
to different parts of code based on the value of the expression.
import java . io .*;
class Example {
public static void main ( String [] args ) {
int num = 20;
switch ( num ) {
case 5:
System . out . println ( " It is 5 " ) ;
break ;
case 10:
System . out . println ( " It is 10 " ) ;
break ;
case 15:
System . out . println ( " It is 15 " ) ;
break ;
case 20:
System . out . println ( " It is 20 " ) ;
break ;

Complete Study Guide


Java Programming – Exam Study Notes 30

default :
System . out . println ( " Not present " ) ;
}
}
}

Output
It is 20

Important
• The expression can be of type byte, short, int, char, or an enumeration. Beginning with JDK7,
the expression can also be of type String.

• Duplicate case values are not allowed.

• The default statement is optional.

• The break statement is used inside the switch to terminate a statement sequence.

• The break statements are necessary; without the break keyword, statements in switch blocks
fall through.

3.1.6 6. Ternary Operator (? :) in Java


The ternary operator in Java is a conditional operator that provides a shorthand way to write simple
if-else statements.
Syntax:
condition ? e xp res si on _if _t ru e : e x p re s si o n_ i f _f a ls e ;

class Example {
public static void main ( String args []) {
int a = 10 , b = 20;
int max = ( a > b ) ? a : b ;
System . out . println ( " Maximum is " + max ) ;
}
}

Output
Maximum is 20

Explanation: This program uses the ternary operator (? :) to find the maximum of two num-
bers. It checks the condition a > b; if true, it assigns a to the variable max, otherwise it assigns
b.

3.1.7 if-else vs switch-case

Features if-else switch-case


Use Case Suitable for condition-based Best for exact value matching
checks
Readability More readable for a few condi- More readable and efficient for
tions many cases

Complete Study Guide


Java Programming – Exam Study Notes 31

Performance Slower for many checks due to Faster and optimized for han-
multiple conditions dling many cases
Flexibility Supports ranges and complex Only supports exact matches of
conditions values

3.2 Java Loops


Loops in programming allow a set of instructions to run multiple times based on a condition. In Java,
there are three main types of loops (plus the enhanced for loop).

3.2.1 1. for Loop


The for loop is used when we know the number of iterations (we know how many times we want to
repeat a task).
Syntax:
for ( initialization ; condition ; increment / decrement ) {
// code to be executed
}

import java . io .*;


class Example {
public static void main ( String [] args ) {
for ( int i = 0; i <= 10; i ++) {
System . out . print ( i + " " ) ;
}
}
}

Output
0 1 2 3 4 5 6 7 8 9 10

How the for loop works:

1. Initialization condition: Initialize the variable in use. Marks the start of a for loop.

2. Testing Condition: Used for testing the exit condition. Must return a boolean value. It is an
Entry Control Loop as the condition is checked prior to execution.

3. Statement execution: Once the condition evaluates to true, the statements in the loop body
are executed.

4. Increment/Decrement: Used for updating the variable for next iteration.

5. Loop termination: When the condition becomes false, the loop terminates.

3.2.2 2. Enhanced for Loop (for-each)


This loop is used to iterate over arrays or collections.
Syntax:
for ( dataType variable : arrayO rCollect ion ) {
// code to be executed
}

Complete Study Guide


Java Programming – Exam Study Notes 32

import java . io .*;


class Example {
public static void main ( String [] args ) {
String [] names = { " Ali " , " Mona " , " Amal " };
for ( String name : names ) {
System . out . println ( " Name : " + name ) ;
}
}
}

Output
Name: Ali
Name: Mona
Name: Amal

3.2.3 3. while Loop


A while loop is used when we want to check the condition before executing the loop body.
Syntax:
while ( condition ) {
// code to be executed
}

import java . io .*;


class Example {
public static void main ( String [] args ) {
int i = 0;
while ( i <= 10) {
System . out . print ( i + " " ) ;
i ++;
}
}
}

Output
0 1 2 3 4 5 6 7 8 9 10

How the while loop works:

• While loop starts with checking of Boolean condition. If evaluated to true, loop body statements
are executed; otherwise first statement following the loop is executed. For this reason, it is also
called Entry control loop.

• Once the condition evaluates to true, statements in the loop body are executed. Normally the
statements contain an update value for the variable being processed for the next iteration.

• When the condition becomes false, the loop terminates.

3.2.4 4. do-while Loop


The do-while loop ensures that the code block executes at least once before checking the condition.
Syntax:
do {
// code to be executed

Complete Study Guide


Java Programming – Exam Study Notes 33

} while ( condition ) ;

import java . io .*;


class Example {
public static void main ( String [] args ) {
int i = 0;
do {
System . out . print ( i + " " ) ;
i ++;
} while ( i <= 10) ;
}
}

Output
0 1 2 3 4 5 6 7 8 9 10

How the do-while loop works:

• do-while loop starts with the execution of the statement. There is no checking of any condition
for the first time.

• After execution of the statements and update of the variable value, the condition is checked for
true or false value. If evaluated to true, next iteration starts.

• When the condition becomes false, the loop terminates.

• The do-while loop will execute its statements at least once before any condition is checked, and
therefore is an example of exit control loop.

3.2.5 Loop Summary Table

Loop Type When to Use Condition Checking Executes At


Least Once?
for loop When you want exact it- Before loop body (Entry- No
erations controlled)
while loop When you need condi- Before loop body (Entry- No
tion check first controlled)
do-while loop When you need to run After loop body (Exit- Yes
at least once controlled)
for-each loop When you process all Internally handled No
collection items

3.3 Common Loop Mistakes and How to Avoid Them


3.3.1 1. Infinite Loops
This is one of the most common mistakes. The loop may not ever exit – it runs for infinite time. This
happens when the condition fails for some reason.
Infinite for Loop:
import java . io .*;
class Example {
public static void main ( String [] args ) {
for ( int i = 0; i < 5; i - -) { // i - - instead of i ++

Complete Study Guide


Java Programming – Exam Study Notes 34

System . out . println ( " This loop will run forever " ) ;
}
}
}

Infinite while Loop:


import java . io .*;
class Example {
public static void main ( String [] args ) {
while ( true ) {
System . out . println ( " Basic example of infinite loop " ) ;
}
}
}

Both produce TLE (Time Limit Exceeded) error.

3.3.2 2. Off-by-One Errors


Off-by-One Errors are caused when the loop runs one more or one fewer time than expected. It happens
when the loop condition is not set correctly.
import java . io .*;
class Example {
public static void main ( String [] args ) {
for ( int i = 0; i <= 5; i ++) { // Runs 6 times , expected 5
System . out . print ( i + " " ) ;
}
}
}

3.3.3 3. Modifying Loop Variables Inside the Loop


When we change the loop variable (like i) inside the loop, it can cause the loop to skip certain iterations
or behave unexpectedly.
import java . io .*;
class Example {
public static void main ( String [] args ) {
for ( int i = 0; i < 5; i ++) {
if ( i == 2) {
i ++; // Modifies loop variable , skips next iteration
}
System . out . println ( i ) ;
}
}
}

3.3.4 4. Empty Loop Body


An empty loop body occurs when a loop iterates but does not perform any operations inside. Running
a loop without useful operations can be confusing.
import java . io .*;
class Example {
public static void main ( String [] args ) {
for ( int i = 0; i < 10; i ++) {

Complete Study Guide


Java Programming – Exam Study Notes 35

// Empty body -- no operations


}
}
}

No output will be generated because the body of the loop is empty.

3.4 Jump Statements in Java


In Java, jump statements are used to alter the normal flow of program execution when certain conditions
are met. They can be used to terminate a loop, skip an iteration, or exit from a method or block of
code.

3.4.1 1. Continue Statement


The continue statement pushes the next repetition of the loop to take place, skipping any code between
itself and the conditional expression that controls the loop.
import java . io .*;
class Example {
public static void main ( String [] args ) {
for ( int i = 0; i < 5; i ++) {
if ( i == 2) {
System . out . println () ;
continue ; // skip the current iteration
}
System . out . println ( i ) ;
}
}
}

Output
0
1

3
4

Explanation: When the value of i is 2, the compiler encounters the continue statement, and
then 2 is skipped.

3.4.2 2. Break Statement


Using Break to Exit a Loop:
The break statement is used to terminate the execution of the nearest looping statement or switch
statement. When a break statement is executed inside a loop, the loop is terminated, and control
reaches the statement that follows the loop.
import java . io .*;
class Example {
public static void main ( String [] args ) {
int n = 10;
for ( int i = 0; i < n ; i ++) {
if ( i == 4)
break ;
System . out . println ( i ) ;
}
}

Complete Study Guide


Java Programming – Exam Study Notes 36

Output
0
1
2
3

Explanation: The code is meant to print 0 to 10 numbers using for loop, but it prints only 0 to
3. As soon as i is equal to 4, the control terminates the loop.
Using Break as a Form of Goto (Labeled Break):
Java does not have a goto statement because it produces an unstructured way to alter the flow
of program execution. Java illustrates an extended form of the break statement. This form of break
works with a label. The label is the name of a label that identifies a statement or a block of code.
When this form of break executes, control jumps out of the labeled statement or block.
import java . io .*;
class Example {
public static void main ( String [] args ) {
for ( int i = 0; i < 3; i ++) {
one : {
two : {
three : {
System . out . println ( " i = " + i ) ;
if ( i == 0) break one ;
if ( i == 1) break two ;
if ( i == 2) break three ;
}
System . out . println ( " after label three " ) ;
}
System . out . println ( " after label two " ) ;
}
System . out . println ( " after label one " ) ;
}
}
}

Output
i=0
after label one
i=1
after label two
after label one
i=2
after label three
after label two
after label one

Explanation: When i=0, the first if succeeds and causes a break to label one, then prints
the statement. When i=1, the second if succeeds and causes a break to label two, then prints the
statements. When i=2, the third if succeeds and causes a break to label three, then prints all three
statements.

Complete Study Guide


Java Programming – Exam Study Notes 37

3.4.3 3. Return Statement


The return keyword can help you transfer control from one method to the method that called it. Since
the control jumps from one part of the program to another, the return is also a jump statement.

• return is a reserved keyword – we can’t use it as an identifier.

• It is used to exit from a method, with or without a value.

import java . io .*;


class ReturnExample {
public static int calculateSum ( int num1 , int num2 ) {
System . out . println ( " Calculating the sum of " + num1 + " and " +
num2 ) ;
int sum = num1 + num2 ;
System . out . println ( " The sum is : " + sum ) ;
return sum ;
// Note : Any code after ’ return ’ will not be executed .
// System . out . println (" end ") ; // error : unreachable statement
}
public static void main ( String [] args ) {
int result = calculateSum (5 , 10) ;
System . out . println ( " Result : " + result ) ;
}
}

Output
Calculating the sum of 5 and 10
The sum is: 15
Result: 15

Explanation: When we call the calculateSum method that has return sum, which returns the
value of sum and that value gets displayed on the console.

3.5 Chapter 3 Quiz


1. What will be the output of the following code?
int x = 5;
if ( x > 2)
if ( x > 4)
System . out . println ( " A " ) ;
else
System . out . println ( " B " ) ;

A: A ← Answer: A
B: B
C: Compilation Error
D: No Output

2. How many times will the following loop execute?


int i = 1;
while ( i <= 5) {
System . out . println ( " Hello " ) ;
}

Complete Study Guide


Java Programming – Exam Study Notes 38

A: 5 times
B: 6 times
C: Infinite times ← Answer: C
D: Compilation Error

3. What is the output of the following Java code?


for ( int i = 0; i < 5; i ++) {
if ( i == 2)
break ;
System . out . print ( i + " " ) ;
}

A: 0 1 2 3 4
B: 0 1 ← Answer: B
C: 0 1 2
D: No Output

4. What is the correct syntax for a do-while loop in Java?

A: do { } while (condition); ← Answer: A


B: while (condition) { }
C: do (condition) { }
D: while { condition };

5. What will be the output of the following nested loop?


for ( int i = 1; i <= 3; i ++) {
for ( int j = 1; j <= 2; j ++) {
System . out . print ( i + " ," + j + " " ) ;
}
}

A: 1,1 1,2 2,1 2,2 3,1 3,2 ← Answer: A


B: 1,1 2,1 3,1 1,2 2,2 3,2
C: 1,1 1,2 1,3 2,1 2,2 2,3
D: Compilation Error

6. What happens if the condition in an if statement is false?

A: It throws an error
B: Else block runs (if available) ← Answer: B
C: Code inside if runs
D: Program exits

7. Which loop guarantees execution at least once?

A: for
B: while
C: do-while ← Answer: C
D: foreach

Complete Study Guide


Java Programming – Exam Study Notes 39

8. Which keyword is used to skip the current iteration in a loop?

A: break
B: exit
C: continue ← Answer: C
D: skip

9. What is the correct structure for a switch-case block?

A: switch {}
B: switch:
C: switch() {} ← Answer: C
D: switch[]

10. Which loop is the best suited for traversing arrays directly?

A: for
B: while
C: do-while
D: for-each ← Answer: D

Complete Study Guide

You might also like