Java Ppt 1947
Java Ppt 1947
Shanmugapriya.V
History of Java
• Java was created in 1991
• The original language was called Oak. In honor of the tree outside
Gosling’s window, its name was changed to java because there was
already a language called Oak.
2
The Architecture
3
Application and Runtime Environment
• The JRE of the SDK contains the complete set of class files for all
the Java technology packages, which includes basic language
classes, GUI component classes, and so on.
4
Application and Runtime Environment
• J2SE includes the essential compiler, tools, runtimes, and APIs for writing,
deploying, and running applets and applications in the Java programming
language.
• JDK is the short-cut name for the set of Java development tools, consisting
of the API classes, a Java compiler, and the Java virtual machine
interpreter, regardless of which version.
• The JDK is used to compile Java applications and applets. The most current
version is the JSE is 6.0
5
Compile time and Runtime Environment
6
Java Run Time Environment
7
Java Features
– Garbage Collection
8
The Java Virtual Machine
9
The Java Virtual Machine
10
Garbage Collection
• Garbage collection thread is responsible for freeing any memory that can
be freed. This happens automatically during the lifetime of the Java
program.
11
Phases of a Java Program
12
Java source
code
(.java)
Bytecodes
(.class)
13
Integrated Development Environments
NetBeans
JDeveloper
Eclipse
14
Java language syntax
Objectives
Identify the basic parts of a Java program
Develop a simple valid Java program using the concepts learned in this
chapter
16
Program structure
• A program in Java consists of one or more class definitions
• One of these classes must define a method main(), which is where the
program starts running
There can be More than one Class Definition in a class ,but only one
public class
17
Example 1.1
package com.training;
18
Example 1.1 (contd)
package com.training;
System.out.println(grtObj.getMessage());
19
The System Class
• Its part of the java.lang package
• The classes in this package are available without the need for an import
statement
• It can’t be Instantiated
20
Comments
– /* multi
line
comment
*/
– /** a
* Javadoc
* comment
*/
21
Variables and Methods
• Variable is a kind of special container that can only hold objects of a certain
type.
22
Instance Variables and Methods
• Variables and methods can be associated either with objects or their
classes
23
Example for Variables
public class VariableTypes {
Instance
Variable
private int inst_empid;
private static String cls_DeptName
Class
Variable
public void getData() { }
public static void getSalary() { }
Parameter
Variable
public void showData(int a)
{ Local
int localVariable ; Variable
}
}
24
Identifiers
• Identifiers are used to name variables, methods, classes and
interfaces
• Identifiers
– start with an alphabetic character
– can contain letters, digits,$ or “_”
– are unlimited in length
• Examples
– answer, total, last_total, relativePoint, gridElement, person, place, stack,
queue
25
Initialization
• Local variables
– must be explicitly initialized before use
• Parameter variables
– Pass by value
26
Local Variable needs to Be Initialized
public class LocalVariable {
private String name;
public void display() Age Should be
Initialized
{
before Use
int age;
System.out.println("Age"+age);
System.out.println
System.out.println("Name"+name);
27
Instance Variable have Default Values
class Values
{
private int a;
private float b;
private String c;
public void display()
{
System.out.println("integer"+a);
System.out.println("float"+b);
System.out.println("String"+c);
}
public class DefaultVales {
x 7
Hello
y 7
s 0x01234
t 0x01234
29
Pass-by-Value
• The Java programming language only passes arguments by value
for primitive data types.
30
Casting Primitive Types
• Casting creates a new value and allows it to be treated as a
different type than its source
• Byte -> short -> int -> long -> float -> double
31
Casting Primitive Types
public class PrimCasting {
33
Wrapping Primitives
• Wrapping a value
– int i = 288
– Integer iwrap = new Integer(i);
• unWrapping a value
– int unwrapped = iwrap.intValue();
34
Wrapper Class Method
Convert String to Numbers
public class ParsingStrings
{
public static void main(String args[])
{
int ino=Integer.parseInt(args[0]);
floatfno = Float.parseFloat(args[1]);
double dno = Double.parseDouble(args[2]);
Long lno = Long.parseLong(args[3]);
35
Auto Boxing
• Java 5.0 provided autoboxing
36
Auto Boxing
public class ABoxing {
Integer a = 10;
Float b =20f;
abObj.show(a,b);
}
}
37
Command Line Arguments
class CommandLineArgs
{
public static void main(String args[])
{
System.out.println("hello, welcome to the java world
"+args[0]+" to all "+args[1]);
38
java.util.Scanner Class
• A simple text scanner which can parse primitive types and strings using
regular expressions.
• A Scanner breaks its input into tokens using a delimiter pattern, which by
default matches whitespace.
• The resulting tokens may then be converted into values of different types
using the various next methods.
39
java.util.Scanner Class
40
java.util.Scanner Class
public static void main(String[] args) {
String
line="Java,is,in,OOP,Language";
sc1.useDelimiter(",");
while (sc1.hasNext())
{
System.out.println(sc1.next());
}
}
41
Flow Control
Objectives
43
Control Structures
• if -- else , if – else if
• switch -- case
• while
• do -- while
• for
44
Decision Control Structures
• Types:
– if-statement
– if-else-statement
– If-else if-statement
if( boolean_expression )
statement;
or
if( boolean_expression ){
statement1;
statement2;
}
• boolean_expression : can be an expression or variable.
45
if-else statement
if( boolean_exp ){
if(boolean_exp1 )
Statement(s)
statement1;
}
else if(boolean_exp2)
else {
statement2;
Statement(s)
else
}
statement3;
46
switch-statement
• If none of the cases are satisfied, the optional default block if present
is executed.
switch( switch_expression ){
case case_selector1:
Statement(s);
break;
case case_selector2:
Statement(s);
break;
default:
statement1;
}
47
switch-statement
– jumps to the case whose selector matches the value of the expression.
48
switch-statement
public double CalculateDiscount(int pCode)
{
double discountPercentage=0.0d;
switch(pCode)
{
case 1:
discountPercentage=0.10d;
break;
case 2:
discountPercentage=0.15d;
break;
case 3:
discountPercentage=0.20d;
break;
default:
discountPercentage=0.0;
}
return discountPercentage;
}
49
Switch-Case in a Method
• Can have Either Return or Break if present inside a
Method, but should provide a default Value
50
Repetition Control Structures
• while-loop
– The statements inside the while loop are executed as long as the
Boolean expression evaluates to true
• do-while loop
51
for-loop
• Same code a number of times.
• for(Initialexpr;LoopCondition;StepExpr) {
statement1;
}
• InitialExpression -initializes the loop variable.
• LoopCondition - compares the loop variable to some limit
value.
• StepExpr - updates the loop variable.
for( ; ; ) {
System.out.println("Inside an endless loop");
}
• Declaration parts are left out so the for loop will
act like an endless loop.
52
Enhanced For Loop
• The enhanced for loop, simplifies looping through an array or a collection.
• Instead of having three components, the enhanced for has two.
• declaration
– The newly declared block variable, of a type compatible with the
elements of the array being accessed.
• expression
– This must evaluate to the array you want to loop through. This could be
an array variable or a method call that returns an array
• int [] a = {1,2,3,4};
• for(int n : a)
• System.out.print(n);.
53
Branching Statements
• Branching statements allows to redirect the flow of program
execution.
– break
– continue
– return.
54
Branching Statement
• continue
• Unlabeled
– skips to the end of the innermost loop's body and evaluates the
Boolean expression that controls the loop,
– skipping the remainder of this iteration of the loop.
• Labeled :
– skips the current iteration of an outer loop marked with the given label.
• return
– Used to exit from the current Method
– Control returns to the statement that follows original method call
– The value to be returned is included after the “return” statement.
– The data value returned by return must match the type of the method's
declared return value
55
Continue
public static void main(String[] args) {
for(int i=0;i<=2;i++)
{
for(int j=0;j<=3;j++)
{
I ,0,J 1
I ,0,J 3
I ,1,J 1
if(j % 2==0)
I ,1,J 3
continue; I ,2,J 1
System.out.println("I ,"+i+",J "+j); I ,2,J 3
}
}
56
break
public static void main(String[] args) {
for(int i=0;i<=2;i++)
{
for(int j=0;j<=5;j++)
0,0
{
0,1
0,2
System.out.println(i+","+j); 0,3
1,0
if(j==3)
1,1
break; 1,2
1,3
2,0
}
2,1
} 2,2
2,3
57
Arrays
Introduction to Arrays
59
Creating Arrays
• declaring
– int[] k;
– float[] yt;
– String[] names;
• allocating
– k = new int[3];
– yt = new float[7];
– names = new String[50];
• initializing
60
Array Bounds
• All array subscripts begin with 0 and ends with n-1
• In order to get the number of elements in an array, can use the
length field of an array.
61
Array of Objects
public class Book
{
private int bookno;
private String bookname;
public Book(int bookno,String bookname)
{
this.bookno=bookno;
this.bookname=bookname;
}
public int getBookno()
{
return this.bookno;
}
public String getBookname()
{
return this.bookname;
}
}
62
Array of Objects
public class ArrayofObject {
63
Classes
Classes
65
Classes
Top-level classes can be declared as
– public
• a public class is globally accessible.
• a single source file can have only one public class or interface
– abstract
• an abstract class cannot be instantiated
– final
• a final class cannot be subclassed
– Default
• With any Modifier
• They can’t be declared as protected and private
66
Constructors
• Have no return type
• Have the same name as the class
• If we don't’ put a constructor the compiler puts a default one
– The default constructor has the same access modifier as the class.
– The default constructor has no arguments.
– The default constructor is always a no-arg constructor, but a no-arg
constructor is not necessarily the default constructor
– The default constructor includes a no-arg call to the super constructor
(super()).
• They are not inherited and hence they are not overridden
• It can be Overloaded
• It can have any of the Four Access Modifies
• It cannot be synchronized
• It can have throws clause
67
Instantiation with new
• It is the process by which individual objects are created.
• Declaration
– Employee empObj;
• Instantiation
– empObj = new Employee()
68
Constructor Overloading
• One constructor can call another overloaded constructor of the same class
by using this keyword.
• The call to this() can be used only in a constructor ,and must be the first
statement in a constructor
• A constructor can call its super class constructor by using the super
keyword.
69
Overloaded Constructor
class Time Time.java
{
private int hour,min,sec;
// Constructor
Time()
{
hour = 0;
min = 0;
sec = 0;
}
//Overloaded constructor
Time(int h, int m, int s)
{
hour = h;
min = m;
sec = s;
}
}
// Code continues …
70
this keyword
• Is a reference to the object from which the method was
invoked
this keyword
71
Modifiers for declarations
• There are Four Access Level and 3 Modifiers
• Any declaration can be preceded by
– public
• a declaration is accessible by any class
– protected
• Accessible by any class in the same package as its class, and
accessible only by subclasses of its class in other packages.
• Works just like default , Except it also allows subclasses
outside the package to inherit the protected thing.
– default(no modifier)
• Only accessible by classes, including subclasses, in the same
package as its class(package accessibility).
– private
• a declaration is only accessible within the class in which it is
declared
72
Method Overloading
• If two (or more) methods of a class have the same name but different
signatures, then the method name is said to be overloaded.
• The signature of a method consists of the name of the method and the
number and types of formal parameters in particular order.
• Several methods that implement similar behavior but for different data
types.
• They are independent methods of a class and can call each other just like
any other method.
73
Overloading Methods
• Overloaded methods MUST change the argument list.
74
Overloading and AutoBoxing
public class Overloading {
return c+100;
}
System.out.println(olObj.add(45, 55));
76
Static Variables and Methods
• A static method belongs to a class and not to its instance objects and
hence they are shared between Objects
• Static Methods can not be overridden
• They can only call other static methods
• They can access only static variables and not instance Variables
• They cannot refer to this or super
• Instance variable : 1 per instance and Static variable : 1 per class
• Static final variables are constants
• main( ) is defined to be a static method so as to be invoked directly
77
Static Method access only static
public class StatClass {
78
Static block
StaticExample.java
class StaticExample{
static{
a = 9;
b = 5;
}
// Other statements
}
79
Static Import
import java.util.*;
import static java.lang.System.out;
import static java.lang.System.in;
int x = kb.nextInt();
out.print("Enter a double ");
double d = kb.nextDouble();
out.println("The sum is " + (x+d));
}
}
80
INHERITANCE
Overview
– A class can inherit from another class
• Original class is the “superclass”
• New class is called the “subclass”
•Inheritance is a fundamental OO concept
Superclass
Car
Subclasses
SportsCar Taxi PoliceCar
82
Example of Inheritance
Car
– Taxi extends Car, and can:
• Add new variables
• Add new methods
Taxi
• Override methods of the Car class
83
Specifying Inheritance in Java
– Inheritance is achieved by specifying which superclass the
subclass
“extends”
•Taxi inherits all the variables and methods of Car
84
Aspects of Inheritance
– Objects
• What does a subclass object look like?
– Construction
• How do constructors work now?
– Methods
• What methods can be called?
• How can methods be overridden?
85
What Does an Object Look Like?
A subclass inherits all the instance variables of its
superclass
Car object
public class Car {
regNum
String regNum;
engineSize
int engineSize; …
}
Taxi object
regNum
public class Taxi extends Car {
engineSize
private int cabNum; …
} cabNum
86
Default Initialization
Taxi object
regNum
Taxi taxi1 = new Taxi(); engineSize
87
Nondefault Initialization
88
Specifying Additional Methods
89
Overriding Superclass Methods
– A subclass inherits all the methods of its superclass
– The subclass can override a method with a specialized
version, if it needs to:
91
Overriding
class Base extends keyword
{
protected int a;
base()
{
a = 20;
}
void display()
{
System.out.print(“a = “+a);
}
}
class Derived extends Base
{
private int b;
derived()
{
b = 25;
}
void display()
{
System.out.print(“b = “+b);
}
}
92
Overriding –When Method Has Exceptions
• Any exceptions declared in overriding method must be of the same type as
those thrown by the super class, or a subclass of that type.
class MyBase {
class Base
{
private int i = 5;
94
Invoking Superclass Methods
– If a subclass overrides a method, it can still call the original
superclass method
96
Hiding-Fields and Static Members
• A Sub Class can hide the fields but cannot override that of the super class,
its done by defining fields with the same name as in the super class.
• Code in the subclass can use the keyword super to access such members
• A static method can hide a static method from the Super Class
• A hidden super class static method is not inherited., will result in compile
time Exception
97
Hiding-Fields and Static Members
Variable
class MyBase class Mysub extends MyBase Method
Hiding
{ { Hiding
int var1=100 ; int var1 =200;
99
Defining Abstract Classes in Java
– Use the abstract keyword to declare a method as abstract
• Only provide the method signature
• Class must also be abstract
– Must be implemented by a concrete subclass
• Each concrete subclass can implement the method differently
System.out.println("Thanks-Come Again");
}
101
Child Class –Its alsoAbstract
102
The Concrete Class
public class Supersavings extends Savingaccount {
float balance,amount ;
String custname;
int accno;
public void deposit(float amt)
{
balance+=amt;
}
public void withdraw(float amt)
{
balance-=amt;
}
public void getClientdetails()
{
System.out.println(custname);
System.out.println(accno);
System.out.println(amount);
System.out.println(balance);
}
}
103
Interfaces & Polymorphism
Interfaces
– An interface is like a fully abstract class
• All of its methods are public and abstract
• No instance variables if present they are public static final
– An interface defines a set of methods that other classes can
implement
• A class can implement many interfaces, but can extend only one
class
105
Interface
• Interfaces define types in an abstract form
– An interface declaration allows the specification of a reference type
without providing an implementation
– The class that implements the interface decides how to implement
implements keyword
// the interface
interface Sort
{
void do_sort();
}
// the implementor
class BubbleSort implements Sort
{
public void do_sort()
{
// The sorting method implementation
}
}
106
Example of Interfaces
– Interfaces describe an aspect of behavior that different classes
can support
– For example, any class that supports the “Steerable” interface can
be steered:
107
Defining an Interface in Java
108
Implementing an Interface
109
Partial Implementation of an Interface
• Declare the class as abstract if the class does not implement all
the methods of an interface
110
Interface
• A single class can implement many interfaces
implements keyword
interface Sort{
void doSort();
}
interface List{
void createList();
}
111
Using instanceof with Interfaces
– The instanceof operator can be used to check if an object
implements an interface
– Downcasting can be used if necessary, to call methods defined in
the interface
113
Polymorphism
• This OO Principle allows the programmer to program abstractly
114
Polymorphism
• Types of Polymorphism -
– Method Overloading.
– Method Overriding.
115
Polymorphism
class SuperClass
{
int value = 100;
void callMe()
{
System.out.println("I am in Super Class");
}
}
void callMe()
{
System.out.println("I am in Sub Class");
}
}
116
Polymorphism
This Object Reference is
public class TestDMD polymorphic
{
public static void main(String s[])
{
objSuperClass.callMe();
System.out.println(objSuperClass.value);
}
• This means object variables are polymorphic , A variable of type Super
Class can refer to an object of type Super class as well as subclass .
117
Substitution of Object References in Method
Calls
•A subclass object can be passed into any method that expects a
superclass object
•The method that got invoked, is the version that's present in the
object type and NOT the reference type.
• superclass = subclass
– always valid
• subclass=(subclass)superclass
– valid at compile time, checked at runtime. if is invalid then the exception
ClassCastException is thrown.
• subclass = superclass
– not valid at compile time, needs a cast
• someClass = someUnrelatedClass
– not valid, won’t compile
• somcClass = (someClass)someUnrelatedClass
– not valid, won’t compile
119
subclass=
(subclass)sup
Dynamic Method Dispatch erclass
Valid at both
class First Compile ,Run
{ Time
First fst = new Second();
public void show()
{
Second sec = (Second)fst;
System.out.println("ShowFirst");
}
} sec.show();
122
Interface, Abstract Class,Subclass,Class
• A plain class is designed when in doesn't pass the “is-a” test.
• A Plain class is designed when its not extending any other class
other than object class
123
Packages
Packages
125
Package
• In the following example, the class class1 is part of the package pack1
• Use the javac -d option to compile
package keyword
package utility;
// indicates that class Sort is part of Utility package
class Sort
{
public void do_sort()
{
// Statements
}
}
126
Package
• Use the import keyword to access the classes in a package
import keyword
import utility.*;
class Test
{
public static void main(String args[]){
Sort obj1;
// Code continues …
127
CLASSPATH
• Is an environment variable which specifies the location of the
class files
• For compiling the Sort.java (listed earlier)
– javac -d c:\packages Sort.java
– this would create a sub-directory Utility under c:\packages and
store Sort.class over there
• While compiling test.java (listed earlier), set
– CLASSPATH = . ; c:\packages
• Any package can be included in the working package
• Include all packages in CLASSPATH
• import package_name.class_name;
• import package_name.subpackage_name.class_name;
• import package_name.*;
128
Package - Access modifiers
129
Creating And Running Executable Jar Files
• Java .jar files are archive files, like .zip files, that can contain a collection of
Java artifacts including class files, source code, supporting documentation,
etc.
• They can be executed by adding a manifest to the .jar file that specifies the
name of the main application class.
• Steps involved in Creating a Executable Jar files
– Create Java program/(s) and save the resulting .class files in the proper
package structure
130
Create An Executable Jar File
• The Files can be executed by invoking java command with the -jar switch :
131
Object Class and Its Methods
Object Class
• Every class in java extends class Object.
• If a class doesn’t explicitly extend any class ,implicitly extends Object class
– boolean equals()
– int hashCode()
– String toString()
– Object.clone()
133
equals( ) method
• The equals operator (==) can be used to test primitives
134
Rules for an equals( ) method
• It is reflexive:
• x.equals(x) must be true.
• It is symmetrical:
• x.equals(y) must be true if and only if y.equals(x) is also true.
• It is transitive:
• if x.equals(y) is true and y.equals(z) is true, then x.equals(z) must
also be true.
• It is repeatable:
• multiple calls on x.equals(y) return the same value (unless state
values used in the comparison are changed, as by calling a set
method).
• It is cautious:
• x.equals(null) must return false rather than accidentally throwing a
NullPointerException .
135
Overriding Equals Methods
public boolean equals(Object otherObject)
{
// check objects are identical
if(this==otherObject)
return true ;
//check for null
if(otherObject==null)
return false;
// check for the class of the object
if(getClass()!=otherObject.getClass())
return false;
// cast the object to the right type
Exampleobject eobj =
(Exampleobject)otherObject;
//check the instance variables
return customername.equals(eobj.customername)
&& orderno==(eobj.orderno);
}
136
The hashCode( ) method
• It returns an integer that should uniquely identify different objects.
• It is repeatable:
– hashCode(x) must return the same int when called repeatedly, unless
set methods have been called.
137
Overriding HashCode
• Acceptable Overriding but not Efficent
138
toString( )
• The objectS can be passed to
– System.out.println( )
– Methods
– Or Can be used string concatenation,
• Java automatically calls its toString( ) method.
• The toString() just prints the class name, an @ sign, and the object's
memory address -hashCode) value
• toString( ) implementation prints the state of the object which will result in
formatting control in println( ) and anywhere objects get referred to in a
String context.
139
Object.clone( )
• Need for cloning
– While method-calling ,the called method can modify the state of
constructed object!
• Cloning the input object before calling the method allows to pass a copy of
the object, keeping the original safe.
140
Clone Method
public class Employee implements Cloneable {
return super.clone( );
}
catch (CloneNotSupportedException e )
{
e.printStackTrace();
}
}
}
141
GC of Object
• Objects become eligible for garbage collection
– Reference goes out of permanently
void add()
{
Employee e = new Employee();
}
142
f a shallow copy is performed on obj1, then it is copied but its contained objects are not
Shallow Clone
• f a shallow copy is performed on obj1, then it is copied
but not its contained objects.
143
Deep Clone
• A deep copy occurs when an object is copied along with the objects to
which it refers.
• Each object is responsible for cloning itself via its clone() method.
144
GC of Object
– The Reference is explicitly set to null
Class EmpTest {
Employee e = new Employee();
void add()
{
e=null;
}
145
Finalize Method()
public class Book {
String bookName;
Book(String bookName)
{
this.bookName=bookName;
}
public String toString()
{
return this.bookName;
}
public void finalize()
{
System.out.println("Inside Finlize“+this);
}
146
Finalize Method()
public static void main(String[] args) {
System.out.println(textbook);
System.gc();
System.out.println(textbook);
textbook=null;
System.gc();
System.out.println(textbook);
}
147
Math Class
• The methods in the Math class don’t use any instance variable values
• The Methods are “static” methods , and they don’t need to have an instance
of the Math class
148
Exception handling
149
Topics
• Define exceptions
• Use try, catch, and finally statements
• Describe exception categories
• Identify common exceptions
• Develop programs to handle your own exceptions
• Use assertions
• Distinguish appropriate and inappropriate uses of assertions
• Enable assertions at runtime
150
Exception and Assertions
• Exceptions handle unexpected situations – Illegal argument,
network failure, or file not found
151
Exceptions
• Conditions that can readily occur in a correct program are checked
exceptions.
152
Exception Handling
java.lang.Object
java.lang.Throwable
java.lang.Error java.lang.Exception
java.io.IOException java.lang.RuntimeException
153
Checked and Unchecked
• Checked exceptions include all subtypes of Exception, excluding classes
that extend Runtime Exception.
• Checked exceptions are subject to the handle or declare rule; any method
that might throw a checked exception
– must either declare the exception using the throws keyword, or handle
the exception with an appropriate try/catch.
154
Catching Exceptions
class DivByZero {
public static void main(String args[]) {
try {
System.out.println(3/0);
System.out.println(“Please print me.”);
} catch (ArithmeticException exc) {
//Division by zero is an ArithmeticException
System.out.println(exc);
}
System.out.println(“After exception.”);
}
}
155
Catching Exception –Multiple Catch
class MultipleCatch {
public static void main(String args[]) {
try {
int den = Integer.parseInt(args[0]);
System.out.println(3/den);
}
catch (ArithmeticException exc)
{
System.out.println(“Divisor was 0.”);
}
catch (ArrayIndexOutOfBoundsException exc2)
{
System.out.println(“Missing argument.”);
}
System.out.println(“After exception.”);
}
}
}
156
Catching Exception –Nested Try’s
public static void main(String args[]){
try {
int a = Integer.parseInt(args[0]);
try {
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
}
catch (ArithmeticException e1)
{
System.out.println("Div by zero error!");
}
}
catch(ArrayIndexOutOfBoundsException e2)
{
System.out.println("Need 2 parameters!");
}
}
}
157
err Field in the System Class
public class Example_ErrField {
PrintStream prt;
System.setErr(prt);
try {
prt = new PrintStream(new File("a.err"));
}
catch (FileNotFoundException e)
{
159
Throwing Exceptions
• The throw Keyword
• Example:
– throw new ArithmeticException(“testing...”);
160
Throws Clause
• A method is required to either catch or list all exceptions it might throw
– Except for Error or RuntimeException, or their subclasses
• If a method may cause an exception to occur but does not catch it, then it
must say so using the throws keyword
161
Uncaught Exception
• Starting from the method where the exception is thrown and ending with
either the first method that has a corresponding catch for that exception type
or a JVM shutdown
162
Effective Exception Hierarchy
• Catches for specific exceptions should always be written prior to the generic
handler.
163
User Defined Exceptions
public class ServerTimedOutException extends Exception {
private int port;
Use the getMessage method, inherited from the Exception class, to get the
reason for which the exception was made.
164
Handle user defined Exception
• A method can throw a user-defined, checked exception:
• 1 public void connectMe(String serverName)
• 2 throws ServerTimedOutException {
• 3 boolean successful;
• 4 int portToConnect = 80;
• 5
• 6 successful = open(serverName, portToConnect);
• 7
• 8 if ( ! successful ) {
• 9 throw new ServerTimedOutException("Could not connect",
• 10 portToConnect);
• 11 }
• 12 }
165
Method Overriding and Exceptions
• The overriding method can throw:
• No exceptions
• One or more of the exceptions thrown by the overridden
method
• One or more subclasses of the exceptions thrown by the
overridden method
• The overriding method cannot throw:
• Additional exceptions not thrown by the overridden
method
• Superclasses of the exceptions thrown by the overridden
method
166
Assertions
• Allow the programmer to find out if an assumption was met
• Running the program informs you if assertions made are true or not
167
What are Assertions
• Allow the programmer to find out if an assumption was met
– Running the program informs you if assertions made are true or not
168
Enabling or Disabling Assertions
• Program with assertions may not work properly if used by clients not aware
that assertions were used in the code
• Compiling
– With assertion feature:
– javac –source 1.4 MyProgram.java
• Without the assertion feature:
– javac MyProgram.java
• Enabling assertions:
– Use the –enableassertions or –ea switch.
– java –enableassertions MyProgram
169
Assert Syntax
• assert <expression1>;
– where <expression1> is the condition asserted to be true
• assert <expression1> : <expression2>;
– <expression1> is the condition asserted to be true
– <expression2> is some information helpful in diagnosing why the
statement failed
170
Assert Syntax
class AgeAssert {
assert(age>0);
}
}
}
171
Don’t Use assertion to validate Arguments of a
Public Method
• A public method has to be called from code that you don’t control for from
code you have never seen,
• public methods are interface to the outside word , that should guarantee
that any constraints on the arguments will enforced by the method itself.
172
Asserting in the Right Way
• Use Assertions to validate Arguments of Private Method
Private void doStuff()
{
Assert(x>0)
}
173
Asserting in the Right Way
• Use , Even in Public Methods to check for cases that you know are
never ever supposed to happen
• Example in a case block that should never be reached , including a
default switch statements as given
Switch(x)
{
case 1: y-3;break;
case 2: y=y-5;break;
default
Assert false;
}
174
Enums
• Previously, the standard way to represent an
enumerated type was to use the
• int Enum pattern:
• No Namespace
– With other enum types
175
Enums
• Enums are classes that extend java.lang.Enum.
• The Enum type can be declared with a constructor, and each enum
constant is declared with parameters to be passed to the constructor.
176
Enums
enum Season{
WINTER, SPRING, SUMMER, FALL
}
if (type == Season.WINTER)
System.out.println (…)
177
ENUM -Examples
enum language {JAVA,J2EE,FORTRAN}
myObj.database = dbprds.ORACLE;
myObj.prglang = language.JAVA;
System.out.println(myObj.database);
System.out.println(myObj.prglang);
}
}
178
public class Enum_Ex2 {
flashDrive usbDrives;
flashDrive(int size)
{
this.size=size;
}
public int getCap()
{
return this.size;
}
}
public static void main(String[] args) {
myObj.usbDrives = flashDrive.SANDISK;
Servers myserver=Servers.WEBLOGIC;
switch (myserver)
{
case WEBLOGIC:
System.out.println("BEA");
break;
case WEBSPHERE:
System.out.println("IBM");
break;
case APACHE:
System.out.println("Open Source");
break;
}
180
for(Servers s:Servers.values())
{
System.out.println(s);
}
myserver = Servers.APACHE;
if(myserver==Servers.APACHE)
{
System.out.println("Good Choice for WEB
Applications");
}
if(Servers.APACHE.equals(Servers.ORACLE))
System.out.println("equals");
else System.out.println("not equal");
}
181