710 likes | 747 Views
Basic Java Syntax. The java language will be described by working through its features: Variable types and expressions. Selection and iteration. Classes. Exceptions. Small sample programs will be provided to illustrate how each feature is used. if if ( boolean_expression ) {
E N D
Basic Java Syntax • The java language will be described by working through its features: • Variable types and expressions. • Selection and iteration. • Classes. • Exceptions. • Small sample programs will be provided to illustrate how each feature is used. Control Statements
if if ( boolean_expression ) { statement(s); } else { statement(s); } while while ( boolean_expression ) { statement(s); } do…while do { statement1; … statementN; } while ( boolean_expression ); switch switch ( switch_expr ) { case item_1: statement1; statement2; … break; case item_2: statement(s); … break; … default: statement(s); … break; } for for ( expression1; expression2; expression3 ) { statement(s); } Selection and Repetition Control Statements
Relational Operators • Relational operators are used to compare two numeric values and create a boolean result. • The result is dependent upon the relationship between the two operators. • Relational operators are evaluated after all arithmetic operators. Control Statements
Relational Operators Control Statements
Relational Operators 4 > 6 7 + 3 / 2 == 5 + 5 / 2 Assume a = 4 and x = 9, a <= x. How are you going to check it? Control Statements
Logical Operators • Logical Operators are used to compare boolean values and create a boolean result. • Logical operators are usually used to compare the results of relational operators. • Logical operators are evaluated after all relational operators. • Logical operators are && (logical And), & (bitwise And), || (logical Or), | (bitwise Or), ^ (logical or bitwise Exclusive Or), and ! (logical Not). Control Statements
Logical Operators • && (logical And): Expression1 Expression2 Expression1 && Expression2 True True True True False False False True False False False False Control Statements
Logical Operators • || (logical Or): Expression1 Expression2 Expression1 || Expression2 True True True True False True False True True False False False Control Statements
Logical Operators • && vs. & and || vs. | • Both && and || will only evaluate the expressions until it knows a result while the & and | operators will evaluate all the expressions before they return the result. • a && b will evaluate true or false • a & b will evaluate: 10010101 a b 10011101 a & b 10010101 Control Statements
Logical Operators • ^ (logical Exclusive Or): Expression1 Expression2 Expression1 ^ Expression2 True True False True False True False True True False False False Control Statements
Logical Operators • ! (logical Not): Expression1 ! Expression1 True False False True Control Statements
Logical Operators • ( 4 >= 7 ) && ( 3 + 4 == 7 ) • ( 4 >= 7 ) && ( 3 + 4 == 7 ) || ( 4 < 7 ) • ( 4 >= 7 ) && ( 3 + 4 == 7 ) || ( 4 < 7 ) && true Control Statements
Precedence and Operators Highest Lowest Control Statements
Control Structures • Control structures are used to organize actions (statements). • Examples: • Sequence Structure • Selection Structure • Repetition Structure Control Statements
Statement • The statement is the main building block from which code sequences are constructed. • Statements are executed in the order listed and are always terminated by a semicolon. Statement1; Statement2; Statement3; … StatementN; Control Statements
public static void main( String[] args ) { MainWindow mainWindow = new MainWindow; OutputBox outputBox = new OutputBox( mainWindow ); outputBox.printLine( "Welcome to " ); outputBox.printLine( "Java Programming!" ); } • Sequence • Selection • Repetition Sequence Structures MainWindow mainWindow = new MainWindow(); OutputBox outputBox = new OutputBox(mainwindow); outputBox.printLine("Welcome to" ); outputBox.printLine("Java Programming!" ); Control Statements
Sequence • Selection • Repetition Selection Structures • Selection Structures allow you to write code that will select and execute specific code statements instead of other code statements. Control Statements
Sequence • Selection • Repetition The ifand if/else Selection Structure • Basic syntax: • Note you can layout code in any way you want. if ( booleanExpression ) { statement(s); } or if ( booleanExpression ) { statement(s); } else { statement(s); } Control Statements
Sequence • Selection • Repetition if Selection Structure • If the booleanExpression is true then the statement is executed. • If the booleanExpression is false then the statement is skipped and the next statement in the sequence is executed. if ( booleanExpression ) { statement(s); } Control Statements
if ( hungry == true ) { System.out.println( "Find some food" ); } • Sequence • Selection • Repetition if Selection Structure System.out.println ( "Find some food" ); True hungry == true False Control Statements
Sequence • Selection • Repetition if/else Selection Structure • The if/else statement allows you to write code that executes one statement if the boolean_expression is true and different statement if the boolean_expression is false. if (boolean_expression) { statement 1; } else { statement 2; } Control Statements
if ( hungry == true ) { System.out.println( "Find some food" ); } else { System.out.println( "Get more work done" ); } • Sequence • Selection • Repetition if/else Selection Structure System.out.println("Get more work done" ); System.out.println("Find some food" ); True False Hungry == true Control Statements
Sequence • Selection • Repetition Example import java.util.*; public class Morning { public static void main( String args[] ) { Calendar rightNow = Calendar.getInstance(); if ( rightNow.get( Calendar.AM_PM ) == Calendar.AM ){ System.out.println( "Good morning..." ); } else { System.out.println( "Good afternoon..." ); } } } Control Statements
Sequence • Selection • Repetition ifSelection Structure • Let’s create the statements for the following problem: We want to categorize grades such that we will print out the corresponding letter grade. • < 60 = F • 60 – 69 = D • 70 - 79 = C • 80 - 89 = B • >= 90 = A. if(grade<60) { System.out.println(“F”); } if((grade>59)&&(grade<70)) { System.out.println(“D”); } if ((grade>69)&&(grade<80)) { System.out.println(“C”); } if ((grade>79)&&(grade<90)) { System.out.println(“B”); } if (grade>89) { System.out.println(“A”); } Control Statements
Sequence • Selection • Repetition if/else Selection Structure • The statement inside an if/else structure may be another if/else statement. In Java it looks like: OR • if (boolean_expression_1) { • statement1; • } else { • if (boolean_expression_2) { • statement2; • } else { • statement 3; • } • } • if (boolean_expression_1) { • statement1; • } elseif (boolean_expression_2) { • statement2; • } else { • statement3; • } Control Statements
Sequence • Selection • Repetition if/elseSelection Structure • Let’s look at our grade program again and rewrite it using the if/else structure. if(grade<60) { System.out.println(“F”); } if((grade>59)&&(grade<70)) { System.out.println(“D”); } if ((grade>69)&&(grade<80)) { System.out.println(“C”); } if ((grade>79)&&(grade<90)) { System.out.println(“B”); } if (grade>89) { System.out.println(“A”); } if (grade<60) { System.out.println(“F”); } else if ((grade>59)&&(grade<70)) { System.out.println(“D”); } else if ((grade>69)&&(grade<80)) { System.out.println(“C”); } else if ((grade>79)&&(grade<90)) { System.out.println(“B”); } else { // grade>89 System.out.println(“A”); } Control Statements
Sequence • Selection • Repetition Nesting if Statements • Nesting if statements makes your program more powerful because it can handle many different situations. • Nesting occurs when one or more if structures are inside of another if statement. • The else statement is always associated with the previous if statement unless { } are used to change the associativity. • Dangling else Control Statements
Sequence • Selection • Repetition Dangling else • The else clause is always associated with the nearest if • Use { … } to change the association if (booleanExpression) if (booleanExpression) statement; else statement; Control Statements
Sequence • Selection • Repetition Dangling else: example if (guess != secretNumber) if (guess < secretNumber) System.out.println("Too small!"); else // guess > secretNumber System.out.println("Too large!"); if (guess != secretNumber) if (guess < secretNumber) System.out.println("Too small!"); else // guess > secretNumber System.out.println("Too large!"); Control Statements
Sequence • Selection • Repetition Nested if Statements • What is printed when the following is evaluated: if (y == 8) if (x == 5) System.out.println( "1" ); else System.out.println( "2" ); System.out.println( "3" ); System.out.println( "4" ); Control Statements
Sequence • Selection • Repetition Are these if Statements Equivalent? if (y == 8) 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 !!! Consider x = 3, y = 4. Control Statements
Sequence • Selection • Repetition switch Selection Structure • The switchselection structure is basically short hand for multiple if/else statements. It allows you to perform statements for a specific value of a variable when there are multiple possibilities. • The switch expression must be an integer, byte, short, or char result. Control Statements
Sequence • Selection • Repetition switch Selection Structure switch ( switch_expr ) { case item_1: statement1; statement2; … break; case item_2: statement3; … break; default: statement 4; … break; } if ( switch_expr==item_1 ) { statement1; statement2; … } else if (switch_expr==item_2) { statement3; … } else { // default case statement 4; … } Control Statements
Sequence • Selection • Repetition switchSelection Structure switch ( grade ) { case 'A': ++aCount; break; case 'B': ++bCount; break; ... default: System.out.println( "Incorrect grade. Enter new grade." ); break; } True break ++aCount Case 'A' False True break ++bCount Case 'B' False ... System.out.println ... Control Statements
Sequence • Selection • Repetition switch Selection Structure • The switch should always use the breakstatement for each case or the structure will not work properly. • Your switchstatements should always have a default case for completeness purposes. • Anything you can represent with a switch you can represent as a nested if/else statement. Control Statements
Sequence • Selection • Repetition switch Selection Structure • What if you have multiple values you want to test for and have them execute the same “case”? switch ( switch_expr ) { case item_1: case item_2: statement1; statement2; … break; case item_3: statement3; … break; default: statement 4; … break; } Control Statements
Sequence • Selection • Repetition Repetition Structures • Repetition Structures allow you to write programs that will repeat program steps multiple times. • Also called Loops • Counter controlled loops are executed a specific number of times. • Conditional loops are executed an indefinite number of times. Control Statements
Sequence • Selection • Repetition The whileLoop • The while loop is a conditional loop. It is executed an indefinite number of times. • A while loop terminates based upon a boolean expression becoming false. • As long as the expression is true, the loop will be executed. while ( num < 5 ) { num = num + 1; } Control Statements
Sequence • Selection • Repetition The while Loop • Syntax of a while loop: while ( boolean_expression ) { statement1; } while ( boolean_expression ) { statement1; … statementN; } while ( num < 5 ) { num = num + 1; } Control Statements
Sequence • Selection • Repetition Thewhile Loop { int num = 0; while ( num < 5 ) { num = num + 1; } } True num = num + 1; num < 5 False Control Statements
Sequence • Selection • Repetition The whileLoop • If the boolean_expression is false when the whileloop is encountered, the statements inside the loop are never executed. • If the boolean_expression never becomes false, then the statements inside the loop are executed “forever” in an infinite loop. Control Statements
Sequence • Selection • Repetition The whileLoop • What happens when we execute the following loops: Assume x = 4; while ( x < 10 ) { x = x + 4; } while ( x < 10 ); x = x + 4; Control Statements
Sequence • Selection • Repetition Divide public class Divide { public static void main( String args[] ) { int dividend = 35; int divisor = 5; int remainder = dividend; int quotient = 0; while ( remainder >= divisor ) { remainder = remainder - divisor; quotient = quotient + 1; } System.out.println( dividend + " / " + divisor + " = " + quotient); System.out.println( dividend + " % " + divisor + " = " + remainder ); } } // Divide Control Statements
Sequence • Selection • Repetition Square Root public class SquareRoot { public static void main( String args[] ) { double epsilon = 1.0e-9; double number = 2.0; double oldGuess = 0; double newGuess = number; while ( Math.abs( newGuess - oldGuess ) > epsilon ) { oldGuess = newGuess; newGuess = ( ( number / oldGuess ) + oldGuess ) / 2.0; } System.out.println( " The square root of " + number + " is " +newGuess ); } } // SquareRoot Control Statements
Sequence • Selection • Repetition The whileLoop • Write a program to print the squares of the even numbers between 0 and 10. Print the results out in a table. Control Statements
Sequence • Selection • Repetition The whileLoop • Example: Write a program to print the squares of the even numbers between 0 and 10 (including 0 and 10). Print the results out in a table. import java.io.*; public class Squares { public static void main( String args[] ) { int x = 0; System.out.println(“Number Square”); while ( x <=10 ) { System.out.println(x + “ “ + x*x); x = x + 2; } } } // Squares • Homework: Based on this example, try to calculate the sum of the even number between 0 and 10 Control Statements
Sequence • Selection • Repetition The do/whileLoop • The do/while repetition structure is very similar to the whilerepetition structure. The difference between the two is where the conditional test is performed. • whilestatement: the conditional test is performed before the body of the loop is executed. • do/whilestatement: the conditional test is performed after the body of the loop is executed. This means the body of the loop is executed at least once. • Syntax: • do { • statement1; • … • statementN; • } while ( boolean_expression ); Control Statements
Sequence • Selection • Repetition The do/whileLoop { // While loop int num = 0; while ( num < 5 ) { num = num + 1; } } ------------------------------------------------ { // Do/While loop int num = 0; do num = num + 1; } while ( num < 5 ); True num = num + 1; num < 5 False True num = num + 1; num < 5 False Control Statements
Sequence • Selection • Repetition The do/whileLoop • If the boolean_expression is false when the while section of the loop is encountered, the statements inside the loop are only executed once. • If the boolean_expression never becomes false, then the statements inside the loop are executed “forever” in an infinite loop. Control Statements
Sequence • Selection • Repetition The do/whileLoop • What is printed when the following code is executed: int x = 1; int y = 1; do { while ( y < x ) { System.out.print( "*" ); y++; } // end of while loop System.out.print( '\n' ); } while ( x <= 5 ); Control Statements