Topic 1: Basic Java Plan: this topic through next Friday (5 lectures) Required reading on web site I will not spell out all the details in lecture! BlueJ Demo BlueJ = Java IDE (Interactive Development Environment) Editor + Compiler + Interpreter + other tools Remember: no "run" button; just execute main function My goal: highlight differences between Java and Python mention things that often trip up Java newbies file I/O Information about 3 Java tools on web site: BlueJ JDK plus text editor Eclipse Other alternatives OK as long as based on standard Sun (Oracle) Java, version 6 or 7 (also known as 1.6 or 1.7) 1 2 Features of Structured Programming Languages basic statements: assignments, function calls... compound statements: 1. Sequencing: one statement after another 2. Selection: choosing among alternatives 3. Iteration: repeating a statement 4. Grouping: treating several statements as a unit abstraction: functions/methods/procedures with parameters & results 1. Sequencing Python: separate one statement from the next by going to the next line (or midline semicolon) a = 7 b = 8 c = 5; d = 6 e = 1 + 2 + 3 + \ 4 + 5 Java: All simple statements end with a semicolon. a = 7; b = 5; c = 1 + 2 + 3 + 4 + 5; d = 6; 3 4
Python: if a > b: c = 17 else: c = 5 2. Selection Python: if n > 10: a = 1 b = 2 c = 3 3. Grouping What statements are executed only when n > 10? How do you know? Java: if (a>b) c = 17; else c = 5; or (ugly but legal): if (a> b) c = 17; else c = 5; Java: if (n > 10) { a = 1; b = 2; c = 3; Green part is called a block. Combines a group of statements into a compond statement. Java also has a switch statement for multi-way branches. Optional for 124. Ugly but legal equivalent: if (n>10) {a = 1; b = 2; c = 3; 5 6 4A. Iteration: While loops 4B. Iteration: For loops Python: while i < n: total += i i += 1 Java: while (i < n) { total += i; i++; Python: for i in range(n): total += i Java: for (int i = 1; i < n; i++) { total += i; Java also has a third kind of loop: do/while Optional for 124. same as: int i = 1; while (i < n) { total += i; i++; 7 8
Dynamic vs. Static Typing Declaring Variables Python uses dynamic typing: must run program to determine the types of expressions if <some condition>: x = 14 else: x = "abc" # what is the type of x??? # is x/4 a legal expression??? Java uses static typing: the value of every expression can be determined at compile time. Every variable must be declared with a type. Or: Rules: int x = 14; String y = "abc"; int x; // later on in program X = 14; A variable must be declared before it is set (possibly on the same line) A variable must be set before it is used 9 10 Nuisance public static void main(string args[]) { int x;.. if (<some error condition>) { System.out.println("error!"); System.exit(1); // aborts program else {... x =...; int y = x + 17; WILL NOT COMPILE!... // end main volume of a cone = In Java: Mixed-Mode Arithmetic double height = 10.6; double radius = 5.24; final double PI = 3.14159; double volume = 1/3 * PI * radius * radius * height; System.out.println(volume); result? why? 1 3 π r 2 h 11 12
Strings The "+" Operator Strings are objects Not lists/arrays String literal: "abcd" Character literal 'a' 'a' and "a" are not the same thing! To access parts of strings, use special String methods: charat length substring int x = 1; int y = 2; // value of x + y? String x = "abc"; String y = "def"; // value of x + y? String x = "one"; int y = 2; // value of x + y? 13 14 The "+" Operator (continued) Comparing Strings (equality) int a = 9; int b = 6; System.out.println("the total is " + a + b); // what is printed? int c = 9; int d = 6; System.out.println(c + d + " is the total"); // what is printed? String s1 = "abcd"; String t = "ab"; prints "not equal"! String u = "cd"; String s2 = t + u; if (s1 == s2) System.out.println("equal"); else System.out.println("not equal"); if (s1.equals(s2)) prints "equal" System.out.println("equal"); else System.out.println("not equal"); 15 16
Comparing Strings (inequality) String a = "apple"; String b = "banana"; int val = a.compareto(b); Output To The Console System.out.print(s) System.out.println(s) compareto returns: 0 if a and b are exactly equal positive int if a is greater than b negative int if a is less than b 17 18 Input From the Keyboard Input, continued 1. Create a Scanner object: Scanner keyboard = new Scanner(System.in); keyboard.hasnextint() true if next token is an integer 2. Use one of the reading methods: keyboard.next(): next "token" as String keyboard.nextline(): rest of current line as String keyboard.nextint(): next token, converted to integer keyboard.nextdouble(): next token, converted to double Example programs: ScannerDemo: basic input of integers & strings; we will add checking ReadLines: reading tokens & whole lines can be tricky 19 20
Reading From a File Needs knowledge of exceptions later this term. For now: helper class FileOpen available on web site. To use FileOpen: add copy to the same folder as your program. (No import necessary.) Methods What is a method? Like a function in Python. Small piece of a program Performs small task Other names in different languages: function, procedure, subprogram, subroutine String inputname = "myfile.txt"; Scanner inputfile = FileOpen.openScanner(inputName); PrintWriter outputfile = FileOpen.openWriter("output.txt"); // use outputfile just like System.out Look at FileOpenDemo... Why do we use methods? avoid duplicated code modularize improve readability readability means: easier to debug easier to modify harder to goof 21 22 Parameters & Return Results Abstraction parameter: information you give to the method return result: information it gives back method with no result is "void" example: leapyear method abstract view of leapyear method: what it does (interface) concrete/implementation view: how it works (implementation) Every method must have a header comment saying what it does Include parameters, return result, possible errors To learn how to call the method: just read the header comment To learn how the method works: read the body too 23 24
Ending Things Early 1. break statement ends the current (innermost) loop 2. return ends the current method Order Of Methods Common question: Does the order in which I declare my methods matter? Answer: For functionality, no. For style, maybe yes. 3. System.exit(n) ends the program convention: n = 0 means normal exit n 0 parameter means error abort Example: Endings.java 25 26 Overloading Scope OK to have two methods with the same name. Call is resolved based on number and/or types of parameters public static double m(double a, double b) { public static String m(int a, int b) { return a + 2*b; return a + b.substring(1); public static double m(double a, double b, double c) { return (a+b+c)/3.0; Scope of variable = where it can be used Scope of a Java variable: from declaration to end of block public static int scope() { int a =...; while (a > 0) { int b =...; for (int i = 0; i < b; i++) { int c = b+i; a += c; while (...) { double c =...;... // end while // end while return a; // end scope 27 28
Scope (2) You can't hide a variable by declaring a variable with the same name in an inner loop. Global Variables You can declare variables outside of any methods -- "globally". Don't do it until we discuss it in the next topic! int a =...; while (a > 0) { int b =...; if (...) { int b =...; // illegal! // end while 29 30 Right now: Arrays basics of one- and two-dimensional arrays lets us use arrays in examples, assignments and quizzes Caution to Python Programmers Arrays are not lists!!!! ignores some details After classes topic we'll fill in some missing details Python Lists: can grow & shrink can mix many types of values (heterogeneous) languages features for adding & deleting at any position Java Arrays: size is specified at creation time, never changes all values must have same type (homogeneous) more programming effort required to add & delete array elements 31 32
Definitions Creating An Array array: ordered collection of elements of the same type [homogeneous collection] Note: indexes go from 0 to length-1 index: position of element length: number of elements in array Size of array specified when created. size can never change! 0 1 2 3 4 5 6 General form: <type>[] <name> = new <type>[<size>] or: <type> <name>[] = new <type>[<size>] Examples: int marks[] = new int[20]; String[] names = new String[10]; In each of above, there are two things happening: 1. Declaring the array variable 2. Creating a new array and assigning it to the variable 33 34 1. Declaring an Array 2. Creating a New Array syntax: <type> <name>[]; or: <type>[] <name>; declaration int coursemarks[]; coursemarks has not been initialized use an array constructor to give it a value: coursemarks = new int[20]; Note: no length specified! examples: int coursemarks[]; String args[]; double[] data; now coursemarks is an array containing 20 integers: indexes 0 to 19 all elements automatically initialized to zero or combine declaration & initialization: int coursemarks[] = new int[20]; 35 36
Using an Array refer to an element of an array as <array name> [ <index> ] // read values into array int coursemarks[] = new int[20]; for (int i = 0; i < 20; i++) { System.out.print("enter next mark: "); coursemarks[i] = keyboard.nextint(); // end for Style problem: 20 used in several places. Why is that // average the values bad? int sum = 0; for (int i = 0; i < 20; i++) sum = sum + coursemarks[i]; System.out.println("average mark: " + (double) sum / 20); Using an Array: Improved Version // read values into array final int NUM_STUDENTS = 20; int coursemarks[] = new int[num_students]; for (int i = 0; i < NUM_STUDENTS; i++) { System.out.print("enter next mark: "); coursemarks[i] = keyboard.nextint(); // end for // average the values int sum = 0; for (int i = 0; i < NUM_STUDENTS; i++) sum = sum + coursemarks[i]; System.out.println("average mark: " + (double) sum / NUM_STUDENTS); 37 38 Even Better Version every array object has length attribute <array name>.length gets the length of the array Bounds Checking Java throws an exception (aborts) if you try to access or change an array element that's out of bounds int coursemarks[] = new int[20]; for (int i = 0; i<coursemarks.length; i++){ System.out.print("enter next mark: "); coursemarks[i] = keyboard.nextint(); // end for int sum = 0; for (int i = 0; i < coursemarks.length; i++) sum = sum + coursemarks[i]; System.out.println("average mark: " + (double) sum / coursemarks.length); Example: int myarray[] = new int[10]; int x = myarray[0]; // OK myarray[9] = 42; // OK int z = myarray[10]; // exception! myarray[-1] = 7; // exception! java.lang.arrayindexoutofboundsexception at ArrayTest.main(ArrayTest.java:9) 39 40
Arrays As Parameters public class ArrayParm { public static void changearray(int numbers[]) { numbers[0]++; // end changearray Two-Dimensional Arrays assignment scores for 20 students, 9 assignments: int scores[][] = new int[20][9]; visualize as a table: 20 rows, 9 columns public static void main(string args[]) { int years[] = new int[3]; years[0] = 1987; years[1] = 1989; years[2] = 1994; changearray(years); for (int i = 0; i < years.length; i++) System.out.println(years[i]); // end main // end class student number 3, assignment 6: scores[3][6] 41 42 2D Arrays &.length Java treats a 2D array as an array of arrays. int scores[][] = new int[20][9]; scores is a 2D array of ints scores[4] is a 1D array of ints (the 5 th row) scores[4][7] is an int What does scores.length mean? number of rows (20) the height of the array Example: Total of 2D Array int numbers[][] =...; // initialize numbers... int total = 0; for (int row = 0; row < numbers.length; row++) { for (int col = 0; col < numbers[row].length; col++) { total += numbers[row][col]; // end for How would you ask for the number of columns (width)? scores[0].length 43 44
Using Java API Classes 1. Spell Out Full Name of Class API is divided into packages. Example Scanner class is in java.util package. Three ways to use Scanner. public class Import { public static void main(string args[]) { java.util.scanner keyboard = new java.util.scanner(system.in); System.out.print("Enter your name: "); String name = keyboard.nextline(); System.out.println("Hello, " + name + "!"); // end main // end class 45 46 2. Import Class From Package 3. Import All Classes From Package import java.util.scanner; public class Import { public static void main(string args[]) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter your name: "); String name = keyboard.nextline(); System.out.println("Hello, " + name + "!"); // end main // end class import java.util.*; public class Import { public static void main(string args[]) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter your name: "); String name = keyboard.nextline(); System.out.println("Hello, " + name + "!"); // end main // end class This is no more expensive than importing just Scanner. 47 48
Special Class: java.lang Caution Automatically imported into all Java programs. Includes standard useful classes including: Math In CISC 124 you may use any API class unless specifically asked not to (for assignments, quizzes, etc) System String You may NOT use non-standard classes & packages (downloaded from Internet, supplied with Eclipse, etc.) 49 50 FAQ Programming Style What's the point of the parameter of the main method?? (Or the parameter to System.exit?) Both are for using Java with a command-line system (DOS, Linux, Mac terminal) Demo... To be useful, a program has to work correctly. Also must be readable by human beings. Examples... Some assignments will have style points. In-class exercises discussing examples of student assignments (anonymously) Not needed for CISC 124. Quizzes & Exams: time pressure, no style points BUT: I can't give you points if I can't understand what you write! Style can mean more partial credit for incorrect code 51 52