Java Concepts Chapter 2 - Using Objects Mr. Smith AP Computer Science A.
-
Upload
lora-dorsey -
Category
Documents
-
view
219 -
download
0
Transcript of Java Concepts Chapter 2 - Using Objects Mr. Smith AP Computer Science A.
Java ConceptsChapter 2 - Using Objects
Mr. SmithAP Computer Science
A
Basic Java Syntax and SemanticsData Types:
Primitive data types Numbers (integer and floating point) Characters (“A”, “B”, etc.) (char) Booleans (true and false) (boolean) Numbers use operators (addition and multiplication)
Objects 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
(+)
Objects Strings
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 byte float
Not in AP CS subset.
Basic Java Syntax and Semantics
Some Java numeric data types:
I hope I don’t have to memorize this
Basic Java Syntax and SemanticsLiterals:
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 SemanticsQuestions/Practice:
What is the data type of each of the following values? 56 “56” 56.0
Tell me whether each of these identifiers are legal or illegal: 100Answers void my_cash <myVar> money$value lucky number
Create a variable to store the school phone number and use camel case.
intStringdouble
illegalillegallegalillegallegalillegal
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: int x, y, z = 7; double p, q = 1.41, t; String name = “AP Computer Science”; UrRobot karel = new UrRobot(1,1,East,0); String name = 13; Types do not match
is the same as: int x; int y; int z = 7;
Basic Java Syntax and Semantics Objects
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
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.
Literal
Constants
Basic Java Syntax and SemanticsAssignment 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
fahrenheitcelsius = (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 SemanticsCommon operators and their precedence:
Basic Java Syntax and Semantics
Terminal I/O forDifferent 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 forDifferent 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 forDifferent Data types
System.out.println ("Greetings " + name + ". You are " + age + " years old and you weigh " + weight + " pounds."); }}
Terminal I/O forDifferent 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 forDifferent 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 forDifferent 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 C50.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 F0.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 F283.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
Modulus:The operator % yields the remainder obtained when one number is divided by another. Thus:
9 % 5 9.3 % 5.1
yields 2.5yields 2 (a quotient in which the decimal portion of the answer is simply dropped)
yields 4yields 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:5.0 / 2.0 5 / 2
5.0 / 2
yields 2.5 (both double)yields 2 (both int)
yields 2.5 (mixed)but
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;
i = d; Can put an integer into a double but
not a double into an integer.
-- Syntax error because i is less inclusive than d.
-- 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.
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, //declare four
string lastName, //variables fullName, lastThenFirst;
firstName = “Debbie”; //initialize firstName
lastName = “Klipp”; //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
b) “number ” + (3 + 4)
c) “number ” + 3 * 4
d) 3 + 4 + “ number”
number 34
number 7
number 12
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 Syntax: _____________ Answer:
_______ Find the remainder of 8.95 / 1.1 Syntax: _____________ Answer:
_______ (double) 15 / 6 ______________________ (double) (15 / 6) ______________________ (double) 15 / 6 + 0.6 ______________________ (int) ((double) 15 / 6 + 0.6) ______________________
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 Syntax: Answer: Find the remainder of 8.95 / 1.1 Syntax: Answer: (double) 15 / 6 (double) (15 / 6) (double) 15 / 6 + 0.6 (int) ((double) 15 / 6 + 0.6)
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();
22.52.52.5 8 % 3 2 8.95 % 1.1 .152.52.03.13
Age 28Age 10Age 1610 Age 8