Java_Unit_II_Part_II

9. What is a package?

Ans:
Package is a Java’s way of grouping a variety of classes and/or interfaces together. Upon importing a package in a program, it will be able to access the classes defined in that package. Creating packages is way of achieving the reusability in Java. The grouping is usually done according to functionality. With the help of packages, we can use classes from other programs without physically copying them into the program under development. Packages concept is similar to "class libraries" in other languages. By organizing our classes into packages we achieve the following benefits: 1. The classes contained in the packages of other programs can be easily reused.
2. In packages, classes can be unique compared with classes in other packages. That is, two classes in two different packages can have the same name. They may be referred to by their name, comprising the package name and the class name. 
3. Packages provide a way to "hide" classes thus preventing other programs or packages from accessing classes that are meant for internal use only.

4. Packages also provide a way for separating "design" from "coding". First we can design classes and decide their relationships, and then we can implement the Java code needed for the methods. It is possible to change the implementation of any method without affecting the rest of the design.


10. Explain the process of using Java API Packages & System Packages

Ans:




There are two ways of accessing the classes stored in packages:
 Using fully qualified class name
 Import package and use class name directly.
1. Using fully qualified class Name:
This is done by using the package name containing the class and then appending the class name to it using dot operator.
Ex: java.util.Vector
2. Import package and use class name directly:
a) Importing a particular class in a package: import java.util.Vector;
b) Importing all the classes in a package: import java.util.*;

11.Explain the creation and accessing of a Package?
Ans:
Creating Package:
Creating a package is quite easy. First declare the name of the package using the ‘package’ key word followed by a package name. This statement defines a name space in which classes are stored. It is followed by package definition. 

Here is an example. 
Package first package // package declaration
Public class Firstclass // class definition 
Body of the class 

Here the package name is first package. The class Firstclass now a part of the package. The listing would be saved as a file called Firstclass.java. It is located in a directory named firstpackage. When the source file is compiled, Java will create a class file and store it in the same directory.
Creating the package involves the following steps: 1. Declare the package at the beginning of a file using the form Package Packagename; 2. Define the class that is to be put in the package and declare it public. 3. Create a subdirectory under the directory where the main source files are stored.
4. Store the listing as the classname.java file in subdirectory. 
5. Compile the file. This creates .class file in subdirectory. Java also supports the concept of package hierarchy. Specifying multiple names in a package statement separated by periods does this. The general form of a multileveled package statement is shown here Package pkg1.pkg2;
Accessing a Package: A Java system package can be accessed either using a fully qualified class name or through the ‘import’ statement. Import statement is used when 1. There are too many references to a particular package. 2. When the package name is too long. The general form of ‘import’ statement for searching a class is as follows 
import package1[.package2] [.package3].class name;
where package1 is the name of the top level package, package2 is the name of package inside package1 and so on. 
Finally, ‘class name’ is specified explicitly. Example:
import firstPackage.SecondPackage.Myclass ; Another Approach : import.packagename.*; Packagename can denote a single package or a hierarchy of packages. The star(*) indicates that the compiler should search this entire package hierarchy.


12.Explain Wrapper Classes.?

Ans:

Wrapper classes can be used to convert primitive data types like int, float, long, and double to objects. These classes are contained in the java.lang package. The classes Byte, Double, Float, Integer and Short extend the abstract class Number. All the wrapper classes are public final ie cannot be extended.

All the wrapper classes have two constructor forms.

 A constructor that takes the primitive type and creates an object eg Character(char), Integer(int).

 A constructor that converts a String into an object eg Integer("1"). But, this type of constructor is not available with Character class.

The methods of the wrapper classes are all static so we can use them without creating an instance of the matching wrapper class. Once assigned a value, the value of a wrapper class cannot be changed. The wrapper classes are just that classes, they are not primitives and instances of the wrappers can only be manipulated in the same way as any class.

The following lists simple data types and their corresponding wrapper classes.

Simple Type   Wrapper class

boolean             Boolean

char                     Character

double                 Double

float                     Float

int                         Int

long                     Long

byte                     Byte

short                     Short


13.Explain Exception in Java?

Ans:

Exception: An exception is a condition that is caused by a run-time error in the program. When the Java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it (i.e., informs us that an error has occurred).

If the object is not caught and handled properly, the interpreter will display an error message and will terminate (stop) the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate (proper) message for taking corrective actions. This task is known as Exception Handling.

The purpose of exception handling mechanism is to provide a means to detect (find) and report an exceptional circumstance so that appropriate can be taken. The mechanism suggests incorporation (to include) of a separate error handling code that performs the following tasks:

 Find the problem (Hit the exception)

 Inform that an error has occurred (Throw the exception)

 Receive the error information (Catch the exception)

 Take corrective actions (Handle the exception)


14.Explain Pre-defined Exceptions in Java.?

Ans:

Some common exceptions that we must watch out for catching are listed below:

 ArithmeticException – Caused by math errors such as division by zero

 ArrayIndexOutOfBoundsException – Caused by bad array indexes

 ArrayStoreException – Caused when a program tries to store the wrong type of data in an array

 FileNotFoundException – Caused by an attempt to access a nonexistent file

 IOException – Caused by general I/O failures, such as inability to read from a file

 NullPointerException – Caused by referencing a null object

 NumberFormatException – Caused when a conversion between strings and number fails

 OutOfMemoryException – Caused when there’s not enough memory to allocate a new object.

 SecurityException – Caused when an applet tries to perform an action not allowed by the browser’s security setting

 StackOverflowException – Caused when the system runs out of stack space.


15.Explain the process of Exception Handling in Java?

Ans:

Exception Handling: If the object is not caught and handled properly, the interpreter will display an error message and will terminate (stop) the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate (proper) message for taking corrective actions. This task is known as Exception Handling.

The basic concept of exception handling are throwing an exception and catching it.




Java uses a keyword try to preface a block of code that is likely to cause an error condition and throw an exception. A catch block defined by the keyword catch catches the exception thrown by the try block and handles it appropriately. The catch block is added immediately after the try block. The following syntax illustrates the use of simple try and catch statements:

………………………….

try

{

statement; // generates an exception

}

catch (Exception-type e)

{

statement; // process the exception

}

……………………………..

……………………………….

try & catch: The try block can have one or more statements that could generate an exception. If any statement generates an exception, the remaining statements in the block are skipped and execution jumps to the catch blocks that is placed next to the try block.

The catch block too can have one or more statements that are necessary to process the exception. Remember that every try statement should be followed by at least one catch statement; otherwise compilation error will occur.

The catch statement works like a method definition. The catch statement is passed a single parameter, which is reference to the exception object thrown (by the try block). If the catch parameter matches with the type of exception object, then the exception is caught and statements in the catch block will be executed. Otherwise, the exception is not caught and the default exception handler will cause the execution to terminate.


16.Write a program to handle division by zero exception.?

Ans:

class ZeroTest

{

public static void main(String as[])

{

int a=5;

int b=0;

try

{

System.out.println(“Division=”+ (a/b));

}

catch(ArithmeticException e)

{

System.out.println(“Division by zero is not possible”);

}

}

}

17. How many catch blocks can we use with one try block?

Ans: It is possible to have more than one catch statement in the catch block. When an exception in a try block is generated, the Java treats the multiple catch statements like case in a switch statement. The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped.

Java does not require any processing of the exception at all. We can simply have a catch statement with an empty block to avoid program abortion.

Example: catch (Exception e);

The catch statement simply ends with a semicolon, which does nothing. This statement will catch an exception and then ignore it.

Syntax:

………………………

try

{

statement; // generates an exception

}

catch (Exception-Type-1 e)

{

statement; // process exception type 1

}

catch (Exception-Type-2 e)

{

statement; // process exception type 2

}

catch (Exception-Type-N e)

{

statement; // process exception type N

}

…………………………….

18.Explain throwing our own exception in Java.?

Ans:There may be times when we would like to throw our own exceptions. We can do this by using the keyword throw as follows: throw new Throwable_subclass;

Example: throw new ArithmeticException( );

throw new NumberFormatException( );

import java.lang.Exception;

class MyException extends Exception

{

MyException(String message)

{

super(message);

}

}

class TestMyException

{

public static void main(String args[ ])

{

int x = 5, y = 1000;

try

{

float z = (float)x/(float)y;

if(z < 0.01)

{

throw new MyException("Number is too small");

}

}

catch(MyException e)

{

System.out.println("caught my exception");

System.out.println(e.getMessage( ));

}

finally

{

System.out.println("I am always here");

}

}

}


Visit http://degreecsa.blogspot.com

No comments:

Post a Comment