Chapter 2
2.1 Elementary Programming
Identifiers
Identifiers are the names that identify the elements such
as classes, methods, and variables in a program.
An identifier consists of a sequence of characters that consist
of letters, digits, underscores (_), and dollar signs ($).
An identifier must start with a letter, an underscore (_), or a
dollar sign ($). It cannot start with a digit.
An identifier cannot be a reserved word, true, false, null.
An identifier can be of any length.
For example: Java is case sensitive
- Total, total, and TOTAL are different identifiers.
Valid Identifiers
Examples of Valid Identifiers
aaa sales_tax _circleArea
box100width $directory ab1234$$
Invalid Identifiers
Examples of Invalid Identifiers
1ab (ERROR: first character starts with a digit)
num-oranges (ERROR: dash is not permitted in
identifiers)
num oranges (ERROR: space is not permitted in
identifiers)
Valid Class Names
Class Name Description
Employee Begins with an uppercase letter
Begins with an uppercase letter and
UnderGradeStudent emphasizes each new word with an initial
uppercase letter
Begins with an uppercase letter and
Budget2004
contains no spaces
Invalid Class Names
Class Name Description
en employee Space character is illegal
class Class is a reserved word
2001Budget Class names cannot begin with a digit
phone# The # symbol is not allowed
Variables
radius = 1.0;
area = radius * radius * 3.14159
[Link]("The area is “ + area +
" for radius "+radius);
Variables are used to
represent values that may be
changed in the program.
Declaring Variables
Declare x to be an
int x;
integer variable;
Declare radius to be a
double radius; double variable;
Declare a to be a
char a; character variable;
Assignment Statements
x = 1; Assign 1 to x
radius = 1.0; Assign 1.0 to radius
a = ‘A’; Assign A to a
int x = 1; Declaring and Initializing
in One Step
1= x; Wrong
Computing the Area of a Circle
1 public class ComputeArea {
2 public static void main(String[] args) {
3 double radius;
4 double area;
5 radius = 20; // Assign a radius
6 area = radius * radius * 3.14159; // Compute area
7 [Link]("The area for the circle of
8 radius " + radius + " ismemory
" + area); // Display
results radius no value
9 } Allocate
memory
10 }
for radius
Computing the Area of a Circle
1 public class ComputeArea {
2 public static void main(String[] args) {
3 double radius;
4 double area;
5 radius = 20; // Assign a radius
6 area = radius * radius * 3.14159; // Compute area
7 [Link]("The area for the circle of
8 radius " + radius + " ismemory
" + area); // Display
results radius no value
9 } Allocate
area no value memory
10 }
for area
Computing the Area of a Circle
1 public class ComputeArea {
2 public static void main(String[] args) {
3 double radius;
4 double area;
5 radius = 20; // Assign a radius
6 area = radius * radius * 3.14159; // Compute area
7 [Link]("The area for the circle of
8 radius " + radius + " ismemory
" + area); // Display
results radius 20
9 } Assign 20
area no value to radius
10 }
Computing the Area of a Circle
1 public class ComputeArea {
2 public static void main(String[] args) {
3 double radius;
4 double area;
5 radius = 20; // Assign a radius
6 area = radius * radius * 3.14159; // Compute area
7 [Link]("The area for the circle of
8 radius " + radius + " ismemory
" + area); // Display
Compute
results radius 20 area and
9 } assign it to
area 1256.636 variable
10 }
area
Computing the Area of a Circle
1 public class ComputeArea {
2 public static void main(String[] args) {
3 double radius;
4 double area;
5 radius = 20; // Assign a radius
6 area = radius * radius * 3.14159; // Compute area
7 [Link]("The area for the circle of
8 radius " + radius + " ismemory
" + area); // Display
results radius 20 Print a
9 } message
area 1256.636 to the
10 }
console
Reading Input from the Console
[Link] refers to the standard output device.
[Link] refers to the standard input device.
Scanner class to create an object to read input from
[Link]
Scanner input = new Scanner([Link]);
The syntax new Scanner([Link]) creates an
object of the Scanner type.
Input is a variable whose type is Scanner.
Methods of Scanner Objects
Method Description
nextByte() reads an integer of the byte type
nextShort() reads an integer of the short type
nextInt() reads an integer of the int type
nextLong() reads an integer of the long type
nextFloat() reads a number of the float type
nextDouble() reads a number of the double type
Reading Number from the Keyboard
1 import [Link]; Import Scanner Class
2 public class ComputeAreaWithConsoleInput {
3 public static void main(String[] args) {
4 Scanner input = new Scanner([Link]);
Construct Scanner Object
5 [Link]("Enter a number for radius: ");
6 double radius = [Link]();
Read Input
7 double area = radius * radius * 3.14159;
Define variable to receive value
8 [Link]("The area for the circle of
radius " + radius + " is " + area);
9 }
10 }
Named Constants
Named Constants
final datatype CONSTANTNAME = VALUE;
The word final
is Java keyword for declaring a constant.
Declaring Constant Variable
1 import [Link];
2 public class ComputeAreaWithConstant {
3 public static void main(String[] args) {
Declare a
4 final double PI = 3.14159;
constant
5 Scanner input = new Scanner([Link]);
6 [Link]("Enter a number for radius: ");
7 double radius = [Link]();
8 double area = radius * radius * PI;
9 [Link]("The area for the circle of
10 radius " + radius + " is " + area);
11 }
12 }
Reserved Java Keywords
Reserved Java Keywords
abstract do if package synchronized
boolean double implements private this
break else import protected throw
byte extends Instance of public throws
case false int return transient
catch final interface short true
char finally long static try
class float native strictfp void
const for new super volatile
continue goto null switch while
default
Numerical Data Types
Name Range Storage Size
byte -27 to 27 - 1 (-128 to 127) 8-bit signed
short -215 to 215 - 1 (-32768 to 32767) 16-bit signed
-231 to 231 - 1 (-2147483648 to
int 32-bit signed
2147483647)
-263 to 263 - 1 (i.e.,
64-bit signed
long -9223372036854775808 to
9223372036854775807)
Negative range: -3.4028235E + 38 to 32-bit IEEE
float
-1.4E - 45 754
Negative range: -1.7976931348623157E
+ 308 to -4.9E – 324 64-bit IEEE
double
Positive range: 4.9E - 324 to 754
1.7976931348623157E + 308
Numeric Operators
Name Meaning Example Result
+ Addition 34 + 1 35
- Subtraction 34.0 – 0.1 33.9
* Multiplication 300 * 30 9000
/ Division 1.0 / 2.0 0.5
% Remainder 20 % 3 2
Augmented Assignment Operators
Operator Name Example Equivalent
+= Addition assignment i += 8 i=i+8
Subtraction
-= i -= 8 i=i–8
assignment
Multiplication
*= i *= 8 i=i*8
assignment
/= Division assignment i /= 8 i=i/8
Remainder
%= i %= 8 i=i%8
assignment
Increment and Decrement Operators
Example
Operator Name Description
(Assume i=1)
Increment var by 1, and use
int j = ++i;
++var preincrement the new var value in the
// j is 2, i is 2
statement
Increment var by 1, but use the int j = i++;
var++ postincrement
original var value in the statement // j is 1, i is 2
Decrement var by 1, and use
int j = --i;
--var predecrement the new var value in the
// j is 0, i is 0
statement
postdecremen Decrement var by 1, and use the int j = i--;
var--
t original var value in the statement // j is 1, i is 0
Integer Division
+, -, *, /, and %
5/2 2
5.0/2 2.5
5%2 1
Type Casting
Implicit casting
• double d = 3; (type widening)
Explicit casting
• int i = (int)3.0; (type
narrowing)
• int i = (int)3.9; (Fraction
part is truncated)
Undeclared/Uninitialized Variables and Unused Variables
public class Test{
public static void main(String[] args) {
double interestRate = 0.05;
double interest = interestrate * 45 }}
Integer Overflow and Round-off Errors
Integer Overflow
• int value = 2147483647 + 1;
Round-off Errors
• [Link](1.0 -
0.1 - 0.1 - 0.1 - 0.1 - 0.1);
• [Link](1.0 -
0.9);
Unintended Integer Division
1 int number1 = 1;
2 int number2 = 2;
3 double average = (number1 + number2) / 2;
4 [Link](average);
(a)
1 int number1 = 1;
2 int number2 = 2;
3 double average = (number1 + number2) / 2.0;
4 [Link](average);
(b)
Redundant Input Objects
1 Scanner input = new Scanner([Link]);
2 [Link]("Enter an integer: ");
3 int v1 = [Link]();
4 Scanner input1 = new Scanner([Link]);
5 [Link]("Enter a double value: ");
6 double v2 = [Link]();
Assignment 1
(Fahrenheit degree to Celsius )
Write program that converts a Fahrenheit degree to
Celsius using the following formula:
celsius ( 5 )(fahrenheit 32)
9
Assignment 1
1 import [Link];
2 public class FahrenheitToCelsius {
3 public static void main(String[] args) {
4 Scanner input = new Scanner([Link]);
5 [Link]("Enter a degree in Fahrenheit: ");
6 double fahrenheit = [Link]();
7 // Convert Fahrenheit to Celsius
8 double celsius = (5.0 / 9) * (fahrenheit - 32);
9 [Link]("Fahrenheit " + fahrenheit + " is " +
10 celsius + " in Celsius");
11 }
12 }