Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 125

Fundamental of Java

TAN TIEN PING

Tan Tien Ping (Dr.), School of Computer Sciences, Universiti Sains Malaysia 1
Java
Java is a general purpose object-oriented program language.
It is first introduced in 1995 by Sun Microsystems.
Java moto: “Write once and run everywhere”
Characteristics of Java
◦ Fully object-oriented language.
◦ C++ like syntax.
◦ Compile codes to bytecodes, and use an interpreter to machine codes.
◦ Automatic memory management with garbage collector.

2
Why Java?
Easy to learn and write for beginners.
Standard and large libraries.
Compile once and run every where.
Supported in many platforms: Linux, Windows, MacOs, Android …
Can be used to write small program to very large application.
Big community of support.
Understanding the object oriented concepts in Java will make your journey of learning other
language easier: C++, C#, Python, VB.Net…
...

3
Top Programming Languages 2021

Refs: https://spectrum.ieee.org/computing/software/the-top-programming-languages-2019 4
Java
Virtual machine for
Windows (java)

Java code Java bytecode


(Program.java) Compiler (javac) (Program.class) Virtual machine for
Linux (java)

Virtual machine for


MacOsX (java)


5
1. What a particular keyword do?

Reserved Words 2. How to use it?

6
HelloWorld!

7
main Method
main() method is used to define self-standing program, the starting point of a program.

Optional arguments (only String) can be passed to an object through command line.

Curly braces “{ }” are used to group statements and to provide scope limit.

8
Others
Comments in Java:
// a single comment
/* comments that span
more than one line */

Annotations: a form of metadata, provide data about a program that is not part of the
program itself. Annotations have no direct effect on the operation of the code they
annotate. An annotation starts with the symbols ‘@’. Examples:
◦ @Override - Checks that the method is an override. Causes a compile error if the method is not
found in one of the parent classes or implemented interfaces.
◦ @Deprecated - Marks the method as obsolete. Causes a compile warning if the method is used.

9
Output to Screen
Use the print() methods in System.out class, to output to screen. Note: System
is a class. out is a static final variable of type PrintStream.

10
Input from Keyboard

11
Hands-on 1
Description: Run and compile a Java hello world program, HelloWorld.java using command line.
Skills
◦ Write a Java program with a text editor.
◦ Compile a program using command line.
◦ Execute a program using command line.
◦ Reading Java API documentation.

12
Hands-on 2
Description: Run and compile a Java hello world program, HelloWorld.java using Eclipse IDE.
Skill
◦ Setup a Java IDE.
◦ Understanding the features of a Java IDE.
◦ Write, compile and execute a Java program with an IDE.

13
Variables
A Java variable is a piece of memory that can store a value. A variable has a data type.
Variables in Java can be divided based on the type of value it can stored:
◦ primitive. e.g. int, char
◦ class. e.g. Object, String
◦ interface. e.g. Comparable
◦ array. e.g. int[], String[].

Variable in Java can also be divided based on “who” the variable is belong to. This is important in term of the scope of
the variables.
◦ instance variable (non-static): belongs to object
◦ class variable: belongs to class
◦ member variable consists of instance variable & class variables
◦ local variable: belongs to method
◦ parameter: variable passed to a method

14
public class MyClass{

int integerValue;
instance variable
String stringValue; member variables / fields / attributes
class/static variable static int classInteger;
parameter

public void myMethod(String sv){


String localStringVal = “an example”; local variable
stringValue = sv;
}

15
Variables
Variables in Java have to be declared (define the type) before it can be used.
Variable naming
◦ Case sensitive.
◦ Cannot be any of the reserved keyword.
◦ An unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$",
or the underscore character "_".

16
Class
A class is a blueprint or prototype from which objects are created.
Analogy: before you construct a building (object), you will design the detail blueprint first.

An object is created from a class that


contains different states, but all the objects
have the same behavior.
A class is defined using the class keyword.
A well defined class should only perform
functions/ do things, related to its definition.
objects

a class

17
Class
A class can derived from another class, therefore inheriting properties and methods of the parent.
All classes (except Object) in Java by default inherit from java.lang.Object.
Each class inherits from a single parent class.

18
Interface
Interface specifies a “standard” that a class can adopt/ implement.

A Bicycle class that


BicycleWheel interface
requires wheel that
implements the
BicycleWheel
standard/interface.

You can use different


type of wheel as you
wish!

RacingWheel class ColorWheel class BMXWheel class

19
Class and Interface
Multiple inheritance of type is supported through interface. Interface specifies the rules a class must
follow. Or in another word, interface is a specification.
For example, a bus (class) inherits from a vehicle (class). It can do all things a vehicle can do. To make
the bus to become a military bus, it just needs to follow the military rules. For instance, the rule that
requires all military tools painted in green. So, as long as it follows the rule, the bus is a military bus.

police siren vehicle


protection military code

police car military bus


20
Objects
A computer program is a collection of instructions that performs a specific task when executed
by a computer. 
Objects are important in OOP language because user uses objects to solve a task/problem.
For example, to solve a math problem, you use a mathematics objects.
A text editor may have different objects that handles different kind of tasks.
◦ Objects to keep the setting/values.
◦ Objects for checking grammars and spelling.
◦ Object to read a file.
◦ Object to write the content to a file.
◦ Object with a GUI.
◦ ...

21
Object
An object is an instance of a class.
Object: An object is a software bundle of related state and behavior. 
State: the features or values that define that object.
Behavior: the thing the object can do.
A person:
◦ state: name, age, height, weight, color ...
◦ behavior: talk, run, jump, learn ...

A calculator:
◦ state: number buttons, operator buttons (e.g. +, -, * ...), color, size
◦ behavior: add, minus, divide, equal, ...

The states of an object is kept in variables, and the behavior is accomplished through
methods/functions.

22
Object
An object may acquire certain functionality through its defined behavior or by using another
object.
◦ Example 1: to acquire the ability to fly, one can either has the fly behavior (e.g. bird, superman) or use
another object to allow it to fly (e.g. airplane).
◦ Example 2: to do a calculation, one can either know how to calculate, or he can just use a calculator.

Object is created through 3 steps


◦ declare the the type of the object for a variable.
◦ instantiate using the new keyword, and
◦ initialize the values of an object through constructor.

23
Constructor
Constructors are chunk of code used to initialize an object.
Constructors look like a method, it has no return type and it has the same name as the class.
All class must have at least one constructor, either explicitly declared in the class or implicit
default constructor.
If user does not provide any constructor in a class, Java will define a default constructor for the
class. Default constructor has zero argument, and empty.
If user has defined a constructor in a class, Java will not define a default constructor.
To invoke a constructor from another constructor in the same class, use the keyword this.

24
Package
Package is used to organize classes. For example:
◦ java.io contains classes that involves file input and output.
◦ java.lang package contains classes that are fundamental in Java programming language.

User can organize the codes using the package keyword.


Package statement is optional, but if user want to put his class in a package, he uses the package
keyword, and it MUST BE the first statement in the .java file.
By default, Java will load some default packages such as java.lang, package with no name and
current working package.
That’s why user/developer can use certain classes without explicitly asking Java to load it.
To use other than the default packages, use the import keyword. (more on this later)

25
Package
Some examples of packages in Java API.

26
Hands-on 3
Description: create a package and implement a class, instantiate an object
Skills:
◦ Using package keyword.
◦ Using class keyword.
◦ Declare and Instantiating an object using the new keyword.
◦ Understanding constructors.

27
Methods
Once you create an object, you may want to use it for something.
◦ To perform an action: accomplished through a method/function.
◦ To read or change the values/properties/states of an object: can be accomplished through a member variable or
method.

A method defines the thing an object can do.


Example definition of a method:
void methodName(String value){

}
Values can be passed to a method through the parameters. Objects are passed by reference and primitive
types are passed by value.
A variable can be returned by a method.

28
Methods
Inside the curly brackets, contains statements.
Variables can also be declared in a method. This variables are known as local variable. Local variable is
only visible inside the method.

After a method is defined, we can invoke the method in an object to perform an action.
For these, you use the dot operator. e.g. theObj.methodName().

Example: a FileWriter object, assume we name it as fw, it has a write() method that allow us to write text
to a file. To write “abc” to a file, we will just call fw.write(“abc”).
A class can have more than one methods with the same name, but their parameters must be different.
This is called method overloading.

29
Instance Variables and Methods

30
Declaring Member Variables and
Methods

31
Instantiating an Object

32
Hands-on 4
Description: methods and method overloading
Skills:
◦ Define a method
◦ Calling a method
◦ local variable
◦ member variable

33
Package and Import
As mentioned, Java will load some default packages for user to use. For other packages, user must explicitly
ask Java to load them, before the classes in the packages can be used.
For example, if user want to use input/output operation, user has to explicitly ask Java to load it, or else user
will not be able to compile it.
If user wants to load other packages, he has to use the import keyword. It must be the statement after
package.
Use the ‘*’ character to load all classes in a package.

If the packages are standard Java API, user just specify the package using import keyword.
If the packages are from other sources, user must specify the location of the sources.
◦ In terminal/command prompt, use classpath/jar in java and javac command.
◦ In IDE, set the project properties.

34
Hands-on 5
Description: importing packages/classes into a class.
Skills:
◦ import classes from standard Java packages.
◦ import external classes using an IDE.
◦ your own classes in other packages.
◦ other people classes.
◦ jar files.

35
Primitive Type
We already see in previous examples, class type variables or objects.
Even though it is possible to write a program using only objects in Java, Java has a data type
known as primitive type, specifically for handling numbers and characters.
Reason: efficiency in term of speed and also easier to use/read/write.
For object, we need to use the keyword new to create an object. But primitive types, you don’t.
Primitive types are elementary data types that are defined by Java language/ build-in. There are
8 types of primitive type.
Each primitive type has a particular type and certain range of values it can keep.
There are also some predefined operators that should be used with the primitive types.

36
Primitive Type
Type Size Range
boolean 1 bit true or false
byte 8 bits -128 .. 127
short 16 bits -32,768 .. 32,767
char 16 bits 16-bits Unicode characters (UTF-
16)
int 32 bits -2,147,483,648 .. 2,147,483,647
long 64 bits -9,223,372,036,854,775,808 ..
9,223,372,036,854,775,807
float 32 bits 3.40282347 x 1038, 1.40239846 x
10-45
1.7976931348623157 x 10308,
double 64 bits
4.9406564584124654 x 10-324

37
Expressions
Boolean value: true or false;
Integer: default int, others can be short, long.
floating point: default is double. So, to assign a float type, you must specify the number with f:
float pi = 3.142f;
Special character:

38
Operators for Primitive Types
higher Operators Precedence Primitive Types
postfix expr++ expr-- number
unary ++expr --expr +expr -expr ~ ! number
multiplicative */% number
additive +- number
shift << >> >>> number
relational < > <= >= instanceof number
equality == != number or boolean
bitwise AND & number
bitwise exclusive OR ^ number
bitwise inclusive OR | number
logical AND && boolean
logical OR || boolean
ternary ?: number or boolean
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=  
lower

Number: char, byte, short, int, long, float, and double

39
Operators
Arithmetic: Logical:
&& AND
|| OR
The && and || operators "short-circuit", meaning
they don't evaluate the right hand side if it isn't
necessary.
Increment and decrement: ++, -- Bitwise:

Relational:

Assignment: =

40
Declaration and Initialization

What happen if the variables verbose and debug are member variables? and what
happen if they are local variables.

41
Wrapper Type
There is a corresponding class for each primitive type.
If primitive types are more efficient and easier to read/write, why do we still want to use a wrapper type?

42
Wrapper Type: Boxing and Unboxing
(Java SE 5)
Boxing and unboxing is the implicit conversion of base primitive type and wrapper type.

Note: If you are using Java2/3/4,


statement 3 should be: int k = a.intValue();
statement 4 should be: int m = j + a+intValue();
statement 5 should be: a = new Integer(3*m);

43
Hands-on 6
Description: using primitive types and wrapper types
Skills:
◦ using primitive types variable
◦ operator and precedence
◦ using wrapper types variable
◦ boxing and unboxing

44
Access Modifier
In OOP, it is a good programming practice to restrict the access of variables and method in a class.
For instance, most of the member variables in a class should be declared as private. This is to
prevent unintentional changing the values/states of an object.
Access level modifiers determine whether other classes can use a particular member variable or
invoke a particular method.
There are 4 different levels of accessibility for members in Java
◦ public: a public member can be accessed from any class.
◦ protected: a protected member can be accessed in the same package or derived (subclass) from the current
class.
◦ no modifier/default: a default member can be accessed in the same class and package.
◦ private: a private member can be accessed only from within the same class.

45
Access Modifiers: Summary
The usage or public and private access modifier is quite clear. Rule of thumb:
Method:
◦ if a method in object A will be performing something for another object B, then the method in object A should be declared public. e.g. a matrix
object for doing addition of 2 matrix.
◦ if a method in object A will be doing some internal stuff that do not suppose to be used by other object, it should be declared private. e.g. a method
that calculate the partial of a formula.

Member variables
◦ Only final member variable should be declared as public.
◦ Other member variable should be declared private.

46
How to decide which access modifier to use in practice? The following is my experience in
general:
Method:
◦ if a method in object A will be performing something for another object B, then the method in object A
should be declared public. e.g. a matrix object for doing addition of 2 matrix.
◦ if a method in object A will be doing some internal stuff that do not suppose to be used by other object,
it should be declared private. e.g. a method that calculate the partial of a formula.

Member variables
◦ Only final member variable should be declared as public.
◦ Other member variable should be declared private.

47
Hands-on 7
Description: using access modifier
Skills:
◦ using public, protected, default and private modifiers.

48
Static Modifier
The static keyword can be used on a member variable and method, making them class variable and method.
What is the difference between class/static variable and a (non-static) member variable?
◦ Static variable belongs to the class not object. In another word, there is only ONE copy of the static variable, even
though you can have many objects of that class. Put it in another way, you have different objects of the same class
sharing the same static variable, any object change it, all objects will observed the changes. So, a static variable
behaves like a global variable.
◦ You call a static variable through the class not object.

When to use a static variable? You want the value of the variable to be accessible to all objects of that class.
When to use static method?
◦ Normally a programmer uses it to implement an ‘standalone’ method/function.
◦ Improve the readability of the code. static method can only use static member variables/method or local variables. You
cannot refer to a non-static members variables and method.
◦ Improve the efficiency of the code. Compiler will produce more efficient codes.

49
Static Modifier
Member variable/ method/ static initializer block is declared static.
◦ The variable and method belongs to the class not object. Therefore, they are called class variables and
class method respectively.
◦ Initialize only once.
◦ Only one copy of the variable exist.
◦ Static variable, method and block are initialized first before others.
◦ A classes static initialization normally happens immediately before the first time one of the following
events occurs:
◦ an instance of the class is created,
◦ a static method of the class is invoked,
◦ a static field of the class is assigned,
◦ a non-constant static field is used, or
◦ for a top-level class, an assert statement lexically nested within the class is executed.

50
Static Initializer Block
Static initializer block is an alternative to initializing member variables in the constructor.
The compiler will copy the codes in the static initializer block to constructor. This save you
some effort in writing the same initialization codes in the constructor.
We can have any number of static initializer block in a class.
It will be initialized according to the order of it in the code.

51
final Modifier
The final modifier is introduced to avoid the values of a variable from being changed once it is
initialized.
The final modifier is also used to avoid the codes in a method and class being modified by another
(child) class. Why? composition instead of inheritance, security...
Examples of final classes in Java: String, Integer, Boolean, Long, ...
A variable that is declared as final cannot be modified after it is assigned a value. In another word, it
is a constant.
A method that is declared final cannot be overwritten/modified by the child class (that inherit from
that class).
A class that is declared final cannot be extended/inherited by another class.
The naming convention use for a constant variable is using upper case letters.

52
Hands-on 8
Description: using static and final modifier
Skills:
◦ static variable
◦ static method
◦ final variable
◦ final method
◦ final class

53
String class
String class provides support to work with sequence of character.
String is a special class in Java. It has the feature of a primitive and a class.
String is immutable. A string object created cannot be modified.
String myStr1 = "Hello";
String myStr2 = "Hello"; This code snippet return true.
if (myStr1 == myStr2){ Note: “Hello” is an object. myStr1 and
System.out.println(“true”); myStr2 are references to the same object.
} else{ System.out.println(“false”);}

String myStr1 = new String("Hello”);


String myStr2 = new String("Hello”); This code snippet return false.
if (myStr1 == myStr2){ Note: 2 copies of “Hello” objects are
System.out.println(“true”); created. myStr1 and myStr2 are references
} else{ System.out.println(“false”);} to 2 different objects.

54
String class
For comparing the content (case sensitive) of two strings, use the method .equals().
Concatenation can be done using “+” operator. A new object is created.
String str1 = “over”;
String str2 = “load”;
String str3 = str1 + str2; //create a string object “overload”

A mutable String type also exist in Java, it’s call StringBuilder.

55
Other Methods in String
Other methods that you may use:
.indexOf()
.lastIndexOf()
.substring()
.toLower()
.toUpper()
.trim()

56
Hands-on 9
Description: using string objects
Skills:
◦ create an instance of string object
◦ comparing string
◦ and other string methods.

57
Array
Array: a sequence collection of variables of the same type.
Array in Java is a special type of object.
◦ One of the most use variable in an array is the .length that return the size of an array.
◦ Like any object, it has to be instantiated using the keyword new, if values are not assigned to it.
◦ We can create array of primitive type or class.

Element in the array starts from 0.


The square bracket is used to indicate a variable is an array:
type array-name[ ] = new type[size];
Declaring an array
◦ int[] counts;
◦ String names[];
◦ boolean[][] values;

58
Array
Creating an array
◦ int[] a = new int[5];
◦ String[] str = new String[3];
◦ boolean[][] values = new boolean[2][5]; //2 dimension array
◦ boolean[][] values = new boolean[2][]; values[0] = new int[8]; values[1] = new int[10]; //irregular array

Instantiating and assigning values to array


◦ int[] a = {1, 3, 5, 7, 9};
◦ String[] str = {“cat”, “dog”, “mouse”};
◦ String[] str = new String[3];
str[0]= new String(“cat”);
str[1]= new String(“dog”);
str[2]= new String(“mouse”);

59
Array
Refering an element in the array
◦ str[0];

Size of an array
◦ a.length; //a is an array
◦ str.length; //stry is an array

ArrayIndexOutOfBoundException: happens when you are refering to an element less than zero
or more than the length-1 of the array.

60
Hands-on 10
Description: using array
Skills:
◦ create an array
◦ accessing an element of an array

61
Enum Type
Enum is a special data type that allow you to define a list of related constants. You can see enum as a shortform.
◦ The class defined by default is inherited from java.lang.Enum.
◦ The variables declared using enum are final and static.

Examples of class and its constant variables that you can use enum:
◦ Direction class : NORTH, SOUTH, EAST, WEST
◦ Day class : MONDAY, TUESDAY, WEDNESDAY, ...]

Before the introduction of enum in Java5, we would declare the constant (member variables) as follows, and many still do:

public class Day{


public static int final MON = 0
public static int final TUE = 1,
public static int final WED = 2;
}

62
Enum Type
Using enum, we will declare the constant as follows:
public enum Day { MON, TUE, WED, THU, FRI, SAT, SUN};
Note that, in this example, we do not really care about the actual values assign to the constant
variables, as long as they are unique value.

The variables defined, can then be refer just like any static variable, e.g. Day.Fri.

63
Enum Type
We can also assign specific values to the constants using enum. You can see enum as the short
form for class and extends java.lang.Enum. Besides, the constructor is private.
public enum Day{

MON(2), TUE(3), WED(4), THU(5), FRI(6), SAT(7), SUN(1);

public final int value;


Day(int value){
this.value = value;
}

64
Hands-on 11
Description: using enum
Skills:
◦ create a list of constant using enum
◦ assign specific values to constants using enum

65
Flow Control
The flow control is one of the most essential components in any programming language. It consists of
◦ Conditional control statements: allow us to check the state, and make decision
◦ Loop statements: repeat the execution of certain codes.
◦ Branching: to transfer control to another point in the code

Conditional control:
◦ if...else
◦ ?:
◦ switch

Loop
◦ for
◦ while
◦ do ... while

66
Flow Control
Branching
◦ break, continue
◦ return

67
if... else
The if... else statement tells your program to execute a certain section of code only if a particular
test evaluates to true. If the first condition is false, the else statement provides a secondary path
of execution. 
If one of the condition is true, the rest of the condition will not be evaluated any more.
Note: short circuit in the Boolean expression.

68
switch
switch works with the byte, char, short, int, and their
respecitive wrapper classes, String or enum data type.

IMPORTANT: If no break after a case, it will fall through


to the next case.

69
Loops
Loop is used to repeat the execution of a block of statements.
There are 3 types of loops in Java
◦ for loop
◦ while loop
◦ do while loop

Given the 3 types of loop, which one should I use? Rule of thumb:
◦ Use for loop if the number of iteration is known.
◦ Use while loop if you need to repeat an unknown amount of time.
◦ Use do while loop if you need to repeat at least once.

Nevertheless, any of these 3 can be used for any problem related to looping. The only question
is how easy to use one compared to the others for a given problem.

70
for Loop
General for loop int[] numbers = {2, 4, 6, 8 10};
for (initialization; booleanCondition; increment) { //Before Java5,
loopBody
} for (int i=0; i<numbers.length; i++) {
int item = numbers[i];
Enhanced for loop
System.out.println(”Value is: " + item); }
for(initialization : array/iterator) {
loopBody
}
//Since Java5: Enhanced for loop
for (int item : numbers) {
System.out.println(”Value is: " + item); }

71
while loop

72
Branching
The 2 branching keywords are: break and continue.
A branching statement can be labelled. The label can be attached to for, while, break statement.
If no label is given, a break/continue statement will break/continue from the innermost switch/for/while loop.

label1: while(x){
label2: while(y){
if (z){
break label1;
} else{
continue lable2;
}
}

73
Assertions
One normally use if... else statements to check/verify the properties of an object to make sure it run
correctly.
Another way to test/check is using the keyword assert.
Assertion has 2 forms:
◦ assert expression1;
◦ assert expression1 : expression2 ;

where expression1 is a boolean expression, the condition that you want to evaluate. expression2 is a value, often it is a
error message you want to display
If the expression1 is evaluated to false, an AssertionError is thrown.

By default, assertion statements are disable at Runtime. To enable it, include the option –enableassertions
at the JVM.

74
Hands-on 12
Description: using if...else, switch, for loop, and while loop
Skills:
◦ if...else
◦ switch
◦ for loop
◦ while loop

75
Exception
Exception: Unexpected events that occur during the execution of a program. Examples:
◦ Input file cannot be found
◦ Accessing outside the boundary of an array
◦ Variable is not assigned any value
◦ …

The Throwable consists of 2 branches: Error class and Exception class.


Error subclasses consists of errors that fatal.
Java exceptions are objects that are instances of classes inherited from java.lang.Throwable.
Exception, 2 types
◦ unchecked exception: happens due to poor programming. All exceptions under RuntimeException.
◦ checked exception: happens due to condition cannot be meet.

76
Exception
When an exception happens and it is not being taken care of (catch), a program will terminate
unexpectedly, after printing some messages together with its runtime stack.
If an exception is caught, appropriate resolution can be carried out, and program can keep running.
This is done using try and catch with finally statements.
try statement is used to detect possible exception.
catch statement (optional) is used to handle the exception. Multiple catch is possible.
finally statement (optional) is used to always execute certain codes no matter what happen (unless
the program dies before it can execute it). The reason? to release resources for instance.

Method that throws checked exception must always be handled using try and catch statement, else
it must be re thrown.

77
Exception
Catching exception: Throwing exception:

public void method() throws ExceptionType{


public void method(){
try{ throw new ExceptionType();
//code block
} catch(ExceptionType varname1){ }
//optional code which can use varname1
} catch(ExceptionType varname2){ Implementing a custom exception:
//optional code which can use varname2
} finally { public class CustomException implements
//some codes here. java.lang.Exception {
}
}
}

78
Hands-on 13
Description: handling exception
Skills:
◦ unchecked exception/ RunTimeException
◦ check exception
◦ try, catch and finally
◦ throws and throw

79
Type Casting
Casting is the changes of the type of the variable. For example, changing of an integer value to
float value. Convert a String variable to the more general Object variable.
Casting can be done on variables of primitive types or class types.
Why casting?
◦ Mismatch of the type used between methods.
◦ Before Java5, casting is the only way for programmer to write generic method or class ~ that can handle
any type of object.
◦ sorting function
◦ Vector/list class allows programmer to put any type of object inside. We have to cast our object to Object and put it inside the
Vector, and cast it back to the original type when we retrieve it.

80
Type Casting in JDK1.4
You put a
variable of
type
Object

Ref: https://depinfo.u-bourgogne.fr/doc/j2sdk-1.4.3/api/index.html 81
Type Casting
Casting can be divided to: implicit casting and explicit casting.
Implicit casting is a widening type conversion.
◦ int to long
◦ int to double
◦ String to Object

Explicit casting is a forced type conversion, normally involved a narrowing type conversion.
◦ long to int
◦ Object to String

Primitive type casting:


byte to short, int, long, float, or double
Narrowing Widening

82
Type Casting
class type casting:
Child, Parent, Grand Parent, Great Grand Parent
Narrowing Widening

Implicit casting in primitive type are guarantee to preserve the value after conversion. But not
explicit casting (when the type you are casting exceed the upper/lower limit of that type).
Explicit casting have to be done correctly or else one will get invalid values or an exception
(ClassCastException) will be raised for class type casting.
For example, casting an Integer to String or vice versa.

83
Type Casting
Explicit Casting:

Implicit Casting:

More: System.out.println(4.5 + “ value”); //compile error


System.out.println(“value ” + 4.5); //ok!

84
Hands-on 14
Description: casting of primitive type and references
Skills:
◦ primitive type casting
◦ class type casting

85
Generic Type
A generic type is a generic class or interface that is parameterized over types. 

class name<T1, T2, ..., Tn> {

//some codes inside

86
Generic Type
If we want to define a class to store 2 objects that are unknown, we can use Generic type.
Prior to the Introduction of Generic type in Java5, the codes are written as below:

87
Generic Type
What is the “problem” with this approach?

ObjectPair op = new ObjectPair(new String(“ORCL”), new Double(32.07));


String myStr = (String) op.getFirst();
Double myDbl = (Double) op.getSecond();

88
Generic Class
Using Java Generic type:

89
Generic Class
Instantiating a Generic type, 2 ways:

No need for explicit casting using Generic

90
Generic Method

91
Hands-on 15
Description: generic
Skills:
◦ generic class
◦ generic method

92
Inheritance in Java
Inheritance in Java is done using extends and implements keyword.
Inheritance is used a lot in design pattern.
A class can extend from a concrete class or an abstract class.
Each class can only have one parent class, except java.lang.Object.
All class by default extends from java.lang.Object.
A class inherits fields and methods from all its superclasses, whether direct or indirect.
A subclass may override methods that it inherits by having the same method name and parameters as the
parent..

public class ChildClass extends ParentClass{

93
Abstract Class
Abstract class is defined using the abstract keyword.
A class must be declared as abstract if it has abstract methods or it does not implement any one
method in an interface that it derived from.
Abstract method is method without a body/implementation.
Abstract class cannot be instantiated.

public abstract class ChildClass extends ParentClass{

//an abstract method


public abstract void method();

94
Reference: Head First Design Patterns 95
96
Interface
Interface allows programmer to define a “contract” or ”rule” that a class must follow, if a class
implements that interface.
Interface is defined using interface keyword.
Interface simply contains the signatures of methods (without body) and/or constants.
A look at the definition of interface does not seems to provide any specific functionality in
programming.
But the fact is, interface is very important in object oriented programming

public interface Vehicle{


//signature of a method
public void move();
}

97
Interface
The (signature of the) methods specified in an interface, force any class that implement the
interface to write codes for the methods.

public class Proton implements Vehicle{ public class Honda implements Vehicle{ public interface Vehicle{
//signature of a method
public void move(){ public void move(){ public void move();
// do something here... // do something here... }
} }
}
public void myothermehtod(){
}
}

98
Interface and Type Casting
We can cast any object to its interface (that the class implements). See example below
Proton p = new Proton();
Vehicle c = p; //implicit casting
Proton p2 = (Proton) c; //explict casting

We can also write like this:


Vehicle v = new Proton();

The power of an interface lies on the ability to cast it.

99
Interface
The power of an interface lies on the ability to cast it.

For example, I can write a ToyCar program, that can move any car, as long as the car implements
the interface.
public class ToyCar{

public void moveTheCar(Vehicle v){


//some codes
v.move();
}

public void moveAllCars(){


moveTheCar(new Honda());
moveTheCar(new Proton());
}
}

100
Interface
Imagine another scenario, you are asked by your boss to write a NEW search algorithm for a list.
The name of the method is mySearch(list). How to do it? You can implement the whole
algorithm, including the list class.

class List{

public List(){
class MyAlgo{
….
}
public Node mySearch(List l){
….
public void add(Node n){
}

}
}

}

101
Interface
But WAIT, why you want to implement the list class if you can use existing LinkedList class in Java
API? Can save you hours to spend on movie and popcorn instead.
OK, you decide to use LinkedList class. So, the codes will be …
class List{
import java.util.LinkedList;
public List(){
class MyAlgo{ ….
}
public <E> mySearch(LinkedList l){
…. public void add(Node n){
} …
} }

}

102
Interface
Tomorrow, your boss told you he want to search Vector import java.util.LinkedList;
and Stack also. So, how to do it? import java.util.Stack;
import java.util.Vector;

class MyAlgo{

public <E> mySearch(LinkedList l){


….
}

public <E> mySearch(Vector v){



}

public <E> mySearch(Stack s){



}
Is this right? }

103
Interface
No, the best way is.. import java.util.List;
class MyAlgo{

public <E> mySearch(List l){


….
}

Notice that, List is not a concrete class, it is an interface. But still we can pass Vector, LinkedList,
Stack objects … to your mySearch method because the List interface defines the “requirement”
for all ”general” list object, which is add(), remove(), isEmpty(), contains() that are available in
ALL these classes! So, by using List type, all classes that implement List can use your search
algorithm.

104
105
Interface in Java8
Since Java8, programmer can implement default method and static method in an interface.
Meaning the method will contains body, not just signature. Blurring the different of it compared
with abstract class.
public interface Vehicle{
//signature of a method
public void move();

public default void turnLeft(){


//some codes
}

public default void turnRight(){


//some codes
}
}

106
Hands-on 16
Description: inheritance
Skills:
◦ extends
◦ abstract class
◦ abstract method
◦ implements

107
Nested Class
Nested class is a class defined inside another class.
Why using a nested class
◦ The nested class is only used in the outer class.
◦ The nested class can access to all the member variables or methods in the outer class.
◦ Improve the readability of the codes, since all the codes are together in a file.

Normally only used to define “small” classes.


class OuterClass {

class NestedClass {
//do something
}

108
Anonymous (Inner) class
Anonymous class does not have a name.
Anonymous classes are expressions.
◦ They are inside another class.
◦ Use the keyword new.
◦ Must implement an interface/extend another class.

They enable you to declare, implement and instantiate a class, all at the same time.
It is often used in GUI, where the anonymous classes are generated by the IDE, (user has to implement it), and the class
is only used once. For example, generating an anonymous class to handle event for a button.
EventHandler eh = new EventHandler<ActionEvent>() { @Override public void
handle(ActionEvent event) { System.out.println("Hello World!");

When to use it?


◦ When you have a class that you want to inherit from and make some small changes to it.
◦ When you are creating a GUI using drag and drop.

109
Lambda Expressions
A Java lambda expression is a method which can be created without belonging to any class.
A lambda expression allows codes to be passed to another method and executed on demand.
Simplify the implementation of a class even further than anonymous class, especially for
implementing (functional) interface with only a single abstract method.
public interface MinString{ ConcreteMinString c = new ConcreteMinString();
boolean flag = c.compare(x, y);
public boolean compare(String a, String b);
replacing 1 statement to replace 5 statements.
}

public class ConcreteMinString implements MinString{ Lambda expression:

public boolean compare(String a, String b){ match parameters (String x, String y) -> x.length < y.length;
return a.length < b.length;
} match return type
} 110
Hands-on 18
Description: anonymous class
Skills:
◦ Writing and using anonymous class

111
Commonly Used Classes in Java SDK
Input/output classes are used for reading and writing to file: Reader and Writer
Use queue classes for storing and accessing objects in first in first out manner: java.util.Vector,
java.util.ArrayList
Use a Hash table to map one object to another: java.util.HashMap, java.util.Hashtable. For
example, assign a unique id for each student in a class.

112
Hands-on 19
Description: commonly used classes in Java SDK
Skills:
◦ Input/Output
◦ Vector, ArrayList
◦ Hashtable and HashMap

113
Thread
Wikipedia: “In computer science, a thread of execution is the smallest sequence of programmed
instructions that can be managed independently by a scheduler, which is typically a part of the 
operating system.[1] The implementation of threads and processes differs between operating
systems, but in most cases a thread is a component of a process. Multiple threads can exist
within one process, executing concurrently and sharing resources such as memory, while
different processes do not share these resources. In particular, the threads of a process share its
executable code and the values of its variables at any given time.”

114
Hardware Thread

115
Multithreading in Java
Although the CPU can do only one thing at a time, the OS accomplishes multitasking by
switching its attention rapidly between different programs/applications.
In a program, multiple processes exists at a time. e.g. in a browser, text, images are loaded
simultaneously. This is accomplished through multithreading.
It is very easy to use thread in Java compared to C/C++, which requires programmer to use
platform specific tools.
In Java multithreaded environment, many separate threads can access the Java Virtual Machine
objects and resources. Programmer need to make sure the threads do not interfere with each
other.
The number of (software) threads that one can create in Java is more than the (hardware)
thread specified in the processor.

116
The Thread Class
4 states of a thread: new, runnable, blocked and dead.

New

Ready Sleeping
Waiting
Blocked IO
Running
Blocked
Runnable

Dead

117
To execute an object as a thread.
◦ The class must implements Runnable. The Runnable interface has only a method.

public void run()

◦ Starting a thread. Make sure everything is setup before calling start() method.

Thread t = new Thread(RunnableClass);


t.start();

◦ Death of a thread: when it exit the run() method. A dead thread cannot be restarted

A thread can be set its priority through the setPriority() method.

118
Programmer responsibility to avoid deadlocks.
It is possible that an object is halfway modified by a thread and halted, and another thread
access that object. To avoid this situation, every object has an internal lock variable that JVM can
manipulate.
If a thread acquire a lock of an object, then another thread is blocked until the lock is released,
then only it can acquired it.
Using/checking the lock takes additional time. Thus, JVM will not use it by default as it affect the
efficiency of the codes.
In situation where an object may be accessed by more than a thread at a particular time,
programmer has to use the keyword synchronized to indicate the block of codes need to be
locked.

119
2 ways to synchronized:
◦ method: use the synchronized keyword on the declaration of a method.

public synchronized void myMethod(){


//do something
}

◦ statement: use the synchronized keyword at a statement.


Object lockObject;

synchronized(lockObject){
//do something
}

120
Constructor cannot be synchronized, because only thread that create an object has access to
that the constructor.
Synchronized on the data that you want to protect.
Do not synchronized local variables (in method) but member variables because every thread has
its own copy of local variables.

121
Important static methods in Thread:
◦ sleep: the executing thread that call the method will be put to sleep for some amount of time.
◦ yield: suspends the operation of the current thread and allows the scheduler to choose another
runnable Thread to execute.

For coordinating threads that beyond the capability of synchronized, use the method wait(),
notify(), and join(). For example, certain thing that must be done in certain order.
◦ wait(): the thread will be put into block state, any lock that it has will be released.
◦ notify(): the thread that being notify will be in runnable state. If more than one thread is waiting, we
cannot know which one will be notified.
◦ join(): the thread that call the join() of another thread will wait for that thread to die before proceeding.

122
Hands-on 20
Description: thread
Skills:
◦ Create thread
◦ Using synchronized keyword

123
Achievement
We have discussed the fundamental features in Java programming language.
By mastering the fundamental, you will be able to do anything with Java (Provided that you
know the actual step/logic of the problem you are going to solve).

IMPORTANT:
◦ Always refer to Java SDK if you require to use some standard API.
◦ Check out other external API if you need some other functionalities not provide by Java SDK.

◦ ...

124
What’s Next
To improve your coding ability
◦ More practice
◦ Learn Java design pattern

Learn creating GUI


Learn web application
Learn android application

125

You might also like