0% found this document useful (0 votes)
25 views829 pages

Exceptions 2

The document outlines key concepts in Java programming, focusing on inheritance, polymorphism, and object-oriented principles. It covers the use of constructors, methods, and class abstraction, emphasizing the importance of encapsulation and the differences between procedural and object-oriented paradigms. Additionally, it discusses the management of local variable scope and the use of ArrayLists for object manipulation.

Uploaded by

kgztjmqsss
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)
25 views829 pages

Exceptions 2

The document outlines key concepts in Java programming, focusing on inheritance, polymorphism, and object-oriented principles. It covers the use of constructors, methods, and class abstraction, emphasizing the importance of encapsulation and the differences between procedural and object-oriented paradigms. Additionally, it discusses the management of local variable scope and the use of ArrayLists for object manipulation.

Uploaded by

kgztjmqsss
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/ 829

EXCEPTION

HANDLING AND
TEXT I/O
Inheritance
and
Polymorphism

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Objectives
■ To define a subclass from a superclass through inheritance (§11.2).
■ To invoke the superclass’s constructors and methods using the super keyword (§11.3).
■ To override instance methods in the subclass (§11.4).
■ To distinguish differences between overriding and overloading (§11.5).
■ To explore the toString() method in the Object class (§11.6).
■ To discover polymorphism and dynamic binding (§§11.7–11.8).
■ To describe casting and explain why explicit downcasting is necessary (§11.9).
■ To explore the equals method in the Object class (§11.10).
■ To store, retrieve, and manipulate objects in an ArrayList (§11.11).
■ To construct an array list from an array, to sort and shuffle a list, and to obtain max and
min element from a list (§11.12).
■ To implement a Stack class using ArrayList (§11.13).
■ To enable data and methods in a superclass accessible from subclasses using the
protected visibility modifier (§11.14).
■ To prevent class extending and method overriding using the final modifier (§11.15)

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Object Oriented
Thinking
Objectives
■ To apply class abstraction to develop software (§10.2).
■ To explore the differences between the procedural paradigm and object-
oriented paradigm (§10.3).
■ To discover the relationships between classes (§10.4).
■ To design programs using the object-oriented paradigm (§§10.5–10.6).
■ To create objects for primitive values using the wrapper classes (Byte,
Short, Integer, Long, Float, Double, Character, and Boolean)(§10.7).
■ To simplify programming using automatic conversion between primitive
types and wrapper class types (§10.8).
■ To use the BigInteger and BigDecimal classes for computing very large
numbers with arbitrary precisions (§10.9).
■ To use the String class to process immutable strings (§10.10).
■ To use the StringBuilder and StringBuffer classes to process mutable strings
(§10.11).
Class Abstraction
• Class abstraction is the separation of class implementation from the use of
a class. The details of implementation are encapsulated and hidden from
the user. This is known as class encapsulation. Java provides many levels of
abstraction, and class abstraction separates class implementation from
how the class is used. The creator of a class describes the functions of the
class and lets the user know how the class can be used. The collection of
methods and fields that are accessible from outside the class, together
with the description of how these members are expected to behave, serves
as the class’s contract. As shown in Figure 10.1, the user of the class does
not need to know how the class is implemented. The details of
implementation are encapsulated and hidden from the user. This is called
class encapsulation. For example, you can create a Circle object and find
the area of the circle without knowing how the area is computed. For this
reason, a class is also known as an abstract data type (ADT).
OBJECTS AND CLASSES
Constructors
A constructor with no parameters is referred to as a
no-arg constructor or default constructor.
· Constructors must have the same name as the
class itself.
· Constructors do not have a return type—not
even void.
· Constructors are invoked using the new operator
when an object is created. Constructors play the
role of initializing objects.
10
Constructors
Constructors are a special
Circle() {
} kind of methods that are
invoked to construct objects.
Circle(double newRadius) {
radius = newRadius;
}

11
Default Constructor
A class may be defined without constructors. In
this case, a no-arg constructor with an empty body
is implicitly defined in the class. This constructor,
called a default constructor, is provided
automatically only if no constructors are explicitly
defined in the class.

12
Creating Objects Using
Constructors
new ClassName();

Example:
new Circle();

new Circle(5.0);

13
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.

To declare a reference variable, use the syntax:

ClassName objectRefVar;

Example:
Circle myCircle;

14
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();

Assign object reference Create an object


Example:
Circle myCircle = new Circle();

15
Accessing Object’s Members
❑ Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius

❑ Invoking the object’s method:


objectRefVar.methodName(arguments)
e.g., myCircle.getArea()

16
ARRAYS
A Main Method is Just a Regular Method
METHODS
Objectives
■ To define methods with formal parameters (§6.2).
■ To invoke methods with actual parameters (i.e., arguments) (§6.2).
■ To define methods with a return value (§6.3).
■ To define methods without a return value (§6.4).
■ To pass arguments by value (§6.5).
■ To develop reusable code that is modular, easy to read, easy to debug,
and easy to maintain (§6.6).
■ To use method overloading and understand ambiguous overloading (§6.8).
■ To determine the scope of variables (§6.9).
■ To apply the concept of method abstraction in software development
(§6.10).
■ To design and implement methods using stepwise refinement (§6.10).

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Scope of Local Variables
A local variable: a variable defined inside a
method.
Scope: the part of the program where the
variable can be referenced.
The scope of a local variable starts from its
declaration and continues to the end of the
block that contains the variable. A local variable
must be declared before it can be used.

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


• A parameter is actually a local variable. The scope of a method
parameter covers the entire method. A variable declared in the initial-
action part of a for-loop header has its scope in the entire loop.
However, a variable declared inside a for-loop body has its scope
limited in the loop body from its declaration to the end of the block
that contains the variable, as shown in Figure

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Scope of Local Variables, cont.
You can declare a local variable with the
same name multiple times in different non-
nesting blocks in a method, but you cannot
declare a local variable twice in nested
blocks.

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Scope of Local Variables, cont.
// Fine with no errors
public static void correctMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is declared again
for (int i = 1; i < 10; i++) {
y += i;
}
}
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Scope of Local Variables, cont.
// With errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
LOOPS

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Objectives
■ To write programs for executing statements repeatedly using a while loop (§5.2).
■ To follow the loop design strategy to develop loops (§§5.2.1–5.2.3).
■ To control a loop with a sentinel value (§5.2.4).
■ To obtain large input from a file using input redirection rather than typing from the
keyboard (§5.2.5).
■ To write loops using do-while statements (§5.3).
■ To write loops using for statements (§5.4).
■ To discover the similarities and differences of three types of loop statements (§5.5).
■ To write nested loops (§5.6).
■ To learn the techniques for minimizing numerical errors (§5.7).
■ To learn loops from a variety of examples (GCD, FutureTuition, Dec2Hex) (§5.8).
■ To implement program control with break and continue (§5.9).
■ To process characters in a string using a loop in a case study for checking palindrome
(§5.10).
■ To write a program that displays prime numbers (§5.11).
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
• Example: Write a program that prompts the user to enter a string and
displays the string in reverse order.

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


import java.util.Scanner;
public class Reverse {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

// Prompt the user to enter a string


System.out.print("Enter a string: ");
String string = input.nextLine();

// Reverse the string


String reverse = "";
for (int i = string.length() - 1; i >= 0; i--) {
reverse += string.charAt(i);
}

// Display the string in reverse order


System.out.println("The reversed string is " + reverse);
}
}

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Example:
• Use nested loops that display the following patterns in two separate
programs:

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


import java.util.Scanner;
public class Pattern_A {
public static void main(String[] args)
{
// Pattern A
System.out.println("Pattern A");
for (int rows = 1; rows <= 6; rows++) {
for (int cols = 1; cols <= rows ; cols++) {
System.out.print(cols + " ");
}
System.out.println();
}
}
}
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
import java.util.Scanner;
public class Pattern_B {
public static void main(String[] args)
{
System.out.println("Pattern B");
for (int r = 6; r >= 1; r--) {
for (int c = 1; c <= r; c++) {
System.out.print(c + " ");
}
System.out.println();
}
}
}

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
SELECTIONS AND
CONDITIONALS

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Objectives
▪To declare boolean variables and write Boolean expressions using relational operators
(§3.2).
▪To implement selection control using one-way if statements (§3.3).
▪To implement selection control using two-way if-else statements (§3.4).
▪To implement selection control using nested if and multi-way if statements (§3.5).
▪To avoid common errors and pitfalls in if statements (§3.6).
▪To generate random numbers using the Math.random() method (§3.7).
▪To program using selection statements for a variety of examples (SubtractionQuiz,
BMI, ComputeTax) (§§3.7–3.9).
▪To combine conditions using logical operators (&&, ||, and !) (§3.10).
▪To program using selection statements with combined conditions (LeapYear, Lottery)
(§§3.11–3.12).
▪To implement selection control using switch statements (§3.13).
▪To write expressions using the conditional expression (§3.14).
▪To examine the rules governing operator precedence and associativity (§3.15)
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Remark

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
****System.currentTimeMillis(): returns the difference, measured in milliseconds,
between the current time and midnight, January 1, 1970 UTC.

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Possible output:
6 8 10 10 5 3 6 10 4 2
GeeksforGeeks
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Extra Example:

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Mathematical Functions,
Characters and Strings

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Objectives
■ To solve mathematical problems by using the methods in the Math class (§4.2).
■ To represent characters using the char type (§4.3).
■ To represent special characters using the escape sequences (§4.4.2).
■ To cast a numeric value to a character and cast a character to an integer (§4.3.3).
■ To compare and test characters using the static methods in the Character class (§4.3.4).
■ To introduce objects and instance methods (§4.4).
■ To represent strings using the String object (§4.4).
■ To return the string length using the length() method (§4.4.1).
■ To return a character in the string using the charAt(i) method (§4.4.2).
■ To use the + operator to concatenate strings (§4.4.3).
■ To return an uppercase string or a lowercase string and to trim a string (§4.4.4).
■ To read strings from the console (§4.4.5).
■ To read a character from the console (§4.4.6).
■ To compare strings using the equals method and the compareTo methods (§4.4.7).
■ To obtain substrings (§4.4.8).
■ To find a character or a substring in a string using the indexOf method (§4.4.9).
■ To program using characters and strings (GuessBirthday) (§4.5.1).
■ To revise the lottery program using strings (LotteryUsingStrings) (§4.5.3).
■ To format output using the System.out.printf method (§4.6)
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns -2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(4.5) returns 4.0
Math.rint(-2.5) returns -2.0

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Math.max(2, 3) returns 3
Math.max(2.5, 3) returns 3.0
Math.min(2.5, 4.6) returns 2.5
Math.abs(-2) returns 2
Math.abs(-2.1) returns 2.1

Introduction to Java Programming, 10th Edition,Y.Daniel Liang


Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Introduction to Java Programming, 10th Edition,Y.Daniel Liang
Motivations
In the preceding chapter, you learned how to create,
compile, and run a Java program. Starting from this
chapter, you will learn how to solve practical problems
programmatically. Through these problems, you will learn
Java primitive data types and related subjects, such as
variables, constants, data types, operators, expressions,
and input and output.

1 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
Objectives
To write Java programs to perform simple computations (§2.2).
To obtain input from the console using the Scanner class (§2.3).
To use identifiers to name variables, constants, methods, and classes (§2.4).
To use variables to store data (§§2.5–2.6).
To program with assignment statements and assignment expressions (§2.6).
To use constants to store permanent data (§2.7).
To name classes, methods, variables, and constants by following their naming conventions (§2.8).
To explore Java numeric primitive data types: byte, short, int, long, float, and double (§2.9.1).
To read a byte, short, int, long, float, or double value from the keyboard (§2.9.2).
To perform operations using operators +, -, *, /, and % (§2.9.3).
To perform exponent operations using Math.pow(a, b) (§2.9.4).
To write integer literals, floating-point literals, and literals in scientific notation (§2.10).
To write and evaluate numeric expressions (§2.11).
To use augmented assignment operators (§2.13).
To distinguish between postincrement and preincrement and between postdecrement and predecrement (§2.14).
To cast the value of one type to another type (§2.15).
To write a program that converts a large amount of money into smaller units (§2.17).
To avoid common errors and pitfalls in elementary programming (§2.18).

2 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 3
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);
}
}

4 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
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
for area
// Compute area
area = radius * radius * 3.14159;

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

5 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
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);
}
}

6 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
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);
}
}

7 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
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);
}
}

8 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 9
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 10
Reading Input from the Console

Introduction to Java Programming, 10th Edition,Y.Daniel Liang 11


Introduction to Java Programming, 10th Edition,Y.Daniel Liang 12
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 13
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 14
Identifiers

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.
An identifier cannot be true, false, or
null.
An identifier can be of any length.

15 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
Variables
Variables are used to represent values that may be changed in the program.

Variables are for representing data of a certain type. To use a variable, you declare
it by telling the compiler its name as well as what type of data it can store. The
variable declaration tells the compiler to allocate appropriate memory space for the
variable based on its data type.
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 16
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 17
Named Constants

A constant must be declared and initialized in the same statement. The word
final is a Java keyword for declaring a constant.

Introduction to Java Programming, 10th Edition,Y.Daniel Liang 18


Introduction to Java Programming, 10th Edition,Y.Daniel Liang 19
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.

20 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
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

21 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
Numerical Data Types and Operations

Numeric Types

Introduction to Java Programming, 10th Edition,Y.Daniel Liang 22


Introduction to Java Programming, 10th Edition,Y.Daniel Liang 23
• Java uses four types for integers: byte, short, int, and long.
Choose the type that is most appropriate for your variable.
For example, if you know an integer stored in a variable is
within a range of a byte, declare the variable as a byte.

• Java uses two types for floating-point numbers: float and


double. The double type is twice as big as float, so the
double is known as double precision and float as single
precision. Normally, you should use the double type,
because it is more accurate than the float type.

Introduction to Java Programming, 10th Edition,Y.Daniel Liang 24


Reading Numbers from the Keyboard

Introduction to Java Programming, 10th Edition,Y.Daniel Liang 25


Introduction to Java Programming, 10th Edition,Y.Daniel Liang 26
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

27 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
Integer Division

+, -, *, /, and %

5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the division)

28 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
Exponent Operations

Introduction to Java Programming, 10th Edition,Y.Daniel Liang 29


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;

30 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 31
double vs. float

Introduction to Java Programming, 10th Edition,Y.Daniel Liang 32


Augmented Assignment Operators

Introduction to Java Programming, 10th Edition,Y.Daniel Liang 33


Increment and Decrement Operators

Introduction to Java Programming, 10th Edition,Y.Daniel Liang 34


Introduction to Java Programming, 10th Edition,Y.Daniel Liang 35
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 36
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 37
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 38
Numeric Type Conversion

Introduction to Java Programming, 10th Edition,Y.Daniel Liang 39


Introduction to Java Programming, 10th Edition,Y.Daniel Liang 40
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 41
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.

42 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 43
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 44
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 45
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 46
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 47
Software Development Process

48 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
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.
49 10th Edition,Y.Daniel Liang
Introduction to Java Programming,
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.
50 10th Edition,Y.Daniel Liang
Introduction to Java Programming,
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.
51 10th Edition,Y.Daniel Liang
Introduction to Java Programming,
IPO
Requirement
Specification

System
Analysis Input, Process, Output

System
Design

Implementation

Testing

The essence of system analysis and design is input,


process, and output. This is called IPO. Deployment

Maintenance

52 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
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

53 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
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

54 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
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

55 10th Edition,Y.Daniel Liang


Introduction to Java Programming,
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.
56 10th Edition,Y.Daniel Liang
Introduction to Java Programming,
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 57
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 58
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 59
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 60
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 61
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 62
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 63
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 64
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 65
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 66
Introduction to Java Programming, 10th Edition,Y.Daniel Liang 67
Java How to Program, 8/e

(C) 2010 Pearson Education, Inc. All rights reserved.


(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Java application
▪ A computer program that executes when you use the java
command to launch the Java Virtual Machine (JVM).
 Sample program in Fig. 2.1 displays a line of text.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Comments
// Fig. 2.1: Welcome1.java
▪ // indicates that the line is a comment.
▪ Used to document programs and improve their readability.
▪ Compiler ignores comments.
▪ A comment that begins with // is an end-of-line comment—it
terminates at the end of the line on which it appears.
 Traditional comment, can be spread over several lines as in
/* This is a traditional comment. It
can be split over multiple lines */
▪ This type of comment begins with /* and ends with */.
▪ All text between the delimiters is ignored by the compiler.

(C) 2010 Pearson Education, Inc. All


rights reserved.
 Javadoc comments
▪ Delimited by /** and */.
▪ All text between the Javadoc comment delimiters is ignored by
the compiler.
▪ Enable you to embed program documentation directly in your
programs.
▪ The javadoc utility program (Appendix M) reads Javadoc
comments and uses them to prepare your program’s
documentation in HTML format.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Blank lines and space characters
▪ Make programs easier to read.
▪ Blank lines, spaces and tabs are known as white space (or
whitespace).
▪ White space is ignored by the compiler.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Class declaration
public class Welcome1
▪ Every Java program consists of at least one class that you
define.
▪ class keyword introduces a class declaration and is
immediately followed by the class name.
▪ Keywords (Appendix C) are reserved for use by Java and are
always spelled with all lowercase letters.

(C) 2010 Pearson Education, Inc. All


rights reserved.
 Class names
▪ By convention, begin with a capital letter and capitalize the
first letter of each word they include (e.g.,
SampleClassName).
▪ A class name is an identifier—a series of characters consisting
of letters, digits, underscores (_) and dollar signs ($) that does
not begin with a digit and does not contain spaces.
▪ Java is case sensitive—uppercase and lowercase letters are
distinct—so a1 and A1 are different (but both valid)
identifiers.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Braces
▪ A left brace, {, begins the body of every class declaration.
▪ A corresponding right brace, }, must end each class declaration.
▪ Code between braces should be indented.
▪ This indentation is one of the spacing conventions mentioned
earlier.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Declaring the main Method
public static void main( String[] args )
▪ Starting point of every Java application.
▪ Parentheses after the identifier main indicate that it’s a
program building block called a method.
▪ Java class declarations normally contain one or more methods.
▪ main must be defined as shown; otherwise, the JVM will not
execute the application.
▪ Methods perform tasks and can return information when they
complete their tasks.
▪ Keyword void indicates that this method will not return any
information.

(C) 2010 Pearson Education, Inc. All


rights reserved.
 Body of the method declaration
▪ Enclosed in left and right braces.
 Statement
System.out.println("Welcome to Java Programming!");
▪ Instructs the computer to perform an action
 Print the string of characters contained between the double
quotation marks.
▪ A string is sometimes called a character string or a string
literal.
▪ White-space characters in strings are not ignored by the
compiler.
▪ Strings cannot span multiple lines of code.

(C) 2010 Pearson Education, Inc. All


rights reserved.
 System.out object
▪ Standard output object.
▪ Allows Java applications to display strings in the command
window from which the Java application executes.
 System.out.println method
▪ Displays (or prints) a line of text in the command window.
▪ The string in the parentheses the argument to the method.
▪ Positions the output cursor at the beginning of the next line in
the command window.
 Most statements end with a semicolon.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Class Welcome2, shown in Fig. 2.3, uses two
statements to produce the same output as that shown in
Fig. 2.1.
 New and key features in each code listing are
highlighted.
 System.out’s method print displays a string.
 Unlike println, print does not position the output
cursor at the beginning of the next line in the command
window.
▪ The next character the program displays will appear
immediately after the last character that print displays.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Newline characters indicate to System.out’s print and
println methods when to position the output cursor at
the beginning of the next line in the command window.
 Newline characters are white-space characters.
 The backslash (\) is called an escape character.
▪ Indicates a “special character”
 Backslash is combined with the next character to form an
escape sequence.
 The escape sequence \n represents the newline character.
 Complete list of escape sequences
java.sun.com/docs/books/jls/third_edition/html/
lexical.html#3.10.6.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 System.out.printf method
▪ f means “formatted”
▪ displays formatted data
 Multiple method arguments are placed in a comma-separated list.
 Java allows large statements to be split over many lines.
▪ Cannot split a statement in the middle of an identifier or string.
 Method printf’s first argument is a format string
▪ May consist of fixed text and format specifiers.
▪ Fixed text is output as it would be by print or println.
▪ Each format specifier is a placeholder for a value and specifies the type
of data to output.
 Format specifiers begin with a percent sign (%) and are followed
by a character that represents the data type.
 Format specifier %s is a placeholder for a string.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Integers
▪ Whole numbers, like –22, 7, 0 and 1024)
 Programs remember numbers and other data in the
computer’s memory and access that data through
program elements called variables.
 The program of Fig. 2.7 demonstrates these concepts.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 import declaration
▪ Helps the compiler locate a class that is used in this program.
▪ Rich set of predefined classes that you can reuse rather than
“reinventing the wheel.”
▪ Classes are grouped into packages—named groups of related
classes—and are collectively referred to as the Java class
library, or the Java Application Programming Interface (Java
API).
▪ You use import declarations to identify the predefined
classes used in a Java program.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Variable declaration statement
Scanner input = new Scanner( System.in );
▪ Specifies the name (input) and type (Scanner) of a variable that
is used in this program.
 Variable
▪ A location in the computer’s memory where a value can be stored for
use later in a program.
▪ Must be declared with a name and a type before they can be used.
▪ A variable’s name enables the program to access the value of the
variable in memory.
▪ The name can be any valid identifier.
▪ A variable’s type specifies what kind of information is stored at that
location in memory.

(C) 2010 Pearson Education, Inc. All


rights reserved.
 Scanner
▪ Enables a program to read data for use in a program.
▪ Data can come from many sources, such as the user at the keyboard or a
file on disk.
▪ Before using a Scanner, you must create it and specify the source of
the data.
 The equals sign (=) in a declaration indicates that the variable
should be initialized (i.e., prepared for use in the program) with
the result of the expression to the right of the equals sign.
 The new keyword creates an object.
 Standard input object, System.in, enables applications to read
bytes of information typed by the user.
 Scanner object translates these bytes into types that can be
used in a program.

(C) 2010 Pearson Education, Inc. All


rights reserved.
 Variable declaration statements
int number1; // first number to add
int number2; // second number to add
int sum; // sum of number1 and number2
declare that variables number1, number2 and sum hold
data of type int
▪ They can hold integer.
▪ Range of values for an int is –2,147,483,648 to +2,147,483,647.
▪ Actual int values may not contain commas.
 Several variables of the same type may be declared in one
declaration with the variable names separated by commas.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Prompt
▪ Output statement that directs the user to take a specific action.
 System is a class.
▪ Part of package java.lang.
▪ Class System is not imported with an import declaration at
the beginning of the program.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Scanner method nextInt
number1 = input.nextInt(); // read first number from
user
▪ Obtains an integer from the user at the keyboard.
▪ Program waits for the user to type the number and press the
Enter key to submit the number to the program.
 The result of the call to method nextInt is placed in
variable number1 by using the assignment operator, =.
▪ “number1 gets the value of input.nextInt().”
▪ Operator = is called a binary operator—it has two operands.
▪ Everything to the right of the assignment operator, =, is always
evaluated before the assignment is performed.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Arithmetic
sum = number1 + number2; // add numbers
▪ Assignment statement that calculates the sum of the variables
number1 and number2 then assigns the result to variable sum
by using the assignment operator, =.
▪ “sum gets the value of number1 + number2.”
▪ In general, calculations are performed in assignment statements.
▪ Portions of statements that contain calculations are called
expressions.
▪ An expression is any portion of a statement that has a value
associated with it.

(C) 2010 Pearson Education, Inc. All


rights reserved.
 Integer formatted output
System.out.printf( "Sum is %d\n", sum );
▪ Format specifier %d is a placeholder for an int value
▪ The letter d stands for “decimal integer.”

(C) 2010 Pearson Education, Inc. All


rights reserved.
 Variables
▪ Every variable has a name, a type, a size (in bytes) and a value.
▪ When a new value is placed into a variable, the new value
replaces the previous value (if any)
▪ The previous value is lost.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Arithmetic operators are summarized in Fig. 2.11.
 The asterisk (*) indicates multiplication
 The percent sign (%) is the remainder operator
 The arithmetic operators are binary operators because
they each operate on two operands.
 Integer division yields an integer quotient.
▪ Any fractional part in integer division is simply discarded (i.e.,
truncated)—no rounding occurs.
 The remainder operator, %, yields the remainder after
division.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Arithmetic expressions in Java must be written in
straight-line form to facilitate entering programs into
the computer.
 Expressions such as “a divided by b” must be written
as a / b, so that all constants, variables and operators
appear in a straight line.
 Parentheses are used to group terms in expressions in
the same manner as in algebraic expressions.
 If an expression contains nested parentheses, the
expression in the innermost set of parentheses is
evaluated first.

(C) 2010 Pearson Education, Inc. All


rights reserved.
 Rules of operator precedence
▪ Multiplication, division and remainder operations are applied first.
▪ If an expression contains several such operations, they are applied from
left to right.
▪ Multiplication, division and remainder operators have the same level of
precedence.
▪ Addition and subtraction operations are applied next.
▪ If an expression contains several such operations, the operators are
applied from left to right.
▪ Addition and subtraction operators have the same level of precedence.
 When we say that operators are applied from left to right, we are
referring to their associativity.
 Some operators associate from right to left.
 Complete precedence chart is included in Appendix A.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 As in algebra, it’s acceptable to place redundant
parentheses (unnecessary parentheses) in an ex-
pression to make the expression clearer.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 Condition
▪ An expression that can be true or false.
 if selection statement
▪ Allows a program to make a decision based on a condition’s value.
 Equality operators (== and !=)
 Relational operators (>, <, >= and <=)
 Both equality operators have the same level of precedence,
which is lower than that of the relational operators.
 The equality operators associate from left to right.
 The relational operators all have the same level of
precedence and also associate from left to right.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
 An if statement always begins with keyword if,
followed by a condition in parentheses.
▪ Expects one statement in its body, but may contain multiple
statements if they are enclosed in a set of braces ({}).
▪ The indentation of the body statement is not required, but it
improves the program’s readability by emphasizing that
statements are part of the body.
 Note that there is no semicolon (;) at the end of the
first line of each if statement.
▪ Such a semicolon would result in a logic error at execution
time.
▪ Treated as the empty statement—semicolon by itself.

(C) 2010 Pearson Education, Inc. All


rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.
(C) 2010 Pearson Education, Inc. All
rights reserved.

You might also like