Unit 1 Primitive Types
Unit 1 Primitive Types
https://longbaonguyen.github.io
Java
Many of the apps you use in an Android phone or tablet are also
written in Java. Java is used worldwide to create software that
we all use.
2
Java
Java is a programming language, which means that we can
use Java to tell a computer what to do.
The source file is something humans can read and edit, and the
class file is code that a computer can understand and can run.
3
Java Terminology
• class:
(a) A module or program that can contain executable
code.
(b) A description of a type of objects. (Animal class,
Human class, Employee class, Car class)
6
File naming
The name of the class has to match up with the name of the file.
For example, the class below is called Main therefore the name
of the file is Main.java. The main class must be called Main.java.
(in other IDEs, you can pick any name.)
7
Printing
8
Find the errors.
pooblic class Errors
public static void main(String args){
System.out.print("Good morning! ")
system.out.print("Good afternoon!);
System.Print "And good evening!";
9
Corrected!
10
Strings
• string: A sequence of characters to be printed.
– Starts and ends with a " quote " character.
• The quotes do not appear in the output.
• Restrictions:
– May not span multiple lines.
"This is not
a legal String."
12
Comments example
/* Alex Student, APCSA B2, Fall 2021
This program prints lyrics about the most viewed song. */
// second verse
System.out.println(“Mommy Shark, doo doo doo doo doo doo ");
System.out.println(“Mommy Shark");
// third verse
System.out.println(“Daddy Shark, doo doo doo doo doo doo ");
System.out.println(“Daddy Shark");
}
}
13
Indent Nicely!
The code above will compile and run correctly. Java ignore whitespaces.
But it is very hard to read, please make an effort to indent nicely!
Output:
I am Sam. Sam I am. I do not like them, Sam-I-am.
I do not like green eggs and ham.
15
Data Types
Data types can be categorized as either primitive or
reference.
The primitive data types used in this course define the set of
operations for numbers and Boolean(true or false) values.
17
Receipt example
What's bad about the following code?
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
System.out.println("Subtotal:");
System.out.println(38 + 40 + 30);
System.out.println("Tax:");
System.out.println((38 + 40 + 30) * .08);
System.out.println("Tip:");
System.out.println((38 + 40 + 30) * .15);
System.out.println("Total:");
System.out.println(38 + 40 + 30 +
(38 + 40 + 30) * .08 +
(38 + 40 + 30) * .15);
}
}
– The subtotal expression (38 + 40 + 30) is repeated
– So many println statements
– We will use variables to solve the above problems. 18
Variables
19
Declaration
• variable declaration: Sets aside memory for storing a value.
– Variables must be declared before they can be used.
• Syntax:
type name;
• The name is an identifier.
x
– int x;
20
Assignment
• assignment: Stores a value into a variable.
– The value can be an expression; the variable stores its result.
• Syntax:
name = expression;
x 3
– int x;
x = 3;
x = 4 + 7;
System.out.println("now x is " + x); // now x is 11
22
Declaration/initialization
• A variable can be declared/initialized in one statement.
• Syntax:
type name = value;
myGPA 3.95
– double myGPA = 3.95;
– int x = (12 - 3) * 2; x 18
23
Assignment and algebra
• Assignment uses = , but it is not an algebraic equation.
24
Multiple Variables
• Multiple variables of the same type can be declared and
initialized at the same time.
• Syntax:
25
Assignment and types
• A variable can only store a value of its own type.
– int x = 2.5; // ERROR: incompatible types
26
Compiler errors
• Order matters.
– int x;
7 = x; // ERROR: should be x = 7;
• A variable can't be used until it is assigned a value.
– int x;
System.out.println(x); // ERROR: x has no value
• You may not declare the same variable twice.
– int x;
int x; // ERROR: x already exists
– int x = 3;
int x = 5; // ERROR: x already exists
• Output:
Your grade was 83.2
There are 65 students in the course.
28
Receipt question
Improve the receipt program using variables.
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
System.out.println("Subtotal:");
System.out.println(38 + 40 + 30);
System.out.println("Tax:");
System.out.println((38 + 40 + 30) * .08);
System.out.println("Tip:");
System.out.println((38 + 40 + 30) * .15);
System.out.println("Total:");
System.out.println(38 + 40 + 30 +
(38 + 40 + 30) * .15 +
(38 + 40 + 30) * .08);
}
}
29
Receipt answer
public class Receipt {
public static void main(String[] args) {
// Calculate total owed, assuming 8% tax / 15% tip
int subtotal = 38 + 40 + 30;
double tax = subtotal * .08;
double tip = subtotal * .15;
double total = subtotal + tax + tip;
30
Bell Work
• Make a TempConverter class that calculates the temperature
and gives the following output:
Celsius Temperature: 24
Fahrenheit Equivalent: 75.2
31
Task
• Revise the TempConverter class so that it will take a user input
to give the converted temperature in Fahrenheit!
32
Task
• Revise the TempConverter class so that it will take a user input
to give the converted temperature in Fahrenheit!
33
Type boolean
• boolean: A logical type whose values are true and false.
34
final
• The keyword final can be used in front of a variable
declaration to make it a constant that cannot be changed.
Constants are traditionally capitalized.
35
Naming variables
The name of the variable should describe the data it holds. A name
like score helps make your code easier to read.
36
Naming variables
The convention in Java and many programming languages is to always start a
variable name with a lower case letter and then uppercase the first letter of
each additional word.
Variable names can not include spaces so uppercasing the first letter of
each additional word makes it easier to read the name. Uppercasing the first
letter of each additional word is called camel case.
38
Input and System.in
39
Scanner syntax
– Example:
Scanner input = new Scanner(System.in);
40
Scanner methods
Method Description
nextInt() reads an int from the user and returns it
nextDouble() reads a double from the user
next() reads a one-word String from the user
nextLine() reads a one-line String from the user
Adapted from:
1) Building Java Programs: A Back to Basics Approach
by Stuart Reges and Marty Stepp
2) Runestone CSAwesome Curriculum
This work is licensed under the
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
https://longbaonguyen.github.io
Escape Sequence
• / : forward slash (imagine someone leaning forward)
• : backward slash (think someone leaning back)
45
Bell Work Activity
• Select one or two articles from the following website:
– https://technews.acm.org/
– After 5 minutes, share among table:
• “What was the most interesting part of your article?”
46
Bell Work Question
Using what we’ve learned with the Scanner Class, create a program
that ask the user:
–“How many hours did you sleep today?”
–Allow the user to enter a number
–If the student enters 7 or more, then tell the user:
slept well: true
–Or if less than 7, then:
slept well: false
Hint: Use boolean to test true or false
47
Bell Work Question
• What do the following expressions equal to?
1 - 2 - 3 -4 or 0
1 + 3 * 4 16 or 13
6 + 8 / 2 * 3 18 or 7.333333333333333333
(1 + 3) * 4
1+3 * 4-2
48
Unit 1: Primitive Types
Arithmetic Operations
Adapted from:
1) Building Java Programs: A Back to Basics Approach
by Stuart Reges and Marty Stepp
2) Runestone CSAwesome Curriculum
This work is licensed under the
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
https://longbaonguyen.github.io
Arithmetic operators
• expression: A value or operation that computes a value.
• Examples: 1 + 4 * 5
(7 + 2) * 6 / 3
• operator: Combines multiple values or expressions.
– + addition
– - subtraction (or negation)
– * multiplication
– / division
– % modulus (a.k.a. remainder)
50
Integer division with /
• When we divide integers, the remainder is excluded.
– 14 / 4 is 3, not 3.5
– What would 45 / 10 give us how about 10/3
• More examples:
– 32 / 5 is 6
– 84 / 10 is 8
– 156 / 100 is 1
51
Integer remainder with %
• The % operator computes the remainder from integer division.
– 14 % 4 is 2
– 218 % 5 is 3
3 43
4 ) 14 5 ) 218
12 20
2 18
15
3
• Applications of % operator:
– Obtain last digit of a number: 230857 % 10 is 7
– Obtain last 4 digits: 658236489 % 10000 is 6489
– See whether a number is odd: 7 % 2 is 1, 42 % 2 is 0
52
% Example
public static void main(String[] args){
System.out.println(45 % 6);
System.out.println(2 % 2);
System.out.println(8 % 10);
System.out.println(11 % 0);
System.out.println(-21 % 4); // probably not on AP
System.out.println(21 % -4); // probably not on AP
}
Output:
3
0
8
ArithmeticException
-1
1
53
Precedence
• precedence: Order in which operators are evaluated.
– Generally operators evaluate left-to-right.
1 - 2 - 3 is (1 - 2) - 3 which is -4
System.out.println(Math.round(totPrice*100)/100.0);
System.out.printf("%f", totPrice);
}
}
57
Computation Lab:
Problem Statement
Suppose you are asked to write a program that simulates a vending machine. A customer selects
an item for purchase and inserts a bill into the vending machine. The vending machine
dispenses the purchased item and gives change. We will assume that all item prices are
multiples of 25 cents, and the machine gives all change in dollar coins and quarters. Your task is
to compute how many coins of each type to return.
Declare variables pennies, dollars, and cents
If you’re done, could you also add dime, nickels, and pennies to return to user if the item
price was 212 cents.
58
Check with neighbor
•1 * 2 + 3 * 5 % 4 1 + 8 % 3 * 2 - 9
• \_/ \_/
| |
2 + 3 * 5 % 4 1 + 2 * 2 - 9
• \_/ \___/
| |
2 + 15 % 4 1 + 4 - 9
• \___/ \______/
| |
2 + 3 5 - 9
• \________/
\_________/
| |
5 -4
59
How about with Real
number
• 2.0 * 2.4 + 2.25 * 4.0 / 2.0
• \___/
|
4.8 + 2.25 * 4.0 / 2.0
• \___/
|
4.8 + 9.0 / 2.0
• \_____/
|
4.8 + 4.5
• \____________/
|
9.3
60
Mixing types
• When int and double are mixed, the result is a double.
– 4.2 * 3 is 12.6
0
0.3333333333333333
0.3333333333333333
0.3333333333333333
1.5 Casting and Ranges of Variables
What is Casting?
● Floating (2)
○ Float 4 bytes *These data types do not need to be
represented using objects
○ Double 8 bytes
Type casting
• type cast: A conversion from one type to another.
– To promote an int into a double to get exact division from /
– To truncate a double from a real number to an integer
• Syntax:
(type) expression
Examples:
double result = (double) 19 / 5; // 3.8
int result2 = (int) result; // 3
66
More about type casting
• Type casting has high precedence and only casts the item
immediately next to it.
– double x = (double) 1 + 1 / 2; // 1.0
– double y = 1 + (double) 1 / 2; // 1.5
67
Casting Example
public static void main(String[] args){
double x = 4 / 3;
double y = (double)(125/10);
double z = (double) 28 / 5;
System.out.println(x + “ ” + y + “ ” + z);
}
Output:
1.0 12.0 5.6
68
Round to the nearest integer
• casting can be used to round a number to its nearest integer.
69
1.4 Compound Assignment Operators
+=
-=
*=
/=
%=
++
--
Increment and decrement
shortcuts to increase or decrease a variable's value by 1
int x = 2;
x++; // x = x + 1;
// x now stores 3
double gpa = 2.5;
gpa--; // gpa = gpa - 1;
// gpa now stores 1.5
71
Modify-and-assign
shortcuts to modify a variable's value
x += 3; // x = x + 3;
gpa -= 0.5;
// gpa = gpa – 0.5;
number *= 2;
// number = number * 2;
72
Code Tracing
What are the values of x, y and z after tracing through the
following code?
int x = 0;
int y = 5;
int z = 1;
x++;
y -= 3;
z = x + z;
x = y * z;
y %= 2;
z--;
Answer: x = 4, y = 0, z = 1
73
Practice
Practice
Practice
Practice
Write a program that can determine whether a user input value
is even or odd. It should out even if the number the user typed
in was even or output odd if it was not even.
Hint: what variable type do you need, what statement can you
use?
77
Lab 1
78
Lab 1
Average =78.33333333333333
Variance = 1.5555555555555556
Standard deviation = 1.247219128924647
79
Lab 1
Create a class and follow the comments below to write a program that compute
some statistics.
81