2 Overview Ofjava Programming
2 Overview Ofjava Programming
PROGRAMMING
Enterprise Application Development
Capital University of Science and Technology
(C.U.S.T)
Preview on JAVA
• Java is a full-fledged powerful language that can be
used in many ways. It comes in three editions:
• Java SE (client-side standalone applications or applets)
• Java EE (server-side applications, such as Java servlets
and Java Server Pages)
• Java ME (applications for mobile devices, such as cell
phones)
Why JAVA?
• Java enables users to develop and deploy applications on
the Internet for servers, desktop computers, and small
hand-held devices.
• The future of computing is being profoundly influenced by
the Internet, and Java promises to remain a big part of
that future.
Simplicity
Object-
Dynamic
Oriented
Multithreaded Distributed
JAVA
Performance Features Interpreted
Portable Robust
Architecture-
Secure
Neutral
JAVA Code Compilation
nt!
Primitive Java Data Types not
a n i
ClassName() { }
Input_output()
{
String name;
int age;
float cgpa;
char grade;
Output:
Exception in thread main java.lang.ArithmeticException by zero rest of the code...
Java Exception Classes Hierarchy
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
ArrayIndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
ArrayIndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
ArrayIndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
ArrayIndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
RuntimeException is caused by
programming errors, such as bad
casting, accessing an out-of-bounds
array, and numeric errors.
Handling Checked Exception using throws
Keyword
Throwing Exception
Use keyword throw to throw exception
throw ex;
throw Keyword – Example
class Test{
• Explanation:
In the above program, we are getting compile
time error because there is a chance of
exception if the main thread is going to sleep,
other threads get the chance to execute main()
method which will cause InterruptedException.
throws in Java
• Explanation:
In the above program, by using throws
keyword we handled the
InterruptedException and we will get the
output as Hello Geeks
throws in Java
Important points to remember about throws keyword:
try{
//statements;
}finally{
/*
Block of code that is always executed when
the try block is exited, no matter how the
try block is exited
*/
}
Multiple catch blocks with a Single try
block
try {
}catch(NullPointerException ex){
}catch(ArithmeticException ex){
}Catch(Exception ex){
}finally {
}
Multiple catch blocks Order
Never use the Super
try { class in the first catch.
This is Compile time
error.
}catch(Exception ex){
}catch(ArithmeticException ex){
}Catch(NullPointerException ex){
}finally {
}
Multiple catch blocks Order
try {
}catch(NullPointerException ex){
}finally {
}
Garbage Collection
• The object no longer referred to in the program is
known as garbage. Garbage is automatically
collected by JVM.
• TIP: If you know that an object is no longer needed,
you can explicitly assign null to a reference variable
for the object.
• The JVM will automatically collect the space if the
object is not referenced by any variable.
Garbage Collection – finalize ()
• The java.lang.Object.finalize() is called by the
garbage collector on an object when garbage
collection determines that there are no more
references to the object.
• A subclass overrides the finalize method to dispose
of system resources or to perform other cleanup.
• This method does not return a value.
• Throwable is the exception raised by this method
• Following is the declaration for
java.lang.Object.finalize() method
protected void finalize()
Example – finalize ()
import java.util.*;
class Test extends GregorianCalendar {
public static void main(String[] args) {
try { // create a new object
Test cal = new Test(); // print current time
System.out.println("" + cal.getTime()); // finalize cal
System.out.println("Finalizing...");
cal.finalize();
System.out.println("Finalized.");
} catch (Throwable ex) { ex.printStackTrace(); }
}
}
Relations – Types
Single
Multiple
Types of Relations
Inheritance Multi-Level
Hierarchal
Hybrid
Simple Association
Association Aggregation
Composition
Inheritance
Multi-Level
Inheritance
Single
Hierarchical
Multiple
Hybrid
Inheritance
Cont…
Output:
Capital…
CS_X001…
Example – Multiple Inheritance
Output:
Compile Time Error
Example – Multiple Inheritance
Output:
Multiple Inheritance
Example – Multilevel Inheritance
class Animal{
void eat(){System.out.println(“Eating...");}
}
class Cat extends Animal{
void Purr(){System.out.println(“Purring...");}
}
class Kitten extends Cat{
void sleepy(){System.out.println(“Sleeping...");}
}
class TestInheritance2{
public static void main(String args[]){
Kitten d=new Kitten(); Output:
d.sleepy(); Sleeping…
d.purr(); Purring…
d.eat(); Eating…
}}
Example – Hierarchal Inheritance
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark(); Error
}}
Take Home Message
// bank name
// employee name
Bank(String name) Employee(String name)
{ {
this.name = name; this.name = name;
} }
System.out.println(emp.getEmployeeName() +
" is an employee of " + bank.getBankName());
} Output:
} Zohaib is an employee of Alfalah
Aggregation
public class Subject {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName()
{
return name;
}
}
public class Student {
private Subject[] studyAreas = new Subject[10];
//the rest of the Student class
}
Composition
class Date class Employee
{ {
private int day, month, year; private int id;
private String name;
Date(int dd, int mm,int yy)
private Date hireDate; //object of Data class
{ Employee(int num,String n, Date hire)
System.out.println("Construct {
or of Data Called"); System.out.println("Constructor of Employee
day=dd; Called");
month=mm; id=num ;
year=yy; name=n ;
} hireDate=hire;
public String toString() }
public void display()
{
{
return System.out.println(“Id = "+id+“\n Name =
(day+"/"+month+"/"+year); "+name+“\nHiredate = "+hireDate);
} }
} }
Cont…
public class Composition
{
public static void main(String[] args)
{
Date d = new Date(01,01,2019);
Employee emp = new Employee(1,“Ahsan Javaid",d);
emp.display();
}
Output:
} Constructor of Data Class Called
Constructor of Employee Class Called
Id = 1
Name = Ahsan Javaid
Hiredate = 01/01/2019
Reading Assignment
• Differentiate between aggregation and composition?
• Also use a coding example to discuss the difference and
similarities between the two.
Polymorphism
• There are two types of polymorphism in Java:
• Compile-time polymorphism (static method dispatch):
• is a process in which a call to an overloading method is resolved at
compile time rather than at run time.
• In this process, we done overloading of methods is called through the
reference variable of a class here no need to superclass.
• Runtime polymorphism (Dynamic Method Dispatch):
• is a process in which a call to an overridden method is resolved at
runtime rather than compile-time
• In this process, an overridden method is called through the reference
variable of a superclass. The determination of the method to be called is
based on the object being referred to by the reference variable
Compile-time Polymorphism
Run-time Polymorphism
Output:
Overriden Second Method
Overriden First Method
Overriden Second Method
Abstract Methods
• A method that does not have an implementation
• Example:
• abstract void printStatus(); //no method body and abstract
Abstract Classes
Abstract Classes – Example
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println(“Running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output:
Running safely
Interfaces
• A blueprint of a class
• Contains static constants and abstract methods
• There can be only abstract methods in the Java interface,
not method body
• It is used to achieve abstraction and multiple inheritance
in Java
• Java Interface also represents the IS-A relationship
• It cannot be instantiated just like the abstract class
Interface – Example
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
Java Java
Java Applets
Applications Servlets