• No results found

IMP: In general programming all of the above loops is used together and all the above loops can be nested also

In document Java Notes1 (Page 49-59)

public static void main(String[] args) {

int a = 0;

while (a < 10) {

System.out.println(a);

a++;

} } }

The do – while Loop

The do – while loop is similar to the while loop and the only difference is that the boolean condition is after the body of the loop, which means that even if the condition is false, the loop will be executed atleast one. In programming, this loop is very important where we want a particular statement to execute atleast once. The syntax for the do loop is;

do {

statement;

}

while (boolean condition)

Each iteration of the loop first executes the body and then evaluates the conditional expression. If this expression is true, then it will execute the body again and then checks for the condition and this goes on till the condition becomes false.

IMP: In general programming all of the above loops is used together and all the above loops can be nested also.

The main difference between the while and do-while loop is that incase the condition is false, the do-while loop will be executed atleast once, whereas the while loop will not be executed at all.

Code

class DoWhile {

public static void main(String[] args) {

do {

System.out.println("Hello");

}

while (false);

} }

Output Hello

Selection statements in Java

Java supports if – else and switch as its selection statements and we will discuss both of them in this section

if Statement

The if statement is used to route programs execution to different paths depending on a particular condition and the syntax for the same is;

if (condition) {

Statement;

} else {

Statement;

}

As in the earlier cases, the condition checking the flow of control is a boolean condition and if the condition is true, then the if part body will be executed or the else part of the body will be executed.

Example int a ; int b ; if (a>b) {

int c = a;

} else {

int c = b;

}

In the above example we want the value of int c to be the higher value amount a and b and this we do not know and hence we will use the if loop and if (a>b) then the value of int c will be the value of a and if int b is higher then the value of int c will be the value of int b as stated in the else part of the body.

Nested ifs

A nested if is an if statement that is the target of another if or else. Nested ifs are very common in programming and when you nest a if, the important point to remember is that an else statement always refer to the nearest if statement that is within the same block as the else.

It is very important that you use block of codes, when using the nested ifs or otherwise you will find a result other than what you were expecting.

if-else-if ladder

The if-else-if ladder syntax looks like this if (condition)

{

Statement;

}

else if (condition) {

Statement;

}

else if (condition) {

Statement;

} else {

Statement;

}

The if condition in the first if will be considered and like the normal if-else will not go to the else part, but it will check the else if condition and like this it goes down the ladder. After the last else if is encountered and then also the condition is not true then the else statement at the end of the ladder will be executed.

Remember, if the last else statement is not there and if all the else if condition returns false then nothing will be executed.

switch Statement

If you need to make a choice between multiple alternative execution paths and the choice can be based on a non-boolean value, then you should use the switch () construct as we cannot use the if-else loop. The syntax is as under:

switch (expression) {

case value1:

{

Statement;

}

case value2:

{

Statement;

}

case value3:

{

Statement;

IMP: It is very important to note here that the expression must be of type byte, short, int or char and each of the values in the cases (e.g. case value1 ....) must be type compatible with the expression and each case should be a unique (e.g. it should not be a constant or a variable).

Duplicate case values are also not allowed.

IMP: There is a fundamental difference between the switch in C++ and java wherein we need to mandatorily use the break statement to jump out once the case have been matched, otherwise the control will enter all the cases and then reach the end of the loop. To understand the meaning of the above statement, please have a look at the following code.

Code

class Test17 {

public static void main(String[] args) {

System.out.println("Zero");

}

case 1:

{

System.out.println("One");

}

case 2:

{

System.out.println("Two");

}

default:

{

System.out.println("Default");

}

Default Two Default

The above output is because of the lack of break statements after the cases and hence once the case is matched, the code enters all the subsequent cases and printout out the same (including the default). To ensure only one case is matched and the code to exit the switch block, we will see the following code where there is a break statement after the cases.

Code

class Test17 {

public static void main(String[] args) {

System.out.println("Zero");

}

break;

case 1:

{

System.out.println("One");

}

break;

case 2:

{

System.out.println("Two");

}

break;

default:

{

System.out.println("Default");

}

We will see later on what is the significance of the break keyword.

The switch starts off with a expression and the value is compared with each of the literal values in the case statements and if a match is found then the body of that case value is executed and if none of the case values are matched the default block is always executed. The default is optional here and if no matching case if found and there is no default then nothing will be executed.

One can use the break statement inside a switch to terminate a statement sequence. When a break statement is encountered, the execution branches to the first line of code that follows the entire switch statement.

The switch statement differs from the other loops in that the switch can only test for equality, where as the other loops test for boolean condition. That is the switch looks only for a match between the value of the expression and one in its case and has nothing to do with the boolean conditions.

Jump statements in Java

The three jump statements in java is the break statement, the continue statement and the return statement. The java’s jump statements help in transferring control to another part of the program.

Using break statements

Break can be used for 3 reasons

a) breaking out of the switch statements b) breaking out of a loop

c) Labeled break to enable transfer to a particular point in the code.

We have seen how to break out of a switch statement in the earlier code.

Using Break to exit out of a loop

We can use break to force immediate termination of a loop and thereby bypassing the conditional expression and any remaining code in the body of the loop. When break statement is encountered inside a loop, the loop is terminated and the program control resumes at the next statement following the loop. Let’s see a example

Code class Test {

public static void main(String args[]) {

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

if (i==10) {

break;

}

System.out.println(“The value of loop is “ + i);

}

System.out.println(“ The loop is complete”);

} }

Output: The above program is to print the numbers from one to hundred, but we are having a if condition which states that if i is equal to 10, then it should break out of the loop and then it will print the statement that loop is complete.

The above program generates numbers till “The value of i is 9” and then will exit out of the loop and then the next statement that “The loop is complete” will be printed out. The following points are also important regarding the break statement:

a) The break statement is used to exit out of infinite loops.

b) When used inside nested loops, the break statement will come out of the innermost loop and the execution of the outer loops will continue.

Using Labeled Break

Java also makes a labeled break available to you, by which you can exit out of any block with the respective block name. It is not necessary that it have to be a loop or switch. The labeled break enables you to break out to the statement following an enclosing block that has a label regardless of how many levels there are. You might have nested blocks and you can exit out of any nested block or blocks by using the respective block name (label) and the only important point here is that you will have to name the block with the name. For Example

Block 1

break Block 2 (here i can break out of any block, either 3,2 or 1) }

} }

The break statement inside block 3, tells to break out of block 2 and hence the point of execution will be switched here and any statement after the break will not be executed.

} Code

class Test19 {

public static void main(String[] args) {

one:{

Two:{

Three:{

System.out.println("Before Break");

if (true) {

break Two;

}

System.out.println("After Break");

}

System.out.println("After Three");

}

System.out.println("After Two");

}

System.out.println("After One");

} // end of main } // end of class

Output: The output would be Before Break

After Two After One

This is because; any statement after the break within a block of codes is never executed and we are specifically telling the compiler to break out of the block named as Two and the cursor would be positioned outside the block Two and then all the statements would be executed.

Points to remember

a) Whenever we are having labeled block of codes, and we want to break outside, we always need to give the block name from which to break and a simple break statement would not work. Let us remove the block Two from the break and it would throw the following exception.

Test19.java:11: break outside switch or loop

break ; ^

1 error

b) We need to put the break inside the if (true) block or otherwise the following error would be generated. (comment the if block and just give break Two; inside the block Three)

Test19.java:13: unreachable statement

System.out.println("After Break");

^ 1 error

Continue Statement

Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop, but stop processing the remainder of the code in its body for this particular iteration.

For example, Incase we need to print out the values from 1 to 10 in a for loop but print only the odd numbers, we will be using the continue statement.

Code class Test20 {

public static void main(String[] args) {

for(int i =1 ; i <= 10 ; i++)

{

if (i % 2 == 0 ) {

continue;

}

System.out.println(i);

} } }

Output 1 3 5 7 9

In the above example we are checking in the if loop incase the remainder is equal to 0 to go to the next iteration and not complete the block of the for loop. This will ensure that it does not print out the System.out.println() statement.

The continue statement can appear anywhere within a block of loop statements.

New Keyword

We have already seen the use of the new keyword earlier, when we created a instance of a class and also we used the same in arrays. Now let us see in depth what does the new keyword means and what it does.

If we have to create an object for a particular class, the same can be done with the help of a new keyword. For example

class Test {

int a;

int b;

double c;

}

The above class is just a template for any object creation and a new object is created with the help of the following syntax:

Test a = new Test();

Here a is just a handle for the Test and is an instance of Test. When you create an object of class Test, it will have its own copy of the instance variables defined by the class. Thus every Test object will have its own copies of int a, int b and double c. Over here it is important to note that a is a variable that refer to an object.

The following examples create new instances of the classes String, Random and store those new instances in variables of the appropriate types:

String str = new String ();

Random r = new Random();

The parentheses are important; don't leave them off. The parentheses can be empty (as in these examples), in which case the most simple, basic object is created; or the parentheses can contain arguments that determine the initial values of instance variables or other initial qualities of that object:

Date dt = new Date (90, 4, 1, 4, 30);

Point pt = new Point (0,0);

The number and type of arguments you can use inside the parentheses with new are defined by the class itself using a special method called a constructor (you'll learn more about constructors later). If you try and create a new instance of a class with the wrong number or type of arguments (or if you give it no arguments and it needs some), then you'll get an error when you try to compile your Java program.

Memory allocation and layout

When variables of any primitive type - that is boolean, int, etc - are declared, the memory space is allocated as part of the operation. The declaration of a variable using a non-primitive type – that is an object does not allocate space for the object.

It is the new keyword that implies allocation and initialization of storage.

Getting Values

To get to the value of an instance variable, you use an expression in what's called dot notation.

With dot notation, the reference to an instance or class variable has two parts: the object on the left side of the dot and the variable on the right side of the dot.

IMP: Dot notation is an expression used to get at instance variables and methods inside a given object

For example, if you have an object assigned to the variable myObject, and that object has a variable called var, you refer to that variable's value like this:

myObject.var;

This form for accessing variables is an expression (it returns a value), and both sides of the dot can also be expressions.

This means that you can nest instance variable access. If that var instance variable itself holds an object and that object has its own instance variable called state, you could refer to it like this:

myObject.var.state;

Dot expressions are evaluated left to right, so you start with myObject's variable var, which points to another object with the variable state. You end up with the value of that state variable after the entire expression is done evaluating.

Changing Values

Assigning a value to that variable is equally easy-just tack an assignment operator on the right side of the expression:

myObject.var.state = true;

Constructor

As already stated the new keyword dynamically allocated memory for an object. We can create an object of a class with the new keyword and the class name is followed by parentheses specifies the constructor for the class.

Constructor’s basic purpose is to initialize the class variables of a class when an object of the class is created. Most of the real world classes define their own constructors and incase there is no explicit constructor defined in a class, java provided its own constructor.

A constructor always has the same name as the class in which it is defined, has no return type specified, and must not include a return statement. You can always specify a constructor with any parameters as the arguments and anything in the body, which will be guaranteed to be initialized when we use the new keyword. A default constructor has nothing in its body and has no arguments in it.

The constructor is an unusual type of method because it has no return value. This is

In document Java Notes1 (Page 49-59)