0% found this document useful (0 votes)
16 views

2 Overview Ofjava Programming

Uploaded by

Tayyaba Zaheer
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

2 Overview Ofjava Programming

Uploaded by

Tayyaba Zaheer
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 78

OVERVIEW OF JAVA

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

boolean • true or false

char • unicode! (16 bits)

byte • signed 8 bit integer

short • signed 16 bit integer

int • signed 32 bit integer

long • signed 64 bit integer

float, double • IEEE 754 floating point


Reserved Keywords
Class
• Classes are constructs that define objects of the same
type.

• A Java class uses variables to define data fields and


methods to define behaviors.

• Additionally, a class provides a special type of methods,


known as constructors, which are invoked to construct
objects from the class.
Objects
• An object has both a state and behavior. The state defines
the object, and the behavior defines what the object does.
Modifiers
• Java uses certain reserved words called modifiers that
specify the properties of the data, methods, and classes
and how they can be used.
• Examples of modifiers are public and static. Other
modifiers are private, final, abstract, and protected.
• A public datum, method, or class can be accessed by
other programs. A private datum or method cannot be
accessed outside the class of its declaration.
Constructors
• A class may be declared without constructors. In this
case, a no-arg constructor with an empty body is implicitly
declared in the class.

ClassName() { }

• This constructor, called a default constructor, is provided


automatically only if no constructors are explicitly declared
in the class.
package com.mycompany.input_output;
import java.util.Scanner;
public class Input_output {

Input_output()
{
String name;
int age;
float cgpa;
char grade;

Scanner scan = new Scanner (System.in);

System.out.print("Please Enter Name : ");


name = scan.nextLine();
System.out.println("Name With Spaces: " + name);

System.out.print("Please Enter Name Again: ");


name = scan.next();
System.out.println("Name Before Space: " + name);

Scanner scanAge = new Scanner (System.in);


System.out.print("Please Enter Age : ");
age = scanAge.nextInt();
System.out.println("Age: " + age);

Scanner scanCgpa = new Scanner (System.in);


System.out.print("Please Enter CGPA : ");
cgpa = scanCgpa.nextFloat();
System.out.println("CGPA: " + cgpa);

Scanner scanGrade = new Scanner (System.in);


System.out.print("Please Enter Grade : ");
grade = scanGrade.next().charAt(0);
System.out.println("Grade: " + grade);
}

public static void main(String[] args) {


//System.out.println("Hello World!");
Input_output in_out = new Input_output();
}
}
Classes & Objects – Class Activity
• Create a class titled “Circle” that contains:
• Data members
• Color (unspecified modifier)
• Radius (public)
• Diameter (private)
• Area (protected)
• Member functions
• Default Constructor that by default sets the color to white
• Public Calculate_Area () that stores and returns the calculated area of the circle
• Protected Calculate_Diameter () that stores and returns the calculated diameter of the
circle
• Public Set_Radius (int) that sets the value of the radius received
• Private Set_Color (string) that sets the color of the circle
• Create an instance of the class Circle, with the following properties:
• Color = Green
• Radius = User Entered Radius
• Calculated diameter and area
• Display the properties onto console
• Incase of an error: identify, correct it and justify it
Exception Handling
Keyword Description
try The "try" keyword is used to specify a block where we should
place exception code. The try block must be followed by either
catch or finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be


preceded by try block which means we can't use catch block
alone. It can be followed by finally block later.
finally The "finally" block is used to execute important code of the
program. It is executed whether an exception is handled or
not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't
throw an exception. It specifies that there may occur an
exception in the method. It is always used with method
signature.
Exception Handling - Example
public class JavaExceptionExample{
public static void main(String args[]){
try{ //code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

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

Many more classes


LinkageError

Error VirtualMachineError

Many more classes


Errors Classes
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
ArrayIndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError System errors are thrown by


JVM and represented in the
Error class. The Error class
Many more classes
describes internal system
errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying
the user and trying to terminate
the program gracefully.
Exception Classes
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
ArrayIndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError

Many more classes

Exception describes errors caused by


your program and external
circumstances. These errors can be
caught and handled by your program.
Runtime Exception Classes
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
ArrayIndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError

Many more classes

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

 Here is an syntax example,

 throw new TheException();


OR
 TheException ex = new TheException();

throw ex;
throw Keyword – Example
class Test{

void static demoMeth(){


try{
throw new NullPointerException(“demo”);
}catch(NullPointerException e){
System.out.println(“Caught: “+ e);
throw e;
}
}
public static void main(String args[]){
try{
demoMeth();
}catch(NullPointerException e){
System.out.println(“Recaught : “ + e);
}
}
}
Difference between throw and
throws

 throw is used to throw an exception explicitly

 A throws clause lists the types of checked


exceptions that a method might throw
throw and throws Keyword –
Example
class Test{

public static void meth() throws IllegalAccessException{


System.out.println(“Inside Meth”);
throw new IllegalAccessException(“Demo”);
}
public static void main(String args[]){
try{
meth();
}catch(IllegalAccessException e){
System.out.println(“Recaught : “ + e);
}
}
}

IllegalAccessException: A java.lang.IllegalAccessException is thrown when


one attempts to access a method or member that visibility qualifiers do not allow.
Typical examples are attempting to access private or protected methods or instance variables.
throw and throws in Java
• throw
• The throw keyword in Java is used to
explicitly throw an exception from a
method or any block of code. We can
throw either
checked or unchecked exception. The
throw keyword is mainly used to throw
custom exceptions.
• Syntax:
throw and throws in Java
• throw
• But this exception i.e., Instance must be of
type Throwable or a subclass of
Throwable. For example Exception is a
sub-class of Throwable and
user defined exceptions typically extend E
xception class
. Unlike C++, data types such as int, char,
floats or non-throwable classes cannot be
used as exceptions.
throw and throws in Java
• throw
• The flow of execution of the program stops
immediately after the throw statement is executed
and the nearest enclosing try block is checked to
see if it has a catch statement that matches the
type of exception.
• If it finds a match, controlled is transferred to that
statement
• otherwise next enclosing try block is checked and
so on.
• If no matching catch is found then the default
exception handler will halt the program.
throw in Java
throw in Java
throw and throws in Java
• throws
• throws is a keyword in Java which is used
in the signature of method to indicate that
this method might throw one of the listed
type exceptions. The caller to these
methods has to handle the exception
using a try-catch block.
• Syntax:
throw and throws in Java
• throws
• In a program, if there is a chance of rising an exception
then compiler always warn us about it and compulsorily
we should handle that checked exception, Otherwise we
will get compile time error saying unreported exception
XXX must be caught or declared to be thrown. To
prevent this compile time error we can handle the
exception in two ways:
1. By using try catch
2. By using throws keyword
• We can use throws keyword to delegate the
responsibility of exception handling to the caller (It may
be a method or JVM) then caller method is responsible to
handle that exception.
throws in Java

• 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:

• throws keyword is required only for checked


exception and usage of throws keyword for
unchecked exception is meaningless.
• throws keyword is required only to convince compiler
and usage of throws keyword does not prevent
abnormal termination of program.
• By the help of throws keyword we can provide
information to the caller of the method about the
exception.
The finally Keyword
 Occasionally, it is required to execute some part of
code regardless of whether an exception occurs or is
caught.
 finally clause is used to execute under all
circumstances regardless of whether an exception
occurs in the try block or is caught.
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
finally with try Block
 It is legal to use finally with try block

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){

}catch(ArithmeticException ex){ Always use the


Super class in the
last catch. This is
correct.
}Catch(Exception 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…

Not Supported in JAVA


Example – Single Inheritance

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

• Inheritance is a mechanism for defining new class types


to be a specialization or an augmentation of existing
types.

• In principle, every member of a base class is inherited by


a derived class with different access permissions, except
for the constructors
Association
//class employee
// class bank
class Employee
class Bank
{
{
private String name;
private String name;

// bank name
// employee name
Bank(String name) Employee(String name)
{ {
this.name = name; this.name = name;
} }

public String getBankName() public String getEmployeeName()


{ {
return this.name; return this.name;
} }
} }
Cont…
// Association between both the
// classes in main method
class Association
{
public static void main (String[] args)
{
Bank bank = new Bank(“Alfalah");
Employee emp = new Employee(“Zohaib");

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");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
} Output:
Hello
Reading Assignment
• Discuss the difference between Abstract Classes and
Interfaces. Also give an example differentiating the two
Java Database Connectivity (JDBC)
• JDBC is a Java API to connect and execute the query with the
database and is a part of JavaSE (Java Standard Edition)
• The JDBC library includes APIs for each of the tasks
mentioned below that are commonly associated with database
usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting record
Java Database Connectivity (JDBC)
• We can use JDBC API to access tabular data stored in any
relational database. By the help of JDBC API, we can save,
update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
• Why should we use JDBC?
• Before JDBC, ODBC API was the database API to connect and
execute the query with the database. But, ODBC API uses
ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its
own API (JDBC API) that uses JDBC drivers (written in Java
language).
Java Database Connectivity (JDBC)
Seven Steps for JDBC:
1. Import package  Java.sql
2. Load and register the driver com.mysql.jdbc.Driver
3. Create connection
4. Create statement
5. Execute the query
6. Process the result
7. Close the connection.
Applications of JDBC

Java Java
Java Applets
Applications Servlets

Java Server Enterprise


Pages JavaBeans
(JSPs) (EJBs).
Exceptions
• Exception handling is the process of responding to the
occurrence anomalous or exceptional situations –
requiring special processing – often changing the normal
flow of program execution
Integrated Development Environment
• An integrated development environment (IDE) is a software
application that provides comprehensive facilities to computer
programmers for software development.
• An IDE normally consists of: Source code editor and Debugger
• Some IDEs contain compiler, interpreter, or both, such as
Microsoft Visual Studio and Eclipse
• Besides JDK, you can use a Java development tool (e.g., Net-
Beans, Eclipse, and TextPad) — Software that provides an
integrated development environment (IDE) for rapidly
developing Java programs.
• Editing, compiling, building, debugging, and online help are
integrated in one graphical user interface. Just enter source
code in one window or open an existing file in a window, then
click a button, menu item, or function key to compile and run the
program.
IntelliJIDEA
Eclipse
NetBeans

You might also like