Java Beginner: Lesson 4

If condition


In order to take decisions in java we use the if condition. The if condition can be applied on boolean expressions only, so we can ask if an expression is true or false.

In the previos lesson, lesson 3, the if condition is used several times in order to determine which operation the user has given as input:

Example code:
if(operation.equalsIgnoreCase("+")){
result = nr1+nr2;
}else if(operation.equalsIgnoreCase("-")){
result = nr1-nr2;
}else if(operation.equalsIgnoreCase("*")){
result = nr1*nr2;
}else if(operation.equalsIgnoreCase("/")){
if(nr2!=0){
result = nr1/nr2;
}else{
System.out.println("Can not devide by 0\n");
return;
}
}

operation variable in the example code above is a String variable. In the string class is declared the public method equalsIgnoreCase(String anotherString) which is a method which returns a boolean value. In the NetBeans IDE if we keep pressed the CTRL key and pres the right button on the mouse we can go to the String.java file where the String class is declared, where we can see the declaration of the equalsIgnoreCase(String anotherString) method as shown in the figure 1 bellow:


Figure 1: equalsIgnoreCase(String anotherString) of String class


Being that all the green expression shown in the figure 2 bellow returns a boolean value it means that we are testing a boolean value.


Figure 2: boolean expression

The logic in the if condition shown in the figure 2 bellow is:
if the String variable operation is equals to the + character execute the code between the curly brackets, otherwise skip the code within the curly brackets.

The example code shown above would be equivalent to the example code bellow.

Example code:
boolean addOperation = operation.equalsIgnoreCase("+");
boolean subtractOperation = operation.equalsIgnoreCase("-");
boolean multiplyOperaiton = operation.equalsIgnoreCase("*");
boolean divideOperation = operation.equalsIgnoreCase("/");
if( addOperation ){
result = nr1+nr2;
}else if( subtractOperation ){
result = nr1-nr2;
}else if( multiplyOperaiton ){
result = nr1*nr2;
}else if( divideOperation ){
if(nr2!=0){
result = nr1/nr2;
}else{
System.out.println("Can not devide by 0\n");
return;
}
}

As can be seen from the example above, we can store the result returned by the equalsIgnoreCase(String anotherString) method into boolean variables, being that it result is a boolean value, than use that variable in the other part of the code. This solution would be convenient in case that the value returned by the method would be needed to be used in multiple parts of the code.

(please report broken link in the comment)

Comments

Popular posts from this blog

Free host and domain

C++ Beginner: Lesson 3 - Simple calculator

C++ Beginner: Lesson 4 - Tic Tac Toe game