Saturday, April 4, 2015

Java programs Conditional and control statements for Selenium interview - Class2

Java hello world program

Hello world Java program :- Java code to print hello world.

Java programming source code

class HelloWorld
{
   public static void main(String args[])
   {
      System.out.println("Hello World");
   }
}
"Hello World" is passed as an argument to println method, you can print whatever you want. There is also a print method which doesn't takes the cursor to beginning of next line as println does. System is a class, out is object of PrintStream class and println is the method. Output of program:









Java hello world code output

Java if else program

Java if else program uses if else to execute statement(s) when a condition is fulfilled. Below is a simple program which explains the usage of if else in java programming language.

Java programming if else statement

// If else in Java code
import java.util.Scanner;
 
class IfElse {
  public static void main(String[] args) {
    int marksObtained, passingMarks;
 
    passingMarks = 40;
 
    Scanner input = new Scanner(System.in);
 
    System.out.println("Input marks scored by you");
 
    marksObtained = input.nextInt();
 
    if (marksObtained >= passingMarks) {
      System.out.println("You passed the exam.");
    }
    else {
      System.out.println("Unfortunately you failed to pass the exam.");
    }
  }
}
Output of program:
Java if else program output
Above program ask the user to enter marks obtained in exam and the input marks are compared against minimum passing marks. Appropriate message is printed on screen based on whether user passed the exam or not. In the above code both if and else block contain only one statement but we can execute as many statements as required.

Nested If Else statements

You can use nested if else which means that you can use if else statements in any if or else block.
import java.util.Scanner;
 
class NestedIfElse {
  public static void main(String[] args) {
    int marksObtained, passingMarks;
    char grade;
 
    passingMarks = 40;
 
    Scanner input = new Scanner(System.in);
 
    System.out.println("Input marks scored by you");
 
    marksObtained = input.nextInt();
 
    if (marksObtained >= passingMarks) {
 
      if (marksObtained > 90) 
        grade = 'A';
      else if (marksObtained > 75)
        grade = 'B';
      else if (marksObtained > 60)
        grade = 'C';
      else
        grade = 'D'; 
 
      System.out.println("You passed the exam and your grade is " + grade);
    }
    else {
      grade = 'F'; 
      System.out.println("You failed and your grade is " + grade);
    }
  }
}


Java for loop

Java for loop used to repeat execution of statement(s) until a certain condition holds true. for is a keyword in Java programming language.

Java for loop syntax

for (/* Initialization of variables */ ; /*Conditions to test*/ ; /* Increment(s) or decrement(s) of variables */) {
  // Statements to execute i.e. Body of for loop
}
You can initialize multiple variables, test many conditions and perform increments or decrements on many variables according to requirement. Please note that all three components of for loop are optional. For example following for loop prints "Java programmer" indefinitely.
// Infinite for loop
for (;;) {
  System.out.println("Java programmer");
}
You can terminate an infinite loop by pressing Ctrl+C.

Simple for loop example in Java

Example program below uses for loop to print first 10 natural numbers i.e. from 1 to 10.
//Java for loop program
class ForLoop {
  public static void main(String[] args) {
    int c;
 
    for (c = 1; c <= 10; c++) {
      System.out.println(c);
    }
  }
}
Output of program:
Java for loop example program output

Java for loop example to print stars in console

Following star pattern is printed
*
**
***
****
*****
class Stars {
  public static void main(String[] args) {
    int row, numberOfStars;
 
    for (row = 1; row <= 10; row++) {
      for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) {
        System.out.print("*");
      }
      System.out.println(); // Go to next line
    }
  }
}
Above program uses nested for loops (for loop inside a for loop) to print stars. You can also use spaces to create another pattern, It is left for you as an exercise.
Output of program:
Java for loop example program output

Java while loop

Java while loop is used to execute statement(s) until a condition holds true. In this tutorial we will learn looping using Java while loop examples. First of all lets discuss while loop syntax:
while (condition(s)) {
// Body of loop
}
1. If the condition holds true then the body of loop is executed, after execution of loop body condition is tested again and if the condition is true then body of loop is executed again and the process repeats until condition becomes false. Condition is always evaluated to true or false and if it is a constant, For example while (c) { …} where c is a constant then any non zero value of c is considered true and zero is considered false.
2. You can test multiple conditions such as
while ( a > b && c != 0) {
 // Loop body
}
Loop body is executed till value of a is greater than value of b and c is not equal to zero.
3. Body of loop can contain more than one statement. For multiple statements you need to place them in a block using {} and if body of loop contain only single statement you can optionally use {}. It is recommended to use braces always to make your program easily readable and understandable.

Java while loop example

Following program asks the user to input an integer and prints it until user enter 0 (zero).
import java.util.Scanner;
 
class WhileLoop {
  public static void main(String[] args) {
    int n;
 
    Scanner input = new Scanner(System.in);
    System.out.println("Input an integer"); 
 
    while ((n = input.nextInt()) != 0) {
      System.out.println("You entered " + n);
      System.out.println("Input an integer");
    }
 
    System.out.println("Out of loop");
  }
}
Output of program:
Java while loop example program
Above program can be written in a more compact way as follows:
// Java while loop user input 
import java.util.Scanner;
 
class WhileLoop {
  public static void main(String[] args) {
    int n;
 
    Scanner input = new Scanner(System.in);
    System.out.println("Input an integer"); 
 
    while ((n = input.nextInt()) != 0) {
      System.out.println("You entered " + n);
      System.out.println("Input an integer");
    }
  }
}

Java while loop break program

Here we write above program but uses break statement. The condition in while loop here is always true so we test the user input and if its is zero then we use break to exit or come out of the loop.
import java.util.Scanner;
 
class BreakWhileLoop {
  public static void main(String[] args) {
    int n;
 
    Scanner input = new Scanner(System.in);
 
    while (true) {
      System.out.println("Input an integer");
      n = input.nextInt();
 
      if (n == 0) {
        break;
      }
      System.out.println("You entered " + n);
    }
  }
}

Java while loop break continue program

import java.util.Scanner;
 
class BreakContinueWhileLoop {
  public static void main(String[] args) {
    int n;
 
    Scanner input = new Scanner(System.in);
 
    while (true) {
      System.out.println("Input an integer");
      n = input.nextInt();
 
      if (n != 0) {
        System.out.println("You entered " + n);
        continue;
      }
      else {
        break;
      }
    }
  }
}
Whatever you can do with while loop can be done with for and do while loop.

No comments:

Post a Comment

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...