Unit 2: Branching and Looping
Branching
1.If Statement
Syntax
if (condition)
{
// code to execute
}
Example
public class IfExample
{
public static void main(String[] args)
{
int x = 10;
if (x > 5)
{
System.out.println("x is greater than 5");
}
}
}
2. If-Else Statement
Syntax
if (condition)
{
// code to execute if true
}
else
{
// code to execute if false
}
Example
public class IfElseExample
{
public static void main(String[] args)
{
int x = 10;
if (x > 5)
{
System.out.println("x is greater than 5");
}
else
{
System.out.println("x is less than or equal to 5");
}
}
}
3. Nested If-Else Statement
Syntax
if (condition1)
{
if (condition2)
{
// code to execute if both true
}
Else
{
// code to execute if condition1 true, condition2 false
}
}
else
{
// code to execute if condition1 false
}
Example
public class NestedIfElseExample {
public static void main(String[] args) {
int x = 10;
int y = 5;
if (x > 5) {
if (y > 3) {
System.out.println("x is greater than 5 and y is greater than 3");
} else {
System.out.println("x is greater than 5 but y is less than or equal to 3");
}
} else {
System.out.println("x is less than or equal to 5");
}
}
}
4. If-Else-If Ladder
Syntax:
if (condition1) {
// code to execute if condition1 true
} else if (condition2) {
// code to execute if condition1 false, condition2 true
} else if (condition3) {
// code to execute if condition1, condition2 false, condition3 true
} else {
// code to execute if all conditions false
}
Example
public class IfElseIfExample {
public static void main(String[] args) {
int x = 10;
if (x > 10) {
System.out.println("x is greater than 10");
} else if (x == 10) {
System.out.println("x is equal to 10");
} else if (x < 5) {
System.out.println("x is less than 5");
} else {
System.out.println("x is between 5 and 10");
}
}
}
5. Switch-Case Statement
switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
...
default:
// code to execute if expression doesn't match any case
break;
}
Example
public class SwitchCaseExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
break;
}
}
}
Looping
1. For Loop
Syntax:
for (initialization; condition; increment/decrement) {
// code to execute
}
Example
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("Iteration " + i);
}
}
}
2. While Loop
Syntax
while (condition) {
// code to execute
}
Example
public class WhileLoopExample {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("Iteration " + i);
i++;
}
}
}
3. Do-While Loop
Syntax
do {
// code to execute
} while (condition);
Example
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 0;
do {
System.out.println("Iteration " + i);
i++;
} while (i < 5);
}
}
Jump Statements
1. Break Statement
Syntax:
break;
Example
public class BreakExample {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
System.out.println("Iteration " + i);
}
}
}
Output
Iteration 0
Iteration 1
Iteration 2
2. Continue Statement
Syntax
continue;
Example
public class ContinueExample {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println("Iteration " + i);
}
}
}
Output
Iteration 1
Iteration 3
Iteration 5
2. Programs to demonstrate
different decision-making
statements.
public class DecisionMakingStatements {
public static void main(String[] args) {
// If Statement
System.out.println("If Statement:");
int num = 10;
if (num > 5) {
System.out.println("Number is greater than 5");
}
// If-Else Statement
System.out.println("\nIf-Else Statement:");
num = 10;
if (num > 5) {
System.out.println("Number is greater than 5");
}
}
}
} else {
System.out.println("Number is less than or equal to 5");
}
// Nested If Statement
System.out.println("\nNested If Statement:");
int num1 = 10;
int num2 = 20;
if (num1 > 5) {
if (num2 > 15) {
System.out.println("Both numbers are greater than 5 and 15 respectively");
}
// If-Else-If Statement
System.out.println("\nIf-Else-If Statement:");
num = 10;
if (num > 10) {
System.out.println("Number is greater than 10");
} else if (num == 10) {
System.out.println("Number is equal to 10");
} else {
System.out.println("Number is less than 10");
}
// Switch Statement
System.out.println("\nSwitch Statement:");
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
break;
}
// Nested If Statement
System.out.println("\nNested If Statement:");
int num1 = 10;
int num2 = 20;
if (num1 > 5) {
if (num2 > 15) {
System.out.println("Both numbers are greater than 5 and 15 respectively");
}
}
}
}
Output
If Statement:
Number is greater than 5
If-Else Statement:
Number is greater than 5
If-Else-If Statement:
Number is equal to 10
Switch Statement:
Tuesday
Nested If Statement:
Both numbers are greater than 5 and 15 respectively
Arrays
Arrays are collections of elements of the same data type stored in contiguous memory locations.
public class ArrayExample {
public static void main(String[] args) {
// Declare an integer array
int[] myArray = {10, 20, 30, 40, 50};
// Print array elements
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
}
}
Output
10
20
30
40
50
Array
Fixed size: You must specify the size when creating an array.
ArrayList
Dynamic size: ArrayLists can grow or shrink dynamically as elements are
added or removed.
When to use each:
Array: Use when you know the exact number of elements in advance and
need fast performance.
ArrayList: Use when you don't know the number of elements in advance
or need to frequently add/remove elements.
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Declare an ArrayList
ArrayList<String> myList = new ArrayList<>();
// Add elements to the list
myList.add("Apple");
myList.add("Banana");
myList.add("Cherry");
// Print the list
System.out.println(myList);
}
}
Output
• [Apple, Banana, Cherry]
Here's a simple explanation of Vector in Java:
What is a Vector?
A Vector is a dynamic array-like data structure in Java that can grow or
shrink as elements are added or removed.
Key Features:
Dynamic size: Vectors can resize automatically when elements are
added or removed.
Key differences:
Synchronization: Vector is synchronized, while ArrayList is not.
Performance: ArrayList is generally faster than Vector.
When to use each:
ArrayList: Use in single-threaded environments or when thread safety is
not a concern.
Vector: Use in multithreaded environments where thread safety is
crucial.
Vector Example
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
// Declare a Vector
Vector<String> myVector = new Vector<>();
// Add elements to the vector
myVector.add("Apple");
myVector.add("Banana");
myVector.add("Cherry");
// Print the vector
System.out.println(myVector);
}
}
Output
• [Apple, Banana, Cherry]
5. Program on Collections
(ArrayList/ Vectors)
import java.util.ArrayList;
import java.util.Vector;
public class ArrayListVsVectorExample {
public static void main(String[] args) {
// Declare an ArrayList
ArrayList<String> myList = new ArrayList<>();
// Add elements to the list
myList.add("Apple");
myList.add("Banana");
myList.add("Cherry");
}
// Print the list
System.out.println("ArrayList: " + myList);
// Declare a Vector
Vector<String> myVector = new Vector<>();
// Add elements to the vector
myVector.add("Apple");
myVector.add("Banana");
myVector.add("Cherry");
// Print the vector
System.out.println("Vector: " + myVector);
}
Strings
Strings are sequences of characters.
public class StringExample {
public static void main(String[] args) {
// Declare a string
String myString = "Hello, World!";
// Print the string
System.out.println(myString);
// Concatenate strings
String greeting = "Hello, ";
String name = "John!";
System.out.println(greeting + name);
}
}
Output
Hello, World!
Hello, John!
String
Immutable: Once created, its value cannot be changed.
StringBuffer
Mutable: Its value can be changed after creation.
When to use each:
String: Use when the string value won't change, such as when
displaying a fixed message.
StringBuffer: Use when the string value will change, such as when
building a dynamic message or reading input from a user.
Stringbuffer
public class StringBufferExample {
public static void main(String[] args) {
// Declare a StringBuffer
StringBuffer myBuffer = new StringBuffer("Hello, ");
// Append a string to the buffer
myBuffer.append("World!");
// Print the buffer
System.out.println(myBuffer);
}
}
4. Program on String and String
Buffer.
public class StringAndStringBufferExample {
public static void main(String[] args) {
// String example
System.out.println("String Example:");
String myString = "Hello, World!";
System.out.println(myString);
// Concatenate strings
String greeting = "Hello, ";
String name = "John!";
System.out.println(greeting + name);
// StringBuffer example
System.out.println("\nStringBuffer Example:");
StringBuffer myBuffer = new StringBuffer("Hello, ");
myBuffer.append("World!");
System.out.println(myBuffer.toString());
}
}
3.Program to implement Arrays
(1D, 2D).
import java.util.Scanner;
public class ArrayExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 1D Array
System.out.print("Enter the size of the 1D array: ");
int size1D = scanner.nextInt();
int[] array1D = new int[size1D];
System.out.println("Enter elements for the 1D array:");
for (int i = 0; i < size1D; i++) {
array1D[i] = scanner.nextInt();
}
System.out.println("1D Array elements:");
for (int i = 0; i < size1D; i++) {
System.out.print(array1D[i] + " ");
}
// 2D Array
System.out.print("\nEnter the number of rows for the 2D array: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns for the 2D array: ");
int cols = scanner.nextInt();
int[][] array2D = new int[rows][cols];
System.out.println("Enter elements for the 2D array:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
array2D[i][j] = scanner.nextInt();
}
}
System.out.println("2D Array elements:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(array2D[i][j] + " ");
}
System.out.println();
}
}
}
Output
Enter the size of the 1D array: 5
Enter elements for the 1D array:
10
20
30
40
50
1D Array elements:
10 20 30 40 50
Enter the number of rows for the 2D array: 3
Enter the number of columns for the 2D array: 3
Enter elements for the 2D array:
1
2
3
4
5
6
7
8
9
2D Array elements:
123
456
789
Addition and Multiplication of
2D Array
import java.util.Scanner;
public class ArrayOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input for 2D array 1
System.out.print("Enter the number of rows for the 1st 2D array: ");
int rows1 = scanner.nextInt();
System.out.print("Enter the number of columns for the 1st 2D array: ");
int cols1 = scanner.nextInt();
int[][] array1 = new int[rows1][cols1];
System.out.println("Enter elements for the 1st 2D array:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
array1[i][j] = scanner.nextInt();
}
}
// Input for 2D array 2
System.out.print("Enter the number of rows for the 2nd 2D array: ");
int rows2 = scanner.nextInt();
System.out.print("Enter the number of columns for the 2nd 2D array: ");
int cols2 = scanner.nextInt();
int[][] array2 = new int[rows2][cols2];
System.out.println("Enter elements for the 2nd 2D array:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
array2[i][j] = scanner.nextInt();
}
}
// Check if arrays have the same dimensions
if (rows1 != rows2 || cols1 != cols2) {
System.out.println("Arrays must have the same dimensions for sum and product
operations.");
return;
}
// Calculate sum
int[][] sumArray = new int[rows1][cols1];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
sumArray[i][j] = array1[i][j] + array2[i][j];
}
}
System.out.println("Sum of the two 2D arrays:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
System.out.print(sumArray[i][j] + " ");
}
System.out.println();
}
/ Calculate multiplication
int[][] productArray = new int[rows1][cols1];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
productArray[i][j] = array1[i][j] * array2[i][j];
}
}
System.out.println("Product of the two 2D arrays:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
System.out.print(productArray[i][j] + " ");
}
System.out.println();
}
}
}
Output
Enter the number of rows for the 1st 2D array: 2
Enter the number of columns for the 1st 2D array: 2
Enter elements for the 1st 2D array:
1
2
3
4
Enter the number of rows for the 2nd 2D array: 2
Enter the number of columns for the 2nd 2D array: 2
Enter elements for the 2nd 2D array:
5
6
7
8
Sum of the two 2D arrays:
68
10 12
Product of the two 2D arrays:
5 12
21 32
Experiments Based on
Experiment List(Experiment
Number 2)
2.a)You have been given an array of positive integers A1, A2,...,An with length N and you have to print an array of same length (N) where the values in the new array
are the sum of every number in the array, except the number at that index.
i/p 1 2 3 4
For the 0th index, the result will be 2+3+4= 9, similarly for the second, third and fourth index the corresponding results will be 8, 7 and 6 respectively.
i/p 4 5 6
o/p 11 10 9
import java.util.Scanner;
public class sumofarr {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of the array: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
int[] result = new int[n];
for (int i = 0; i < n; i++) {
int sum = 0;
for (int j = 0; j < n; j++) {
if (i != j) {
sum += arr[j];
}
}
result[i] = sum;
}
System.out.println("Result array:");
for (int i = 0; i < n; i++) {
System.out.print(result[i] + " ");
}
}
}
• 2.b)
a. The annual examination results of 5 students are tabulated as follows:
Roll No Subject1 Subject2 Subject3
1 10 20 60
2 80 60 70
WAP to read the data and determine the following
Total marks obtained by each student
The student who obtained the highest total marks
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] marks = new int[2][3];
int[] totalMarks = new int[2];
for (int i = 0; i < 2; i++) {
System.out.println("Student " + (i + 1));
for (int j = 0; j < 3; j++) {
System.out.print("Subject " + (j + 1) + ": ");
totalMarks[i] += scanner.nextInt();
}
System.out.println("Total: " + totalMarks[i]);
}
if (totalMarks[0] > totalMarks[1]) {
System.out.println("\nStudent 1 wins with " + totalMarks[0] + "
marks!");
} else {
System.out.println("\nStudent 2 wins with " + totalMarks[1] + "
marks!");
}
}
}
2.c)
a. WAP to display following pattern using irregular arrays (jagged arrays).
1
12
1 2 3 ………..
public class Main {
public static void main(String[] args) {
int[][] jaggedArray = {
{1},
{1, 2},
{1, 2, 3},
{1, 2, 3, 4},
{1, 2, 3, 4, 5}
};
for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
}
}
Experiments Based on
Experiment List(Experiment
Number 3)
3a)WAP to find out number of uppercase &
lowercase characters, blank spaces and digits from
the string.
import java.util.Scanner;
public class space {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
int upper = 0, lower = 0, space = 0, digit = 0;
for (char c : input.toCharArray()) {
if (c >= 'A' && c <= 'Z') upper++;
if (c >= 'a' && c <= 'z') lower++;
if (c == ' ') space++;
if (c >= '0' && c <= '9') digit++;
}
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
System.out.println("Spaces: " + space);
System.out.println("Digits: " + digit);
}
}
3B) WAP to count the frequency of occurrence of a
given character in a given line of text.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text: ");
String input = scanner.nextLine();
System.out.print("Enter character: ");
char c = scanner.next().charAt(0);
int count = 0;
for (char ch : input.toCharArray()) {
if (ch == c) count++;
}
System.out.println(c + " appears " + count + " times.");
}
}
Output
Enter text: hello world
Enter character: l
l appears 3 times.
3c.WAP to check if a string is a palindrome or not
using inbuild functions
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
StringBuilder sb = new StringBuilder(input);
String reversed = sb.reverse().toString();
if (input.equals(reversed)) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}
}
}
4.a) WAP to accept students name from
command line and store them in vector
import java.util.Scanner;
import java.util.Vector;
public class SimplestStudentNames {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Vector<String> studentNames = new Vector<>();
System.out.println("Enter student names (type 'exit' to stop):");
while (true) {
String name = scanner.nextLine();
if (name.equals("exit")) { // Case-sensitive comparison
break;
}
studentNames.add(name);
}
System.out.println(studentNames);
scanner.close();
}
}
4.b)WAP to add n strings in a vector array. Input new string and check if it is present in the
vector. If present delete it else add to the vector
import java.util.Scanner;
import java.util.Vector;
public class SimplestManageStringsInVector {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Vector<String> strings = new Vector<>();
System.out.println("Enter number of strings:");
int n = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.println("Enter " + n + " strings:");
for (int i = 0; i < n; i++) {
strings.add(scanner.nextLine());
}
System.out.println("Enter a new string:");
String newString = scanner.nextLine();
if (strings.contains(newString)) {
strings.remove(newString);
} else {
strings.add(newString);
}
System.out.println(strings);
scanner.close();
}
}
Output