Language Translator

Showing posts with label FAQs. Show all posts
Showing posts with label FAQs. Show all posts

NESTED CLASS DESCRIPTION

A class that is declared within another class or interface is called a
nested class. For example,
//a class declared within a class.
class A
{
int i=100;
//this is a nested class.
class B
{
int j=100;
}
}

//a class declared within an interface.
interface A
{
int i=100;
//this is a nested class.
class B
{
int j=100;
}
}

Q. What is a nested interface?

Ans. An interface declared within another class or interface is called a nested interface. For example,
//an interface declared within another class.
Class A
{
int i=100;
//nested interface.
interface A
{
int j=100;
void fun();
}
}

//an interface declared within another interface.
interface A
{
int i=100;
public void fun();

//nested interface.
interface B
{
int j=100;
public void fun();
}
}

Q. How many types of nested classes and interfaces are available in Java?

Ans. Nested classes and interfaces can be broadly put into two categories:
1. Inner classes
2. Non-inner classes and interfaces.

1. Inner classes comprise of
1.1 Non-static member classes.
1.2 Local classes.
1.3 Anonymous classes.

2. Non-inner classes comprise only of
2.1 Static member classes and interfaces.

Q. What is the difference between an inner class and a non-inner class?

Ans. The difference lies in the syntax of accessing inner and non-inner classes. An inner class can be accessed only via an instance of its enclosing class. For example,
class A
{
int i=100;
class B
{
int j=200;
class C
{
int k=300;
}
}
}

public class test
{
public static void main(String args[])
{
A a=new A();
System.out.println(a.i); //will print 100.

A.B b=a.new B();
System.out.println(b.j); //will print 200.


A.B.C c=b.new C();
System.out.println(c.k); //will print 300.
}
}

However, a non-inner class can be accessed directly without creating an instance of its enclosing class. For example,
class A
{
int i=100;
static class B
{
int j=200;
static class C
{
int k=300;
}
}
}

public class test
{
public static void main(String args[])
{
A a=new A();
System.out.println(a.i); //will print 100.

A.B b=new A.B();
System.out.println(b.j); //will print 200.

A.B.C c=new A.B.C();
System.out.println(c.k); //will print 300.
}
}

Q. How far can an inner class access the members of its enclosing classes?

Ans. An inner class can access all the members (including private data members) of all its enclosing classes. For example,



class A
{
private int i=100;
void fun()
{
System.out.println(i);
}

class B
{
private int j=200;
void fun()
{
System.out.println(i);
System.out.println(j);
}
class C
{
private int k=300;
void fun()
{
System.out.println(i);
System.out.println(j);
System.out.println(k);
}
}
}
}

public class test
{
public static void main(String args[])
{
A a=new A();
a.fun(); //will print 100.

A.B b=a.new B();
b.fun(); //will print 100 200

A.B.C c=b.new C();
c.fun(); //will print 100 200 300
}
}





Q. Can we declare a non-static, local or anonymous interface?

Ans. No, it is illegal to declare a non-static, local or anonymous interface. Interfaces are always declared either at the top level or as static members. For example,

Q. What is a local class?

Ans. A local class is an inner class that is defined within a block. This block could be a method body, a constructor, a local block or a static intializer. For example,

class A
{
int i=100;
void fun()
{
int j=200;
//this is a local class.
class B
{
int k=300;
}
}
}

Q. Can a nested class have the same name as that of any of its enclosing classes or interfaces?

Ans. No. For example,
class A
{
class B
{
class C
{
class A //Error here
{
}
}
}
}

Q. What is a top-level class or interface?

Ans. A top-level class or interface is one which is not nested.


Q. Nested interfaces are implicitly ______ ?

Ans. static.
For example,
class A
{
interface B
{
int j=200;
}
}

public class test
{
public static void main(String args[])
{
System.out.println(A.B.j); //will print 200
}
}

Q. Static member classes and interfaces can be nested within other ______ member or ________ classes and interfaces only.

Ans. static, top-level.
For example,
class A
{
interface B
{
}
class C
{
//not allowed inside an inner class.
interface D
{
}
}
class E
{
//not allowed inside an inner class.
static class F
{
}
}
}


Q. Can a non-static member class declare static members?

Ans. No, a non-static member class cannot declare static members. For example,
class A
{
class B
{
static int i=100; //not allowed.
static class C //not allowed.
{
}
}
}
However, a non-static member class can use static members. For example,
class A
{
static int i=100;
class B
{
int k=A.i;

void fun()
{
A.i=300;
System.out.println(A.i); //will print 300.
System.out.println(k); //will print 100.
}
}
}

public class test
{
public static void main(String args[])
{
A a=new A();
A.B b=a.new B();
b.fun();
}
}

The only exception is that, final static variables can be declared within non-static member classes. For example,
class A
{
class B
{
static final int f=500;
}

}
public class test
{
public static void main(String args[])
{
A a=new A();
A.B b=a.new B();
System.out.println(b.f); //will print 500.
}
}

Q. What access specifiers can a nested class use?

Ans. A nested class is like any other class member. Therefore it can use the following access specifiers:
1. public
2. protected
3. private.

Q. What is the scope of a local class?

Ans. A local class can be instantiated only in the block in which it is defined. Clients outside the scope of the local class cannot instantiate the local class. For example,
class A
{
void fun()
{
//this is a local class which can be instantiated only
//within the method fun().
class B
{
int i=100;
}
}
}

Q. Is it possible for a method to return an object of a local class?

Ans. Yes, a method can return an object of a local class. However, the
return type cannot be the same as the local class type, since this type is not accessible outside of the method. A supertype of the local class must be specified as the return type. This implies that in order for the objects of the local class to be useful outside the method, a local class should implement an interface or override the behavior of its supertypes. For example,

class A
{
int i=100;
public void fun()
{
}
}

class B
{
public A fun()
{
class C extends A
{
int j=200;
public void fun()
{
System.out.println(i);
System.out.println(j);
}
}
return(new C());
}
}

public class test
{
public static void main(String args[])
{
A a=new B().fun();
a.fun(); //will print 100 200.
}
}

Q. Can a local class have static members?

Ans. No, a local class cannot have static members. For example,
class A
{
public void fun()
{
class B
{
static int i=100; //not allowed.
}
}
}

Q. Can a local class have access specifiers?

Ans. No, a local class cannot use any of the access specifiers. The reason being; a local class is exists only within the block in which it is defined.

Q. Can a local class be specified with the keyword static?

Ans. No, a local class cannot be specified with the keyword static. For example,
class A
{
public void fun()
{
static class B //not allowed.
{
}
}
}

Q. What is an anonymous class?

Ans. Anonymous classes are defined at the location they are instantiated. These classes combine the process of definition and instantiation into a single step. For example,
class B
{
public void fun()
{
}
}

class A
{
int i=100;
public B fun()
{
return(new B()
{
int j=200;
public void fun()
{
System.out.println("Inside B's fun; j= "+j);
}
});
}
}

public class test
{
public static void main(String args[])
{
A a=new A();
B b=a.fun();
b.fun(); //will print 200
}
}

Q. How can an anonymous class pass arguments to its super class?

Ans. Following syntax can be used to pass arguments to its super class:
new () {member declarations}

For example,
class A
{
int i;
A(int ii)
{
i=ii;
}
void fun()
{
System.out.println("Inside A's fun; i ="+i);
}
}

class B
{
int j=200;
public A fun()
{
return(new A(10)
{
int j=20;
public void fun()
{
System.out.println("Inside A's fun; i= "+i+" and j= "+j);
}
});
}
}

public class test
{
public static void main(String args[])
{
A a=new B().fun();
a.fun();
}
}


Q. Can the static keyword be placed before an anonymous class?

Ans. No, the static keyword cannot be placed before an anonymous class.

Q. Is it possible to declare static members inside an anonymous class?

Ans. No, static members cannot be declared inside anonymous classes. However, final static variables can be declared inside an anonymous class.




























Q. What is the output of the following program?

class A
{
int i=100;
void func()
{
System.out.println("Inside A's func; i ="+i);
}

A fun()
{
class B extends A
{
int j=200;

void func()
{
i=300;
System.out.println("Inside B's func; i ="+i);
System.out.println("Inside B's func; j ="+j);
}
}
return(new B());
}
}

public class test
{
public static void main(String args[])
{
A a=new A();
a.func();

a=a.fun();
a.func();
}
}

Ans. Inside A's func; i =100
Inside B's func; i =300
Inside B's func; j =200

JDBC DESCRIPTION

Q. JDBC stands for _______

Ans. Java Database Connectivity.

Q. What is JDBC API?

Ans. JDBC API is a collection of classes and interfaces, which help a Java application to connect to SQL based relational databases by abstracting vendor specific details of the database.

Q. The JDBC classes and interfaces are found in the packages _________ and
________

Ans. java.sql and javax.sql

Q. The latest version of JDBC is __________

Ans. JDBC 3.0

Q. What is a JDBC Driver?

Ans. A JDBC Driver is a middleware that translates the JDBC API calls to database vendor specific API calls. It is an implementation of the classes and interfaces specified in the java.sql and javax.sql packages by the database vendors or third-party vendors.

Q. How does JDBC provide database abstraction to a Java application developer?

Ans. Since the JDBC drivers follow the JDBC specification, the JDBC application developers can replace one driver for their application with another better one without having to rewrite their application. If they had used some proprietary API provided by some RDBMS vendor, they would not have been able to change the driver and/or database without having to rewrite the complete application.

Q. Who develops JDBC Specification?

Ans. SUN Microsystems prepares and maintains the JDBC specification. Since JDBC is just a specification (suggestions for writing and using JDBC drivers), third-party vendors develop JDBC drivers adhering to this specification. JDBC developers then use these drivers to access data sources.

Q. There are _____ types of JDBC drivers.

Ans. 4

Q. What are the four types of JDBC drivers?

Ans. There are four types of JDBC drivers. Here is a brief description of each of them:

1. JDBC Type 1 Driver (JDBC-ODBC Bridge)

The JDBC-ODBC Bridge translates the standard JDBC API calls to corresponding ODBC calls. This configuration requires the client application to have the JDBC-ODBC API implementation (SUN provides the JDBC-ODBC Driver), the ODBC Driver, and the database vendor specific native APIs such as the OCI library for Oracle installed on each client machine. Since each data access call has to go through many layers, this approach is the slowest and the most inefficient for high performance database access requirements. The use of JDBC-ODBC should be considered for experimental purposes only or when no other driver is available (this is because the Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn't require any extra setup itself). However this approach has to be used in some situations for example, a Microsoft Access 2000 database can only be accessed using the JDBC-ODBC Bridge.

2. JDBC Type 2 Driver (Part Java, Part Native Driver)

These type of drivers use a mixture of JDBC API implementation and database vendor specific native APIs for data access. When a database call is made, the JDBC driver translates the request into database vendor specific API call. In this approach, the JDBC Driver along with the database vendor specific native APIs such as the OCI library for Oracle should be installed on each client machine. It doesn't require the presence of ODBC. Type 2 drivers are faster than Type 1 drivers because of the absence of ODBC.

3. JDBC Type 3 Driver (Intermediate Database Access Server)

Type 3 drivers use an intermediate database server (middleware) that has the ability to connect multiple Java clients to multiple databases. The Java client application sends a database call through the JDBC Driver which forwards it to the Intermediate Database Access Server. The intermediate server can use different native protocols to connect to different databases.
One of the benefits of using a Type 3 driver is that it allows the Java application to be flexible, as the Intermediate Database Server can abstract the details of connection to various databases.

4. JDBC Type 4 Driver (Pure Java Driver)

Type 4 Drivers are a pure Java alternative to Type 2 Drivers. When a database call is made, Type 4 drivers connect to the database directly, using database vendor specific network protocols. They do so by making direct socket connections with the database. Type 4 drivers are the simplest to deploy since there are no additional libraries or middleware to install. They are also the most efficient and most widely used JDBC drivers in industry. All major database vendors provide Type 4 JDBC Drivers for their databases and they are also available from third party driver vendors.

Q. Classify the following as a class or an interface:
a) java.sql.Drivermanager
b) java.sql.Connection
c) java.sql.Statement
d) java.sql.ResultSet
e) java.sql.DatabaseMetaData
f) java.sql.ResultSetMetaData
g) java.sql.PreparedStatement
h) java.sql.CallableStatement
i) java.sql.Driver

Ans. a) java.sql.DriverManager is a class.
b) java.sql.Connection is an interface.
c) java.sql.Statement is an interface.
d) java.sql.ResultSet is an interface.
e) java.sql.DatabaseMetaData is an interface.
f) java.sql.ResultSetMetaData is an interface.
g) java.sql.PreparedStatement is an interface which extends the java.sql.Statement interface.
h) java.sql.CallableStatement is an interface which extends the java.sql.Statement interface.
i) Java.sql.Driver is an interface.

Q. The Exception subclass which handles JDBC related exceptions is _________

Ans. java.sql.SQLException







Q. Which interfaces in the java.sql package are implemented by the database vendors/third party driver vendors?

Ans. a) java.sql.Driver
b) java.sql.Connection
c) java.sql.Statement
d) java.sql.PreparedStatement
e) java.sql.CallableStatement

Q. Can we establish more than one connection with a database using a single driver?

Ans. Yes, we can establish more than one connection with a database using a single driver.

Q. What is a URL in JDBC? Why is it used?

Ans. A URL is a method of uniquely identifying a database driver. In a scenario where more than one driver is used for connecting to one or databases, there has to be some way for uniquely identifying each driver.

Q. Each driver needed by a Java application must first be registered with the _________

Ans. java.sql.DriverManager class

Q. What are the two different ways to load a JDBC driver?

Ans. A JDBC driver can be loaded by using any of the following two ways:

a) By using Class.forName() method as:

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

b) By using DriverManager class as:

DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());

Q. What are the basic operations that can be performed on any database? How do we handle such operations in JDBC?

Ans. The basic operations that can be performed on any database are:


a) Create a table.
b) Insert a row in the table.
c) Retrieve row(s) from the table.
d) Modify row(s) in the table.
e) Delete row(s) from the table.

Using JDBC, we can perform the aforesaid operations in the following way:

a) Create a table
……
stmt.executeUpdate(“create table Employee (EMPNO (varchar(6), NAME(char(40)”);
……

b) Insert a row into the table
……
stmt.executeUpdate(“insert into Employee values(‘E0001’,’XYZ’”);
……

c) Retrieve row(s) from the table
……
//select ALL the rows from the table.
ResultSet rst=stmt.executeQuery(“select * from Employee”);
while(rst.next())
{
System.out.println(rst.getString(“EMPNO”));
System.out.println(rst.getString(“NAME”));
}
……
//select PARTICULAR rows from the table.
ResultSet rst=stmt.executeQuery(“select * from Employee where
EMPNO=’E0001’”);
while(rst.next())
{
System.out.println(rst.getString(“EMPNO”));
System.out.println(rst.getString(“NAME”));
}

d) Modify row(s) in the table
……
int numUpdated=stmt.executeUpdate(“update Employee set NAME=’ABC’ where EMPNO=’E0001’”);
……

e) Delete row(s) from the table
……
int updated=stmt.executeUpdate(“delete from Employee where EMPNO=’E0001’”);
……
Q. What is the utility of prepared statements?

Ans. Databases are tuned to do statement caches. This cache uses the statement itself as a key and the access plan is stored in the cache with the corresponding statement. This allows the database engine to reuse the plans for statements that have been executed previously. For example, if we sent the database a statement such as "select a, b from t where c = 2", then the computed access plan is cached. If we send the same statement later, the database can reuse the previous access plan, thus saving us CPU power.
Note however, that the entire statement is the key. For example, if we later sent the statement "select a, b from t where c = 3", it would not find an access plan. This is because the "c=3" is different from the cached plan "c=2". So, for example:

for(int i = 0; i < 1000; ++i)
{
PreparedStatement ps = conn.prepareStatement("select a, b
from t where c = " + I);
ResultSet rs = Ps.executeQuery();
rs.close();
ps.close();
}

Here the cache won't be used. Each iteration of the loop sends a different SQL statement to the database. A new access plan is computed for each iteration and we're basically throwing CPU cycles away using this approach. However, look at the next snippet:

PreparedStatement ps = conn.prepareStatement("select a, b from t
where c = ?");
for(int i = 0; i < 1000; ++i)
{
ps.setInt(1, I);
ResultSet rs = ps.executeQuery();
rs.close();
}
ps.close();

Here it will be much more efficient. The statement sent to the database is parameterized using the '?' marker in the SQL. This means every iteration is sending the same statement to the database with different parameters for the "c=?" part. This allows the database to reuse the access plans for the statement and makes the program execute more efficiently inside the database. This basically let's your application run faster or makes more CPU available to users of the database.

Q. What does the method executeUpdate() return?

Ans. It returns the number of rows successfully inserted, updated or deleted. When it is used in conjunction with a select query, it returns a 0 since no rows are updated.

Q. Should we use column names or column index in the getXXX() methods of ResultSet interface?

Ans. Since the column indexes are subject to change due to a change in the database schema, it is advisable to use column names in these methods.

Q. What does the ResultSet.next() method return?

Ans. It returns false when the last record is reached and true otherwise.

Q. How many types of ResultSet objects are provided by JDBC?

Ans. JDBC classifies ResultSet objects on the basis of two characteristics:

a) Scroll Sensitivity
b) Updateability

a) Scroll Sensitivity

A scroll-insensitive resultset represents a static snapshot of the results when the query was made. On the other hand, a scroll-sensitive resultset is sensitive to the changes made to the data after the query has been executed, thus providing a dynamic view of the data as it changes.
The ResultSet class has two static data members; TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE to denote scroll-insensitive and scroll-sensitive resultsets respectively.

c) Updateability

The contents of an updateable resultset can be changed whereas those of a non-updateable resultset cannot be changed. The ResultSet class has two static data members; CONCUR_READ_ONLY and CONCUR_UPDATABLE to denote non-updateable and updateable resultsets.


Q What is the sequence of steps followed by JDBC to communicate with a database?

Ans. JDBC follows the following sequence to talk to a database:

a) Create an instance of a JDBC driver.
b) Register the driver with the DriverManager class.
c) Open a database connection.
d) Submit a query.
e) Receive results.

JAVA EXCEPTIONS DESCRIPTION

Q. The two immediate subclasses of Throwable class are: __________ and _________.

Ans. Exception and Error.

Q. What is an exception?

Ans. An exception is basically a runtime error.

Q. How does an exception arise in a Java code? Illustrate with the help of an example.

Ans. Consider the following code snippet:

public class A
{
public static void main(String args[])
{
int k=4/0;
System.out.println(k);
}
}

The statement int k=4/0; generates an object of the class ArithmeticException via the statement;

ArithmeticException e=new ArithmeticException();

This object starts searching from the line where the exception arose, for a piece of code which can accept it and process accordingly. As a result, all subsequent lines of code are skipped from being executed.

Q. What are the cases in which the finally block is executed?

Ans. The finally block is always executed in the following cases:

1. When no exception arises.
2. When an exception arises and it is handled by one of the catch blocks.
3. When an exception arises and it is not handled by any of the catch blocks.

Q. Is it necessary to write a finally with a try-catch block?

Ans. No, it is not at all mandatory to write a finally block with a try-catch block. This is because a finally block contains code which should execute whether or not the exception arises. However this might not always be required.
Usually, a finally block is used to place code that will release resources acquired in a try block. This strategy is an effective way to avoid resource leaks.

Q. Can a try statement be used in isolation, i.e., without a catch or finally block?

Ans. No, a try statement cannot be used in isolation. It should be followed by either the catch block or the finally block.

Q. What is the output of the following code:

public class A
{
public static void main(String args[])
{
try
{
int num=4/0;
}
catch(Exception e)
{
System.out.println(“Inside Exception”);
}
catch(ArithmeticException e)
{
System.out.println(“Inside ArithmeticException”);
}
}
}

Ans. Output:
Error: exception java.lang.ArithmeticException has already been caught catch(ArithmeticException e)

Reason:
When multiple catch statements are used, it is important to remember that exception subclasses must come before any of their superclasses. This is because, a catch statement that uses a superclasses will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it comes after its superclass. In the above case, Exception is the superclass of all types of exceptions including ArithmeticException.




Q. What is the output of the following code?

public class A
{
public static void main(String args[])
{
try
{
try
{
int num=4/0;
}
catch(NullPointerException e)
{
System.out.println(“Inside NullPointerException”);
}
}
catch(ArithmeticException e)
{
System.out.println(“Inside ArithmeticException”);
}
}
}

Ans. Ouput: Inside ArithmeticException

Reason: In case of nested try-catch statements, if an inner try statement does not have a catch handler for a particular exception, the next try statement’s catch handlers are examined for a match. This continues until one of the catch statements succeeds or until the entire nested try statements are exhausted.

Q. Is it possible to create exceptions of our own?

Ans. Yes, it is possible to create user-defined exceptions. This can be done by extending the Exception class as:

public MyException extends Exception
{
………
………
}




Q. Is it possible that the finally block is not executed?

Ans. Yes, it is possible that the finally block is not executed. This is possible when there is an exception in the finally block itself.

Q. What is the use of throws keyword?

Ans. If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of that method can guard themselves against that exception. This is done by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.

Q. What is the error in the following code:

void fun() throws NullPointerException, ArithmeticException

……….

public class A
{
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
}
}
}

Ans. For all the exceptions listed in the throws list of a method, a catch block should be written; otherwise the compiler would report an error. In the above example, the try block should be succeeded by two catch blocks for handling objects of the type NullPointerException and ArithmeticException.

Reason: The Java compiler forces the user to write catch blocks for each of the exceptions mentioned in the throws clause because it is not known till run-time that which exception out of the pre-specified list can be thrown by the method. Therefore, in order to make provision for every possible contingency, the compiler forces the programmer to write a catch block for all exceptions mentioned in the throws exception list.


Q. What is the error in the following code?

public class A
{
public static void main(String args[])
{
float f=2.5f;

switch(f)
{
case 5: System.out.println(“Hello”);
break;

case 2.5: System.out.println(“Bye”);
break;

default: System.out.println(“Not Found”);
}
}
}

Ans. The switch expression can take only the following types of values:
1. byte
2. short
3. int
4. char
It cannot take a float or any other type.

Q. What is a null statement in Java?

Ans. A statement that consists of only a semicolon is called a null statement.

Q. What is the output of the following code?

………
for(int i=0;i<4;i++)
System.out.println(“Hello”);

System.out.println(i);
……….

Ans. Output: cannot resolve the symbol: variable i
Reason: The scope of a variable inside a for-loop ends when the for block ends. Outside the for-block, the variable ceases to exist.



Q. What is the error in the following code?

public class A
{
public static void main(String args[])
{
int t=5, x=10, y=2;

switch(t)
{
case(10/2):
System.out.println(“Hello”);
break;

case(x/y): System.out.println(“Bye”);
break;

default: System.out.println(“Not Found”);
}
}
}

Ans. A case value must be a constant and not a variable. It can be an expression involving only constants which evaluates to a constant. An expression involving variables is not allowed.

Q. What is the error in the following code?

public class A
{
public static void main(String args[])
{
int t=9;

switch(t)
{
case(10-1):
System.out.println(“Hello”);
break;

case(3*3):
System.out.println(“Bye”);
break;

default: System.out.println(“Not Found”);
}
}
}

Ans. Duplicate case values are not allowed.

Q. What is the output of the following code?

public class A
{
public static void main(String args[])
{
int t=9;

switch(f)
{
case(10-1):
System.out.println(“Hello”);

case 3:
System.out.println(“Bye”);

case 4:
System.out.println(“Good Day”);
break;

default:
System.out.println(“Not Found”);
}
}
}

Ans. Output: Hello
Bye
Good Day

Reason: If there are no break statements after any case, it would result in the execution of all the case blocks starting from the first case value which matches with the switch expression.












Q. What is the use of the break statement?

Ans. The break statement causes the termination of a loop and the program control resumes at the next statement following the loop. For example,

for(……..)
{
for(……..)
{
for(……..)
{
if(……..)
break;
}
//Control resumes from here.
}
}

Q. What is the result when you compile and run the following code?

int i = 100;
switch (i)
{
case 100:
System.out.println(i);
case 200:
System.out.println(i);
case 300:
System.out.println(i);
}

[a] Nothing is printed
[b] Compile time error
[c] The values 100,100,100 printed
[d] Only 100 is printed

Ans. The values 100, 100, 100 are printed.








Q. How can you change the break statement below so that it breaks out of the inner and middle loops and continues with the next iteration of the outer loop?

outer:
for ( int x =0; x < 3; x++ ) {
middle: for ( int y=0; y < 3; y++ ) {
if ( y == 1)
break;
}
}
}

[a] break inner:
[b] break middle:
[c] break outer:
[d] continue
[e] continue middle

Ans. break middle;
Reason: When this form of break executes, the control is transferred out of the named block of code. The labeled block of code must enclose the break statement, but it does not need to be the immediately enclosing block. This means you can use a labeled break statement to exit from a set of nested blocks. But you cannot use break to transfer control to a block of code that does not enclose the break statement.

Q. Select all correct answers:
public class ExpTest {
public static void main ( String[] args ) {
try {
MyMethod();
} catch ( Exception e) {
}
}
static void MyMethod() {
try {
System.out.println("a");
} catch ( ArithmeticException ae) {
System.out.println("b");
} finally {
System.out.println("c");
}
System.out.println("d");
}
}

[a] a
[b] b
[c] c
[d] d

Ans. a
c
d

Q. What is the result of the following code when you compile and run?

public class ThrowDemo
{
static void demoMethod()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demoMethod.");
throw e; // re-throw the exception
}
}
public static void main(String args[])
{
try
{
demoMethod();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}

[a] Compilation error
[b] Runtime error
[c] Compile successfully, nothing is printed.
[d] Caught inside demoMethod. followed by Recaught: java.lang.NullPointerException: demo



Ans. Caught inside demoMethod. followed by Recaught: java.lang.NullPointerException: demo

Reason: NullPointerException is one of Java’s unchecked exceptions. Therefore, there is not need to mention it in the method’s throws list.

Q. Select the correct answer:

public class ThrowsDemo
{
static void throwMethod()
{
System.out.println("Inside throwMethod.");
throw new IllegalAccessException("demo");
}

public static void main(String args[])
{
try
{
throwMethod();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}

[a] Compilation error
[b] Runtime error
[c] Compile successfully, nothing is printed.
[d] inside demoMethod. followed by caught: java.lang.IllegalAccessException: demo

Ans. Compilation error.
Reason: IllegalAccessException is one of Java’s checked exceptions. Therefore, it has to be mentioned in the throws list of throwMethod().









Q. What is the output of the following program if you compile and run?
outer: for (int i = 0; i < 2; i++ ) {
for ( int j = 0; j < 3; j++ ) {
if ( i == j ) {
continue outer;
}
System.out.println("The value of i is: " + i );
System.out.println("The value of i is: " + j);
}
}
[a] The value of i is: 0
The value of j is: 0
[b] The value of i is: 0
The value of j is: 1
[c] The value of i is: 0
The value of j is: 2
[d] The value of i is: 1
The value of j is: 0
[e] The value of i is: 1
The value of j is: 1
[f] The value of i is: 1
The value of j is: 2
Ans. The value of i is: 1
The value of j is: 0
Reason: If you are using the continue statement in labeled form then the statement continues at the next iteration of the labeled loop.

Q. What is the result when you compile and run the following code?

int i = 100;
switch (i)
{
case 100:
System.out.println(i);
case 200:
System.out.println(i);
case 300:
System.out.println(i);
}

[a] Nothing is printed
[b] Compile time error
[c] The values 100,100,100 printed
[d] Only 100 is printed

Ans. The values 100, 100, 100 are printed.

Q. What is the base class for Error and Exception?

Ans. Throwable.

Q. Throwable class resides in the package _______ ?

Ans. java.lang

Q. What class of exceptions are generated by the Java run-time system?

Ans. The Java run-time system generates RuntimeException and Error exceptions.

Q. Can a no argument constructor throw exception?

Ans. Yes, see the following code:
public class A
{
public A() throws Exception
{
throw new Exception("No argu constructor can throw
exception too");
}

public static void main(String args[])
{
try
{
new A();
}
catch (Exception e)
{
System.out.println(e);
}
}
}






Q. I have two exceptions thrown in the same try block,
when the first exeption is thrown, the second exception is
ignored. Why?

Ans. When an exception is thrown, the code cannot continue
its normal path. Therefore, he code following the exception line will not
be executed no matter what.

Q. Checked exception must be caught or declared, how about
unchecked ones?

Ans. Checked exceptions must be caught or declared in the method throws
statement. Unchecked Exceptions do not require the same.
However, if you do, it does not cause an error either. Something must be specified does not imply Something else must not be specified.

Event Delegation Model

Q. Explain the Event Delegation Model.

Ans. The Event Delegation Model is Java’s way of handling user/process generated events. In this model, a source generates an event which is sent to one or more listeners registered with it. The listener then processes the event accordingly.



Q. What is an Event?

Ans. An event is an object that describes a state change in an event source.
For example, a button is an event source and pressing of the button is an event.

Q. What is an Event Source?

Ans. An event source is an object that generates an event. For example, a button is an event source.

Q. What is a Listener?

Ans. A listener is an object that is notified when an event occurs. There are two conditions to be fulfilled in order to become a valid listener;
1. The listener must be registered with at least one of the event sources.
2. It must implement methods that receive and process such events.



Q. The methods that receive and process events are defined in a set of interfaces in the _______ package.

Ans. java.awt.event

Q. Is it necessary to register a listener with an event source?

Ans. Yes, it is necessary to register a listener with an event source because an event notification is sent to only those listeners that are registered with the event source. All registered listeners receive a copy of the event object.

Q. How can a listener register itself with an event source?

Ans. The general form of the registration method is:

public void addTypeListener(new TypeListener())

Here, Type is the name of the event and new TypeListener() is an instance of the event listener object.

Some event sources may allow only one listener to be registered. The general form of such a registration method is:

public void addTypeListener(new TypeListener()) throws java.util.TooManyListenersException

Q. What is multicasting and unicasting?

Ans. When an event occurs, all the registered listeners are notified and sent a copy of the event object. This is known as multicasting.
If there is only one registered listener, then this process is called as unicasting.

Q. Name the event objects and their respective listener interfaces and Adapter Classes for the following events:
1. A button is pressed, a list item is double-clicked, or a menu item is selected.
2. A component is hidden, moved, resized or becomes visible.
3. A component is added to or removed from a container.
4. A check box is clicked.
5. A key is pressed.
6. Mouse is moved or clicked.
7. Value of a text area is changed.
8. A window is opened or closed.


Ans. Event Listener Interface Adapter Class

1. ActionEvent ActionListener None
2. ComponentEvent ComponentListener ComponentAdapter
3. ContainerEvent ContainerListener ContainerAdapter
4. ItemEvent ItemListener None
5. KeyEvent KeytListener KeyAdapter
6. MouseEvent MouseListener MouseAdapter
7. TextEvent TextListener None
8. WindowEvent WindowListener WindowAdapter

Q. Why are there no adapter classes for:
1. ActionEvent
2. ItemEvent
3. TextEvent

Ans. All these classes contain only one method. So, there is no need to write an adapter classes for them.

Q. What is an adapter class?

Ans. An adapter class provides an empty implementation of all the methods in an event listener interface. Such a class is useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act as an event listener by extending such an adapter class and implementing only those events in which you are interested.





















Q. What is an inner class? State an example.

Ans. An inner class is a class defined within another class or within an expression. For example,

public class MousePressedDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter(this));
}
}

class MyMouseAdapter extends MouseAdapter
{
MousePressedDemo mousePressedDemo;
//single argument constructor.
public MyMouseAdapter(MousePressedDemo mpd)
{
this.mousePressedDemo=mpd;
}
public void mousePressed(MouseEvent me)
{
mousePressedDemo.showStatus(“Mouse Clicked”);
}
}

Q. What is an Anonymous Inner Class? State an example.

Ans. An Anonymous Inner Class is one that is not assigned a name. For example,

public class AnonymousInnerClassDemo extends Applet
{
public void init()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
showStatus(“Mouse Clicked”);
}
});
}
}

Java Virtual Machine

Java Virtual Machine (JVM) is a virtual computer, typically implemented in software on top of a "real" hardware platform and operating system that runs compiled Java programs.

All Java programs are compiled for the JVM. Therefore, the JVM must be implemented on a particular platform before compiled Java programs will run on that platform.

The JVM executes Java bytecodes, so Java bytecodes can be thought of as the machine language of the JVM.

Role of JVM in making Java portable, How?

The JVM plays a central role in making Java portable. It provides a layer of abstraction between the compiled Java program and the underlying hardware platform and operating system. The JVM is central to Java's portability because compiled Java programs run on the JVM, independent of whatever may be underneath a particular JVM implementation.

Various parts of a JVM?

The "virtual hardware" of the Java Virtual Machine can be divided into four basic parts:

1. The Registers
2. The Stack
3. The garbage-collected Heap
4. The Method Area.

These parts are abstract, just like the machine they compose, but they must exist in some form in every JVM implementation. The size of an address in the JVM is 32 bits. The JVM can, therefore, address up to 4 gigabytes (2 to the power of 32) of memory, with each memory location containing one byte. Each register in the JVM stores one 32-bit address. The stack, the garbage-collected heap, and the method area reside somewhere within the 4 gigabytes of addressable memory. The exact location of these memory areas is a decision of the implementer of each particular JVM.

Various data types provided by JVM?

A word in the Java Virtual Machine is 32 bits. The JVM has a small number of primitive data types: byte (8 bits), short (16 bits), int (32 bits), long (64 bits), float (32 bits), double (64 bits), and char (16 bits). With the exception of char, which is an unsigned Unicode character, all the numeric types are signed. These types conveniently map to the types available to the Java programmer. One other primitive type is the object handle, which is a 32-bit address that refers to an object on the heap.

Use of the Stack in JVM?

The Java stack is used to store parameters for and results of bytecode instructions, to pass parameters to and return values from methods, and to keep the state of each method invocation. The state of a method invocation is called its stack frame. All the local variables being used by the current method invocation are also stored in the stack.

Use of the Heap in JVM?

The heap is where the objects of a Java program live. Any time you allocate memory with the new operator; that memory comes from the heap. The Java language doesn't allow you to free allocated memory directly. Instead, the runtime environment keeps track of the references to each object on the heap, and automatically frees the memory occupied by objects that are no longer referenced -- a process called garbage collection.

Method Area in JVM?

The method area is where the bytecodes reside.