Arrays, Opp, Statements and Loops
Arrays, Opp, Statements and Loops
STATEMENTS, OPERATORS
AND INTRO. TO LOOPS IN
JAVA
BY SYED HASSAN MUJTABA ZAIDI
ARRAYS
AN ARRAY IN JAVA IS A COLLECTION OF ELEMENTS OF THE SAME TYPE, STORED
KEY POINTS:
}
CODE
Declaration:
int[] numbers; creates a reference to an array of integers.
Initialization:
new int[5] creates an array with 5 slots, each initialized to 0 by default.
Assignment:
Values are assigned using the syntax arrayName[index] = value.
Accessing Elements:
Use arrayName[index] to retrieve the value at the specified index.
Iteration:
for loop: Access each element by its index.
for-each loop: Simplifies iteration when you only need to read elements.
OUTPUT
FIRST ELEMENT: 10
SECOND ELEMENT: 20
ALL ELEMENTS IN THE ARRAY:
ELEMENT AT INDEX 0: 10
ELEMENT AT INDEX 1: 20
ELEMENT AT INDEX 2: 30
ELEMENT AT INDEX 3: 40
ELEMENT AT INDEX 4: 50
USING FOR-EACH LOOP: 10
20
30
40
50
ARITHMETIC OPERATORS
ARITHMETIC OPERATORS ARE USED FOR BASIC MATHEMATICAL CALCULATIONS LIKE
ADDITION, SUBTRACTION, MULTIPLICATION, ETC.
PUBLIC CLASS ARITHMETICOPERATORS {
INT A = 10;
INT B = 5;
}
RELATIONAL (COMPARISON) OPERATORS
Relational operators are used to compare two values. They return true or false.
STATEMENTS.
DECISION-MAKING STATEMENTS (IF, IF-ELSE, SWITCH)
a) if Statement
The if statement runs a block of code only if a condition is true.
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
}
}
c) switch
Statement
The switch statement selects one block of code to execute from
multiple options.
public class SwitchStatement {
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;
default:
System.out.println("Other day");
}
}
}
JUMP STATEMENTS (BREAK, CONTINUE)
a) break Statement
The break statement stops the loop immediately.
Thank you