Object oriented programming Chapter 02
Object oriented programming Chapter 02
Slide 1
© Information Technology
Outlines
Blocks of java programming
Identifiers (Variable, classes, methods, interfaces…)
Data Types
keywords
Operators
Control statements
Decision Statements
If statement, Switch statement
Repetition Statements
• For loop, While, Do while loop
Arrays and working with arrays
Slide 2
© Information Technology
Variable types and identifiers
Java Variables
• Variables are containers for storing data values.
• Name of a location in memory that holds a data value.
• In Java, there are different types of variables, for example:
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
boolean - stores values with two states: true or false
Slide 3
© Information Technology
Variable types and identifiers…
• Where type is one of Java's types (such as int or String), and variableName is
the name of the variable (such as x or name). The equal sign is used to assign
values to the variable.
• To create a variable that should store text, look at the following example:
Slide 4
© Information Technology
Variable types and identifiers…
Slide 5
© Information Technology
Variable types and identifiers…
Final Variables
• you can add the final keyword if you don't want others (or yourself) to
overwrite existing values (this will declare the variable as "final" or "constant",
which means unchangeable and read-only):
public class Example {
public static void main(String[] args) {
final int myNum = 15;
myNum = 20; // will generate an error: Cannot assign a value to a final keyword
System.out.println(myNum);
}
}
Slide 6
© Information Technology
Variable types and identifiers…
Display Variables
• The println() method is often used to display variables.
• To combine both text and a variable, use the + character.
Slide 7
© Information Technology
Variable types and identifiers…
Slide 8
© Information Technology
Variable types and identifiers…
Java Identifiers
• All Java components require unique name.
• Name used for classes, methods, interfaces and variables are called Identifier.
• Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
• Note: It is recommended to use descriptive names in order to create
understandable and maintainable code.
• EX:
int minutesPerHour = 60;
Slide 9
© Information Technology
Variable types and identifiers…
Java Identifiers…
The general rules for naming variables are:
• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter, underscore or dollar sign
• Names should start with a lowercase letter and it cannot contain whitespace
• Names are case sensitive ("myVar" and "myvar" are different variables)
• Reserved words (like Java keywords, such as int or Boolean) cannot be used as names
Slide 10
© Information Technology
Java Data Types
Slide 11
© Information Technology
Java Data Types…
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Slide 13
© Information Technology
Java Data Types…
Slide 14
© Information Technology
Java Data Types…
Slide 15
© Information Technology
Java Data Types…
Slide 16
© Information Technology
Java Data Types…
Slide 17
© Information Technology
Java Data Types…
Slide 18
© Information Technology
Java Data Types…
Slide 19
© Information Technology
Java Data Types…
Slide 22
© Information Technology
Java Data Types…
Slide 25
© Information Technology
Java Keywords…
Slide 26
© Information Technology
Java Operators
Slide 27
© Information Technology
Java Operators…
Arithmetic Operators
• Arithmetic operators are used to perform common mathematical operations.
Operator Name Description Example public class Example{
+ Addition Adds together two values x+y public static void main(String args[]){
int a =10;
- Subtraction Subtracts one value from x-y int b =20;
another int c =25;
* Multiplicatio Multiplies two values x*y int d =25;
n System.out.println("a + b = "+(a + b));
/ Division Divides one value by another x/y System.out.println("a - b = "+(a - b));
System.out.println("a * b = "+(a * b));
% Modulus Returns the division x%y
System.out.println("b / a = "+(b / a));
remainder System.out.println("b % a = "+(b % a));
System.out.println("c % a = "+(c % a));
++ Increment Increases the value of a ++x
variable by 1 System.out.println("a++ = "+(a++));
System.out.println("b-- = "+(b--));
-- Decrement Decreases the value of a --x
variable by 1 System.out.println("d++ = "+(d++));
© Information Technology
System.out.println("++d = "+(++d)); Slide 28
Java Operators…
Assignment Operators
• Assignment operators are used to assign values to variables.
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
!= x != 3 x = x !3
Slide 29
© Information Technology
Java Operators…
Comparison Operators
• Comparison operators are used to compare two values
Operator Name Example
public class Example{
== Equal to x == y public static void main(String args[]){
int a =10;
!= Not equal x != y int b =20;
Output:
> Greater than x>y
System.out.println("a == b = "+(a==b)); a == b = false
a != b = true
System.out.println("a != b = "+(a !=b)); a > b = false
< Less than x<y System.out.println("a > b = "+(a > b)); a < b = true
b >= a = true
System.out.println("a < b = "+(a < b)); b <= a = false
>= Greater than or equal x >= y
to System.out.println("b >= a = "+(b>=a));
<= Less than or equal to x <= y System.out.println("b <= a = "+(b<=a));
}
}
© Information Technology
Slide 30
Java Operators…
Logical Operators
• Logical operators are used to determine the logic between variables or values
public class Example{
Opera Name Description Example
tor public static void main(String args[]){
&& Logical Returns true if both x < 5 && x boolean a = true;
and statements are true < 10
boolean b = false;
System.out.println("a && b ="+(a&&b));
|| Logical or Returns true if one x < 5 || x <
of the statements is 4 System.out.println("a || b = "+(a||b));
true
System.out.println("!(a && b)=“ + ! ( a&&
! Logical not Reverse the result, !(x < 5 && b) ); u t:
returns false if the x < 10)
O ut p
result is true } = fa lse
& & b e
} a t r u
|| b = true
a b )=
&
© Information Technology !(a & Slide 31
Java Type Casting
• Type casting is when you assign a value of one primitive data type to another
type.
• In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a larger type size
byte (1byte)-> short (2byte)
char (2byte)-> int (4byte)
float (4byte)-> double (8byte)
Narrowing Casting (manually) - converting a larger type to a smaller size type
double (8byte)-> float (4byte)
long (8byte)-> int (4byte)
char (2byte)-> short (4byte)
Slide 32
© Information Technology
Java Type Casting…
Widening(implicit) Casting
• Widening casting is done automatically when passing a smaller size type to a
larger size type
public class Example {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; //automatic casting: int to double
System.out.println(myInt); //outputs 9
System.out.println(myDouble); //outputs 9.0
}
}
Slide 33
© Information Technology
Java Type Casting…
Narrowing(explicit) Casting
• Narrowing casting must be done manually by placing the type in parentheses
in front of the value:
public class Example {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; //manual casting: double to int
Slide 34
© Information Technology
Java Control Statements
Conditions and If Statements
• Java supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to: a == b
Not Equal to: a != b
• You can use these conditions to perform different actions for different
decisions.
Slide 35
© Information Technology
Java Conditions and If Statements…
Slide 36
© Information Technology
Java Conditions and If Statements…
The if Statement
• Use the if statement to specify a block of Java code to be executed if a
condition is true
• Syntax if (condition) {
// block of code to be executed if the condition is
true
}
Slide 37
© Information Technology
Java Conditions and If Statements…
The else Statement
• Use the else statement to specify a block of code to be executed if the
condition is false
• Syntax if (condition) {
// block of code to be executed if the condition is true
} else{
// block of code to be executed if the condition is false
}
if (condition1) {
// block of code to be executed if the condition1 is true
} else if (condition2){
// block of code to be executed if the condition1 is false and
condition2 is true
} else{
// block of code to be executed if the condition1 is false and
condition2 is false
}
Slide 39
© Information Technology
Java Conditions and If Statements…
The else if Statement…
public class Example {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 25) {
System.out.println("Good day."); //outputs Good day.
} else {
System.out.println("Good evening.");
}
}
}
Slide 40
© Information Technology
Java Conditions and If Statements…
Short Hand If...Else (Ternary Operator)
• There is also a short-hand if else, which is known as the ternary operator
because it consists of three operands.
• It can be used to replace multiple lines of code with a single line. It is often
used to replace simple if else statements
• Syntax
variable = (condition) ? expressionTrue :
expressionFalse;
Slide 41
© Information Technology
Java Conditions and If Statements…
Short Hand If...Else (Ternary Operator)…
Slide 42
© Information Technology
Java Switch Statements
• Use the switch statement to select one of many code blocks to be executed.
• Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Slide 43
© Information Technology
Java Switch Statements…
Slide 44
© Information Technology
Java Switch Statements…
public class Example {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5: Output
System.out.println("Friday"); Thursday
break;
case 6:
System.out.println("Saturday");
break;
}
}
} © Information Technology
Slide 45
Java Switch Statements…
public class Example {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
} Output
}
Looking forward to the Weekend
Slide 46
© Information Technology
Java Iteration Statements
Slide 47
© Information Technology
Java Iteration Statements..
While Loop…
Slide 48
© Information Technology
Java Iteration Statements..
Slide 49
© Information Technology
Java Iteration Statements..
Slide 50
© Information Technology
Java Iteration Statements..
For Loop
• When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop.
• Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
• Statement 1 is executed (one time) before the execution of the code block.
• Statement 2 defines the condition for executing the code block.
• Statement 3 is executed (every time) after the code block has been executed.
Slide 51
© Information Technology
Java Iteration Statements..
For Loop…
public class Example {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
} Output
0
} 1
2
3
4
Slide 52
© Information Technology
Java Iteration Statements..
For-Each Loop
• There is also a "for-each" loop, which is used exclusively to loop through
elements in an array
• Syntax
for (type variableName : arrayName) {
// code block to be executed
}
Slide 53
© Information Technology
Java Iteration Statements..
For-Each Loop…
Slide 54
© Information Technology
Java Break and Continue
Java Break
• The break statement can also be used to jump out of a loop.
public class Example {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
} Output
System.out.println(i); 0
1
} 2
} 3
}
Slide 55
© Information Technology
Java Break and Continue…
Java Continue
• The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
public class Example {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) { Output
0
continue; 1
} 2
System.out.println(i); 3
} 5
6
}
7
} 8
9 Slide 56
© Information Technology
Java Arrays
String[] cars;
• We have now declared a variable that holds an array of strings. To insert values
to it, we can use an array literal - place the values in a comma-separated list,
inside curly braces
String[] cars = {"Volvo", "BMW", "Ford",
"Mazda"};
Slide 57
© Information Technology
Java Arrays…
Slide 58
© Information Technology
Java Arrays…
Slide 59
© Information Technology
Java Arrays…
Slide 60
© Information Technology
Java Arrays…
Array Length
• To find out how many elements an array has, use the length property
public class Example {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length); Output
} 4
}
Slide 61
© Information Technology
Java Arrays…
Multidimensional Arrays
• A multidimensional array is an array of arrays.
• To create a two-dimensional array, add each array within its own set of curly
braces
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6,
• Example 7} };
• myNumbers is now an array with two arrays as its elements.
• To access the elements of the myNumbers array, specify two indexes: one for
the array, and one for the element inside that array. The next example accesses
the third element (2) in the second array (1) of myNumbers:
Slide 64
© Information Technology
Java Arrays…
Multidimensional Arrays…
public class Example {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x);
} Output
} 7
Slide 65
© Information Technology