Review UTS Lengkap
Review UTS Lengkap
Review UTS Lengkap
Identifier
Operator
Selection (Percabangan)
Looping (Perulangan)
Positive range:
4.9E-324 to 1.7976931348623157E+308
Numeric Type Conversion
Explicit casting
int i = (int)3.0; (type
narrowing)
int i = (int)3.9; (Fraction part
is truncated)
double vs. float
16 digits
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
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
+ Addition 34 + 1 35
% Remainder 20 % 3 2
Precedence Operators
Precedence Operators
Augmented Assignment
Operators
Solution:
area = radius;
area *= radius;
area *= 3.14;
Increment and
Decrement Operators
|| or logical disjunction
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;
(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);
• 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,
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
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
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
// 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
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
datatype[] arrayRefVar;
Example:
double[] myList;
Example:
myList = new double[10];
arrayRefVar.length
For example,
myList = new double[10];
myList.length returns 10
Accessing elements of Arrays
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
Output
Displaying arrays
Solution
Ada tiga cara untuk menyalin isi suatu array ke dalam array lain supaya
hubungan kedua array saling lepas:
Output
Quiz time: Guess the output
Copying arrays : Guess the
output?
Fast way to Copy Arrays
You can't. What you can do is to copy your array to a larger array.
Method “main” pada main class
// 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;
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,
array[4].length ArrayIndexOutOfBoundsException
Classes and Instances/Objects
• 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(double newRadius) {
radius = newRadius;
}
Creating Objects Using
Constructors
new ClassName(); class Circle {
/** The radius of this circle */
double radius = 1.0; Data field
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.
ClassName objectRefVar;
objectRefVar = new ClassName();
Example:
Circle myCircle;
myCircle = new Circle();
Declaring/Creating Objects
in a Single Step
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
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
...
}
1
Person
Supervisor
m
Car Passengers
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.
char ch = ‘a’;
Example 1 // Autoboxing- primitive to Character object conversion
Character a = ch;
Character ch = 'a';
Example 1 // unboxing - Character object to primitive conversion
char a = ch;
Equivalent
Integer[] intArray = {new Integer(2), Integer[] intArray = {2, 4, 3};
new Integer(4), new Integer(3)};
Unboxing
Java Built-in Classes
The String Class
Constructing Strings
String newString = new String(stringLiteral);
String message = new String("Welcome to Java");
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).
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
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
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");
}
}
class Fruit {
String name;
public Fruit(String name) {
this.name = name;
System.out.println("Fruit's constructor is invoked");
}
}
Defining a Subclass
class B { class B {
public void p(double i) { public void p(double i) {
System.out.println(i * 2); System.out.println(i * 2);
} }
} }
InstanceOf and
Casting Object
Equals Method
Visibility
Final Modifier
Modifier
Polymorphism
Polymorphism
Dynamic Binding }
}
return "Student";
Programming
public String toString() {
return "Person";
}
}
Polymorphism
assigns the object new Student() to a parameter of the Object type. This statement
is equivalent to:
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
Apple x = (Apple)fruit;
Orange x = (Orange)fruit;
The instanceof Operator
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 (==)
Visibility increases
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;