JAVA Chapter III

man-using-computerHi people, this blog is going to discuss about very basic points and main concepts you must know before using JAVA language. This third article will be helpful to build the foundation of JAVA programming. In this tutorial we will learn about:-

  • Loops
  • Break & continue statements
  • Switch case

Loops

  1. For loop
  • for loop is a repetition block that needs to be executed a specific number of times.
  • This loop is useful when you know how many times a block should be repeated.

1

Code example

2

Console

4

  1. For each loop / Enhanced for loop
  • This loop uses to traverse collection of elements including arrays.

5

Code example

6

Console

7

  1. While loop
  • This is the very basic loop in java.
  • While loop repeatedly executes the block as long as the given condition is true.

Code example

8

Console

9

  1. Do while loop
  • This one similar to while
  • Only differentiation is do while loop is guaranteed to execute at least one time.
  • Do while loop check condition at last.

Code example

10

Console

11

Break & continue statements

Break

  • This uses to terminate the loop immediately.
  • After terminate next statement will be executed. (outside the loop)
  • Break statement also uses to terminate a case in the switch statement. (look at the next topic)

Code example

12

Console

13

Continue

  • From this statement loop will jump immediately to the next iteration of the loop.

Code example

14

Console

15

Switch case

  • The switch statement uses to check equality of set of values for one variable.
  • Each value is called a case.
  • The variable used in a switch can only be integers, convertible integers (byte, short, char) and strings.
  • Using break statement a switch can be terminated after execute a matched case.
  • If we not using break statement within cases then all cases will execute until a brake is reached.
  • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Code example

16

Console

17

Important

  • If we check equality we use == for primitive data types and .equals() for object data types.

Code example

HelloWorld .java

18

HumanBeing.java

19

Console

20

 

JAVA Chapter I               JAVA Chapter II

Leave a comment