You are on page 1of 196

Tipe Data

Identifier

Declare and Inisialisasi

Operator

Selection (Percabangan)

Looping (Perulangan)

Fungsi Matematika, character dan String


Elementary
Programming
Numerical Data Types

Name Range Storage Size

byte –27 to 27 – 1 (-128 to 127) 8-bit signed

short –215 to 215 – 1 (-32768 to 32767) 16-bit signed

int –231 to 231 – 1 (-2147483648 to 2147483647) 32-bit signed

long –263 to 263 – 1 64-bit signed


(i.e., -9223372036854775808 to 9223372036854775807)

float Negative range: 32-bit IEEE 754


-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to -4.9E-324

Positive range:
4.9E-324 to 1.7976931348623157E+308
Numeric Type Conversion

Widening Casting (Otomatis)  byte – short – int – long – float – double


Narrowing Casting (Manual)  double – float – long – int – short – byte
Implicit casting
double d = 3; (type widening)

Explicit casting
int i = (int)3.0; (type
narrowing)
int i = (int)3.9; (Fraction part
is truncated)
double vs. float

The double type values are more accurate than the


float type values. For example,
System.out.println("1.0 / 3.0 is " + 1.0 / 3.0);

displays 1.0 / 3.0 is 0.3333333333333333

16 digits

System.out.println("1.0F / 3.0F is " + 1.0F / 3.0F);

displays 1.0F / 3.0F is 0.33333334


7 digits
Tipe Data Reference

Tipe data reference digunakan untuk menampung referensi Object


 Integer, Long, Float, Double, String, Array dll.
Primitif Reference
Diawali huruf kecil  int, long, float, double, Diawali huruf capital  Integer, Long, Float,
char Double, String
Kategori keyword Bukan keyword
Nilai default tergantung pada tipe data Nilai default = null
Menampung nilai/ value Menampung referensi object
Saat declare tanpa inisialisasi sudah Saat declare tidak dialokasikan ke memory.
dialokasikan ke memory baru ketika diinisialisasi dialokasikan ke memory
Identifiers
 Identify variable, method, class.
 An identifier is a sequence of characters that consist of letters, digits,
underscores (_), and dollar signs ($).
 An identifier must start with a letter, an underscore (_), or a dollar sign
($). It cannot start with a digit.
 An identifier cannot be a reserved word.
 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
 An identifier cannot be true, false, or null.
 An identifier can be of any length.
Declaring Variables

int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
Assignment Statements

int x; // Declare x to be an
// integer variable;
x = 1; // Assign 1 to x;
double radius; // Declare radius to
// be a double variable;
radius = 1.0; // Assign 1.0 to radius
char a; // Declare a to be a
// character variable;
a = 'A'; // Assign 'A' to a;
Declaring and Initializing
in One Step
int x = 1;
double d = 1.4;
Reading Input from the Console

 Create a Scanner object.


 Scanner input = new Scanner(System.in);
 Use the method nextDouble() to obtain to a double value.
For example,
 System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
Input Scanner

Methode Deskripsi
nextByte() Membaca nilai integer pada tipe byte
nextShort() Membaca nilai integer pada tipe short
nextInt() Membaca nilai integer pada tipe int
nextLong() Membaca nilai integer pada tipe long
nextFloat() Membaca nilai integer pada tipe float
nextDouble() Membaca nilai integer pada tipe
double
Numeric Operators

Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2
Precedence Operators
Precedence Operators
Augmented Assignment
Operators

area = radius * radius * 3.14;

Solution:
area = radius;
area *= radius;
area *= 3.14;
Increment and
Decrement Operators

What is the output?


int i = 2;
System.out.println(7 - ++i * 1.5 / 3 + 6 % 4 - ++i); 3.5
System.out.println(7 - i++ * 1.5 / 3 + 6 % 4 - ++i); 1.0
Increment and
Decrement Operators

int i = 10; Same effect as


int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as


int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;
Relational Operators

Java Mathematics Name Example Result


Operator Symbol (radius is 5)

< < less than radius < 0 false


<= ≤ less than or equal to radius <= 0 false
> > greater than radius > 0 true
>= ≥ greater than or equal to radius >= 0 true
== = equal to radius == 0 false
!= ≠ not equal to radius != 0 true
Logical Operators

Operator Name Description

! not logical negation

&& and logical conjunction

|| or logical disjunction

^ exclusive or logical exclusion


Switch-case
IF Else Switch-case
Lamda
• If
• If – Else
• If – Else if -
Else
One-way if Statements

if (boolean-expression) { if (radius >= 0) {


statement(s); area = radius * radius * PI;
} System.out.println("The area" + " for the
circle of radius " + radius + " is " + area);
}
Note for One-way if statements

if i > 0 { if (i > 0) {
System.out.println("i is positive"); System.out.println("i is positive");
} }
(a) Wrong (b) Correct

if (i > 0) { if (i > 0)
System.out.println("i is positive"); Equivalent System.out.println("i is positive");
}

(a) (b)
Two-way if Statements (if -
else)
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
if-else Example

if (radius >= 0) {
area = radius * radius * 3.14159;

System.out.println("The area for the “


+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}
Multiple Alternative if
Statements
Multiple Alternative if
Statements
Cara Penulisan yang dapat digunakan
if (score >= 90.0) if (score >= 90.0)
System.out.print("A"); System.out.print("A");
else else if (score >= 80.0)
if (score >= 80.0) Equivalent System.out.print("B");
System.out.print("B"); else if (score >= 70.0)
else System.out.print("C");
if (score >= 70.0) else if (score >= 60.0)
System.out.print("C"); System.out.print("D");
else else
if (score >= 60.0) System.out.print("F");
System.out.print("D"); This is better
else
System.out.print("F");

(a) (b)
Note

The else clause matches the most recent if clause in the same
block.
Note Next

Nothing is printed from the preceding statement. To force the else clause to
match the first if clause, you must add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
Common Errors
 Adding a semicolon at the end of an if clause is a common mistake.
if (radius >= 0);
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
 not a compilation or a runtime error, it is a logic error.
Note

Make it Shorter
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)
Conditional Expressions
switch Statements

switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(1);
}
switch Statements Flow Chart
switch Statement Rules

The value1, ..., and valueN switch (switch-expression) { The switch-expression must
must have the same data type yield a value of char, byte,
case value1: statement(s)1; short, or int type and must
as the value of the switch-
expression. The resulting break; always be enclosed in
parentheses.
statements in the case case value2: statement(s)2;
statement are executed when break;
the value in the case statement statement are

matches the value of the executed when
switch-expression. Note that case valueN: statement(s)N; the value in the
value1, ..., and valueN are break; case statement
constant expressions, meaning default: statement(s)-for-default; matches the
that they cannot contain value of the
variables in the expression, }
switchexpression.
such as 1 + x.
switch Statement Rules

switch (switch-expression) {
case value1: statement(s)1;
The keyword break is
break;
optional, but it should be
used at the end of each case value2: statement(s)2; The default case, which is
case in order to terminate break; optional, can be used to
the remainder of the perform actions when none
switch statement. If the …
of the specified cases
break statement is not case valueN: statement(s)N; matches the switch-
present, the next case
statement will be break; expression.
executed. default: statement(s)-for-default;
}
Conditional Expressions
Switch LAMDA Statements
Flow Chart
Switch LAMDA Statements
Example
Switch LAMDA Statements
Example in Methods
While

Do -
While

For
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s);
count++;
}
}
Ending a Loop with a Sentinel
Value
 You may use an input value to signify the end of the loop. Such a
value is known as a sentinel value.
double item = 1; double sum = 0;
while (item != 0) { // No guarantee item will be 0
sum += item;
item -= 0.1;
}
System.out.println(sum);
do-while Loop

do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
do-while Loop

do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);

Must end with


Terminator (;)
for Loops
for (initial-action; loop-continuation- int i;
condition; action-after-each- for (i = 0; i < 100; i++) {
iteration) { System.out.println( “
// loop body; Welcome to Java!");
Statement(s); }
}
Which Loop To use?

while (loop-continuation-condition) { Equivalent for ( ; loop-continuation-condition; )


// Loop body // Loop body
} }
(a) (b)

for (initial-action; initial-action;


loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
Nested Loops
Break and Continue
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;

while (number < 20) {


number++;
sum += number;
if (sum >= 100)
break;
}

System.out.println("The number is " + number);


System.out.println("The sum is " + sum);
}
}
Break and Continue
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;

while (number < 20) {


number++;
if (number == 10 || number == 11)
continue;
sum += number;
}

System.out.println("The sum is " + sum);


}
}
Math Class
Class Constans
Modifier dan Type Field Penggunaan
Static final double PI () Math.PI
Static final double E () Math.E
Static final double TAU () Math.TAU

• Field TAU baru dapat dipakai pada java versi 19.


• Contoh penggunaan PI

• https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/lang/Math.html
• https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/Math.html
Math Class
Method
 Membutuhkan nilai input dan menghasilkan output.
 Nilai input dan output berbeda.
 Macam-macam method yang dapat digunakan
◦ Trigonometri methods
◦ Exponen methods
◦ Rounding methods
◦ sqrt, abs, min, max, etc…
Character Data Type
Four hexadecimal digits.
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)

NOTE: The increment and decrement operators can also be used on char
variables to get the next or preceding Unicode character. For example, the
following statements display character b.
char ch = 'a';
System.out.println(++ch);
The String Type

The char type only represents one character. To represent a string of characters, use the
data type called String. For example,

String message = "Welcome to Java";

String type is not a primitive type but reference type.


Reference data types will be thoroughly discussed in “Objects and Classes.”
For this time you just need to know how to
declare a String variable,
assign a string to the variable,
concatenate strings, and
perform simple operations for strings.
String class
Komponen Methods

Deklarasi dan pemanggilan methods

Passing Parameter

Overloading Methods
 Base case
Recursion Methods  recursive
Methods
Method Component
A method is a collection of statements that are grouped together to perform
an operation.
Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}
Method

1 //Method tanpa return tanpa parameter 3 // Method tanpa return dengan parameter
public static void Halo(){ public static void IsiNama(String nama){
System.out.println("Halo Apa Kabar"); System.out.println("Nama : " + nama);
} }

// method dengan return tanpa parameter // method dengan return dengan parameter
2 4
public static double Hitung(){ public static double Hitung2(double Jari2){
double Luas = 0.0; double Luas2 = 0.0;
double Jari = 10.0; Luas2 = Math.PI * Jari2 * Jari2;
Luas = Math.PI * Jari * Jari; System.out.println("Luas Area Lingkaran : " + Lu
System.out.println("Luas Area Lingkaran : " +
Luas); return Luas2; }
return Luas; }
Calling Method

pass the value of i


pass the value of j

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
Method Void

 Method Void  tidak mengembalikan Nilai


 Void (hampa),  kosong, sehingga tidak perlu membuat sebuah nilai return didalam
method void. public static void main(String[] args){
Halo();
IsiNama(“Maemunah");
Hitung();
Hitung2(100.0);
Kosong/
}
Return 0;
//Method tanpa return tanpa parameter
public static void Halo(){
System.out.println("Halo Apa Kabar");
}
// Method tanpa return dengan parameter
public static void IsiNama(String nama){
System.out.println("Nama : " + nama);
}
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Suppose you invoke the method using
nPrintln(“Welcome to Java”, 5);
What is the output?

Suppose you invoke the method using


nPrintln(“Computer Science”, 15);
What is the output?

Can you invoke the method using


nPrintln(15, “Computer Science”);
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Suppose you invoke the method using
nPrintln(“Welcome to Java”, 5);
What is the output?

Suppose you invoke the method using


nPrintln(“Computer Science”, 15);
What is the output?

Can you invoke the method using


nPrintln(15, “Computer Science”);
Call Stacks

Call Stack adalah urutan pemanggilam method di dalam Java.


Pertama kali tentu saja method main.
Kemudian dari method main ini memanggil method lain lalu method lain
tersebut memanggil method yang lain lagi,
begitu seterusnya sehingga pemanggilan methodnya bertumpuk.
Setelah method selesai dieksekusi, activation record untuk method tersebut
akan dibuang dari call stack.
Call Stacks
Overloading Methods

 Overloading methods enable you to define the methods with the


same name as long as their parameter lists are different.
 Two ways to overload a method:
 Change the number of arguments
 Change the argument’s data type
Overloading Methods
Change data type arguments
Overloading Methods
Change return type
Overloading Methods

We can’t only change the


return type of the method
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}

public static double max(int num1, double num2) {


if (num1 > num2)
return num1;
else
return num2;
}

public static double max(double num1, int num2) {


if (num1 > num2)
return num1;
else
return num2;
}
}
Scope of Local Variables

A local variable: a variable defined inside a method.


Scope: the part of the program where the variable can be
referenced.
The scope of a local variable starts from its declaration and
continues to the end of the block that contains the variable.
A local variable must be declared before it can be used.
You can declare a local variable with the same name multiple
times in different non-nesting blocks in a method, but you
cannot declare a local variable twice in nested blocks.
Scope of Local Variables

It is fine to declare i in two It is wrong to declare i in


non-nesting blocks two nesting blocks

public static void method1() { public static void method2() {


int x = 1;
int y = 1; int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
x += i; for (int i = 1; i < 10; i++) {
} sum += i;
}
for (int i = 1; i < 10; i++) {
y += i; }
}
}
Scope of Local Variables

// With errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}
Method Composition

Suatu method besar dapat dipecah menjadi method-method kecil. Dengan


demikian, kita
dapat menggunakan suatu method sebagai bagian (komposisi) dari method lain.
Recursion: Base case + recursive
case
public static int faktor(int n){
if (n==0){
return 1; Base CASE
}
else{
return n * faktor(n-1); Recursive CASE
}
}
Be careful infinite recursion

 Check if there is
a base case
 Recursive call must move toward the base case
Tail Recursion

 A recursive
method is said to be tail recursive if there are no
pending operations to be performed on return from a recursive call.
Array One Dimension

Komponen Array

Create Array

• Accessing Index
Operation In Array •

Accessing Element of Array
Manipulating Element of Array

Two Dimensional Array

Searching and Sorting


Arrays
Introducing Arrays

 Array is a data structure that


represents a collection of the
same types of data.
 The values in an array are
called elements.
 Once an array is created, its
size is fixed.
An array reference variable is
used to access the elements in
an array using an index.
Declaring Array Variables

 datatype[] arrayRefVar;
Example:
double[] myList;

 datatype arrayRefVar[]; // This style is allowed, but not preferred


Example:
double myList[];
Creating Arrays

arrayRefVar = new datatype[arraySize];

Example:
myList = new double[10];

myList[0] references the first element in the array.


myList[9] references the last element in the array.
Declaring and Creating
in One Step
 datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];

 datatype arrayRefVar[] = new


datatype[arraySize];
double myList[] = new double[10];
Default Values

When an array is created, its elements are


assigned the default value of

0 for the numeric primitive data types,


'\u0000' for char types, and
false for boolean types.
null for reference types.
Creating Arrays with element in
one statement
int[] myInts = { 9, 1, 7, 7 };
Yang terjadi Error?

int[] myInts; int[] myInts = new int[]{9,1,7,7};


myInts = {9,1,7,7}; int[] myInts = new int [4];
myInts[0] = 9;
int myInts = [] myInts;
myInts[1] = 1;
new int[] {9,1,7,7}; myInts[2] = 7;
myInts[3] = 7;
Creating Arrays with element in
one statement
int[] myInts = { 9, 1, 7, 7 };
Yang terjadi Error?

int[] myInts; int[] myInts = new int[]{9,1,7,7}; OK


Error
myInts = {9,1,7,7}; int[] myInts = new int [4];
myInts[0] = 9;
int myInts = [] myInts;
OK myInts[1] = 1;
new int[] {9,1,7,7}; OK
myInts[2] = 7;
myInts[3] = 7;
The Length of an Array

Once an array is created, its size is fixed. It cannot be


changed. You can find its size using

arrayRefVar.length

For example,
myList = new double[10];
myList.length  returns 10
Accessing elements of Arrays

When creating an array of ints, the elements are initialized to zero.


elements

index
The [ ] operator selects elements from an array
What's the output of:
System.out.println(“The zeroth element is ”+myList[0]);
Manipulating array elements

What are the contents of array myList after executing the following
statements?
Manipulating array elements

What are the contents of array myList after executing the following
statements?
Output
Printing every element of an
arrays

for (int i = 0; i < 4; i++) {


System.out.print(myList[i] + " ");
}
Printing every element of an
arrays

for (int i = 0; i < 5; i++) {


System.out.print(myList[i] + " ");
}
Printing every element of an
arrays
Solution

for (int i = 0; i < myList.length; i++) {


System.out.print(myList[i] + " ");
}
Enhanced for Loop (for-each
loop)
General syntax is

for (elementType value: arrayRefVar) {


// Process the value
}
Example:
int[] myInts = new int[] Output
{9,1,7,7};
for(int element:myInts) {
System.out.println(element);
}
Enhanced for Loop (for-each
loop)
Foreach loop is best when:
- No need to manipulate array content.
- No need to use the indexes for something.

int[] myInts = new int[] Output


{9,1,7,7};
for(int element:myInts) {
System.out.println(element);
}
Displaying arrays

 Be careful when printing arrays:

Output
Displaying arrays

 Solution

 Class java.util.Arrays berisi method method static yang mendukung


manipulasi array, seperti perbandingan array, sorting, searching, dsb.
Copying arrays

Copying Array Or copying references? Have a look below:

Here's what really happens:

Saat mengcopy array maka yang dicopy bukan element


arraynya tapi adress/lokasi memorinya. (pass by
references). Be Carefull
Copying arrays

Ada tiga cara untuk menyalin isi suatu array ke dalam array lain supaya
hubungan kedua array saling lepas:

● Assign nilai setiap elemen arr2 dengan nilai dari arr1.


● Menggunakan Arrays.copyOf().
● Menggunakan System.arrayCopy().
Copying arrays

Copying Array Or copying references? Have a look below:

Output
Quiz time: Guess the output
Copying arrays : Guess the
output?
Fast way to Copy Arrays

 use copyOf to copy just part of an array.


Alternative copying arrays

int[] myInts = new int[]{9,1,7,7};


int[] copiedInts = new int[3];
System.arraycopy(myInts, 1, copiedInts, 0, 2);
System.out.println(Arrays.toString(copiedInts));

Parameters for System.arraycopy(sourceArr, What is the major difference


sourcePos, destArr, between
destPost, length): System.arraycopy(...)
- sourceArr: array to be copied from with Arrays.copyOf(...)?
- sourcePos: starting position in source
- destArr: array to be copied in
- destPos: starting position in destination
- length: length of array to be copied
Sorting arrays

int[] myInts = new int[]{9,1,7,7};


Arrays.sort(myInts);
System.out.println(Arrays.toString(myInts));
Filling arrays

int[] intArr = new int[3];


Arrays.fill(intArr, 100);
System.out.println(Arrays.toString(intArr));
Arrays.fill(intArr, 1, 3, 7);
System.out.println(Arrays.toString(intArr));
Check array content equality

int[] intArr = new int[3];


Arrays.fill(intArr, 100);
int[] intArrAnother = new int[3]; Membandingkan Alamatnya
Arrays.fill(intArrAnother, 100);
System.out.println(intArr == intArrAnother);
System.out.println(Arrays.equals(intArr, intArrAnother));

Membandingkan Value/nilai elementnya


Pass by Value

 Java uses pass by value to pass arguments to a method. There are


important differences between passing a value of variables of
primitive data types and passing arrays.
 For a parameter of a primitive type value, the actual value is passed.
Changing the value of the local parameter inside the method does
not affect the value of the variable outside the method.
 For a parameter of an array type, the value of the parameter
contains a reference to an array; this reference is passed to the
method. Any changes to the array that occur inside the method
body will affect the original array that was passed as the argument.
Enlarge array capacity

 You can't. What you can do is to copy your array to a larger array.
Method “main” pada main class

public class Test {


public static void main(String[] args){
//statements
}
} Elements dari array “args”
Tipe data berupa String

Pada method main, sebenarnya menampung argument-


argument dari args[0] – args[n]
Declare and Create Two-
dimensional Arrays
// Declare array ref var
dataType[][] refVar;

// Create array and assign its reference to variable


refVar = new dataType[10][10];

// Combine declaration and creation in one statement


dataType[][] refVar = new dataType[10][10];

// Alternative syntax
dataType refVar[][] = new dataType[10][10];
Declare and Create Two-
dimensional Arrays
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;

for (int i = 0; i < matrix.length; i++)


for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 1000);

double[][] x;
Declaring, Creating, and
Initializing Using Shorthand
Notations
You can also use an array initializer to declare, create and
initialize a two-dimensional array. For example,

int[][] array = int[][] array = new int[4][3];


{ array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{1, 2, 3}, Same as array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{4, 5, 6}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
{7, 8, 9},
{10, 11, 12}
};
Lengths of Two-dimensional
Arrays
int[][] x = new int[3][4];
Lengths of Two-dimensional
Arrays
int[][] array = { array.length
{1, 2, 3}, array[0].length
{4, 5, 6}, array[1].length
{7, 8, 9}, array[2].length
array[3].length
{10, 11, 12}
};

array[4].length ArrayIndexOutOfBoundsException
Classes and Instances/Objects

Have a class DesignHome and we can have


many instaces of house.
Object and Classes
• Objects in java defined by classes
• Classes define object with the same type
• Object must have unique identity, state, and behavior
• Class provides contructor, which are invoked when we construct
instance/new object of the class.

State : Area, Behavior:


radius
What are the Properties? perimeter What does it/they do?

The state of the Object The Behavior


Consist set of data fields/ variables define by method
Data Fields

• Circle (default/no-arguments)
Constructors • Circle(parameter) with arguments

Circle.java • getArea
Circle
Methods
radius: double
radius
Circle() This Keyword
Circle(newRadius: double)
getArea(): double a. Public c. Private
Modifier b. Protected d. Default

• Getter
Visibility Modifier • Setter

• Variables
Static dan Instance • Method
Object of Circle

Circle.java Circle Class is a Blueprint to construct Object


radius: double UML notation
radius for objects
Circle()
circle1: Circle circle2: Circle circle3: Circle
Circle(newRadius: double)
getArea(): double radius = 1.0 radius = 25 radius = 125

radius radius radius


Constructors
 A constructor with no parameters is referred to as a no-arg
constructor.
 a special kind of methods that are invoked to construct
objects.
 must have the same name as the class itself.
 do not have a return type—not even void.
Circle() {  invoked using the new operator when an object is created.
} Constructors play the role of initializing objects.

Circle(double newRadius) {
radius = newRadius;
}
Creating Objects Using
Constructors
new ClassName(); class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Construct a circle object */


Example: Circle() {
}
Constructors
new Circle(); /** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
new Circle(5.0); /** Return the area of this circle */
double getArea() { Method
return radius * radius * 3.14159;
}
}
Data Field and Methods

Data Field: class Circle {


/** The radius of this circle */
Identity/Properties of the double radius = 1.0; Data field

objects. /** Construct a circle object */


Circle() {
}
Methods: behaviors of the /** Construct a circle object */
Constructors

objects. Circle(double newRadius) {


radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}
Instance methods, Static
methods
 Instance methods are invoked by an instance of the class.
 Static methods are not tied to a specific object.

UML Class Diagram


Cube
color : String
length : double
numOfCubes: int
Cube()
Cube(color: String, length: double)
toString(): String
getVolume(): double Instance Method
getNumOfCubes(): int
Static Method
this Keyword
 this keyword refers to an object itself.
 One common use of the this keyword is reference a class’s data
fields.
class Circle{
double radius;
Circle(double radius) {
this.radius = radius;
}

double getArea(){
return Math.PI * this.radius * this.radius;
}
}
this Keyword
 Another common use of the this keyword is to enable a constructor
to invoke another constructor of the same class.

class Circle{
double radius;
Circle() {
this(0.0);
}

Circle(double radius){
this.radius=radius;
}
}
Declare and Initialization Object
Reference Variables
To reference an object, assign the object to a reference variable.

To declare a reference variable, use the syntax:

ClassName objectRefVar;
objectRefVar = new ClassName();

Example:
Circle myCircle;
myCircle = new Circle();
Declaring/Creating Objects
in a Single Step

ClassName objectRefVar = new ClassName();


Create an object
Assign object reference
Example:
Circle myCircle = new Circle();
Primitive Data Types Vs Object
Types
 Variabel dengan tipe data primitif menyimpan nilai data secara
langsung,
 sedangkan variabel dengan tipe data reference menyimpan alamat
penyimpanan objek tersebut di dalam heap memory.
Copying Variables of Primitive
Data Types and Object Types

 The object previously referenced by c1 is


no longer referenced (known as
garbage). Garbage is automatically
collected by JVM
Visibility modifiers

 Data fields inside a class are too "open".


 By default, they can be accessed by any class in the same package.
 We need information hiding: a way to control what can be accessed
from outside, and what cannot.

public class Time {


int hour;
int minute;
double second;
}
Visibility Modifiers

 public
The class, data, or method is visible to any class in any package.
 default (no modifier)
The data or method is visible to any class within a package.
 private
The data or methods can be accessed only by the declaring class.
 protected
The class, data, or method is visible to any its subclasses or any class
within a package.
TIP to Make OOP

 Defining a class creates a new object type.


 Every object belongs to a certain object type.
 A class definition is like a template for objects, it specifies:
 what attributes the objects have; and
 what methods can operate on them.
 The new operator creates new instances of a class.
 Think of a class like a blueprint for a house: you can use the
same blueprint to build any number of houses.
Abstraction
and
Encapsulation

Aggregation
And
Composition

Wrapper Class
Autoboxing
and Unboxing
Thinking
In Object
Class Abstraction and
Encapsulation
 Class abstraction means to separate class implementation from the use
of the class.
 The creator of the class provides a description of the class and let the
user know how the class can be used.
 The user of the class does not need to know how the class is
implemented.
 The detail of implementation is encapsulated and hidden from the user.
Class implementation Class Contract
is like a black box (Signatures of Clients use the
hidden from the clients
Class public methods and class through the
public constants) contract of the class
Object Composition

 Composition is actually a special case of the aggregation relationship.


 Aggregation models has-a relationships and represents an ownership
relationship between two objects.
 The owner object is called an aggregating object and its class an
aggregating class.
 The subject object is called an aggregated object and its class an
aggregated class.
Class Representation

An aggregation relationship is usually represented as a data field in


the aggregating class.

public class Name { public class Student { public class Address {


... private Name name; ...
} private Address address; }

...
}

Aggregated class Aggregating class Aggregated class


Aggregation Between Same
Class
Aggregation may exist between objects of the same class. For
example, a person may have a supervisor.
1
Person
Supervisor
1

public class Person {


// The type for the data is the class itself
private Person supervisor;
...
}
Aggregation Between Same
Class
What happens if a person has several supervisors?

1
Person
Supervisor
m

public class Person {


...
private Person[] supervisors;
}
Composition

Composition a special case from agregation


Car Machine

Composition : every car has an Machine

Car Passengers

Aggregation : car may have or not a Passengers


Wrapper Classes

NOTE:
(1) The wrapper classes do not
have no-arg constructors.
(2) The instances of all wrapper
classes are immutable, i.e., their
internal values cannot be changed
once the objects are created.

Why Wrapper Class is important?


Data structures in the Collection framework, such as ArrayList
and Vector, store only objects (reference types), not primitive
types.
Autoboxing and Unboxing

 Autoboxing: Automatic conversion of primitive types to the object of


their corresponding wrapper classes.

char ch = ‘a’;
Example 1 // Autoboxing- primitive to Character object conversion
Character a = ch;

ArrayList<Integer> arrayList = new ArrayList<Integer>();


Example 2 // Autoboxing because ArrayList stores only objects
arrayList.add(25);
Autoboxing and Unboxing

 Unboxing: Automatically converting an object of a wrapper class to its


corresponding primitive type.

Character ch = 'a';
Example 1 // unboxing - Character object to primitive conversion
char a = ch;

ArrayList<Integer> arrayList = new ArrayList<Integer>();


Example 2 arrayList.add(24);
// unboxing because get method returns an Integer object
int num = arrayList.get(0);
Automatic Conversion Between Primitive
Types and Wrapper Class Types

Equivalent
Integer[] intArray = {new Integer(2), Integer[] intArray = {2, 4, 3};
new Integer(4), new Integer(3)};

(a) New JDK 1.5 boxing (b)

Integer[] intArray = {1, 2, 3};


System.out.println(intArray[0] + intArray[1] + intArray[2]);

Unboxing
Java Built-in Classes
The String Class

Constructing Strings
String newString = new String(stringLiteral);
String message = new String("Welcome to Java");

Since strings are used frequently, Java provides a shorthand


initializer for creating a string:
String message = "Welcome to Java";
Strings Are Immutable

A String object is immutable; its contents cannot be changed.


Does the following code change the contents of the string?
String s = "Java";
s = "HTML";
After executing String s = "Java"; After executing s = "HTML";

s : String s : String This string object is


now unreferenced
String object for "Java" String object for "Java"

Contents cannot be changed : String

String object for "HTML"


Interned Strings (Java String
Pool)
 Since strings areimmutable and are frequently used, to
improve efficiency and save memory,
 the JVM uses a unique instance for string literals with the
same character sequence.
 Such an instance is called interned.
Interned Strings Example
String s1 = "Welcome to Java"; s1
: String
s3
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";

System.out.println("s1 == s2 is " + (s1 == s2)); s2 : String


System.out.println("s1 == s3 is " + (s1 == s3));
A string object for
"Welcome to Java"

Output  A new object is created if you use the


s1 == s is false new operator.
 If you use the string initializer, no new
s1 == s3 is true object is created if the interned object is
already created.
Superclass and Subclass

Super keyword

Constructor Chaining

Overriding Method
Inheritance
Superclasses and Subclasses
GeometricObject
-color: String The color of the object (default: white).
-filled: boolean Indicates whether the object is filled with a color (default: false).

Superclass = parent class / base class -dateCreated: java.util.Date


+GeometricObject()
The date when the object was created.
Creates a GeometricObject.
Subclass = derived class / extended +GeometricObject(color: String,
filled: boolean)
Creates a GeometricObject with the specified color and filled
values.
class / child class +getColor(): String Returns the color.
+setColor(color: String): void Sets a new color.
+isFilled(): boolean Returns the filled property.

Subclass memiliki hubungan IS-A +setFilled(filled: boolean): void


+getDateCreated(): java.util.Date
Sets a new filled property.
Returns the dateCreated.
dengan superclass. +toString(): String Returns a string representation of this object.

Setiap subclass mewarisi field -radius: double


Circle
-width: double
Rectangle

(atribut), method, dan nested class +Circle() -height: double

dari superclass. +Circle(radius: double)


+Circle(radius: double, color: String,
+Rectangle()
+Rectangle(width: double, height: double)
filled: boolean) +Rectangle(width: double, height: double
+getRadius(): double color: String, filled: boolean)
Yang tidak dapat diwariskan: +setRadius(radius: double): void +getWidth(): double
+setWidth(width: double): void
+getArea(): double
-. Constructor +getPerimeter(): double +getHeight(): double
+getDiameter(): double +setHeight(height: double): void
+printCircle(): void +getArea(): double
+getPerimeter(): double
Are superclass’s Constructor
Inherited?

SuperClass Y  Subclass Inherits all Properties and methods


 Unlike properties and methods, a superclass's constructors are
not inherited in the subclass.
 They can only be invoked from the subclasses' constructors,
SubClass X
using the keyword super.
 If the keyword super is not explicitly used, the superclass's no-
arg constructor is automatically invoked.
Using the Keyword super

The keyword super refers to the superclass of the class in


which super appears.

The keyword can be used in two ways:


 To call a superclass constructor
 To call a superclass method
Superclass’s Constructor Is
Always Invoked
 A constructor may invoke an overloaded constructor or its superclass’s
constructor.
 If none of them is invoked explicitly, the compiler puts super() as the first
statement in the constructor.

public A() { public A() {


is equivalent to
} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}
Using the Keyword super
Caution!
 You must use the keyword super to call the superclass
constructor.
 Invoking a superclass constructor’s name in a subclass causes
a syntax error.
 Java requires that the statement that uses the keyword super
appear first in the constructor.
Constructor Chaining

Constructing an instance of a class invokes all the superclasses’


constructors along the inheritance chain. This is known as constructor
chaining.

Konstruktor Berjenjang :
 subclass yang paling bawah akan memanggil konstruktor dari
superclass di atasnya.
 konstruktor superclass atas tersebut juga memanggil konstruktor
superclass lain yang lebih atas dan seterusnya.
Constructor Chaining

First Super Class is ‘Person’

class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor
is invoked");
}
}
Constructor Chaining
Second Class that extends from ‘Person’ class is Employee, the
Employee is Subclass from Person class.
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded
constructor");
System.out.println("(3) Employee's no-arg
constructor is invoked");
}

public Employee(String s) {
System.out.println(s);
}
}
Constructor Chaining

And the Employee have a sub class, the Faculty class.

public class Faculty extends Employee {


public static void main(String[] args) {
new Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor
is invoked");
}
}
Example on the Impact of a
Superclass without no-arg
Constructor
public class Apple extends Fruit {
}

class Fruit {
public Fruit(String name) {
System.out.println("Fruit's constructor is invoked");
}
}

Error karena Class Constructor dengan parameter di


Superclass harus di akses di class Child/ Sub class
Example on the Impact of a
Superclass without no-arg
Constructor
public class Apple extends Fruit {

} Add a constructor with a call to


super(“name”); here
class Fruit { Or Add a no-argument
constructor here
public Fruit(String name) {
System.out.println("Fruit's constructor is invoked");
}
}
Example on the Impact of a
Superclass without no-arg
Constructor Solution!
public class Apple extends Fruit {
public Apple(String name){
super(name);
}
}

class Fruit {
String name;
public Fruit(String name) {
this.name = name;
System.out.println("Fruit's constructor is invoked");
}
}
Defining a Subclass

A subclass inherits from a superclass. You can also:


 Add new properties
 Add new methods
 Override the methods of the superclass
Calling Superclass Methods

You could rewrite the printCircle() method in the Circle class

public void printCircle() {


System.out.println("The circle is created " +
super.getDateCreated() + " and the radius is " + radius);
}
Overriding Methods in the
Superclass
A subclass inherits methods from a superclass. Sometimes it is necessary for the
subclass to modify the implementation of a method defined in the superclass. This is
referred to as method overriding.
public class Circle extends GeometricObject {

/** Override the toString method defined in GeometricObject */


public String toString() {
return super.toString() + "\nradius is " + radius;
}
}
Overriding Methods in the
Superclass
public class GeometricObject {
private String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
}
}

How about if Like This? It’s Still Override?


public class Circle extends GeometricObject {
public String toString() {
return super.toString() + "\nradius is " + radius;
}
}
Overriding vs. Overloading
 Kunci dari Overriding “Jika kita ingin megubah fungsi dari method yang ada di Super
Class”. public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
A a = new A(); A a = new A();
a.p(10); a.p(10);
a.p(10.0); a.p(10.0);
} }
} }

class B { class B {
public void p(double i) { public void p(double i) {
System.out.println(i * 2); System.out.println(i * 2);
} }
} }

class A extends B { class A extends B {


// This method overrides the method in B // This method overloads the method in B
public void p(double i) { public void p(int i) {
System.out.println(i); System.out.println(i);
} }
} }
NOTE!

 An instance method can be overridden only if it is


accessible.
 Thus a private method cannot be overridden,
because it is not accessible outside its own class.
 If a method defined in a subclass is private in its
superclass, the two methods are completely
unrelated.
NOTE!

 Like an instance method, a static method can be


inherited.
 However, a static method cannot be overridden.
 If a static method defined in the superclass is
redefined in a subclass, the method defined in the
superclass is hidden.
The Object Class and Its
Methods
 Every class in Java is descended from the
java.lang.Object class.
 If no inheritance is specified when a class is
defined, the superclass of the class is Object.

public class Circle { public class Circle extends Object {


... Equivalent
...
} }
The toString() method in Object

 The toString() method returns a string representation of the object.


 The default implementation returns a string consisting of a class name
of which the object is an instance, the at sign (@), and a number
representing this object.
Loan loan = new Loan();
System.out.println(loan.toString());

 The code displays something like Loan@15037e5 . This message is


not very helpful or informative.
 Usually you should override the toString method so that it returns a
digestible string representation of the object.
Generic
Dynamic Binding
Programming

InstanceOf and
Casting Object
Equals Method

Visibility
Final Modifier
Modifier
Polymorphism
Polymorphism

 Polymorphism means that a variable of a supertype can refer to a


subtype object.
 A class defines a type. A type defined by a subclass is called a
subtype, and a type defined by its superclass is called a supertype.
Therefore, you can say that Circle is a subtype of GeometricObject
and GeometricObject is a supertype for Circle.
public class PolymorphismDemo {
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Object x) {
Method m takes a parameter of System.out.println(x.toString());
the Object type. You can }
}
invoke it with any object.
class GraduateStudent extends Student {
}

Polymorphism, class Student extends Person {


public String toString() {

Dynamic Binding }
}
return "Student";

and Generic class Person extends Object {

Programming
public String toString() {
return "Person";
}
}
Polymorphism

public class PolymorphismDemo {


public static void main(String[] args) { Method m takes a parameter
m(new GraduateStudent()); of the Object type. You can
m(new Student()); invoke it with any object.
m(new Person());
m(new Object()); An object of a subtype can be
} used wherever its supertype
public static void m(Object x) { value is required. This is
System.out.println(x.toString()); known as polymorphism
}
}
Dynamic Binding

public class PolymorphismDemo {


public static void main(String[] args) { When the method m(Object x)
m(new GraduateStudent()); is executed, the argument x’s
m(new Student()); toString method is invoked.
m(new Person());
m(new Object()); Which implementation is
} used will be determined
public static void m(Object x) { dynamically by JVM at
System.out.println(x.toString()); runtime. This is known as
} dynamic binding.
}
Dynamic Binding

 Dynamic binding works as follows: Suppose an object o is an instance


of classes C1, C2, ..., Cn-1, and Cn, where C1 is a subclass of C2, C2 is a
subclass of C3, ..., and Cn-1 is a subclass of Cn.
 That is, Cn is the most general class, and C1 is the most specific class.
 In Java, Cn is the Object class.
 If o invokes a method p, the JVM searches the implementation for the
method p in C1, C2, ..., Cn-1 and Cn, in this order, until it is found.
 Once an implementation is found, the search stops and the first-found
implementation is invoked.
Cn Cn-1 ..... C2 C1

Since o is an instance of C1, o is also an


Object instance of C2, C3, …, Cn-1, and Cn
Method Matching vs. Binding

 Matching a method signature and Binding a method


implementation are two issues.
 The compiler finds a matching method according to parameter
type, number of parameters, and order of the parameters at
compilation time.
 A method may be implemented in several subclasses.
 The Java Virtual Machine dynamically binds the implementation
of the method at runtime.
Generic Programming
public class PolymorphismDemo {  Polymorphism allows methods to be
public static void main(String[] args) {
m(new GraduateStudent()); used generically for a wide range of
m(new Student());
m(new Person()); object arguments.
m(new Object());  This is known as generic programming.
}
public static void m(Object x) {  If a method’s parameter type is a
System.out.println(x.toString()); superclass (e.g., Object), you may
}
} pass an object to this method of any of
class GraduateStudent extends Student { the parameter’s subclasses (e.g.,
} Student or String).
class Student extends Person {
public String toString() {
 When an object (e.g., a Student object
return "Student"; or a String object) is used in the
}
} method, the particular implementation
class Person extends Object { of the method of the object that is
public String toString() { invoked (e.g., toString) is determined
return "Person";
} dynamically.
}
Casting Objects
You have already used the casting operator to convert variables of one primitive
type to another. Casting can also be used to convert an object of one class type to
another within an inheritance hierarchy. In the preceding section, the statement
m(new Student());

assigns the object new Student() to a parameter of the Object type. This statement
is equivalent to:

Object o = new Student(); // Implicit casting


m(o);
The statement Object o = new Student(), known as implicit
casting, is legal because an instance of Student is
automatically an instance of Object.
Why Casting Is Necessary?

Suppose you want to assign the object reference o to a variable of


the Student type using the following statement:
Compile
Student b = o;
Error

 A compile error would occur. Why does the statement Object o = new
Student() work and the statement Student b = o doesn’t?
 This is because a Student object is always an instance of Object, but an
Object is not necessarily an instance of Student.
 Even though you can see that o is really a Student object, the compiler is not
so clever to know it.
Explisit Casting

To tell the compiler that o is a Student object, use an explicit casting.


The syntax is similar to the one used for casting among primitive data
types.
Enclose the target object type in parentheses and place it before the
object to be cast

Student b = (Student)o; // Explicit casting


Casting from
Superclass to Subclass
Explicit casting must be used when casting an object from a superclass to a
subclass. This type of casting may not always succeed.

Apple x = (Apple)fruit;

Orange x = (Orange)fruit;
The instanceof Operator

 Use the instanceof operator to test whether an object is an instance of


a class:
Object myObject = new Circle();
... // Some lines of code
/** Perform casting if myObject is an instance of Circle */
if (myObject instanceof Circle) {
System.out.println("The circle diameter is " +
((Circle)myObject).getDiameter());
...
}
Note

To help understand casting, you may also consider the


analogy of fruit, apple, and orange with the Fruit class
as the superclass for Apple and Orange.
An apple is a fruit, so you can always safely assign an
instance of Apple to a variable for Fruit.
However, a fruit is not necessarily an apple, so you
have to use explicit casting to assign an instance of
Fruit to a variable of Apple.
Polymorphism and Casting
Example
 This example creates two geometric objects: a circle, and a rectangle,
invokes the displayGeometricObject method to display the
objects.
 The displayGeometricObject displays the area and diameter if
the object is a circle, and displays area if the object is a rectangle.

https://
liveexample.pearsoncmg.com/html/Castin
gDemo.html
The equals Method
 The equals() method compares the contents of two objects.
 The default implementation of the equals method in the Object class.
public boolean equals(Object obj) {
return this == obj;
 The equals }method can be overridden For example, the equals
method is overridden in the Circle class.
public boolean equals(Object o) {
if (o instanceof Circle) {
return radius == ((Circle)o).radius;
}
else
return false;
}
NOTE (==)

 The == comparison operator is used for comparing two primitive


data type values or for determining whether two objects have the
same references.
 The equals method is intended to test whether two objects have the
same contents, provided that the method is modified in the defining
class of the objects.
 The == operator is stronger than the equals method, in that the ==
operator checks whether the two reference variables refer to the
same object.
Visibility Modifier ?
The protected Modifier

 The protected modifier can be applied on data and methods


in a class.
 A protected data or a protected method in a public class can be
accessed by any class in the same package or its subclasses,
even if the subclasses are in a different package.
private, default, protected, public

Visibility increases

private, none (if no modifier is used), protected, public


Comparison of Accessibility

Modifier Accessed Accessed Accessed Accessed


on members from the from the from a from a different
in a class same class same package subclass package

public

protected -

default - -

private - - -
Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }

package p2;

public class C3 public class C4 public class C5 {


extends C1 { extends C1 { C1 o = new C1();
can access x; can access x; can access o.x;
can access y; can access y; cannot access o.y;
can access z; cannot access z; cannot access o.z;
cannot access u; cannot access u; cannot access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }
Note

 A Subclass Cannot Weaken the Accessibility


 A subclass may override a protected method in its superclass and
change its visibility to public. However, a subclass cannot weaken
the accessibility of a method defined in the superclass.
 For example, if a method is defined as public in the superclass, it
must be defined as public in the subclass.
 The modifiers are used on classes and class members (data and
methods), except that the final modifier can also be used on local
variables in a method. A final local variable is a constant inside a
method.
The final Modifier
The final class cannot be extended:
final class Math {
... //statements
}

The final variable is a constant:

final static double PI = 3.14159;

The final method cannot be overridden by its subclasses.

You might also like