0% found this document useful (0 votes)
2 views116 pages

CT176-OOP With Java Ch1 Java E

This document is a chapter on the Java programming language, covering its basic components, structure of simple programs, and execution processes. It explains the development cycle of Java programs, including writing, compiling, and executing code, as well as key features like platform independence. Additionally, it introduces Java syntax, data types, control structures, and common classes in the Java library.

Uploaded by

hquyn183
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)
2 views116 pages

CT176-OOP With Java Ch1 Java E

This document is a chapter on the Java programming language, covering its basic components, structure of simple programs, and execution processes. It explains the development cycle of Java programs, including writing, compiling, and executing code, as well as key features like platform independence. Additionally, it introduces Java syntax, data types, control structures, and common classes in the Java library.

Uploaded by

hquyn183
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

Chapter 1

Java Programming Language


CT108H – OBJECT ORIENTED PROGRAMMING
Dr. Triệu Thanh Ngoan
ttngoan@[Link]
Faculty of Networks and Communications
Objectives

This chapter will introduce some basic components of


Java programming language,
how to combine and execute programs

CT108H - Object Oriented Programming 2


Contents
• Structure of a simple Java program
• Combine and execute a Java program
• Java syntax
• Data types
• Control structures
• Common classes in Java library

CT108H - Object Oriented Programming 3


v Structure of a simple Java program

Structure of A Simple Java Program

CT108H - Object Oriented Programming 4


v Structure of a simple Java program

Example 1 – Hello World


• A Java program to display greeting on screen:
/* [Link] */
public class HelloWorld {
public static void main(String args[]) {
[Link]("Hello");
[Link]("How are you");
}
}

• Execution results:

CT108H - Object Oriented Programming 5


v Structure of a simple Java program

Structure of A Simple Java Program


class name
comments (must be the same as the file
name, excluding the extension)
/* [Link] */ main program (the main
// comment function is the entry
public class HelloWorld { point of the program)
public static void main(String args[]) {
[Link]("Hello!");
[Link]("How are you?");
}
}
commands in the program
[Link]() command is used to display a string on the screen
• Notice:
§ class name and file name must be the same
§ main() has the same function as main() in C

CT108H - Object Oriented Programming 6


v Structure of a simple Java program

Example 2 – Multiple Functions


main program

public class Arithmetic {


public static void main(String[] args) {
[Link]("The sum of 2 and 3 = " + 5);
[Link]("7 + 8 = " + avg(7, 8));
}
gọi hàm
public static float avg(float a, float b) {
return (a + b)/2;
}
} avg() function to calculate the
average of two numbers

• Execution results:

CT108H - Object Oriented Programming 7


• s statement
package

CT108H - Object Oriented Programming 8


v Combine and execute a Java program

Combine and Execute a Java program

CT108H - Object Oriented Programming 9


v Combine and execute a Java program

Key Features
• Platform Independence
• Java is a programming language that is both interpreted
and compiled
§ A Java program, after being developed, will be compiled into
bytecode using the Java compiler.
§ When a bytecode program needs to be executed, the Java
virtual machine will interpret each bytecode instruction into
machine code.

• Java programs are multi-platform: they can be executed


on many different computer architectures and operating
systems thanks to the interpretation mechanism.
CT108H - Object Oriented Programming 10
v Combine and execute a Java program

Process of Developing a Java Program


• Programmers write a Java program:
§ Including a set of statements
§ Using text editor or IDE
§ Save files using .java extension
§ Those files are called source code

• Java compiler combine source code:


§ Into bytecode
§ Save in .class extension
§ Syntax errors, if any, are generated

CT108H - Object Oriented Programming 11


v Combine and execute a Java program

Process of Developing a Java Program


• Java Virtual Machine will execute the bytecode:
§ Loader will load bytecode into JVM
§ JVM will intepret bytecode to machine code on the
corresponding platform for execution

• Java Virtual Machine (JVM):


§ Act as a virtual computer: executes bytecode (vs. CPU is a
“real” computer, executing machine code interpreted by
JVM)
§ Bytecode is the same for JVM on all platforms ⇒ JVMs on
each platform will interpret bytecode into machine code on
the corresponding platform

CT108H - Object Oriented Programming 12


v Combine and execute a Java program

Process of Developing a Java Program


Combine

read compile
source code .java Compiler Bytecode
(.class)

load

execute
Java Virtual Machine

interprete

Hardware &
Operating System

CT108H - Object Oriented Programming 13


v Combine and execute a Java program

Process of Developing a Java Program


• Java Virtual Machine – Portability:
Bytecode
(.class)

JVM JVM
for Windows for Unix

JVM JVM
for Linux for Mac

Why Java bytecode?


CT108H - Object Oriented Programming 14
v Combine and execute a Java program

Combining and Executing Environment


• Command line:
§ Unix + Mac OS: Terminal

§ Windows: Command Prompt

CT108H - Object Oriented Programming 15


v Combine and execute a Java program

Combining and Executing Environment


• IDE: Netbean, Eclipse,...

CT108H - Object Oriented Programming 16


v Combine and execute a Java program

Combining and Executing Environment


• IDE: Netbean, Eclipse,...

CT108H - Object Oriented Programming 17


v Combine and execute a Java program

Environment Installation
• Java Development Kit:
1. JDK download link : [Link]
2. Select the appropriate installer(Windows, Linux, Mac OS,…)
3. Run the installer as instructed
4. Test the installation: Execute the following commands from
the command line
o Java Compiler: javac –version
o Java Virtual Machine: java –version

• JDK installer including JVM


CT108H - Object Oriented Programming 18
v Combine and execute a Java program

Environment Installation

CT108H - Object Oriented Programming 19


v Combine and execute a Java program

Environment Installation
• Environment variables:
1. Choose Computer / Properties/ Advanced System
Settings / Advanced / Environment Variables…
2. Click New:
o Variable name: JAVA_HOME
o Variable value: choose JDK path
3. Choose path in User variable for USER
4. Click Edit and add Variable Values:
;%JAVA_HOME%/bin;.;
5. Click OK
6. Test (as before)

CT108H - Object Oriented Programming 20


•s

CT108H - Object Oriented Programming 21


v Combine and execute a Java program

Command Line Arguments


• Executing a Java program, we can pass arguments from
command line to the program
§ Syntax: java <program name> [list of arguments]
§ Arguments are separated by spaces
§ If the argument value has spaces, then enclose the argument
value with a double quotation marks "
• The values of the command line arguments will be
passed to the args argument of the main
function(String args[])
• Starting index from 0: args[0], args[1],…

CT108H - Object Oriented Programming 22


v Combine and execute a Java program

Command Line Arguments


/* [Link] */
public class HelloWorldArg {
public static void main(String args[]) {
[Link]("Hello " + args[0]);
[Link]("How are you?");
}
}

arguments

CT108H - Object Oriented Programming 23


v Combine and execute a Java program

Assignment 1
A1:
• Install JDK
• Set environment variables (in Windows)
• Combine and execute HelloWorld (in command line)
A2:
• Install Eclipse
• Combine and execute HelloWorld (with Eclipse)

⇒Submission: a pdf file including all figures illustrating results


⇒Time: a week from now on

CT108H - Object Oriented Programming 24


v Basic Components of Java

Basic Components of Java

CT108H - Object Oriented Programming 25


v Basic Components of Java

Statement & Comment

• A statement in Java ends with a semicolon ;


• Commands and identifiers are case sensitive
• Example:
[Link]("Hello!");
[Link]("How are you?"); -> error
• Two types of comments in Java (similar to C):
§ Single line: // comment
§ Multiple lines: /* comment */
• A block of statements is enclosed in curly braces { }

CT108H - Object Oriented Programming 26


v Basic Components of Java

Variable & Identifier


• A variable is a named memory area used to store data for
processing in a program
§ Variable declaration:
<data type> <variable name>;
<data type> <variable name 1> [<, variable name
2>...];
• Variables are named according to the identifier naming
rules:
§ Can contain characters (A-Z, a-z), numbers (0-9), _ and $
§ The first character cannot be a number
§ Cannot match Java keywords
§ Case sensitive: Distinguish between uppercase and lowercase
§ Examples: itemOrdered, noOfStudent
CT108H - Object Oriented Programming 27
v Basic Components of Java

Keywords
• Keywords are Java reserved words:
abstract double instanceof static
assert else int super
boolean enum interface switch
break extends long synchronized
byte false native this
case for new throw
catch final null throws
char finally package transient
class float private true
const goto protected try
continue if public void
default implements return volatile
do import short while

CT108H - Object Oriented Programming 28


v Basic Components of Java

Variable & Identifier

• In addition to the naming rules, it is necessary to


refer to the following naming conventions
§ Variable names must be meaningful
§ Variable names in Java often use Pascal case: the
first word in the variable name is lower case, the
following words are capitalized (title case).
§ Variable names usually include nouns or noun
phrases
§ Coding convention in Java:
[Link]
[Link]

CT108H - Object Oriented Programming 29


v Basic Components of Java

Scope of Variable
• Variable scope: locations in the program where the
variable can be accessed

§ A variable declared in a block of code can only be accessed


within that block of code

§ The scope of a variable is from the variable declaration


statement to the end of the block of code containing the
variable declaration

§ A variable will be destroyed (the memory area reserved for


the variable is reclaimed) when the program executes out of
the scope of the variable
CT108H - Object Oriented Programming 30
v Basic Components of Java

Scope of Variable
• Can be declared anywhere in the program
• Global variable: the entire program
• Local variable: in which it is declared
• Example:
public class Number{
int so = 5;
void GanSo ( int x) {
so = x;
}
int NuaSo ( int x) {
int c = 2;
so = x/c ;
return so;
} 31

}
CT108H - Object Oriented Programming 31
v Basic Components of Java

Scope of Variable
• Variables in nested blocks cannot have the same name

• Example:
public class NestVar {
public static void main (String args[]) {
int count;
for (count = 0; count < 10; count = count+1) {
[Link] ("This is count: " + count);
int count; // illegal!!!
for (count = 0; count < 2; count++)
[Link] ( "This program is in error!");
}
}
}
CT108H - Object Oriented Programming 32
v Basic Components of Java

Data Types
• Java has 8 primitive data types:
§ Integer number:
o byte
o short
o int
o long
§ Floating-point number:
o float
o double
§ Logical value: boolean
§ Charater: char
§ Non-primitive data type: String (S in uppercase)

CT108H - Object Oriented Programming 33


v Basic Components of Java Primitive data types

Numeric Datatype

Type Size Value domain

byte 1 byte -128 to +127


short 2 bytes -32,768 to +32,767
int 4 bytes -2,147,483,648 to +2,147,483,647
long 8 bytes -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
float 4 bytes ±3.410-38 to ±3.41038, with 7 digits of accuracy
double 8 bytes ±1.710-308 to ±1.710308, with 15 digits of accuracy

• Size: The amount of memory allocated to a variable of


the corresponding type.

CT108H - Object Oriented Programming 34


v Basic Components of Java Primitive data types

Numeric Datatype
• Numeric literal:
§ Integer number: 0, 5, 10, 12, -25, -30,...
§ Floating-point number: real literals have the double type
by default
§ Example: int a; // Declare a type int
float b; // Declare b type float
a = 123;
b = 123.5; //Error!
Double values are not compatible with float variables
because of different precisions (7 vs. 15 decimal places).
⇒ b = 123.5F;
§ Can use E-notation:
number = 1.234E2F;

CT108H - Object Oriented Programming 35


v Basic Components of Java Primitive data types

Numeric Datatype
// This program has variables of several of the integer types.
public class IntegerVariables {
public static void main(String[] args) {
int checking; // Declare an int variable named checking.
byte miles; // Declare a byte variable named miles.
short minutes; // Declare a short variable named minutes.
long days; // Declare a long variable named days.

checking = -20;
miles = 105;
minutes = 120;
days = 185000;
[Link]("We've made a journey of " + miles +
" miles.");
[Link]("It took us " + minutes + " minutes.");
[Link]("Our account balance is $" + checking);
}
}

CT108H - Object Oriented Programming 36


v Basic Components of Java Primitive data types

Numeric Datatype
// This program demonstrates the double data type.

public class Sale


{
public static void main(String[] args)
{
double price, tax, total;
price = 29.75;
tax = 1.76;
total = 31.51;
[Link]("The price is " + price);
[Link]("The tax is " + tax);
[Link]("The total is " + total);
[Link](2.00-1.10);
[Link]("%.2f",2.00-1.10);
}
}

CT108H - Object Oriented Programming 37


v Basic Components of Java Primitive data types

Boolean Datatype
• boolean type can have one of two values:
§ true
§ false

• A boolean variable can only be assigned one of these


two values

• Usually, boolean variables/values are used in


conditional statements and loops

CT108H - Object Oriented Programming 38


v Basic Components of Java Primitive data types

Boolean Datatype

// A program for demonstrating boolean variables

public class TrueFalse


{
public static void main(String[] args)
{
boolean bool;

bool = true;
[Link](bool);
bool = false;
[Link](bool);
}
}

CT108H - Object Oriented Programming 39


v Basic Components of Java Primitive data types

Character Datatype
• The char dataype allows operations on a single character
• A character constant value is enclosed in a pair of single
quotes''
§ Ví dụ: 'a', '\n', '\t', '2', (‘’ incorrect)
• Each character has a character code:
§ Example: 'a' has the code 95, 'b' has the code 96,...
§ When operating on a character, we can use the character
enclosed in a pair of single quote or the character code.
§ The character code has a value from 0 – 65.335 (216 – 1)
• The size of each character is 2 bytes (Unicode)

CT108H - Object Oriented Programming 40


v Basic Components of Java Primitive data types

Character Datatype

// This program demonstrates the char data type.

public class Letters


{
public static void main(String[] args)
{
char ch;

ch = 'A';
[Link](ch);
ch = 66; //ch = 'B';
[Link](ch);
}
}

CT108H - Object Oriented Programming 41


v Basic Components of Java

String Datatype
• A string is considered as a sequence of characters
• A string of characters is enclosed in double quotes "”
§ Example: "Hello World", "Chào bạn"
• Each character in the string has an index with the first
character of the string being indexed from 0
• In Java: String
• String operators: + (plus, concatenation)
[Link]("The sum = " + 12 + 26);
• Notice: String is a class ⇒ supporting multiple
methods to manipulate strings

CT108H - Object Oriented Programming 42


v Basic Components of Java

String Datatype
// This program demonstrates a few of the String methods.

public class StringMethods {


public static void main(String[] args) {
String message = new String("Java is Great Fun!");
String upper = [Link]();
String lower = [Link]();
char letter = [Link](2);
int stringSize = [Link]();

[Link](message);
[Link](upper);
[Link](lower);
[Link](letter);
[Link](stringSize);
}
}

CT108H - Object Oriented Programming 43


v Basic Components of Java

Variable Assignment
• To assign a value to a variable, we use the assignment
operator =
<variable> = <variable| constant | expression>
// This program shows variable assignment

public class Initialize {


public static void main(String[] args) {
int month, days;

month = 2;
days = 28;
[Link]("Month " + month + " has " +
days + " days.");
}
}

CT108H - Object Oriented Programming 44


v Basic Components of Java

Variable Initialization
• A variable can be initialized immediately upon declaration
<kiểu DL> <tên biến> [= giá trị];
// This program shows variable initialization

public class Initialize {


public static void main(String[] args) {
int month = 2, days = 28;

[Link]("Month " + month + " has " +


days + " days.");
}
}

• Notice: Variables must be initialized or assigned a value


before they can be accessed.
CT108H - Object Oriented Programming 45
v Basic Components of Java

Variable Initialization
• Which are the correct declarations?

[Link] a = '\u0061';
[Link] 'a' = 'a';
[Link] \u0061 = 'a';
[Link]\u0061r a = 'a';
[Link]'a'r a = 'a';

CT108H - Object Oriented Programming 46


v Basic Components of Java

Fun Activity (at home)


• Put this in [Link] and see the
results
\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020\u0020
\u0063\u006c\u0061\u0073\u0073\u0020\u0055\u0067\u006c\u0079
\u007b\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020
\u0020\u0020\u0020\u0020\u0073\u0074\u0061\u0074\u0069\u0063
\u0076\u006f\u0069\u0064\u0020\u006d\u0061\u0069\u006e\u0028
\u0053\u0074\u0072\u0069\u006e\u0067\u005b\u005d\u0020\u0020
\u0020\u0020\u0020\u0020\u0061\u0072\u0067\u0073\u0029\u007b
\u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074
\u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0020
\u0022\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u0022\u002b
\u0022\u006f\u0072\u006c\u0064\u0022\u0029\u003b\u007d\u007d

CT108H - Object Oriented Programming 47


v Basic Components of Java

Arithmetic Operators
Operator Meaning Example
+ Add total = cost + tax;
Minus cost = total – tax;
-
Unary Minus a = -b;
* Multiply tax = cost * rate;
/ Divide salePrice = original / 2;
% Modulus remainder = value % 5;
++ Increment a++; ++a;
-- Decrement a--; --a;

• The / operator will be an integer division operator if both


operands are integer types, otherwise it will be a real division.
• Operator precedence is similar to C language
CT108H - Object Oriented Programming 48
v Basic Components of Java

Other Operators
• Comparisons:
== != < <= > >=
• Boolean operators: int a = 6, b=3;
int [] c = {1,2,3,4}; int d=5;
&& || ! if( a>0 || c[0] <0) d = 1;
if(a < 0 || c[1] >0) d = 2;
if( a>0 || c[2] >0 && b < 0) d = 3;
• Bitwise operators: if(a < 0 && c[3] >0) d = 4;
& | ^ [Link](d);

• Compound operators: Combines mathematical


operators and assignment into a single operator
+= -= *= /= %=
&= |= ^=

CT108H - Object Oriented Programming 49


v Basic Components of Java

Expression
• An expression is a combination of operators with
variables, constants, or other expressions
• Example:
-5
8 – 7
Arithmetic expression
2 + 3 * 5
(b * b) + (4 * a * c)

(month > 0) && (month <= 12)


Logical expression
(year % 100) == 0

CT108H - Object Oriented Programming 50


v Basic Components of Java

Numeric Promotions
• The type conversion rules of arithmetic expressions :
§ If either operand is a double, the other is promoted
to double, and the result is double.
§ Otherwise, if either operand is a float, the other is
promoted to float, and the result is float.
§ Otherwise, if either operand is a long, the other is
promoted to long, and the result is long.
§ Otherwise (for byte, short, and char), both operands are
promoted to int, and the result is int.
• Example:
§ (3/2 + 4)/2 = (1 + 4)/2 = 2
§ (3/2 + 4.0)/2 = (1 + 4.0)/2 = 5.0/2 = 2.5

CT108H - Object Oriented Programming 51


v Basic Components of Java

Numeric Promotions
Short i = 6, j = 7;
i = i + j; //Error
i += j; //OK

Short l, m = 5;
int n = 6;
l = (Short)n + m; //Error
l = (Short)(n + m);//OK

CT108H - Object Oriented Programming 52


v Các thành phần cơ bản của Java

Question
What will be the results?
public static void main(String[] args) {
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
[Link](MICROS_PER_DAY);
[Link](MILLIS_PER_DAY);
[Link](MICROS_PER_DAY/MILLIS_PER_DAY);
}

final long MICROS_PER_DAY = 24L * 60 * 60 * 1000 * 1000;


CT108H - Object Oriented Programming 53
v Basic Components of Java

Type Casting
• Type casting is the conversion of a value from one type to
another.
§ Implicit casting: Java automatically casts the operands in an
expression when there is a type incompatibility
§ Explicit casting: the programmer explicitly requests the casting

• Syntax: (data type) <expression>


§ "a = " + 3 => "a = " + "3" => "a = 3"
§ 3 / 2 + 4.0 => 1 + 4.0 => 1.0 + 4.0 => 5.0
§ (float) 11 * 0.3 => 11.0*0.3 => 3.3
§ (float)(3 / 2) + 4.0 = 1.0 + 4.0 => 5.0
§ (float)3 / 2 + 4.0 = 1.5 + 4.0 => 5.5

CT108H - Object Oriented Programming 54


v Basic Components of Java

Type Casting
• Java API also provides some functions for type conversion
• Some common type conversion functions:
§ int [Link](String s): returns the integer
value corresponding to a string of numbers.
§ float [Link](String s): returns the float
value corresponding to a string of numbers.
§ double [Link](String s): returns the
double value corresponding to a string of numbers.
§ String [Link](int a): returns a string
corresponding to an integer

Wrapper classes: Boolean, Byte, Char, Double, Float,


Integer, Long, Short
CT108H - Object Oriented Programming 55
v Basic Components of Java

Type Casting
public class TypeCasting {
public static void main(String[] args) {
[Link]( (int)(7.9+ 2.0) );
[Link]( [Link]("3"+5) );
[Link]( [Link]("15")/2 );
[Link]( [Link]((double)15/2+"")+"" );
[Link]( (int)(7.8 + (double)15/2) );
[Link]( (int)(7.8 + (double)(15/2)) );
[Link]( 1 + 2 + "3" );
[Link]( "1" + 2 + 3 );
[Link]('H'+'a');
}
} CT108H - Object Oriented Programming 56
v Basic I/O Operations

Basic I/O Operations

CT108H - Object Oriented Programming 57


v Basic I/O Operations

Display on Screen
• [Link](String s): print + newline
• [Link](String s): print without newline
• [Link](String format, Object… args): display
formatted data, similar to C's printf() function
[Link]("Solution of the equation is %.2f",
-(float)b/a);

§ Format syntax can be found at:


[Link]
[Link]#syntax

CT108H - Object Oriented Programming 58


v Basic I/O Operations

Input from Keyboard


• To enter data from keyboard, use Scanner, combined
with [Link] as follows:
§ Create a Scanner:
Scanner sc= new Scanner([Link]);
§ Scanner class is defined in [Link], thus we must add
the following command at the beginning of a program:
import [Link];
§ Read data from the keyboard: use functions
o String nextLine(): read a string
o int nextInt(): read an int
o long nextLong(): read a long
o float nextFloat(): read a float
o ...
[Link]
CT108H - Object Oriented Programming 59
v Basic I/O Operations

Input from Keyboard


import [Link];

public class PTB1 {


public static void main(String args[]) {
//Create a Scanner to enter data from the keyboard
Scanner sc= new Scanner([Link]);

int a, b;
[Link]("a = ");
a = [Link](); // read an int
[Link]("b = ");
b = [Link]();
[Link]("Nghiem cua PT x = %.2f", -(float)b/a);
}
}

• Notice: assuming that a and b are different from 0 and


the equation always has a solution.
CT108H - Object Oriented Programming 60
v Basic I/O Operations

Input from Keyboard


• Beware of data remaining in the keyboard buffer
import [Link];
public class ScannerFlush {
public static void main(String args[]) {
//Tạo đối tượng thuộc lớp Scanner để nhập dữ liệu từ bàn phím
Scanner keyboard = new Scanner([Link]);

String name;
long ID;
[Link]("Enter your ID: ");
ID = [Link]();
• [Link]();
[Link]("Enter your name: ");
name = [Link]();

[Link]("ID :" + ID + ", name: " + name);


}
}

CT108H - Object Oriented Programming 61


v Control Structures

Control Structures

CT108H - Object Oriented Programming 62


v Control Structures

Control Structures
• Control structure: controls how the instructions in the
program are executed.
• There are 3 control structures:
§ Sequence
§ Selection Statement 1
§ Repetition
Statement 2

...

Statement n

CT108H - Object Oriented Programming 63


v Control Structures

Selection Structure
• Select 1 of 2 tasks (blocks of commands) to perform
based on a given condition.

yes no
block 1 Condition block 2

• Selection structures:
§ if … else
§ switch … case

CT108H - Object Oriented Programming 64


v Control Structures Selection

if … else
• Full if statement:
if (condition) {
//statement T;
}
else {
//statement F;
}

§ If the condition is true, execute statement T, otherwise


execute statement F.
§ Statement T/F can be one or more statements
§ In case there is only one statement, the curly braces are not
needed

CT108H - Object Oriented Programming 65


v Control Structures Selection

if … else
• Example: find max value
if (x > y) {
max = x;
}
else {
max = y;
}

yes no
max = x x>y? max = y

CT108H - Object Oriented Programming 66


v Control Structures Selection

if … else
import [Link];
public class PTB1 {
public static void main(String args[]) {
Scanner keyboard = new Scanner([Link]);

int a, b;
[Link]("a = ");
a = [Link]();
[Link]("b = ");
b = [Link]();
if (a == 0) {
if (b == 0)
[Link]("Multiple solution");
else
[Link]("No solution");
}
else
[Link]("Solution x = %.2f", -(float)b/a);
}
}

CT108H - Object Oriented Programming 67


v Control Structures Selection

if … else
• else if:
if (condition 1) {
//statements 1 ;
}else if (condition 2){
//statements 2;
} else if (condition 3){
//statements 3;
} else {
//statements n;
}
§ There can be multiple else if, but only one else

CT108H - Object Oriented Programming 68


v Control Structures Selection

if … else
• if without else:
if (condition) {
statement T;
}

§ If condition is true, execute statement T

Find absolute value


if (x < 0) { yes
x<0? x = -x
x = -x;
}
no

CT108H - Object Oriented Programming 69


v Control Structures Selection

switch … case

switch (exp) {
case value1: yes
exp=value_1? Statements_ 1 break
statements_1;
break; no (without break)
case value_2: yes
exp=value_2? Statements_ 2 break
statements_2;
no (without break)
break;
...
...
case value_n: (without break)
statements_n; yes
exp=value_n? Statements_n break
break;
no
default: yes
optional default? Statements
statements;
} no

CT108H - Object Oriented Programming 70


v Control Structures Selection

switch … case
• Explanation:
§ exp must be an expression with an integer or character
value (from Java 7 onwards, it can be a string)
§ If any case clause has a value equal to the value of exp,
the statements from that case clause will be executed until
the break statement is encountered or until the end of the
switch statement
§ The break statement is used to exit the switch structure
§ The statements in the default clause (optional) will be
executed if the value of exp is not among the values listed in
the case clauses

CT108H - Object Oriented Programming 71


v Control Structures Selection

switch … case
switch (grade)
{
case 'A':
[Link]("The grade is A.");
break;
case 'B':
[Link]("The grade is B.");
break;
case 'C':
[Link]("The grade is C.");
break;
case 'D':
[Link]("The grade is D.");
break;
case 'F':
[Link]("The grade is F.");
break;
default:
[Link]("The grade is invalid.");
}

CT108H - Object Oriented Programming 72


v Control Structures Selection

switch … case
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
[Link]("31-day month");
break;
case 4:
case 6:
case 9:
case 11:
[Link]("30-day month");
break;
default:
[Link]("28/29-day month");
}

CT108H - Object Oriented Programming 73


v Control Structures Loops

Repetition/Loop
• Used to repeatedly perform a task (block of commands)
a number of times based on given conditions.

• Repetition statements:
§ while no
§ for Condition

§ do … while
yes
Statement 1 ... Statement n

CT108H - Object Oriented Programming 74


v Control Structures Loops

while
while (condition) { 1. Check “conditional
statement 1;
expression”
. . . loop body
statement n; 2. If true, execute the loop
} body; Otherwise, exit the
loop
3. Return to step 1.
no
Condition

yes
Statement 1 ... Statement n

CT108H - Object Oriented Programming 75


v Control Structures Loops

while
• Notice:
§ Condition is checked before executing the loop body
⇒ The loop body may not be executed at all if the condition
is false from the beginning
§ A loop with an infinite number of iterations is called an infinite
loop
§ To avoid an infinite loop, the loop body must contain at least
1 statement that changes the value of the conditional
expression

int x = 20;
while (x > 0)
[Link]("x is greater than 0");

CT108H - Object Oriented Programming 76


v Control Structures Loops

while
• Example: Display the values 2i with 2i <= 2N, N is passed
via command line argument.
public class PowersOfTwo {
public static void main(String[] args) {
args[0]
int N = [Link](args[0]);

int i = 0; $java PowersOfTwo 6


int v = 1;
while (i <= N) {
[Link](i + "\t" + v);
i = i + 1;
v = 2 * v;
}
}
}

CT108H - Object Oriented Programming 77


v Control Structures Loops

do … while
do { 1. Execute the loop body
statement 1;
. . . loop body 2. Evaluate the “conditional
statement n; expression”:
} while (condition); a) If true, return to step 1
b) Otherwise, exit the loop

Statement 1
• Remarks:
...
§ The loop body is always
executed at least once
Statement n
§ Note the case of infinite loops

Condition
yes
no

CT108H - Object Oriented Programming 78


v Control Structures Loops

do … while
import [Link]; // Needed for the Scanner class
public class DoWhileSqrt {
public static void main(String[] args) {
int n; // number that will be calculated the square root
char repeat; // To hold 'y' or 'n'

Scanner keyboard = new Scanner([Link]);


do {
[Link]("Enter a number: ");
n = [Link]();
[Link]();

[Link]("SQRT of " + n + " is " + [Link](n));

[Link]("Continue (y/n)? ");


repeat = [Link]().charAt(0); // Read a line.
} while (repeat == 'Y' || repeat == 'y');
}
}

CT108H - Object Oriented Programming 79


v Control Structures Loops

for
for (init; condition; increment) {
statement 1;
init
... loop body
statement n;
} Statement 1
...
1. Execute initialization expression
Statement n
2. Evaluate “conditional expression”:
a) If true, execute step 3
increment
b) Otherwise, exit the loop
3. Execute loop body
condition?
4. Execute increment expression yes
no

CT108H - Object Oriented Programming 80


v Control Structures Loops

for
• Remarks:
§ The initialization expression is executed only once
before entering the loop.
o Variables can be declared in the initialization expression
§ The iteration/increment expression is executed after
each time the loop body is executed
§ All three expressions in the loop statement are
optional
§ The for loop statement converts to the while loop
statement and vice versa
§ The initialization and increment expressions can
contain multiple statements, separated by a comma
CT108H - Object Oriented Programming 81
v Control Structures Loops

for
import [Link]; // Needed for the Scanner class

public class ForSum_1_N {


public static void main(String[] args) {
int n;
Scanner keyboard = new Scanner([Link]);

// Get the maximum value to display.


[Link]("n = ");
n = [Link]();

// Calculate the sum


int sum = 0;
for (int i = 1; i <= n; i++)
sum += i;

[Link]("1 + 2 + ... + " + n + " = " + sum);


}
}

CT108H - Object Oriented Programming 82


v Control Structures Loops

for
• Switch between for and while loops
init;
for (init; condition; increment) { while (condition) {
statement 1;
statement 1;
... . . .
statement n;
statement n;
} increment;
}

init;
while (condition) {
for(init; condition; increment)
statement 1; {
. . .
statement 1;
statement n; ...
increment;
statement n;
} }

CT108H - Object Oriented Programming 83


v Control Structures Loops

for
int i = 0;
Initialize
int v = 1;
while (i <= N) {
[Link](i + "\t" + v);
v = 2 * v;
i = i + 1; Increment
}

for (int i=0, int v=1; i <= N; i++, v *= 2)) {


[Link](i + "\t" + v);
}

int v = 1;
for (int i=0; i <= N; i++)) {
Normally [Link](i + "\t" + v);
v = 2 * v;
}

CT108H - Object Oriented Programming 84


v Control Structures Loops

Nested Loop
• Control structures can be nested:
if (a == 0) { Solves a first-
if (b == 0) degree equation
[Link]("No solution");
else
[Link]("Multiple solutions");
} Show triangle of stars *
else { for (int i=0; i<5; i++) {
... for (int j=0; j <= i; j++)
} [Link]("*");

[Link]("");
Calculate the sum of even numbers from 1..N }
int sum = 0;
*
for (int i=0; i < N; i++) { * *
if (i % 2 == 0) * * *
sum += i; * * * *
} * * * * *

CT108H - Object Oriented Programming 85


v Control Structures

break and continue


• break: Ends a loop
§ When a break statement is encountered, the loop will end
immediately, regardless of the value of the conditional
expression
• continue: Starts a new iteration
§ When a continue statement is encountered, the program
will return to the beginning of the loop to perform a new
iteration
§ The statements below the continue statement will be
ignored
• Notice: Only use these two statements when
absolutely necessary because they break the structure
of the program.
CT108H - Object Oriented Programming 86
v Control Structures

Choosing
• while:
§ Check condition first (pre-test loop)
§ Used in case we do not want to execute the loop body if the
condition is false from the beginning
• do…while:
§ Check condition after (post-test loop)
§ Used in case of looping at least once
• for:
§ Check condition first (pre-test loop)
§ Often used in case of looping with a counting variable

CT108H - Object Oriented Programming 87


v Array

Array

CT108H - Object Oriented Programming 88


v Array

Array
• A sequence of elements having a same data type
• Is a reference variable:
§ Declare: <data type> <array name>[];
§ Initialize: <array name> = new <data type>;
double gpa[];
gpa 0 1 2 3 4
gpa = new double[5];

• Initialization at the same time of declaration


int []number = {2, 4, 6, 8};
String []monthName = {"Jan", "Feb", "March",…};

CT108H - Object Oriented Programming 89


v Array

Array
• Array elements are accessed through indexes
• Indexes start from 0
public class Fibonaci {
public static void main(String args[]) {
int fibo[] = new int [10];

fibo[0] = fibo[1] = 1;

for (int i=2; i< 10; i++)


fibo[i] = fibo[i-1] + fibo[i-2];

for (int i=0; i< 10; i++)


[Link](fibo[i] + " ");
}
}

CT108H - Object Oriented Programming 90


v Array

Array
p
• Array of objects: 
Person []p;  p
p = new Person[5]; ‚
p[0] = new Person();
//...
ƒ ‚
0 1 2 3 4

p
prs[0].setName("Tommy");
p[0].setName("Tommy");
prs[0].setAge(20);
p[0].setAge(20); 0 1 2 3 4
ƒ
for (Person t : p) {
Person
[Link]([Link]());
}

CT108H - Object Oriented Programming 91


v Array

Array
• Java supports multi-dimensional arrays

• Example: a two-dimensional array is defined as follows:


class TwoD { 0 1 2 3
public static void main (String args[]) { 0 1 2 3 4
int h, c; 1 5 6 7 8
int table[][] = new int [3][4]; 2 9 10 11 12
for (h=0; h < 3; ++h) {
for (c=0; c < 4; ++c) {
table[h][c] = (h*4) + c + 1; table[1][2]

[Link](table[h][c] + " ");


} [Link]();
}
}
}
CT108H - Object Oriented Programming 92
String

CT108H - Object Oriented Programming 93


v String

String
• String declaration and initialization:
§ String str1 = new String( );
§ String str11 = "Java strings";
//str1 is an empty string.
§ String str2 = new String("Hello World");
§ String str21 = new String (str2);
//str2 and str21 contain "Hello World"
§ char ch[] = {'A', 'B', 'C', 'D', 'E'};
§ String str3 = new String (ch);
//str3 contains "ABCDE"
§ String str4 = new String (ch,0,2);
//str4 contains "AB" since 0 - starting character, 2 -
number of characters
CT108H - Object Oriented Programming 94
v String

String
• Commonly used methods:
• boolean equals(String str): return true if the strings
are equals and false if not

String name = new String ("Java Language");


String name1 = new String ("Java Languages");
if ( [Link](name1) )
[Link]("equal");
else
[Link] ("not equal");

CT108H - Object Oriented Programming 95


v String

String
• int compareTo( String str): compares the given string with
the current string lexicographically. (less than 0 if current
string comes before given string, greater than 0 if current
string comes after given string and equal to 0 if they are
the same.
if ( [Link](name1) > 0)
[Link]("name1 comes before name2");
else if ( [Link](name1) < 0)
[Link]("name1 comes after name2");
else
[Link]("name1 equals name2");

CT108H - Object Oriented Programming 96


v String

String
• char charAt(int index)
• int length()
• String substring(int beginIndex)
• String substring(int beginIndex, int endIndex)
• boolean contains(CharSequence s)
• boolean equals(Object another)
• boolean isEmpty()
• String concat(String str)
• String replace(String oldStr, String newStr)
• String trim()
• int indexOf(String substring)
• String[] split(String string)
• boolean matches("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$")

CT108H - Object Oriented Programming 97


v Java Library

Java Library

CT108H - Object Oriented Programming 98


v Java Library

Math
• Provide methods for performing basic numeric
operations ([Link])
• Mostly are static methods (call from class)
§ [Link](25)
• Commonly used methods:
§ double/float/int/long abs(double/float/int/long);
§ double log/log10(double);
§ long/int round(double/float);
§ double sqrt(double);
§ double random();
• Other methods: sin, cos, asin, acos, exp, floor,
ceil, pow, min, max

CT108H - Object Oriented Programming 99


v Java Library

System
• package [Link]
• Provides useful utilities for standard I/O control:
InputStream in, PrintStreams out and err
• Commonly used methods:
§ void arraycopy: copy an array
§ long currentTimeMilis: return current time in miliseconds
§ void gc: request Garbage collection
§ Methods related to system’s properties: Java Runtime Environment version,
Java Path, etc.

[Link](src, srcPos, dest, destPos, length);

CT108H - Object Oriented Programming 100


v Java Library

Arrays
• import [Link];
• Perform operations like copying, sorting, and searching
elements on arrays
• Commonly used methods:
§ static int [] copyof: array copy, return new array
§ static boolean equals: compare two arrays for equality
(element by element)
§ static void sort: sort an array of primitive data
types or an array of objects (must implement Comparable
inferface or a custom Comparator can be provided)
§ static String toString: obtain a string representation
of the contents of an array

[Link](original, newLength)

CT108H - Object Oriented Programming 101


v Java Library

StringBuilder
• package [Link]
• Provides a mutable sequance of characters
• Eficient for operations involving frequent modifications
or concatenations of strings
• Một số hàm thông dụng như:
§ StringBuilder delete(int start, int end);
§ StringBuilder delete(int index);
§ StringBuilder insert(int index, char c);
§ StringBuilder replace(int start, int end, String str);
§ StringBuilder reverse();

CT108H - Object Oriented Programming 102


v Java Library

ArrayList
• import [Link];
• A resizable array (it can grow and shrink in size as
elements are added or removed)
• Commonly used methods:
§ boolean add(Object item);
§ Object get(int i);
§ Object remove(int i);
§ boolean remove(Object item);
§ boolean contain(Object item);
§ boolean isEmpty();
§ int size();

CT108H - Object Oriented Programming 103


v Java Library

ArrayList

CT108H - Object Oriented Programming 104


v Java Library

Collection and Map

CT108H - Object Oriented Programming 105


v Java Library

Collection Interface
• Define basic operations
§ Adding
§ Removing
§ Checking membership
• Contains methods for operating on
individual or block elements
• Provides methods for iterating
over the elements and converting
the collection to an array

CT108H - Object Oriented Programming 106


v Java Library

Collections
•s

CT108H - Object Oriented Programming 107


v Java Library

Collections
•s

CT108H - Object Oriented Programming 108


v Java Library

List Interface
• List inherits from Collection,
providing additional
methods for handling list-
type collections

• A list is a collection with


elements ordered by index

CT108H - Object Oriented Programming 109


v Java Library

Set Interface
• Set inherits from Collection
• Set: non-duplicate elements

• SortedSet: inherits Set


interface. Elements are
arranged in an order

CT108H - Object Oriented Programming 110


v Java Library

Set and HashSet


•s

CT108H - Object Oriented Programming 111


v Java Library

Map Interface
• Basic interface for
manipulating a collection of
key-value pairs
§ Add a key-value pair
§ Delete a key-value pair
§ Retrieve a value with an
existing key
§ Check if it is a member (key
or value)

CT108H - Object Oriented Programming 112


v Java Library

Map and HashMap


•s

CT108H - Object Oriented Programming 113


v Java Library

Iterator

CT108H - Object Oriented Programming 114


v Java Library

for each

CT108H - Object Oriented Programming 115


Question?
CT108H - OBJECT ORIENTED PROGRAMMING

You might also like