Java Logical Operators( for loop , while loop and switch statement)

Java Logical Operators
  • Equality and Rational Operators
= Equal to
!= Not equal to
>Greater than
>=Greater than or equal to
< Less than
<= Less than or equal to
  • Conditional Operator
?:Ternary(shorthand for if-then-else statement)
  • Type comparison operator
instanceof Compares an object to a specified type

Arrays and for-each Loop

public class ArrayOperations {

Public static void main (String  args []){

String [] names = new String [3];

name[0] = "Blue Shirt" ;

name[1] = "Red Shirt" ;

name[2] = "Black Shirt" ;

int [] numbers = {100, 200, 300};

for (String name: names){

System.out.println("Name :  " + name);


for (int number: numbers){

System.out.println("Number:  "+ number);




The output of the class is shown here:

Name: Blue Shirt

Name: Red Shirt

Name: Black Shirt

Number: 100

Number: 200

Number: 300

Note: Arrays are also object by default. All array support the methods  of the class Object. You can always obtain the size of an array using its length field.

for Loop

public class ForLoop {

public static void main( String args []) {

for (int i=0; i<9; i++){

System.out.println("i: " + i);



The classic for loop is shown in the slide. A counter is initialized and incremented for each step of the loop. When the condition statement evaluates to false (when i is no longer less than 9) , the loop exits. Here is the sample output for the program.

i: 0

i  1

i: 2

i: 3

i: 4

i: 5

i: 6

i: 7

i: 8

while loop

public class WhileLoop {

public static void main( String args []) {

int i =0;

int []  numbers = { 100, 200, 300};

while( i< numbers.length){

System.out.println("Number: " + numbers[i]);





The While loop performs a test and continues if the expression  evaluates to true. The while loop, shown here, iterates through an array using a counter.

Here is the output for the code:

Number: 100

Number: 200

Number: 300

String switch Statement

This example shows a switch statement  in Java using  a String. Prior to version 7 of Java , only enums  and byte, short ,  char and int primitive data types could be used in a switch statement.

About Codingwelove

Recommended Posts × +


Post a Comment