Java3
Java3
Handling
Packages In Java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to
package");
}
}
Compiling pacakge
javac -d . Simple.java
• Built-in Packages
• User-defined packages
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
How to import packages in Java?
1)import package.*;
2)import package.classname;
3)fully qualified name.
Using packagename.*
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Using packagename.classname
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Using fully qualified name
To Compile:
javac -d . filename.java
To Run:
java packagename.filename
To Compile:
// A simple interface
interface Player{
final int id = 10;
int move();
}
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){
System.out.println("drawing rectangle");
} }
class Circle implements Drawable{
public void draw(){
System.out.println("drawing circle");
}
//Using interface
public static void main(String args[]){
Drawable d=new Rectangle()/Circle();
//In real scenario, object is provided by
method e.g. getDrawable()
d.draw();
}}
Extending Interfaces
1.)Built-in Exceptions
Checked Exception
Unchecked Exception
2.)User-Defined Exceptions
Built-in Exceptions:
Built-in exceptions are the exceptions that are available in
Java libraries. These exceptions are suitable to explain
certain error situations.
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception
occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds
Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception
occurs");
}
System.out.println("rest of the code");
} }
Nested try blocks
System.out.println("ArrayIndexOutOfBounds
Exception");
} }}
Java finally block
Java finally block is a block used to execute
important code such as closing the
connection, etc.
checksal(3000);
System.out.println("rest of the code...");
}
}
If we throw unchecked exception from a
method, it is must to handle the exception or
declare in throws clause.
Throwing Checked Exception
import java.io.*;
}
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Throwing User-defined Exception
public class TestThrow3
{
public static void main(String args[])
{ try
{
throw new UserDefinedException("This
is user-defined exception");
}
System.out.println(ude.getMessage());
} } }