Post on 19-Jul-2020
JAVA Ch. 4 Variables and Constants
© 2007 Lawrenceville Press Slide 1
Warm up/Introduction int A = 13; int B = 23; int C; C = A+B; System.out.print(“The answer is” +C);
© 2007 Lawrenceville Press
Slide 2
Declaring and using variables
© 2007 Lawrenceville Press
Slide 3
Declaring Variables � Variable – name for a value stored in
memory. � Variables must be “declared” before they
are used.
� Variable declarations take the form: <data type> <variable name/identifier>;
int length;
© 2007 Lawrenceville Press
Slide 4
Using Variables � An assignment statement is formed with
the variable type and name on the left side of an equal sign; and the value it is to receive on the right side of the equal sign.
int A = 40;
� Operator – the equal sign (=) � Literal – the value to the right of the equal
sign.
© 2007 Lawrenceville Press
Slide 5
Chapter 4
Assignment Statement
© 2007 Lawrenceville Press
Slide 6
An assignment statement gives a value to a variable. Assignment can take several forms: x = 5; a literal (5) is assigned to x x = y + 2; the value of an expression (y + 2) is
assigned to x x = z; the value of another variable (z) is
assigned to x
Using Variables int A = 10; int A;
� What is the difference between the two assignments statements above?
� If a variable does not include a literal, that variable’s value is going to change as we navigate its class.
© 2007 Lawrenceville Press
Slide 7
Chapter 4 Variable Assignment
© 2007 Lawrenceville Press
Slide 8
A variable can store only one value at any time.
int x; x = 5; x = 10;
x
5 10
Types of Variables
© 2007 Lawrenceville Press
Slide 9
Chapter 4
Primitive Data Types
© 2007 Lawrenceville Press
Slide 10
Type Storage Required int 4 bytes double 8 bytes char 2 bytes boolean 1 bit
Notes: int – integer double – decimal number char – character boolean – true or false
Outputting variable values
© 2007 Lawrenceville Press
Slide 11
Outputting Variables � When outputting variables we must
concatenate the value of the variable to a string. To do this we put a (+) in front of the variable name in our output statement.
int s = 90; System.out.print(“My score is ” +s “out of 100.”); My score is 90 out of 100.
© 2007 Lawrenceville Press
Slide 12
Current Class Format
© 2007 Lawrenceville Press
Slide 13
/*Name *Date *Class *Period *Class name */ public class ClassName {
public static void main(String[] args) { int A = 10; int B = 20; int C; C= A + B; System.out.print("this is my score "+C); }
}
© 2007 Lawrenceville Press
Slide 14
Variable Initialization
Program statements
/*Name *Date *Class *Period *Class name */ public class ClassName {
public static void main(String[] args) { int A = 10; int B = 80; int C; C= A + B; System.out.print("this is my score "+C); }
}
© 2007 Lawrenceville Press
Slide 15
Practice -
© 2007 Lawrenceville Press
Slide 16
Creating a Ch. 4 Project � Create a new project. Call it… � First initial, last name Chapter 4
� BBarrett Chapter 4
© 2007 Lawrenceville Press
Slide 17
Practice - � In your chapter 4 project, create a class titled:
RectanglePerimeter � We will do this together
� In your chapter 4 project, create a class titled: DistancePtOne � Pg. 79 � You are responsible for completing tis on your
own. Mr. Barrett will help you if needed.
© 2007 Lawrenceville Press
Slide 18
Java Packages
© 2007 Lawrenceville Press
Slide 19
Java Packages � Java has tools that are available to the
programmer. They are called packages, and Java comes ready equipped for them to be used.
� These classes contain general utility classes, and special purpose packages.
� The most fundamental packages is the… Java.util.*;
package
© 2007 Lawrenceville Press
Slide 20
Java Packages: Receiving input from your end-user
© 2007 Lawrenceville Press
Slide 21
Java Packages � The first package we will introduce will be
the: import java.util.Scanner;
Package. This is the ‘import statement’ used to make the package accessible to a method/project.
© 2007 Lawrenceville Press
Slide 22
Java Packages � Instantiation – after importing our ready-
made package, we must initialize the package. This process is called instantiation.
� The following statement is used to initialize
our scanner:
Scanner input = new Scanner(System.in);
© 2007 Lawrenceville Press
Slide 23
/* *Name *Date *Class *Period *Class name */ public class ClassName {
public static void main(String[] args) {
} } © 2007 Lawrenceville Press
Slide 24
Variable Initialization
Program statements
Package Instantiation
Class importation
import java.util.Scanner;
/* *Name *Date *Class *Period *Class name */ public class ClassName {
public static void main(String[] args) {
-
} } © 2007 Lawrenceville Press
Slide 25
int x = 10; int y = 5; int c;
Program statements
Scanner input = new Scanner(System.in);
Receiving Data From your end user
© 2007 Lawrenceville Press
Slide 26
§ Part of the java.util.Scanner package
§ To receive data from the end user, the following methods are required.
§ Methods include: variableName = input.nextInt(); variableName = input.nextLine(); variableName = input.next(); variableName = input.nextDouble(); variableName = input.nextBoolean(); Input.close();
Receiving Data From your end user
© 2007 Lawrenceville Press
Slide 27
Methods include: • input.nextInt(); - integer
• input.next(); - string
• input.nextDouble(); - decimal
• input.nextBoolean(); - boolean
• input.close(); - closes the input stream
Receiving data example: import java.util.Scanner; int x, y, z;
Scanner input = new Scanner(System.in); System.out.print("Enter your first value: "); x = input.nextInt(); System.out.print("Enter your second value: "); y = input.nextInt(); input.close(); z=x+y;
System.out.print("The sum of your numbers is "+z);
© 2007 Lawrenceville Press
Slide 28
Abstract Data Types
© 2007 Lawrenceville Press
Slide 29
Primitive data types � We already discussed primitive data
types, i.e., integers, doubles, characters, and Booleans; but there is another type of data that we must cover…
© 2007 Lawrenceville Press
Slide 30
Abstract Data Types
� Abstract data type – A class. A data type that can store data and methods.
� Method – A named set of statements that
perform a single, well-defined task. � Object – A variable declared with a class.
© 2007 Lawrenceville Press
Slide 31
Creating a new object… � Creating a new object is called instantiation. In
addition to declaring a variable to refer to the object, the object must be created and initialized in a statement that takes the form:
<class> <variable name> = new <class>(<arguments>);
© 2007 Lawrenceville Press
Slide 32
Abstract Data Types � Where have we seen this before?
<class> <variable name> = new <class>(<arguments>);
Scanner input = new Scanner(System.in);
Our scanner class is the first abstract data type you have been exposed to.
© 2007 Lawrenceville Press
Slide 33
Chapter 4
Abstract Data Types
© 2007 Lawrenceville Press
Slide 34
A variable declared with a class is called an object. For example, the object spot is type Circle:
Circle spot = new Circle(4);
spot getRadius() area()
Practice
© 2007 Lawrenceville Press
Slide 35
Practice
© 2007 Lawrenceville Press
Slide 36
� In your chapter 4 project, create a class titled: DistancePtTwo � Page 82 (bottom) � You are responsible for completing this on your
own. Mr. Barrett will help you if needed.
Algorithms
© 2007 Lawrenceville Press
Slide 37
Algorithms
� Algorithm – A set of steps that outline how to solve a problem.
© 2007 Lawrenceville Press
Slide 38
Algorithms � Algorithm for DistancePtTwo Class
1. Set class template 2. Initialize our variables 3. Initialize our scanner 4. Prompt end user to enter our needed
values 5. Calculate the total distance 6. Output total distance
© 2007 Lawrenceville Press
Slide 39
Numeric Expressions
© 2007 Lawrenceville Press
Slide 40
Numeric Expressions � A numeric expression contains at least
one operand (a value or primitive variable), and my contain operators.
© 2007 Lawrenceville Press
Slide 41
Numeric Expressions � Our Operators –
� + : addition � - : subtraction � / : division � % : modulus division (the remainder) � * : multiplication � = : equals � > : greater than � < : less than
© 2007 Lawrenceville Press
Slide 42
Numeric Expressions � Our Operators –
� >= : greater than or equal to � <= : less than or equal to � != : not equal to…
© 2007 Lawrenceville Press
Slide 43
Chapter 4
Integer Division
© 2007 Lawrenceville Press
Slide 44
Integer division (/) is performed when both operands are integers. Only the integer portion of the quotient is returned:
Chapter 4
Real Division
© 2007 Lawrenceville Press
Slide 45
Real division (/) is performed when one or both operands are type double. The entire quotient, including the decimal portion is returned: double result; result = 20.0/7.0; //result is 2.857
Chapter 4
Modulus Division
© 2007 Lawrenceville Press
Slide 46
Modulus division (%) returns the remainder of a division operation:
� 7 % 20 = 7 (zero with a remainder of seven.)
� 7 % ? = (a number between 0 and 6)
� 100 % ? = (a number between 0 and 99)
© 2007 Lawrenceville Press
Slide 47
Chapter 4
Modulus Division
Chapter 4 Operator Precedence
© 2007 Lawrenceville Press
Slide 48
Operators in Java have the following precedence:
1. multiplication and division
2. addition and subtraction
Operators of the same precedence are evaluated in order from left to right. For example, multiplication is performed first, then division, and finally addition:
5 + 6 * 4 / 2 = 17
Chapter 4 Changing the Order of Operations
© 2007 Lawrenceville Press
Slide 49
The order in which operators are evaluated can be changed by using parentheses. For example, addition is performed first, then multiplication, and finally division:
(5 + 6) * 4 / 2 = 22
Practice
© 2007 Lawrenceville Press
Slide 50
Practice
© 2007 Lawrenceville Press
Slide 51
� In your chapter 4 project, create a class titled: DivisionOperators � Follow along with Mr. Barrett when writing this
program. Program found on pages 83 and 84.
Practice
© 2007 Lawrenceville Press
Slide 52
� In your chapter 4 project, create a class titled: Digits � Page 84. � Write the digits program.
Assignment Operators
© 2007 Lawrenceville Press
Slide 53
Chapter 4
Assignment Operators
© 2007 Lawrenceville Press
Slide 54
Operator Operation += addition and then assignment -= subtraction and then assignment *= multiplication and then assignment /= division and then assignment %= modulus division and then assignment
Assignment Operators (+) int A = 10; int B = 5;
A += B;
System.out.print(”Our output is” +A); 15 © 2007 Lawrenceville Press
Slide 55
Assignment Operators (-) int A = 10; int B = 5;
A -= B;
System.out.print(”Our output is” +A); 5 © 2007 Lawrenceville Press
Slide 56
Assignment Operators (*) int A = 10; int B = 5;
A *= B;
System.out.print(”Our output is” +A); 50 © 2007 Lawrenceville Press
Slide 57
Assignment Operators (/) int A = 10; int B = 5;
A /= B;
System.out.print(”Our output is” +A); 2 © 2007 Lawrenceville Press
Slide 58
Assignment Operators (%) int A = 17; int B = 5;
A %= B;
System.out.print(”Our output is” +A); 2 © 2007 Lawrenceville Press
Slide 59
© 2007 Lawrenceville Press
Slide 60
Type Casting
© 2007 Lawrenceville Press
Slide 61
Chapter 4 Type Casting
© 2007 Lawrenceville Press
Slide 62
Type Casting converts a number of one type to a number of a different, but compatible type. Type casting is used to:
1. make the operand types in an expression match. For example, wholeNum = (int)y * 2
2. truncate the decimal portion of a double. For example, wholeNum = (int)z
3. change the way in which a division (/) operation will be performed. For example, realDivision = (double)a / (double)b
Type Casting � Casting a double to an int truncates, or
removes, the decimal portion of the number.
© 2007 Lawrenceville Press
Slide 63
Type Casting public class TypeCasting {
public static void main(String[] args) { int a = 2; int b = 3; int c; c=(double)a*b; System.out.print(+c); }
}
© 2007 Lawrenceville Press
Slide 64
6.0
Type Casting: Truncating public class TypeCasting {
public static void main(String[] args) { double a = 2.2; double b = 3.1; double c; c=a*b; System.out.print(+(int)c); }
}
© 2007 Lawrenceville Press
Slide 65
6
Programming Errors
© 2007 Lawrenceville Press
Slide 66
Chapter 4
Programming Errors
© 2007 Lawrenceville Press
Slide 67
§ Syntax errors violate the rules of Java.
§ look for the red (X)
§ Logic errors, also called semantic errors, occur in statements that are syntactically correct, but produce undesired or unexpected results.
§ Run-time errors, also called exceptions, halt program execution at the statement that cannot be executed. One type of exception is called InputMismatchException.
§ Look for the error that appears in your console.
Practice
© 2007 Lawrenceville Press
Slide 68
Practice
© 2007 Lawrenceville Press
Slide 69
� In your chapter 4 project, create a class titled: GradeAvg1of2 � Follow along with Mr. Barrett when writing this
program. Program found on page 85.
Practice
© 2007 Lawrenceville Press
Slide 70
� In your chapter 4 project, create a class titled: TempConverter � Follow along with Mr. Barrett when writing this
program. Program found on page 85.
Number Formatting Class
© 2007 Lawrenceville Press
Slide 71
Numeric Output � The NumberFormat class is used to create
objects that format numbers. � NumberFormat objects return a string that
contains a formatted number. 1. $21.00 2. 1,342 3. 0.667 4. 33%
© 2007 Lawrenceville Press
Slide 72
Numeric Output � The number format class allows us to
output… 1. Money - $x.xx 2. Number Format – xx,xxx 3. Decimal - x.xxx 4. Percentage - xx%
© 2007 Lawrenceville Press
Slide 73
Numeric Output (step 1) � Import the NumberFormating class on line
one or two of your class.
import java.text.NumberFormat
© 2007 Lawrenceville Press
Slide 74
Numeric Output (step 2) � Initialize the format you need to use:
1. NumberFormat money = NumberFormat.getCurrencyInstance(); 2. NumberFormat number = NumberFormat.getIntegerInstance(); 3. NumberFormat decimal = NumberFormat.getNumberInstance(); 4. NumberFormat percent = NumberFormat.getPercentInstance();
© 2007 Lawrenceville Press
Slide 75
Numeric Output (step 3) � Prepare output statement:
1. System.out.print(money.format(variableName)); 2. System.out.print(number.format(variableName)); 3. System.out.print(decimal.format(variableName)); 4. System.out.print(percent.format(variableName));
© 2007 Lawrenceville Press
Slide 76
Numeric Output � The number format class allows us to
output… � Money - $x.xx - � Number Format – xx,xxx � Decimal - x.xxx � Percentage - xx%
© 2007 Lawrenceville Press
Slide 77
Practice
© 2007 Lawrenceville Press
Slide 78
� In your chapter 4 project, create a class titled: FormattingNumericOutput � Copy this class into your chapter 4 project.
(P 86)
Named Constants
© 2007 Lawrenceville Press
Slide 79
Chapter 4
Named Constants
© 2007 Lawrenceville Press
Slide 80
§ A constant is a name for a memory location that stores a value that cannot be changed from its initial assignment.
§ The keyword final is used in the variable’s declaration.
§ Constant identifiers are typically all uppercase with an underscore (_) separating words within the identifier name.
§ EX:
final int LAST_NUMBER = 100
final double PI = 3.14
Public class CircleArea{ public static void main (String[] args){ final double PI = 3.14; double radius = 5; double area;
area = PI* radius * radius; System.out.print(“The area is” +area); }
}
© 2007 Lawrenceville Press
Slide 81
Final CH 4 Programs
© 2007 Lawrenceville Press
Slide 82
Final CH 4 Programs � PizzaCost (p.99) � Change (p.100) � TimeConversion (p.101) � Sleep (p.101) � Spending (p.102)
© 2007 Lawrenceville Press
Slide 83
© 2007 Lawrenceville Press
Slide 84
Chapter 4
Java Keywords abstract double int strictfp boolean else interface super break extends long switch byte final native synchronized case finally new this catch float package throw char for private throws class goto protected transient const if public try continue implements return void default import short volatile do instanceof static While
© 2007 Lawrenceville Press
Slide 85
Chapter 4
Flowchart Symbols
© 2007 Lawrenceville Press
Slide 86
process
Chapter 4
The BirthdayGame Flowchart
© 2007 Lawrenceville Press
Slide 87