OOP Unit 2- Control
statements in java
By Prof. Apurva Joshi
What Are Conditional Statements in Java?
• Conditional statements are essential in Java programming, allowing
your programs to respond dynamically to different situations.
• With Java conditional statements, you can create smarter code that
adapts to a variety of scenarios, ensuring accuracy and flexibility in
your applications.
• Conditional statements in Java are instructions that help your
program make decisions. Think of them like traffic lights for your
code: they tell the program when to go, stop, or change direction
based on specific conditions. If a certain condition is true, the
program runs one block of code. If it’s false, it might run a different
block or do nothing at all.
By Prof Apurva Joshi
If statement
int marks = 75;
if (marks >= 50) {
[Link]("You passed!");
} else {
[Link]("You need to try again.");
}
the program checks if the marks are 50 or more. If true, it prints “You
passed!” Otherwise, it prints “You need to try again.”
By Prof Apurva Joshi
By Prof Apurva Joshi
If statement
if (condition) {
// code to execute if condition is true
}
• If.. Else
• if (condition) {
• // code if condition is true
• } else {
• // code if condition is false
•}
By Prof Apurva Joshi
Else if ladder
• if (condition1) {
• // code for condition1
• } else if (condition2) {
• // code for condition2
• } else {
• // code if no conditions are true
•}
By Prof Apurva Joshi
Nested Conditional Statements in Java
• if (condition1) {
• if (condition2) {
• // code runs if both conditions are true
• } else {
• // code runs if condition1 is true and condition2 is false
• }
• } else {
• // code runs if condition1 is false
•}
By Prof Apurva Joshi
To check if number is positive or zero
// Check if the number is positive, negative, or zero
import [Link]; if (number > 0) {
[Link]("The number is
positive.");
public class PositiveNegativeCheck { } else if (number < 0) {
public static void main(String[] args) { [Link]("The number is
// Create a Scanner object for user input negative.");
Scanner scanner = new } else {
Scanner([Link]); [Link]("The number is zero.");
}
// Prompt the user to enter a number // Close the scanner
[Link]("Enter a number: "); [Link]();
double number = [Link](); }
}
By Prof Apurva Joshi
To check age of user as adult or // Check if the age is valid
minor if (age < 0) {
[Link]("Invalid age
entered. Please enter a positive number.");
import [Link]; } else {
// Determine if the person is an adult
or a minor
public class AgeChecker { if (age >= 18) {
public static void main(String[] [Link]("You are an
args) { adult.");
} else {
Scanner scanner = new [Link]("You are a
Scanner([Link]);
minor.");
}
// Prompt the user to enter }
their age
[Link]();
[Link]("Enter your }
age: "); }
int age = [Link]();
By Prof Apurva Joshi
• Grade // Input marks from the user
[Link]("Enter marks (out of 100): ");
int marks = [Link]();
import [Link];
// Determine grade based on marks
String grade;
if (marks >= 90) {
public class StudentGrade { grade = "A+";
} else if (marks >= 80) {
grade = "A";
public static void } else if (marks >= 70) {
grade = "B+";
main(String[] args) { } else if (marks >= 60) {
grade = "B";
Scanner scanner = new } else if (marks >= 50) {
grade = "C";
Scanner([Link]); } else if (marks >= 40) {
grade = "D";
} else {
grade = "F";
}
// Output the grade
[Link]("Your grade is: " + grade);
[Link]();
}
}
By Prof Apurva Joshi
switch Statement in Java
• switch (variable) {
• case value1:
• // code
• break;
• case value2:
• // code
• break;
• default:
• // code if no cases match
•}
By Prof Apurva Joshi
Days of week using switch case 3:
[Link]("Wednesday");
break;
import [Link];
case 4:
[Link]("Thursday");
public class WeekDayPrinter { break;
public static void main(String[] args) { case 5:
Scanner scanner = new [Link]("Friday");
Scanner([Link]); break;
case 6:
[Link]("Enter a number (1-7) [Link]("Saturday");
to get the corresponding day of the week: "); break;
int dayNumber = [Link](); case 7:
[Link]("Sunday");
break;
switch (dayNumber) {
default:
case 1: [Link]("Invalid input! Please
[Link]("Monday"); enter a number between 1 and 7.");
break; }
case 2:
[Link]("Tuesday"); [Link]();
break; }
}
By Prof Apurva Joshi
Loops in java
• Loops are one of the most essential tools in Java programming,
helping you avoid repetitive code and improve program efficiency.
With the right use of loops in Java, you can perform tasks like printing
patterns, iterating over arrays, or executing a block of code multiple
times with ease.
• There are different types of loop statements in Java, each with
specific use cases that suit various programming needs.
Using for, while, or do-while effectively allows you to build strong
logic and cleaner code.
By Prof Apurva Joshi
What Are Loops in Java?
• Java loops are used to repeat a block of code multiple times until a specific
condition is met. This helps reduce repetitive code and makes programs
shorter and easier to manage. Instead of writing the same line again and
again, you write it once inside a loop, and Java takes care of repeating it as
needed.
• Loops are commonly used for printing values, processing arrays, and
running tasks in a cycle.
for (int i = 1; i <= 5; i++) {
[Link]("Hello Java");
}
By Prof Apurva Joshi
Why Use Loops in Java?
• 1. Reduces Code Repetition: Loops allow you to execute the same code multiple
times without rewriting it, making your program shorter and cleaner.
• 2. Makes Code More Efficient: Instead of manually writing multiple statements,
loops automate tasks, saving time during both coding and execution.
• 3. Useful for Working with Data Structures: Loops are essential when working
with arrays, lists, or any collection, helping you access and process each element
easily.
• 4. Enhances Logic Building Skills: Using loops improves your ability to build
logical and optimized solutions for real-world problems in programming.
• 5. Enables Dynamic Execution: With user input or real-time conditions, loops let
your program adapt and repeat tasks until the desired condition is met.
By Prof Apurva Joshi
By Prof Apurva Joshi
while Loop in Java
• The while loop in Java is used when you
want to repeat a block of code as long as
a condition remains true. It checks the
condition before each iteration, which
means the loop may never run if the
condition is false at the start. It is ideal
when the number of repetitions is
unknown and depends on dynamic
inputs or runtime decisions.
• Use it when you need more control over
when to start or stop the loop based on
logic that can change inside the loop.
By Prof Apurva Joshi
public class WhileExample {
While syntax public static void main(String[] args) {
int i = 1;
while (i <= 5) {
• while (condition) { [Link]("Current value: " +
i);
• // code to be executed i++;
}
•} }
}
Output:
Current value: 1
Current value: 2
Current value: 3
Current value: 4
Current value: 5
Ref: Java Loops: All Types of Loop Statements With Examples
By Prof Apurva Joshi
// Java program to find the sum of positive
numbers using while loop
• import [Link]; // while loop continues
// until entered number is positive
• class Main { while (number >= 0) {
• public static void main(String[] args) { // add only positive numbers
• sum += number;
• int sum = 0;
[Link]("Enter a number");
• // create an object of Scanner class number = [Link]();
• Scanner input = new Scanner([Link]); }
• // take integer input from the user [Link]("Sum = " + sum);
• [Link]("Enter a number"); [Link]();
• int number = [Link](); }
• }
By Prof Apurva Joshi
Take input in Array using while Loop
import [Link]; // Take input for the array elements
[Link]("Enter " + size + " elements:");
int i = 0;
public class ArrayInputWhileLoop { while (i < size) {
public static void main(String[] args) { array[i] = [Link]();
i++;
Scanner scanner = new }
Scanner([Link]);
// Print the array elements
// Prompt user for the size of the [Link]("The elements of the array are:");
array i = 0;
[Link]("Enter the size of while (i < size) {
the array: "); [Link](array[i] + " ");
i++;
int size = [Link]();
}
// Initialize the array [Link]();
int[] array = new int[size]; }
}
By Prof Apurva Joshi
do-while loop in Java
• The do-while loop in Java works
similarly to the while loop but with
one big difference—it always runs at
least once, no matter what the
condition is. This is because the
condition is checked after the code
block executes.
• It is useful when the loop body must
be executed first (like displaying a
menu, taking user input, or running
an initial task) before deciding
whether to repeat.
By Prof Apurva Joshi
Do-While syntax
• do {
• // code to be executed
• } while (condition);
• When to Use do-while Loop
• Code should run at least once
• Used in menu-driven programs
• Useful for input validation or retry loops
By Prof Apurva Joshi
Print menu once and repeat until user selects
Exit using Do.. While
• import [Link]; if (choice == 1) {
[Link]("Hello!");
• public class MenuExample { } else if (choice == 2) {
• public static void main(String[] args) { [Link]("Bye!");
• Scanner sc = new Scanner([Link]); }
• int choice;
} while (choice != 3);
• do { [Link]("Program
• [Link]("1. Say Hello"); exited.");
• [Link]("2. Say Bye"); }
• [Link]("3. Exit"); }
• [Link]("Enter your choice:
");
• choice = [Link]();
By Prof Apurva Joshi
Sum of Numbers (User Input until 0 is
entered):
• import [Link]; do {
[Link]("Enter a number: ");
number = [Link]();
• public class SumOfNumbersDoWhile { sum += number; // Add the entered number to the
• public static void main(String[] args) sum
{ } while (number != 0); // Loop continues until 0 is
entered
• Scanner scanner = new
Scanner([Link]);
[Link]("The total sum is: " + sum);
• int number; [Link]();
• int sum = 0; }
}
• [Link]("Enter
numbers to sum (enter 0 to stop):");
By Prof Apurva Joshi
for Loop in Java
• The for loop in Java is used when you know exactly how many times
you want to execute a block of code. It has a clear structure with
three parts: initialization, condition, and update. This loop is widely
used for counting, iterating over arrays, and repetitive tasks with a
known number of steps.
• It's one of the most readable and commonly used loops in Java. You
should use it when the number of iterations is fixed or can be easily
determined before the loop starts.
By Prof Apurva Joshi
For loop
for (initialization; condition; update) {
// code to be executed
}
Sum of first 10 numbers
public class SumExample {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum = sum + i;
[Link]("After adding " + i + ", sum is: " +
sum);
}
[Link]("Final Sum of first 10 numbers: " +
sum);
}
} By Prof Apurva Joshi
To take input in array through For Loop
// Loop to take input for each element of the array
for (int i = 0; i < arraySize; i++) {
import [Link]; [Link]("Enter element at index " + i + ":
");
numbers[i] = [Link]();
public class ArrayInputAndPrint { }
public static void main(String[] args) { [Link]("\nElements of the array are:");
Scanner inputScanner = new // Loop to print each element of the array
Scanner([Link]);
for (int i = 0; i < arraySize; i++) {
[Link]("Element at index " + i + ": " +
[Link]("Enter the size of numbers[i]);
the array: "); }
int arraySize = [Link]();
[Link]();
}
int[] numbers = new int[arraySize]; }
[Link]("Enter " +
arraySize + " integer elements for the
array:");
By Prof Apurva Joshi
• Multiplication table
• import [Link]; // Import the Scanner class to read user input
• public class MultiplicationTable {
• public static void main(String[] args) {
• Scanner input = new Scanner([Link]); // Create a Scanner object
• [Link]("Enter the number for which you want the multiplication table: ");
• int number = [Link](); // Read the integer input from the user
• [Link]("Multiplication Table of " + number + ":");
• // Use a for loop to iterate from 1 to 10
• for (int i = 1; i <= 10; i++) {
• // Calculate and print each line of the multiplication table
• [Link](number + " * " + i + " = " + (number * i));
• }
• [Link](); // Close the scanner to release system resources
• }
• }
By Prof Apurva Joshi
Switch Statements in Java
• The switch statement in Java is a multi-way branch statement.
In simple words, the Java switch statement executes one
statement from multiple conditions.
• It is an alternative to an if-else-if ladder statement. It provides
an easy way to dispatch execution to different parts of the
code based on the value of the expression. The expression can
be of type byte, short, char, int, long, enums, String, or wrapper
classes (Integer, Short, Byte, Long).
By Prof Apurva Joshi
• // Java program demonstrates how to use
switch-case case 3:
[Link]("Medium");
break;
• public class Number case 4:
• { [Link]("Large");
• public static void main(String[] args) { break;
case 5:
•
[Link]("Extra Large");
• // Replace with desired size (1, 2, 3, 4, or 5) break;
• int size = 2; default:
[Link]("Invalid size
• switch (size) { number");
}
• case 1: }
• [Link]("Extra Small"); }
• break;
• case 2:
• [Link]("Small");
• break;
By Prof Apurva Joshi
Break and Continue statement in Java
• The break and continue statements are the jump statements that are used
to skip some statements inside the loop or terminate the loop
immediately without checking the test expression. These statements can
be used inside any loops such as for, while, do-while loop.
• Break: The break statement in java is used to terminate from the loop
immediately. When a break statement is encountered inside a loop, the
loop iteration stops there, and control returns from the loop immediately
to the first statement after the loop. Basically, break statements are used
in situations when we are not sure about the actual number of iteration
for the loop, or we want to terminate the loop based on some condition.
• In Java, a break statement is majorly used for:
• To exit a loop.
• Used as a “civilized” form of goto.
• Terminate a sequence in a switch statement.
By Prof Apurva Joshi
• // Java program to demonstrate using
• // break to exit a loop
• class Test {
• public static void main(String[] args)
• {
• // Initially loop is set to run from 0-9
• for (int i = 0; i < 10; i++) {
• // Terminate the loop when i is 5
• if (i == 5)
• break;
• [Link]("i: " + i);
• }
• [Link]("Out of Loop");
• }
• }
By Prof Apurva Joshi
Java Methods
• Java Methods are // Creating a method
public class MyFirstMethod
blocks of code that {
perform a specific task. public void printMessage() {
A method allows us to [Link]("Hello, Geeks!");
reuse code, improving }
public static void main(String[] args) {
both efficiency and // Create an instance of the Method class
organization. All Geeks obj = new Geeks();
methods in Java must
belong to a class. // Calling the method
[Link]();
Methods are similar to }
functions and expose }
the behavior of objects.
By Prof Apurva Joshi
Syntax of a Method
By Prof Apurva Joshi
Why Do We Break Code into Methods?
• Breaking code into separate methods helps improve
readability, reusability, and maintainability
• Reusability: Write once, use multiple times without repeating
code so that code reusability increase.
• Readability: Smaller, named methods make the code easier to
read and understand.
• Maintainability: It’s easier to fix bugs or update code when it's
organized into methods.
• Testing: Methods can be tested independently, improving code
reliability and easier debugging.
By Prof Apurva Joshi
• Method Call Stack in Java
• Java is an object-oriented and stack-based programming language where
methods play a key role in controlling the program's execution flow. When a
method is called, Java uses an internal structure known as the call stack to
manage execution, variables, and return addresses.
• What is the Call Stack
• The call stack is a data structure used by the program during runtime to manage
method calls and local variables. It operates in a Last-In-First-Out (LIFO)
manner, meaning the last method called is the first one to complete and exit.
• How Are Methods Executed
• When a method is called:
• A new stack frame is added to the call stack to store method details.
• The method runs its code.
• After execution, the stack frame is removed, and control goes back to the calling
method.
• Java automatically manages the call stack using the Java Virtual Machine (JVM).
By Prof Apurva Joshi
Types of Methods in Java
• 1. Predefined Method [Link]() // returns random value
[Link] // return pi value
• Predefined methods are the
method that is already defined
in the Java class libraries. It is
also known as the standard
library method or built-in
method. For
example, random() method
which is present in the Math
class and we can call it using
the [Link]()
as shown in the below example.
By Prof Apurva Joshi
Types of Methods in Java
• 2. User-defined sayHello // user define method created above in the article
Method
Greet()
setName()
• The method written by
the user or
programmer is known
as a user-defined
method. These
methods are modified
according to the
requirement.
By Prof Apurva Joshi
Different Ways to Create Java Method
• There are two ways to create a public void disp( )
method in Java: {
• 1. Instance Method: Access the int a= 10;
instance data using the object name. [Link](a);
Declared inside a class. }
• The important points regarding
instance variables are:
[Link] methods can access
instance variables and instance
methods directly and undeviatingly.
[Link] methods can access static
variables and static methods
directly.
By Prof Apurva Joshi
Calling a method in java
• // Java program to see how can we call
• // an instance method with parameter // Instance method with parameter
void add(int a, int b)
• import [Link].*; {
// local variables
• class GFG { int x= a;
• // static method int y= b;
• public static void main (String[] args) {
int z= x + y;
•
[Link]("Sum : " + z);
• // creating object
}
• GFG obj = new GFG();
}
•
• // calling instance method by passing value
• [Link](2,3);
•
• [Link]("GFG!");
• }
•
By Prof Apurva Joshi
2. Static Method:
• Access the static data using class name.
Declared inside class with static keyword.
• In Java, the static keyword is used to create
methods that belongs to the class rather than
any specific instance of the class. Any method
that uses the static keyword is referred to as
a static method.
• Features of Static Method:
• A static method in Java is associated with the
class, not with any object or instance.
• It can be accessed by all instances of the
class, but it does not rely on any specific
instance.
• Static methods can access static variables
directly without the need for an object.
• They cannot access non-static variables
(instance) or methods directly.
• Static methods can be accessed directly in
both static and non-static contexts.
By Prof Apurva Joshi
Static Method Cannot Access Instance
Variables
• The JVM executes the static
method first, even before
creating class objects. So, static
methods cannot access
instance variables, as no object
exists at that point.
By Prof Apurva Joshi
• Example of Static method
• // the static method does not have
// Declaration of a static method
• // access to the instance variable
static void staticDisplay()
{
• import [Link].*;
[Link](a);
}
• public class Geeks {
•
• // static variable
// Java program to demonstrate that
• static int a = 40; // main method
public static void main(String[] args)
• // instance variable {
• int b = 50; Geeks obj = new Geeks();
[Link]();
• void simpleDisplay()
• { // Calling static method
• [Link](a); staticDisplay();
• [Link](b); }
• } }
By Prof Apurva Joshi
Why Use Static Methods?
• To access or modify static variables or perform actions not tied to any
instance.
• Useful for utility or helper classes like Collections, Math, etc.
• Restrictions on Static Methods
• Non-static data members or non-static methods cannot be used by static
methods, and static methods cannot call non-static methods directly.
• In a static environment, this and super are not allowed to be used.
• Why is the main Method Static in Java?
• The main method must be static because the JVM does not create an
object of the class before invoking it. If it were a non-static method, JVM
would first build an object before calling the main() method, resulting in
an extra memory allocation difficulty.
By Prof Apurva Joshi
By Prof Apurva Joshi
Java Math Class
[Link] Class methods help to perform numeric
operations like square, square root, cube, cube root, exponential
and trigonometric operations.
By Prof Apurva Joshi
Method Overloading in Java
• In Java, Method Overloading allows us to define multiple methods
with the same name but different parameters within a class. This
difference may include:
• The number of parameters
• The types of parameters
• The order of parameters
• Method overloading in Java is also known as Compile-time
Polymorphism, Static Polymorphism, or Early binding, because
the decision about which method to call is made at compile time.
When there are overloaded methods that accept both a parent type
and a child type, and the provided argument could match either one,
Java prefers the method that takes the more specific (child) type.
This is because it offers a better match.
By Prof Apurva Joshi
Key features of Method Overloading
• Multiple methods can share the same name in a class when
their parameter lists are different.
• Overloading is a way to increase flexibility and improve the
readability of code.
• Overloading does not depend on the return type of the method,
two methods cannot be overloaded by just changing the return
type.
By Prof Apurva Joshi
• // Java program to demonstrate working of // Overloaded sum()
method // This sum takes two double parameters
• // overloading in Java public double sum(double x, double y)
• public class Sum { {
return (x + y);
• }
• // Overloaded sum()
// Driver code
• // This sum takes two int parameters public static void main(String args[])
• public int sum(int x, int y) { return (x + y); } {
Sum s = new Sum();
[Link]([Link](10, 20));
• // Overloaded sum() [Link]([Link](10, 20, 30));
• // This sum takes three int parameters [Link]([Link](10.5, 20.5));
}
• public int sum(int x, int y, int z) }
• {
• return (x + y + z);
• }
By Prof Apurva Joshi
What is Java API?
• The term API stands for Application Programming Interface. It
is a set of communication protocols and programming code
that makes communication between two or more applications
possible. It receives the request from the user, sends it to the
information provider, and then gets the result from the
information provider and sends it to the user. It is like when we
search for something online, the API sends the request to the
database, and after the data is found in the database, the
required result is provided.
By Prof Apurva Joshi
Java API
ava APIs are very important for developers as they provide
a collection of classes, interfaces, methods, and tools that
developers use to build Java applications. It simplifies
coding by providing ready-to-use modules, enabling
developers to focus on application logic rather than
reinventing basic functionalities. Also, APIs in Java let the
developers access some third-party services in just a few
lines of code.
Sometimes Java APIs may be important for the
functionality of an application. Moreover, it helps
streamline operating procedures in different applications
such as LinkedIn, Instagram, and Twitter by providing
multiple options for a user on a single screen.
By Prof Apurva Joshi
Example of an API in Java
• import [Link].*
• import [Link].*
• import [Link];
• import [Link];
• public static void commit() {
• Connection con = [Link]();
• if (con != null) {
• try {
• [Link]();
• } catch (SQLException e) {
• [Link]();
• throw new RuntimeException("Transaction related exception occurred while trying to establish a connection…");
• }
• }
• }
By Prof Apurva Joshi
Example Explained.
• This code is designed for managing transactions in a database,
where the `commit()` method finalizes a series of database
operations, making their changes permanent. Here the
‘commit()’ method is responsible for committing a transaction
using the Java JDBC API. The method begins by obtaining a
‘Connection’ object through the ‘[Link]()’ method, indicating a
connection to a database. Subsequently, it checks if the
connection is not null before attempting to commit the
transaction using the ‘[Link]()’ statement. In the event of
an ‘SQLException’ during the commit process, the code catches
the exception, prints the stack trace for debugging purposes,
and throws a `RuntimeException` with an informative message.
By Prof Apurva Joshi
RESTful API in Java
• A RESTful API (Representational State Transfer) is an
architectural style for designing networked applications.
RESTful APIs define a set of principles and constraints for the
development of scalable, stateless, and maintainable web
services. In the Java ecosystem, constructing RESTful APIs is
commonly achieved through frameworks such as Spring Boot.
• RESTful APIs should possess a uniform and consistent
interface. This API demands well-defined conventions for
resource naming, the utilization of standard HTTP methods, and
a consistent approach to representing resources.
• Ref: Java API: Definition, Packages, Types, and Examples Explained
By Prof Apurva Joshi
• Thank You
By Prof Apurva Joshi