0% found this document useful (0 votes)
17 views60 pages

02 Foundation1

Chapter 2 provides an overview of the Java programming language, covering its structure, data types, operators, and control structures. It explains how to declare variables and constants, input and output data, and utilize arrays and strings. Additionally, it discusses control flow with if-else and switch statements, as well as looping structures like while and for.

Uploaded by

hamanhthe2005
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)
17 views60 pages

02 Foundation1

Chapter 2 provides an overview of the Java programming language, covering its structure, data types, operators, and control structures. It explains how to declare variables and constants, input and output data, and utilize arrays and strings. Additionally, it discusses control flow with if-else and switch statements, as well as looping structures like while and for.

Uploaded by

hamanhthe2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Chapter 2

FOUNDATION OF JAVA PROGRAMMING LANGUAGE

o Structure of a java program

o Data

o Operators

o Variable, constant

o Input/Ouput data

o Control structures

o Array

o String

2
Java program structure

program
(Project)

Package_1 Package_2 Package_n

Class1 Class 2 Class _n

Method21 Method22 Method2k


Java program structure
STRUCTURE OF A JAVA SOURCE FILE:

[ Package packageName;] //Declare package name


[ import java.awt.*;] //Declare the name of an existing library, if needed

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

✓ A single-line comment begins with //;


✓ multiple-line comments begin with /* and end with */.

// Command to display “Hello World!” on the screen


System.out.println(" Hello World! ");

/* Command to display
“Hello World!”
on the screen*/
System.out.println(" Hello World !");

6
IDENTIFICATION

Identifiers are names given in the program such as variable names


and constant names. Note:
• Case sensitive. Can contain letters, numbers, _, $
• Do not start with a number and do not use the same keyword as
the name
• Does not contain spaces, mathematical symbols
• Recommendation
✓ Meaningful names
✓ Start with lowercase letter.
For example: dateOfBirth, address, description, placeOfBirth
✓ Temporary variables in a narrow scope can be set to a, i, j….
✓ Avoid combining multiple languages (English + Vietnamese…)

7
DATA TYPES

o Basic data types : byte, float, short, double, int, char, long, boolean
o Object data type :

array An array of data of the same type.


User-defined object class data. Contains a set of properties
class
and methods..
User-defined interface class data. Contains interface
interface
methods.

8
DATA TYPES

Type Size value range example

byte 1 byte [ -128 , 127] byte x = 56;

short 2 byte [ -32768..32767 ] short x = 1000;

int 4 byte [ -2,147,483,648 , 2,147,483,647 ] int x = 150000 ;


[ -9,223,372,036,854,775,808 (2^63) , long x = 6
long 8 byte 9,223,372,036,854,775,807 (2^63 – 1)] 53535535632l;
float 4 byte 1.4E -45 - 3.4028235E 38 float x = 5 . 4 21 f
4.9E-34 -
double 8 byte 1.7976931348623157E308
double x = 5 . 4 21 d

char 2 byte 0 to 65,535 char c = ' ' ;

Boolean 1 bit True (1), false (0) boolean b = true;

9
DATA TYPES

char

byte short int long

float double

10
EXPRESSIONS AND OPERATORS

11
Mathematical functions
EXPRESSIONS AND OPERATORS

The conditional operator:


• Syntax:
< condition > ? < true value > : < false value >
• Interpretation: If the expression <condition> has the value true then
the result of the expression is < true value >, otherwise <false value >

• Example 1 : Find the largest of two numbers a and b


int a = 1, b = 9;
int max = a > b ? a : b;
Example 2 : Find the largest of the three numbers a, b , and c.
int max3 = (a>b?a:b)>c?(a>b?a:b):c;
Or: max2 = a>b?a:b
max3 = max2 > c ? max2: c

13
DECLARE VARIABLE

• Variable declaration syntax :


< data type > < variable name > [= <initial value ] ;
• For example:
✓ int a; // declare variable with no initial value
✓ double b = 5; // declare variable with initial value
✓ String name = “Anna”;
• Declare multiple variables of the same type: int a, b=5, c;

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

• A constant is a quantity whose value does not change during


program execution . Each constant has its own data type.
• Names are given by convention as variable names.
• Declaration using the final keyword

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

• Three functions can be used to output data:


System.out.print(): No line break after output
System.out.println(): Prints with a new line
System.out.printf(): Formatted output, characters format
✓ %d : integer
✓ %f : real number, default is 6 odd numbers
%.3f format 3 odd numbers
✓ %s: string
• For example:
✓ System.out. print (“UTC - ”);
✓ System.out.println (“University of Transport and Communications”) ;
✓ System.out. printf (“Training %d majors”, 20);

UTC – University of Transport and Communications


Training 20 majors

20
INPUT DATA - Scanner

• Step 1: import java.util.Scanner

• Step 2: Create Scanner object


Scanner <object_name> = new Scanner(System.in)

• B3: Use common methods to input


Scanner sc = new Scanner(System.in)
sc .nextLine() : input string
sc .nextInt() : input integer
sc .nextDouble() : input real

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

❖ There are 3 form of if


Form 1:

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 :

int a=10, b=4;


char ch='+';
switch (ch){
case '+': System.out.printf(“%d + %d = %d\n”,a,b,a+b ); break;
case '-': System.out.printf(“%d - %d = %d\n”,a,b,a-b ); break;
case '*': System.out.printf(“%d * %d = %d\n”, a,b,a*b ); break;
case '/': System.out.printf(“%d / %d = %.2f\n",a,b,(float)a/b);
break;
default :
System.out.println(“The calculation you entered is incorrect!”);
break;
}

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)

2. Write a personality test program based on the color you like:

- Enter color : blue, red, purple, yellow, pink, white

- 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

for(varInit; Condition; Step){ for(varInit:List){


Statements; Statements;
} }

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

o break : used to break the loop

o continue: used to continue the loop

36
BREAK, CONTINUE

o Example break : Enter a valid math score (must be between 0 and 10)

Scanner sc = new Scanner (System.in);


int score = 0;
while ( true ){
score = sc.nextInt();
if (score >= 0 && score <= 10){
break ;
}
System.out.println ("Score must be between 0 and 10");
}

37
BREAK, CONTINUE

o Example continue : Print out the numbers not divisible by 4 in the


range [1,10]

for (int i=1;i<=10;i++){


if (i%4 ==0){
continue ;
}
System.out. print (i + “,”);
}

Screen results: 1,2,3,5,6,7,9,10

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 s = new String(“abc”);


STRING
JAVA MEMORY

String s1= “Java” HEAP

String s2 = “PHP”
“Java”
“PHP”
String s3 = “Java”

String s4 = new String(“Java”)


“Java”
String s5 = new String(s1)

“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

• compare chain history use .equals


String s1 = " abc ";
System.out.println (s1.equals (" abc ")) ;
// or
System.out. println (“abc ”. equals (s1));

String s = new String(" abc ");


//s does
s.trim ();
System.out.print (s ); //"abc"
//need to reassign
s = s.trim ();
System.out.print (s); //" abc "
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

s.toUpperCase () Convert to uppercase

s.trim() Cut blank characters from both ends of string s

s.length () Get length string s

s.substring(n,m) Get m characters from position n

s.charAt (index) Get character at position index

s.replaceAll (find, replace) Find and replace all

s.split (separator) Split string into array


String s = “1,2,3,4,5,6,7”;
String arr[]=s.split(“,”);
METHODS OF STRING CLASS

Method describe
equals() Compare with distinction flower/regular

equalsIgnoreCase() Compare with no distinction flower/regular

contains(String str) Check if string str is present

startsWith(String str) Check if it starts with the string str

endsWith(String str) Check if it ends with the string str

matches() Match

indexOf(String str) Find the first position of a substring

lastIndexOf(String str) Find the last position of a substring

String valueOf(int a) Convert number to string


int a = 10; String s = String.valueOf(a);
EXAMPLE

String fullName = “Nguyen Van Ty ”; String


first = fullName. substring(0, 6) ;

Nguyen

// Split string into array


String s = “[email protected]
String[] sArr = s.split ("@", 2);
System.out.print (sArr [0]); // myemail
System.out.print (sArr [1]); //gmail.com

String s = "Hello world";


System.out.print(s.indexOf("world")); //6
EXAMPLE
❑ Write a program that inputs the username "hello" and the password is
greater than 8 characters, then prints out the login as successful,
otherwise it fails.
❑ Use equalsIgnoreCase( ) to compare usernames and length() to get the
length of the string

if(username .equalsIgnoreCase (“hello”) && password .length () > 8){



}
else{

}
EXAMPLE
❑ Enter an array of full names
❑ Output a list with full names in uppercase
❑ Output a list with full names entered from the keyboard
❑ Output a list with middle or first names as Thanh
❑ Replace full name with full name entered from the keyboard
EXAMPLE
❑ check the number even

String str = “2,5,6,4,8,9,12,13”;


String [] arrNumber = str.split(“,”)
for(String number : arrNumber){
int x = Integer.parseInt(number);
if(x % 2 == 0){
System.out.println(x);
}
}
REGULAR EXPRESSION

❑Do you know what the following strings mean?

[email protected] 1. Do you know why you recognize


them?
❖30A-771.61
❖0913745789 2. How can computers recognize them
❖192.168.11.200 like you?
REGULAR EXPRESSION

❑ Computers can recognize objects if we provide them with


recognition rules. Regular expressions provide string
recognition rules for computers.

❑ A regular expression is a pattern string used to specify the


format of a string. If a string matches the pattern, the string is
said to match.

❑ Example: [0-9]{3,7}: This regular expression matches


numeric strings of 3 to 7 characters.
[0-9]: characters from 0 to 9
{3,7}: minimum of 3 characters and a maximum of 7
characters
REGULAR EXPRESSION
REGULAR EXPRESSION

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

Information Check control


Student ID 5 numeric characters
Full Name letters only
Date of Birth format dd/mm/yyyy
Address 10 numeric characters,
Phone Number leading zero
Email

You might also like