02 Foundation1
02 Foundation1
o Data
o Operators
o Variable, constant
o Input/Ouput data
o Control structures
o Array
o String
2
Java program structure
program
(Project)
// define classes:
[access range] class ClassName [ extends AnyClass] [ implements
InterfaceList]{ }
/*Note, if necessary*/
// Declare variable
// Define functions and methods
// define interfaces:
[access range] interface InterfaceName [ extends AnyInterface] {
}
//Declare constants
// Declare functions (Name Only, No Body)
Java program structure
Example 1: HelloWorld.java
public class Hello
{
public static void main(String[] args)
{
System.out.println( " Hello You !" );
} // end method
} //end class
Hello You !
5
COMMENT
/* Command to display
“Hello World!”
on the screen*/
System.out.println(" Hello World !");
6
IDENTIFICATION
7
DATA TYPES
o Basic data types : byte, float, short, double, int, char, long, boolean
o Object data type :
8
DATA TYPES
9
DATA TYPES
char
float double
10
EXPRESSIONS AND OPERATORS
11
Mathematical functions
EXPRESSIONS AND OPERATORS
13
DECLARE VARIABLE
Note: In Java, if a variable is not initialized when declared, it will receive a default
value. Each data type has a different default value.
– 0 if the data type is numeric
– '\0' if the data type is character
– false if data type is boolean
– null if data type is class
14
DECLARE VARIABLE
• How to name variables:
✓ Use alphabetic characters, numbers, $ or underscore (_).
✓ Names are case sensitive
✓ Do not start with a number, do not use keywords
15
DECLARE VARIABLES
16
DECLARE VARIABLES
17
DECLARE CONSTANT
final < data type > < constant name > = < value > ;
• For example:
✓ final int a=20 ;
✓ final String hoten = “Nguyen Van Dung";
• Attention:
✓ Character constants: placed between 2 single quotes ‘ '
✓ String constant: is a sequence of characters placed between 2 double
quotes “ ”
18
DECLARE CONSTANT
character meaning
\b Backspace (BackSpace)
\t Tab
\n Down row
\r Sign enter
\” Blink double
\' Blink single
\\ \
\f Push page
\uxxxx Character Unicode
Special character constants
19
OUTPUT DATA IN JAVA
20
INPUT DATA - Scanner
21
INPUT DATA - Scanner
• For example:
package Lab01;
import java.util.Scanner;
public class Lab11 {
public static void main(String[] args){
//Input
Scanner sc = new Scanner(System.in);
System.out.print("Full name : "); String fullName = sc.nextLine();
System.out.print(“Java score: "); double java = sc.nextDouble();
//Output
System.out.print(fullName + ", java score : " + java + "\n");
System.out.println(fullName + ", java score: " + java);
System.out.printf("%s %.2f \n", fullName, java);
}
} 22
INPUT DATA - Scanner
INPUT DATA – BufferedReader
Enter characters from the keyboard
Convert string to number
CONTROL STRUCTURES
❑ Branch
✓ if
✓ switch
❑ Repeat:
✓ while
✓ do…while
✓ for
❑ Interrupt command:
✓ break
✓ continue
27
IF STRUCTURE
if (condition) {
//Statements;
}
Example :
int a=8;
if (a % 2 == 0) {
System.out.println(a + “ is an even number”);
}
28
IF STRUCTURE
❖ Form 2:
if (condition) {
//Statements;
} else {
//Statement;
}
Example :
int a=8;
if (a % 2 == 0) {
System.out.println(a + “ is an even number”);}
else {
System.out.println(a + “ is an odd number”); }
29
IF STRUCTURE
Form 3 : Multiple conditions
if (condition_1) {
//Statements_1;
} else if (condition_2){
//Statements_2;
} else if (condition_3){
//Statements_3;
}
…
else {
//Statements_N+1;
}
int a = -10;
if (a > 0) {
System.out.println(a + “ is a number greater than 0”);}
else if (a == 0){
System.out.println(“This is 0”); }
else {
System.out.println(a + “ is a number less than 0”);}
30
SWITCH STRUCTURE
Syntax:
switch ( Expression )
{
case Cons1 : Statement_1; [break] ;
case. case Cons2 : Statement_2; [break] ;
…
default : Statement_N+1; [break] ;
}
Interpretation:
If <expression> = <value i> then perform <job i> in reverse will do <job N+1>
If the case does not contain break then the next case will be executed
The program will exit the switch statement when it encounters a break
statement.
31
SWITCH STRUCTURE
Example :
32
EXERCISES USING IF AND SWITCH
1. Write a program to input month and year. Display the number of days in
that month and year on the screen. (Months 1, 3, 5, 7, 8, 10, 12 have
31 days . Months 4, 6, 9, 11 have 30 days . If the year is divisible by 4,
then February has 29 days)
- Displays the personality of the person who likes that color on the screen.
If you enter a different color, the program will say: “The program is
updating!”
33
REPEATING STRUCTURE
o Syntax :
while (Condition) { do {
Statements; Statements;
} }
while (condition);
o example: o example:
int i=1; int i=1;
while (i<=20) { do {
System.out. print (i + “,”); System.out.println(i + “,”);
i++; i++; }
} while (i<=20);
34
REPEATING STRUCTURE
o Example 1 :
int[] a = new int[] { 1, 2, 3, 4, 5 };
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
o Example 2 :
int[] a = new int[] { 1, 2, 3, 4, 5 };
for (int n : a) {
System.out.println(n);
}
35
BREAK, CONTINUE
36
BREAK, CONTINUE
o Example break : Enter a valid math score (must be between 0 and 10)
37
BREAK, CONTINUE
38
ARRAY
❑ Advantage
❖ Use arrays to store multiple values instead of declaring multiple
value variables
❖ Easily read, sort and search data from elements
❑ Disadvantages
❖ Fixed array size
❖ Requires sufficient memory
ARRAY
Example:
int[] a = {4, 3, 5, 9};
❑ Declaration array for(int i=0; i<a.length ; i++){
❖ datatype [] arr; -> int[] A; System.out.println( a[i] );
}
❖ data type arr [] ; -> int A[];
❑ Initialize size array
arr = new datatype[ size]; -> A = new int[10];
❑ Declare and initialize the
datatype[] arr = new datatype[ size]; -> int[] A = new int[10];
datatype[] arr = {elem1, elem2,…}; -> int[] A = {2,4,6,7,8,9};
Array size: array_name.length
ARRAYS CLASS
import java.util.Arrays;
Note: binarySearch() only works with arrays that are sorted in ascending order.
ARRAYS CLASS
STRING
• Syntax
String < name > [= VALUE];
String s = “abc ”;
String s2 = “PHP”
“Java”
“PHP”
String s3 = “Java”
“Java”
System.out.print (s1 == s3) //true
System.out.print (s1 == s4) //false
s1, s3 refer to the same “Java” value stored in the String Pool
s 4, s5 are created with new so the value is stored in new memory because it
is not managed by String Pool
The == operator compares the memory address of an object.
STRING
String Pool
“hello n02-k59”
“HELLO N02-K59”
STRING
• use “+ “
String s1 = “An";
System.out.println (“My name is ” + s1);
JAVA MEMORY
HEAP
String s1= “abc”
String Pool
“abc”
s1 = s1 + “def” “abcdef”
“abcdefghi”
s1 = s1 + “ghi”
String s1 = "abc";
s1 = s1 + "def";
s1 = s1 + "ghi";
System.out.println (s1);
STRING
StringBuilder sb = new StringBuilder("abc");
sb.append ("def");
sb.append ("ghi");
System.out.println(sb.toString());
JAVA MEMORY
HEAP
String Pool
StringBuilder sb = new
StringBuilder (" abc “); “abc”
sb.append ("def "); “def”
sb.append ("ghi"); “ghi"
METHODS OF STRING CLASS
methods describe
s.toLowerCase () Convert to lowercase
Method describe
equals() Compare with distinction flower/regular
matches() Match
Nguyen
[0-9] {3, 7}
REGULAR EXPRESSION
❑ ID: [0-9]{9}
❑ Vietnamese mobile phone number: 0\d{9}
❑ Motorcycle license plate: 5\d-[AZ]\d-((\d{4})|(\d{3}\.\d{2}))
❑ Email
❖ \w+@\w+(\.\w){1,2}
❖ ^ [\w - _\. + ] * [\w - _\.]\@ ([\w] + \.) + [\w] + [\w]
❑ Check username: Username must be 6 to 12 characters long,
with no spaces: [a - z0 - 9_ - ] {6,12}
❑ Date format dd/mm/yyyy or dd-mm-yyyy:
❖ \\d {2} [ - |/]\d{2}[-|/]\d {4}
REGULAR EXPRESSION
❑ Enter employee information from the keyboard. Each employee's
information must comply with the following constraints. Output an error
message and ask for re-entry.