1 / 71

Basic Java Syntax

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 ) {

mdaryl
Download Presentation

Basic Java Syntax

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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

  3. 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

  4. Relational Operators Control Statements

  5. 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

  6. 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

  7. Logical Operators • && (logical And): Expression1 Expression2 Expression1 && Expression2 True True True True False False False True False False False False Control Statements

  8. Logical Operators • || (logical Or): Expression1 Expression2 Expression1 || Expression2 True True True True False True False True True False False False Control Statements

  9. 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

  10. Logical Operators • ^ (logical Exclusive Or): Expression1 Expression2 Expression1 ^ Expression2 True True False True False True False True True False False False Control Statements

  11. Logical Operators • ! (logical Not): Expression1 ! Expression1 True False False True Control Statements

  12. Logical Operators • ( 4 >= 7 ) && ( 3 + 4 == 7 ) • ( 4 >= 7 ) && ( 3 + 4 == 7 ) || ( 4 < 7 ) • ( 4 >= 7 ) && ( 3 + 4 == 7 ) || ( 4 < 7 ) && true Control Statements

  13. Precedence and Operators Highest Lowest Control Statements

  14. Control Structures • Control structures are used to organize actions (statements). • Examples: • Sequence Structure • Selection Structure • Repetition Structure Control Statements

  15. 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

  16. 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

  17. 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

  18. 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

  19. 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

  20. 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

  21. 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

  22. 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

  23. 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

  24. 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

  25. 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

  26. 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

  27. 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

  28. 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

  29. 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

  30. 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

  31. 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

  32. 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

  33. 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

  34. 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

  35. 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

  36. 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

  37. 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

  38. 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

  39. 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

  40. Sequence • Selection • Repetition Thewhile Loop { int num = 0; while ( num < 5 ) { num = num + 1; } } True num = num + 1; num < 5 False Control Statements

  41. 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

  42. 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

  43. 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

  44. 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

  45. 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

  46. 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

  47. 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

  48. 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

  49. 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

  50. 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

More Related