Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CompSci 125 Lecture 03 Applications and Applets, Console I/O The String class, Assignment The int data type Homework Update § HW1 § Sec 1,2 due 9/4 (now) § Sec 3 due 9/5 (start of class) § HW2 § Will post on website today § Sec 1,2 due 9/13 (start of class) § Sec 3 due 9/13 (midnight) Programming Assignment Update § p0: Linux Lab & Eclipse Skills (Due Sept 3) Two Forms of a Java Program § Applet § Intended to execute inside of a browser § Can also run inside of the Java “Applet Viewer” (from Eclipse) § Intended to be served up by a web server § Can be embedded into an HTML document § Not to be confused with JavaScript § Application § Ordinary client-side application § Example: Hello World program in Programming Assignment 0 HowTo Embed an Applet Hello.class in an HTML Document <html>! <meta http-equiv="Content-Type" content="text/html; charset=MacRoman"/>! <body>! <applet code=“Hello.class” width="200" height="200" >! </applet>! </body>! </html>! Applets in the Real World § Security issue --- allows web sites to serve executable programs to run on your computer § google “java applet vulnerabilities” for latest news § Nearly every browser configured by default to block them Java Types § Recall that a type describes (amongst other things) how data will be encoded in the computer’s memory Type String! § A sequence of zero or more characters § An object of the built-in class String! § A string literal provides an easy way to build a String object: § “Some string literal” § “S” § “” http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html Type char! § Exactly one character § char literals coded with apostrophe rather than quotes: § ‘A’ § ‘B’ § ‘1’ String and char Literals § ‘1’ and “1” do not encode the same bits in memory § “1” is a String containing digit one § ‘1’ is a char containing digit one § We’ll revisit this difference as we learn more about types, classes and objects UTF-16 Symbol Encoding § Consider String “ABC”! § UTF-16 defines how Java encodes characters as binary 0s and 1s § What actually gets stored in the computer’s memory? Memory Address Symbol Binary Encoding 1000 A 00000000 01000001 1002 B 00000000 01000010 1004 C 00000000 01000011 Escape Sequences § String literals enclosed in quotes § “Jane said, \“This is odd.\”” § “This will output on one line.\nAnd this the next.” § “You can include the backslash \\ character.” Java Console Output System.out.println(“Hello World”);! ! § Java statement invokes the println method § The println method writes a String to the console followed by a newline “\n” § The String is an argument (something like a mathematical function) to the println method § System is a built-in class, part of the java.lang package Java Console Output System.out.print(“Hello World”);! ! § Similar to println § But doesn’t output a newline after printing the text Java Console I/O § Most programs also need to accept input from their users § The built-in Java class Scanner can process keyboard input Scanner Example import java.util.Scanner;! public class Echo {! public static void main(String[] args) {! !System.out.print("Enter string: "); Scanner stdin = new Scanner(System.in); !String token = stdin.next(); ! System.out.println(token); ! }! } //Echo !//Prompt! !//Build Scanner object! !//Read a String! !//Print a String! Prints a prompt. Creates an instance of a Scanner called stdin. Reads the next String token from stdin (keyboard) and prints it to stdout (console)… Java import Statement import java.util.Scanner;! public class Echo {! public static void main(String[] args) {! !System.out.print("Enter string: ");! Scanner stdin = new Scanner(System.in);! !String token = stdin.next();! System.out.println(token);! }! } //Echo This import statement tells Java our class wishes to use the Scanner class in the built-in package java.util! The Built-In Scanner class § Reads tokens (words delimited by whitespace) from a specified input “stream” (e.g. System.in ≈ keyboard) § Must tell Java we are using it with an import statement § We must “new up” an instance of a Scanner before using it § Every instance of a Scanner implements many methods § Method next() returns the next String token read from stdin § Method nextInt() returns the next integer number § Etc § http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html Building a Scanner Object import java.util.Scanner;! public class Addition {! public static void main(String[] args) {! Scanner stdin = new Scanner(System.in);! System.out.print("Enter two integers: ");! int n = stdin.nextInt();! int m = stdin.nextInt();! System.out.printf("The sum is %d\n", n+m);! }! } //Addition Creates a variable (named memory location) called stdin with type Scanner Builds a new Scanner object to read from System.in (keyboard). Places the address of the new Scanner object in the variable stdin. We say the variable stdin “references” the new Scanner object We can use the stdin variable to refer to the new Scanner. Prompting the User import java.util.Scanner;! public class Addition {! public static void main(String[] args) {! Scanner stdin = new Scanner(System.in);! System.out.print("Enter two integers: ");! int n = stdin.nextInt();! int m = stdin.nextInt();! System.out.printf("The sum is %d\n", n+m);! }! } //Addition A “prompt” is an instruction displayed for the user of our program, telling them what they need to do next. Reading an integer import java.util.Scanner;! public class Addition {! public static void main(String[] args) {! Scanner stdin = new Scanner(System.in);! System.out.print("Enter two integers: ");! int n = stdin.nextInt();! int m = stdin.nextInt();! System.out.printf("The sum is %d\n", n+m);! }! } //Addition Creates a variable called n with type int to hold an integer value. Reads the next integer token from the keyboard by invoking the nextInt() method of the Scanner object referenced by stdin. Stores (“assigns”) the value of that integer in the variable n. Reading another integer import java.util.Scanner;! public class Addition {! public static void main(String[] args) {! Scanner stdin = new Scanner(System.in);! System.out.print("Enter two integers: ");! int n = stdin.nextInt();! int m = stdin.nextInt();! System.out.printf("The sum is %d\n", n+m);! }! } //Addition Creates a variable called m to hold an integer (int) value. Reads another integer token from the keyboard. Assigns the value of the next integer to the variable m. More About Invoking Methods § Recall that a class may define data and methods § An object is an instance of a class in memory § A variable can reference (contain the address of) an object § A method is an operation (function) implemented by a class SomeClassName myVariable = new SomeClassName();! myVariable.voidMethod();! ! //Invoking a void method! int x = myVariable.intMethod(); //Method returning an int! § Some methods “return” a result, like a mathematical function § By convention, we usually capitalize class names, but not variables and methods Printing Formatted Output import java.util.Scanner;! public class Addition {! public static void main(String[] args) {! Scanner stdin = new Scanner(System.in);! System.out.print("Enter two integers: ");! int n = stdin.nextInt();! int m = stdin.nextInt();! System.out.printf("The sum is %d\n", n+m);! }! } //Addition Adds two integer values, n and m! Prints the string “The sum is %d\n” replacing “%d” format specifier with the sum of n and m, and replaces the “\n” with the codes to advance the cursor to the beginning of the next line. Data Type Summary § Working definition: Define how Java interprets memory content § Specifies how a data value will be encoded as 0s and 1s § Specifies what operations (methods) can be performed § Two kinds: Primitive Types and Reference Types § Examples: § String: Built-in Java class representing 0..n characters § char: Primitive type representing exactly one character § int: Primitive type representing a single integer § Scanner: Built-in Java class we used to represent the keyboard § http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html Variable Summary § Occupies memory, has an associated type, and contains a value § Must define a variable before using it in your program § Primitive value: Variable of a primitive type contains the value § Reference value: Variable of a reference type contains the address of the value § Example Definitions: § Scanner stdin = new Scanner(System.in);! § int n = stdin.nextInt();! More About the int Type § Primitive Type § Some operations may be efficiently implemented by the hardware § A variable of type int stores a single integer § Uses 4 bytes (32 bits) of memory to store each int value § Encodes integer as 1s and 0s using Two’s Compliment technique § This encoding uses one bit for the sign, and 31 bits for the value § Can’t store really, really large negative or positive integers § The range is: -2,147,483,648 to 2,147,483,647 § Can’t represent fractions, only whole numbers § http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html § http://en.wikipedia.org/wiki/Two's_complement int Examples Java Statement Commentary int n;! Defines variable n to be an int int n = 0;! Defines and initializes n to be 0 n = 3;! Assigns 3 to previously defined n n = -1;! Assigns -1 to previously defined n int n = stdin.nextInt();! Defines and assigns to n the next value read from the Scanner stdin! n = stdin.nextInt();! Assigns to n the next value read from Scanner stdin! int jabberwocky;! Can use any legal identifier name int Examples Java Statement Commentary int n;! Defines variable n to be an int n = 3 + 1;! Addition n = 3 – 1;! Subtraction n = 3 * 1;! Multiplication n = 3 / 1;! Division n = 3 / 0;! Error: Division by zero Even more int Java Statement Commentary int n, m, k;! Defines variables n, m and k to be each an int n = 1 – 3;! Assigns -2 to n n = 1 / 3;! Assigns 0 to n n = 5;! Assigns 5 to n n = n + 1;! Assigns 6 to n n = 20,000,000;! Compiler error n = 20000000;! Twenty million m = 60000000;! Sixty million k = n * m;! Becomes a negative number!!! How Java stores 3 in an int variable sign (1 bit) 0! binary value (31 bits) 0000000000000000000000000000011! An int variable can store integers between -231 and 231-1 inclusive. Integers outside this range require must use a different type (e.g. long) Limitations of int Variables § What happens if we try to do the following: int x; ! ! x = 2147483647; ! x = x + 1;! ! //Define an int variable x! //Largest possible integer in 31 bits! //Add one to that integer! § -2147483648 which is -(231) ... how could this happen?!! sign (1 bit) binary value (31 bits) 0! 1111111111111111111111111111111! 1! 0000000000000000000000000000000! “Declaring” Variables § int n;! § int n, m;! § int n=0;! § int n=0, m=1;! § char c;! § final char LETTER_A = ‘A’;! § String x;! § String alphabet = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;! § Scanner stdin = new Scanner(System.in);! Java Primitive Types Limited to just those built-into Java Type #Bytes byte! 1 Integers in -27..27-1 short! 2 Integers in -215..215-1 int! 4 Integers in -231..231-1 long! 8 Integers in -263..263-1 float! 4 Fractions encoded by 32 bits double! 8 Fractions encoded by 64 bits char! 2 Single UTF-16 encoded character boolean! undefined Description true or false! http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html Reference Types § Classes (both those built-into Java and those you define) § More (later in course) Reference Variables § Variables associated with a reference type 10000 alphabet! 42000 Reference variable alphabet located (for example) at address 10000 42000 “ABC…” String object located (for example) at address 42000 Assignment § int n; § n = 42; ! ! !//Defines a variable, n! !//Assigns a value to n! § Assignment stores a value in a memory location (the variable appearing on the left-hand side of the “=“ sign) You can define and assign a value to a variable in a single statement § int n = 3; ! !! § String s = “foo”; !! § Scanner stdin = new Scanner(System.in);! Integer Expressions § n § n § n § n § n § n ! = = = = = = 7 + 5; ! (7 + 5) / 2; 7 + 5 / 2; (7 + 5) / (2 2 * 3 + 1; 5 % 2; ! ! ! ! + 1); ! ! !//12! !//6! !//9! !//4! !//7! !//1 (Remainder or “modulo”)! Operator Precedence Rules 1. Multiplication, division and remainder applied first. If there is a sequence of several of these operators, they are applied left-to-right. 2. Addition and subtraction are applied next, left-to-right 3. The assignment (“=“) is applied last 4. Parenthesis over-ride the rules above