3 - Elementary Programming 2_Data Types, Operators, Type Casting
3 - Elementary Programming 2_Data Types, Operators, Type Casting
Part (2)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
1
Introduction
Thislecture will cover Java data types, the
various operator types in Java, and how to
use the scanner class to obtain console
input. As a result, we will understand Java's
conversion concept and learn how to avoid
common errors in elementary programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
2
Learning Objectives
1. Understand the concept of data types.
2. obtain input from the console using the scanner class.
3. Understand the Different types of Operators in Java
4. Understand the concept of conversion in Java.
5. Avoid common errors and pitfalls in elementary programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
3
outlines
• Data Types
• Reading Input from the Console
• Java Operators
• Arithmetic Expressions
• Conversion Rules
• Common Errors and Pitfalls
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
4
Data Types
As explained in the previous slides, a variable in
Java must be a specified data type:
Data types are divided into two groups:
– Primitive data types - includes byte, short, int, long,
float, double, boolean and char
– Non-primitive data types - such as String, Arrays and
Classes (you will learn more about these in a later
chapter)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
5
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has no additional methods.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
7
Numerical Data Types
name range Storage Size
Byte -27to27 -1(-128to127) 8-bit signed
Short -215 to 215 - 1 (-32768 to 16-bit signed
32767)
Int -231 to 231 - 1 (-2147483648 to 32-bit signed
2147483647)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
8
Number Literals
A literal is a constant value that appears directly in the
program. For example, 34, 1,000,000, and 5.0 are literals
in the following statements:
int i = 34;
long x = 1000000L;
float f = 5.75f;
double d = 19.99d;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
9
Integer Literals
An integer literal can be assigned to an integer variable as
long as it can fit into the variable. A compilation error
would occur if the literal were too large for the variable to
hold. For example, the statement byte b = 1000 would
cause a compilation error, because 1000 cannot be stored
in a variable of the byte type.
An integer literal is assumed to be of the int type, whose
value is between -231 (-2147483648) to 231–1
(2147483647). To denote an integer literal of the long
type, append it with the letter L or l. L is preferred because
l (lowercase L) can easily be confused with 1 (the digit
one).
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
10
Floating-Point Literals
Floating-point literals are written with a decimal
point. By default, a floating-point literal is treated
as a double type value. For example, 5.0 is
considered a double value, not a float value. You
can make a number a float by appending the letter f
or F, and make a number a double by appending
the letter d or D. For example, you can use 100.2f
or 100.2F for a float number, and 100.2d or 100.2D
for a double number.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
11
double vs. float
The precision of a floating point value indicates how many digits the value can have after
the decimal point. The precision of float is only six or seven decimal digits,
while double variables have a precision of about 15 digits. Therefore it is safer to
use double for most calculations.
float f1 = 35e3f;
double d1 = 12E4d;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
13
Data Type (Cont..)
A Boolean data type is declared with the boolean keyword
and can only take the values true or false.
The char data type is used to store a single character. The
character must be surrounded by single quotes, like 'A' or 'c'.
– Alternatively, you can use ASCII values to display certain
characters:
char a = 65, b = 66, c = 67;
The String data type is used to store a sequence of characters
(text). String values must be surrounded by double quotes.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
14
Non-Primitive Data Types
Non-primitive data types are called reference types
because they refer to objects. The main difference
between primitive and non-primitive data types are:
– Primitive types are predefined (already defined) in Java.
Non-primitive types are created by the programmer and is
not defined by Java (except for String).
– Non-primitive types can be used to call methods to
perform certain operations, while primitive types cannot.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
15
Non-Primitive Data Types (Cont..)
– A primitive type has always a value, while non-primitive
types can be null.
– A primitive type starts with a lowercase letter, while non-
primitive types starts with an uppercase letter.
– The size of a primitive type depends on the data type,
while non-primitive types have all the same size.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
16
Exercise:
Add the correct data type for the following variables:
____myNum = 9;
____ myDoubleNum = 8.99;
____ myLetter = 'A';
____ myBool = false;
____ myText = "Hello World";
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
17
Reading Input from the Console
1. Create a Scanner object
Scanner input = new Scanner(System.in);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
18
Reading Numbers from the
Keyboard
Scanner input = new Scanner(System.in);
int value = input.nextInt();
method description
nextByte() Reads an integer of the byte type
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
19
Java Operators
Operators are used to perform operations on
variables and values. Examples:
int x = 100 + 50;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
20
Java Operators (Cont..)
Java
divides the operators into the following
groups:
– Arithmetic operators
– Assignment operators
– Comparison operators
– Logical operators
– Bitwise operators
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
21
Arithmetic Operators
Operator Name Description Example
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
22
Integer Division
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
23
Remainder Operator
Remainder is very useful in programming. For example, an
even number % 2 is always 0 and an odd number % 2 is always
1. So you can use this property to determine whether a number
is even or odd. Suppose today is Saturday and you and your
friends are going to meet in 10 days. What day is in 10
days? You can find that day is Tuesday using the following
expression:
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
24
Increment and
Decrement Operators
Operator name Description Example (assume i = 1)
++var preincrement Increment var by 1, and int j = ++i;
use the new var value in // j is 2, i is 2
the statement
var++ postincrement Increment var by 1, but int j = i++;
use the // j is 1, i is 2
original var value in the
statement
--var predecrement Decrement var by 1, and int j = --i;
use the new var value in // j is 0, i is 0
the statement
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
25
Increment and
Decrement Operators (Cont..)
int i = 10;
int newNum = 10 * (++i); Same effect as i = i + 1;
int newNum = 10 * i;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
26
Increment and
Decrement Operators (Cont..)
Using increment and decrement operators makes
expressions short, but it also makes them complex and
difficult to read. Avoid using these operators in expressions
that modify multiple variables, or the same variable for
multiple times such as this: int k = ++i + i.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
27
Java Assignment Operators
Assignment operators are used to assign values to
variables. In the example below, we use the
assignment operator (=) to assign the value 10 to a
variable called x: int x = 10;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
28
Java Assignment Operators
(Cont..)
Operator Example Same as
= X=5 X=5
+= X += 3 X=x+3
-= X -= 3 X= x - 3
*= X *= 3 X=x*3
/= X /= 3 X= x/3
%= X %= 3 X=x%3
&= X &= 3 X= x & 3
|= X|=3 X = x |3
^= X ^= 3 X=x^3
>>= X >> = 3 X = x >> 3
<<= X << =3 X = x << 3
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
29
Java Comparison Operators
Comparison operators are used to compare two values:
Operator Name example
== equal to X == y
!= not equal to X != y
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
30
Java Logical Operators
! Logical not Reverse the result , !(X < 5 && x < 10)
returns false if the
result is true
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
31
Exercise:
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
32
Problem: Displaying Time
Write a program that obtains minutes and
remaining seconds from seconds.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
33
NOTE
Calculations involving floating-point numbers are
approximated because these numbers are not stored
with complete accuracy. For example,
System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not 0.5, and
System.out.println(1.0 - 0.9);
displays 0.09999999999999998, not 0.1. Integers are
stored precisely. Therefore, calculations with integers
yield a precise integer result.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
34
Exponent Operations
System.out.println(Math.pow(2, 3));
// Displays 8.0
System.out.println(Math.pow(4, 0.5));
// Displays 2.0
System.out.println(Math.pow(2.5, 2));
// Displays 6.25
System.out.println(Math.pow(2.5, -2));
// Displays 0.16
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
35
Arithmetic Expressions
is translated to
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
36
How to Evaluate an Expression
Though Java has its own way to evaluate an
expression behind the scene, the result of a Java
expression and its corresponding arithmetic
expression are the same. Therefore, you can safely
apply the arithmetic rule for evaluating a Java
expression. 3 + 4 * 4 + 5 * (4 + 3) - 1 (1) inside parentheses first
3+4*4+5*7–1
(2) Multiplication
3 + 16 + 5 * 7 – 1
(3) Multiplication
3 + 16 + 35 – 1
(4) Addition
19 + 35 – 1
(5) Addition
54 – 1
(6) subtraction
53
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
37
Problem: Converting Temperatures
Write a program that converts a Fahrenheit degree
to Celsius using the formula:
celsius ( 95 )( fahrenheit 32)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
38
Problem: Displaying Current Time
Write a program that displays current time in GMT in the
format hour:minute:second such as 1:45:19.
The currentTimeMillis method in the System class returns
the current time in milliseconds since the midnight, January
1, 1970 GMT. (1970 was the year when the Unix operating
system was formally introduced.) You can use this method
to obtain the current time, and then compute the current
second, minute, and hour as follows.
Elapsed
time
time
Unix Epoch
01-01-1970 Current Time
00:00:00 GMT System.currentTimeMills()
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
39
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
40
Conversion Rules
When performing a binary operation involving two
operands of different types, Java automatically
converts the operand based on the following rules:
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
41
Type Casting
Type casting is when you assign a value of one primitive data
type to another type.
In Java, there are two types of casting:
– Widening Casting (automatically) - converting a smaller type to a larger type
size
byte -> short -> char -> int -> long -> float -> double
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
42
Type Casting
Implicit casting (done automatically)
double d = 3; (type widening)
range increases
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
43
Widening Casting
Widening casting is done automatically when passing a
smaller size type to a larger size type:
int myInt = 9;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
44
Narrowing Casting
Narrowing casting must be done manually by placing the
type in parentheses in front of the value:
double myDouble = 9.78d;
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
45
Problem: Keeping Two Digits After
Decimal Points
Write a program that displays the sales tax with two
digits after the decimal point.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
46
Casting in an Augmented Expression
In Java, an augmented expression of the form x1 op=
x2 is implemented as x1 = (T)(x1 op x2), where T is
the type for x1. Therefore, the following code is
correct.
int sum = 0;
sum += 4.5; // sum becomes 4 after this statement
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
48
Problem: Monetary Units
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
49
Common Errors and Pitfalls
Common Error 1: Undeclared/Uninitialized
Variables and Unused Variables
Common Error 2: Integer Overflow
Common Error 3: Round-off Errors
Common Error 4: Unintended Integer Division
Common Error 5: Redundant Input Objects
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
51
Common Error 2: Integer Overflow
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
52
Common Error 3: Round-off Errors
System.out.println(1.0 - 0.9);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
53
Common Error 4: Unintended Integer
Division
int number1 = 1; int number1 = 1;
int number2 = 2; int number2 = 2;
double average = (number1 + number2) / 2; double average = (number1 + number2) / 2.0;
System.out.println(average); System.out.println(average);
(a) (b)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
54
Common Pitfall 1: Redundant Input
Objects
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int v1 = input.nextInt();
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
56
References
Y. Daniel Liang, 2019, Intro to Java Programming, Comprehensive Version, Student Value Edition
12th Edition. Pearson, ISBN-10 : 0136520154 ISBN-13: 978-0136520153.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
57