Java Concepts Chapter 2 - Using Objects Mr. Smith AP Computer Science A Basic Java Syntax and Semantics Data Types: Primitive data types Objects Numbers (integer and floating point) Strings Characters (“A”, “B”, etc.) (char) Objects Booleans (true and false) (boolean) Numbers use operators (addition and multiplication) Are sent messages Must be instantiated before use (remember robots?) Strings Are objects Are sent messages Do not need to be instantiated Can be combined using the concatenation operator (+) Basic Java Syntax and Semantics Numeric Data Types: 6 numeric data types are used in Java: int (integer, no decimals) double (double precision floating-point numbers; i.e. numbers with decimals) short long Not in AP CS subset. byte float Basic Java Syntax and Semantics Some Java numeric data types: I hope I don’t have to memorize this Basic Java Syntax and Semantics Literals: By literal, we mean any number, text, or other information that represents a specific value and does not change: (PI) 7.21 “Hello World” In the statement: int month = 10; 10 is the literal Basic Java Syntax and Semantics Identifiers An identifier is the name of a variable, method, or class Java imposes the following rules on identifiers: Can be made up of letters, digits, underscore (_), and dollar sign ($) characters. Cannot start with a digit: score1 is legal but not 1score Cannot use reserved symbols such as ! and %: money! is not a legal identifier. Spaces are not permitted: myScore is legal but not my Score. Cannot use reserved words such as new, public, while. int newNum = 2; is legal but int new = 2; is not valid. Identifiers are case sensitive: myScore and myscore are different identifiers. Basic Java Syntax and Semantics Questions/Practice: What is the data type of each of the following values? int String double 100Answers void my_cash <myVar> money$value lucky number illegal illegal legal illegal legal illegal Tell me whether each of these identifiers are legal or illegal: 56 “56” 56.0 Create a variable to store the school phone number and use camel case. Basic Java Syntax and Semantics Declarations Variables A variable is a storage location in memory that has a type, name (identifier), and value. Before using a variable for the first time, the program must declare its type. Declare a variable in a variable declaration statement (i.e. int year; ) Several variables can be declared in a single declaration. Remember to use camelCase for variable names Basic Java Syntax and Semantics Declarations Variables Syntax: <typeName> <variableName> = <value>; OR <typeName> <variableName>; Initial values can be assigned in the same statement as its variable declaration: is the same as: int x; int x, y, z = 7; int y; double p, q = 1.41, t; int z = 7; String name = “AP Computer Science”; UrRobot karel = new UrRobot(1,1,East,0); String name = 13; Types do not match Basic Java Syntax and Semantics Objects Constants Declare the object variable, instantiate or create an object, and assign the object to the variable. <className> <variableName> = new <className>() Robot bot = new Robot(1, 1, North, 0); Constants The value cannot change Literal final double SALES_TAX_RATE = 7.00; final indicates a variable is declared as a constant The naming convention for constants is that they are written in UPPERCASE with underlines between words. Trying to change the value of a constant after it is initialized will be flagged by the compiler as an error. Basic Java Syntax and Semantics Assignment Statements The assignment operator is = An assignment statement has the following form: <variableName> = <expression>; The value of the expression on the right is assigned to the variable on the left. It simply replaces the value of the variable: double celsius; double fahrenheit = 82.5; //Assign 82.5 to variable fahrenheit celsius = (fahrenheit – 32.0) * 5.0 / 9.0; Basic Java Syntax and Semantics Assignment Statements It is an error to use a variable that has never had anything assigned to it: int myNumber; System.out.println(myNumber); The solution to this problem is: int myNumber; myNumber = 20; // Assign a value to myNumber System.out.println(myNumber); Basic Java Syntax and Semantics Arithmetic Expressions An arithmetic expression consists of operands and operators combined in a manner used in algebra. The usual rules apply: Remember the mnemonic phrase: “Please Excuse My Dear Aunt Sally” Multiplication and division are evaluated before addition and subtraction. Operators of equal precedence are evaluated from left to right. Parentheses can be used to change the order of evaluation. Basic Java Syntax and Semantics Common operators and their precedence: Basic Java Syntax and Semantics Terminal I/O for Different Data types Scanner class: reads from the input stream **** new for Java 5.0, but not tested on AP exam Here are the methods in the Scanner class: METHOD DESCRIPTION double nextDouble() Returns the first double in the input line. Leading and trailing spaces are ignored. int nextInt() Returns the first integer in the input line. Leading and trailing spaces are ignored. String nextLine() Returns the input line, including leading and trailing spaces. Warning: A leading newline is returned as an empty string. Terminal I/O for Different Data types The following program illustrates the major features of terminal I/O: import java.util.Scanner; public class TestTerminalIO { public static void main (String [] args) { Scanner in = new Scanner(System.in); System.out.print ("Enter your name (a string): "); String name = in.nextLine(); System.out.print("Enter your age (an integer): "); int age = in.nextInt(); System.out.print("Enter your weight (a double): "); double weight = in.nextDouble(); Terminal I/O for Different Data types System.out.println ("Greetings " + name + ". You are " + age + " years old and you weigh " + weight + " pounds."); } } Terminal I/O for Different Data types Warning: A leading newline is returned as an empty string. // now change the order of the input, // putting the string last System.out.print("Enter your age (an integer): "); int age = in.nextInt(); System.out.print("Enter your weight (a double): "); double weight = in.nextDouble(); System.out.print ("Enter your name (a string): "); String name = in.nextLine(); Terminal I/O for Different Data types The string name is the empty string. The reason is that the method nextDouble ignored but did not consume the new line that the user entered following the number. Therefore, this newline character was waiting to be consumed by the next call of nextLine, which was expecting more data. To avoid this problem, you should either input all lines of text before the numbers or, when that is not feasible, run an extra nextLine after numeric input to eliminate the trailing newline characters. Terminal I/O for Different Data types Warning: A leading newline is returned as an empty string. // now change the order of the input, // putting the string last System.out.print("Enter your age (an integer): "); int age = in.nextInt(); System.out.print("Enter your weight (a double): "); double weight = in.nextDouble(); in.nextLine(); // to consume the newline char System.out.print ("Enter your name (a string): "); String name = in.nextLine(); TemperatureConversion Create a TemperatureConversion class as follows: Enter a prompt for the Fahrenheit temperature in the console (using the Scanner class), and allow the user to enter the temperature there. Convert the temperature from Fahrenheit to Celsius Convert the temperature from Fahrenheit to Kelvin Print a message to the console that shows the conversion, such as: 50.0 F = 10.0 C 50.0 F = 283.15 K Do the same thing to allow the user to enter the temperature in Celsius and then print the conversion to Fahrenheit and Kelvin. 0.0 C = 32.0 F 0.0 C = 273.15 K Do the same thing to allow the user to enter the temperature in Kelvin and then print the conversion to Fahrenheit and Celsius. 283.15 K = 50.0 F 283.15 K = 10.0 C The conversion formulas can easily be found on the internet Please try these conversions where Fahrenheit = 50 and Celsius = 0. Also try a couple of other examples of your choice to verify that the program is working correctly. Basic Java Syntax and Semantics Division: The semantics of division are different for integer and floating-point operands. Thus: 5.0 / 2.0 5/2 yields 2.5 yields 2 (a quotient in which the decimal portion of the answer is simply dropped) Modulus: The operator % yields the remainder obtained when one number is divided by another. Thus: 9%5 9.3 % 5.1 yields 4 yields 4.2 Basic Java Syntax and Semantics Mixed-Mode Arithmetic Intermixing integers and floating-point numbers is called mixed-mode arithmetic. When arithmetic operations occur on operands of different numeric types, the less inclusive type (int) is temporarily and automatically converted to the more inclusive type (double) before the operation is performed. Examples: but 5.0 / 2.0 5/2 yields 2.5 (both double) yields 2 (both int) 5.0 / 2 yields 2.5 (mixed) Basic Java Syntax and Semantics Mixed-mode assignments are also allowed, provided the variable on the left is of a more inclusive type than the expression on the right. Otherwise, a syntax error occurs. double d; int i; i = 45; d = i; -- OK, because i is an integer and 45 is an integer. -- OK, because d is more inclusive than i. The value 45.0 is stored in d. -- Syntax error because i is less inclusive than d. i = d; Can put an integer into a double but not a double into an integer. Basic Java Syntax and Semantics Difficulties associated with mixed-mode arithmetic can be circumvented using a technique called “casting”. This allows one data type to be explicitly converted to another. The cast operator, either (int) or (double), appears immediately before the expression it is supposed to convert. The (int) cast simply throws away the digits after the decimal part. The (double) cast inserts a .0 after the integer. Basic Java Syntax and Semantics Examples: double x, y; int m, n; a) x = (double) 5 / 4; x = 5.0 / 4; x = 1.25 b) y = (double) (5 / 4); y = (double) (1); y = 1.0 c) m = (int) (x + 0.5); if x = 1.1, then m = (int) (1.6); m=1 Basic Java Syntax and Semantics String Expressions and Methods Simple Concatention The concatenation operator uses the plus symbol (+) String firstName, lastName, fullName, lastThenFirst; //declare four string //variables firstName = “Debbie”; lastName = “Klipp”; //initialize firstName //initialize lastName fullName = firstName +” “ + lastName; //yields “Debbie Klipp” lastThenFirst = lastName +”, “+ firstName; //yields “Klipp, Debbie” Basic Java Syntax and Semantics Concatenating Strings and Numbers Strings also can be concatenated to numbers. (The number is automatically converted to a string before the concatenation operator is applied.) String message; int x = 20, y = 35; message = “Bill sold ” + x + “ and Sylvia sold ” + y + “ subscriptions.”; // yields “Bill sold 20 and Sylvia sold 35 subscriptions.” Basic Java Syntax and Semantics Precedence of Concatenation The concatenation operator has the same precedence as addition, which can lead to unexpected results: a) “number ” + 3 + 4 number 34 b) “number ” + (3 + 4) number 7 c) “number ” + 3 * 4 number 12 d) 3 + 4 + “ number” 7 number Basic Java Syntax and Semantics The length Method Strings are objects and implement several methods. A String returns its length in response to a length message: String theString; int theLength; theString = “the cat sat on the mat.”; theLength = theString.length(); // yields 23 What is the result of printing the following to the console? If you don’t know the answer, then create a client class and print it to the console using a System.out.println() statement. Calculate the following and print the results to the console: 15 / 6 15.0 / 6.0 15.0 / 6 15 / 6.0 Find the remainder of 8 / 3 Find the remainder of 8.95 / 1.1 (double) 15 / 6 (double) (15 / 6) (double) 15 / 6 + 0.6 (int) ((double) 15 / 6 + 0.6) ______________________ ______________________ ______________________ ______________________ Syntax: _____________ Answer: _______ Syntax: _____________ Answer: _______ ______________________ ______________________ ______________________ ______________________ Output the following string functions to the console: “Age “ + 2 + 8 “Age “ + (2 + 8) “Age “ + 2 * 8 2 + 8 + “ Age” If name = “John Doe”, then what ______________________ ______________________ ______________________ ______________________ is name.length(); _______ What is the result of printing the following to the console? If you don’t know the answer, then create a client class and print it to the console using a System.out.println() statement. Calculate the following and print the results to the console: 15 / 6 15.0 / 6.0 15.0 / 6 15 / 6.0 Find the remainder of 8 / 3 Find the remainder of 8.95 / 1.1 (double) 15 / 6 (double) (15 / 6) (double) 15 / 6 + 0.6 (int) ((double) 15 / 6 + 0.6) 2 2.5 2.5 2.5 Syntax: 8 % 3 Syntax: 8.95 % 1.1 2.5 2.0 3.1 3 Output the following string functions to the console: “Age “ + 2 + 8 “Age “ + (2 + 8) “Age “ + 2 * 8 2 + 8 + “ Age” If name = “John Doe”, then what Age 28 Age 10 Age 16 10 Age is name.length(); 8 Answer: Answer: 2 .15 What is the result of printing the following to the console? If you don’t know the answer, then create a client class and print it to the console using a System.out.println() statement. Calculate the following and print the results to the console: (3.0 + 6.0) / 2 * 3 3.0 + 6.0 / 2 * 3 3.0 + 6.0 / (2 * 3) 8 + 6 + 3.5 - 6.0 (int) 15.0 / 4 * 4 (double) (15 / 6 + 9) (int) Math.PI * 10 (int) (4.0 / 2) * 3 + 1.5 3.0 / 6.0 + (3 * 3) 3 / 6 + 7 / 14 (((6 * 4) + (7 * 2)* 2) + 5) 13.5 12.0 4.0 11.5 12 11.0 30 7.5 9.5 0 57