You are on page 1of 50

Chapter 3

Data Types, Constants and Variables


• Computer Memory
• Data Types
• Literals
• Identifiers
• Constants
• Variables
• Programming Style
• Case Study
1
Review Ch 2: Java Program Development

• Aim: for Problem Solving


• Program Development Process Problem Specification

1)  Problem Specification
- identify user requirements Problem Analysis
2)  Problem Analysis
- identify inputs, outputs, formulas
3)  Program Design Program Design
- write solution steps
(using pseudocode or flowcharts)
- go through dry-run to test the Implementation
solution steps using test samples
4)  Implementation
- translate solution into computer program Program Testing
5)  Program Testing
- use test samples to test the program 2
Chapter 3
Data Types, Constants and Variables
• Computer Memory
• Data Types
• Literals
• Identifiers
• Constants
• Variables
• Programming Style
• Case Study
3
Computer Memory
Memory
Address
Memory Cells
1000 0 1 0 1 0 1 1 0
1001 Content of
1 0 1 0 0 1 0 1
1002
memory
0 1 0 1 1 0 1 0
1003
1004
To store
1005
1006 program
1007 instructions
1008
1009 and
data 4
Memory and Variables
for data objects
Memory
Address

1000 0 1 0 1 0 1 1 0
1001 Content of
1 0 1 0 0 1 0 1
1002
memory
0 1 0 1 1 0 1 0
1003
Program logic
1004
10 (for variable1)
1005 DataType Variable Value
Memory
1006 20 (for variable2) int variable1=10;
To store 1007
1008 int variable2=20;
data
1009 30 (for variable3) int variable3;
variable3 = variable1 + variable2;
5
….
Chapter 3
Data Types, Constants and Variables
• Computer Memory
• Data Types
• Literals
• Identifiers
• Constants
• Variables
• Programming Style
• Case Study
6
Data Types
• A program needs to work with data.
• A data object is of a certain type that requires the
specified memory storage size. The data types in Java
are
- Primitive Data Types Why Variables & Data Type?
- Reference Data Types
 
• A data object in a Java program can be
- a constant
Declared with Data Type
- a variable

Java reserves the necessary data storage locations


depending on the data type of the data object.
7
Data Types
Array Type

String
Reference Types Class Types
(Class Type)

Interface Type

Data Types double


Floating-point
Types
Boolean Type float

Primitive Types Numerical Types

int
Character Type
Integer Types short
byte

long

8
Primitive Data Types

• Four integer number data types:


- byte, short, int, long
• Two floating-point number data types:
- float, double
• Character data type:
- char
• Boolean data type:
- boolean (true or false)

9
Integer Data Types

Data Storage Range


Type Size
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to
2,147,483,647
long 8 bytes -9,223,372,036,854,775,807
to
9,223,372,036,854,775,808

10
Floating-point Data Types

Data Storage Range Precision


Type Size

float 4 bytes -3.4e38 6 to 7 significant


to digits
3.4e38
double 8 bytes -1.7e308 14 to 15
to significant digits
1.7e308

11
Character and Boolean Data Types
Character Data Type
• Any data object which is
-an English letter (a,..,z,A,..,Z)
-an English punctuation mark (!, ?, etc.)
-a decimal digit (0,..,9), or
-a symbol such as a space,
-etc…
• A storage space of 2 bytes needed
Boolean Data Type
• boolean literals: true or false
12
Reference Data Types
String Type
• A reference data type is used to store an
address of an object that can be used to refer to
the object.
• String Data Type
– Strings are represented by a sequence of
characters within double quotes, Data Type Quiz
e.g. “Hui Siu Cheung”, “Hello Students!”
– Strings are not primitive data types
– Java provides the String class with methods
13
Chapter 3
Data Types, Constants and Variables
• Computer Memory
• Data Types
• Literals
• Identifiers
• Constants
• Variables
• Programming Style
• Case Study
14
Literals

• Literals are values (associated with data


type) used in the program.

• Five types of literals:


– Integer literals, e.g. 100, 256
– Floating-point literals, e.g. 2.4, 3.0
– Character literals, e.g. 'a', '+'
– Boolean literals, e.g. true, false
– String literals, e.g. "Hello Students"

15
Character Literals
• A character is stored as 16-bit (2 bytes) unsigned
values using Unicode encoding scheme which is
established by the Unicode Consortium to support
interchange, processing, and display of text in
different languages such as Chinese and Korean.

• Unicode includes the ASCII (American Standard Code


of Information Interchange) code. A total of 128
characters. Each character is enclosed with quotes,
e.g. ‘A’.

• Each character in the Unicode has a corresponding


numeric code, e.g. ‘A’ has a value of 41 in
hexadecimal representation (or 65 in decimal). (See
Appendix A of the textbook) 16
ASCII Unicode Set (1 byte)
0 1 2 3 4 5 6 7 8 9

0 NUL BEL BS TAB

1 LF FF CR

2 ESC

3 SP ! " # $ % & '

4 ( ) * + , - . / 0 1
5 2 3 4 5 6 7 8 9 : ;
6 < = > ? @ A B C D E
7 F G H I J K L M N O
8 P Q R S T U V W X Y
9 Z [ \ ] ^ _ ' a b c
10 d e f g h i j k l m
11 n o p q r s t u v w
12 x y z { | } ~ DEL
17
Examples of Escape Sequence

• Some useful non-printable control characters are


referred to by the escape sequence which is a better
alternative, in terms of memorization, than numbers.
e.g. ‘\n’ the newline (or linefeed) character instead of
the number 10. 

‘\a’ alarm bell ‘\f’ form feed ‘\n’ newline

‘\t’ horizontal ‘\”’ double quote ‘\v’ vertical tab


tab
‘\b’ back space ‘\\’ backslash ‘\r’ carriage return

‘\’’ single quote


18
Chapter 3
Data Types, Constants and Variables
• Computer Memory
• Data Types
• Literals
• Identifiers
• Constants
• Variables
• Programming Style
• Case Study
19
Identifiers
Identifiers are used to name things such as variables,
constants, classes and packages.

Rules for naming identifiers:


• An identifier must start with a letter, an underscore character (_)
or a dollar sign ($).
• An identifier may contain only letters, digits (0,..,9), and the
underscore character (_).
• An identifier is case sensitive.
• An identifier cannot contain a space, or any other characters
such as a dot (.) or an asterisk (*).
• An identifier cannot be a reserved word or keyword.
• An identifier does not have any length limit.

Ex: Valid - area, Length, a, A, sevenAnd1, my_program


20
Invalid - new, my-program, Java.com, 7and1
Chapter 3
Data Types, Constants and Variables
• Computer Memory
• Data Types
• Literals
• Identifiers
• Constants
• Variables
• Programming Style
• Case Study
21
Constants
• A constant is an object whose value is unchanged
throughout program execution.

• Define a constant by using the Java keywords static final.


The form is
    static final Type CONSTANT_NAME = Value;
 

where CONSTANT_NAME - name of the constant.


(where CONSTANT_NAME should use upper case,
separated with an underscore if comprising two or more
words)
e.g. static final double PI = 3.14159;
 

• During compilation, the value of the constant will be


substituted whenever the name of the constant appears in
the program.     
22
Constants
By giving a symbolic name to a constant:
- it improves the readability of the program
- it makes programs easier to be modified

Example:

public class DefineConstant {


static final double PI = 3.14159;
public static void main(String[] args) {
System.out.println("The value for pi is " + PI);
}

Output:
The value for pi is 3.14159 23
Chapter 3
Data Types, Constants and Variables
• Computer Memory
• Data Types
• Literals
• Identifiers
• Constants
• Variables
• Programming Style
• Case Study
24
Variables
 Variables are data objects that may change and be
  

assigned values as the program runs.


 Each variable has a name. The name of a variable is a
  

sequence of alphanumeric characters plus the underscore


_. The first character must be a letter or an underscore.
 Meaningful names make programs more readable. e.g.
‘tax’ will make a program easier to understand than ‘t’.
 Variable names are case sensitive.

 Valid: goodName, newValue, taxRate, etc.


 Invalid: good Name, new-Value, tax+Rate, 7And11

25
 A variable name cannot be any of the keywords in Java.
    

Keywords have special meanings to Java compiler.

abstract boolean break byte case


catch char class const continue
default do double else extends
final finally float for goto
if implements import instanceof int
interface long native new package
private protected public return short
static super switch synchronized this
throw throws transient try void
volatile while

26
 Each variable has a data type such as int, float
    

and char.
 
 Variables are declared by declaration statements.
A declaration can be done with or without
initialization.
 
 A declaration statement without initialization has the
    

form
 
Type Variable[, Variable];
  Variable Names
where Type can be int, float, or char, etc. Quiz
Variable is the name of the variable.
[...] may be repeated zero or more times.
27
Program: Variables without Initialization
 
Specification: Computing Income Tax
CONSTANTS
public class DeclareVariable {
static final int DEDUCTION = 2000; // Constant
static final double TAX_RATE = 0.2; // Constant
public static void main(String[ ] args){ VARIABLES
// Define Variables
double incomeTax, taxableIncome, grossSalary;
int numOfDependents, numOfChildren, numOfParents;

// Assign or read numOfChildren, numOfParents, grossSalary

// Compute income tax LOGIC IN SEQUENCE


(Note the order of statements
// Print the income tax – dependent)
} 28
}
Program: Computing Income Tax
public class DeclareVariable {
static final int DEDUCTION = 2000; // Constant
 
static final double TAX_RATE = 0.2; // Constant
public static void main(String[ ] args){
// Variables
double incomeTax, taxableIncome, grossSalary;
int numOfDependents, numOfChildren, numOfParents;

// Assignment statements LOGIC IN


numOfChildren = 2; SEQUENCE
numOfParents = 2;
grossSalary = 100000.0; ASSIGNMENT

numOfDependents = numOfChildren + numOfParents;


taxableIncome =
grossSalary – numOfDependents*DEDUCTION;
incomeTax = taxableIncome * TAX_RATE;

System.out.println("The income tax is " + incomeTax);


} 29
}
Program output:
The income tax is 18400.0
 int numOfChildren, numOfParents, numOfDependents;
double grossSalary, taxableIncome, incomeTax;

Memory
Variable Names
1000 (Memory Address)
numOfChildren (4 bytes)
If variables are not
1024 initialized with initial
numOfParents (4 bytes) values, Java will initialize
1028 the variables automatically:
numOfDependents (4 bytes) -numerical types -> 0
-Boolean -> false
1036
grossSalary
-Reference data type -> null
(8 bytes)

1044
taxableIncome (8 bytes)

1050
incomeTax (8 bytes) 30
Program: Variables with Initialization
 
public class DeclareVarInit {
// constants int numOfChildren = 2, numOfParents = 2, numOfDependents;
double grossSalary, taxableIncome, incomeTax;
static final int DEDUCTION = 2000;
static final double TAX_RATE = 0.2; Memory
public static void main(String[] args) { Variable Names
1000 (Memory Address)
// variables
numOfChildren 2 (4 bytes)
double incomeTax, taxableIncome, grossSalary;
int numOfDependents, numOfChildren=2, 1024
numOfParents 2 (4 bytes)
numOfParents=2;
// assignment statements 1028
numOfDependents (4 bytes)
grossSalary = 100000;
numOfDependents = numOfChildren + 1036

numOfParents; grossSalary (8 bytes)

taxableIncome = grossSalary – 1044


numOfDependents*DEDUCTION; taxableIncome (8 bytes)

incomeTax = taxableIncome * TAX_RATE; 1050


System.out.println("The income tax is " + incomeTax (8 bytes)

incomeTax);
} 31
}
 Initialization can also be done as part of a declaration. This
means a variable is given a starting value when it is declared.

 To improve readability of the program, it is better to declare


    

initialized and un-initialized variables in separate declaration


statements.
Example:  
int numOfChildren=2, numOfParents = 2;
int numOfDependents;
 
 During compilation, a memory location of suitable size is
 

assigned for each variable. Naturally a variable must be


declared before it is used.

32
Chapter 3
Data Types, Constants and Variables
• Computer Memory
• Data Types
• Literals
• Identifiers
• Constants
• Variables
• Programming Style
• Case Study
33
Programming Style
• Make programs simple, readable and easy to
understand.
• Using Proper Programming Style
- should use indentation, blank spaces, blank lines.
- e.g. using indentation as follows:
public class DeclareVarInit { Use Generate CSD
// constants
static final int DEDUCTION = 2000; in jGRASP
static final double TAX_RATE = 0.2;
public static void main(String[] args){
// variables
int numOfChildren=2, numOfParents=2, numOfDependents;
double grossSalary, taxableIncome, incomeTax;
// assignment statements
grossSalary = 100000;
numOfDependents = numOfChildren + numOfParents;
taxableIncome =
grossSalary - numOfDependents*DEDUCTION;
incomeTax = taxableIncome * TAX_RATE;
System.out.println("The income tax is " + incomeTax);
}
} 34
Using Generate CSD in jGRASP

35
Programming Style
• Using Meaningful Names
- Class names – The first letter of each word in the class
name should be capitalized (e.g. CurrencyExchange).

- Variable, method and package names – Lowercase


letters should be used for variable and method names. If
the name consists of several words, we then use
lowercase for the first word, and use capital letter for the
first letter of subsequent words, e.g. convertDollars().

- Constants – Uppercase letters should be used for


symbolic constants (e.g. MAXIMUM), and underscores
should be used to separate between words (e.g.
MAX_LIMIT).
36
Programming Style

 Adding comments into the program.


    

 
- At the beginning of the program, put comments to say
what the program will do; your name and date.
Subsequently when the program is modified/extended,
put comments to record the modifications, who made
it, and the date of the modifications.
 
- If the purpose of a portion of the program is not very
clear at a glance, e.g. a nested loop or nested-if
statement, put comments to say what the program is
doing.

37
Chapter 3
Data Types, Constants and Variables
• Computer Memory
• Data Types
• Literals
• Identifiers
• Constants
• Variables
• Programming Style
• Case Study
38
 
Case Study
Finding Area and Circumference of a
Circle

Problem Specification

Design a program to solve the following problem:


 

“Write a program to read in the radius of a circle,


and then compute and output the circle’s area
and circumference. ”
39
Problem Analysis
Input Program Output

Circle

r Area
Radius(r) Circumference

Area = *r*r; Circumference= 2**r


Required input:
FORM VARIABLES ?
• the radius of a circle
Required outputs:
• the area of the circle
FORM VARIABLES ?
• the circumference of the circle
Formulas: Need to derive
• Area of a circle = π * radius * radius the formula
• Circumference of a circle = 2 * π * radius 40
Program Design
Initial Algorithm
1. Read the radius of a circle.
2. Calculate the area.
3. Calculate the circumference.
4. Print the area and circumference of the circle.

Algorithm in Pseudocode ANY CONSTANTS?


main:
SET constant PI TO 3.14159 ANY VARIABLES ?
READ radius
LOGIC IN
COMPUTE area = radius * radius * PI SEQUENCE
COMPUTE circumference = 2 * radius * PI
PRINT area, circumference ASSIGNMENT
41
Program Design
Program Dry-run
Input:
radius = 5.0
PI = 3.14159

Area = 5.0*5.0*3.14159 = 78.53975


Circumference = 2*5.0*3.14159 = 31.4159

Outputs:
The area is: 78.53975
The circumference is: 31.4159

42
Implementation
import java.util.Scanner;
public class ComputeCircle {
static final double PI = 3.14159; CONSTANT
public static void main(String[ ] args) {
double radius, area, circumference; VARIABLES
Scanner sc = new Scanner(System.in);

// read the radius of the circle


System.out.print("Enter the radius: ");
radius = sc.nextDouble(); LOGIC IN
SEQUENCE
// calculate the area
area = PI * radius * radius;
// calculate the circumference ASSIGNMENT
circumference = 2 * PI * radius;

// print the area and circumference of the circle


System.out.println("The area is " + area);
System.out.println("The circumference is " + circumference);
43
}
Testing
Program sample input and output
Enter the radius: 5
The area is 78.5397
The circumference is 31.4159

Program sample input and output


Enter the radius: 10
The area is 314.159
The circumference is 62.8318

44
Key Terms
• data type
• primitive data type
• byte type, short type, int type, long type
• float type, double type
• character type
• boolean type
• reference data type
• String type
• literal
• identifier
• constant
• variable declaration
• declaration statement
• assignment operator, assignment statement
45
  Review Exercise: Linear Interpolation
Problem Specification
 

“The equation of a straight line is given as y=mx+c, where m


is the slope and c is the intercept. If the coordinates of two
points P1 and P2 are (x1, y1) and (x2, y2), the slope and the
intercept of the line are given in the following equations:
  y 2  y1
Slope: m 
x 2  x1

Intercept: c  y1 x 2  y 2 x 1
  x 2  x1
Write a program to read in two points. Then, it finds the
slope and intercept of the straight line given by the
coordinates of the two points on the straight line. In addition,
the program will also read in the x-coordinate of a point,
and then find the y-coordinate of the point on the straight
46

line. ”
Problem Analysis
Required inputs: ______, ______ and _______
Required output: ___________ and _________
Formulas: slope = ________________,
intercept = ______________,
y = ___________________

System Design
Initial Algorithm: (Exercise)
Algorithm in Pseudocode
main()
READ __, __, __, ___, ___
COMPUTE ___ = ________________
COMPUTE ___ = ________________
COMPUTE ___ = ________________
PRINT _____. _____. _____ 47
Implementation
Import java.util.Scanner;
public class LinearInterpolate {
public static void main(String[] args){
// Declare variables

double __, __, __, __, __, __, __, __;


Scanner sc = new Scanner(System.in);

// Read the two points & x-coordinate

System.out.print("Enter first point x1 y1: ");


__ = sc.nextDouble();
__ = sc.nextDouble();

System.out.print("Enter second point x2 y2: ");


__ = sc.nextDouble();
__ = sc.nextDouble();

System.out.print("Enter x-coordinate of pt: ");


__ = sc.nextDouble();
48
Implementation

// Calculate the slope, int and y-ccordinate

__ = ______;
__ = ______;
__ = ______;
// Print slope, intercept, y-ccordinate

System.out.println("The ___ is " + ___);


System.out.println("The ___ is " + ___);
System.out.println("The ___ is " + ___);
}
} Exercise Solution

49
Further Reading

• Read Chapter 3 on “Data Types, Constants and


Variables” of the textbook

50

You might also like