Download II. Types of primitive data values

yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Chapter 3. Numerical Data
Reference: Chapter 3, and powerpoint presentation from publisher.
Objectives of this chapter:
- Understand the type of numerical data
- Difference between primitive data (variable) and object
- Understand arithmetic expressions (operations due to different types)
- Get to know math class, GregorianCalendar class, DecimalFormat class,
input and output with and System.out
I. Introduction
Major challenge: “=” is actually assignment rather than equality.
II. Types of primitive data values
II.1. Variable has three properties:
- A memory location to store the value
- The type of data stored in the memory location, and
- The name used to refer to the memory location
Six numerical data types: byte, short, int, long, float, and double.
II.2. Constant: If we want the value to remain the same, we use a constant.
final double PI
= 3.14159
final int
The constant PI is called a named constant or symbolic constant. The
second type of constant is called a literal constant – the actual value.
What is the type of literal constant 345.79? It is double. So, the following
will create compilation error:
float number;
number = 345.79;
This is because the variable (float) has lower precision than that of the constant
(double). To correct this error, we have to write the assignment statement as:
number = (float) 345.79; or number = 345.79f;
final double SPEED_OF_LIGHT = 3.0E+10D
(literal constant suffixed by f, F, d or D).
1 of 5
II.3. Primitive vs Reference
Numerical data are called primitive data types
Objects are called reference data types, because the contents are addresses
that refer to memory locations where the objects are actually store.
III. Arithmetic Expressions
Assignment statement, precedence rules, (implicit and explicit) type casting.
To input a numerical value, we have to first input a String object and then convert
it to a numerical representation. We call such operation a type conversion.
To perform the necessary type conversion in Java, we use different utility classes
called wrapper classes. The name wrapper derives from the fact that these
classes surround, or wrap, primitive data with useful methods.
int num = Integer.parseInt(“14”);
String str = JOptionPane.showInputDialog(null, “Enter age:”);
int age = Integer.parseInt(str);
String radiusStr = JOptionPane.showInputDialog(null, “Enter radius:”);
Double radius = Double.parseDouble(radiusStr);
IV. Useful Classes
Useful classes:
System.out ( need to use together with IOException, so import; or, use it together with Scannar)
Scanner (import java.util.*)
DecimalFormat (import java.text.*)
Math class
GregorianCalender (import java.util.*)
See/Demo of examples come with your textbook:
- (page 99) ….use Wrapper classes (Integer.parseInt(str))
- (page 105) ….use DecimalFormat
- (page 112) ….use Scanner
- Ch3PoleHeight (page 116) ….use Math class
- Ch3SelectWinner (page 118) ….use Math.random()
- Ch3TestCalendar (page 121) ….use GregorianCalendar()
2 of 5
IV.1. System.out, and Scanner
System.out refers to a precreated PrintStream object we use to output muyltiple
lines of text to the standard output window. The actual appearance of the
standard output window depends on which Java tool we use.
e.g. System.out.print(“x + x =” + ans);
System.out.println( “x + x =” + ans);
Analogous to System.out for output, we have for input. We call the
technique to input data using standard input. We also use the term
console input to refer to standard input.
Using for input is slightly more complicated than using System.out for
output. is an instance of the InputStream class that provides only a
facility to input 1 byte at a time with its read method. However, multiple bytes are
required to represent a primitive data type or a string (for example, 4 bytes is
used to store an int value). So to input primitive data values or strings easily, we
need an input facility to process multiple bytes as a single unit.
Try out the following program in DrJava to see:
class UseSystemIn {
public static void main ( String[] args ) {
int i =;
and also try out:
class UseSystemIn2 {
public static void main (String[ ] args) {
try {
int i =;
catch (IOException e) {
System.out.println(“Unable to read from”);
The most common way of using for input is to associate a Scanner
object to the object. A Scanner object will allow us to read primitive
data type values and strings. First we create a new Scanner object by passing as an argument:
3 of 5
Import java.util.*;
Scanner scanner;
scanner = new Scanner (;
Once we have a Scanner object, then we can call its nextInt method to input an
int age;
Age = scanner.nextInt();
Or other types of numeric data, such as:
Double dNum1;
dNum1 = scanner.nextDouble();
Note that reading a string input is slightly more complicated than reading
numerical data. Compare the following:
System.out.print (“Enter your name: “);
name =;
The above does not get all the words in a name. To remedy the problem,
Scanner scanner = new Scanner (;
String lineSeparator = System.getProperty(“line.separator”);
System.out.print(“Enter your name: “);
String name =;
IV.2. DecimalFormat
Import java.text.*;
DecimalFormat df = DecimalFormat(“0.000”);
Double radius = 0.123456;
System.out.println(“Radius : “ + df.format(radius)) ;
IV.3. Math Class
doube alpha = 10.0;
// angle
doube alphaRad = Math.toRadians(alpha);
double height = Math.sqrt(Math.sin(alphaRad));
// select the winner
int min = startingNumber + 1;
int max = startingNumber + count;
winningNumber = (int)(Math.floor(math.random() * (max – min +1)) + min);
System.out.println(“The Winning Number is “ + winningNumber);
4 of 5
IV.3. GregorianCalendar Class
Import java.util.*;
GregorianCalendar cal = new GregorianCalendar();
System.out.println(“ “);
“ + cal.get(Calendar.YEAR));
“ + cal.get(Calendar.MONTH));
“ + cal.get(Calendar.DATE));
“ + cal.get(Calendar.MINUTE));
GregorianCalendar independenceDay = new GregorianCalendar(1965,
Calendar.AUGUST, 9);
SimpleDateFormat sdf = new SimpleDateFormat(“EEEE”);
JOptionPane.showMessageDialog(null, “Our independence day was on “
+ sdf.format(independenceDay.getTime()));
V. Sample Development
Problem statement: Write a loan calculator program that computes both
monthly and total payments for a given loan amount, annual interest rate, and
loan period.
Objects consideration – design – code – test
Objects consideration: JOptionPane, System.out, Math classes.
One way of design: input, process, output.
L R
Monthly payment =
 1 
1 
 1 R 
where L is the loan amount, R is the monthly interest rate, and N is the
number of payments. The monthly rate R is expressed in a fractional value, for
example, 0.01 for 1 percent monthly rate.
We do incremental coding for input, output, and then process. In this approach,
we test besides coding as we go along. Also, at the end of this, we may need to
do a more comprehensive understanding of monthly payment, total
payment….(number of significant digits etc.)
5 of 5