0% found this document useful (0 votes)
52 views

Chapter 01

1) The document discusses the fundamentals of Java programming including data types, control statements, loop statements, and methods. 2) It provides examples of Java's versatility in developing standalone applications, applets, servlets, and applications for mobile devices. 3) The key aspects of Java covered are that it is a simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, multithreaded, and dynamic programming language.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

Chapter 01

1) The document discusses the fundamentals of Java programming including data types, control statements, loop statements, and methods. 2) It provides examples of Java's versatility in developing standalone applications, applets, servlets, and applications for mobile devices. 3) The key aspects of Java covered are that it is a simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, multithreaded, and dynamic programming language.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Advanced Programming

Language
MSc. Nguyen Cao Dat
[email protected]

Chapter I
FUNDAMENTALS OF PROGRAMMING

1
Content

Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods

Content

Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods

2
Introduction
Why Java?
- Java is a general purpose programming language.
- Java is the Internet programming language.
- Java can be used to develop Web applications.
- Java can also be used to develop applications for smart
phone with Android OS.

Introduction
Examples of Java’s Versatility
Standalone Application: TicTacToe
Applet: TicTacToe
Servlets: SelfTest Web site
Mobile Computing: Cell phones

3
TicTacToe Standalone

TicTacToe Applet

4
SelfTest Website (using Java Servlets)

PDA and Cell Phone

10

10

5
Introduction
In 1991, James Gosling of Sun
Microsystems designed what
would become the Java
programming language
– In 2010, Sun was acquired by
Oracle
Platform independent
– Can run on almost any machine
Used to create Internet
applets

11

11

Introduction
Characteristics of Java
– Java Is Simple
– Java Is Object-Oriented
– Java Is Distributed
– Java Is Interpreted
– Java Is Robust
– Java Is Secure
– Java Is Architecture-Neutral
– Java Is Portable
– Java Is Multithreaded
– Java Is Dynamic

12

12

6
Introduction
JDK Editions
– Java Standard Edition (J2SE)
J2SE can be used to develop client-side standalone
applications or applets.
– Java Enterprise Edition (J2EE)
J2EE can be used to develop server-side applications such as
Java servlets and Java ServerPages.
– Java Micro Edition (J2ME).
J2ME can be used to develop applications for mobile devices.
This course uses J2SE to introduce Java programming.

13

13

JDK(Java Development Kit) Versions

14

14

7
Java Virtual Machine (JVM)
Java code starts as
source code (human-
readable)
A compiler converts it
into machine readable
code (byte code)
Any JVM can then run
the code, which is in a
.class file
15

15

Introduction
The Java Platform consists of
two parts
– Java Virtual Machine (JVM)
– Java Application Programming
Interface (API)
A huge collection of handy software
packages that programmers can use
– Graphics, user interface, networking,
sound, database, math, etc.
Helps programmers not have to
reinvent the wheel
16

16

8
Introduction
Java Development Kit (JDK)
– To be able to create Java programs, you must
install the Java Development Kit (JDK)
– Download: http://www.oracle.com/java/
– Common location after installation will be:
C:\Program Files\Java\jdk_____ (a set of numbers)
The set of numbers will vary with the release
– The JDK includes programs such as:
javac.exe (Java compiler)
javadoc.exe (Javadoc generator)
java.exe (executes Java applications)

17

17

Java Integrated Development


Environment (IDE)
There are many free programming tools
available for Java
jGrasp (http://www.jgrasp.org/) is strongly
recommended for this course instead of
anything else (e.g. NetBeans, Eclipse, etc.)
Source code editor helps programming by:
– Lists line numbers
– Color codes special words
– Helps with indenting for readability
Output window
18

18

9
jGrasp: An Example IDE

Editor

Many IDEs are


designed specifically
for Java programming

Output

19

19

Text Editor Programming


You do not need to have an IDE
You can use a simple text editor, such as Notepad to write your
source code
Assuming a code file named, HelloPrinter.java, you can use a
command prompt to:
– Compile the program
– Execute the program

Compile
Output Execute

20

20

10
jGrasp: Compiling a Program

Click the "+"


icon to
compile the
program

Result

21

21

jGrasp: Running a Program

Click the red "Running


Man" icon to execute the
program

Output

22

22

11
Source Code to Running Program

The compiler generates .class files for each


.java file, which contains machine-readable
instructions for the Java Virtual Machine
(JVM)
.class files contain 'byte code' that are machine
readable and uneditable

23

23

Organize Your Work


Source code is stored in .java files
Create one folder per program
– A program can have many .java files
Be sure you know where the IDE stores
your files
"**IT Happens"
– Backup your work!
Backup your work to a Flash Drive, external
hard drive, network drive, or cloud storage that
is backed up nightly.

24

24

12
Hello World: Your First Java Program
Below is a traditional "Hello World" program in Java
– The name of the file is HelloWorld.java
Typing the program into your IDE would be good practice!
– Be careful of spelling
– JaVa iS CaSe SeNsItiVe
– Java uses special characters, such as curly braces {} and parentheses ()
– Java ignores whitespace

25

25

Analyzing Your First Java Program

Line 1: Declares a class called HelloWorld


– Java programs are constructed with one or more classes
Line 2: Declares a method called main
– Every Java program has exactly one main method
– The main method is the entry point where the program starts
Line 3: Method System.out.println outputs "Hello World"
– System.out is part of the Java API
– All statements must end with a semicolon

26

26

13
Calling Java API Methods
Note the Line:

It shows how to "call" a method from the Java


API (System.out.println)
– Code that somebody else wrote for you
– Notice the dots (periods)
– Parentheses surround the arguments that you "pass" to a
method
We are passing a String "Hello World"
Using double quotes denotes a string
– You can also print numeric values
Example: System.out.println(106);
Example: System.out.println(3 + 4);
Note that numbers are not quoted
27

27

More on the println Method


The println method prints a
string or a number and then
starts a new line
– System.out.println("Hello"); Hello
– System.out.println("World!"); World!
A similar function that does
not print a new line is print
– System.out.print("00"); 007
– System.out.println(3+4);

28

28

14
Errors
Syntax Errors
– Examples
Misspelling, capitalization, punctuation
Ordering of statements, matching of braces/parentheses
– No .class file is generated by the compiler
– Correct the first error listed, then compile again
Logic Errors
– Program runs, but produces unintended results
– Check your algorithm for the logic you have included
Runtime Errors
– Causes the program to crash immediately, such as divide
by zero
– Check your algorithm to make sure you have handled all
cases
29

29

Syntax Errors

What happens if you:


– misspell a word System.ou.println
– don't capitalize a word system.out.println
– leave out a word System.println
– forget a semicolon Remove ; at the end of line 3
– don't match a curly brace Remove line 5
Try each of these to see what happens when you try to
compile to get practice in dealing with compiler error
messages

30

30

15
Logic Errors

What happens if you:


– misspell the output ("Hello Word")
– forget to output Remove line 3
In these cases, the program will compile
and run
– The output may not be as expected
31

31

Runtime Errors

What happens if you:


– Divide by zero System.out.println(1/0)
In these cases, the program will compile, but when it
runs, it will crash

32

32

16
Anatomy of a Java Program
Comments
Package
Reserved words
Modifiers
Statements
Blocks
Classes
Methods
The main method
33

33

Comments
In Java, comments are preceded by two slashes (//) in a
line, or enclosed between /* and */ in one or multiple
lines. When the compiler sees //, it ignores all text after //
in the same line. When it sees /*, it scans for the next */
and ignores any text between /* and */.

34

34

17
Package
The second line in the program (package chapter1;)
specifies a package name, chapter1, for the class
Welcome. IDE compiles the source code in
Welcome.java, generates Welcome.class, and stores
Welcome.class in the chapter1 folder.

35

35

Reserved Words
Reserved words or keywords are words that have a
specific meaning to the compiler and cannot be used for
other purposes in the program. For example, when the
compiler sees the word class, it understands that the word
after class is the name for the class. Other reserved words
in Listing 1.1 are public, static, and void. Their use will
be introduced later in the book.

36

36

18
Modifiers
Java uses certain reserved words called modifiers that
specify the properties of the data, methods, and
classes and how they can be used. Examples of
modifiers are public and static. Other modifiers are
private, final, abstract, and protected. A public datum,
method, or class can be accessed by other programs.
A private datum or method cannot be accessed by
other programs. Modifiers are discussed in Chapter 6,
“Objects and Classes.”

37

37

Classes
The class is the essential Java construct. A class is a
template or blueprint for objects. To program in Java,
you must understand classes and be able to write and use
them. The mystery of the class will continue to be
unveiled throughout this course. For now, though,
understand that a program is defined by using one or
more classes.

38

38

19
Methods
What is System.out.println? It is a method: a collection
of statements that performs a sequence of operations to
display a message on the console. It can be used even
without fully understanding the details of how it works.
It is used by invoking a statement with a string argument.
The string argument is enclosed within parentheses. In
this case, the argument is "Welcome to Java!" You can
call the same println method with a different argument to
print a different message.

39

39

main Method
The main method provides the control of program flow. The
Java interpreter executes the application by invoking the main
method.

The main method looks like this:

public static void main(String[] args) {


// Statements;
}

40

40

20
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. (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.

41

41

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);

42

42

21
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;

43

43

Assignment Statements
x = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to radius;


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

44

44

22
Declaring and Initializing
in One Step
int x = 1;
double d = 1.4;

45

45

Constants
final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159;


final int SIZE = 3;

46

46

23
Programming Style and
Documentation
Appropriate Comments
Naming Conventions
Proper Indentation and Spacing Lines
Block Styles

47

47

Appropriate Comments
Include a summary at the beginning of the
program to explain what the program does, its
key features, its supporting data structures, and
any unique techniques it uses.

Include your name, class section, instructor,


date, and a brief description at the beginning of
the program.

48

48

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

49

49

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

50

50

25
Proper Indentation and Spacing
Indentation
– Indent two spaces.

Spacing
– Use blank line to separate segments of the code.

51

51

Block Styles
Use end-of-line style for braces.

Next-line public class Test


style {
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}

End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}

52

52

26
Content

Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods

53

53

Variable Data Types


Data types are used to tell the compiler what type of data you
are trying to store
– Helps to allocate the correct amount of memory
Common Types
– A whole number (no fraction) – int
– A number with a fraction part – double
– A single character – char
– A word (a group of characters) – String
The type is specified when declaring the variable
– Example: int cansPerPack = 6;
– Example: double canVolume = 12.0;
– Example: String name = "Jack";
Back to the garage analogy, parking spaces may be different
sizes for different types of vehicles
– E.g. bicycle, motorcycle, full size, van, etc.

54

27
Variable Data Types (Cont'd)
Integer Types (Whole numbers, no fractions)
– byte: a very small number (-127 to +128)
– short: a small number (-32,768 to +32,767)
– int: a large number (-2,147,483,648 to +2,147,483,647)
– long: a huge number
Floating Point Types
– float: a huge number with decimal places
– double: a more precise, floating type, used for calculations
Other Types
– boolean: true or false
– char: one symbol in single quotes, such as: 'a'

55

Variable Data Type Storage


Integer Types (Whole numbers, no fractions)
– byte:
– short:
– int:
– long:
Floating Point Types
– float:
– double:
Other Types
– boolean:
– char:

56

28
IT 106: Introduction to IT Problem Solving Using Computer Programming

Number Literal Examples in Java

Use the
double
type for
floating-
point numbers.

57

IT 106: Introduction to IT Problem Solving Using Computer Programming

Java Comments
There are three forms of comments
– // a single line comment (or rest of line to the right)
– /*
multi-line comment – all comments within /* */
*/
– /**
multi-line Javadoc comments – used to automatically
generate documentation
*/
The compiler ignores commented code
Use comments at the beginning of each program and
within the program to clarify details of the code

58

29
IT 106: Introduction to IT Problem Solving Using Computer Programming

Java Comment Example


External
Documentation

Internal
Documentation

Lines 1-5 are Javadoc comments for the class "SodaCanVolume"


Line 10 uses a single-line comment to clarify the unit of measurement
Line 12 shows what the following three lines after it are doing

59

IT 106: Introduction to IT Problem Solving Using Computer Programming

Common Variable Errors


• Undeclared Variables
– You must declare a variable before you use it: (i.e.
above in the code)
double canVolume = 12 * literPerOunce; // ??
double literPerOunce = 0.0296;
• Uninitialized Variables
– You must initialize (i.e. set) a variable’s contents
before you use it
int bottles;
int bottleVolume = bottles * 2; // ??

60

30
IT 106: Introduction to IT Problem Solving Using Computer Programming
Common Variable Errors
• Overflow
(Cont'd)
– The storage for the variable cannot correctly hold the value
– Example: Remember the int data type can store values in
the range of -2,147,483,648 to +2,147,483,647
• int oneThousand = 1000; // OK
• int oneMillion = 1000 * oneThousand; // OK
• int oneBillion = 1000 * oneMillion; // OK
• System.out.println(3 * oneBillion); // ??
– Output will print: -1294976296
– Why?
• The result (3 billion) overflowed the capacity of an int, truncated
the value, and provided something useless
– To fix this, use a long (if integer) or a double (if floating
point)

61

IT 106: Introduction to IT Problem Solving Using Computer Programming

Variable Assignment
You can use the assignment operator (=) to
place a new value into a variable
int cansPerPack = 6; //declare and initialize
cansPerPack = 8; //assignment
Warning! The = sign is NOT used for
comparison
– It copies the value on the right side into the
variable on the left side
The variable MUST be on the left side for assignment
– Comparisons will be covered a bit later

62

31
IT 106: Introduction to IT Problem Solving Using Computer Programming

Incrementing a Variable

Code: counter = counter + 1;


Steps:
1. Do the right hand of the assignment first
Find the value stored in counter, then add 1 to it
2. Store the result in the variable named on the left side
of the assignment operator (counter in this case)

63

IT 106: Introduction to IT Problem Solving Using Computer Programming

Shorthand for Incrementing


Incrementing (+1) and decrementing (-1)
integer types is so common that there is a
shorthand version for each

64

32
IT 106: Introduction to IT Problem Solving Using Computer Programming

Modifying a Variable
Assumes counter has already been declared using int counter;

65

IT 106: Introduction to IT Problem Solving Using Computer Programming

Syntax: Assignment
Review of the assignment statement
– The value on the right is copied to the variable on the left

66

33
IT 106: Introduction to IT Problem Solving Using Computer Programming

Constants
It is a good practice to declare values that will
not change during program execution as
constants
Use the reserved word final before the type
in the declaration
– Example: final double BOTTLE_VOLUME = 1.75;
– They can then be used like any other variable
double volume = bottles * BOTTLE_VOLUME;
Constants are usually declared near the
beginning of the program or class
You cannot assign a new value
to a constant at run-time.

67

IT 106: Introduction to IT Problem Solving Using Computer Programming

INPUT/OUTPUT

68

34
IT 106: Introduction to IT Problem Solving Using Computer Programming
Using a Graphical User
Interface
Previously for output, we have been using
System.out.println to print to the IDE or
a console window
Users are now used to seeing graphical
interfaces instead of just a text-based
command prompt
For now, don't worry about the details
– Pay attention to the format of the code

69

IT 106: Introduction to IT Problem Solving Using Computer Programming

Using a GUI for Output


JOptionPane: Package that provides dialog
boxes for GUI output
– Benefit: Makes your program look "prettier"
Implementation
– Import Java package containing JOptionPane class
Use: import javax.swing.JOptionPane; at
the top of your .java file
– Use showMessageDialog() method, which is
similar to println(), but takes in two pieces of data
instead
Pass null and the String you want to output

70

35
IT 106: Introduction to IT Problem Solving Using Computer Programming

Using a GUI for Output


Old

New

71

IT 106: Introduction to IT Problem Solving Using Computer Programming

Reading Input
You frequently will need to ask the user
for input (i.e. prompt them) and then
save what was entered
– We will be reading input from the keyboard

72

36
IT 106: Introduction to IT Problem Solving Using Computer Programming

Reading Input (Cont'd)


Three step process to do this, using a GUI
– Import Java package containing JOptionPane class
Use: import javax.swing.JOptionPane; at the top of
your .java file
– Use methods of the JOptionPane class to show an input
dialog
Use: JOptionPane.showInputDialog("MessageToUser");
– In the same line, convert the input entered into the correct
data type if the data type is numeric and calculations will
be needed

73

IT 106: Introduction to IT Problem Solving Using Computer Programming

Example: Reading Input

74

37
IT 106: Introduction to IT Problem Solving Using Computer Programming

ARITHMETIC OPERATIONS

75

IT 106: Introduction to IT Problem Solving Using Computer Programming

Arithmetic Operations
Java supports all of the same
basic calculator operations
– Addition, subtraction,
multiplication, division
However, Java expressions may No Yes
only be written on one line
Precedence is similar to
Algebra
– Remember PEMDAS
Parentheses, exponents,
multiplication/division,
addition/subtraction

76

38
IT 106: Introduction to IT Problem Solving Using Computer Programming
Integer Division and
Remainders
If both operands are integer types, you need to be
careful not to lose precision
int first = 7, second = 4, answer;
answer = first / second; // answer is 1!
– The result is an integer. The fraction was lost.
To find the fractional part, use the modulo
operator (%)
int first = 7, second = 4, answer, remainder;
answer = first / second;
remainder = first % second; // set to 3
You could also use floating-point data types,
instead

77

IT 106: Introduction to IT Problem Solving Using Computer Programming

Powers and Roots


There are no symbols for powers and roots
– But, methods exist in the Java Math class

Java

78

39
IT 106: Introduction to IT Problem Solving Using Computer Programming

Powers and Roots (Cont'd)

79

IT 106: Introduction to IT Problem Solving Using Computer Programming

CONVERTING AND
FORMATTING DATA

80

40
IT 106: Introduction to IT Problem Solving Using Computer Programming
Converting Between Data
Types
It is safe to convert a value from an integer data type
to a floating point data type
– No decimal points (precision) is lost
Going the other way can be dangerous
– All fractional information is lost
– To "force" a conversion, variables can be cast from one type
to another
– Example
double balance = total + tax;
int dollars = (int) balance;
The fractional part is discarded (not rounded)
If you do not use the cast, the compiler will generate a syntax
error

81

IT 106: Introduction to IT Problem Solving Using Computer Programming

Formatted Output
Outputting floating point values can look
strange, such as at gas stations
– Example: Price per liter = 1.21997
To control the output appearance we can create
and format a String containing a number
through a format specifier
Once the string has been formatted, we can
output it
The book covers more detailed ways you can
format your output
Note: Not all format specifiers are supported using JOptionPane

82

41
IT 106: Introduction to IT Problem Solving Using Computer Programming

Formatted Output (Cont'd)

83

IT 106: Introduction to IT Problem Solving Using Computer Programming

Common Errors
Unintended Integer Division

Why an error?
– Since all of the data types are integers, the compiler performs
integer division
– Then the resulting integer is assigned to a double
– When decimal points are important, use a floating-point type

84

42
IT 106: Introduction to IT Problem Solving Using Computer Programming

Common Errors (Cont'd)


Unbalanced Parentheses
The count of ( and ) must match
– Incorrect: -(b * b - (4 * a * c) ) ) / 2 *
a)
It can be difficult to keep track
– Trick:
Count ( as + 1 and ) as -1. Goal : 0
– Example:
-(b * b - (4 * a * c) ) ) / 2 * a)
1 2 1 0 -1 -2

85

IT 106: Introduction to IT Problem Solving Using Computer Programming

STRINGS

86

43
IT 106: Introduction to IT Problem Solving Using Computer Programming

Strings
The String data type stores a set of characters
Once you have a string variable you can use methods
on it, such as finding the length

The maximum length of a string is the size of an


integer
"" is considered an empty String (length 0)

87

IT 106: Introduction to IT Problem Solving Using Computer Programming

String Concatenation (+)


You can add or concatenate one String
onto the end of another

You can also concatenate a number to a


String

88

44
IT 106: Introduction to IT Problem Solving Using Computer Programming

String Escape Sequences


How would you store a " within a String?
– Preface the " with a \ inside the double quoted String
How would you print a backslash?
– Preface the \ with another \
Special characters inside String
– To create a new line, use \n

89

Numerical Data Types


Name Range Storage Size

byte –27 (-128) to 27–1 (127) 8-bit signed

short –215 (-32768) to 215–1 (32767) 16-bit signed

int –231 (-2147483648) to 231–1 (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

90

90

45
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

91

91

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)

92

92

46
Remainder Operator
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. 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

93

93

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.

94

94

47
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)

95

95

Example: Converting Temperatures

Write a program that converts a Fahrenheit degree


to Celsius using the formula:

celsius = ( 95 )( fahrenheit − 32)

96

96

48
Shortcut Assignment
Operators
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8

97

97

Increment and
Decrement Operators
Operator Name Description
++var preincrement The expression (++var) increments var by 1 and
evaluates
to the new value in var after the increment.
var++ postincrement The expression (var++) evaluates to the original value
in var and increments var by 1.
--var predecrement The expression (--var) decrements var by 1 and
evaluates
to the new value in var after the decrement.
var-- postdecrement The expression (var--) evaluates to the original value
in var and decrements var by 1.

98

98

49
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;

99

99

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.

100

100

50
Assignment Expressions and
Assignment Statements
Prior to Java 2, all the expressions can be used as
statements. Since Java 2, only the following types of
expressions can be statements:
variable op= expression; // Where op is +, -, *, /, or %
++variable;
variable++;
--variable;
variable--;

101

101

Numeric Type Conversion


Consider the following statements:

byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;

102

102

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

103

103

Type Casting
Implicit casting
double d = 3; (type widening)

Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is
truncated)
What is wrong? int x = 5 / 2.0;

range increases

byte, short, int, long, float, double

104

104

52
Character Data Type
Four hexadecimal digits.
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)

NOTE: The increment and decrement operators can also be used


on char variables to get the next or preceding Unicode character.
For example, the following statements display character b
char ch = 'a';
System.out.println(++ch);
105

105

Unicode Format
Java characters use Unicode, a 16-bit encoding scheme
established by the Unicode Consortium to support the
interchange, processing, and display of written texts in the
world’s diverse languages. Unicode takes two bytes,
preceded by \u, expressed in four hexadecimal numbers
that run from '\u0000' to '\uFFFF'. So, Unicode can
represent 65535 + 1 characters.
Unicode \u03b1 \u03b2 \u03b3 for three Greek
letters

106

106

53
Escape Sequences for Special
Characters
Description Escape Sequence Unicode
Backspace \b \u0008
Tab \t \u0009
Linefeed \n \u000A
Carriage return \r \u000D
Backslash \\ \u005C
Single Quote \' \u0027
Double Quote \" \u0022

107

107

Appendix B: ASCII Character Set


ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

108

108

54
ASCII Character Set, cont.
ASCII Character Set is a subset of the Unicode from \u0000 to \u007f

109

109

Casting between char and


Numeric Types
int i = 'a'; // Same as int i = (int)'a';

char c = 97; // Same as char c = (char)97;

110

110

55
The String Type
The char type only represents one character. To represent a string
of characters, use the data type called String. For example,

String message = "Welcome to Java";

String is actually a predefined class in the Java library just like the
System class and JOptionPane class. The String type is not a
primitive type. It is known as a reference type. Any Java class can
be used as a reference type for a variable. Reference data types
will be thoroughly discussed in Chapter 6, “Classes and Objects.”
For the time being, you just need to know how to declare a String
variable, how to assign a string to the variable, and how to
concatenate strings.

111

111

String Concatenation
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";

// String Chapter is concatenated with number 2


String s = "Chapter" + 2; // s becomes Chapter2

// String Supplement is concatenated with character B


String s1 = "Supplement" + 'B'; // s becomes
SupplementB

112

112

56
Obtaining Input
1. Using JOptionPane input dialogs
2. Using Scanner class

113

113

Getting Input from Input Dialog


Boxes
String string = JOptionPane.showInputDialog(
null, “Prompting Message”, “Dialog Title”,
JOptionPane.QUESTION_MESSAGE));

114

114

57
Two Ways to Invoke the Method
There are several ways to use the showInputDialog method. For
the time being, you only need to know two ways to invoke it.
One is to use a statement as shown in the example:

String string = JOptionPane.showInputDialog(null, x,


y, JOptionPane.QUESTION_MESSAGE));

where x is a string for the prompting message, and y is a string for


the title of the input dialog box.

The other is to use a statement like this:


JOptionPane.showInputDialog(x);
where x is a string for the prompting message.

115

115

Converting Strings to Integers


The input returned from the input dialog box is a string. If
you enter a numeric value such as 123, it returns “123”.
To obtain the input as a number, you have to convert a
string into a number.

To convert a string into an int value, you can use the


static parseInt method in the Integer class as follows:

int intValue = Integer.parseInt(intString);

where intString is a numeric string such as “123”.


116

116

58
Converting Strings to Doubles
To convert a string into a double value, you can use the
static parseDouble method in the Double class as follows:

double doubleValue =Double.parseDouble(doubleString);

where doubleString is a numeric string such as “123.45”.

117

117

Getting Input Using Scanner


1. Create a Scanner object
Scanner scanner = new Scanner(System.in);

2. Use the methods next(), nextByte(), nextShort(),


nextInt(), nextLong(), nextFloat(), nextDouble(), or
nextBoolean() to obtain to a string, byte, short, int,
long, float, double, or boolean value. For example,
System.out.print("Enter a double value: ");
Scanner scanner = new Scanner(System.in);
double d = scanner.nextDouble();

118

118

59
The boolean Type and Operators
Often in a program you need to compare two
values, such as whether i is greater than j. Java
provides six comparison operators (also known
as relational operators) that can be used to
compare two values. The result of the
comparison is a Boolean value: true or false.

boolean b = (1 > 2);

119

119

Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to

120

120

60
Boolean Operators
Operator Name
! not
&& and
|| or
^ exclusive or

121

121

Examples
System.out.println("Is " + num + " divisible by 2 and 3? " +
((num % 2 == 0) && (num % 3 == 0)));

System.out.println("Is " + num + " divisible by 2 or 3? " +


((num % 2 == 0) || (num % 3 == 0)));

System.out.println("Is " + num +


" divisible by 2 or 3, but not both? " +
((num % 2 == 0) ^ (num % 3 == 0)));

122

122

61
Example: Determining Leap
Year?
This program first prompts the user to enter a year as
an int value and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by
100, or it is divisible by 400.
(year % 4 == 0 && year % 100 != 0) || (year % 400
== 0)

123

123

The & and | Operators


&&: conditional AND operator
&: unconditional AND operator
||: conditional OR operator
|: unconditional OR operator

exp1 && exp2


(1 < x) && (x < 100)

(1 < x) & (x < 100)


124

124

62
The & and | Operators
If x is 1, what is x after this
expression?
(x > 1) & (x++ < 10)

If x is 1, what is x after this


expression?
(1 > x) && ( 1 > x++)

How about (1 == x) | (10 > x++)?


(1 == x) || (10 > x++)?

125

125

Content

Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods

126

126

63
Control Statements
if Statements
switch Statements
Conditional Operators

127

127

TIP
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)

128

128

64
CAUTION
if (even == true) Equivalent if (even)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)

129

129

Example: Guessing Birth Date


The program can guess your birth date.

130

130

65
Conditional Operator, cont.
I = (booleanExp) ? exp1 :
exp2

131

131

Operator Precedence
var++, var--
+, - (Unary plus and minus), ++var,--var
(type) Casting
! (Not)
*, /, % (Multiplication, division, and remainder)
+, - (Binary addition and subtraction)
<, <=, >, >= (Comparison)
==, !=; (Equality)
& (Unconditional AND)
^ (Exclusive OR)
| (Unconditional OR)
&& (Conditional AND) Short-circuit AND
|| (Conditional OR) Short-circuit OR
=, +=, -=, *=, /=, %= (Assignment operator)

132

132

66
Content

Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods

133

133

while Loop Flow Chart


int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s); count++;
} }
count = 0;

Loop
false false
Continuation (count < 100)?
Condition?

true true
Statement(s) System.out.println("Welcome to Java!");
(loop body) count++;

(A) (B)

134

134

67
Example: An Advanced Math Learning Tool
The Math subtraction learning tool program
generates just one question for each run. You can
use a loop to generate questions repeatedly. This
example gives a program that generates ten
questions and reports the number of the correct
answers after a student answers all ten questions.

135

135

Ending a Loop with a Sentinel


Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to signify the
end of the loop. Such a value is known as a sentinel value.

Write a program that reads and calculates the sum of an


unspecified number of integers. The input 0 signifies the
end of the input.

136

136

68
Caution
Don’t use floating-point values for equality checking in
a loop control. Since floating-point values are
approximations, using them could result in imprecise
counter values and inaccurate results. This example uses
int value for data. If a floating-point type value is used
for data, (data != 0) may be true even though data is 0.

// data should be zero


double data = Math.pow(Math.sqrt(2), 2) - 2;

if (data == 0)
System.out.println("data is zero");
else
System.out.println("data is not zero");
137

137

do-while Loop

Statement(s)
(loop body)

true Loop
Continuation
do { Condition?
// Loop body; false
Statement(s);
} while (loop-continuation-condition);

138

138

69
for Loops
for (initial-action; loop- int i;
continuation-condition; for (i = 0; i < 100; i++) {
action-after-each-iteration) { System.out.println(
// loop body; "Welcome to Java!");
Statement(s);
} }

Initial-Action i=0

Loop
false false
Continuation (i < 100)?
Condition?
true true
Statement(s) System.out.println(
(loop body) "Welcome to Java");

Action-After-Each-Iteration i++

(A) (B)
139

139

Note
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-each-
iteration in a for loop can be a list of zero or more comma-
separated statements. Therefore, the following two for
loops are correct. They are rarely used in practice,
however.
for (int i = 1; i < 100; System.out.println(i++));

for (int i = 0, j = 0; (i + j < 10); i++, j++) {


// Do something
}
140

140

70
Note
If the loop-continuation-condition in a for loop is omitted,
it is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct. Nevertheless, it is
better to use the equivalent loop in (b) to avoid confusion:

for ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }
(a) (b)

141

141

Example: Using for Loops


Problem: Write a program that sums a series that starts
with 0.01 and ends with 1.0. The numbers in the series will
increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on.

142

142

71
Nested Loops
Problem: Write a program that uses nested for loops to
print a multiplication table.

143

143

Example:
Finding the Greatest Common Divisor
Problem: Write a program that prompts the user to enter two positive
integers and finds their greatest common divisor.
Solution: Suppose you enter two integers 4 and 2, their greatest
common divisor is 2. Suppose you enter two integers 16 and 24, their
greatest common divisor is 8. So, how do you find the greatest
common divisor? Let the two input integers be n1 and n2. You know
number 1 is a common divisor, but it may not be the greatest commons
divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a
common divisor for n1 and n2, until k is greater than n1 or n2.

144

144

72
Example: Finding the Sales
Amount
Problem: You have just started a sales job in a department store. Your
pay consists of a base salary and a commission. The base salary is
$5,000. The scheme shown below is used to determine the
commission rate.
Sales Amount Commission Rate
$0.01–$5,000 8 percent
$5,000.01–$10,000 10 percent
$10,000.01 and above 12 percent
Your goal is to earn $30,000 in a year. Write a program that will find
out the minimum amount of sales you have to generate in order to
make $30,000.

145

145

Example:
Displaying a Pyramid of Numbers
Problem: Write a program that prompts the user to enter an integer
from 1 to 15 and displays a pyramid. For example, if the input integer
is 12, the output is shown below.

146

146

73
Content

Introduction
Data Types and Operations
Control Statements
Loop Statements
Methods

147

147

Example: Displaying Prime


Numbers
Problem: Write a program that displays the first 50 prime numbers in
five lines, each of which contains 10 numbers. An integer greater than
1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5,
and 7 are prime numbers, but 4, 6, 8, and 9 are not.
Solution: The problem can be broken into the following tasks:
•For number = 2, 3, 4, 5, 6, ..., test whether the number is prime.
•Determine whether a given number is prime.
•Count the prime numbers.
•Print each prime number, and print 10 numbers per line.

148

148

74
Introducing Methods
A method is a collection of statements that are
grouped together to perform an operation.

Define a method Invoke a method

modifier return value type method name formal parameters

method
public static int max(int num1, int num2) { int z = max(x, y);
header

int result;
method actual parameters
body parameter list (arguments)
if (num1 > num2)
result = num1;
else
result = num2;
return value
return result;
}

149

149

Introducing Methods, cont.


• Method signature is the combination of the
method name and the parameter list.
• The variables defined in the method header are
known as formal parameters.
• When a method is invoked, you pass a value to
the parameter. This value is referred to as actual
parameter or argument.

150

150

75
Introducing Methods, cont.
• A method may return a value. The
returnValueType is the data type of the value the
method returns. If the method does not return a
value, the returnValueType is the keyword void.
For example, the returnValueType in the main
method is void.

151

151

Calling Methods
Testing the max method
This program demonstrates calling a method max
to return the largest of the int values

152

152

76
Calling Methods, cont.

pass the value of i


pass the value of j

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

153

153

Reuse Methods from Other


Classes
NOTE: One of the benefits of methods is for reuse. The
max method can be invoked from any class besides
TestMax. If you create a new class Test, you can invoke
the max method using ClassName.methodName (e.g.,
TestMax.max).

154

154

77
Call Stacks

Space required for the


max method
result: 5
num2: 2
num1: 5
Space required for the Space required for the Space required for the
main method main method main method
k: k: k: 5 Stack is empty
j: 2 j: 2 j: 2
i: 5 i: 5 i: 5

The main method The max method is The max method is The main method
is invoked. invoked. finished and the return is finished.
value is sent to k.

155

155

Trace Call Stack

Return result and assign it to k

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {


i nt i = 5;
i nt j = 2;
i nt k = max( i , j ) ; Space required for the
max method
result: 5
Syst em. out . pr i nt l n( num2: 2
num1: 5
" The maxi mum bet ween " + i + Space required for the
" and " + j + " i s " + k) ; main method
} k:5
j: 2
i: 5

publ i c st at i c i nt max( i nt num1, i nt num2) {


i nt r esul t ; The max method is
invoked.

i f ( num1 > num2)


r esul t = num1;
el se
r esul t = num2;
r et ur n r esul t ;
}

156

156

78
Overloading Methods
Listing 5.3 Overloading the max Method

public static double max(double num1, double


num2) {
if (num1 > num2)
return num1;
else
return num2;
}

157

157

Ambiguous Invocation
Sometimes there may be two or more
possible matches for an invocation of a
method, but the compiler cannot
determine the most specific match. This
is referred to as ambiguous invocation.
Ambiguous invocation is a compilation
error.

158

158

79
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}

public static double max(int num1, double num2) {


if (num1 > num2)
return num1;
else
return num2;
}

public static double max(double num1, int num2) {


if (num1 > num2)
return num1;
else
return num2;
}
}
159

159

Method Abstraction
You can think of the method body as a black
box that contains the detailed implementation
for the method.
Optional arguments Optional return
for Input value

Method Signature
Black Box
Method body

160

160

80
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.

161

161

The Math Class


Class constants:
– PI
–E
Class methods:
– Trigonometric Methods
– Exponent Methods
– Rounding Methods
– min, max, abs, and random Methods

162

162

81
Trigonometric Methods
sin(double a) Examples:

cos(double a)
Math.sin(0) returns 0.0
tan(double a) Math.sin(Math.PI / 6)
returns 0.5
acos(double a) Math.sin(Math.PI / 2)
returns 1.0
asin(double a)
Math.cos(0) returns 1.0
atan(double a) Math.cos(Math.PI / 6)
returns 0.866
Math.cos(Math.PI / 2)
Radians returns 0
toRadians(90)
163

163

Exponent Methods
exp(double a) Examples:
Returns e raised to the power of a.
Math.exp(1) returns 2.71
log(double a)
Math.log(2.71) returns 1.0
Returns the natural logarithm of a.
Math.pow(2, 3) returns 8.0
log10(double a) Math.pow(3, 2) returns 9.0
Returns the 10-based logarithm of Math.pow(3.5, 2.5) returns
a. 22.91765
Math.sqrt(4) returns 2.0
pow(double a, double b)
Math.sqrt(10.5) returns 3.24
Returns a raised to the power of b.
sqrt(double a)
Returns the square root of a.

164

164

82
Rounding Methods
double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a double
value.
double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a
double value.
double rint(double x)
x is rounded to its nearest integer. If x is equally close to two integers,
the even one is returned as a double.
int round(float x)
Return (int)Math.floor(x+0.5).
long round(double x)
Return (long)Math.floor(x+0.5).

165

165

Rounding Methods Examples


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.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(-2.5) returns -2.0
Math.round(2.6f) returns 3
Math.round(2.0) returns 2
Math.round(-2.0f) returns -2
Math.round(-2.6) returns -3
166

166

83
min, max, and abs
max(a, b)and min(a, Examples:
b)
Returns the maximum or Math.max(2, 3) returns 3
minimum of two parameters.
Math.max(2.5, 3) returns
abs(a) 3.0
Returns the absolute value of the Math.min(2.5, 3.6)
parameter. returns 2.5
random() Math.abs(-2) returns 2
Returns a random double value Math.abs(-2.1) returns
in the range [0.0, 1.0). 2.1

167

167

The random Method


Generates a random double value greater than or equal to 0.0
and less than 1.0 (0 <= Math.random() < 1.0).

Examples:

Returns a random integer


(int)(Math.random() * 10)
between 0 and 9.

50 + (int)(Math.random() * 99) Returns a random integer


between 50 and 149.

In general,

a + Math.random() * b Returns a random number between


a and a + b, excluding a + b.

168

168

84

You might also like