Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

Java

Learn step by step



JAVA STATEMENT

Methods and constructors are sequences of statements, along with variable definitions. The statements specify the sequence of actions to be performed when a method or constructor is invoked. They can alter the value of variables, generate output, process input, or respond to user mouse or keyboard actions.

Different types of statements are described in the following sections.
1.Assignment Statements

An assignment statement has the following form.

variable = expression;

This statement changes the value of the variable on the left side of the equals sign to the value of the expression on the right-hand side. The variable is often just specified by a variable name, but there are also expressions that specify variables. Java treats an assignment as both an expression and as a statement. As an expression, its value is the value assigned to the variable. This is done to allow multiple assignments in a single statement, such as

a = b = 5;
By treating b = 5 as an expression with value 5, Java makes sense of this statement, assigning the value 5 to both a and b.
Statements involving Messages

Messages are the fundamental means of communication between objects in a Java program. A message has the following form.

receiver.method-name(parameters)
Here,

  • receiver is an expression (often just a variable name) that specifies the object that should respond to the message.
  • method-name is the name of the method that the receiver should execute.
  • parameters is a comma-separated list of expressions that provide data that the receiver can use in its execution of the method.

The receiver can be omitted if it is the object that you are writing code for. That is, you do not need to specify the receiver for messages sent from an object to itself. Messages can be used in three ways to form statements. First, if the method specified by a message returns a value then the message can be used as the expression in an assignment statement.

variable = message;

For messages with methods that do not return values, a statement can also be formed by just terminating the message with a semicolon.

message;

This statement form can also be used when the method returns a value, although it is not usually a good idea to ignore a returned value.
Finally, if a message returns an object, then that object can be used directly as the receiver of a message. In an applet method, for Example, getContentPane() returns a container to which components can be added. This container is the receiver of the add() message in the following statement.

getContentPane().add(button);

Statement Blocks
In Java, any sequence of statements can be grouped together to function as a single statement by enclosing the sequence in braces. These groupings are called statement blocks. A statement block may also include variable declarations.
Statement blocks are used to define methods and to allow multiple statements in the control structures described in the following sections.

2.Control Statements

Normally, statements in a method or constructor are executed sequentially. Java also has control statements that allow repetitive execution of statements and conditional execution of statements. Java has the following types of control statements.

1.Conditional Execution and Selection

  • If Statements - conditional execution of a single statement
  • If-Else Statements - conditional selection among two statements
  • Switch Statements - conditional selection among several statements
  • Extended If-Else Statements - conditional selection among several statements

2.Repetition

  • While Loops - pretest loops
  • For Loops - pretest loops
  • Do-While Loops - posttest loops

3.Special Control Statements

  • Return Statements - return values from and terminate it
  • Continue Statements - skip the remaining statements in an iteration of a loop
  • Switch Statements - conditional selection among several statements
  • Break Statements - exit a loop or switch statement

1.Conditional Execution and Selection:

Java has three kinds of statements that permit execution of a nested statement based on the value of a boolean expression or selection among several statements based on the value of a boolean expression or a control variable. These statements are the if statement, the if-else statement, and the switch statement.

A.If Statements

The if statement has the following form.

if (boolean-expression) {
then-clause
}

Here,
boolean-expression is an expression that can be true or false. then-clause is a sequence of statements. If there is only one statement in the sequence then the surrounding braces may be omitted. The then-clause statements are executed only if the boolean-expression is true.


public class SimpleIfStatementExample {

public static void main(String[] args) {

/*
* If statement is used to execute an action if particular condition is true.
* Syntax of if statement is,
*
* if(<condition>)
* <statement>
*
* while <condition> is a boolean expression, and statement is a valid java
* statement which will be executed if <condition> is true. To use multiple
* statements, enclose them in a block.
*
*/

boolean blnStatus = true;

if(blnStatus)
System.out.println("Status is true");
}
}

Output would be

Status is true


public class Test {

public static void main(String args[]){
int x = 10;

if( x < 20 ){
System.out.print("This is if statement");
}
}
}

Output would be

This is if statement

B.If-Else Statement

The if-else statement has the following form

if (boolean-expression) {
then-clause
} else {
else-clause
}

Here,

  • boolean-expression is an expression that can be true or false.
  • then-clause and else-clause are sequences of statements. If there is only one statement in a sequence then the surrounding braces may be omitted. The then-clause statements are executed only if the boolean-expression is true. The else-clause statements are executed if the boolean-expression is false

We can take a look on a program which will display a message “Success” if a particular value is greater than 5. If this value is not greater than 5, it will display a message “Failure”. It then displays a message “Executed successfully” and complete its execution.


/*
* FileName : IfElseStatementDemo1.java
*/
public class IfElseStatementDemo1
{
public static void main(String args[])
{
//Declaring a variable "test" and initializing it with a value 10
int test=10;

//Checking if "test" is greater than 5
if(test>5)
{
//This block will be executed only if "test" is greater than 5
System.out.println("Success");
}
else
{
//This block will be executed only if "test" is not greater than 5
System.out.println("Failure");

}

//The if else blocks ends.
System.out.println("Executed successfully");
}
}

Output would be

This program outputs the message “Success” because the declared variable “test” has a value 10 which is greater than 5.

If the value of “test” was lesser than or equal to 5, the message “Failure” would have been displayed instead of “Success”.


public class Test {

public static void main(String args[]){
int x = 30;

if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}

Output would be

This is else statement

C.if–else-if ladder

The if–else-if ladder statement has the following form.

If(condition-1)
{
Statements which will be executed if condition-1 is true
}
else if (condition-2)
{
Statements which will be executed if condition-2 is true
}
.
.
.
else if (condition-n)
{
Statements which will be executed if condition-n is true
}
else
{
Statements which will be executed if none of the conditions in
condition-1, condition2,…condition-n are true.

}

Statements which will be executed always

As you can see in this if-else-if ladder, conditions are evaluated from top. First condition-1 will be evaluated and if this is true, the code inside the if block will be executed. If condition-1 is false, condition-2 will be evaluated.

If condition-2 is true, the code inside that else if block will be executed. If condition-2 is false, condition-3 will be evaluated. This will go on like this.

If none of the conditions are true, the code inside the else block will be executed.

Example:
We can take a look on a program which will

  • display a message “Hello” if a particular value is equal to 1.
  • display a message “Hi” if a particular value is equal to 2.
  • display a message “Good” if a particular value is equal to 3.
  • display a message “No Match Found” if none of the above conditions are matching.


/*
* FileName : IfElseIfLadderDemo1.java
*/
public class IfElseIfLadderDemo1
{
public static void main(String args[])
{
//Declaring a variable "test" and initializing it with a value 2
int test=2;

if(test==1)
{
//This block will be executed only if "test" is equal to 1
System.out.println("Hello");
}
else if(test==2)
{
//This block will be executed only if "test" is equal to 2
System.out.println("Hi");

}
else if(test==3)
{
//This block will be executed only if "test" is equal to 3
System.out.println("Good");
}
else
{
System.out.println("No Match Found");
}
}
}

Output would be

This program outputs the message “Hi” because the declared variable “test” has a value 2.
If the value of “test” was 1, the message “Hello” would have been displayed.
If the value of “test” was 3, the message “Good” would have been displayed
If the value of “test” was any other than 1, 2, 3, the message “No Match Found” would have been displayed.
Please change the value of the variable “test” accordingly and execute the program and see the different outputs.


public class Test {

public static void main(String args[]){
int x = 30;

if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}

Output would be

Value of X is 30

D.Switch Statements

The switch statement allows execution of different statements depending on the value of an expression. It has the following form.

switch (control-expression) {
case constant-expression-1:
statements-1
.
.
.
case constant-expression-n:
statements-n
default:
default-statements
}

Here,

  • control-expression control-expression is an expression of a simple type, such as int, char, or an enum type. It cannot have float or double type.
  • constant-expression-1 through constant-expression-n are expressions of a type that converts to the type of control-expression. The compiler must be able to evaluate these expressions to constant values.
  • statements-1 through statements-n are sequences of statements.

When the switch statement is executed, control-expression is evaluated. The resulting value is compared to the values of constant-expression-1 through constant-expression-n in order until a matching value is found. If a match is found in constant-expression-i then statements-i through statements-n and default-statements are executed, with switch statement execution terminated if a break statement is encountered. Normally, the last statement in each sequence is a break statement so that only one sequence is executed.

The default clause is optional. If it is present then the default-statements are executed whenever the value of control-expression does not match any of the constant-expression-i values.

Purpose of switch: select one of many possible statements to execute
The if statement allows you to select one of two sections of code to execute based on a boolean value (only two possible values). The switch statement allows you to choose from many statements based on an integer (including char) or enum value.

Syntax2

switch (expr) {
case c1:
statements // do these if expr == c1
break;
case c2:
statements // do these if expr == c2
break;
case c2:
case c3:
case c4: // Cases can simply fall thru.
statements // do these if expr == any of c's
break;
. . .
default:
statements // do these if expr != any above
}

Switch keywords
1.switch
The switch keyword is followed by a parenthesized integer expression, which is followed by the cases, all enclosed in braces.. The switch statement executes the case corresponding to the value of the expression. Normally the code in a case clause ends with a break statement, which exits the switch statement and continues with the statement following the switch. If there is no corresponding case value, the default clause is executed. If no case matched and there is no default clause, execution continues after the end of the switch statement.
2. case
The case keyword is followed by an integer constant and a colon. This begins the statements that are executed when the switch expression has that case value.
3. default
If no case value matches the switch expression value, execution continues at the default clause. This is the equivalent of the "else" for the switch statement. It is written after the last case be convention, and typically isn't followed by break because execution just continues out the bottom of switch if this is the last clause.
4. break
The break statement causes execution to exit to the statement after the end of the switch. If there is no break, execution flows thru into the next case. Flowing directly into the next case is almost always an error.

The following program, SwitchDemo, declares an int named month whose value represents a month out of the year. The program displays the name of the month, based on the value of month, using the switch statement.


class SwitchDemo {
public static void main(String[] args) {

int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}

Output would be

In this case, "August" is printed to standard output.

The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case.

2.Repetition:

Java has three kinds of loop statements: while loops, for loops, and do-while loops. Loop statements allow a nested statement to be executed repetitively. The nested statement can be a block statement, allowing repetition of a sequence of statements. When a loop is executed its nested statement can be executed any number of times. Each execution of the nested statement is called an iteration of the loop.

A. While Loops

The while loop is a pretest loop statement. It has the following form.

while (boolean-expression) {
nested-statements
}

Here,

  • boolean-expression boolean-expression is an expression that can be true or false.
  • nested-statementsnested-statements is a sequence of statements. If there is only one statement then the braces can be omitted

The boolean expression is tested before each iteration of the loop. The loop terminates when it is false.

The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program:


class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}

You can implement an infinite loop using the while statement as follows:

while (true){
// your code goes here
}

The Java programming language also provides a do-while statement, which can be expressed as follows:

do {
statement(s)
} while (expression);

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program:


public class Test {

public static void main(String args[]) {
int x = 10;

while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

Output would be

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

B. For Loops

The for loop is a pretest loop statement. It has the following form.

for (initialization; boolean-expression; increment) {
nested-statements
}

Here,

  • initialization is an expression (usually an assignment expression).
  • boolean-expressionboolean-expression is an expression that can be true or false.
  • increment is an expression.
  • nested-statements is a sequence of statements. If there is only one statement then the braces may be omitted.

When a for loop is executed the initialization expression is evaluted first. This expression is usually an assignment (for Example, i = 0) that sets the initial value of a loop control variable.

The boolean expression is tested before each iteration of the loop. The loop terminates when it is false. The boolean expression is frequently a comparison (for Example, i < 10).

At the end of each iteration, the increment expression is evaluated. The expression is often an expression that increments the control variable (for Example, i++).

When using this version of the for statement, keep in mind that:

  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output:


class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}

Output would be

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by the for statement, so it can be used in the termination and increment expressions as well. If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The names i, j, and k are often used to control for loops; declaring them within the initialization expression limits their life span and reduces errors

C.Do-While Loops

The do-while loop is a post-test loop statement. It has the following form.

do {
nested-statements
} while (boolean-expression);

Here,

  • nested-statements is a sequence of statements. If there is only one statement then the braces may be omitted.
  • boolean-expressionboolean-expression is an expression that can be true or false.
  • increment is an expression.

The boolean expression is tested after each iteration of the loop. The loop terminates when it is false.

Do while loop executes group of Java statements as long as the boolean condition evaluates to true.
It is possible that the statement block associated with While loop never get executed because While loop tests the boolean condition before executing the block of statements associated with it.
In Java programming, sometime it's necessary to execute the block of statements at least once before evaluating the boolean condition. Do while loop is similar to the While loop, but it evaluates the boolean condition after executing the block of the statement.

The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output:


/*
Do While loop Example
This Java Example shows how to use do while loop to iterate in Java program.
*/

public class DoWhileExample {

public static void main(String[] args) {

/*
* Do while loop executes statment until certain condition become false.
* Syntax of do while loop is
*
* do
* <loop body>
* while(<condition>);
*
* where <condition> is a boolean expression.
*
* Please not that the condition is evaluated after executing the loop body.
* So loop will be executed at least once even if the condition is false.
*/

int i =0;

do
{
System.out.println("i is : " + i);
i++;

}while(i < 5);

}
}

Output would be

i is : 0
i is : 1
i is : 2
i is : 3
i is : 4

E. For-each Loop

The basic for loop was extended in Java 5 to make iteration over arrays and other collections more convenient. This newer for statement is called the enhanced for or for-each (because it is called this in other programming languages). I've also heard it called the for-in loop.
Use it in preference to the standard for loop if applicable (see last section below) because it's much more readable.
Seriesof values . The for-each loop is used to access each successive value in a collection of values.
Arrays and Collections. It's commonly used to iterate over an array or a Collections class (eg, ArrayList).
Iterable. It can also iterate over anything that implements the Iterable interface (must define iterator() method). Many of the Collections classes (eg, ArrayList) implement Iterable, which makes the for-each loop very useful. You can also implement Iterable for your own data structures.

General Form The for-each and equivalent for statements have these forms. The two basic equivalent forms are given, depending one whether it is an array or an Iterable that is being traversed. In both cases an extra variable is required, an index for the array and an iterator for the collection.

For-each loopEquivalent for loop
for (type var : arr) {
    body-of-loop
}
for (int i = 0; i < arr.length; i++) { 
    type var = arr[i];
    body-of-loop
}
for (type var : coll) {
    body-of-loop
}
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
    type var = iter.next();
    body-of-loop
}

Adding all elements of an array
Here is a loop written as both a for-each loop and a basic for loop.

double[] ar = {1.2, 3.0, 0.8};
int sum = 0;
for (double d : ar) { // d gets successively each value in ar.
sum += d;
}

And here is the same loop using the basic for. It requires an extra iteration variable.

double[] ar = {1.2, 3.0, 0.8};
int sum = 0;
for (int i = 0; i < ar.length; i++) { // i indexes each element successively.
sum += ar[i];
}

Where the for-each is appropriate
Altho the enhanced for loop can make code much clearer, it can't be used in some common situations.

  • Only access. Elements can not be assigned to, eg, not to increment each element in a collection.
  • Only single structure. It's not possible to traverse two structures at once, eg, to compare two arrays.
  • Only single element. Use only for single element access, eg, not to compare successive elements.
  • Only forward. It's possible to iterate only forward by single steps.
  • At least Java 5. Don't use it if you need compatibility with versions before Java 5.

3. Special Control Statements
A. Return Statements

The return statement is used in the definition of a method to set its returned value and to terminate execution of the method. It has two forms. Methods with returned type void use the following form.
return;
Methods with non-void returned type use the following form
return expression;

Here,

  • expression is an expression that yields the desired return value. This value must be convertible to the return type declared for the method.


import java.util.Scanner;

class group{
public static void main(String arng[]){
Scanner data = new Scanner(System.in);
int num1, num2;
System.out.println("Enter 1st number");
num1 = data.nextInt();
System.out.println("Enter 2nd number");
num2 = data.nextInt();

total(num1,num2);

}

public static void total(int numx, int numy){
int sum=0;
sum=numx+numy;
if(sum==0)
return;
System.out.println("Sum of 2 number:"+sum);

}
}

Output would be

Here total method is terminated when sum is zero.

if(sum=0) is necessary in above Example because java compiler shows error "unreachable code" to avoid this error i used if condition to demonstration return statement.

B.Continue Statements

The continue statement is used in while loop, for loop, or do-while loop to terminate an iteration of the loop. A continue statement has the following form.

{
//loop body
-----------
-----------
-----------
-----------

continue;

-----------
-----------
}

After a continue statement is executed in a for loop, its increment and boolean expression are evaluated. If the boolean expression is true then the nested statements are executed again.

The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. The following program, ContinueDemo , steps through a String, counting the occurences of the letter "p". If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a "p", the program increments the letter count.


class ContinueDemo {
public static void main(String[] args) {

String searchMe = "peter piper picked a peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;

for (int i = 0; i < max; i++) {
//interested only in p's
if (searchMe.charAt(i) != 'p')
continue;

//process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}

Output would be

Found 9 p's in the string.

C.Break Statements

The break statement is used in loop (for, while, and do-while) statements and switch statements to terminate execution of the statement. A break statement has the following form.
break;

After a break statement is executed, execution proceeds to the statement that follows the enclosing loop or switch statement.
[an error occurred while processing this directive]



Related Videos