0% found this document useful (0 votes)
10 views90 pages

02 Slide

Chapter 2 of 'Introduction to Java Programming and Data Structures' covers the basics of programming in Java, including creating, compiling, and running programs, as well as understanding programming errors. It introduces key concepts such as algorithms, primitive data types, variables, and input/output operations, using examples like computing the area of a circle. The chapter emphasizes the importance of designing a strategy for problem-solving and provides practical examples of reading user input and using the Scanner class.

Uploaded by

Hamza AKSİN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views90 pages

02 Slide

Chapter 2 of 'Introduction to Java Programming and Data Structures' covers the basics of programming in Java, including creating, compiling, and running programs, as well as understanding programming errors. It introduces key concepts such as algorithms, primitive data types, variables, and input/output operations, using examples like computing the area of a circle. The chapter emphasizes the importance of designing a strategy for problem-solving and provides practical examples of reading user input and using the Scanner class.

Uploaded by

Hamza AKSİN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Chapter 2 Elementary Programming

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
1
Lecture 1 Review
• Create, compile, and run a Java program.
• Programming Errors

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
2
Motivations
• How to solve practical problems programmatically

• Java primitive data types and related subjects, such as


– variables,
– constants,
– data types,
– operators,
– expressions, and
– input and output.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
3
Writing a program
Writing a program involves designing a
strategy for solving the problem and then
using a programming language to implement
that strategy.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
4
Algorithm
• An algorithm describes how a problem is solved by
listing the actions that need to be taken and the order
of their execution.

• Algorithms can help the programmer plan a program


before writing it in a programming language.

• Algorithms can be described in natural languages or in


pseudocode (natural language mixed with some
programming code).

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
5
Introducing Programming with
an Example
• Computing the Area of a Circle
• The algorithm for calculating the area of a
circle
1. Read in the circle’s radius.
2. Compute the area using the following formula:
area = radius * radius * pi;
3. Display the result.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
6
Writing a program
Every Java program begins with a class
definition in which the keyword class is
followed by the class name.

public class ComputeArea {


// Details to be given later
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
7
Writing a program
Every Java program must have a main method
where program execution begins.

public class ComputeArea {


public static void main(String[] args){
// Step 1: Read in radius
// Step 2: Compute area
// Step 3: Display the area
}
}
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
8
Writing a program
Step 1: Read in radius
– The program needs to read the radius entered by the user
from the keyboard.
 Reading the radius
 Storing the radius in the program

– In order to store the radius, the program needs to declare a


symbol called a variable.

– A variable represents a value stored in the computer’s


memory.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
9
Writing a program
 Choose descriptive names for variables:
– radius for radius, and area for area

 To let the compiler know what radius and area are, specify
their data types.

 That is the kind of data stored in a variable, whether integer,


real number, or something else. This is known as declaring
variables.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
10
Writing a program
Primitive data types:
– Integers,
– Real numbers,
– Characters,
– Boolean types.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
11
Writing a program
Use the keyword double to declare a floating-
point variable.

public class ComputeArea {


public static void main(String[] args){
double radius;
double area;
// Step 1: Read in radius
// Step 2: Compute area
// Step 3: Display the area
}
} Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
12
ComputeArea.java
1 public class ComputeArea {
2 public static void main(String[] args) {
3 double radius;
4 double area;
5
6 // Assign a value to radius
7 radius = 20; // radius is now 20
8
9 // Compute area
10 area = radius * radius * 3.14159;
11
12 // Display the result
13 System.out.println("The area for the circle of radius " +
radius + " is " + area);
14 }
15 } Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
13
Introducing Programming with an
Example
Listing 2.1 Computing the Area of a Circle
This program computes the area of the circle.

ComputeArea Note: Clicking the green button displays the source code
with interactive animation. You can also run the code in
a browser. Internet connection is needed for this button.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
14
animation

Trace a Program Execution


public class ComputeArea { allocate memory
/** Main method */ for radius
public static void main(String[] args) {
double radius; radius no value
double area;

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
15
animation

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius no value
double area; area no value

// Assign a radius
radius = 20;
allocate memory
// Compute area for area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
16
animation

Trace a Program Execution


public class ComputeArea { assign 20 to radius
/** Main method */
public static void main(String[] args) {
double radius; radius 20
double area; area no value
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
17
animation

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area; area 1256.636
// Assign a radius
radius = 20;
compute area and assign it
// Compute area
to variable area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
18
animation

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area; area 1256.636
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
19
Reading Input from the Console
• Reading input from the console enables the
program to accept input from the user.
• Use the Scanner class for console input
• Java uses System.out to refer to the standard
output device and System.in to the standard input
device.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
20
Reading Input from the Console
1. Create a Scanner object
Scanner input = new Scanner(System.in);

2. Use the method nextDouble() to obtain to a double


value. For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();

ComputeAreaWithConsoleInput

ComputeAverage
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
21
ComputeAreaWithConsoleInput.java
import java.util.Scanner; // Scanner is in the java.util package

public class ComputeAreaWithConsoleInput {


public static void main(String[] args) { // Create a Scanner object
Scanner input = new Scanner(System.in);

// Prompt the user to enter a radius


System.out.print("Enter a number for radius: ");
double radius = input.nextDouble();

// Compute area
double area = radius * radius * 3.14159;

// Display result
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
22
ComputeAreaWithConsoleInput.java

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
23
ComputeAverage.java
import java.util.Scanner; // Scanner is in the java.util package

public class ComputeAverage {


public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);

// Prompt the user to enter three numbers


System.out.print("Enter three numbers: ");
double number1 = input.nextDouble();
double number2 = input.nextDouble();
double number3 = input.nextDouble();

// Compute average
double average = (number1 + number2 + number3) / 3;

// Display result
System.out.println("The average of " + number1 + " " + number2 +
" " + number3 + " is " + average);
}
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
24
ComputeAverage.java

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
25
import statement
• specific import specifies a single class in the
import statement.
import java.util.Scanner;

• wildcard import imports all the classes in a


package by using the asterisk
import java.util.*;

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
26
print vs. println
• println moves to the beginning of the next
line after displaying the string.

• print does not advance to the next line


when completed.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
27
Identifiers
• Identifiers are the names that identify the elements such as classes, methods,
and variables in a program.

• An identifier is 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.


• (See Appendix A, “Java Keywords,” for a list of reserved words).

• An identifier cannot be true, false, or null.

• An identifier can be of any length.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
28
Variables
• Variables are used to represent values that may be
changed in the program.

• To use a variable, you declare it by telling the


compiler its name as well as what type of data it
can store.

• The syntax for declaring a variable


datatype variableName;

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
29
Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);

// Compute the second area


radius = 2.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
30
Declaring Variables
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
int i, j, k; //Declare i, j, and k as int
//variables

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
31
Assignment Statements
• An assignment statement designates a value for a
variable.
• The equal sign (=) is used as the assignment operator .
• Syntax:
variable = expression;

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
32
Assignment Statements
x = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to radius;


a = 'A'; // Assign 'A' to a;

x = x + 1; // The result of x+1 is


assigned to x
1 = x; // Wrong

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
33
Declaring and Initializing
in One Step
 Syntax:
datatype variable = expression;

int x;
 int x = 1;
x = 1;

 double d = 1.4; double d;


d = 1.4;

34
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
Expression
An expression represents a computation involving values,
variables, and operators that, taking them together, evaluates
to a value.

int y = 1; // Assign 1 to variable y


double radius = 1.0; // Assign 1.0 to variable radius
int x = 5 * (3 / 2); // Assign the value of the expression to x
x = y + 1; // Assign the addition of y and 1 to x
double area = radius * radius * 3.14159; // Compute area

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
35
Expression
• The following statement is true
System.out.println(x = 1);

x = 1;
System.out.println(x);

• If a value is assigned to multiple variables,


you can use this syntax:
k = 1;
i = j = k = 1; j = k;
i = j;

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
36
Named Constants
• A named constant is an identifier that represents a
permanent value.

• Syntax:
final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159;


final int SIZE = 3;

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
37
ComputeAreaWithConstant.java
public class ComputeAreaWithConstant {
public static void main(String[] args) {
final double PI = 3.14159; // Declare a constant

// Create a Scanner object


Scanner input = new Scanner(System.in);

// Prompt the user to enter a radius


System.out.print("Enter a number for radius: ");
double radius = input.nextDouble();

// Compute area
double area = radius * radius * PI;

// Display result
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
38
Naming Conventions
 Choose meaningful and descriptive names.
 Variables and method names:
– Use lowercase. If the name consists of several
words, concatenate all in one, use lowercase
for the first word, and capitalize the first letter
of each subsequent word in the name.
– For example, the variables radius and area,
and the method computeArea.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
39
Naming Conventions, cont.
 Class names:
– Capitalize the first letter of each word in
the name. For example, the class name
ComputeArea.

 Constants:
– Capitalize all letters in constants, and use
underscores to connect words. For
example, the constant PI and
MAX_VALUE

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
40
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

int –231 to 231 – 1 (-2147483648 to 2147483647) 32-bit signed

long –263 to 263 – 1 64-bit signed


(i.e., -9223372036854775808 to 9223372036854775807)

float Negative range: 32-bit IEEE 754


-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to -4.9E-324

Positive range:
4.9E-324 to 1.7976931348623157E+308

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
41
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.


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.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
42
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

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
43
Division
• When both operands of a division are
integers, the result of the division is the
quotient and the fractional part is truncated.
5 / 2 yields an integer 2,

• To perform a floating-point division, one of


the operands must be a floating-point
number.
5.0 / 2 yields a double value 2.5.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
44
Remainder Operator
• The % operator yields the remainder after division.

• 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.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
45
Remainder Operator
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:

Saturday is the 6th day in a week


A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
46
Problem: Displaying Time
Write a program that obtains minutes and
remaining seconds from seconds.

DisplayTime

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
47
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 and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
48
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 and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
49
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 = 1000000;
double d = 5.0;

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
50
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.
– (Note that the range of byte value is from -128 to 127.)

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
51
Integer Literals
• 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 and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
52
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.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
53
Floating-Point Literals
• 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 and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
54
double vs. float
The double type values are more accurate than the
float type values. For example,
System.out.println("1.0 / 3.0 is " + 1.0 / 3.0);

displays 1.0 / 3.0 is 0.3333333333333333

16 digits

System.out.println("1.0F / 3.0F is " + 1.0F / 3.0F);

displays 1.0F / 3.0F is 0.33333334


7 d igits

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
55
Scientific Notation
• Floating-point literals can also be specified in
scientific notation.
• For example,
– 1.23456e+2, same as 1.23456e2, is equivalent to
123.456, and
– 1.23456e-2 is equivalent to 0.0123456.
– E (or e) represents an exponent and it can be either in
lowercase or uppercase.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
56
JShell
JShell is a command line interactive tool
introduced in Java 9. JShell enables you to type a
single Java statement and get it executed to see the
result right away without having to write a
complete class. This feature is commonly known as
REPL (Read-Evaluate-Print Loop), which
evaluates expressions and executes statements as
they are entered and shows the result immediately.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
57
Arithmetic Expressions
3 + 4 x 10( y - 5)( a + b + c ) 4 9+ x
- + 9( + )
5 x x y

is translated to

(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
58
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 and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
59
Problem: Converting Temperatures
Write a program that converts a Fahrenheit degree
to Celsius using the formula:
celsius = ( 95 )( fahrenheit - 32)

Note: you have to write


celsius = (5.0 / 9) * (fahrenheit – 32)

FahrenheitToCelsius

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
60
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 ShowCurrentTime
Unix Epoch Current Time
01-01-1970 System.currentTimeMills()
00:00:00 GMT

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
61
Augmented Assignment Operators

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
62
Augmented Assignment Operators
• The augmented assignment operator is
performed last after all the other operators
in the expression are evaluated.
• For example,
x /= 4 + 5.5 * 1.5;
is same as
x = x / (4 + 5.5 * 1.5);

Cauition!
There are no spaces in the augmented assignment operators.
For example, + = should be +=.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
63
Example: Show the output of the
following code
double a = 6.5;
a += a + 1;
System.out.println(a);
a = 6;
a /= 2;
System.out.println(a);

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
64
Increment and
Decrement Operators

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
65
Increment and
Decrement Operators, cont.

int i = 10; Same effect as


int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as


int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
66
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 and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
67
Example: Show the output of the
following code
int x = 3;
int y = 4;
int k = x * y++;
int l = x * ++y;
System.out.println("x " + x);
System.out.println("y " + y);
System.out.println("k " + k);
System.out.println("l " + l);

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
68
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 and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
69
Conversion Rules
When performing a binary operation involving two
operands of different types, Java automatically
converts the operand based on the following rules:

1. If one of the operands is double, the other is


converted into double.
2. Otherwise, if one of the operands is float, the other is
converted into float.
3. Otherwise, if one of the operands is long, the other is
converted into long.
4. Otherwise, both operands are converted into int.

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
70
Type Casting
• Casting is an operation that converts a value of
one data type into a value of another data type
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)

What is wrong? int x = 5 / 2.0;


range increases

byte, short, int, long, float, double


Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
71
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

sum += 4.5 is equivalent to sum = (int)(sum + 4.5).


Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
72
Problem: Keeping Two Digits After
Decimal Points
Write a program that displays the sales tax with two
digits after the decimal point.

SalesTax

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
73
Software Development Process

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
74
Requirement Specification
A formal process that seeks to understand
Requirement
Specification
the problem and document in detail what
the software system needs to do. This
System phase involves close interaction between
Analysis
users and designers.
System
Design

Implementation

Testing

Most of the examples in this book are simple,


and their requirements are clearly stated. In Deployment

the real world, however, problems are not


well defined. You need to study a problem Maintenance
carefully to identify its requirements.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
75
System Analysis
Requirement
Specification Seeks to analyze the business
process in terms of data flow, and
System
Analysis to identify the system’s input and
output.
System
Design

Implementation

Part of the analysis entails modeling Testing

the system’s behavior. The model is


Deployment
intended to capture the essential
elements of the system and to define
Maintenance
services to the system.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
76
System Design
Requirement
Specification
The process of designing the
system’s components.
System
Analysis

System
Design

Implementation

Testing

This phase involves the use of many levels


Deployment
of abstraction to decompose the problem into
manageable components, identify classes and
interfaces, and establish relationships among Maintenance
the classes and interfaces.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
77
IPO
Requirement
Specification

System
Analysis Input, Process , Outp ut

System
Design

Implementation

Testing

The essence of system analysis and design is input,


process, and output. This is called IPO. Deployment

Maintenance

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
78
Implementation
Requirement The process of translating the
Specification
system design into programs.
System Separate programs are written for
Analysis
each component and put to work
System together.
Design

Implementation

Testing
This phase requires the use of a
programming language like Java. Deployment
The implementation involves
coding, testing, and debugging. Maintenance

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
79
Testing
Requirement
Specification Ensures that the code meets the
requirements specification and
System
Analysis weeds out bugs.
System
Design

Implementation

Testing
An independent team of software
engineers not involved in the design Deployment
and implementation of the project
usually conducts such testing. Maintenance

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
80
Deployment
Requirement
Specification Deployment makes the project
available for use.
System
Analysis

System
Design

Implementation

Testing

For a Java program, this means Deployment


installing it on a desktop or on the
Web. Maintenance

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
81
Maintenance
Requirement
Specification Maintenance is concerned with
changing and improving the
System
Analysis product.
System
Design

Implementation

Testing
A software product must continue to
perform and improve in a changing Deployment
environment. This requires periodic
upgrades of the product to fix newly Maintenance
discovered bugs and incorporate changes.
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
82
Problem:
Computing Loan Payments
This program lets the user enter the interest
rate, number of years, and loan amount, and
computes monthly payment and total
payment.
loanAmount ´ monthlyInterestRate
monthlyPayment =
1- 1
(1 + monthlyInterestRate) numberOfYears´12

ComputeLoan
Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
83
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

 Common Pitfall 1: Redundant Input Objects

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
84
Common Error 1:
Undeclared/Uninitialized Variables
and Unused Variables
double interestRate = 0.05;
double interest = interestrate * 45;

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
85
Common Error 2: Integer Overflow

int value = 2147483647 + 1;


// value will actually be -2147483648

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
86
Common Error 3: Round-off Errors
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

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
87
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 and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
88
Common Pitfall 1: Redundant Input
Objects
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int v1 = input.nextInt();

Scanner input1 = new Scanner(System.in);


System.out.print("Enter a double value: ");
double v2 = input1.nextDouble();

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
89
Common Pitfall 1: Redundant Input
Objects (cont.)
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int v1 = input.nextInt();
System.out.print("Enter a double value: ");
double v2 = input.nextDouble();

Liang, Introduction to Java Programming and Data Structures, Twelfth Edition, Global Edition,
Copyright © 2022 Pearson Education Ltd. All rights reserved.
90

You might also like