0% found this document useful (0 votes)
18 views13 pages

Java Basics: Identifiers, Data Types, Operators

The document provides an overview of Java programming basics, including identifiers, data types, operators, control statements, and arrays. It outlines naming conventions for identifiers, the types of data in Java, and the various operators available. Additionally, it covers control flow mechanisms such as if-else statements, switch-case, and loops, along with examples for better understanding.
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)
18 views13 pages

Java Basics: Identifiers, Data Types, Operators

The document provides an overview of Java programming basics, including identifiers, data types, operators, control statements, and arrays. It outlines naming conventions for identifiers, the types of data in Java, and the various operators available. Additionally, it covers control flow mechanisms such as if-else statements, switch-case, and loops, along with examples for better understanding.
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

2

Content
1. Identifiers
OBJECT-ORIENTED LANGUAGE AND THEORY 2. Data Types
02-2. JAVA BASICS 3. Operators
4. Control Statements
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 each 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 four different identifiers

3 4

Page 1
1
5 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 Type 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 Type
• Array
• Object

7 8

Page 2
2
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
3
13 14

2.2. Literal Literal of Integer


• Literal is a value of primitive types or string. • Octal starts with number 0
• 032 = 011 010(2) = 16 + 8 + 2 = 26(10)
• 5 categories:
• Hexadecimal starts with number 0 and character x
• integer
• 0x1A = 0001 1010(2) = 16 + 8 + 2 = 26(10)
• floating point • Value ends with character “L” representing long data type
• boolean Literals • 26L

• character integer…………..7 • Case insensitive: uppercase and lowercase characters are


• string floating point…7.0f the same
boolean……….true • 0x1a , 0x1A , 0X1a , 0X1A all are 26 in decimal
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 is the same as 7.1d

15 16

Page 4
4
17 18

Escape sequence
2.3. Casting
• Characters for keyboard control
• \b backspace • Java is a strongly-typed language
• \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


• Casting is done long p = (long) 12345.56; // p == 12345
automatically if it does not int g = p; // syntax error although an int
lose information (widening // can hold a value of 12345
primitive conversion)
• byte à short à int à char c = ‘t’;
long à float à double int j = c; // implicit conversion
• Explicit cast is required if short k = c; // error
there is a “risk” of reduced
accuracy (narrowing short k = (short) c; // explicit conversion
primitive conversion) float f = 12.35; // error

19 20

Page 5
5
21 22

Example - Casting 2.4. Declaring and Initializing Variables


float f = 0.0; • Single variables (that are not array) need to be
float f = 0; initialized before being used in expressions
long l = 999999999999; • We can declare and initialize at the same time.
short k = 99999999; • We use = to assign new value (or initialize variable)
• Example:
short i = 6, j=7; int i, j; // Variable declaration
i = i + j;
i = 0;
i += j;
int k =i+1;
float x=1.0f, y=2.0f;
short i, j = 5; [Link](i); // Print out 0
int n = 6;
[Link](k); // Print out 1
i = (short)n + j;
[Link](j); // Compile error

21 22

23 24

Comments Command
• Java supports three types of comments: • Command ends with;
• // Comments in a single line
• Multiple commands can be written on one line
// Without line break
• /* Comments as a paragraph */ • A command can be written in multiple lines
• /** Javadoc * comments in form of Javadoc */
• Example:

[Link](
“This is part of the same line”);

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

23 24

Page 6
6
25 26

Content 3. Operators
1. Identifiers • An operator combines single values or child expressions
into a more complex expression. It can return a value.
2. Data Types • Java provides the following operators:
3. Operators • Arithmetic operators
• Bitwise operator, relational operators
4. Control Statements
• Logical operators
5. Arrays • Assignment operators
• Unary operators

25 26

27 28

3. Operators (2) 3. Operators (3)


• Arithmetic operators • Unary operators
• +, -, *, /, % • Reverse sign : +, -
• Bitwise operators • Increase/decrease by 1 unit: ++, --
• Negation of a logic expression: !
• AND: &, OR: |, XOR: ^, NOT: ~
• bit: <<, >> • Assignment operators
• Relational operators • =, +=, -=, %=

• ==, !=, >, <, >=, <= • >>=, <<=, &=, |=, ^=

• Logical operators
• &&, ||, !

27 28

Page 7
7
29 30

Precedence of Java Operators Content


Operator precedence determines the grouping of terms in an

expression. This affects how an expression is evaluated.
1. Identifiers
• Postfix operators [] . (params) x++ x--
• Unary operators ++x --x +x -x ~ !
2. Data Types
• Creation or cast new (type)x
• Multiplicative * / %
3. Operators
• Additive + -
• Shift << >> >>> (unsigned shift)
4. Control Statements
• Relational < > <= >= instanceof
• Equality == !=
5. Arrays
• Bitwise AND &
• Bitwise exclusive OR ^
• Bitwise inclusive OR |
• Logical AND &&
• Logical OR ||
• Conditional (ternary) ?:
• Assignment = *= /= %= += -= >>= <<= >>>= &= ^= |=

29 30

31 32

4.1. if – else statement Example – Checking odd – even numbers


• Syntax class CheckNumber
if (condition){ {
statements; public static void main(String args[])
} {
else { int num =10;
statements; if (num %2 == 0)
} [Link] (num + “is an even number”);
else
• condition expression returns Boolean value [Link] (num + “is an odd number”);
• else expression is optional }
}

31 32

Page 8
8
33 34

4.2. switch – case statement Example - switch - case


switch (day) {
case 0:
• Check a single variable with case 1:
different values and perform the case a [true]
case a break
rule = “weekend”;
[false] action(s) break;
corresponding case case 2:
[true]
• break: exits switch-case command case b case b break …
[false] action(s)
• default: manages values outside the case 6: if (day == 0 || day == 1) {
values defined in case . rule = “weekday”; rule = “weekend”;
.
break; } else if (day > 1 && day <7) {
• The variable used in a switch
.
[true]
default: rule = “weekday”;
statement can only be integers, case z
[false]
case z
action(s)
break
rule = “error”; } else {
convertable integers (byte, short, default
action(s) } rule = error;
char), strings and enums. }

33 34

35 36

4.3. while and do while statements Example – while loop


• Perform a command or a command block
class WhileDemo{
as long as a given condition is true public static void main(String args[]){
• while() performs 0 or multiple times int a = 5,fact = 1;
• do...while() performs at least 1 time action state
while (a >= 1){
int x = 2;
fact *=a;
[true]
while (x < 2) { condition a--;
x++;
[false]
[Link](x); }
}
[Link](“The Factorial of 5
int x = 2; is “+fact);
do {
x++; }
[Link](x);
} while (x < 2);
}

35 36

Page 9
9
37 38

4.4. for loop Example – for loop


• Syntax: class ForDemo
for (start_expr; test_expr; increment_expr){ {
// code to execute repeatedly public static void main(String args[])
} {
• 3 expressions can be absent int i=1, sum=0;
• A variable can be declared in for command: for (i=1;i<=10;i+=2)
• Usually declare a counter variable
sum+=i;
• Usually declare in the “start” expression
[Link] (“Sum of first five
old numbers is “ + sum);
• Variable scope is in the loop
}
• Example: }
for (int index = 0; index < 10; index++) {
[Link](index);
}

37 38

39 40

Loop control statements Example - break and continue


public int myMethod(int x) {
• break
int sum = 0;
• Can also be used to exit switch command outer: for (int i=0; i<x; i++) {
• Terminate loops (for, while or do...while ) inner: for (int j=i; j<x; j++){
• There are two types: sum++;
• labeled: continue to perform commands after the labeled loop if (j==1) continue;
• unlabeled: perform next commands outside the loop containing if (j==2) continue outer;
the break statement if (i==3) break;
• continue if (j==4) break outer;
}
• Can be used for for, while or do...while loops }
• Ignore the remaining commands of the current loop and return sum;
perform the next iteration. }

39 40

Page 10
10
41 42

Variable scope Content


• Scope of a variable is a program area in which the variable
is referred to
1. Identifiers
• Variables declared in a method can only be accessed 2. Data Types
inside that method
3. Operators
• Variables declared in a loop or code block can only be
accessed in that loop or that block 4. Control Statements
5. Arrays

41 42

43 44

5. Array variableName Array declaration, instantiation, and initialization

reference • Declaration, instantiation and initialization:


• Syntax:
• Finite set of elements of the same type • datatype[] arrayName = {initial_values};
• Must be declared before being used Array or Object • Example:
• int[] numbers = {10, 9, 8, 7, 6};
• Declaration and instantiation:
• Without initialization à receives the default value
• Syntax:
• datatype[] arrayName= new datatype[ARRAY_SIZE];
depending on the data type.
• datatype arrayName[] = new datatype[ARRAY_SIZE]; • Always starts with the element of index 0
• Example:
• char c[] = new char[12];

43 44

Page 11
11
45 46

Example
Example - Array
//Java Program to illustrate how to declare, instantiate, initialize c[ 0 ] -45
Array name (all the
//and traverse the Java array. elements of array c[ 1 ] 6
class Testarray { have the same
name, c) c[ 2 ] 0
public static void main(String args[]) {
int a[] = new int[5];// declaration and instantiation c[ 3 ] 72
a[0] = 10;// initialization c[ 4 ] 1543
a[1] = 20; [Link]: length of
a[2] = 70; the array c c[ 5 ] -89
a[3] = 40; c[ 6 ] 0
a[4] = 50;
c[ 7 ] 62
//traversing array
for (int i = 0; i < [Link]; i++)// length is the property of array c[ 8 ] -3
[Link](a[i]); c[ 9 ] 1
} Index (to access to the
} elements of array) c[ 10 ] 6453
c[ 11 ] 78

45 46

47 48

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 } };
[Link](bit[0]); // prints “false”
• 1 and 2 are initialized for b[0][0] and b[0][1]
[Link](value[3]); // prints “0.0” • 3 and 4 are initialized for b[1][0] and b[1][1]
[Link](number[1]); // prints “9” • int b[3][4];

47 48

Page 12
12
49

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

49

Page 13
13

You might also like