Operators and Control Structures

2.1 Assignment aerators
The following code assigns the value 15 to the variable x.
int x;
x = 15;
In Java, a single equal's sign is the assignment operator. Consider we append the statement with.
x=x+15;
The new value of x will now be 20. First, the addition on the right is done. Then, the result is assigned to the variable on the left. In Java, you can also use the following shortcut to arrive at the same value:
int x= 15;
x;= x+5;
2.2 Increment/ Decrement operators
There is one addition statement in java that is so common, it gets its own operator. It means, simply, "Add/Subtract one to the variable." And you can do pre-increment/decrement, or a post-increment/decrement.
per
++x; x++;
post
--x; x--;
If each of these statements is on a line by itself, there is no difference in the effect of doing a pre- or post-increment. However, if the variable that is having the pre-or post-increment applied to it is used within another statement, your choice of pre-or post-increment can alter your results which will made clear using this example.
// prepostIncrement-java
public class prepostIncrement
{
public static void main (string args [ ] )
{int x= 0;
system.out.print1n (" baseline, x = " + x);
system.out.print1n "/n pre-increment = ++x ="+ ++x );
system.out.print1n ("/n After increment, x = " + x) ;
x = 0;
system.out.print1n ("/n 2nd Baseline, x = " + x);
system.out.print1n ("/n post-increment = x++ = " + x++);
system.out.print1n ("/n After increment, x = " + x);
system. exit (0) ;
}
}
Baseline, x = 0
pre- increment = ++x = 1
After increment, x = 1
2nd baseline, x = 0
post- increment, = x++ = 0
After increment, x = 1
2.3 Logical operators
So far, all of the conditions we have tested were simple. It is possible to construct complex conditions using the Java Logical Operators, which again- were inherited form C/C++.
&& Logical And
.. Logical OR
! Logical Not
2.3.1 Logical AND
if ( gender == 'F' && age >= 65 )
Condition is true if both halves are true. Java will short-circuit the process-skipping the 2nd half of the expression- if the first half is false.
2.3.2 Logical OR
if ( gender == 'F' .. age >= 65 )
Entire condition is true if either half is true.
2.3.3 Logical NOT
if ( ! (age <= 65) ) Negates the expression- not many opportunities to use. 2.3.4 Logical Boolean AND if ( gender == 'F' & ++age >= 65 )
A Logical Boolean AND [ &] works exactly like a Logical AND [ && ] with one exception. It will always check both halves of the equation, even if the first is false.
2.3.5 Logical Boolean OR
if ( gender == 'F' ^ age >= 65 )
This Logical exclusive Boolean OR is true only if one side is true and the other false. If both sides are true, the entire expression is false.
2.4 Control Structures
2.4.1 The "if" statement
This control statement is used for decision making in any java application. The if in Java exactly mirrors C/ C++, and it has three variants:
if ( expression )
statement:
if ( expression )
statement;
else
statement;
if ( expression )
statement;
else if ( expression )
statement;
else
statement;
The "expression" must be something that uses the comparison operators and resolves to either true of false. The statement is executed if the expression is true. Only one statement can be made conditional without brackets. If you wish to conditionally execute more than one statement, you use brackets to create a block. If the "expression" is not true, the else branch executes.
2.4.2 While
It's used for repetition in Java. The syntax of this statement is"
while ( expression )
statement;
Alternatively, you can write it as:
do
{
statements;
}
while ( expression ) ;
Let's see these in real examples.
// selectionTest.java to try the ternary operator import javax.swing.*;
public class selectionTest
{
public static void main ( string args [ ] )
{
int b, s;
string big, email, out;
big = JOPtionpane.sgowInputDialog ( "small Number" ) ;
b = integer.parseInt ( big ) ;
s = Integer.parseInt ( small ) ;
out = (b > s ? "Big was larger": "small was larger"); JoptionPane. INFORMATION_MESSAGE ;
system.exit (0);
}
}
// DowhileTest.java to try while statement
import javax.swing.*;
public class DowhileTest
Public static void main ( string args [ ] )
{ int b = 2, s = 1;
string big, small, out = "Big is still Bigger";
while (b > s )
{
JoptionPane.showMessageDialog ( null, out, "Results",
big = JoptionPane.showInputDialog ( "Big Number" );
small = JoptionPane.showInputDiaglog ( "Small Number" );
b = Integer.ParseInt (big);
s = Integer.parseInt (small);
}
system. exit (0) ;
}
}
// DoUntilTest.java to try the do_while statement
import javax.swing.*;
public class DountiTest
{
public static void main ( string args [ ] )
{
int b = 2, s= 1; // preload variables.
string big, small, out = "Big is still Bigger"
do
{
JoptionPane.showMessageDialog (null, out, "Results"; JoptioPane.INFORMATION_MESSAGE)
big = JoptionPane.showInputDialog ( "Big Number" ) ;
small = JoptionPane,showInputDialog ( "small Number") :
b = Integer.parseInt (big):
s = Integer.parseInt (small);
}
while ( b> s ) ;
system. exit ( 0 )'
}
}
2.4.3 The for loop
A common structure called a for loop is specially designed to manage counter – controlled looping.
for ( int x = 1; x < 10; x++ )
An example program implementing the same:
// ForCounter.java
Import java.awt.Graphics;
import javax.swing.JApplet;
public class ForCounter extends JApplet
{
public void paint ( Graphics g )
{
for ( int counter=1 ; counter <= 10 ; counter ++ )
{
g. drawLine ( 10,10, 250, counter* 10 ) ;
}
}
}
When appropriate, for is quick and easy. The for loop is a do-white. It tests the condition before it executes the loop for the first time.
note: since the variable int counter was declared within for, it vanishes after the for is executed. All three sections are optional.
If you omit the condition, java assumes the statement is true, and you have an infinite loop.
for ( in x = 1;; x++ )
You can omit the initialization if you have initialized the control variable someplace else.
int x = 1;
for (; x < 10; x++ )
You can omit the increment of variable if you are doing within the body of the loop.
for ( int x = 1; x < 10; )
{
other stuff
x++;
}
Let's take another example. this time a more compresensive one to explain the use of the for loop.
// calculate Compound Interest
import javax.swing.JoptionPane;
import java .test.Declma1From;
import javax.swing.JtextArea;
public static vold main ( string arge [ ] )
{
double amount. pricipics = 1000.0, rate = 0.05;
Dec1Format twoDig = new Dec1malFormat ( "0.00" ) '
Ktextarea output = new JextArea ( 11, 20 );
output, append ( "years/amount on deposited \n" ) '
for ( int year = 1; year <= 10; years++ )
{
amount = principle * Math.pow ( 1.0 + rate, year );
output, append ( year + "/t" twoDig.format (amount) + "/n") ;
} // end of for
JoptionPane.showMessgeDialog ( null, output, "compound Interest", JOptionPane.INFORMATION_MESSAGE);
system.exit (0) ;
} // end of main ( )
} // end of class Interest
Multiple-selection structure
Once you start nesting many 'if's, it becomes a nuisance.Java-like C and C++ before it –provides the switch structure, which provides multiple selections. Unfortunately-in contrast to visual Basic's Select Case and even COBOL's Evauate- you cannot use any of type of argument in the switch statement other than an integer.
int x = 0;
switch ( x )
{
case 1:
do stuff;
break;
case 2:
do stuff;
break;
case 55:
do stuff;
break;
case 102:
case299:
do stuff okay for both;
break;
default:
if nothing else do this stuff;
break;
}
The integer expression x is evaluated. If x contains a 1, then the case branch is performed. Notice the 'break;' statement. This is required. Without it, every line after the match will be executed until it reaches a break:
The expression within the switch (expression) section must evaluate to an integer. Actually, the expression can evaluate to any of these types (all numeric but long):
• byte
• short
• int
• char
but they will be reduced to an integer and that value will be used in the comparison. Also, the expression after each case statement can only be a constant integral expression or any combination of character constants and integer constants that evaluate to a constant integer value.
The default: is optional. If you omit the default choice, then it is possible for none of your choices to find a match and that nothing will be executed. If you omit the break: then the code for every choice after that- except the default!-will be executed.
2.4.5 break; and continue;
Both of these statements alter the flow of control. The break statement can be executed in a:
• while
• do/while
• for
• switch
It causes the immediate exit from the structure. After a break exits the "structure"-whatever that is- execution resumes with the first statement following the structure. If you have nested structures-be they a while, do/ while/for or switch-the break will only exit the innermost nesting. It will not exit you out of all nests. To do that, you need another break. However, there is variant of break called a labeled break-but this is similar to a go to and is frowned upon.
The continue statement, when used in a while or do/while or a for, skips the remaining code in the structure and returns up to the condition. If the condition permits it, the next iteration of the loop is permitted to continue so, they continue is "temporary break." It is only used in iterative structures, such as the while, do/while and for.
The "Labeled" continue and break statements send execution to the label to continue execution. Note: using the labeled break and continue is bad code. Avoid using them! We still give you an example just in case its absolutely required.
stop:
for (row = 1; row<= 10; row++)
{
for (col=1; col <=5' cod++)
{
if (row == 5)
break stop; // jump to stop block
}
output += "* ";
}
output += "/n";
}