Content: Nguyen Thi Thu Trang

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

1 – Java Basics

@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn @NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 2

Content
1. Identifiers
OBJECT-ORIENTED PROGRAMMING 2. Data Types
1.2 JAVA BASICS 3. Operators
Nguyen Thi Thu Trang 4. Control Statements
trangntt@soict.hust.edu.vn 5. Arrays

1 2

3 4

1. Identifiers 1. Identifiers (2)


• Naming convention:
• Identifiers: • Start with an Alphabet
• A set of characters representing variables, • Package: all in lowercase
methods, classes and labels • theexample
• Naming rules:
• Class: the first letter of word is in uppercase
• Characters can be numbers, alphabets, '$'
• TheExample
or ‘_’
• Name must not: • Method/field: start with a lowercase letter, the first letter
• Start by a Number of remaining word is in uppercase
• Be the same as a keyword • theExample
• Distinguish between UpperCases and • Constants: All in uppercase
LowerCases
• THE_EXAMPLE
• Yourname, yourname, YourName and
yourName are for different identifiers

3 4

Page 1
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 1
1 – Java Basics

5 @NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 6

1. Identifiers (3) Content


• Literals 1. Identifiers
null true false
• Keyword 2. Data Types
abstract assert boolean break byte case catch
char class continue default do double else 3. Operators
extends final finally float for if implements
import instanceof int interface long native new 4. Control Statements
package private protected public return short
static strictfp super switch synchronized this 5. Arrays
throw throws transient try void volatile while
• Reserved for future use
byvalue cast const future generic goto inner operator
outer rest var volatile

5 6

7 8

2. Data Types 2.1. Primitives


• Two categories:
• Every variable must be declared with a
• Primitive data type:
• Integer • Primitive data type contains a single value
• Size and format must be appropirate to its
• Float data type
• Char • Java has 4 primitive data types
• Logic (boolean)
• Reference
• Array
• Object

7 8

Page 2
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 2
1 – Java Basics

9 10

Integer Real
• Signed integer • Initially created with value 0.0
• Initially created with value 0

9 10

11 12

Characters Logic value


• Boolean value is clearly specified in Java
• Unsigned Unicode characters, placed between two single • An int value can not be used for a boolean value
quotes • Can store value “true” or “false”
• 2 ways to assign value: • Boolean variable is initially created with false value
• Using number in hexa: char uni ='\u05D0';
• Using character: char a = ‘A’;
• Default value is zero (\u0000)

11 12

Page 3
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 3
1 – Java Basics

13 14

2.2. Literal Literal of Integer


• Literal is a value of a set of primitive data types and • Octals start with number 0
character string. • 032 = 011 010(2) = 16 + 8 + 2 = 26(10)

• Has 5 categories: • Hexadecimals start with number 0 and character x


• 0x1A = 0001 1010(2) = 16 + 8 + 2 = 26(10)
• integer
• Ends with character “L” reperesenting data type long
• floating point Literals • 26L
• boolean integer…………..7 • Uppercase characters, usually have the same values
• character floating point…7.0f • 0x1a , 0x1A , 0X1a , 0X1A đều có giá trị 26 trong hệ decimal

• string boolean……….true
character……….'A'
string………….."A"

13 14

15 16

Literal of Real Literal of boolean, character and string


• Float ends with character f (or F) • boolean:
• true
• 7.1f
• false
• Double ends with character d (or D)
• Character:
• 7.1D
• Located between two single quotes
• e (or E) is used in scientific representation: • Example: ‘a’, ‘A’ or ‘\uffff’
• 7.1e2 • String:
• A value without ending character is considered as a • Located between two double quotes
double • Example: “Hello world”, “Xin chao ban”,…

• 7.1 giống như 7.1d

15 16

Page 4
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 4
1 – Java Basics

17 18

Escape sequence
2.3. Casting
• Characters for keyboard control
• \b backspace • Java is a strong-type languge
• \f form feed • Casting a wrong type to a variable can lead to a compiler
• \n newline error or exceptions in JVM
• \r return (về đầu dòng)
• \t tab
• JVM can implicitly cast a data type to a larger
• Display special characters in a string data type
• \" quotation mark • To cast a variable to a narrower data type, we
• \’ apostrophe need to do it explicitly
• \\ backslash
double f;
int a, b; int d; long g;
short c; short e; f = g;
a = b + c; e = (short)d; g = f; //error

17 18

19 20

c. Casting (2) Example - Casting


long p = (long) 12345.56; // p == 12345
• Casting is done
int g = p; // syntax error although int
automatically if no
// can hold a value of 12345
information loss
char c = ‘t’;
occurs
int j = c; // implicit casting
• byte à short à int à
short k = c; // error
long à float à double
short k = (short) c; // explicit casting
• Eexplicit cast is
float f = 12.35; // error
required if there is a
“risk” of reduced
accuracy

19 20

Page 5
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 5
1 – Java Basics

21 22

2.4. Declaration and Creation of Variables Comments


• Simple variables (that are not array) need to be • Java supports three types of comments:
initialized before being used in expressions • // Comments in a single line
• Can declare and initialize at the same time. // Without line break
• Using = to assign (including initialization) • /* Comments as a paragraph */

• Example: • /** Javadoc * comments in form of Javadoc */


int i, j; // Variable declaration
i = 0;
int k =i+1;
float x=1.0f, y=2.0f;
System.out.println(i); // Print out 0
System.out.println(k); // Print out 1
System.out.println(j); // Compile error

21 22

23 @NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 24

Command Content
• Command ends with; 1. Identifiers
• Multiple commands can be written on one line 2. Data Types
• A command can be written in multiple lines
3. Operators
• Example:
4. Control Statements
System.out.println(
5. Arrays
“This is part of the same line”);

a=0; b=1; c=2;

23 24

Page 6
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 6
1 – Java Basics

25 26

3. Operators 3. Operators (2)


• Combining single values or child expressions into a new • Arithmetic operators
expression, more complex and can return a value. • +, -, *, /, %
• Java provides the following operators: • Bit operators
• Arithmetic operators • AND: &, OR: |, XOR: ^, NOT: ~
• bit: <<, >>
• Bit oprator, Relational opretors
• Logic operators • Relational operators
• ==, !=, >, <, >=, <=
• Assignment operators
• Logic operators
• Unary operators
• &&, ||, !

25 26

27 28

3. Operators (3) Priorities of Operators


• Define the order of performing operators – are identified
• Unary operators by parentheses or by default as follows:
• Reverse sign : +, - • Postfix operators [] . (params) x++ x--
• Increase/decrease by 1 unit: ++, -- • Unary operators ++x --x +x -x ~ !
• Negation of a logic expression: ! • Creation or cast new (type)x
• Multiplicative * / %
• Assignment operators • Additive + -
• =, +=, -=, %= similar to >>, <<, &, |, ^ • Shift << >> >>> (unsigned shift)
• Relational < > <= >= instanceof
• Equality == !=
• Bitwise AND &
• Bitwise exclusive OR ^
• Bitwise inclusive OR |
• Logical AND &&
• Logical OR ||
• Conditional (ternary) ?:
• Assignment = *= /= %= += -= >>= <<= >>>= &= ^= |=

27 28

Page 7
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 7
1 – Java Basics

@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 29 30

Content 4.1. if – else statement


1. Identifiers • Syntax
if (condition){
2. Data Types statements;
}
3. Operators else {
statements;
4. Control Statements }

5. Arrays • condition expression can receive boolean value


• else expression is optional

29 30

31 32

Example – Checking odd – even numbers 4.2. switch – case statement


class CheckNumber
{
public static void main(String args[]) • Checking a single variable with
{ different values and perform the case a
[false]
[true]
case a break
action(s)
int num =10; corresponding case
[true]
if (num %2 == 0) • break: exits switch-case command case b case b break
[false] action(s)
System.out.println (num+ “la so chan”); • Default: manages values outside the
else values defined in case: .
.
.
System.out.println (num + “la so le”); [true]
case z case z break
} [false] action(s)
} default
action(s)

31 32

Page 8
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 8
1 – Java Basics

33 34

Example - switch - case 4.3. while and do while statements


switch (day) { • Perform a command or a command block
case 0:
case 1: while the control expression is still true
rule = “weekend”; • while() performs 0 or multiple times
break; • do...while() performs at least 1 time action state
case 2:
… int x = 2;
[true]
case 6: if (day == 0 || day == 1) { while (x < 2) { condition

rule = “weekday”; rule = “weekend”; x++;


[false]
System.out.println(x);
break; } else if (day > 1 && day <7) {
}
default: rule = “weekday”;
rule = “error”; } else { int x = 2;
} rule = error; do {
} x++;
System.out.println(x);
} while (x < 2);

33 34

35 36

Example – while loop 4.4. for loop


• Syntax:
class WhileDemo{
for (start_expr; test_expr; increment_expr){
public static void main(String args[]){
// code to execute repeatedly
int a = 5,fact = 1; }
while (a >= 1){ • 3 expressions can be absent
fact *=a; • A variable can be declared in for command:
a--; • Usually declare a counter variable
} • Usually declare in “start” expression
System.out.println(“The Factorial of 5 • Variable scope is in the loop
is “+fact); • Example:
} for (int index = 0; index < 10; index++) {
} System.out.println(index);
}

35 36

Page 9
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 9
1 – Java Basics

37 38

Example – for loop Commands for changing control structure


class ForDemo • break
{
• Can be used to exit switch command
public static void main(String args[])
{ • Terminate loops for, while or do...while
int i=1, sum=0; • There are two types:
for (i=1;i<=10;i+=2) • Labeling: continue to perform commands after the labeled loop
sum+=i; • No-Labeling: perform next commands outside the loop
System.out.println (“Sum of first five • continue
old numbers is “ + sum);
} • Can be used for for, while or do...while loops
} • Ignore the remaining commands of the current loop and
perform the next iteration.

37 38

39 40

Example - break and continue Variable scope


public int myMethod(int x) { • Scope of a variable is a program area in which that
int sum = 0; variable is referred to
outer: for (int i=0; i<x; i++) { • Variables declared in a method can only be accessed
inner: for (int j=i; j<x; j++){ inside that method
sum++;
• Variables declared in a loop or code block can only be
if (j==1) continue;
accessed in that loop or that block
if (j==2) continue outer;
if (i==3) break;
if (j==4) break outer;
}
}
return sum;
}

39 40

Page 10
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 10
1 – Java Basics

@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 41 42

Content 5. Array variableName

1. Identifiers reference
2. Data Types • Finite set of elements of the same type
3. Operators • Must be declared before use Array or Object
• Declaration:
4. Control Statements
• Syntax:
5. Arrays • datatype[] arrayName= new datatype[ARRAY_SIZE];
• datatype arrayName[] = new datatype[ARRAY_SIZE];
• Example:
• char c[] = new char[12];

41 42

43 44

Array declaration and initialization


Example - Array
c[ 0 ] -45
Array name (all the
• Declaration and initialization: elements of array c[ 1 ] 6
• Syntax: have the same
name, c) c[ 2 ] 0
• datatype[] arrayName = {initial_values};
c[ 3 ] 72
• Example:
c[ 4 ] 1543
• int[] numbers = {10, 9, 8, 7, 6}; c.length: length of
the array c c[ 5 ] -89
• Without initialization à receives the default value
c[ 6 ] 0
depending on the data type.
c[ 7 ] 62
• Always starts with the element of index 0 c[ 8 ] -3
c[ 9 ] 1
Index (to access to the
elements of array) c[ 10 ] 6453
c[ 11 ] 78

43 44

Page 11
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 11
1 – Java Basics

45 46

Array declaration and initialization – Example Multi-dimensional array


int MAX = 5; • Table with rows and columns
boolean bit[] = new boolean[MAX];
• Usually use two-dimensional array
float[] value = new float[2*3];
• Example of declaration b[2][2]
int[] number = {10, 9, 8, 7, 6};
• int b[][] = { { 1, 2 }, { 3, 4 } };
System.out.println(bit[0]); // prints “false”
• 1 and 2 are initialized for b[0][0] and b[0][1]
System.out.println(value[3]); // prints “0.0” • 3 and 4 are initialized for b[1][0] and b[1][1]
System.out.println(number[1]); // prints “9” • int b[3][4];

45 46

47

Multi-dimensional array (2)

Column 0 Column 1 Column 2 Column 3

Row 0
b[ 0 ][ 0 ] b[ 0 ][ 1 ] b[ 0 ][ 2 ] b[ 0 ][ 3 ]

Row 1
b[ 1 ][ 0 ] b[ 1 ][ 1 ] b[ 1 ][ 2 ] b[ 1 ][ 3 ]

Row 2
b[ 2 ][ 0 ] b[ 2 ][ 1 ] b[ 2 ][ 2 ] b[ 2 ][ 3 ]

Column index

Row index

Array name

47

Page 12
@NGUYỄN Thị Thu Trang, trangntt@soict.hust.edu.vn 12

You might also like