Control & Arrays 15-121 Fall 2020 Margaret Reid-Miller
Today • No in class Quiz. Quiz will be asynchronous. • Strings continued • Java naming conventions • Flow Control: conditionals, loops, scope • Arrays Fall 2020 15-121 (Reid-Miller) 2
Basic types What is the difference between a char and a String variable? char is a primitive type for a single character. String is an object type for a sequence of characters. How are char and String literals different? char uses a pair of single quotes ( e.g. , 'x' ). String uses a pair of double quotes ( e.g. , "x" ). What is the difference between a null String and an empty String? null is when a String variable is undefined. an empty no has characters in it ( i.e. , "" ). Fall 2020 15-121 (Reid-Miller) 3
Python vs Java How does LetterCounter1.java compare to LetterCounter1.py ? In Java • Must declare types of variables • To read input, need a Scanner object • Statements terminated with ; • Uses {} to delimit blocks of code • Cannot use list(array) indexing on Strings • for loops are different Fall 2020 15-121 (Reid-Miller) 4
Identifiers and Keywords • Identifiers are names that specify different elements of a program such as class, method, or variable • can be any combination of letters, digits, _ or $ • the first character must NOT be a digit • case-sensitive ( total is different from Total ) Examples: main method1 maxCount TUESDAY $amount Puzzle • Keywords are a set of predefined identifiers that are reserved for special uses. Examples: public static void class Fall 2020 15-121 (Reid-Miller) 5
Java naming conventions readily distinguish various Java elements • Class: Starts with a capital letter , same name as file name • A class names should be a noun that describe an object type. e.g., String , Dice , Radio • Method: Starts with a lower case letter, camelCase • A method name should start with a verb and describe what the method does. e.g., displayQuestion , getName , computeTax Fall 2020 15-121 (Reid-Miller) 6
Java Naming Conventions (cont’d) • Variable: Starts with a lower case letter, camelCase • A variable name should be a noun that describes what data it holds. e.g., favoriteFood , name • Constant: All upper case with underscores • Constants are declared with the keyword final • A constant name should be a noun that describes what data it holds. e.g., PI , TAX_RATE Fall 2020 15-121 (Reid-Miller) 7
Flow Control Conditionals, Loops, Scope
Conditionals if ( boolean_expression ) statement if ( boolean_expression ) statement1 else statement2 A statement can be any Java statement: • A simple statement • A compound statement, such as an if statement • A block statement, a group of statements enclosed in braces {} Fall 2020 15-121 (Reid-Miller) 9
The Dangling else Problem • When an if statement is nested inside an if clause, its else clause is paired with the closest if statement that does not have an else clause. if (x > 0) if (y > 0) color = “red”; Misleading else indentation color = “blue”; Recall: Indentation is not semantic! Fall 2020 15-121 (Reid-Miller) 10
Each else is paired with closest if that has no else • In reality it is y y if (x > 0) if (y > 0) color = “red”; else x x color = “blue”; Fall 2020 15-121 (Reid-Miller) 11
Always use {} with if statements • Use braces to pair else y with the outer if if (x > 0) { if (y > 0) color = “red”; x } else { color = “blue”; } ( if or else on a single line without braces is OK.) Fall 2020 15-121 (Reid-Miller) 12
Multiple Alternatives • Determine if a number is positive, negative, or zero: if (value < 0) { System.out.println(“Value is negative.”); } else if (value == 0) { System.out.println(“Value is zero.”); } else if (value > 0) { // Redundant test! System.out.println(“Value is positive.”); } At most one statement is executed. Each choice, however, is at same indentation . Fall 2020 15-121 (Reid-Miller) 13
Multiple Alternatives • Determine if a number is positive, negative, or zero: if (value < 0) { System.out.println(“Value is negative.”); } else if (value == 0) { System.out.println(“Value is zero.”); } else { // value must be positive System.out.println(“Value is positive.”); } It is clear, exactly one statement is executed. Fall 2020 15-121 (Reid-Miller) 14
The switch statement • If an if/else statement with multiple alternatives compares an int or char expression against several constants you can use a switch statement. Example: switch (suitAsChar) { case ‘C’: suitAsName = “Clubs”; break; case ‘D’: suitAsName = “Diamonds”; break; case ‘H’: suitAsName = “Hearts”; break; case ‘S’: suitAsName = “Spades”; break; default: suitAsName = “Unknown”; } WARNING: You must include break to avoid executing the • the body of the following case! Fall 2020 15-121 (Reid-Miller) 15
Java has 3 kinds of Loops initialize while ( test ) { do_stuff update } for ( initialize; test; update ) { do_stuff } initialize Note: do-statement executes loop at least do { once – not often used do_stuff update } while ( test ); Fall 2020 15-121 (Reid-Miller) 16
While Loop int i = 0; while (i < n) { System.out.print(“*”); i++; } System.out.println(); Fall 2020 15-121 (Reid-Miller) 17
for Loop for (int i = 0; i < n; i++) { System.out.print(“*”); } System.out.println(); Fall 2020 15-121 (Reid-Miller) 18
Scope • The scope of a variable is the area within a program that can reference the variable. • The scope depends on where the variable is declared. int sum = 0; for (int i = 1; i <= n; i++) { Scope of sum += i*i; variable i } System.out.println(sum); Fall 2020 15-121 (Reid-Miller) 19
Scope int sum = 0; int i; for (i = 1; i <= n; i++) { sum += i*i; Scope of } variable i System.out.println(“Sum of first “ ends at the + (i-1) + “ integers squared is “ enclosing + sum); brace } Fall 2020 15-121 (Reid-Miller) 20
Use a do-while if you must execute the body of the loop at least once. Scanner console = new Scanner(System.in); Must be declared int month; outside the loop do { System.out.print( “Please enter the month [1-12]: ”); month = console.nextInt(); } while ( ); month < 1 || month > 12 Outside the scope of the loop Fall 2020 15-121 (Reid-Miller) 21
Arrays
Java arrays use special syntax • How do we say/pronounce this? Array of int or int Array int[] • What is poor about this code? int[] count ; Use plural names • What does this code do? int[] counts ; Declares counts to refer to an array of ints (but doesn’t yet) • How do I create an array? new [ ] type how many Fall 2020 15-121 (Reid-Miller) 23
Creating an array • Declare and create: must match int[] counts; counts = new int[6]; • Shortcut: int[] counts = new int[6] ; • Arrays are automatically filled with default values when created: • int[] , double[] , char[] is 0 • boolean[] is false • String[] is null (as with all objects) Fall 2020 15-121 (Reid-Miller) 24
Initializer List • You can declare, create, and initialize an array with a list of values or expressions . int[] counts = {12, 22, 17, 16, 4, 11}; • You can use an initializer list only when the array is first declared. • Each value must match the type of the array. • The values go into the array in the order given and determine the length of the array. Fall 2020 15-121 (Reid-Miller) 25
Arrays are uniform, fixed length, and have no methods • Every element of an array must be the same type . We will see how to get around that restriction later • • You can make arrays of primitives values or objects. • The length of an array is determined when it is first created and cannot grow or shrink Note no ()! It’s a value, not a method. E.g., counts.length • Unlike Python, there is no slicing (e.g., arr[2:5] ) and no negative indices (e.g., arr[-1]) . Fall 2020 15-121 (Reid-Miller) 26
Array Demo Fall 2020 15-121 (Reid-Miller) 27
Aliasing When you copy an array variable x to a variable y , you • copy the reference not the values in the array. int[] x = {1, 3, 7, -4, 2, 8, 5, 0, 4, 6} int[] y = x f2e23 f2e23 x 1 3 7 -4 2 8 5 0 4 6 y f2e23 • Changes made to x or y are seen by both variables. • We say x and y are aliases (two names for the same array) Fall 2020 15-121 (Reid-Miller) 28
Pass by Value • When you call a method with an argument, the method parameter variable receives a copy of the argument value. • The argument and parameter variables are in different scopes. • When the method returns, what happens to the parameter variable? • It is destroyed. Recall the scope ( end-of-the-life ) of a variable. • What is copied when the argument is an array? • The reference to the array. Fall 2020 15-121 (Reid-Miller) 29
Arrays as Parameters int[] values = new int[10]; In main , for example fillAllSums(values); public static void fillAllSums(int[] vals) { vals[0] = 0; for (int i = 1; i < vals.length; i++) { vals[i] = vals[i-1] + i; } } ae2f3 ae2f3 values 0 0 0 0 0 0 0 0 0 0 Fall 2020 15-121 (Reid-Miller) 30
Recommend
More recommend