CT176-OOP With Java Ch1 Java E
CT176-OOP With Java Ch1 Java E
• Execution results:
• Execution results:
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.
read compile
source code .java Compiler Bytecode
(.class)
load
execute
Java Virtual Machine
interprete
Hardware &
Operating System
JVM JVM
for Windows for Unix
JVM JVM
for Linux for Mac
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
Environment Installation
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)
arguments
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)
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
Scope of Variable
• Variable scope: locations in the program where the
variable can be accessed
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)
Numeric Datatype
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;
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);
}
}
Numeric Datatype
// This program demonstrates the double data type.
Boolean Datatype
• boolean type can have one of two values:
§ true
§ false
Boolean Datatype
bool = true;
[Link](bool);
bool = false;
[Link](bool);
}
}
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)
Character Datatype
ch = 'A';
[Link](ch);
ch = 66; //ch = 'B';
[Link](ch);
}
}
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
String Datatype
// This program demonstrates a few of the String methods.
[Link](message);
[Link](upper);
[Link](lower);
[Link](letter);
[Link](stringSize);
}
}
Variable Assignment
• To assign a value to a variable, we use the assignment
operator =
<variable> = <variable| constant | expression>
// This program shows variable assignment
month = 2;
days = 28;
[Link]("Month " + month + " has " +
days + " days.");
}
}
Variable Initialization
• A variable can be initialized immediately upon declaration
<kiểu DL> <tên biến> [= giá trị];
// This program shows variable initialization
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';
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;
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);
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)
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
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
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);
}
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
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
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
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);
int a, b;
[Link]("a = ");
a = [Link](); // read an int
[Link]("b = ");
b = [Link]();
[Link]("Nghiem cua PT x = %.2f", -(float)b/a);
}
}
String name;
long ID;
[Link]("Enter your ID: ");
ID = [Link]();
• [Link]();
[Link]("Enter your name: ");
name = [Link]();
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
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
if … else
• Full if statement:
if (condition) {
//statement T;
}
else {
//statement F;
}
if … else
• Example: find max value
if (x > y) {
max = x;
}
else {
max = y;
}
yes no
max = x x>y? max = y
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);
}
}
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
if … else
• if without else:
if (condition) {
statement T;
}
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
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
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.");
}
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");
}
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
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
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");
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]);
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
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'
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
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
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;
} }
for
int i = 0;
Initialize
int v = 1;
while (i <= N) {
[Link](i + "\t" + v);
v = 2 * v;
i = i + 1; Increment
}
int v = 1;
for (int i=0; i <= N; i++)) {
Normally [Link](i + "\t" + v);
v = 2 * v;
}
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; * * * *
} * * * * *
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
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];
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;
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]());
}
Array
• Java supports multi-dimensional arrays
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
• 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");
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}$")
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
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.
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)
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();
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();
ArrayList
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
Collections
•s
Collections
•s
List Interface
• List inherits from Collection,
providing additional
methods for handling list-
type collections
Set Interface
• Set inherits from Collection
• Set: non-duplicate elements
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)
Iterator
for each