It really depends on what you need to do. If you need to do one thing after another, you will use a sequential structure. If you need to do different things based on a decision, you will use a selection or conditional structure. Next week we will add another structure as well that helps us to repeat things. Implementation "patterns" can help us understand what's required in a particular situation.
if ( y == 8 )and
if ( x == 5 )
System.out.println( "1" );
else
System.out.println( "2" );
System.out.println( "3" );
System.out.println( "4" );
if ( y == 8 && x == 5 )
System.out.println( "1" );
else
System.out.println( "2" );
System.out.println( "3" );
System.out.println( "4" );
No, try tracing what happens if y is 7 and x is 4. (For the first if, the output is 3 followed by 4 on the next line. In the second, it is 2 and 3 and 4 all on separate lines!) This is a good example of why both the use of indentation and the use of {}'s are helpful to those of us humans trying to read the code. If written according to our style standards, the two pieces of code would be written as follows:
if ( y == 8 ) {and
if ( x == 5 ) {
System.out.println( "1" );
} else {
System.out.println( "2" );
}
System.out.println( "3" );
System.out.println( "4" );
if ( y == 8 && x == 5 ) {
System.out.println( "1" );
} else {
System.out.println( "2" );
}
System.out.println( "3" );
System.out.println( "4" );
It doesn't compare anything, it's an assignment. Unlike C or C++, Java requires that the expression in an "if" statement be a boolean_expression. It will complain if we try to compile an if statement that incorrectly uses a = instead of ==, UNLESS the assignment is to a boolean variable. For example, see code/CompareWrong.java. If you download it and compile it, you will receive the following error message:
Compare.java:34: incompatible types
found : int
required: boolean
if ( x = y ) {
^
1 error
No, but they are different constructs for making selections of the path your program is to follow. And, you can do many of the same things with each. They differ substantially though in syntax and symantics!
Yes, the switch statement can work on multiple cases. In ALL cases it stops executing when it reaches the first break statement after the matching case.
For example,
char grade;switch ( grade ) {
case 'A':
System.out.println( "A" );
break;
case 'B':
System.out.println( "B" );
break;
case 'C':
case 'D':
System.out.println( "Other passing grade" );
break;
case 'F':
System.out.println( "Failing" );
break;
default:
System.out.println( "Invalid grade" );
break;
}
becomes
char grade;if ( grade == 'A' ) {
System.out.println( "A" );
} else if ( grade == 'B') {
System.out.println( "B" );
} else if ( grade == 'C' || grade == 'D' ) {
System.out.println( "Other passing grade" );
} else if ( grade == 'F') {
System.out.println( "Failing" );
} else {
System.out.println( "Invalid grade" );
}