Introduction to Java 15-121 Fall 2020 Margaret Reid-Miller Academic Integrity • You must do your own work. • Discussion with other students is limited to clarifying the assignments or at a high non- code level (pictures). • If you need help, ask the course staff or me (see the Staff page for office hours). • You should never look at another person’s program nor allow another student to look at your program (except recitation labs). Fall 2020 15-121 (Reid-Miller) 2 What if I cheat on a assignment? • Record a negative score on the assignment. • Reduce your final semester letter grade. • Prevent you from dropping, withdrawing, or changing to pass/fail. • Send letters to Student Affairs, your advisor, various deans, etc. • May result in long-term suspension. Fall 2020 15-121 (Reid-Miller) 4 Life happens So I give you some late days. How many late days in total? How many late days can you use for a single assignment? What is the penalty for turning an assignment late when you run out of late days? Fall 2020 15-121 (Reid-Miller) 5 4 2 No credit, so always submit something on time Quizzes • When is our first quiz? • How often do we have a quiz? • How many quizzes will be counted? • Can your arrange to make up a quiz? Fall 2020 15-121 (Reid-Miller) 6 Tomorrow Every Thursday 10 (1-2 will be dropped) You can’t, but each is worth only 0.5% 15-121 (Reid-Miller) 7 Java vs Python • Program Translation: • Java is compiled, Python is interpreted • Java syntax: • Uses braces {} to group statements (indentation is not semantic, but recommended) • Most statements end in semi-colons. • Java programs: • Often have several classes, each in a file with same name. • Java programs start with the method main. There is no required textbook. • I will post related readings, however, from a free on-line text book Introduction to Programming Using Java by David J. Eck that you may find helpful for your understanding. • You are welcome to use other books on data structures using Java. Fall 2020 15-121 (Reid-Miller) 8 Today • Data types (primitive/reference) • Basic Operators • Variable declaration • Strings • Before next lecture, review and compare syntax of LetterCounter1.java and LetterCounter1.py Fall 2020 15-121 (Reid-Miller) 9 Java requires that you declare the type of each variable before it is used. • You also need to declare the type of the expression return from a method Basic types: boolean (true or false) int (integer) double (floating point decimal) String (sequence of characters) … void return type of a method that returns no value • Java checks that the types match when you compile. Compiler error messages often indicate a type mismatch. Fall 2020 15-121 (Reid-Miller) 10 Fall 2020 15-121 (Reid-Miller) 11 Primitive Data Types • Java has two categories of data: • primitive data (e.g., number, character) • object data (programmer created types) • There are 8 primitive data types: byte, short, int, long, float, double, char, boolean • Primitive data are only single values; they have no special capabilities • You cannot define new primitive data types. Fall 2020 15-121 (Reid-Miller) 12 Common Basic Types Type Description Example of Literals int integers (whole numbers) 42, 60634, -8, 0 double real numbers 0.039, -10.2, 4.2E+72 char single characters boolean logical values String List of characters "", "a", "ab6&" 'a', 'B', '&', '6' true, false Fall 2020 15-121 (Reid-Miller) 13 Mostly use int and double Type Storage Range of Values byte 8 bits -128 to 127 short 16 bits -32,768 to 32,727 int 32 bits -2,147,483,648 to 2,147,483,647 long 64 bits -9x1018 to 9x1018 float 32 bits ±10-45 to ±1038, 7 significant digits double 64 bits ±10-324 to ±10308, 15 significant digits Recall • What is 210 in base 10, approximately? • 220 ? • 230 ? • 232 ? Fall 2020 15-121 (Reid-Miller) 14 103 1 million 1 billion 4 billion Fall 2020 15-121 (Reid-Miller) 15 Note the limited range of int Type Storage Range of Values byte 8 bits -128 to 127 short 16 bits -32,768 to 32,727 int 32 bits -2 billion to 2 billion, approximately long 64 bits -9x1018 to 9x1018 float 32 bits ±10-45 to ±1038, only 7 significant digits! double 64 bits ±10-324 to ±10308, 15 significant digits Fall 2020 15-121 (Reid-Miller) 16 Basic Operators Type Description Operators int integers +, -, *, /, %, ++, -- double real numbers +, -, *, / char single characters +, - (int arithmetic) boolean relational logical ==, !=, <, >, <=, >= ! , &&, || String Strings + (concatenation) Fall 2020 15-121 (Reid-Miller) 17 Before you can use a variable, you must declare its type. • You can declare a variable only once in a method. • Examples: int numDimes; double length; char courseSection; boolean done; String lastName; camelCase is the Java convention Fall 2020 15-121 (Reid-Miller) 18 Declaring Variables • Declaring a variable instructs the compiler to set aside a portion of memory large enough to hold data of that type. int count; double length; count length • No value has be put in memory yet. That is, the variable is undefined. Fall 2020 15-121 (Reid-Miller) Assignment Statements • An assignment statement stores a value into a variable's memory location:= ; • The type of the variable and expression must match. • The first assignment to a variable initializes it. count = 3; count length = 72.3 + 2.0; length 3 74.3 19 Fall 2020 15-121 (Reid-Miller) 20 Assignment statements shortcuts int n; n = 0; int n = 0; n = n + 1; n += 1; n++; n = n - 1; n -= 1; n--; Other assignment operators: *=, /=, %= Fall 2020 15-121 (Reid-Miller) 21 Strings https://docs.oracle.com/javase/8/docs/api/java/lang/String.html • String is not a primitive type, but a class/type • String variables store references to memory addresses • Strings are immutable! That is, you cannot change a string, but you can assign a new string to a variable. • A string cannot span more than one line: "Not a valid String literal” How do you include a newline or single quote in a string? WRONG! Fall 2020 15-121 (Reid-Miller) 22 As with Python, Java has escape sequences Escape sequence: a two-character sequence that represent a single special character. Sequence Meaning \t \n \" \' \\ tab character newline character double quote single quote backslash character System.out.println( "What \"character\" is this \\? "); Fall 2020 15-121 (Reid-Miller) 23 An object of type String is a sequence of (unicode) characters. • When we declare a variable of type String, it does not create an object. String founder; • To create an object we use the new operator: founder = new String("Carnegie"); • Strings have a shortcut way of creating them: String founder2 = "Mellon"; initializes its state nullfounder • A primitive variable holds an actual value: int count = 15121; • An object variable holds a reference (address) to the object. String founder = new String("Carnegie"); Fall 2020 15-121 (Reid-Miller) 24 Object vs Primitive Data 15121count A String object "Carnegie" a35f3cdfounder a35f3cd reference: computer generated address length() substring()… object data object methods Fall 2020 15-121 (Reid-Miller) 25 String Length int length() • int indicates that the data type of the value the method returns. • Returns the number of characters in this string. • Example: String founder = "Carnegie"; int numChar = founder.length(); object dot operator method method header Fall 2020 15-121 (Reid-Miller) 26 Getting a single character char charAt(int index) Returns the character at a specified index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 C a r n e g i e M e l l o n Example: String school = "Carnegie Mellon"; char firstChar = school.charAt(0); WARNING: You cannot assign a char to an object of type String without first converting the char to a String object ! e.g., String initial = "" + firstChar; Fall 2020 15-121 (Reid-Miller) 27 Substrings String substring(int startIndex, int endIndex) String substring(int startIndex) Returns a new string consisting of the substring starting at startIndex (inclusive) and ending at endIndex (exclusive) or, if one parameter, to the last character. Example: String school = "Carnegie Mellon"; String founder = school.substring(0, 8); String founder2 = school.substring(9); 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 C a r n e g i e M e l l o n An example of method overloading, where the number of parameters differs. Fall 2020 15-121 (Reid-Miller) 28 Replacing Characters String replace(char oldChar, char newChar) Returns a new String object resulting from replacing every occurrence of oldChar with newChar. • The original String object is unchanged. (Strings are immutable!) Example: String founder = "Carnegie"; System.out.println( founder.replace('e', 'E')); System.out.println(founder); OUTPUT: CarnEgiE Carnegie Fall 2020 15-121 (Reid-Miller) 29 Changing Case String toUpperCase() Returns a new String object with all letters converted to uppercase. String toLowerCase() Returns a new String object with all letters converted to lowercase. Example: String founder = "Carnegie"; String upper = founder.toUpperCase(); String lower = founder.toLowerCase(); Immutable: You need to print or assign the result to a variable! Fall 2020 15-121 (Reid-Miller) 30 Equals boolean equals(String str) Returns true if str represents the same sequence of characters as this string. Example: String founder = "Carnegie"; founder.equals(“Carnegie”); // returns true founder.equals(“carnegie”); // returns false Fall 2020 15-121 (Reid-Miller) 31 Testing For Equality • For primitive values use == for equality testing. • For objects, use the equals method for testing equal contents. • The argument must be the same type as the object on which equals() is called. • For example: if (day == 1 && month.equals(“APRIL”)) { System.out.println(“It’s April Fool’s Day”); } WARNING: Never use == with strings! The results are unpredictable! Fall 2020 15-121 (Reid-Miller) 32 Compare the lexicographical order of two strings int compareTo(String str) Returns: • value < 0 if this string is “less than” str • value = 0 if they are equal • value > 0 if this string is “greater than” str Example: “mellon”.compareTo(“carnegie”); // returns positive # “Mellon”.compareTo(“mellon”); // returns negative #