Wednesday, May 20, 2009

java Interviw questions

Java Interview Questions




[ Java 2, Servlet, JSP, XML, JNDI, EJB , Swing, Applets, JMS, Java mail, Tomcat, XSL, Weblogic ]












1) Difference between Abstract class and Interface?
i.A Java interface is just that, a purely abstract method interface with no implementation component. An abstract class provides not just an interface, it also provides a (partial) implementation.

ii.Java supports multiple interface inheritance, but only single implementation inheritance.

iii.Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code.
iv.A class can implement any number of interfaces, but subclass at most one abstract class.
v.An abstract class can have nonabstract methods. All methods of an interface are abstract.
vi.An abstract class can have instance variables. An interface cannot.
vii.An abstract class can define constructor. An interface cannot.
viii.An abstract class can have any visibility: public, protected, private or none (package).
An interface's visbility must be public or none (package).
ix.An abstract class inherits from Object and includes methods such as clone() and equals().


2) What are the adv. of interface?
"Interface" is the Java way to do multiple inheritance, or a better way to think of it is as a way to design plug-ins. For example, let's say we have an application that monitors a network of computers. Our monitors might check for web pages, or they may check for other ports, or they may have hooks for hardware checks.
The interface to our main control panel is always the same: We need some means to poll the monitor object for an answer. This is the "NetworkMonitor" interface and all network monitors will share this interface, but they may have a class heirarchy that is very different, for example, port-monitors may all fork a thread that periodically checks whereas our control panel interface just asks for the most recent answer; hardware monitors may ask for their data in real-time or over RPC and thus have no need of inheriting from Thread. Because they share the same Interface definition, the control panel application does not need to know if they are polling monitors or real-time monitors because, from the control panel's point of view, it does not matter


3) What do u mean by encapsulation?
Wrapping up of data and methods is called Encapsulation. Hiding an implementation is often called an encapsulation. This is a fundamental concept in Object Oriented Programming. Another way of saying is that data hiding or separating the interface from its implementation.

The tightly encapsulated classes are more efficient. Main advantages of encapsulation is the code reuse.
The perfect encapsulation means making member variables as private and allowing access to only through public interface, which is methods. In Java the concept called mutator/accessor methods.


4) How can u start the process?
Using exec method.
5) Write the code to start notepad.exe?

class startnotepad
{
public static void main(String args []) {
Runtime r = Runtime.getRuntime();
Process p = null;
try {
p = r.exec("notepad");
p.waitFor(); // waits till notepad is closed
}catch(Exception e ) {
System.out.println("Error executing notepad");
}
System.out.println("notepad closed.");
}
}



6) what r the classes and interfaces availale in util package?
Interface Implementation classes
Set HashSet TreeSet
List ArrrayList LinkedList
Map HashMap TreeMap


7.) Adv. and Disadv of using Vector?
i.Since the Vector method uses an array for storage but has extra steps involved in getting an element, use an array for fastest access.
ii.This should be evident just looking at the amount of code you need to traverse one versus the other. It might also be beneficial to write a linkedlist class and use that. That way you have a dynamic container which has potential to be faster than a vector (though still not as fast as an array). The
problem with arrays is that if you need more space than the current size, you have to hardcode their copying into a bigger array.
Conversely, if you never (or rarely) use the entire array, its a waste of space and memory.

14) how will u insert element in Vector?
using addElement() method.
15) iteration from vector? write the code?

for (int i = 0; i < vector.size(); i++) {
System.out.println(vector.elementAt(i));
}

16) Do u know about LinkedList?

The LinkedList implements java.util.List interface and uses linked list for storage. A linked list allow elements to be added, removed from the collection at any location in the container by ordering the elements. With this implementation you can only access the elements in sequentially. You can easily treat the LinkedList as a stack, queue and etc., by using the LinkedList methods.
Methods:

void addFirst(Object o);
void addLast(Object o);
Object getFirst();
Object getLast();
Object removeFirst();
Object removeLast();

r what are the types of constructor in Vector?


General :
1. What is the Difference Between B2B and B2C?
In a business-to-business (B2B) environment, Company A and Company B want to
exchange information about e-commerce transactions in which both are involved.


Html:

1) What is the tag for textarea?



2) What is the tag for combobox?


1) What is the role in XML in your project?
i.Used as Data Carrying Element
ii.Used as configuration files


2) How to send XML file from one Server to another?


3) Diff. between DOMparser and SAXparser?
1. DOM reads an XML document into memory and represents it as a tree.



4) Adv. and Disadv of DomParser?
i. The main drawback, however, is that the entire XML document has to be read into memory for DOM to create the tree.
2. If your document is very large, using SAX will save significant amounts of memory when compared to using DOM. This is especially true if you only need a few elements in a large document.
3. On the other hand, the rich set of standard functions provided by the DOM isn't available when you use SAX.

5) What is Dtd, Schema?
DTD : The purpose of a Document Type Definition is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements.
SCHEMA : XML Schemas are an XML Language for describing and constraining the content of XML Document.


6) Diff. between DTD, Schema?
Although XML does not require data to be validated against a DTD, many of the benefits of using the technology are derived from being able to validate XML documents against business or technical architecture rules. Polling for the list of DTDs that developers have worked with provides insight to their general exposure to the technology. The ideal candidate will have knowledge of several of the commonly used DTDs such as FpML, DocBook, HRML, and RDF, as well as experience designing a custom DTD for a particular project where no standard existed


7) When will you use DTD and when will you use Schema?
To define the format of XML messages, or XML documents, Company A creates two
document type definitions (DTDs): one that describes the information that A will
provide about customers and one that describes the information that A wants to receive
about a newly affiliated company. Company B must also create two DTDs: one to
process the XML documents received from Company A and one to prepare an XML
document in a format that can be processed by Company A.


Jsp
~~~
1) diff. between forward and sendRedirect?
When we use "forward", the process is happening at the web container without the client being informed that a different resource is going to process the request.
When we use "sendRedirect", it causes the web container to return to the browser indicating that a new URL should be requested.


With Forward, request & response would be passed to the destination URL which should be relative (means that the destination URL should be within a servlet context). Also, after executing forward method, the
control will return back to the same method from where the forward method was called. All the opposite to the above points apply to sendRedirect.
(OR)The forward will redirect in the application server itself. It does not come to the client. whereas Response.sendredirect() will come to the client and go back ...ie. URL appending will happen.

When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container.
When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.


2) diff. between jsp:include and page include?
The include directive lets you reuse navigation bars, tables, and other elements in multiple pages. The included elements can contain JSP code and thus are inserted into the page before the page is translated into a servlet.(which is typically the first time it is accessed).
The jsp:include action includes files at the time of the cli-ent request and thus does not require you to update the main file when an included file changes.


3) Which situation will u use the above?
Use the include directive if included files will use JSP constructs. Otherwise, use jsp:include.


4) write down the Jsp tags?
i) Directives
ii) Scripting elements
iii) Comments
iv) Actions


5) write down the Jsp directives?
i) Page Directive
ii) Include Directive
iii) Tag library Directive


6) Jsp lifecycle methods?
i) jspInit()
ii) _jspService()
iii) _jspDestroy()


Servlet
~~~~~~~
1) Lifecycle methods?
i. init()
ii. service()
iii.destroy()

2) Can u override the destroy() method in servlet?


3) Diff. between destroy() and finalizer()?


Tomcat
~~~~~~
1) How will u increase the HeapMemory of Tomcat?
2) Do u see the catalina?
3) catalina.odbms file when will come?


Jdbc
~~~~
1) write the code for connecting db

Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/om");
st=con.createStatement();
str ="select * from admin where admin_name ='"+s1+"' "+" and password ='"+pas+"'";
rs=st.executeQuery(str);



2) which class have the createStatement()?
java.sql.Connection

3) Types of driver?
TYPE 1 : JDBC ODBC Bridge
TYPE 2 : Part Java Part Native
TYPE 3 : Intermediate Data access Server
TYPE 4 : Pure Java Driver


4) Connection methods?
1. Using DSN
2. Using Port


5) connection pooling?
Connection pooling is a mechanism through which open database connections are held in
a cache for use and reuse by different parts of an application.

6) Port number for mysql?
3306 is the port number for mysql.
1)Difference between JSP and Struts:
jsp:
i) JSP scriptlets are quick and dirty, but always rough and ready
ii) It won't give i18n standard
Struts:
The Struts template custom tags are used to create templates for groups of pages that share a common format.
The functionality of these templates is similar to the JSP include directive or the JSP include action, but more dynamic than the include directive and more flexible than the include action.

3) Ant
Another Neat Tool(Ant) enables you to automate the build deploy process of your server-side Java Web components, such as custom tags, servlets, and JSPs.

4) Introduction to JDO
The Java Data Objects (JDO) specification from Sun Microsystems aims to provide Java
programmers with a much-needed, lightweight view of object-oriented persistent data. JDO
frees developers to interact with objects in a natural way, providing an alternative to JDBC or
Enterprise JavaBeans with Bean Managed Persistence or Container Managed Persistence,
the two previous options in this area. One of JDO's biggest advantages is that it lets us
concentrate on developing a correct class model, rather than on developing a relational class
model. Further, JDO attempts to abstract the actual data source from the class model. This
allows different types of data sources to be "plugged in" to a deployed system. Rather than
being stuck with a relational database on the back end, we can now use object databases or
even XML files residing in the filesystem as our data sources.

EJB Container Managed Persistence (EJB CMP) has been a preferred method of dealing with
object persistence on relational databases. But using EJB CMP entails adherence to the EJB
programming model, the use of heavyweight development and deployment tools, and a steep
learning curve for all the developers involved. By preserving the object semantics and moving
the burden of programming-model adherence to a set of tools, JDO makes object-based
persistence much more accessible to Java developers.

1) What is Framework?
2) What is Specification?
3) What is Xercers and Parsers?
4) What is the level of Core Java? ( 1 to 10 )
5) Do you write the Ant Script?
6) MVC Model - 2 Architecture


What is a Framework?
A framework is a set of classes and interfaces that cooperate to solve a specific type of software problem. A framework has the following characteristics:

A framework is made up of multiple classes or components, each of which may provide an abstraction of some particular concept.
The framework defines how these abstractions work together to solve a problem.
The framework components are reusable.

A good framework should provide generic behavior that can be utilized across many different types of applications.

Struts:

1) if we add any new field which is not in formbean into validation.xml, whether the error will come or not?

2) can we have a duplicate field in validation.xml?

3) whatever problems faced when deploying your project in Linux?

4) how to use different ApplicationResources.properties as per locale?

5) Diff String and StringBuffer

1)What is struts?
Struts is a framework that promotes the use of the Model-View-Controller architecture for designing large scale applications. The framework includes a set of custom tag libaries and their associated Java classes, along with various utility classes. The most powerful aspect of the Struts framework is its support for creating and processing web-based forms.

OR
i) Struts is an open-source MVC implementation
ii) Manages complexity in large Web sites with servlets and JSP framework
iii) Struts can help you control change in your Web project and promote specialization.

2) What is MVC?
"Model-View-Controller" is a way to build applications that promotes complete separation between business logic and presentation. It is not specific to web applications, or Java, or J2EE (it predates all of these by many years), but it can be applied to building J2EE web applications. The beauty of model-view-controller separation is that new views and controllers can be created independently of the model.

OR

Model-View-Controller (MVC) is a design pattern put together to help control change.

Struts is an MVC implementation that uses Servlets 2.2 and JSP 1.1 tags, from the J2EE specifications, as part of the implementation.

MVC helps resolve some of the issues with the single module approach by dividing the problem into three categories:
Model
The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.

View
The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.

Controller
The controller reacts to the user input. It creates and sets the model.


3) What is JSP?
A JavaServer Page (JSP) file is nothing more than another way to view a servlet. The concept of a JSP file is to allow us to see a Java servlet as an HTML page. This view eliminates all of the ugly print() statements that normally show up in Java code. The JSP file is pre-processed into a .java file, then compiled into a .class.

4) Purpose of JSP tag?
A JSP tag is simply a way of abstracting out code from a JSP file.

0) How much do u know about struts? ( 4 among 10 )

1) draw MVC Architechture? (whether view initiate controller or controller initiate view??)
ans: browser


view controller model



2) what are the tags u have used in struts? (html, bean, tiles, logic )
ans: html => Wrapping the html tags for binding with fromBean
Bean =>
Logic => Use to write page flow logic
template => put, get, insert


3) how to validate? (serverside or clientside) (if clientside how?)


4) how to create user_defined controller_servlet?
ans: controller tag in struts-config.xml


5) where will u put session.timeout()? if we want to clearup some database tables when the session times out, where will u place the code, how will u call?
ans: using Listener


6) if we want to use anyone properties file otherthan "ApplicationResources.properties", what will u do?
ans: getClass().getPath("com.wiley.App");


7) MVC2 arch

8) log4J is whose product?

9) ServletContext ==> whether used for every context?

1) Struts useful to whom? (Whether for client or user or developer? )
2) J2ee is useful to whom?
3) public interface int
{
private int i=0;
Vector v = new Vector();
public final int j=2;
}

What is wrong in this interface?
i) it contains private modifier
ii) all the variables are not final
iii) ...
iv) No error

4) Class.forName(....)
What are the usages of forName here?
PlanetAsia Interview Questions:

0) What's the level of jsp,servlet among 1 to 10 by you?

1) is Jsp multithreaded? how? -- "isThreadSafe=true"

2) how to use Thread? -- Runnable interface, Thread class

3) How to catch an exception in Jsp (or servlet)? -- try-catch-finally, throws

4) Java supports whichever OOP concept? -abstract, encapsulation, polimorphism, inheritance

5) Difference between Abstract and Interface?

6) Difference between jsp:include and include action?

7) Action Elements : usebean, getproperty, setproperty, include, forward, param, plugin


1) What are the seven type of Listener?

StartupListener,..............

2) JspPage is a interface. But HttpJspPage extends JspPage.

3) Whats the difference between ServletContext and ServletRequest in RequestDispature.


What is JavaServer Pages technology?
JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically-generated content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the format and syntax of the page.

How does the JavaServer Pages technology work?
JSP pages use XML tags and scriptlets written in the Java programming language to encapsulate the logic that generates the content for the page. It passes any formatting (HTML or XML) tags directly back to the response page. In this way, JSP pages separate the page logic from its design and display.
JSP technology is part of the Java technology family. JSP pages are compiled into servlets and may call JavaBeans components (beans) or Enterprise JavaBeans components (enterprise beans) to perform processing on the server. As such, JSP technology is a key component in a highly scalable architecture for web-based applications.
JSP pages are not restricted to any specific platform or web server. The JSP specification represents a broad spectrum of industry input.

What is a servlet?
A servlet is a program written in the Java programming language that runs on the server, as opposed to the browser (applets). Detailed information can be found at http://java.sun.com/products/servlet.

Why do I need JSP technology if I already have servlets?
JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

Where can I get the most current version of the JSP specification?
The JavaServer Pages 2.0 specification is available for download from here.
How does the JSP specification relate to the Java 2 Platform, Enterprise Edition?
The JSP 2.0 specification is an important part of the Java 2 Platform, Enterprise Edition 1.3. Using JSP and Enterprise JavaBeans technologies together is a great way to implement distributed enterprise applications with web-based front ends.

Which web servers support JSP technology?
There are a number of JSP technology implementations for different web servers. The latest information on officially-announced support can be found at http://java.sun.com/products/jsp/industry.html.

Is Sun providing a reference implementation for the JSP specification?
The J2EE SDK is a reference implementation of the JavaTM 2 Platform, Enterprise Edition. Sun adapts and integrates the Tomcat JSP and Java Servlet implementation into the J2EE SDK. The J2EE SDK can be used as a development enviroment for applications prior to their deployment and distribution.
Tomcat a free, open-source implementation of Java Servlet and JavaServer Pages technologies developed under the Jakarta project at the Apache Software Foundation, can be downloaded from http://jakarta.apache.org/downloads/binindex.html Tomcat is available for commercial use under the ASF license from the Apache web site in both binary and source versions. An implementation of JSP technology is part of the J2EE SDK.

How is JSP technology different from other products?
JSP technology is the result of industry collaboration and is designed to be an open, industry-standard method supporting numerous servers, browsers and tools. JSP technology speeds development with reusable components and tags, instead of relying heavily on scripting within the page itself. All JSP implementations support a Java programming language-based scripting language, which provides inherent scalability and support for complex operations.

Where do I get more information on JSP technology?
The first place to check for information on JSP technology is http://java.sun.com/products/jsp/. This site includes numerous resources, as well as pointers to mailing lists and discussion groups for JSP technology-related topics.

What is a JSP page?
A JSP page is a page created by the web developer that includes JSP technology-specific and custom tags, in combination with other static (HTML or XML) tags. A JSP page has the extension .jsp; this signals to the web server that the JSP engine will process elements on this page.
The exact format of a JSP page is described in the JSP specification..

How do JSP pages work?
A JSP engine interprets tags, and generates the content required - for example, by calling a bean, accessing a database with the JDBC API or including a file. It then sends the results back in the form of an HTML (or XML) page to the browser. The logic that generates the content is encapsulated in tags and beans processed on the server.

Does JSP technology require the use of other Java platform APIs?
JSP pages are typically compiled into Java platform servlet classes. As a result, JSP pages require a Java virtual machine that supports the Java platform servlet specification.

How is a JSP page invoked and compiled?
Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.

What is the syntax for JavaServer Pages technology?
The syntax card and reference c an be viewed or downloaded from our website.

Can I create XML pages using JSP technology?
Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output. See the white paper Developing XML Solutions with JavaServer Pages Technology (PDF) for details.

Can I generate and manipulate JSP pages using XML tools?
The JSP 1.2 specification describes a mapping between JSP pages and XML documents. The mapping enables the creation and manipulation of JSP pages using XML tools.

How do I use JavaBeans components (beans) from a JSP page?
The JSP specification includes standard tags for bean use and manipulation. The useBean tag creates an instance of a specific JavaBeans class. If the instance already exists, it is retrieved. Otherwise, it is created. The setProperty and getProperty tags let you manipulate properties of the given object. These tags are described in more detail in the JSP specification and tutorial.

What is the difference between an Interface and an Abstract class?
An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.

What is the purpose of garbage collection in Java, and when is it used?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Describe synchronization in respect to multithreading.
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

Explain different way of using thread?
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

What are pass by reference and passby value?
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

What is HashMap and Map?
Map is Interface and Hashmap is class that implements that.

Difference between HashMap and HashTable?
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is non synchronized and Hashtable is synchronized.
Difference between Vector and ArrayList?
Vector is synchronized whereas arraylist is not.

Difference between Swing and Awt?
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

What is the difference between a constructor and a method?
A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

What is an Iterators?
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.

What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
TOP

What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

What is final?
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

What if the main method is declared as private?
The program compiles properly but at runtime it will give "Main method not public." message.

What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".

What if I write static public void instead of public static void?
Program compiles and runs properly.

What if I do not provide the String array as the argument to the method?
Program compiles but throws a runtime error "NoSuchMethodError".

What is the first argument of the String array in main method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.

If I do not provide any arguments on the command line, then the String array of Main method will be empty of null?
It is empty. But not null.

How can one prove that the array is not null but empty?
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.

What environment variables do I need to set on my machine in order to be able to run Java programs?
CLASSPATH and PATH are the two variables.

Can an application have multiple classes having main method?
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

Can I have multiple main methods in the same class?
No the program fails to compile. The compiler says that the main method is already defined in the class.


Do I need to import java.lang package any time? Why ?
No. It is by default loaded internally by the JVM.

Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.

What are Checked and UnChecked Exception?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method· Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often
cannot be.

What is Overriding?
When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.

What are different types of inner classes?
Nested top-level classes, Member classes, Local classes, Anonymous classes
Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.
Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.
Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.
Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.


Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
Yes the imports are checked for the semantic validity at compile time. The code containing above line of Import will not compile. It will throw an error saying,can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;




Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.

What is the difference between declaring a variable and defining a variable?
In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

What is the default value of an object reference declared as an instance variable?
null unless we define it explicitly.

Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

What type of parameter passing does Java support?
Java supports both pass by value as well as pass by reference.

Primitive data types are passed by reference or pass by value?
Primitive data types are passed by value.

Objects are passed by value or by reference?
Objects are always passed by reference. Thus any modifications done to an object inside the called method will always reflect in the caller method.

What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

How do I serialize an object to a file?
The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.

Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.

How can I customize the seralization process? i.e. how can one have a control over the serialization
process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

What is the common usage of serialization?
Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.


What is Externalizable interface?
Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.

What happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.

What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.

What happens to the static fields of a class during serialization? Are these fields serialized as a part of each serialized object?
Yes the static fields do get serialized. If the static field is an object then it must have implemented Serializable interface. The static fields are serialized as a part of every object. But the commonness of the static fields across all the instances is maintained even after serialization.


Does Java provide any construct to find out the size of an object?
No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java.

Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code...

long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();
System.out.println ("Time taken for execution is " + (end - start));
Remember that if the time taken for execution is too small, it might show that it is taking zero
milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing.

What are wrapper classes?
Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.

Why do we need wrapper classes?
It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.

What are checked exceptions?
Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.


What are runtime exceptions?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

What is the difference between error and an exception?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).

How to create custom exceptions?
Your class should extend class Exception, or some more specific type thereof.

If I want an object of my class to be thrown as an exception object, what should I do?
The class should extend from Exception class. Or you can extend your class from some more precise exception type also.

If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

What happens to an unhandled exception?
One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

How does an exception permeate through the code?
An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

What are the different ways to handle exceptions?
There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions.
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.


What is the basic difference between the 2 approaches to exception handling...1> try catch block and 2> specifying the candidate exceptions in the throws clause?
When should you use which approach?
In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.



Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

If I write return at the end of the try block, will the finally block still execute?
Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

If I write System.exit (0); at the end of the try block, will the finally block still execute?
No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.


What is diffrence between StateFul and Stateless Session Bean?
A Stateful Session Bean is a bean that is designed to service business processes that span multiple method requests or transactions. Stateful Session beans retain state on behalf of an individual client. Stateless Session Beans do not maintain state.
EJB containers pools stateless session beans and reuses them to service many clients. Stateful session beans can be passivated and reused for other clients. But this involves I/O bottlenecks. Because a stateful session bean caches client conversation in memory, a bean failure may result in loosing the entire client conversation. Therefore, while writing a stateful session bean the bean developer has to keep the bean failure and client conversation loss in mind.

In case of stateless session beans, client specific data has to be pushed to the bean for each method invocation which will result in increase in the network traffic. This can be avoided in a number of ways like persisting the client specific data in database or in JNDI. But this also results in I/O performance bottlenecks.

If the business process spans multiple invocations thereby requiring a conversation then stateful session bean will be the ideal choice. On the other hand, if business process lasts only for a single method call, stateless session bean model suits.

Stateful session beans remembers the previous request and responses. But stateless beans do not. stateful does not have pooling concept, whereas the stateless bean instances are pooled

What is difference between BeanMangedPersistance and ContainerMangedPersistance?
CMP: Tx behaviour in beans are defined in transaction attributes of the methods
BMP: Programmers has to write a code that implements Tx behaviour to the bean class.
Tuned CMP entity beans offer better performance than BMP entity beans. Moving towards the CMP based approach provides database independence since it does not contain any database storage APIs within it. Since the container performs database operations on behalf of the CMP entity bean, they are harder to debug. BMP beans offers more control and flexibility that CMP beans.
Diff 1) In BMP you will take care of all the connection and you write the SQL code inside the bean whereas in CMP the container will take care of it
Diff 2) The BMP is not portable across all DB's.whereas the CMP is

Draw and explain MVC architecture?
MVC Architecture is Module- View-Controller Architecture. Controller is the one which controls the flow of application / services the requests from the View. Module is the other layer which performs the exact operations. Each layer should be loosely coupled as much as possible.
Difference between forward(request,response) and SendRedirect(url) i n Servlet?
With Forward, request & response would be passed to the destination URL which should be relative (means that the destination URL shud be within a servlet context). Also, after executing forward method, the control will return back to the same method from where the forward method was called. All the opposite to the above points apply to sendRedirect.
(OR)The forward will redirect in the application server itself. It does not come to the client. whereas Response.sendredirect() will come to the client and go back ...ie. URL appending will happen.

What is Synchornize?
Synchronize is a technique by which a particular block is made accessible only by a single instance at any time. (OR) When two or more objects try to access a resource, the method of letting in one object to access a resource is called sync

How to prevent Dead Lock?
Using synchronization mechanism. For Deadlock avoidance use Simplest algorithm where each process tells max number of resources it will ever need. As process runs, it requests resources but never exceeds max number of resources. System schedules processes and allocates resoures in a way that ensures that no deadlock results.
Explain different way of using thread? :
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help

what are pass by reference and passby value?
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.
(9)How Servlet Maintain Session and EJB Maintain Session?
Servlets maintain session in ServleContext and EJB's in EJBContext.
Explain DOM and SAX Parser?
DOM parser is one which makes the entire XML passed as a tree Structure and will have it in memory. Any modification can be done to the XML.
SAX parser is one which triggers predefined events when the parser encounters the tags in XML. Event-driven parser. Entire XML will not be stored in memory. Bit faster than DOM. NO modifications can be done to the XML.

What is HashMap and Map?
Map is Interface and Hashmap is class that implements that and its not serialized HashMap is
non serialized and Hashtable is serialized

Difference between HashMap and HashTable?
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time.

Difference between Vector and ArrayList?
Vector is serialized whereas arraylist is not

Difference between Swing and Awt?
AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

Explain types of Enterprise Beans?
Session beans -> Associated with a client and keeps states for a client
Entity Beans -> Represents some entity in persistent storage such as a database

What is enterprise bean?
 Server side reusable java component
 Offers services that are hard to implement by the programmer
 Sun: Enterprise Bean architecture is a component architecture for the deployment and development of component-based distributed business applications. Applications written using enterprise java beans are scalable, transactional and multi-user secure. These applications may be written once and then deployed on any server plattform that supports enterprise java beans specification.
 Enterprise beans are executed by the J2EE server.

First version 1.0 contained session beans, entity beans were not included.
Entity beans were added to version 1.1 which came out during year 1999.
Current release is EJB version 1.2

Services of EJB?
Database management
–Database connection pooling
–DataSource, offered by the J2EE server. Needed to access connection pool of the server.
–Database access is configured to the J2EE server -> easy to change database / database driver
Transaction management
–Distributed transactions
–J2EE server offers transaction monitor which can be accessed by the client.
Security management
–Authetication
–Authorization
–encryption
Enterprise java beans can be distributed /replicated into separate machines

lDistribution/replication offers
–Load balancing, load can be divided into separate servers.
–Failover, if one server fails, others can keep on processing normally.
–Performance, one server is not so heavy loaded. Also, for example Weblogic has thread pools for improving performance in one server.

When to choose EJB?
Server will be heavy loaded
–Distribution of servers helps to achieve better performance.
Server should have replica for the case of failure of one server.
–Replication is invisible to the programmer
Distributed transactions are needed
–J2EE server offers transaction monitor that takes care of transaction management.
–Distributed transactions are invisible to the programmer
 Other services vs. money
Weblogic J2EE server ~ 80 000 mk and Jbuilder X Professional Edition ~ 5 000mk

Why not to use free J2EE servers?
–no tecnical support
–harder to use (no graphical user interface ...)
–no integration to development tools (for example, Jbuilder)
–Bugs? Other problems during project?

Alternative:Tuxedo
 Tuxedo is a middleware that offers scalability services and transaction monitors.
 C or C++ based.
 Can be used with Java client by classes in JOLT package offered by BEA.
Faster that J2EE server?

Harder to program?
Harder to debug?
Implementation is platform dependent.


J2EE server offers
 DataSource.
–Object that can be used to achieve database connection from the connection pool.
–Can be accessed by the interface DataSource
 Transaction monitor
–Can be accessed by the interface UserTransaction.
 Java Naming and the Directory Service

Java Naming and the Directory Service
 Naming service is needed to locate beans home interfaces or other objects (DataSource, UserTransaction)
–For example, jndi name of the DataSource
 Directory service is needed to store and retrieve properties by their name.
–jndi name: java:comp/env/propertyName

XML – deployment descriptor
ejb-jar.xml + server-specific xml- file Which is then Packed in a jar – file together with bean classes.
Beans are packaged into EJB JAR file , Manifest file is used to list EJB’s and jar file holding Deployment descriptor.

Session Bean
Developer programs three classes:
–Home interface, contains methods for creating (and locating for entity beans) bean instances.
–Remote interface, contains business methods the bean offers.
–Bean class, contains the business logic of the enterprise bean.

Entity Beans
 Represents one row in the database.
–Easy way to access database
–business logic concept to manipulate data.
 Container managed persistence vs. bean managed persistence.

Programmer creates three or four classes:
–Home interface for locating beans
–Remote interface that contains business methods for clients.
–Bean class that implements bean’s behaviour.
–Primary key class – that represents primary key in the database. Used to locate beans.
Primary key class is not needed if primary key is a single field that could be

When to use which bean?
Entity beans are effective when application wants to access one row at a time. If many rows needs to be fetched, using session beans can be better alternative
ava class (for example, Integer).

Entity beans are efficient when working with one row at a time
Cause a lot of network trafic.
Session Beans are efficient when client wants to access database directry.
–fetching/updating multiple rows from the database

Explain J2EE Arch?
Normally, thin-client multitiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multithreading, resource pooling, and other complex low-level details.
The component-based and platform-independent J2EE architecture makes J2EE applications easy to write because business logic is organized into reusable components and the J2EE server provides underlying services in the form of a container for every component type. Because you do not have to develop these services yourself, you are free to concentrate on solving the business problem at hand.
Containers and Services
Component are installed in their containers during deployment and are the interface between a component and the low-level platform-specific functionality that supports the component. Before a web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.
The assembly process involves specifying container settings for each component in the J2EE application and for the J2EE application itself. Container settings customize the underlying support provided by the J2EE Server, which include services such as security, transaction management, Java Naming and Directory InterfaceTM (JNDI) lookups, and remote connectivity.
Figure : J2EE Server and Containers
Container Types
The deployment process installs J2EE application components in the following types of J2EE containers. The J2EE components and container addressed in this tutorial are shown in Figure 5.
An Enterprise JavaBeans (EJB) container manages the execution of all enterprise beans for one J2EE application. Enterprise beans and their container run on the J2EE server.
A web container manages the execution of all JSP page and servlet components for one J2EE application. Web components and their container run on the J2EE server.
An application client container manages the execution of all application client components for one J2EE application. Application clients and their container run on the client machine.
An applet container is the web browser and Java Plug-in combination running on the client machine.


1.What is the diffrence between an Abstract class and Interface?
Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code.
A class can implement any number of interfaces, but subclass at most one abstract class.
An abstract class can have nonabstract methods. All methods of an interface are abstract.
An abstract class can have instance variables. An interface cannot.
An abstract class can define constructor. An interface cannot.
An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package).
An abstract class inherits from Object and includes methods such as clone() and equals().

2. What is a user defined exception?
User-defined exceptions may be implemented by defining a class to respond to the exception and
embedding a throw statement in the try block where the exception can occur or declaring that the method throws the exception (to another method where it is handled).
The developer can define a new exception by deriving it from the Exception class as follows:
code: public class MyException extends Exception
{/* class definition of constructors (but NOT the exception
handling code) goes here */ public MyException() {
super();
}
public MyException(
String errorMessage )
{
super( errorMessage );
}}
The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax.
code: throw new MyException("I threw my own exception.")
To handle the exception within the method where it is thrown, a catch statement that handles
MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax:
code: public myMethodName() throws MyException


3. What do you know about the garbage collector?
Garbage collector is a runtime component of Java which sits on top of the heap: memory area from which Java objects are created and periodically scans it for objects which are eligible to be reclaimed when there are no references to these objects in the program. There is simply no way to force garbage collection, but you can suggest your intention of getting the object garbage collecetd to Java Virtual Machine by calling
code:
System.gc()

4. What is the difference between C++ & Java?
Well as Bjarne Stroustrup says "..despite the syntactic similarities, C++ and Java are very different
languages. In many ways, Java seems closer to Smalltalk than to C++..". Here are few I discovered:
Java is multithreaded
Java has no pointers
Java has automatic memory management (garbage collection)
Java is platform independent (Stroustrup may differ by saying "Java is a platform" )
Java has built-in support for comment documentation
Java has no operator overloading
Java doesn’t provide multiple inheritance
There are no destructors in Java


Can a String extend a class?
no

What is the difference between Swing and AWT components?
AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.

Why Java does not support pointers?
Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers. This is why Java and C# shine.

Parsers? DOM vs SAX parser
parsers are fundamental xml components, a bridge between XML documents and applications that process that XML. The parser is responsible for handling xml syntax, checking the contents of the document against constraints established in a DTD or Schema.

Sno
DOM
SAX
1
Tree of nodes
Sequence of events
2.
Memory: Occupies more memory, preferred for small XML documents.
does'nt use any memory preferredfor large documents
3.
Slower at runtime
Faster at runtime
4.
stored as objects
objects are to be created
5.
Programmatically easy, since objects are to reffered
Need to write code for creating objects
6.
Ease of navigation not possible as processes the document
backward navigation is not possible as it sequentially processes the document



Networking

What two protocols are used in Java RMI technology?
Java Object Serialization and HTTP. The Object Serialization protocol is used to marshal call and return data. The HTTP protocol is used to "POST" a remote method invocation and obtain return data when circumstances warrant.

What is difference between Swing and JSF?
The key difference is that JSF runs on the server in a standard Java servlet container like Tomcat or WebLogic and display HTML or some other markup to the client.

What is JSF?
JSF stands for JavaServer Faces, or simply Faces. It is a framework for building Web-based user interfaces in Java. Like Swing, it provides a set of standard widgets such as buttons, hyperlinks, checkboxes, ans so on.

JSP

What is difference between custom JSP tags and beans?
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use Custom JSP tags, you need to define three separate components:
1. the tag handler class that defines the tag's behavior
2. the tag library descriptor file that maps the XML element names to the tag implementations
3. the JSP file that uses the tag library

When the first two components are done, you can use the tag by using taglib directive:
<%@ taglib uri="xxx.tld" prefix="..." %>
Then you are ready to use the tags you defined. Let's say the tag prefix is test:
MyJSPTag or
JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags

to declare a bean and use

to set value of the bean class and use
<%=identifier.getclassField() %>
to get value of the bean class.
Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and
accessible forms. There are several differences:
o Custom tags can manipulate JSP content; beans cannot.
o Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
o Custom tags require quite a bit more work to set up than do beans.
o Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.
o Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.


what are the two kinds of comments in JSP and whats the difference between them
<%-- JSP Comment --%>


What mechanisms are used by a Servlet Container to maintain session information?
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information

Difference between GET and POST
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy.
In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.

What is session?
The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.

What is servlet mapping?
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.

What is servlet context ?
The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. (answer supplied by Sun's tutorial).

Which interface must be implemented by all servlets?
Servlet interface.

EJB
When to use CMP and BMP
The design situation speaks for which Bean type to use.
o Use BMP when you are writing a solution for an application which is supposed to be higly portable and highly transactionable.
o Use BMP if there are not much transactions and it is known that you will be tied to one type of storage medium.
3. What is session Facade
Session Facade is a design pattern to access the Entity bean through local interface than acessing directly. It increases the performance over the network. In this case we call session bean which on turn call entity bean

what is the difference between session and entity bean?
Session beans are business data and have not any persistance. Entity beans are Data Objects and have more persistance.


J2EE

What is N-tier architecture
N-tier architecture is based on a multilayer communication mechanism between components. Presentation Layer which is the UI, Business Logic Layer which is the J2EE portion, and the Data Layer which is the DB.

How do you check the performance tunning for j2ee project?
answer is on the way

What is difference between J2EE 1.3 and J2EE 1.4?
J2EE 1.4 is an enhancement version of J2EE 1.3. It is the most complete Web services platform ever.
J2EE 1.4 includes:
o Java API for XML-Based RPC (JAX-RPC 1.1)
o SOAP with Attachments API for Java (SAAJ),
o Web Services for J2EE(JSR 921)
o J2EE Management Model(1.0)
o J2EE Deployment API(1.1)
o Java Management Extensions (JMX),
o Java Authorization Contract for Containers(JavaACC)
o Java API for XML Registries (JAXR)
o Servlet 2.4
o JSP 2.0
o EJB 2.1
o JMS 1.1
o J2EE Connector 1.5
The J2EE 1.4 features complete Web services support through the new JAX-RPC 1.1 API, which supports service endpoints based on servlets and enterprise beans. JAX-RPC 1.1 provides interoperability with Web services based on the WSDL and SOAP protocols.
The J2EE 1.4 platform also supports the Web Services for J2EE specification (JSR 921), which defines deployment requirements for Web services and utilizes the JAX-RPC programming model.
In addition to numerous Web services APIs, J2EE 1.4 platform also features support for the WS-I Basic Profile 1.0. This means that in addition to platform independence and complete Web services support, J2EE 1.4 offers platform Web services interoperability.
The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which defines the information model for J2EE management, including the standard Management EJB (MEJB). The J2EE Management 1.0 API uses
the Java Management Extensions API (JMX).
The J2EE 1.4 platform also introduces the J2EE Deployment 1.1 API, which provides a standard API for deployment of J2EE applications.
The J2EE 1.4 platform includes security enhancements via the introduction of the Java Authorization Contract for Containers (JavaACC). The JavaACC API improves security by standardizing how authentication mechanisms are integrated into J2EE containers.
The J2EE platform now makes it easier to develop web front ends with enhancements to Java Servlet and JavaServer Pages (JSP) technologies. Servlets now support request listeners and enhanced filters. JSP technology has simplified the page and extension development models with the introduction of a simple expression language, tag files, and a simpler tag extension API, among other features. This makes it easier than ever for developers to build JSP-enabled pages, especially those who are familiar with scripting languages. Other enhancements to the J2EE platform include the J2EE Connector Architecture, which provides incoming resource adapter and Java Message Service (JMS) pluggability. New features in Enterprise JavaBeans (EJB) technology include Web service endpoints, a timer service, and enhancements to EJB QL and message-driven beans. The J2EE 1.4 platform also includes enhancements to deployment descriptors. They are now defined using


XML Schema which can also be used by developers to validate their XML structures.
Note: The above information comes from SUN released notes.
5. Do you have to use design pattern in J2EE project?
Yes. If I do it, I will use it. Learning design pattern will boost my coding skill.
6. Is J2EE a super set of J2SE?
Yes

JMS

What is JMS?
Java Message Service is the new standard for interclient communication. It allows J2EE application
components to create, send, receive, and read messages. It enables distributed communication that is loosely coupled, reliable, and asynchronous.

what type messaging is provided by JMS
Both synchronous and asynschronous

How may messaging models do JMS provide for and what are they?
JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing


What is WML?
Wireless Markup Language (WML) page is delivered over Wireless Application Protocol (WAP) and the network configuration requires a gateway to translate WAP to HTTP and back again. It can be generated by a JSP page or servlet running on the J2EE server.

What is the difference between component and Class?
A component is a finished class, whereas a class is a design schema. A component is ready to be used as a member of a class and a class may consist of many components(classes). Component and class names may be exchangeble in context. For example, a Button is a component and also a class. MyWindow class may contain several buttons.

What is your favorite sport?
My answer would be football if the interviewer is a man.

What is JUnit?
JUnit is a unit-testing framework. Unit-testing is a means of verifying the results you expect from your Classes. If you write your test before hand and focus your code on passing the test you are more likely to end up with simple code that does what it should and nothing more. Unit-testing also assists in the refactoring process. If your code passes the unit-test after refactoring you will know that you haven't introduced any bugs to it.

What is the difference between Java and PL/SQL?
Java is a general programming language. PL/SQL is a database query languague, especially for Oracle database.

Explain RMI Architecture?

RMI uses a layered architecture, each of the layers could be enhanced or replaced without affecting the rest of the system. The details of layers can be summarised as follows:
Application Layer: The client and server program
Stub & Skeleton Layer: Intercepts method calls made by the client/redirects these calls to a remote RMI service.
Remote Reference Layer: Understands how to interpret and manage references made from clients to the remote service objects.
Transport layer: Based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.

How do you communicate in between Applets & Servlets ?
We can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection and "tunnel" to the web server. The server then passes this information to the servlet in the normal way. Basically, the applet pretends to be a web browser, and the servlet doesn't know the difference. As far as the servlet is concerned, the applet is just another HTTP client.

What is the use of Servlets ?
Servlets may be used at different levels on a distributed framework. The following are some examples of servlet usage:
To accept form input and generate HTML Web pages dynamically.
As part of middle tiers in enterprise networks by connecting to SQL databases via JDBC.
In conjunction with applets to provide a high degree of interactivity and dynamic Web content generation.
For collaborative applications such as online conferencing.
A community of servlets could act as active agents which share data with each other.
Servlets could be used for balancing load among servers which mirror the same content.
Protocol support is one of the most viable uses for servlets. For example, a file service can start with NFS and move on to as many protocols as desired; the transfer between the protocols would be made transparent by Servlets. Servlets could be used for tunneling over HTTP to provide chat, newsgroup or other file server functions.

What is JDBC? How do you connect to the Database ?
JDBC stands for Java Database Connectivity. Its a set of programming APIs which allow easy connection to a wide range of databases through Java programs.
To connect to the database we will need to load the database driver and then request a connection as below: code:
Class.forName([LOCATION OF DRIVER]);Connection jdbcConnection = DriverManager.getConnection ([LOCATION OF DATASOURCE]);

In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?
We can use the setTimeout method to use delay time and then the window.open method to open the new page.
The script could be something like the following. We could call the doPopup() method on the click event of the button placed on our webpage.





11. What is the difference between RMI & Corba ?
The most significant difference between RMI and CORBA is that CORBA was made specifically for interoperability across programming languages. That is CORBA fosters the notion that programs can be built to interact in multiple languages. The server could be written in C++, the business logic in Python, and the front-end written in COBOL in theory. RMI, on the other hand is a total Java solution, the interfaces, the implementations and the clients--all are written in Java.
RMI allows dynamic loading of classes at runtime. In a multi-language CORBA environment, dynamic class loading is not possible. The important advantage to dynamic class loading is that it allows arguments to be passed in remote invocations that are subtypes of the declared types. In CORBA, all types have to be known in advance.
RMI (as well as RMI/IIOP) provides support for polymorphic parameter passing, whereas strict CORBA does not.
CORBA does have support for multiple languages which is good for some applications, but RMI has the advantage of being dynamic, which is good for other applications.

12. What are the services in RMI ?
An RMI "service" could well be any Java method that can be invoked remotely. The other service is the JRMP RMI naming service which is a lookup service.

13. How will you initialize an Applet ?
Write my initialization code in the applets init method or applet constructor.

14. What is the order of method invocation in an Applet ?
public void init() : Initialization method called once by browser.
public void start() : Method called after init() and contains code to start processing. If the user leaves the page and returns without killing the current browser session, the start () method is called without being preceded by
init ().
public void stop() : Stops all processing started by start (). Done if user moves off page.
public void destroy() : Called if current browser session is being terminated. Frees all resources used by applet.

15. When is update method called ?
Whenever a screen needs redrawing (e.g., upon creation, resizing, validating) the update method is called. By default, the update method clears the screen and then calls the paint method, which normally contains all the drawing code.

16. How will you pass values from HTML page to the Servlet ?
First we put the values to be passed inside a HTML form and then call the servlet in the form action. To catch the form fields values we simply call the getParameter method of the HttpServletRequest, supplying the parameter name as an argument. The return value is a String corresponding to the first occurrence of that parameter name.
An empty String is returned if the parameter exists but has no value, and null is returned if there was no such parameter.
If the parameter could potentially have more than one value we should call getParameterValues instead of getParameter. This returns an array of strings. To get a full list of parameters we can use getParameterNames which returns an Enumeration, each entry of which can be cast to a String and used in a getParameter call.

18. How will you communicate between two Applets ?
The simplest method is to use the static variables of a shared class since there's only one instance of the class and hence only one copy of its static variables. A slightly more reliable method relies on the fact that all the applets on a given page share the same AppletContext. We obtain this applet context as follows:


AppletContext ac = getAppletContext();
AppletContext provides applets with methods such as getApplet(name), getApplets(),getAudioClip, getImage, showDocument and showStatus().

19. What are statements in JAVA ?
Statements are equivalent to sentences in natural languages. A statement forms a complete unit of execution.
The following types of expressions can be made into a statement by terminating the expression with a semicolon
Assignment expressions
Any use of ++ or --
Method calls
Object creation expressions
These kinds of statements are called expression statements.
In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. A control flow statement regulates the order in which statements get executed. the for loop and the if statement are both examples of control flow statements.

20. What is JAR file ?
JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to make one simple, smaller file to ease Applet downloading. Normally when a browser encounters an applet, it goes and downloads all the files, images, audio, used by the Applet separately. This can lead to slower downloads.

21. What is JNI ?
JNI is an acronym of Java Native Interface. Using JNI we can call functions which are written in other languages from Java. Following are its advantages and disadvantages:
Advantages:
You want to use your existing library which was previously written in other language.
You want to call Windows API function.
For the sake of execution speed.
You want to call API function of some server product which is in c or c++ from java client.

Disadvantages:
You can’t say write once run anywhere.
Difficult to debug runtime error in native code.
Potential security risk.
You can’t call it from Applet.

22. What is the base class for all swing components ?
JComponent (except top-level containers)

23. What is JFC ?
Java Foundation Classes include:
Standard AWT 1.1
Accessibility interface
Lightweight components: which are user interface components that do not subclass an existing AWT interface element. They do not use native interface elements as provided by the underlying windowing system. This means that they are less limiting than standard AWT components.
Java look and feel Support for native look and feel Services such as Java2D and Drag and Drop





24. What is Difference between AWT and Swing ?
Swing provides a richer set of components than AWT. They are 100% Java-based. AWT on the other hand was developed with the mind set that if a component or capability of a component weren’t available on one platform, it wouldn’t be available on any platform. Due to the peer-based nature of AWT, what might work on one implementation might not work on another, as the peer-integration might not be as robust. There are a few other advantages to Swing over AWT: Swing provides both additional components and added functionality to AWT-replacement components
Swing components can change their appearance based on the current "look and feel" library that's being used. Swing components follow the Model-View-Controller (MVC) paradigm, and thus can provide a much more flexible UI.
Swing provides "extras" for components, such as:
Icons on many components
Decorative borders for components
Tool tips for components
Swing components are lightweight (less resource intensive than AWT)
Swing provides built-in double buffering
Swing provides paint debugging support for when you build your own components
Swing also has a few disadvantages:
It requires Java 2 or a separate JAR file
If you're not very careful when programming, it can be slower than AWT (all components are drawn)
Swing components that look like native components might not act exactly like native components

25. Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times?
Where 3 processes are started or 3 threads are started ?
3 separate processes are started.

26. How does thread synchronization occurs inside a monitor ?
[Question not too clear to me ]
The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in that it watches over a sequence of code, making sure only one thread at a time executes the code. Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code it must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code. When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object.

27. How will you call an Applet using a Java Script function ?
Like this:
document.appletName.methodCall(...)
Does not work with IE though

28. Is there any tag in HTML to upload and download files ?
I am not aware of HTML tags to help me upload a file, we would certianly need some server side scripting to process that. We can certainly use HTML to provide a download hyperlink as follows:
code:
Click here to download

29. Why do you Canvas ?
The Canvas class of java.awt is used to provide custom drawing and event handling. It provides a general GUI component for drawing images and text on the screen. It does not support any drawing methods of its own, but provides access to a Graphics object through its paint() method. The paint() method is invoked upon the creation and update of a canvas so that the Graphics object associated with a Canvas object can be updated.


30. How can you push data from an Applet to Servlet ?
By using the java.net packages to create a direct network connection; or by invoking a remote method using Java's remote method invocation (RMI) interface or by using CORBA. (Any rancher would like to add details here?)

31. What are 4 drivers available in JDBC ?
34. And What situation , each of the 4 drivers used ?
Type 1: JDBC-ODBC Bridge
The type 1 driver, JDBC-ODBC Bridge, translates all JDBC calls into ODBC (Open DataBase Connectivity) calls and sends them to the ODBC driver. As such, the ODBC driver, as well as, in many cases, the client database code, must be present on the client machine. May be used when an ODBC driver has already been installed on client machine and performance is not an issue.
Type 2: Native-API/partly Java driver
JDBC driver type 2 -- the native-API/partly Java driver -- converts JDBC calls into database-specific calls for databases such as SQL Server, Informix, Oracle, or Sybase. The type 2 driver communicates directly with the database server; therefore it requires that some binary code be present on the client machine. Can be used when application is not for internet.
Type 3: Net-protocol/all-Java driver
JDBC driver type 3 -- the net-protocol/all-Java driver -- follows a three-tiered approach whereby the JDBC database requests are passed through the network to the middle-tier server. The middle-tier server then translates the request (directly or indirectly) to the database-specific native-connectivity interface to further the request to the database server. If the middle-tier server is written in Java, it can use a type 1 or type 2 JDBC driver to do this.
Type 3 drivers are best suited for environments that need to provide connectivity to a variety of
DBMS servers and heterogeneous databases and that require significantly high levels of concurrently connected users where performance and scalability are major concerns.
Type 4: Native-protocol/all-Java driver
The native-protocol/all-Java driver (JDBC driver type 4) converts JDBC calls into the vendor-specific database management system (DBMS) protocol so that client applications can communicate directly with the database server. Level 4 drivers are completely implemented in Java to achieve platform independence and eliminate deployment administration issues. Useful for Internet-related applications.

32. How you can know about drivers and database information?By using the methods of
java.sql.DatabaseMetaData interface.

33. If you are truncated using JDBC, How can you know ..that how much data is truncated ?
This can be known using the class DataTruncation. DataTruncation is an exception that reports a DataTruncation warning (on reads) or throws a DataTruncation exception (on writes) when JDBC unexpectedly truncates (meaning that less information was read or written than requested) a data value. So all we should do is write our code using the getDataSize() and getTransferSize() methods of this class in our catch block trapping this SQLException. The getDataSize() returns the number of bytes of data that should have been transferred while the getTransferSize() method returns the number of bytes of data actually transferred. The SQLstate for a DataTruncation is 01004.

38. What is serialization ?
Quite simply, object serialization provides a program the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. A seralizable object must implement the Serilizable interface. We use ObjectOutputStream to write this object to a stream and ObjectInputStream to read it from the stream.

41. To a server method, the client wants to send a value 20, with this value exceeds to 20,. a message should be sent to the client ? What will you do for achieving for this ?
I hope this question is not in terms of RMI. We can use a Servlet or JSP for this, call it using an HTML (or a Servlet or JSP for that matter) and pass the value through a HTML form. We check this request parameter and send a reponse back to browser if value of input parameter exceeds 20.

43. Where the CardLayout is used ?
CardLayout manages two or more components that share the same display space. It lets you use one container (usually a panel) to display one out of many possible component children (like flipping cards on a table). A program can use this layout to show a different child component to different users. For example, the interface shown to an administrator might have additional functionality from the interface shown to a regular user. With card layout, our program can show the appropriate interface depending on the type of user using the program. Another typical use of card layout would be to let end user toggle among different displays and choose the one they prefer. In this case, the program must provide a GUI for the user to make the selection.

44. What is the Layout for ToolBar ?
I did not find any Toolbar class in AWT..ranchers hit me if I am wrong ..

1.What is the diffrence between an Abstract class and Interface?

A Java interface is just that, a purely abstract method interface with no implementation component. An abstract class provides not just an interface, it also provides a (partial) implementation. Java supports multiple interface inheritance, but only single implementation inheritance. Everything else follows from these two.

3. What do you know about the garbage collector?

In addition to what has been written above: all you really know about the garbage collector is that it will run to clear unreferenced objects from the heap before an OutOfMemoryError is thrown.

6. How do you communicate in between Applets & Servlets ?

An applet may use the URL class to submit HTTP requests to invoke a servlet. It's as simple as that. This is not tunneling. Tunneling would be, for instance, used to allow the applet to make RMI calls to server-side Java classes (RMI over HTTP), or to allow a JDBC connection over HTTP.

7. What is the use of Servlets ?

They are components to receive and process requests in some request/response protocol. Most often, they are used to receive and process HTTP requests (HttpServlet). Note that (1) this includes JSPs, as JSPs are just servlets, and (2) this covers lots of protocols that use HTTP as a transport or that can be tunneled over HTTP, such as RMI, JDBC, SOAP, XML-RPC, WebDAV, and so forth.

8. What is JDBC? How do you connect to the Database ?

JDBC is a set of APIs to connect to any row-based data source, usually relational database systems. I would submit that these days, DriverManager.getConnection() is not the best answer you can give to the question "how do you connect to the Database". The preferred way is to use a DataSource wherever possible: code:

Context ctx = new InitialContext();DataSource ds = (DataSource)ctx.lookup(
"java:comp/env/jdbc/TestDB");Connection conn = ds.getConnection();

The actual data source is set up by/using the application server.



10. What is the difference between Process and Threads ?

The difference between them is mainly the level of isolation; in particular, each process gets its own memory space, where threads belonging to the same process share each other's memory.

12. What are the services in RMI ?

This question is very ambiguous. In addition to the answer given above, you could perhaps say that the distributed garbage collector (DGC) is a service, provided by the RMI implementation to the application software. Briefly, the DGC keeps track of the number of remote references to a given exported (RMI-callable) object that exist. When no more remote references exist, the DGC can notify the object using the Unreferenced interface. It will also start cleaning up its own internal bookkeeping for that object since no-one will be able to call that object anymore.

20. What is JAR file ?
JARs are not always compressed; for software that is not downloaded, but simply installed locally, an uncompressed JAR can be accessed a little faster. The jars in your JRE are a point in case.

26. How does thread synchronization occurs inside a monitor ?
The only thing you could add to the explanation above is that a thread can acquire a monitor lock multiple times, i.e. it is OK to call further methods that synchronize on the same object. The monitor is released only when you've released all the locks.

28. Is there any tag in HTML to upload and download files ?
An in an HTML form will allow file upload. A simple anchor tag will allow file download -- based on the file type (extension and/or MIME type), the browser will decide whether the linked-to contents needs to be displayed in a browser window, launched in an external application, or whether they can only be saved to disk.

30. How can you push data from an Applet to Servlet ?
In practice, a servlet receives only HTTP request, so the answer is to submit a HTTP request with the data in the URL (GET) or the request body (POST), e.g. using java.net.URL.

109. Latest version of JDBC and new features.
The latest version of JDBC is JDBC 3.0 . Some of the new features that are included in it are :
Support for SavePoints
Improved Support CLOB and BLOB data types
Ability to open multiple Resultsets
Addition of Boolean Data type
Retrieval of auto-generated keys

33. If you are truncated using JDBC, How can you know ..that how much data is truncated ?
This can be known using the class DataTruncation. [...] So all we should do is write our code [...] in our catch
block trapping this SQLException.


Ah. But this is actually not true at all.
You've just fallen into one of the biggest traps in the JDBC API. DataTruncation looks like an exception, smells like an exception, but actually is not really an exception. It's a subclass of SQLWarning. SQLWarning objects are not normally thrown, so trying to catch them is a fruitless exercise. After executing a statement, you can retrieve any warnings that have been generated using ResultSet.getWarnings(), Statement.getWarnings() or Connection.getWarnings(). These methods will return the first warning (or null); you can access subsequent warnings (if any) by calling SQLWarning.getNextWarning().

36. In RMI, server object first loaded into the memory and then the stub reference is sent to the client ? or
whether a stub reference is directly sent to the client ?
In the simplest case, you make a Remote object available for remote calls using RemoteStub
UnicastRemoteObject.exportObject(Remote). So usually you first have to create the Remote object and only then can get the stub to send to the client.

37. Suppose server object is not loaded into the memory, and the client request for it , what will happen?
I guess this is where they want to hear about RMI Activation, where rmid will receive the RMI call and create the Remote object on-demand. Basically, Activatable.register() will return a stub that knows how to create your object when it receives a call.

40. What is the difference RMI registry and OSAgent ?
OSAgent, isn't that the VisiBroker CORBA naming service? It may be that OSAgent is to CORBA objects what the RMI registry is to RMI objects, but take that with a pinch of salt, I don't really have a clue. I know very little about CORBA.

41. To a server method, the client wants to send a value 20, with this value exceeds to 20,. a message should be sent to the client ? What will you do for achieving for this ?
I don't see the point of this question. If it's an RMI question, you can either throw an exception or return some kind of code -- like in any ordinary Java method, really. RMI was created to give you Java method call semantics for remote objects. There's no difference.

49. Can you run the product development on all operating systems ?
Well, that depends, doesn't it? On all OSs that have a JVM of the right version, and only insofar as you did not build any OS-specific assumptions in your product, and only if you actually debugged your application on that OS. Java: write once, debug everywhere. Seriously, there are platform-specific bugs, quirks and peculiarities which can cause plenty of headaches for some types of applications.

50. What is the webserver used for running the Servlets ?
I don't understand this question. Webservers don't run servlets. Webservers may have a link to a servlet engine which runs the servlets. Or, conversely, many servlet engines implement full webserver functionality since they're 90% of the way there anyway

51. What is Servlet API used for connecting database ?
The Servlet API cannot be used to connect to a database. But every application server worth its salt supports the JDBC 2.0 and JNDI APIs and allows you to set up DataSources and bind them into the JNDI tree.

52. What is bean ? Where it can be used ?
A JavaBean is basically a Java class which satisfies a few simple rules (it must have a no-arg constructor, properties have getters and setters; actually, you can get around the last rule by supplying a BeanInfo object for your bean). JavaBeans were originally conceived for graphical application builder tools, but that emphasis has shifted considerably and they're now used almost everywhere.

53. What is difference in between Java Class and Bean ?
The rules mentioned above. A Bean can have associated support classes: a BeanInfo class providing information about the bean, its properties and its events, and also property editors and a graphical customizer.

54. Can we send object using Sockets ?
Sure. Why not? Socket I/O is exposed at streams. We can send/receive objects to/from streams using serialization.

55. What is the RMI and Socket ?
I don't understand the question. RMI is built on top of the Java socket API. UnicastRemoteObject creates ServerSockets for exported Remote objects; the client-side stub uses Sockets to connect to these ServerSockets.

56. How to communicate 2 threads each other ?
The only answer I can give is: synchronized access to shared state. That's a very general answer to an equally general question.

60. What is the functionality stubs and skeletons ?
The stub is a client-side class. It implements whatever interface your Remote object implements, but its methods merely marshal the method call information over the wire. The skeleton is a server-side class. It receives the marshalled method calls that the stub generated, and turns them into method calls to the actual Remote object that you wrote. The 1.2 JRMP stub protocol did away with the need for skeletons. It seems to me that the Proxy class introduced in Java 1.3 could replace RMI stubs. I'm not sure why this hasn't happened yet -- probably I'm missing something.
It would be nice to use RMI without bothering with rmic though.
- Peter

101. Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?
Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable

93. What is meant by Servlet? What are the parameters of the service method ?
A Servlet is a java class that extends the request-response model of an webserver. it recieves request from a client performs any neccessary operations..builds a response object and sends it back to the client. The Parameteres of the service method are HttpServletRequest and HttpServletResponse objects

public void service(HttpServletRequest request, HttpServletResponse response)

114. What is meant by cookies ? Explain ?
A Cookie is a small bit of textual information send by an website to the browser with some information about the user. The browser sends it back to the webserver upon subsequent visits of the user to that particular website.

96. What is the difference in between the HTTPServlet and Generic Servlet ? Explain
A GenericServlet is a protocol independent servlet. The HttpServlet class extends the GenericServlet..it is meant specifically for the HTTP protocol

17. Yes I have used the hashtables and dictionary. Here are the differences I found :-
A dictionary is a key-value pair somewhat akin to a hashtable. The crucial difference between the two structures is that a dictionary supports the notion of multi-keyed data whereas a hashtable uses a single object as a key

48. A lightweight component is one that "borrows" the screen resource of an ancestor (which means it has no native resource of its own -- so it's "lighter").
The advantages of creating lightweight components are the following:
The Lightweight component can now have transparent areas by simply not rendering to those areas in its paint() method (although, until we get full shape support from Java2D, the bounding box will remain rectangular). The Lightweight component is "lighter" in that it requires no native data-structures or peer classes. There is no native code required to process lightweight components, hence handling of lightweights is 100% implemented in common java code, which leads to complete consistency across platforms.

62. Difference between Application and Applet
The difference between an application and an applet, is that an applet is used in a browser, and an application, in a stand alone mode. A Java applet is made up of at least one public class that has to be subclassed from java.awt.Applet. The applet is confined to living in the user's Web browser, and the browser's security rules, (or Sun's appletviewer, which has fewer restrictions). In an application, if you want to "show" something, you have to declare one or more panel, and add your stuff in it. In an applet, you only add your stuff directly into your applet. (Well, because an applet is just a kind of panel
8). A Java application is made up of a main() method declared as public static void that accepts a string array argument, along with any other classes that main() calls. It lives in the environment that the host OS provides.

63. Serializable is a tagging interface; it prescribes no methods. It serves to assign the Serializable data type to the tagged class and to identify the class as one which the developer has designed for persistence.

64. Difference between and servlet
Servlets are effectively a Java version of CGI scripts, which are written in Perl, C, C++, UNIX shell scripts, etc. There are however, a few important differences.
When a CGI program (or script) is invoked, what typically happens is that a new process is spawned to handle the request. This process is external to that of the webserver and as such, you have the overhead of creating a new process and context switching, etc. If you have many requests for a CGI script, then you can imagine the consequences! Of course, this is a generalization and there are wrappers for CGI that allow them to run in the same process space as the webserver. I think ISAPI is/was one of these. Java Servlets on the other hand actually run inside the webserver (or Servlet engine). The developer writes the Servlet classes, compiles them and places them somewhere that the server can locate them. The first time a Servlet is requested, it is loaded into memory and cached. From then on, the same Servlet instance is used, with different requests being handled by different threads. Of course, being Java, the compiled Servlet classes can be moved from one Servlet compatible webserver to another very easily. CGI programs or scripts on the other hand may be platform dependent, need to be recompiled or even webserver dependent

65.) An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior.so, we can different implications of same method (that is in interface) in different classes.

69.) In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language (OOPL).

72.) Within a class definition, you can specify functions as being "virtual". Virtual functions can be
re-implemented by sub-classes. Say you declare the function within the class Synchronous:
virtual void getReady(); Whatever your class needs to do to get ready will be done in getReady(). Now, a sub-class (say QuintSynchronous) can also delcare this function:virtual void getReady();

However, it may do something else to get ready. It may, however still wish to call the getReady() function of its parent class, this can always be done by specifying the name of the parent class to distinguish between the own implementation of getReady() and the one of the parent class:
Invariant::getReady();
Purely Virtual functions.
Sometimes, a base class doesn't implement any functionality, but defines a function that the sub-classes necessarily need to provide. The rest of the code can then rely on using this class, no matter what kind of sub-class is used. Such functions are called purely virtual and defined using "=0": void getReady()=0; // I don't
implement anything, but the sub-classes need to !
This is extremely useful when using pointers to an object, as the rest of the code can stay umodified when substituting one sub-class for another, if the rest of the code only depends on the functions declared in the parent-class (for instance Quintessence or Perturbation).

88.) Java has absolutely no control over hardware
Java has no pointers
Java's class declaration syntax is alot easier than C++
Java has no header-files
Java has an automatic garbage collection
Java is multithreaded

New Features in Version2

20/06/2004 – IBM Question For J2EE :

What will be Executed this Command // int i “/u000”;


When will use Two tier Architecture? Three tier Architecture?
Two Tier Architecture :
These are generally data driven, with the application, existing entirely on the client machine while the data base server is deployed some where in the organization.

Three Tier Architecture :
An application is broken up into the three separate logical layers, each with a well defined set of interfaces.

Using in Distributed Environment

Tell me procedure to revert or transverse SQL Statement to print the result set from Bottom to Top.
Ans: Using ‘Order By’ Keyword.

Write notes on RowNum and RowId?
Hexadecimal string representing the unique address of a row in its table.

How to achieve Outer Join?
An OUTER JOIN is used to return all rows that exist in one table, even though corresponding rows do not exist in the joined table.

Note: The Syntax for Outer may differ from database to database. Eg. Oracle (+), MySql LEFT

eg: select f.no,name,remark from first f, second s where f.no = s.no (+);
// all the values in first, matched rows in second. Unmatched columns are NULL.

Difference Between Inner Join/Outer Join?
The EQUIJOIN joins two tables with a common column, in which each is usually the primary key.
eg: select * from first f, second s where f.no=s.no

An OUTER JOIN is used to return all rows that exist in one table, even though corresponding rows do not exist in the joined table.

How do you create a Thread?
i) By extending Thread class
ii) implements Runnable Interface.

Can you call run() method Explicitly?
No. Run method isn’t called by explicitly.

What are the two kinds of Servlets?
1.Generic Servlet
2. Http Servlet.
When will you use which Servlets?
If you are using only HTTP protocol, you can use HttpServlet. Otherwise, you must use GenericServlet.

Can you call the Service Method Explicitly?
No.

How is Servlet safe from Thread?
When you implement the SingleThreadModel interface, your servlet become a thread safe i.e It won’t span the threads.
IsThreadSafe( )

If four requests are coming to a particular servlet, how many instance will be created?
Only one.

JDBC :-

1.Write the code extract result set?
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“jdbc:odbc:dsnName”);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(“select * from emp”);
While(rs.next())
{ System.out.println(rs.getInt(1) + “ “ + rs.getString(2));
}
rs.close();
st.close();
con.close();

2. What will happen, if you declare a class as private?
Compile time error. (Private modifier not allowed here.)

3. Tell me about constructor in thread?

4. How can you make a constructor?

5.What are the available beans in the EJB?
Stateless Session Bean
Stateful Session Bean
Container Managed Persistence Entity Bean
Bean managed Persistence Entity Bean
Message Driven Bean.

6.What is thin client / fat client?
If the Client Program doesn’t depend on the native code is known as thin client. If the client run in the native system and take the code from the native system is known as fat client.

10.Define the default Layout for different components ,window , dialog?
Applet, Window, Dialog : BorderLayout
Panel, Frame : Flow Layout

11.What is GridbackLayout?
You can merge the adjustment grid of the gridLayout is know as gridBackLayout.

12.Suppose I want to place a Component in particular position?
setLayout is null then used the setBounds Method inside the setBounds method X-axis ,Y-axis , height ,width.

14.When do you use, which parser?


15.Is it possible to access the code from the client machine using servlet?
No.

16.How could you expire the cookies?
Using the setMaxAge() function you can expire the cookies.

17.What is JNDI? Which database compact of components?
JNDI is Java Naming Directory Interface.

JNDI is designed to simplify access to the directory infrastructure used in the development of advanced network application. Directories are special type of databases that provide quick access to their data source.

18.What is DTD?
Data Type Definition – DTD are define the rules that setout how a document should be structured, what should be included, what kind of data may be included and what default value to use.
Valid XML documents are well formed documents that also comply with syntax, structural and other rules as defined in DTD.

19.Can you send the document with out DTD?
Yes.

20.What is functionality of Servlet?
Servlets are used to handle the HttpRequest and HttpResponse .

23.In RMI, what Interface is used?
java.rmi.Remote

24.What is overloading ,overwriting ?
Overloading:
i) Must be same method name, different no. of arguments or different types of arguments.

ii) Eventhough the access specifier changed, or , the return type changed, or the exceptions changed, or static used with the same method name and same argument, the error will come.

Overriding:

In an Inheritance hierarchy, when a subclass have the same method signature as it's superclass, the subclass's method overrides the super class's method. So the sub class method is only called.

25. If it possible to presents of two JVM in single system?
No.

26. What will happen, the following 2 methods are in a program?
public int method( ),
public float method() ?
Ans: Compilation Error.

1. How many Servlets in struts?
1. ActionServlet
2. Action

2. What is "Tightly Encapsulated" Class?



3. What are all the functions of web servers?
1. It redirect the request to the corresponding container.
2. It can manage the scalability.

4. What is XSL?
Extensible Style Sheet Language. As the Name implies, is an XML based language used to create the style sheet.

5. What is the difference between the prepared statement and Callable statement?
It allows as to specify the data, prepared statements are parameterized, with each parameter represent as a question mark.

Callable statement are used to execute the stored procedure

6. What is stored procedure?
A Stored procedure is a group of SQL and PL/SQL commands that execute certain tasks. It is created, compiled, and stored in the database, and can be executed by a user or database application.

Advantages: The processing of complex business rules may be performed within the database. Reusability. Good performance.

7. What is the use of finalize method?
Finalize method is used to clean up the memory.

8. What is the use of finally?
Finally is used in combination with try block. Whether the exception is thrown or not, finally block will be executed.

9. How memory management done in java?
Using the Garbage collection.

10. Is there any other port for Apache ( 80 )?


11. Is there any other port for tomcat ( 8080 )?

12. When to use Interface and Abstract class?


13. How to catch Exception?
Using Try Catch.

15. Which is Faster SAX or DOM?
SAX.

17. What is the difference between DTD and Schema?
Schemas have very primitive system of data type. Schemas are not modular, so it is not easy to reuse part of the DTD.
They are not easily extensible: There is nothing like inheritance in the DTD world.

18. Explain URL and URI?
For Example: www.yahoo.com/cricket/score.htm. Here www.yahoo.com is a URL other than URL is a URI.

19. Which one is not used in struts?
(i). Dispatcher (ii) Front Controller (iii) View Helper (iv) Abstract factory

(ii) Front Controller

20. Actually URI mention which one's path?
URI mention the Schema’s path.

21. What are all the available tags in XSL?



















22. Action mapping is derived from which class?


23. How Internationalization done in Struts ?
Using properties files, Bean : message tag

24. What is function in Database?
A function is similar to a Stored Procedure. The main difference between them is that a function returns a value, and a stored procedure doesn’t. Another difference is how a function can be called. It can return a value, be invoked through a SELECT command, and also be used in computations with another function.

25. Which language used in Stored procedure?
PL SQL.

26. Why swing application is slower than AWT?
Because swing doesn’t support peer object native from native machine.

27. What is difference between string buffer and byte array?


29. What is the Temporary Servlet?


30. Which part in Servlet to handle requests?



----------------------------------------
Questions and Tips:
1) Polymorphism (overloading, overriding, public, static)
2) Serialization (steps, coding)
3) Collection
(Interfaces, Classes, duplications, null of keys, null of values, order, synchronized)
4) a) Synchronized.
b) What is the diff. between synchronized block, and snychronized method?
c) What is the different between process and threads?
5) Exception (try, catch, finally, throw, throws, user-defined also)
Types of exception? Diff. between Error and Exception?
6) ConnectionPooling
7) String (Object, LiteralPool, Equals, == )
8) Interface
9) Abstract class (Diff. between abstract class, interface), what is the usage of abstract
class, when will u use it?
10) Packages
11) java.lang.Object (cloneable)

12) AbstractFactory, Singleton classes


Servlet:
1) context,config
2) cookies
3) RequestDespatcher

jsp:
1) <%! - with and without NOT symbol
2) usage of all objects
3) jsp:include, page directive
4) config
5) taglib, user-defined

struts:
1) how will u check the value is NULL in a form (eg. UserLogin )
2) Attributes of Action (eg. type, name, scope...)
3) Life cycle of Struts
4)


1)

Overloading:

i) must be same method name, different no. of arguments or different types of arguments.
ii) Eventhough the access specifier changed, or , the return type changed, or the
exceptions changed, or static used with the same method name and same argument,
the error will come.

Overriding:

In a Inheritance hierarchy, when a subclass have the same method signature as
it's superclass, the subclass's method overrides the super class's method. So
the sub class method is only called.

i) if u want to change access specifier, the super class's access specifier
must be weaker than the subclass.
ii) if u want to change Exception, the super class's access specifier must be weaker than the subclass.
eg. class top { protected void method1() throws Exception .....
class bottom extends top{ public void method1() throws IOException ....

iii) if u use 'static', u must declare both at super-class and sub-class.

2)
Serialization: Process of writing the state of an Object to a Byte Stream.

Code With Example:

import java.io.*;

class MyClass implements Serializable
{ String s; int i; double d;

public MyClass(String s, int i, double d){
this.s = s; this.i=i; this.d=d;
}

public String toString(){
return "s=" + s + " i=" + i + " d=" + d;
}
}

class SerializationDemo
{
public static void main(String[] args) {
try{
MyClass object1 = new MyClass("Naga", -7, 2.5e10);
System.out.println("Object1: " + object1);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("serial"));
oos.writeObject(object1);
oos.close();
}catch(Exception e){
System.out.println("Exception during serialization");
System.exit(0);
}

try{
MyClass object2;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("serial"));
object2 = (MyClass) ois.readObject();
ois.close();
System.out.println("Object2: " + object2);
}catch(Exception e){
System.out.println("Exception during serialization");
System.exit(0);
}
}
}



3)
I) Collection Interfaces
i) Collection - Enables you to work with groups of objects; it is at the top
of collection hierarchy.
ii) List - Extends Collection, to handle sequences (lists of objects) (duplicates possible)
iii) Set - Extends Collection to handle sets, which must contain unique elements (no duplicate)
iv) SortedSet - Extends Set to handle sorted sets.
Some Additionals are
v) Comparator - defines how two objects are compared
vi) Iterator & ListIterator - enumerate the objects within a collection.
Ex. code for iteration:
Iterator itr = ArrayListObj.iterator();
while(itr.hasNext())
System.out.println(itr.next());


II) Collection Classes
i) ArrayList - we can add the object directly, or with the index.
We can remove existing or non-existing objects with or without index.
Duplication and null are possible.

ii) LinkedList -
iii) HashSet - (allows null, no duplication of result.) Order is not guaranteed,
since it used hashing technique. If you need sorted storage, then another
collection, such as TreeSet, is a better choice.

iv) TreeSet - doesn't allow null at compile time, no duplication of result at
runtime.. Objects are sorted in ascending order.


III) Map Interfaces:
i)Map - is an object that stores associations between keys and values, or key/value pairs.
ii) SortedMap - interface exteds Map. It ensures that the entries are maintained
in ascending key order.

IV) Map Classes:
i) AbstractMap - implements most of the Map interface
ii) HashMap - Extends AbstractMap to use a hash table
iii) TreeMap - Extends AbstractMap to use a tree
iv) WeakHashMap - Extends AbstractMap to use a hash table with weak keys.

HashMap - implements Map and extends AbstractMap. (Order is not quaranteed,
allows null for key and values, no duplication of results. )
Sample Code:
import java.util.*;

class HashMapDemo
{
public static void main(String[] args)
{
HashMap hs = new HashMap();
hs.put("4","raj");
hs.put("1","kumar");
hs.put("8","hai");
hs.put("0",null);
hs.put(null,null);
hs.put("1","Argun");
//hs.add(null);
hs.put(null,null);
//we can't get newKeyIterator(), newValueIterator(), newEntryIterator
// since they r private. So, we must use Set.
Set set = hs.entrySet();

Iterator it = set.iterator();
while(it.hasNext())
{ Map.Entry me = (Map.Entry) it.next(); // in-order to get key/value we use Map.Entry
System.out.println(" " + me.getKey() + " : " + me.getValue());
}

System.out.println(hs);//{8=hai, 4=raj, null=null, 1=Argun, 0=null}
}
}


TreeMap : Storing key/value pairs in sorted order, and allows rapid retrieval.
Does not allow Key as 'null' in run-time. Allows 'null' as value.
No duplication of results.


Some methods in Collections:
static Collection synchronizedCollection(Collection c)
static List synchronizedList(List list)
static Map synchronizedMap(Map m)
static Set synchronizedSet(Set s)
static SortedMap synchronizedSortedMap(SortedMap sm)
static SortedSet synchronizedSortedSet(SortedSet ss)
Likewise, static Collection unmodifiableCollection(Collection c) and so on.

V) Legacy classes 1) Dictionary 2) Hashtable 3) Properties 4) Stack 5) Vector
Legacy interface : 1) Enumeration

NOTE: The main diff. between Vector and ArrayList are two.
i) Vector is synchronized, and it contains many legacy methods that are not part
of the collections framework.
ii) it was reengineered, so it is now fully compatible with collections.
iii) We can specify the increment value with it's constructor.


VI) Hashtable - It is similar to HashMap, but is synchronized. Reengineered.


4) Synchronization : ensures that the shared resource will be used by only one thread at a time.
(or) With respect to multithreading, synchronization is the capability to control the
access of multiple threads to shared resources.

i) interthread communication
a) wait() - tells the calling thread to give up the monitor and go to
sleep until some other thread enters the same monitor and calls notify().

b) notify() - wakes up the first thread that called wait() on the same object.

c) notifyAll() - wakes up all the threads that called wait() on the
same object. The highest priority thread will run first.

ii) Deadlock - With respect to multitasking, when two threads have a circular
dependency on a pair of synchronized objects. (It may involve on more objects by more threads.)

iii) Deprecated methods
a) final void suspend() - to pause the execution of a thread
b) final void resume() - to restart the execution of a thread
c) void stop() - to stop the thread

iv) Others:
a) isAlive() - returns true, if the thread upon which it is called is
still running. Otherwise, returns false.
b) join () - is used to wait for a thread to finish.

v) Synchronized block, synchronized method
synchronized Statement: Imagine that you want to synchronize access to
objects of a class that was not designed for multithreaded access. That is,
the class does not use 'synchronized' methods. Further, this calss was not
created by you, buy by a third party, and you do not have access to the
source code. Thus, you can't add 'synchronized' to the appropriate methods
within the class. How can access to an object of this class by synchronized?.
Fortunately, the solution to this problem is quite easy: You simply put calls
to the mehtods defined by this class inside a 'synchronized' block.
eg. synchronized(object) {
// statements to be synchronized
}

vi) Difference between Process and Thread.
A Process is, a program that is executing. Thus, PROCESS-BASED
multitasking is the feature that allows your computer to run two or more
programs concurrently. For example, process-based multitasking enables you
to run the Java compiler at the same time that you are using a text editor.
In process-based multitasking, a program in the smallest unit of code that
can be dispatched by the scheduler.

A Thread is the smallest unit of dispatchable code. This means
that a single program can perform two or more tasks simultaneously. For
instance, a text editor can format text at the same time that is printing,
as long as these two actions are being performed by two separate threads.
Thus, process-based multitasking deals with the "big picture," and
thread-based multitasking handles the details.

5) What is a user defined exception?
I)User-defined exceptions may be implemented by defining a class to respond to the exception and embedding a throw statement in the try block where the exception can occur or declaring that the method throws the exception (to another method where it is handled).
The developer can define a new exception by deriving it from the Exception class as follows:
code:
public class MyException extends Exception
{/* class definition of constructors (but NOT the exception handling code) goes here */
public MyException() {
super();
}
public MyException( String errorMessage ){
super( errorMessage );
}
}
The throw statement is used to signal the occurrence of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax.
code:
throw new MyException("I threw my own exception.");
To handle the exception within the method where it is thrown, a catch statement that handles MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax:
code:
public myMethodName() throws MyException

II)
a) public class Error extends Throwable
An Error is a subclass of Throwable that indicates serious problems that a reasonable
application should not try to catch. Most such errors are abnormal conditions. The
ThreadDeath error, though a "normal" condition, is also a subclass of Error because
most applications should not try to catch it.

A method is not required to declare in its throws clause any subclasses of Error that
might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

b) public class Exception extends Throwable
The class Exception and its subclasses are a form of Throwable that indicates
conditions that a reasonable application might want to catch.

6) /*Sample code for ConnectionPool*/
import java.util.*;
import java.sql.*;

class ConnectionPool
{
Hashtable connections = null;
String dbURL = null;
int increment = 0;

public ConnectionPool(String dbURL,String driver, int initial, int increment)
throws ClassNotFoundException, SQLException {
/* load the driver */
Class.forName(driver);

/* initialization variables */
connections = new Hashtable();
this.dbURL = dbURL;
this.increment = increment;

/* open initial connections */
for(int i=0;i connections.put(DriverManager.getConnection(dbURL),Boolean.FALSE);
}

public Connection getConnection() throws SQLException {
Connection con = null;

Enumeration enumCons = connections.keys();
synchronized(connections){
while(enumCons.hasMoreElements()){
con = (Connection) enumCons.nextElement();
Boolean b = (Boolean) connections.get(con);
if (Boolean.FALSE == b) //connection available at the pool.
{ /* check the integrity */
try{
con.setAutoCommit(true);
}catch(SQLException sql){
con = DriverManager.getConnection(dbURL);
}
connections.put(con,Boolean.TRUE);
return con;
}
}
}
/* if the control comes here, no free connections available in the pool */
/* So, we have to increment the connections. */
for(int i=0;i connections.put(DriverManager.getConnection(dbURL), Boolean.FALSE);

return getConnection();
}

public void returnConnection(Connection returned) throws SQLException {
Connection con = null;
Enumeration enumCons = connections.keys();
while(enumCons.hasMoreElements()){
con = (Connection) enumCons.nextElement();
if (con==returned ) {
connections.put(con, Boolean.FALSE);
break;
}
}
}
}

What is the current version of EJB?
EJB Version 2.1
What is the main difference between EJB 1.1 and EJB 2.1?
Message Driven Bean
Container manager specification declaration given clearly in EJB2.1
What are all the Beans available in EJB?
a. Stateless Session Bean
b. Stateful Session Bean
c. Entity Bean ( CMP, BMP )
d. Message Driven Bean
What is the difference between stateless and Stateful session beans?
Stateful Session Bean
Stateless Session Bean
A Bean that is designed to service business processes that span multiple method requests or transactions.
A Bean that holds conversations that span a single method call.
Stateful Session beans maintain data (state) across business logic method invocations
Stateless Session bean do not maintain data ( state ) across business logic method Invocations.
It can utilize the bean-pooling feature of the EJB container.
More than One create methods (can have arguments)
There must be only one create method without argument.


What are all the types of available beans for Persistence mechanism?
Bean Managed Persistence (BMP).
Container Managed Persistence (CMP).
Life Cycle of All the Beans. Session , Entity, BMP, CMP, Message Driven Bean.
What are all the call back methods in EJB?
setSessionContext(SessionContext ctx)
ejbCreate()
ejbPassivate()
ejbActivate()
ejbRemove()

How many classes we have to create EJB Bean?
Enterprise Bean class
Home Interface
Remote Interface
What is Call by reference , Call by value?
Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.
If it is necessary to create a create method?


What is CMP?
In CMP, entity bean data is maintained automatically by the container that uses the mechanism of its choosing.

What is BMP?
When using BMP, the bean is responsible for storing and retrieving persisted data. The entity bean interface provides methods for the container to notify an instance when it needs to store or retrieve data.

What is difference between the Both? Prons and cons.
CMP Pros Benefits of container-managed persistence include the following:
a. Database-independence The container, not the enterprise bean provider, maintains database access code to most popular databases.
b. Container-specific features Features such as full text search are available for use by the enterprise bean provider.
CMP Cons Drawbacks to container-managed persistence include the following:
a. Algorithms Only container-supported algorithms persistence can be used.
b. Portability Portability to other EJB containers may be lost.
c. Access The developer has no access to the view and cannot modify the actual code.
d. Efficiency Sometimes the generated SQL is not the most efficient with respect to performance.


BMP Pros Benefits of bean-managed persistence include the following:
a. Container independent Entity bean code written for one EJB container should be easily portable to any other certified EJB container. Standards based The standard EJB and JDBC APIs can be used for data access calls.
b. Datatype access The ability to access nonstandard datatypes and legacy applications is supported.
c. Maximum flexibility Data validation logic of any complexity is supported.
d. Database specific features The application is able to take advantage of nonstandard SQL features of different SQL servers.
BMP Cons Drawbacks to bean-managed persistence include the following:
a. Database specific Because entity bean code is database specific, if access to multiple databases is required, the enterprise bean provider will have to account for this in its data access methods.
b. Knowledge of SQL The enterprise bean provider must have knowledge of SQL.
c. Development time These beans on average take much longer time to develop—as much as five times longer.

How to write a CMP bean?
What is CMR field?
Recall that a CMP entity bean has an abstract get/set method for the relationship. We need to tell the container which get/set method corresponds to this relationship, so that the container can generate the appropriate scaffolding code when sub classing our bean. That is the purpose of this element, which is called the container-managed relationship ( CMR ) field. The value of the CMR field should be the name of your get/set method, but without the get/set, and with a slight change in capitalization.
What is transaction isolation levels?
What are all the transaction attributes and explain each things?
Transaction Attribute Settings
A transaction attribute supports declarative transaction demarcation and conveys to the container the intended transactional behavior of the associated EJB component’s method. Six transaction attributes are possible for container-managed transaction demarcation:
a. NotSupported The bean runs outside the context of a transaction. Existing transactions are suspended during method calls. The bean cannot be invoked within a transaction. An existing transaction is suspended until the method called in this bean completes.
b. Required Method calls require a transaction context. If a transaction already exists, the bean will use it; if a transaction does not exist, it will be created. The container starts a new transaction if no transaction exists.
c. Supports Method calls use the current transaction context if one exists but they don’t create one if none exists. The container will not start a new transaction. If a transaction already exists, the bean will be included in that transaction. Note that with this attribute, the bean can run without
a transaction.
d. Requires New Containers create new transactions before each method call on the bean and commit transactions before returning. A new transaction is always started when the bean method is called. If a transaction already exists, that transaction is suspended until the new transaction completes.
e. Mandatory Method calls require a transaction context. If one does not exist, an exception is thrown. An active transaction must already exist. If no transaction exists, the javax.ejb.TransactionRequired exception is thrown.
f. Never Method calls require that no transaction context be present. If one exists, an exception is thrown. The bean must never run with a transaction. If a transaction exists, the java.rmi.RemoteException exception is thrown.
What is Session Synchronization?
What is two phase commit protocol? How it is working?
How Invoke the EJB Bean from the client?
What is the use of the local interface?
a. Obtain the local home Interface for the Entity object.
b. Remove the Entity Object
c. Obtain the entity object’s primary key.
d. It can be used as a replacement for JDBC – supporting fast calls to a database while the client runs inside the same JVM as the Entity bean.
What are all the services provide by the container to the EJB?
Distributed Transaction management
Security
Resource Management and component life cycle
Persistence
Remote Accessibility
Multiclient support
Component Location transparency

What is the difference between EJB find method EJB select method?
When you used BMP and CMP?
You can use CMP and BMP beans in the same application... obviously, a bean can be BMP or CMP, not both at the same time (they are mutually exclusive). There is a common approach that is normally used and considered a good one. You should start developing CMP beans, unless you require some kind of special bean, like multi-tables, that cannot be completely realized with a single bean. Then, when you realize that you need something more or that you would prefer handling the persistence (performance issue are the most common reason), you can change the bean from a CMP to a BMP.
Study something about JMS.


What is Session Facade pattern in EJB? And mention the advantages.
The Session Façade Shows how to properly partition the business logic in your system to help minimize dependencies between client and server, while forcing use cases to execute in one network call to execute in one network and in one transaction.
Advantages :
a. Low Network overhead
b. Clean and strict separation of business logic from presentation lgic
c. Transactional Integrity
d. Low Coupling
e. Good reusability
f. Good maintainability
g. Clean verb-noun separation

What is the value object pattern and its advantages in J2EE?
The Value Object pattern is a simple but very useful pattern in J2EE. A value object is a serializable representation of a complex set of data suitable for pass-ing between application tiers via RMI. Value objects are generally utility classes, similar to structs in C, but can contain behavior to validate or prohibit internal data modification as well. An example of this pattern is creating an
OrderInfo object that contains all the data about a given order. This object could be serialized across the network and used to display information to the user. Value objects are critical to the proper operation of an RMI-based compo-nent model such as EJB. Since local references to remote data are not possible, a snapshot of the data is passed by value to the remote client. Value objects are
employed very often. See the case study for a detailed example of their use with XML structures.
There are two other J2EE patterns used with value objects. For complete-ness, we mention them here. The Value Object Assembler is a pattern for composing complicated value objects from various other objects. The Value List Handler is a pattern for creating, manipulating, and updating sets of value
objects at the same time. The details of these patterns are available at Sun’s J2EE patterns web site.
Difference between Context and Initial Context?
javax.naming.Context is an interface that provides methods for binding a name to an object. It's much like the RMI Naming.bind() method. javax.naming.InitialContext is a Context and provides implementation for methods available in the Context interface. Where as SessionContext is an EJBContext object that is provided by the EJB container to a SessionBean in order for the SessionBean to access the information and/or services or the container.
What all methods are available in EJB Home Interface?
getEJBMetaData
getHomeHandle
remove

Define Fine and Course Grained Entity? (Aggregated entity)
A 'fine grained' entity bean is pretty much directly mapped to one relational table, in third normal form. A 'coarse grained' entity bean is larger and more complex, either because its attributes include values or lists from other tables, or because it 'owns' one or more sets of dependent objects. Note that the coarse grained bean might be mapped to a single table or flat file, but that single table is going to be pretty ugly, with data copied from other tables, repeated field groups, columns that are dependent on non-key fields, etc. Fine grained entities are generally considered a liability in large systems because they will tend to increase the load on several of the EJB server's subsystems (there will be more objects exported through the distribution layer, more objects participating in transactions, more skeletons in memory, more EJB Objects in memory, etc.) The other side of the coin is that the 1.1 spec doesn't mandate CMP Error! No index entries found.support for dependent objects (or even indicate how they should be supported), which makes it more difficult to do coarse grained objects with CMP. The EJB 2.0 specification improves this in a huge way.




What of the following will stop the execution of a running Thread ?
When the thread throws an interrupted exception.
When a high priority thread starts running.
While the thread’s wait method is called.
When the main method completes.
In the running thread when a new thread is created
Which of the following will throw a NullPointerException?
String s = null;
if ((s!=null) & (s.length() > 0))
if ((s!=null) && (s.length() == 0))
if ((s==null) (s.length() > 0))
if ((s==null) (s.length() > 0))
Which of the following describes a fully encapsulated class?
Methods cannot be private
Variables cannot be private
All instance variables are private.
All instance variables are public
All instance variables are private and public accessor methods are provided to get the values of instance variables
In the following program, if somecondition() returns true, then only line number 3 must throw a custom exception MyException. MyException is not a subclass of runtime exceptions. What are the changes to be made to the given method to handle the eception
1. Class Exceptionthrown{
2. public void method() {
3. --------------
4. ---------------
5. If (somecondition()) {
6.
7. }
8.
9. }
10. }
K. Add throws new MyException(); in line number 4
L. Add throw MyException(); in line number 6
M. Add throw new MyException(); in line number 6
N. Add throw new MyException(); in line number 4
O. Modify the method declaration such that an object of type Exception is to be thrown
What is the output of the following program
public class Trial{
int x;
public static void main(String args[]) {
x = 8;
System.out.print("The value of x is " + x);
} }
. The program prints The value of x is 8;
A. The program prints The value of x is 0;
B. The program will not compile.
Given the following code
Float F1 = new Float(0.9F);
Float F2 = new Float(0.9F);
Double D1 = new Double (0.9);
Which of the following will return true?
. (F1 == F2)
A. (F1 == D2)
B. F1.equals(F2)
C. F1.equals(D2)
D. F1.equals(new Float(0.9F))
What are the assignments which are valid in the line XXXX
class Super{
private int i;
public int ma_cd(float f){
i = (int) f;
return i;
}
}
class Sub extends Super{
int j;
float g;
public Sub(){
Super s = new Super();
XXXX
}
}
. j = i;
A. g = f;
B. j = s.ma_cd(3.2f);
C. j = s.i;
D. g = s.f;
Which is the earliest possible instance at which the String object referred by s is eligible for Garbage Collection?
public static void main(String args[ ]){
1.String s = "abcd";
2.String s1 = "efghi";
3.String s2 = s+ s1;
4.s = null;
5.s = s1;
6.s1 = s;
. Before Line 4.
A. Before Line 5 starts
B. After Line 5.
C. Before line 6.
A Polygon is drawable. You want to store the coordinates of the Polygon in a vector. The Polygon has color and fill flags. Which of the following types will you choose for declaring the variables of a Polygon class.
. Vector
A. drawable
B. Polygon
C. Color
D. Boolean
An Employee is a Person. The Employee has a identity, name etc. There is a plan to prepare a class of type Employee which is going to used in many unrelated parts of the project. Using the following keywords construct a class that defines an Employee.
abstract, public, Employee, throws, class, Person, void, extends
public class Employee extends Person
FilterOutputStream has sub classes such as BufferedOutputStream, DataOutputStream and PrintStream. Which of the following is the valid argument type for the constructor of the FilterOutputStream
. File
A. PrintStream
B. DataOutputStream
C. BufferedOutputstream
D. FileOutputStream
What is the equivalent Octal representation of 7 (not more that 4 characters)
07
What is the return type of the methods in Java 2 Listener Interfaces ?
. Boolean
A. boolean
B. void
C. String
D. int
Which of the following is true regarding GridBagLayout
. if a component has been given fill both is true, then as the container resizes the component resizes
A. The number of rows and columns are fixed while loading the components.
B. The number of rows and columns are fixed while loading the layout itself .
C. if a component has a non-zero weightY value, then the component grows in height as the container is resized.
Given the following code
switch(x){
case 1: System.out.println("Test 1");
case 2:
case 3: System.out.println("Test 3");
break;
default : System.out.println("Test 4");
break;
}
What are the possible values of x if "Test 3" is to be printed ?
. 4
A. 2
B. 3
C. 1
D. 0
What is the valid argument type for the methods in a MouseMotionListener Interface ?
MouseEvent
Which of the following is valid native method declaration in Java ?
. public static void native method1(){}
a. static void native method1(){}
b. static native void method1();
c. static void native method1(){}
d. static native int method1();
Given the following code
class Super{
public void method1() {}
}
class Sub extends Super{
// xx
}
Which of the following methods can be legally added at line marked xx ?
. int method1() { }
a. String method1() throws IOException{ }
b. void method1(String s) { }
c. void method1(Float s) { }
d. public void method2() { }
Given the following code
if (x > 4) {
System.out.println( "Test 1" );
}
else if (x> 9){
System.out.println("Test 2");
}
else
System.out.println("Test 3");
What are the possible values of x that will cause "Test 2 " to be printed ?
. 0 to 4
A. Less than 0
B. 5 to 9
C. 10 and greater
D. None
What is the range of a char type?
0 to 216-1
Which of the following are true about >> and >>> operators?
. >> performs a unsigned shift and >>> performs a rotate.
A. >> performs a signed shift and >>> performs an unsigned shift.
B. >> performs an unsigned shift and >>> performs a signed shift.
What are valid Java keywords
. NULL
A. null
B. TRUE
C. implements
D. interface
E. instanceof
F. sizeof
Which of the following collection objects can be used for storing values that may appear more than once and ordered ?
. Map
A. List //dupes + ordered
B. Set
C. Collection // dupes + unordered
You want a component to retain its width, but not the height when resized. How will you achieve this ?
. Place the component in North or South in a BorderLayout
A. Place the component in the Center of a BorderLayout
B. Place the component in East or West in a BorderLayout
You have defined a class and sub classes of the same. But you don’t want the methods of the super class to be overridden . what modifier you will use for declaring the methods of the super class ?
final
What is the body of a Thread
. public void run()
A. public void start()
B. public void runnable()
C. public static void main(String args[])
What is the output of the following code?
int i = 0;
while(i-- > 0) {
System.out.println("The value of i is " + i);
}
System.out.println("Finished");
. The value of i is 1
A. The value of i is 0
B. Finished
C. Compilation Error
D. Runtime Error
What is the output of the following program
class Example{
static int arr[] = new int[10];
public static void main(String args[]){
System.out.println(" The value 4th element is " + arr[4]);
}
}
. The value of 4th element is 4
A. The value of 4th element is null
B. The value of 4th element is 0
C. Null Pointer exception is raised
D. Runtime error, because the class is not instantiated
Which of the following is the correct class declaration for Car.java. See to that it is a case-sensitive system
. public class Car{
int in;
public Car(int inn){
in = inn
}
}
A. public class Car extends Truck, Vehicle{
int in;
public Car(int inn){
in = inn;
}
}
B. public class Car{
int in;
public abstract void raceCar() {System.out.println("RaceCar");}
public Car(int inn){
in = inn;
}
}
C. public class Car{
int in;
public Car(int inn){
in = inn;
} }
Which of the following is true about Garbage Collection mechanism
. Garbage Collection is carried out at predictable intervals
A. The programmer can write come complex code to perform garbage collection
B. The programmer can make objects eligible for garbage collection through the reference variables
C. Garbage collection cannot be performed on objects which are referred by the running threads.
What is the output of the following program?
class Super{
String name;
Super(String s){
name =s ;
} }
class Sub extends Super{
String name;
Sub(String s){
name=s;
}
public static void main(String args[]){
Super sup = new Super("First");
Sub sub = new Sub("Second");
System.out.println(sub.name + " " + sup.name);
} }
. First Second
A. Second First
B. Compilation error
C. Runtime error stating same name found in Super as well as in the Sub class
java.awt.AWTEvent is a super class of all delegation model event classes. There is one method called getID() in that class. What does that method returns
. text of the event
A. source of the event
B. ID of the event
What of the following cannot be added to a container ?
. Applet
A. Panel
B. Frame
C. Component
D. Container
E. MenuComponent
How to initialise the variables in class Super from a constructor in the same class(at line xx). Write a single line code without any spaces
class Super{
float x;
float y;
float z;
Super(float a, float b){
x = a;
y = b;
}
Super(float a, float b, float c){
//xx
z = c;
}
}
this(a,b);
What is true about inner classes?
. Inner classes have to be instantiated only in the enclosing class
A. Inner classes can access all the final variables of the enclosing class
B. Inner classes cannot be static
C. Inner classes cannot be anonymous class
D. Inner classes can extend another class.
Consider the following hierarchy
Parent
------------------------------

DerivedOne DerivedTwo
The following variables are initialised to null.
Parent P1;
DerivedOne D1;
DerivedTwo d2;
What will happen if the following assignment is made( take the above into account)?
D1 = (DerivedOne) P1

. It is legal at compile time and illegal at run time
A. It is legal at compile time and legal at run time // read q properly, init to null
B. It is illegal at compile time.
C. It legal at compile time and may throw "CastClassException" at run time
Which modifiers are to be used to obtain the lock on the object
. public
A. private
B. static
C. synchornized
D. lock
// Point X
public class Example
What can be possibly used at Point X
. import java.awt.*;
A. package local.util;
B. class NoExample{}
C. protected class SimpleExample
D. public static final double PI = 3.14;
What is the range of int type
-231 to 231-1
What are the legal identifers in Java?
. %employee
A. $employee
B. employ-ee
C. employee1
D. _employee
Which of the following are true about the listener interfaces in Java ?
. awt listener menthods generally takes an argument which is an instance of some subclass of java.awt.AWTEvent
A. When multiple listeners are added to a single component the order of invocation of the listeners cannot be guaranteed
B. A single component can have multiple listeners added to it.
Given the following declaration.
String S1 = "Hello";
Which of the following are true ?
. S1 = S1 >> 2;
A. S1 += "there";
B. S1 += 3;
C. char c = S1[2]; // Will give an error, use chatAt, as String is a class not a Array
Given the following String declarations and methods. What is the String object referred by S1 after execution of these statements ?
String S1 = "Hello";
String S2 = "There";
S1.concat(" my friend");
S1.concat(" our friend");
S1 += S2;
HelloThere

. Which declarations are true about inner classes?
A. new InnerClass(){
B. public abstract class Innerclass{
C. new Ineerclass() extends Mainclass{
2. Which access modifier is used to restrict the methods scope to itself and still allows other classes to subclass that class?
private
final
protected
friend
3. Which one of the following will equate to true?
Float f1 = new Float(0.9f);
Float f2 = new Float(0.9f);
Double d = new Double(0.9);
f1 == f2;
f2 == d;
f1.equals(f2);
f2.equals(f1)
f2.equals(d); // will return false not error
4. Which statement below is true regarding the above code?
The following shows class hierarchy
Derived1 , Derived2 extends from Mainclass.
Mainclass m;
Derived1 one;
Derived2 two;
one = (Derived1) m;
A. Compilation error
B. Comiplation is legal but generates runtime error
C. Compilation is legal but generates ClassCastException during execution
D. Compilation is legal probably okay during execution

5. What will be printed when the follwoing code is executed?
outer : for(int i =1; i<3 ; i++){
inner : for ( int j = 1;j<3;j++){
if ( j ==2)
continue outer;
System.out.println("i is "+i+" j is "+j);
}
}
A. i = 1 j = 1
B. i = 1 j = 2
C. i = 1 j = 3
D. i = 2 j = 1
E. i = 2 j = 2
F. i = 2 j = 3
G. i = 3 j = 1
H. i = 3 j = 2
I. i = 3 j = 3

6. Check the correct class declaration for the Car.java
A. public class Car{
static int x =0;
public static void method(int y){
x = y;
} }

B. public class Car extends Myclass,Hisclass{
static int x;
public void method(int y){
x = y;
} }

C. public class Car {
static int x;
public abstract void method(int y){
x = y;
} }

D. import java.awt.*;
public class Car extends Object{
static int x;
public void method(int y){
x = y;
} }

7. Employee is a Person. Employee has details stored in Vector, name as String and educated as boolean flag. Using the words given below make correct signature for Employee class.
Import static void extends Employee public class Person Vector String
public class Employee extends Person

8. Shape is a Drawable one.Shape has details stored in Vector, fill color and flag having boolean state.
What will be included in the construction of Shape class?
A. Drawable
B. Vector
C. String
D. Color
E. boolean
F. int

9. The class definition is as below:
1 public class Test{
2 public static void main(String args[]){
3 StringBuffer sb1 = new StringBuffer("Hello");
4 StringBuffer sb2 = new StringBuffer("I am here");
5 method(sb1,sb2);
6 System.out.println("sb1 "+sb1+" sb2 "+sb2); // this is ok
7 }
8 static void method(StringBuffer s1,StringBuffer s2){
9 s1 = s1+"hello"; // this is a error
10 s2 = s1;
11 }
12 }
What will be the output of the above ?
A. Compilation error at line 5
B. Compilation error at line 6 as StringBuffer does not override '+' operator
Code compiles and output will be
sb1 Hello sb2 I am here
D. Code compiles and output will be
sb1 Hellohello sb2 Hellohello
10. Which modifier will you use to restrict the access of instance variable to the class only and not to any other classes?
A. protected
B. default
C. final
D. private
11. What is the octal representation of 7 (Answer within 4 characters )
07
12. Class Test is defined as below
public class Test{
int x,y;
public Test(int a,int b){
// some complex calculations
x = a;
Y = b;
}
public Test(int a, int b, String s){
// some complex calculations as two integer constructor
// and finally assigns x =a, y=b
System.out.println("sdfd");
}
}
Write a line of code in the 2nd constructor such that 1st constructor codings need not be repeated
this(a,b);
13. What will happen if you try to compile and run the following program
import java.awt.*
import java.awt.event.*;
public class Test extends Frame implements ActionListener{
public Test(){
Button b = new Button("Press");
String s = "Message";
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
System.out.println("Message is "+s); // s is not final!
}
} );
add(b,BorderLayout.NORTH);
setSize(300,300);
setVisible(true);
}
public static void main(String args[]){
Test t = new Test();
}
}
A. Compilation error while adding Button as BorderLayout is not default layout of Test
B. Compilation error at adding ActionListener
C. Compilation error at actionPerformed method as 's' is not accessible inside this method
D. Message is Message is printed on pressing Button
14. The classes are defined as follows in different java files
public class First{
static int x;
public void method(int y){
x = y;
}
}
public class Second extends First{ }
What are the legal method declarations in Second class?
A. int method(int x){}
B. public void method(String x){}
C. public abstract void method(int y);
D. int anotheeMethod(int x){}
15. The following code lists class hierarchy
class First{
String primary,secondary;
public First(String s1,String s2){
primary = s1;
secondary = s2;
}
String toString(){
return primary;
}
}
class Second extends First{
String primary,secondary;
public Second(String s1,String s2){
super(s1,s2);
primary = s1;
secondary = s2;
}
String toString(){
return primary + secondary;
}
public static void main(String args[]){
First f1 = new First("First","1st");
First f2 = new Second("Second","2nd");
System.out.println(f1.toString());
System.out.println(f2.toString());
} }
What will be the output?
A. First 1st
Second 2nd
B. First
Second 2nd
C. First 1st
First 1st
D. Second 2nd
Second 2nd
16. Where a button to be placed so that its width remains same and height changes on resizing?
A. Using GridLayout with single Button
B. Placing in North,South in Borderlayout
C. Placing in East,West in BorderLayout
D. Placing at center in FlowLayout
17. What is true about GridBagLayout? (Radio button)
A.If component has to be the last one i a row the gridX value should be REMAINDER
B.Fill value has no effect if anchor value is set to center
C.Anchor value has no effect if Fill Value is Both
18. What will be the output?
String s = "hello";
String s1 = "there";
s.concat(s1);
s.toUpperCase();
s += "here";
System.out.println(s);
A. hello THERE
B. hello there
C. hello here
D. HELLO THERE here
E. HELLO here
19. Which modifier for a local variable cannot be used inside a method declarations ?
A. final
B. public // No Access modifiers allowed
C. default
20. A Socket s is established with a port and the output from the Socket to be read as lines of data from the socket which one you will use?
A. FileInutStrean f = new FileInputStream(s.getInoutStream());
B. DataInputStream d = new DataInputStream(s.getInputStream());
C. ByteArrayInputStream b = new ByteArrayInputStream(s.getInputStream());
D. BufferedReader b= new BufferedReader(s.getInputStream());
E. BufferedInputStream bis = new BufferedInputStream(s.getInputStream(),"8859_1");
21. What is the argument for all MouseMotionListener interface methods?
MouseEvent
22. Part of main method is defined as follows:
{
int i =0;
while(i-- > 0){
System.out.println("i is "+i);
}
System.out.println("Finished");
}
What will be the output of the above code?
A. i is 0
B. Infinite loop
C. Finished
D. i is 1
23. getID() method of AWTEvent refers to what?
Nature or Type of Event
24. What are the correct declarations for 2 dimensional ararys?
A. int a[][] = new int[4,4];
B. int []a[] = new int[4][4];
C. int a[][] = new int[4][4];
D. int a[4][4] = new int[][];
E. int [][]a = new int[4][4];
25. What causes current thread to stop executing?( which statements are true about thread?)
A. Threads created from same class finish together
B. Thread can be created only by subclassing java.lang.Thread
C. Thread execution of specific thread can be suspended indefinitely if required.
D. Java interpreter exits when main thread exits even if the other threads are running.
E. Uncoordination of multiple threads will affect data integrity .
26. What statements are true about gc?
A. gc releases memory at predictable rates.
B. gc requires additional code in case multiple threads are running
C. Programmer has a mechanism that explicitly & immediately frees memory used by java objects
D. gc system never reclaims memory from objects which are still accessible to a running user thread
27. What are true about Listeners?
A. Return value is boolean
B. Most components allow multiple listeners to be added
C. A copy of original event passed to listener method
D. Multiple listeners added to single component, they must be made friends
E. The order of invocation of the listener is specified to be in which they are added
28. What is the correct way of declaring native methods?
A. public abstract native method() {}
B. public native void method();
C. native void method(){}
D. public native void method() {}
29. What are the java keywords?
A. friendly
B. extends
C. synchronized
D. sizeof
E. interfaceof
30. What is the range for char variable?
0 to 216-1
31. What is the range for int variable?
-231 to 231-1
32. Which are valid java identifiers?
A. thisfinal
B. %great
C. intern
D. 3fun
z_fal
33. The main method for class Test is given below:
try{
state();
}
catch(ArithmeticException ex)
{
System.out.println("Arithmetic");
}
finally{
Sytem.out.println("finally");
}
System.out.println("done");
What will be the output of the above code (Choose the correct one) if method state() throws NullPointerException?
A. Arithmetic
B. finally
C. done
D. Exception not caught
34. At what point will the String referenced at line 1 is available for garbage collection in this method?
1. String s1 = "abc";
2. String s2 = "bdc";
3. s1.concat(s2);
4. s1 = null;
5. s1 += s2;
6. System.out.println(s1);
A. Just Before 4
B. Just Before 5
C. Just Before 6
D. never
35. Which cannot be added to Container?
A. Applet
B. Panel
C. Container
D. MenuComponent
36. Which of the following code statement will throw NullPointerException
String s = "hello";
s == null;
a. if(s != null & s.length() >0)
b. if(s == null && s.length() >0)
c. if(s != null s.length() >0)
d. if(s == null s.length() >0)
37. which of the following are true?
class x {
int x;
public static void main(String args[]) {
x = 10;
System.out.println(" value of x "+x);
}
}
a. prints "value of x 10"
b. compilation error
c. Runtime Error
38. what are the valid codes that come in //Point X place declared in Test.java
// Point X
public class Test {}
a. import java.awt.*;
b. package local.util;
c. class someclass {}
d. protected class myclass {}
e. private static final int more = 1000;
39. Which of the following evaluate to true?
float f = 10.0f
long l = 10L
a. f == 10.0f
b. f = 10.0 // 10.0 is a double value
c. f == 10.0 // converted to parent class, here double
d. f == l
e. l == 10.0
40. FilterInputStream is subclassed by DataInputStream, BufferedInputStream, ByteArrayInputStream.
What is the valid argument for FilterInputStream constructor?
a. File
b. FileInputStream
c. PrintStream
d. BufferedReader
Java Tips
By Heather MacKenzie
Object-Oriented Programming
No explicit cast needed for upcasting, but explicit cast needed for downcasting.
Defining your class as implementing an interface marks objects of that class as an instance of that interface.
An abstract method cannot (obviously) be final.
An abstract method cannot be static because static methods cannot be overridden.
An instance method can be both protected and abstract. A static method can be protected.
Before Java runtime clones an object, it checks to see if the object’s class implements the Cloneable interface. If it does, the clone() method returns a clone of the object. If not, the clone() method throws a CloneNotSupportedException.
The clone method is protected, so an object can only request a clone of another object which is either in the same package or which it inherits from. (i.e. standard meaning of protected)
The JVM does not call an object’s constructor when you clone the object.
Keywords
Classes can be modified from their default state using any of the three keywords: public, abstract, and final. So, can’t have a static class, only static methods.
A final variable is a constant, and a final method cannot be overridden.
A synchronised method can belong to an object or to a class.
Only one public class per file.
package statement must come first in file and must be followed by any import statements.
An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. Java letters include _ and $. Digits include 0..9.
Constructors
The JVM does not call an object’s constructor when an object is cloned.
Constructors never return a value. If you do specify a return value, the JVM will interpret your intended constructor as a method.
If a class contains no constructor declarations, then a default constructor that takes no arguments is supplied. This default constructor invokes the no-args superclass constructor, i.e. calls super();
If, in a constructor, you do not make a direct call to super or this (with or without args) [note: must be on the first line] then super(no args) will first be invoked then any code in the constructor will be executed. See constructors.jpr project.
A call to this in a constructor must also be on the first line. Note: can’t have an explicit call to super followed by a call to this in a constructor - only one direct call to another constructor is allowed.
Memory and Garbage Collection
As soon as you lose the reference to an object, that object becomes eligible for garbage collection.
Setting your object reference to null makes it a candidate for garbage collection.
You can directly invoke the garbage collector by getting an object which represents the current runtime and invoking that object’s gc() method (see p.95 of Exam Guide).
Can’t predict when garbage collection will occur, but it does run whenever memory gets low.
If you want to perform some task when your object is about to be garbage collected, you can override the java.lang.Object method called finalize(). This method is declared as protected, does not return a value, and throws a Throwable object, i.e. protected void finalize() throws Throwable.
Always invoke the superclass’s finalize() method if you override finalize().
The JVM only invokes finalize() once per object. Since this is the case, do not resurrect an object in finalize as when the object is finalized again its finalize() method will not be called. Instead you should create a clone of the object if you must bring the object back to life.
Remember that Java passes method parameters by value and not by reference. Obviously then, anything that happens to a primitive data type inside a method does not affect the original value in the calling code. Also, any reassignment of object references inside a method has no effect on the objects passed in.
Data Types and Values
Ranges for primitive data types are as follows:-
Data Type
Range of Values

byte
-27.. 27-1
signed integer
short
-215.. 215-1
signed integer
int
-231.. 231-1
signed integer
long
-263.. 263-1
signed integer
float
32 bit
signed floating point
double
64 bit
signed floating point
char
16 bit
Unicode character
boolean
either true or false

To specify an octal (base 8) number, put a leading ‘0’ in front of i
To specify a hexadecimal (base 16) number, put a leading ‘0x’ in front of it.
By default, integer values are of type int. However, you can force an integer value to be a long by placing an ‘L’ after it.
By default, floating point values are of type double. However, you can force a floating-point value to be a float by placing an ‘F’ after it.
Java sets each element in an array to its default value when it is created. Default object value is null, default integer value is 0, default boolean value is false, default floating point value is 0.0, default char value is ‘\u0000’.
Arrays are objects allocated at runtime, so you can use a variable to set their length.
First element in an array is at index 0 and last element is at length-1. length is a special array variable (not a method, so don’t need round brackets after it).
Can only use curly braces in array initialisation when array is actually declared, i.e. can’t declare the array on one line then initialise it with curly braces on line below.
ASCII characters are all found in the range ‘\u0000’ to ‘\u00ff’
The default value for any class variable or instance variable declared as a char is ‘\u0000’.
Operators
>> is right shift keep the sign, >>> is right shift don’t keep the sign.
& and can be used with both integral and boolean types. If used with integers the result is integral. If used with booleans, both operands are evaluated, even when the result of the operation can be determined after evaluating only the left operand.
&& and are used with boolean operands only. The right operand is not evaluated if the result of the operation can be determined after evaluating only the left operand.
The equals() method (defined at the ‘highest’ level as a method of Object) is used to test the value of an object. The == operator is used to test the object references themselves.
By default, equals() returns true only if the objects reside in the same memory location, i.e. if the object references are equal. So, by default, equals() and == do the same things. This will be the case for all classes that do not override equals().
String, Wrappers (including Integer, Long, Float, Double, Character and Boolean), BitSet, Date and File classes all override equals() so that the value true is returned if the values are equal.
The + and += operators are overloaded for Strings.
Dividing an integer by 0 is illegal and would cause Java to throw an ArithmeticException. Floating point numbers have values for infinity and not-a-number, so using arithmetic operators on floating point numbers never results in an exception.
Control Flow
A loop counter is usually an integer, however it could also be a floating point number - incrementing by 1.0
Breaking to a label means that the loop at the label is terminated. Any outer loop will keep iterating.
In contrast, a continue to a label continues execution with the next iteration of the labelled loop.
The expression for an if and while statement must be a Boolean.
The expression in a switch statement must be an int or a char.
A default statement in a switch is optional.
A case block will fall through to the case block which follows it, unless the last statement in a case block is a throw, return or break.
As with if statements, for and while loops, it is possible to nest switch statements.
Any line of code can be labelled BUT can only do a labelled continue to a loop, and can only do a labelled break to a loop or to an enclosing statement.
Exceptions
It is possible to have multiple catch blocks in a try-catch-finally. The finally block is optional.
A catch block must always be associated with a try block, i.e. can’t have a catch block by itself or with a finally block.
A finally block must always be associated with a try block, i.e. can’t have a finally block by itself or with a finally block.
With multiple catch blocks, the type of exception caught must progress from the most specific exception that you wish to catch to the superclasses for these exceptions. (Makes sense!)
Methods must declare any exception which they throw.
Invoking a method which declares it throws exceptions is not possible unless either the code is placed in a try-catch, or the calling method declares that it throws the exceptions, i.e. checked exceptions must be caught or rethrown. If the try-catch approach is used, then the try-catch must cope with all of the exceptions which a method declares it throws.
You can list more than one exception in the throws clause if you separate them with commas.
RuntimeException and its subclasses are unchecked exceptions.
Unchecked exceptions do not have to be caught.
All Errors are unchecked.
You should never throw an unchecked exception in your own code, even though the code will compile.
You cannot use a try block on its own. It must be accompanied by a following catch or finally (or both).
Code in a finally block will always be executed, whether an exception is thrown or not and whether any exception thrown is caught or not. Only terminating the program will stop the finally code from being executed.
A method can only throw those exceptions listed in its throws clause, or subclasses of those exceptions.
A method can throw any unchecked exception, even if it is not declared in its throws clause.
When you override a method, you must list those exceptions that the override code might throw. You can list only those exceptions, or subclasses of those exceptions, that are defined in the method definition you are inheriting from, i.e. you cannot add new exception types to those you inherit. You can choose to throw a subset of those exceptions listed in the method’s superclass, however, a subclass further down the hierarchy cannot then re-list the exceptions dropped above it.
Methods
If you define more than one method with the same name in the same class, Java must be able to determine which method to invoke based on the number and types of parameters defined for that method.
The compiler will complain if you have two methods with identical signatures exception for the return type and/or the exceptions thrown, i.e. can’t overload based on return type and/or exceptions thrown.
Determining which methods will be invoked with integer params - see p.195 of the Exam Guide.
It is possible to declare an inherited method abstract.
Obviously, it is not possible to override a final method.
A subclass may make an inherited method synchronized, or it may leave off the synchronized keyword so that its version is not synchronized. If a method in a subclass is not synchronized but the method in the superclass is, the thread obtains the monitor for the object when it enters the superclass’s method.
It is possible to declare an inherited method as abstract, but then there is no way to get to the behaviour in the hierarchy above the abstract declaration.
Return types must match the overriden method in the superclass exactly. The parameter types must match those in the superclass exactly, i.e. in the same order. If this is not the case, then the superclass’s method is not overridden. Compiler will not complain, however, unless exactly the same signature except for return type (or exceptions thrown - see earlier).
You cannot make a method in a subclass more private than it is defined in the superclass, ‘though you can make it more public.
Coercion of arguments only happens with overloading, not overriding.
It is perfectly legal to have two different instance variables with the same name if they are defined in different classes where one class inherits from the other.
Which variable is accessed depends on the type of object reference which the variable was declared to hold. Which method gets invoked depends on the underlying object. See p.106 Q1 & p.201 of Exam Guide.
A native method does not have a body, or even a set of braces, e.g. public native void method();
A native method cannot be abstract.
A native method can throw exceptions.
Math and String Classes
ceil() returns the next highest integer (expressed as a double)
Method call
Returns
ceil(9.01)
9.0
ceil(-0.1)
0.0
ceil(100)
100.0
round() returns the closest integer (expressed as an int if the parameter was a float, or a long if the parameter was a double)
Method call
Returns
round(9.01)
9
round(9.5)
10
round(-9.5)
-9
round(-0.1)
0
round(100)
100
random() returns a random number, a double, between 0.0 and 1.0
sqrt() takes a double and returns a double. If the argument is NaN or <0, the result is NaN.
sin(), cos() and tan() all take a double and return a double.
All objects respond to toString(), which you can override to return a String representation of your object.
String objects have the following methods: length(), toUpperCase(), toLowerCase(), equals(), equalsIgnoreCase(), charAt(), indexOf(), lastIndexOf(), substring(), toString() and trim().
There are four versions of indexOf()
Arguments
Results
(int ch) - works if you put a char in!
Finds the first occurrence of this character
(int ch, int fromIndex)
Finds the first occurrence of this character starting from fromIndex
(String substring)
Finds the start of this substring
(String substring, int fromIndex)
Finds the start of this substring searching from fromIndex
There are four versions lastIndexOf() - as above table but, in each method, finding the last index rather than the first index.
First character in a String is at position 0, last character is at position length()-1
There are two versions of substring()
Arguments
Results
(int startIndex)
Returns a substring starting with startIndex and extending to the end of the String
(int startIndex, int endIndex)
Returns a substring starting with startIndex and extending to (but not including) endIndex

For a StrintoString() returns itself - the same object reference (obviously pointing to the same object) that was used to invoke the method.
trim() returns a new String object that cuts off any leading and trailing whitespace for the String for which it was invoked.
Java considers "whitespace" to be any character with a code less than or equal to ‘\u0020’ which is the space character.
Input/Output
InputStream and OutputStream are abstract classes.
FileInputStream and FilterInputStream both inherit directly from InputStream.
FileOutputStream and FilterOutputStream both inherit directly from OutputStream.
DataInputStream inherits directly from FilterInputStream.
DataOutputStream inherits directly from FilterOutputStream.
When you create a Filter stream, you must specify the stream to which it will attach.
A Filter stream processes a stream of bytes in some way. By "chaining" any number of Filter streams, you can add any amount of processing to a stream of bytes.
DataInputStream, DataOutputStream and RandomAccessFile know how to work with Java data types because they implement the DataInput and DataOutput interfaces, whereas FileInputStream and FileOutputStream know only how to work with individual bytes.
RandomAccessFile implements both DataInput and DataOutput methods - RandomAccessFile objects can read from and write to files.
The File class is not used to create files. Can create a file using an instance of class RandomAccessFile and FileOutputStream.
To test if a File object refers to an existing file, you can invoke exists() which returns true or false. The File methods canRead() and canWrite() return boolean values that indicate whether the application can read from or write to the file. (Note: applets can’t write to a file.)
Can use File methods to make a permanent change to the file system. For example, you can call delete() or rename(). For rename(), need to supply a File object which embodies the new name.
You can create a directory using the File class. The method mkdir() does this.
It is possible to navigate the filing system using the File class. Methods getParent(), getPath() and getName() are provided, and also getAbsolutePath().
The method getAbsolutePath() returns the name of the current user directory (the full pathname included) with the file name concatenated. See Practice Exam 1 Q.45
Creating a FileOutputStream object creates the appropriate file. If the file already exists, FileOutputStream replaces it (unless the FileOutputStream object is created using the constructor which takes a String and a boolean - see later)
Upon creation of a RandomAccessFile object, need to supply a file object plus a mode. Alternatively, can supply a filename plus a mode.
Valid modes for RandomAccessFile are "r" and "rw".
Constructors for FileInputStream: one takes a String, one takes a File, one takes a FileDescriptor
Constructors for FileOutputStream: one takes a String, one takes a File, one takes a FileDescriptor, one takes a String and a boolean (which indicates whether or not to append).
Constructors for FilterInputStream: one only, which takes an InputStream
Constructors for FilterOutputStream: one only, which takes an OutputStream
See Chapter 11 Review Questions for io stuff - very useful.
Threads
A Java program runs until the only threads left running are daemon threads.
A Thread can be set as a user or daemon thread when it is created.
In a standalone program, your class runs until your main() method exists - unless your main() method creates more threads.
You can initiate your own thread of execution by creating a Thread object, invoking its start() method, and providing the behaviour that tells the thread what to do. The thread will run until its run() method exists, after which it will come to a halt - thus ending its life cycle.
The Thread class, by default, doesn’t provide any behaviour for run().
There are two ways to provide the behaviour for a thread
Subclass the thread and override the run() method - see p.253 of Exam Guide.
Implement the Runnable interface and indicate an instance of this class will be the thread’s target.
A thread has a life cycle. Creating a new Thread instance puts the thread into the "new thread" state. When the start() method is invoked, the thread is then "alive" and "runnable". A thread at this point will repond to the method isAlive() by returning true.
The thread will continue to return true to isAlive() until it is "dead", no matter whether it is "runnable" or "not runnable".
If 2 threads are alive, with the same highest priority, the JVM switches between them. The JVM will switch between any number of threads with the same highest priority.
The priority numbers for threads falls between the range of Thread.MIN_PRIORITY and Thread.MAX_PRIORITY.
The default thread priority is Thread.NORM_PRIORITY.
New threads take on the priority of the thread that spawned them.
You can explicitly set the priority of a thread using setPriority(), and you can get the priority of a thread using getPriority(). There is no constructor for thread which takes a priority.
The JVM determines the priority of when a thread can run based on its priority ranking, but this doesn’t mean that a low priority thread will not run.
The currently executing thread can yield control by invoking yield(). If you invoke yield(), Java will pick a new thread to run. However, it is possible the thread that just yielded might run again immediately if it is the highest priority thread.
There are 3 types of code that can be synchronized: class methods, instance methods, any block of code within a method.
Variables cannot take the synchronized keyword.
Synchronization stays in effect if you enter a synchronized method and call out to a non-synchronized method. The thread only gives up the monitor after the synchronized method returns.
Using a thread’s stop() method will make it die.
There are 3 ways to transition a thread between "runnable" and "not runnable"

put it to sleep and wake it up
(not on the test)
pause it and resume it
(not on the test)
use the methods wait(), notify() and notifyAll() - these are methods of class Object. wait() throws InterruptedException.


The third method listed above allows communication between the threads, whereas the other 2 methods don’t.
By using the methods wait(), notify() and notifyAll(), any thread can wait for some condition in an object to change, and any thread can notify all threads waiting on that object’s condition that the condition has changed and that they should continue.
When a waiting thread pauses, it relinquishes the object’s monitor and waits to be notified that it should try to reacquire it.
If you know you only have one thread waiting on a condition, you can feel free to use notify(), otherwise you should use notifyAll(). The notifyAll() method wakes up all threads waiting to reacquire the monitor for the object.
The reasons why a thread might be "alive" and "not runnable" are as follows:
the thread is not the highest priority thread and so is not able to get CPU time
the thread has been put to sleep using the sleep() method (of class Thread. Throws InterruptedException)
the thread has been suspended using the suspend() method
the thread is waiting on a condition because someone invoked wait() for the thread
the thread has explicitly yielded control by invoking yield()
Graphical User Interfaces
If you want to explicitly repaint a component, you should not call paint() directly. Instead you should invoke your component’s repaint() method.
The repaint() method is overloaded. The no-args version of repaint() does not cause your user interface to repaint right away. In fact, when repaint() returns, your component has not yet been repainted - you’ve only issued a request for a repaint(). There is another version of repaint() that requests the component to be repainted within a certain number of milliseconds.
The repaint() method will cause AWT to invoke a component’s update() method. AWT passes a Graphics object to update() - the same one that it passes to paint(). So, repaint() calls update() which calls paint().
The Graphics object that AWT hands to update() and paint() is different every time the Component is repainted.
When Java repaints on its own, such as when the user resizes an applet, the AWT does not invoke update() - it just calls paint() directly.
The update() method does three things in this order:
clears the background of the object by filling it with its background colour
sets the current drawing colour to be its foreground colour
invokes paint(), passing it the Graphics object received
Common graphics methods:
drawString() - takes a String, followed by x then y co-ord of baseline for first char
drawLine() - takes x then y co-ords of starting point, then x then y co-ords of end point
drawRect() / fillRect() - take 4 params - x then y co-ords of top left corner, then width then height
drawOval() / fillOval() - take 4 params - x, y, width, height and draw an oval inside corresponding rectangle
drawPolygon() / fillPolygon() - (int[] xpoints, int[] ypoints, int npoints) - array of x co-ords then array of y co-ords followed by the number of points to use
drawArc() / fillArc() - takes 6 params - x then y co-ord of top left corner (of bounding rectangle of corresponding oval), width then height of arc, then start angle (not really an angle, more a position on the clock - 0 represents 3 o’clock), then number of degrees to move along the arc. Last parameter can also be negative, if you want to move in a clockwise direction round the arc.
The Image class does not provide a constructor for specifying where an image will come from.
You can obtain an Image, typically by downloading it from the Internet by specifying a URL. You can retrieve an image and obtain an Image object by invoking an Applet method named getImage(). This method takes a URL.
When the getImage() method returns, the data for the image is not necessarily immediately available. The method returns right away, even if the image resource is located over the Internet on a Web server and must be downloaded.
When you invoke the Graphics method drawImage() the image download begins. The object you specify as an ImageObserver keeps the Java graphics system up-to-date on the state of the download. When the ImageObserver sees that the download is complete, it notifies the graphics system that it can draw the image in its entirety.
ImageObserver is an interface. The Component class implements this interface, so any component (such as an Applet itself) can be used as an ImageObserver.
TextArea takes rows then cols in constructor. If you type in more text than can be displayed all at one, scrollbars appear automatically.
TextField takes only cols. A user may one type one line into a TextField. No scrollbars appear if the line is too long to be displayed, but can use arrow keys to move to beginning or end of text.
TextArea and TextField both inherit from TextComponent which provides a setEditable() method.
For a variable width font, TextArea / TextField width is based on average of letter widths.
Can populate a List using addItem() method.
As well as a no-args constructor and a constructor which takes number of rows, List class also has a constructor which takes number of rows followed by a boolean value which represents whether or not multiple list item selections are allowed.
Java 1.0
o Component methods for Java 1.0.2 - enable(), disable(), show(), hide(), size(), resize(), setForeground(), setBackground().
o enable() / disable() - make a component selectable or not by the user.
o size() / resize() - the size() method retrieves the size of the Component as a Dimension object which has two fields (width and height). The resize() method sets the size of the Component. The method is overloaded - one version takes a Dimension object and the other takes width and height directly as int values.
o show() / hide() - the show() method makes a Component visible, the hide() method makes a Component invisible. The show() method is overloaded so that you can supply a boolean parameter to indicate whether to show the Component (if the parameter is true).
o A Frame is only visible when the show() method has been invoked.
Java 1.1
o Component methods for Java 1.1 - setEnabled(), getSize(), setSize(), setVisible(), setForeground(), setBackground(). setEnabled() replaces enable() / disable() and takes a boolean value. getSize() and setSize() replace size() / resize(). setVisible() replaces show() / hide() and takes a boolean value.

Java provides a Color class which defines many static constants that contain instances of class Color already initialized to common colours. To use red, for example, you can access Color.red. The Color class has a constructor which takes three int values of red, green and blue so that you can make up your own colour.
Each container has exactly one layout manager which determines how to arrange the Components within a Container.
A layout manager is any class that implements the LayoutManager interface. Java’s 5 layout managers all inherit directly from class Object, but they implement the LayoutManager interface, which defines 5 abstract methods:
addLayoutComponent()
layoutContainer()
minimumLayoutSize()
preferredLayoutSize()
removeLayoutComponent()
Instead of invoking the layout manager’s methods yourself, Java’s default Container methods invoke them for you at the appropriate times. These Container methods include add(), getMinimumSize(), getPreferredSize(), remove() and removeAll() (these are all Java 1.1 methods).
Each type of container comes with a default layout manager. Default for a Frame, Window or Dialog is BorderLayout. Default for a Panel is FlowLayout().
A FlowLayout object arranges components left to right and top to bottom, centering each line as it goes. The FlowLayout layout manager is the only layout manager which allows components to be their preferred size. If a container using a FlowLayout is resized, all of the components inside it might need to be rearranged, and some might not be completely visible.
A BorderLayout object arranges components according to the directions "North", "South", "East" and "West". There’s also an area for "Center" which includes any space left over from other regions.
Components are rarely allowed to be their preferred size in a BorderLayout. BorderLayout stretches components. Stretches "North" and "South" components horizontally. Stretches "East" and "West" components vertically. Stretches "Center" components both horizontally and vertically.
If nothing is placed in "East" or "West", for example, then the "Center" stretches all the way from the left edge of the Container to the right edge.
Some components are stretchable and others are not. For example, Button, Label and TextField are stretchable, whereas Checkbox is not.
GridLayout objects allow you to specify a rectangular grid in which to place the components. Each cell in the grid is the same height as the other cells, and each width is the same as the other cells. Components are stretched both horizontally and vertically to fill the cell.
When a GridLayout object is first constructed, you must first specify how many rows and how many columns the grid will have. Components are added to the grid left to right and top to bottom. If more components are added than there are columns, the GridLayout keeps the same number of rows but adds the necessary number of columns.
You can change a Container’s layout manager to be a different one by invoking setLayout().
Event Handling
All of the events dispatched by AWT’s components use event classes that are subclasses of AWTEvent, which is in java.awt. These subclasses are defined in the java.awt.event package.
The AWT does not notify your event handler of every event that occurs over a component, as in the old days of 1.0.2. Now, AWT informs your event handler only about the events it is interested in.
Define a class which implements the necessary Listeners and then use the Component addABCListener() method to register an interest in a certain type of event, e.g. addMouseListener(this).
The Listener interfaces inherit directly from java.util.EventListener.
The Listener interfaces are
ActionListener
AdjustmentListener
ComponentListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
TextListener
WindowListener
If you define a class which implements a listener, you must obviously include stubs for those listener methods not implemented as interfaces are implicitly abstract and failure to implement all of the methods would result in an abstract subclass.
The Listener methods are as follows: (Note - all are declared as public void and all take only one parameter which is an Event of the same name as the Listener, i.e. ActionListener methods take an ActionEvent etc.
Listener
Methods
ActionListener
actionPerformed
AdjustmentListener
adjustmentPerformed
ComponentListener
componentHidden
componentMoved
componentResized
componentShown
ContainerListener
componentAddedcomponentRemoved
FocusListener
focusGainedfocusLost
ItemListener
itemStateChanged
KeyListener
keyPressed
keyReleased
keyTyped
MouseListener
mouseClicked
mouseEntered
mouseExited
mousePressed
mouseReleased
MouseMotionListener
mouseDraggedmouseMoved
TextListener
textValueChanged
WindowListener
windowClosed
windowClosing
windowDeiconified
windowActivated
windowDeactivated
windowIconified
windowOpened
See pages 360-363 for Event classes.
There’s an Adapter class to match each Listener interface. Each Adapter class defines no-op stubs for the methods declared in the corresponding interface. So can extend an Adapter rather than implement a Listener interface (but this only makes sense when the object that will listen for and handle the event has no other responsibilities).
Passing Arguments to Programs
The main() method must be declared as a public, static method that does not return a value and takes an array of String objects. The order of public and static, and the way in which the String array is defined, is not strictly enforced.
When main() ends, that may or may not be the end of the program. The JVM will run until the only remaining threads are daemon threads. If main() does not spawn any more threads, then the program will end when main() ends.
Embedding Applets into Web Pages
The applet tag requires three codewords - code, width and height, e.g.
If the applet is loaded relative to the page, there are two things that can change the base location - one of which is if the HTML file itself contains a tag - this tag specifies where to look for the applet class.
The conventional way to pass a parameter to an applet is to use the tag, using one tag per parameter. Each tag can take only one parameter.
Each parameter value can be retrieved by the applet as a String, using methods defined in class Applet.
If you want to pass a different type of value, such as an int or a boolean, you must convert it from a String, most likely by using a wrapper class.
If you’d like a parameter to contain spaces, you should place this value between quotes. Otherwise it’s not strictly necessary to pass params in quotes (good style though).
You retrieve the value of a parameter using the getParameter() method defined by the Applet class. This method returns a String containing the value of the parameter, or null if the parameter was not defined at all.
Class Applet inherits from Panel.
When an applet instance is first instantiated, Java invokes the applet’s init() method.
When the Web page containing the applet is about to appear, Java invokes the applet’s start() method.
When the Web page is about to be replaced with another page, Java invokes the applets stop() method.
When the Web page is removed from the browser’s cache and the applet instance is about to go away, Java invokes the applet’s destroy() method.
Inner Classes
In Java 1.1 you can define classes inside classes - these are known as "inner classes".
If you define an inner class at the same level as the enclosing class’ instance variables, the inner class can access those instance variables - no matter what their access control.
If you define an inner class within a method, the inner class can access the enclosing class’ instance variables and also the local variables and parameter for that method.
If you do reference local variables or parameters from an inner class, those variables or parameters must be declared as final to help guarantee data integrity.
You can also define an anonymous class - a class without a name. See p.399 Exam Guide for syntax.
If you’d like to refer to the current instance of the enclosing class, you can write EnclosingClassName.this.
If you need to refer to the inner class using a fully qualified name, you can write EnclosingClassName.InnerClassName.
If your inner class is not defined as static you can only create new instances of this class from a non-static method.
Anonymous classes cannot have const
JAR Files
JAR stands for "Java Archive". The 1.1 JDK comes with a utility called ‘jar’ that creates JAR files. Example syntax: jar -cf Jungle.jar Panther.class Leopard.class
Directories are processed recursively
Can specify a JAR file in a Web page by adding ‘archive="jars/Jungle.jar" ’ to the tag. E.g.
You can also define more than one JAR file in the archive value by listing them all within the quotes and separating their names with commas.
Serializing Objects
In Java 1.1 it is now possible to read and write objects as well as primitive data types, using classes that implement ObjectInput and ObjectOutput. These two interfaces extend DataInput and DataOutput to read or write an object. ObjectInputStream and ObjectOutputStream implement these interfaces.
If a class implements the Serializable interface, then its public and protected instance variables will be read from and written to the stream automatically when you use ObjectInputStream and ObjectOutputStream.
If an instance variable refers to another object, it will also be read or written, and this continues recursively.
If the referenced object does not implement the Serializable interface, Java will throw a NotSerializableException.
The Serializable interface serves only to identify those instances of a particular class that can be read from and written to a stream. It does not actually define any methods that you must implement.
If you create your own class and want to keep certain data from being read or written, you can declare that instance variable using the transient keyword. Java skips any variable declared as transient when it reads and writes the object following the Serializable protocol.
Reflection
Using the Reflection API, a program can determine a class’ accessible fields, methods and constructors at runtime.

1. What is the output of the following StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2= new StringBuffer("Amit"); String ss1 = "Amit"; System.out.println(sb1==sb2); System.out.println(sb1.equals(sb2)); System.out.println(sb1.equals(ss1)); System.out.println("Poddar".substring(3));
Ans: a) false false false dar b) false true false Poddar c) Compiler Error d) true true false dar
Correct Answer is a)
***** Look carefully at code and answer the following questions ( Q2 to Q8) 1 import java.applet.Applet; 2 import java.awt.*; 3 import java.awt.event.*; 4 public class hello4 extends Applet { 5 public void init(){ 6 add(new myButton("BBB")); 7 } 8 public void paint(Graphics screen) { 9 } 10 class myButton extends Button{ 11 myButton(String label){ 12 super(label); 13 } 14 public String paramString(){ 15 return super.paramString(); 16 } 17 } 18 public static void main(String[] args){ 19 Frame myFrame = new Frame( 20 "Copyright Amit"); 21 myFrame.setSize(300,100); 22 Applet myApplet = new hello4(); 23 Button b = new Button("My Button"); 24 myApplet.add(b); 25 b.setLabel(b.getLabel()+"New"); 26 // myButton b1 =(new hello4()).new myButton("PARAMBUTTON"); 27 System.out.println(b1.paramString()); 28 myFrame.add(myApplet); 29 myFrame.setVisible(true); 30 myFrame.addWindowListener(new WindowAdapter(){ 31 public void windowClosing(WindowEvent e){ 32 System.exit(0);}}); 33 } 34 } //End hello4 class.
Q2. If you run the above program via appletviewer ( defining a HTML file), You see on screen. a) Two buttons b) One button with label as "BBB" c) One button with label as "My ButtonNew" d) One button with label as "My Button"
Correct answer is b)
Q3. In the above code if line 26 is uncommented and program runs as standalone application
a) Compile Error b) Run time error c) It will print the the label as PARAMBUTTON for button b1
Correct answer is c)
Q4 In the code if you compile as "javac hello4.java" following files will be generated. a) hello4.class, myButton.class,hello41.class b)hello4.class, hello4$myButton.class,hello4$1.class c)hello4.clas,hello4$myButton.class
Correct answer is b)
Q5. If above program is run as a standalone application. How many buttons will be displayed
a) Two buttons b) One button with label as "BBB" c) One button with label as "My ButtonNew" d) One button with label as "My Button"
correct answer is C)
Q6. If from line no 14 keyword "public" is removed, what will happen.( Hint :paramString() method in java.awt.Button is a protected method. (Assume line 26 is uncommented)
a) Code will not compile. b) Code will compile but will give a run time error. c) Code will compile and no run time error.
Correct answer is a). As you can not override a method with weaker access privileges
Q7. If from line no 14 keyword "public" is replaced with "protected", what will happen.(Hint :paramString() method in java.awt.Button is a protected method.(Assume line 26 is uncommented)
a) Code will not compile. b) Code will compile but will give a run time error. c) Code will compile and no run time error.
Correct answer is c) . As you can access a protected variable in the same package.
Q8.If line no 26 is replaced with Button b1 = new Button("PARAMBUTTON").(Hint :paramString() method in java.awt.Button is a protected method.(Assume line 26 is uncommented)
a) Code will not compile. b) Code will compile but will give a run time error. c) Code will compile and no run time error.
Correct answer is a) Because protected variables and methods can not be accssed in another package directly. They can only be accessed if the class is subclassed and instance of subclass is used.
Q9. What is the output of following if the return value is "the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument" (Assuming written inside main)
String s5 = "AMIT"; String s6 = "amit"; System.out.println(s5.compareTo(s6)); System.out.println(s6.compareTo(s5)); System.out.println(s6.compareTo(s6));
Ans a> -32 32 0 b> 32 32 0 c> 32 -32 0 d> 0 0 0
Correct Answer is a)
Q10) What is the output (Assuming written inside main) String s1 = new String("amit"); String s2 = s1.replace('m','i'); s1.concat("Poddar"); System.out.println(s1); System.out.println((s1+s2).charAt(5));
a) Compile error b) amitPoddar o c) amitPoddar i d) amit i
Correct answer is d)As String is imutable.so s1 is always "amit". and s2 is "aiit".
Q11) What is the output (Assuming written inside main) String s1 = new String("amit"); System.out.println(s1.replace('m','r')); System.out.println(s1); String s3="arit"; String s4="arit"; String s2 = s1.replace('m','r'); System.out.println(s2==s3); System.out.println(s3==s4);
a) arit amit false true b) arit arit false true c) amit amit false true d) arit amit true true Correct answer is a) s3==s4 is true because java points both s3 and s4 to same memory location in string pool
Q12) Which one does not extend java.lang.Number 1)Integer 2)Boolean 3)Character 4)Long 5)Short
Correct answer is 2) and 3)
Q13) Which one does not have a valueOf(String) method 1)Integer 2)Boolean 3)Character 4)Long 5)Short Correct answer is 3)
Q.14) What is the output of following (Assuming written inside main) String s1 = "Amit"; String s2 = "Amit"; String s3 = new String("abcd"); String s4 = new String("abcd"); System.out.println(s1.equals(s2)); System.out.println((s1==s2)); System.out.println(s3.equals(s4)); System.out.println((s3==s4)); a) true true true false b) true true true true c) true false true false Correct answer is a)
Q15. Which checkbox will be selected in the following code ( Assume with main and added to a Frame) Frame myFrame = new Frame("Test"); CheckboxGroup cbg = new CheckboxGroup(); Checkbox cb1 = new Checkbox("First",true,cbg); Checkbox cb2 = new Checkbox("Scond",true,cbg); Checkbox cb3 = new Checkbox("THird",false,cbg); cbg.setSelectedCheckbox(cb3); myFrame.add(cb1); myFrame.add(cb2); myFrame.add(cb3); a) cb1 b) cb2,cb1 c) cb1,cb2,cb3 d) cb3
Correct Answer is d) As in a CheckboxGroup only one can be selected
Q16) Which checkbox will be selected in the following code ( Assume with main and added to a Frame) Frame myFrame = new Frame("Test"); CheckboxGroup cbg = new CheckboxGroup(); Checkbox cb1 = new Checkbox("First",true,cbg); Checkbox cb2 = new Checkbox("Scond",true,cbg); Checkbox cb3 = new Checkbox("THird",true,cbg); myFrame.add(cb1); myFrame.add(cb2); myFrame.add(cb3); a) cb1 b) cb2,cb1 c) cb1,cb2,cb3 d) cb3
Correct Answer is d) As in a CheckboxGroup only one can be selected
Q17) What will be the output of line 5 1 Choice c1 = new Choice(); 2 c1.add("First"); 3 c1.addItem("Second"); 4 c1.add("Third"); 5 System.out.println(c1.getItemCount()); a) 1 b) 2 c) 3 d) None of the above
Correct Answer is c)
Q18) What will be the order of four items added Choice c1 = new Choice(); c1.add("First"); c1.addItem("Second"); c1.add("Third"); c1.insert("Lastadded",2); System.out.println(c1.getItemCount()); a) First,Second,Third,Fourth b) First,Second,Lastadded,Third c) Lastadded,First,Second,Third
Correct ANswer is b)
Q19) Answer based on following code 1 Choice c1 = new Choice(); 2 c1.add("First"); 3 c1.addItem("Second"); 4 c1.add("Third"); 5 c1.insert("Lastadded",1000); 6 System.out.println(c1.getItemCount());
a) Compile time error b) Run time error at line 5 c) No error and line 6 will print 1000 d) No error and line 6 will print 4
Correct ANswer is d)
Q20) Which one of the following does not extends java.awt.Component
a) CheckBox b) Canvas c) CheckbocGroup d) Label
Correct answer is c)
Q21) What is default layout manager for panels and applets? a) Flowlayout b) Gridlayout c) BorderLayout
Correct answer is a)
Q22) For awt components which of the following statements are true?
a) If a component is not explicitly assigned a font, it usese the same font that it container uses. b) If a component is not explicitly assigned a foreground color , it usese the same foreground color that it container uses. c) If a component is not explicitly assigned a backround color , it usese the same background color that it container uses. d) If a component is not explicitly assigned a layout manager , it usese the same layout manager that it container uses.
correct answer is a),b),c)
Q23)java.awt.Component class method getLocation() returns Point (containg x and y cordinate).What does this x and y specify
a) Specify the postion of components lower-left component in the coordinate space of the component's parent. b) Specify the postion of components upper-left component in the coordinate space of the component's parent. c) Specify the postion of components upper-left component in the coordinate space of the screen.
correct answer is b)
Q24. What will be the output of follwing { double d1 = -0.5d; System.out.println("Ceil for d1 " + Math.ceil(d1)); System.out.println("Floor for d1 " +Math.floor(d1)); }
Answers: a) Ceil for d1 0 Floor for d1 -1; b) Ceil for d1 0 Floor for d1 -1.0; c) Ceil for d1 0.0 Floor for d1 -1.0; d) Ceil for d1 -0.0 Floor for d1 -1.0;
correct answer is d) as 0.0 is treated differently from -0.0
Q25. What is the output of following { float f4 = -5.5f; float f5 = 5.5f; float f6 = -5.49f; float f7 = 5.49f; System.out.println("Round f4 is " + Math.round(f4)); System.out.println("Round f5 is " + Math.round(f5)); System.out.println("Round f6 is " + Math.round(f6)); System.out.println("Round f7 is " + Math.round(f7)); } a)Round f4 is -6 Round f5 is 6 Round f6 is -5 Round f7 is 5
b)Round f4 is -5 Round f5 is 6 Round f6 is -5 Round f7 is 5
Correct answer is b)
Q26. Given Integer.MIN_VALUE = -2147483648 Integer.MAX_VALUE = 2147483647
What is the output of following
{ float f4 = Integer.MIN_VALUE; float f5 = Integer.MAX_VALUE; float f7 = -2147483655f; System.out.println("Round f4 is " + Math.round(f4)); System.out.println("Round f5 is " + Math.round(f5)); System.out.println("Round f7 is " + Math.round(f7)); }
a)Round f4 is -2147483648 Round f5 is 2147483647 Round f7 is -2147483648
b)Round f4 is -2147483648 Round f5 is 2147483647 Round f7 is -2147483655
correct answer is a) //Reason If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE. If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE. // From JDK api documentation
Q27) 1 Boolean b1 = new Boolean("TRUE"); 2 Boolean b2 = new Boolean("true"); 3 Boolean b3 = new Boolean("JUNK"); 4 System.out.println("" + b1 + b2 + b3);
a) Comiler error b) RunTime error c)truetruefalse d)truetruetrue
Correct answer is c)
Q28) In the above question if line 4 is changed to System.out.println(b1+b2+b3); The output is a) Compile time error b) Run time error c) truetruefalse d) truetruetrue
Correct answer is a) As there is no method to support Boolean + Boolean Boolean b1 = new Boolean("TRUE"); Think ----->System.out.println(b1); // Is this valid or not?
Q29. What is the output { Float f1 = new Float("4.4e99f"); Float f2 = new Float("-4.4e99f"); Double d1 = new Double("4.4e99"); System.out.println(f1); System.out.println(f2); System.out.println(d1); }
a) Runtime error b) Infinity -Infinity 4.4E99 c) Infinity -Infinity Infinity d) 4.4E99 -4.4E99 4.4E99
Correct answer is b)
Q30 Q. Which of the following wrapper classes can not take a "String" in constructor
1) Boolean 2) Integer 3) Long 4) Character 5) Byte 6) Short
correct answer is 4)
Q31. What is the output of following Double d2 = new Double("-5.5"); Double d3 = new Double("-5.5"); System.out.println(d2==d3); System.out.println(d2.equals(d3));
a) true true b) false false c) true false d) false true
Correct answer is d)
Q32) Which one of the following always honors the components's preferred size. a) FlowLayout b) GridLayout c) BorderLayout
Correct answer is a)
Q33) Look at the following code import java.awt.*; public class visual extends java.applet.Applet{ static Button b = new Button("TEST"); public void init(){ add(b); } public static void main(String args[]){ Frame f = new Frame("Visual"); f.setSize(300,300); f.add(b); f.setVisible(true); } }
What will happen if above code is run as a standalone application
a) Displays an empty frame b) Displays a frame with a button covering the entire frame c) Displays a frame with a button large enough to accomodate its label.
Correct answer is b) Reason- Frame uses Border Layout which places the button to CENTRE (By default) and ignores Button's preferred size.
Q34 If the code in Q33 is compiled and run via appletviewer what will happen a) Displays an empty applet b) Displays a applet with a button covering the entire frame c) Displays a applet with a button large enough to accomodate its label.
Correct answer is c) Reason- Applet uses FlowLayout which honors Button's preferred size.
Q35. What is the output public static void main(String args[]){ Frame f = new Frame("Visual"); f.setSize(300,300); f.setVisible(true); Point p = f.getLocation(); System.out.println("x is " + p.x); System.out.println("y is " + p.y); }
a) x is 300 y is 300 b) x is 0 y is 0 c) x is 0 y is 300
correct answer is b) Because postion is always relative to parent container and in this case Frame f is the topemost container
Q36) Which one of the following always ignores the components's preferred size. a) FlowLayout b) GridLayout c) BorderLayout
Correct answer is b)
Q37) Consider a directory structure like this (NT or 95) C:\JAVA\12345.msg --FILE \dir1\IO.class -- IO.class is under dir1
Consider the following code
import java.io.*; public class IO { public static void main(String args[]) { File f = new File("..\\12345.msg"); try{ System.out.println(f.getCanonicalPath()); System.out.println(f.getAbsolutePath()); }catch(IOException e){ System.out.println(e); } } }
What will be the output of running "java IO" from C:\java\dir1 a) C:\java\12345.msg C:\java\dir1\..\12345.msg
b) C:\java\dir1\12345.msg C:\java\dir1\..\12345.msg
c) C:\java\dir1\..\12345.msg C:\java\dir1\..\12345.msg
correct answer is a) as getCanonicalPath Returns the canonical form of this File object's pathname. The precise definition of canonical form is system-dependent, but it usually specifies an absolute pathname in which all relative references and references to the current user directory have been completely resolved. WHERE AS getAbsolutePath Returns the absolute pathname of the file represented by this object. If this object represents an absolute pathname, then return the pathname. Otherwise, return a pathname that is a concatenation of the current user directory, the separator character, and the pathname of this file object.
Q38) Suppose we copy IO.class from C:\java\dir1 to c:\java What will be the output of running "java IO" from C:\java. a) C:\java\12345.msg C:\java\..\12345.msg
b) C:\12345.msg C:\java\..\12345.msg
c) C:\java\..\12345.msg C:\java\\..\12345.msg
correct answer is b)
Q39) Which one of the following methods of java.io.File throws IOException and why
a) getCanonicalPath and getAbsolutePath both require filesystem queries. b) Only getCannonicalPath as it require filesystem queries. c) Only getAbsolutePath as it require filesystem queries.
Correct answer is b)
Q40) What will be the output if Consider a directory structure like this (NT or 95) C:\JAVA\12345.msg --FILE \dir1\IO.class -- IO.class is under dir1
import java.io.*; public class IO { public static void main(String args[]) { File f = new File("12345.msg"); String arr[] = f.list(); System.out.println(arr.length); } }
a) Compiler error as 12345.msg is a file not a directory b) java.lang.NullPointerException at run time c) No error , but nothing will be printed on screen
Correct ansewer is b)
Q41) What will be the output Consider a directory structure like this (NT or 95) C:\JAVA\12345.msg --FILE
import java.io.*; public class IO { public static void main(String args[]) { File f1 = new File("\\12345.msg"); System.out.println(f1.getPath()); System.out.println(f1.getParent()); System.out.println(f1.isAbsolute()); System.out.println(f1.getName()); System.out.println(f1.exists()); System.out.println(f1.isFile()); } }
a) \12345.msg \ true 12345.msg true true
b) \12345.msg \ true \12345.msg false false
c) 12345.msg \ true 12345.msg false false d) \12345.msg \ true 12345.msg false false
correct answer is d)
Q42) If in question no 41 the line File f1 = new File("\\12345.msg"); is replaced with File f1 = new File("12345.msg"); What will be the output
a) 12345.msg \ true 12345.msg true true
b) 12345.msg null true 12345.msg true true c) 12345.msg null false 12345.msg true true
d) \12345.msg \ true 12345.msg false false Correct answer is c)

1.Float a = new Float(10.0F);
Float b = new Float(10.0F);
Long c = new Long(10L);
which one is true
a) a == b
b) a.equals(b)
c) a.equals(c)
d) a.equals(new Float(10.0F))
Answer: B & D
2. From given code, which are possible values for 'a' to print "test2" in output
if (a >4)
System.out.println("test1");
Else if (a >9)
System.out.println("test2");
Else
System.out.println("test3");
a.less than 0
b.less than 4
c.between 4 and 9
d.greater than 9
e.none
Answer: E
3. Choose the correct sentence for fully encapsulated class
a.All member variables are private
b.All member variables declared private and provide
public accessor methods for each variable.
c.Declare all variables without any access modifier.
e.Make all the methods private
Answer: B
4.You have a method in a class whose implementation you don't
want to change although you want to allow the class to be inherited
and used freely. What keyword would u use in the method declaration?
Answer: final
5.Choose correct declarations of two dimensional String array
a.String[][] a = String[20][20]
b.String[][] a = new String[20,20]
c.String[][] a = new String[20][20]
d.String a[][] = new String[20][20]
e.String[] a[] = new String[20]20]
Answer: C,D & E
6.Quesion on identifiers like Choose Correct identifiers
a.thisString
b.%var
c._toString
d._4_
Answer : A,C & D
7.choose the correct statement about gridbag layout
a.The weightx & weighty should have values between 0.0 & 1.0
b.If you specify the fill field is BOTH, there is no meaaning to set anchor field
c.If you specify anchoe field there is no meaning to set fill field is BOTH
Like this
Ans A
8.A question on Garbage collecting like it wiil ask you where the particlular
object exactly available to garbage collection
after line3
after line4
after line5
like this
9.What is the return type of main function which is the starting point of class
Ans void
10.Choose the Java key words from below
a.NULL
b.sizeof
c.extends
d.synchronized
Answer : C & D
11.Employee is a person. Employee has some info stored in vector,
no. of dependants, a flag tells is he IT asesse or not
Write a primary declaration for employee class by using the below words
public
Person
Employee
Vector
Boolean
int
class
extends
Ans : public class Employee extends Person
12.FilterInputStream is base class for BufferedInputStream and DataInputStream.
Choose the correct one which is the correct argument for the FilterInputStream
a.file
b.OutputStream
c.RandomAccessFile
d.InputStream
Answer : D
13.If you want to make your component to activate for user events,
choose the statements which are correct
a.you can add listener interfaces to this component
b.If you add multiple listeners they will become friendly to each other
c.You can add multiple interfaces to the component for different events
d.If listeners added, user can choose and implement only those methods what he needs
e.The component which is derived from awt.component is not listen the events for it self.
Answer : A,C
14.Choose the correct one about thread
a.The threads from one class ends at same time
b.when JVM exits the main method, it will stop only after all the threads are stopped.
c.If there are multiple threads , reading or writing of data of class is inconsistant
d.Programmer has to write a special programe for garbage collection in multiple threads
Answer B & C


15. Parent p = new Parent();
Child1 c1 = new Child1();
Child2 c2 = new Child2();
Child1 s = (Child1) new Parent;
Which one is correct
a)legal at compile time but illegal at runtime
b)illegal at compile time and runtime
c)illegal at compile time but legal at runtime
d)legal at compile time and runtime
Answer : A
16.Which one is valid for declaring the automatic variable
(method local variables)
public
final
static
Answer: final
17.which is java modifier to use method declaration
prevents to use 'this' in the method
Answer: static
18 from given code, which are possible values for 'a' to print
"test3" in output
if (a >4)
System.out.println("test1");
Else if (a >9)
System.out.println("test2");
Else
System.out.println("test3");
a.less than 0
b.less than 4
c.between 4 and 9
d.greater than 9
e.none
Answer : B
19. Range of the int

20. Range of the char
21. Parameters for main method in Java :
Answer : String [] arv
22. Interface with out order, duplicate and with out any search key.
: Set
23.
Public class MyClass{
Float x, float y;
Int z;
public MyClass(float a, float b)
{
x= a;
y=b;
}
public MyClass(float a,float b, int c)
{
// write code to do what MyClass (float a,float b ) is doing
z =c;
}
Answer : this(a,b)
24. write the code in Hex for 7
Answer : 0x07
25. Polygon is a Shape. This class has to access from any where is
the program..
Answer: public class Polygon extends Shape
26. String s = "Test"; Select all correct ans.
1. char c = "s";
2. s= s.append("For ")
3. s.length();
4. s.trim();
5. s = "For " + s;
Answer : 3,4 & 5
trim() returns the trimmed string so the output needs to be
assigned to another string as in :- s=s.trim();
27. In design the employee has the tasks in vector, Joining Date and
no. of depends. So following fields should be available in the class
of employee.
String
Vector
Date
Int
Float
Person
28. All the methods in Listener Interfaces should be
private
public
protected
undefined (friendly)
static
final
29. >> and >>> are
a.unsigned right shift and right rotate
b.unsigned right shift and signed right shift.
c.signed right shift and unsigned right shift.
d.Signed left shift and unsigned right shift.
e.signed left shift and unsigned left shift.
Answer : C
30 Best way to read the file as Strings.
Like
DataInputStream dis = new DataInputStream (new FileInputStream("test.txt"));
BufferedInputStream bis = new BufferInputStream (new FileInputStream("test"));
31.The parameter as to be passed for FilterInputStream.
File
String
Empty
FileReader
InputStream
32. Which of the following statements is true about the above code?
import java.awt.*;
import java.awt.event.*;
public class fram extends Frame
{
public static void main(String arg[])
{
fram f=new fram();
String msg="hello";
Button b=new Button("Click");
b.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println(msg);
}
}
);
f.add(b);
f.pack();
f.show();
}
}
a.The code will not compile complaining that no layout has been
defined for the frame.
b.The code compiles and doesn't display anything.
c.The code runs and shows a single button occupying the whole frame.
On clicking the button you get the message "hello" at the Std o/p.
d.The code does not compile complaining about the inaccessibility of
a certain variable.
e.The code doesn't compile complaining that the constructor for fram
has not been defined.
Answer : D
the compilation error is
"Attempt to use a non-final variable msg from a different
method.From enclosing blocks, only final local variables are available.
System.out.println(msg);
^
"

33. Which of the following ?
1. public class sb
2.{
3. static public void main(String jk[])
{
StringBuffer s1=new StringBuffer("Hello");
StringBuffer s2=new StringBuffer("Hello");
meth(s1,s2);
System.out.println(s1+"\n"+s2);
}
private static void meth(StringBuffer s1,StringBuffer s2)
{
s2.append(" there");
s1=s2;
}
}
a.The code doesn't compile; it complains at line 3.
b.The code runs and produces O/p : Hello
Hello
c.The code runs and produces O/p : Hello
Hello there
d.The code runs and produces O/p : Hello there
Hello there
e.The code fails to compile saying the method meth is
declared private and is not accessible.
Answer : C
34. Which of the following?
class exSuper
{
public void func(String p,String s)
{
System.out.println(p);
}
}
public class example extends exSuper
{
public void func(String p,String s)
{
System.out.println(p+ " : " +s);
}
static public void main(String arg[])
{
exSuper e1=new exSuper();
e1.func("hello1","hi1");
exSuper e2=new example();
e2.func("hello2","hi2");
}
}
a.The code compiles and produces O/p : hello1 h1
hello2 hi2
b.The code compiles and produces O/p : hello1
hello2 hi2
c.The code compiles and produces O/p : hello1
hello2
d.The code compiles and produces O/p : hello1 h1
hello2
e.The code doesn't compile
Answer : B
1) The Java interpreter is used for the execution of the source code.
a) True
b) False
Ans: a.
2) On successful compilation a file with the class extension is created.
a) True
b) False
Ans: a.
3) The Java source code can be created in a Notepad editor.
a) True
b) False
Ans: a.
4) The Java Program is enclosed in a class definition.
a) True
b) False
Ans: a.
5) What declarations are required for every Java application?
Ans: A class and the main( ) method declarations.
6) What are the two parts in executing a Java program and their purposes?
Ans: Two parts in executing a Java program are:
Java Compiler and Java Interpreter.
The Java Compiler is used for compilation and the Java Interpreter is used for execution of the application.
7) What are the three OOPs principles and define them?
Ans : Encapsulation, Inheritance and Polymorphism are the three OOPs Principles.
Encapsulation:
Is the Mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse.
Inheritance:
Is the process by which one object acquires the properties of another object.
Polymorphism:
Is a feature that allows one interface to be used for a general class of actions.
8) What is a compilation unit?
Ans : Java source code file.
9) What output is displayed as the result of executing the following statement?
System.out.println("// Looks like a comment.");
// Looks like a comment
The statement results in a compilation error
Looks like a comment
No output is displayed
Ans : a.
10) In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true?
It must have a package statement
It must be named Test.java
It must import java.lang
It must declare a public class named Test
Ans : b
11) What are identifiers and what is naming convention?
Ans : Identifiers are used for class names, method names and variable names. An identifier may be any descriptive sequence of upper case & lower case letters,numbers or underscore or dollar sign and must not begin with numbers.
12) What is the return type of program’s main( ) method?
Ans : void
13) What is the argument type of program’s main( ) method?
Ans : string array.
14) Which characters are as first characters of an identifier?
Ans : A – Z, a – z, _ ,$
15) What are different comments?
Ans : 1) // -- single line comment
2) /* --
*/ multiple line comment
3) /** --
*/ documentation
16) What is the difference between constructor method and method?
Ans : Constructor will be automatically invoked when an object is created. Whereas method has to be call explicitly.
17) What is the use of bin and lib in JDK?
Ans : Bin contains all tools such as javac, applet viewer, awt tool etc., whereas Lib
contains all packages and variables.
Data types,variables and Arrays
1) What is meant by variable?
Ans: Variables are locations in memory that can hold values. Before assigning any value to a variable, it must be declared.
2) What are the kinds of variables in Java? What are their uses?
Ans: Java has three kinds of variables namely, the instance variable, the local variable and the class variable.
Local variables are used inside blocks as counters or in methods as temporary variables and are used to store information needed by a single method.
Instance variables are used to define attributes or the state of a particular object and are used to store information needed by multiple methods in the objects.
Class variables are global to a class and to all the instances of the class and are useful for communicating between different objects of all the same class or keeping track of global states.
3) How are the variables declared?
Ans: Variables can be declared anywhere in the method definition and can be initialized during their declaration.They are commonly declared before usage at the beginning of the definition.
Variables with the same data type can be declared together. Local variables must be given a value before usage.
4) What are variable types?
Ans: Variable types can be any data type that java supports, which includes the eight primitive data types, the name of a class or interface and an array.
5) How do you assign values to variables?
Ans: Values are assigned to variables using the assignment operator =.
6) What is a literal? How many types of literals are there?
Ans: A literal represents a value of a certain type where the type describes how that value behaves.
There are different types of literals namely number literals, character literals,
boolean literals, string literals,etc.
7) What is an array?
Ans: An array is an object that stores a list of items.
8) How do you declare an array?
Ans: Array variable indicates the type of object that the array holds.
Ex: int arr[];
9) Java supports multidimensional arrays.
a)True
b)False
Ans: a.
10) An array of arrays can be created.
a)True
b)False
Ans: a.
11) What is a string?
Ans: A combination of characters is called as string.
12) Strings are instances of the class String.
a)True
b)False
Ans: a.
13) When a string literal is used in the program, Java automatically creates instances of the string class.
a)True
b)False
Ans: a.
14) Which operator is to create and concatenate string?
Ans: Addition operator(+).
15) Which of the following declare an array of string objects?
String[ ] s;
String [ ]s:
String[ s]:
String s[ ]:
Ans : a, b and d
16) What is the value of a[3] as the result of the following array declaration?
1
2
3
4
Ans : d

17) Which of the following are primitive types?
byte
String
integer
Float
Ans : a.
18) What is the range of the char type?
0 to 216
0 to 215
0 to 216-1
0 to 215-1
Ans. d
19) What are primitive data types?
Ans : byte, short, int, long
float, double
boolean
char
20) What are default values of different primitive types?
Ans : int - 0 short - 0 byte - 0 long - 0 l float - 0.0 f double - 0.0 d boolean - false
char - null
21) Converting of primitive types to objects can be explicitly.
a)True
b)False
Ans: b.
22) How do we change the values of the elements of the array?
Ans : The array subscript expression can be used to change the values of the elements of the array.
23) What is final varaible?
Ans : If a variable is declared as final variable, then you can not change its value. It becomes constant.
24) What is static variable?
Ans : Static variables are shared by all instances of a class.
Operators
1) What are operators and what are the various types of operators available in Java?
Ans: Operators are special symbols used in expressions.
The following are the types of operators:
Arithmetic operators,
Assignment operators,
Increment & Decrement operators,
Logical operators,
Biwise operators,
Comparison/Relational operators and
Conditional operators
2) The ++ operator is used for incrementing and the -- operator is used for decrementing.
a)True
b)False
Ans: a.
3) Comparison/Logical operators are used for testing and magnitude.
a)True
b)False
Ans: a.
4) Character literals are stored as unicode characters.
a)True
b)False
Ans: a.
5) What are the Logical operators?
Ans: OR(), AND(&), XOR(^) AND NOT(~).
6) What is the % operator?
Ans : % operator is the modulo operator or reminder operator. It returns the reminder of dividing the first operand by second operand.
7) What is the value of 111 % 13?
3
5
7
9
Ans : c.
8) Is &&= a valid operator?
Ans : No.
9) Can a double value be cast to a byte?
Ans : Yes
10) Can a byte object be cast to a double value ?
Ans : No. An object cannot be cast to a primitive value.
11) What are order of precedence and associativity?
Ans : Order of precedence the order in which operators are evaluated in expressions.
Associativity determines whether an expression is evaluated left-right or right-left.
12) Which Java operator is right associativity?
Ans : = operator.
13) What is the difference between prefix and postfix of -- and ++ operators?
Ans : The prefix form returns the increment or decrement operation and returns the value of the increment or decrement operation.
The postfix form returns the current value of all of the expression and then
performs the increment or decrement operation on that value.
14) What is the result of expression 5.45 + "3,2"?
The double value 8.6
The string ""8.6"
The long value 8.
The String "5.453.2"
Ans : d
15) What are the values of x and y ?
x = 5; y = ++x;
Ans : x = 6; y = 6
16) What are the values of x and z?
x = 5; z = x++;
Ans : x = 6; z = 5
Control Statements
1) What are the programming constructs?
Ans: a) Sequential
b) Selection -- if and switch statements
c) Iteration -- for loop, while loop and do-while loop
2) class conditional {
public static void main(String args[]) {
int i = 20;
int j = 55;
int z = 0;
z = i < j ? i : j; // ternary operator
System.out.println("The value assigned is " + z);
}
}
What is output of the above program?
Ans: The value assigned is 20
3) The switch statement does not require a break.
a)True
b)False
Ans: b.
4) The conditional operator is otherwise known as the ternary operator.
a)True
b)False
Ans: a.
5) The while loop repeats a set of code while the condition is false.
a)True
b)False
Ans: b.
6) The do-while loop repeats a set of code atleast once before the condition is tested.
a)True
b)False
Ans: a.
7) What are difference between break and continue?
Ans: The break keyword halts the execution of the current loop and forces control out of the loop.
The continue is similar to break, except that instead of halting the execution of the loop, it starts the next iteration.
8) The for loop repeats a set of statements a certain number of times until a condition is matched.
a)True
b)False
Ans: a.
9) Can a for statement loop indefintely?
Ans : Yes.
10) What is the difference between while statement and a do statement/
Ans : A while statement checks at the beginning of a loop to see whether the next loop iteration should occur.
A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
Introduction to Classes and Methods
1) Which is used to get the value of the instance variables?
Ans: Dot notation.
2) The new operator creates a single instance named class and returns a
reference to that object.
a)True
b)False
Ans: a.
3) A class is a template for multiple objects with similar features.
a)True
b)False
Ans: a.
4) What is mean by garbage collection?
Ans: When an object is no longer referred to by any variable, Java automatically
reclaims memory used by that object. This is known as garbage collection.
5) What are methods and how are they defined?
Ans: Methods are functions that operate on instances of classes in which they are defined.Objects can communicate with each other using methods and can call methods in other classes.
Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method.
A method's signature is a combination of the first three parts mentioned above.
6) What is calling method?
Ans: Calling methods are similar to calling or referring to an instance variable. These methods are accessed using dot notation.
Ex: obj.methodname(param1,param2)
7) Which method is used to determine the class of an object?
Ans: getClass( ) method can be used to find out what class the belongs to. This class is defined in the object class and is available to all objects.
8) All the classes in java.lang package are automatically imported when
a program is compiled.
a)True
b)False
Ans: a.
9) How can class be imported to a program?
Ans: To import a class, the import keyword should be used as shown.;import classname;

10) How can class be imported from a package to a program?
Ans: import java . packagename . classname (or) import java.package name.*;
11) What is a constructor?
Ans: A constructor is a special kind of method that determines how an object is initialized when created.
12) Which keyword is used to create an instance of a class?
Ans: new.
13) Which method is used to garbage collect an object?
Ans: finalize ().
14) Constructors can be overloaded like regular methods.
a)True
b)False
Ans: a.
15) What is casting?
Ans: Casting is bused to convert the value of one type to another.
16) Casting between primitive types allows conversion of one primitive type to another.
a)True
b)False
Ans: a.
17) Casting occurs commonly between numeric types.
a)True
b)False
Ans: a.

18) Boolean values can be cast into any other primitive type.
a)True
b)False
Ans: b.
19) Casting does not affect the original object or value.
a)True
b)False
Ans: a.
20) Which cast must be used to convert a larger value into a smaller one?
Ans: Explicit cast.
21) Which cast must be used to cast an object to another class?
Ans: Specific cast.
22) Which of the following features are common to both Java & C++?
A.The class declaration
b.The access modifiers
c.The encapsulation of data & methods with in objects
d.The use of pointers
Ans: a,b,c.
23) Which of the following statements accurately describe the use of access modifiers within a class definition?
a.They can be applied to both data & methods
b.They must precede a class's data variables or methods
c.They can follow a class's data variables or methods
d.They can appear in any order
e.They must be applied to data variables first and then to methods
Ans: a,b,d.
24) Suppose a given instance variable has been declared private.Can this instance variable be manipulated by methods out side its class?
a.yes
b.no
Ans: b.
25) Which of the following statements can be used to describe a public method?
a.It is accessible to all other classes in the hierarchy
b.It is accessablde only to subclasses of its parent class
c.It represents the public interface of its class
d.The only way to gain access to this method is by calling one of the public class methods
Ans: a,c.
26) Which of the following types of class members can be part of the internal part of a class?
a.Public instance variables
b.Private instance variables
c.Public methods
d.Private methods
Ans: b,d.
27) You would use the ____ operator to create a single instance of a named class.
a.new
b.dot
Ans: a.
28) Which of the following statements correctly describes the relation between an object and the instance variable it stores?
a.Each new object has its own distinctive set of instance variables
b.Each object has a copy of the instance variables of its class
c.the instance variable of each object are seperate from the variables of other objects
d.The instance variables of each object are stored together with the variables of other objects
Ans: a,b,c.
29) If no input parameters are specified in a method declaration then the declaration will include __.
a.an empty set of parantheses
b.the term void
Ans: a.
30) What are the functions of the dot(.) operator?
a.It enables you to access instance variables of any objects within a class
b.It enables you to store values in instance variables of an object
c.It is used to call object methods
d.It is to create a new object
Ans: a,b,c.
31) Which of the following can be referenced by this variable?
a.The instance variables of a class only
b.The methods of a class only
c.The instance variables and methods of a class
Ans: c.
32) The this reference is used in conjunction with ___methods.
a.static
b.non-static
Ans: b.
33) Which of the following operators are used in conjunction with the this and super references?
a.The new operator
b.The instanceof operator
c.The dot operator
Ans: c.
34) A constructor is automatically called when an object is instantiated
a. true
b. false
Ans: a.
35) When may a constructor be called without specifying arguments?
a. When the default constructor is not called
b. When the name of the constructor differs from that of the class
c. When there are no constructors for the class
Ans: c.
36) Each class in java can have a finalizer method
a. true
b.false
Ans: a.
37) When an object is referenced, does this mean that it has been identified by the finalizer method for garbage collection?
a.yes
b.no
Ans: b.
38) Because finalize () belongs to the java.lang.Object class, it is present in all ___.
a.objects
b.classes
c.methods
Ans: b.
39) Identify the true statements about finalization.
a.A class may have only one finalize method
b.Finalizers are mostly used with simple classes
c.Finalizer overloading is not allowed
Ans: a,c.
40) When you write finalize() method for your class, you are overriding a finalizer inheritd from a super class.
a.true
b.false
Ans: a.
41) Java memory management mechanism garbage collects objects which are no longer referenced
a true
b.false
Ans: a.
42) are objects referenced by a variable candidates for garbage collection when the variable goes out of scope?
a yes
b. no
Ans: a.
43) Java's garbage collector runs as a ___ priority thread waiting for __priority threads to relinquish the processor.
a.high
b.low
Ans: a,b.
44) The garbage collector will run immediately when the system is out of memory
a.true
b.false
Ans: a.
45) You can explicitly drop a object reference by setting the value of a variable whose data type is a reference type to ___
Ans: null
46) When might your program wish to run the garbage collecter?
a. before it enters a compute-intense section of code
b. before it enters a memory-intense section of code
c. before objects are finalized
d. when it knows there will be some idle time
Ans: a,b,d
47) For externalizable objects the class is solely responsible for the external format of its contents
a.true
b.false
Ans: a
48) When an object is stored, are all of the objects that are reachable from that object stored as well?
a.true
b.false
Ans: a
49) The default__ of objects protects private and trancient data, and supports the __ of the classes
a.evolution
b.encoding
Ans: b,a.
50) Which are keywords in Java?
a) NULL
b) sizeof
c) friend
d) extends
e) synchronized
Ans : d and e
51) When must the main class and the file name coincide?
Ans :When class is declared public.
52) What are different modifiers?
Ans : public, private, protected, default, static, trancient, volatile, final, abstract.
53) What are access modifiers?
Ans : public, private, protected, default.
54) What is meant by "Passing by value" and " Passing by reference"?
Ans : objects – pass by referrence
Methods - pass by value
55) Is a class a subclass of itself?
Ans : A class is a subclass itself.
56) What modifiers may be used with top-level class?
Ans : public, abstract, final.
57) What is an example of polymorphism?
Inner class
Anonymous classes
Method overloading
Method overriding
Ans : c
Packages and interface
1) What are packages ? what is use of packages ?
Ans :The package statement defines a name space in which classes are stored.If you omit the package, the classes are put into the default package.
Signature... package pkg;
Use: * It specifies to which package the classes defined in a file belongs to. * Package is both naming and a visibility control mechanism.
2) What is difference between importing "java.applet.Applet" and "java.applet.*;" ?
Ans :"java.applet.Applet" will import only the class Applet from the package java.applet
Where as "java.applet.*" will import all the classes from java.applet package.
3) What do you understand by package access specifier?
Ans : public: Anything declared as public can be accessed from anywhere
private: Anything declared in the private can’t be seen outside of its class.
default: It is visible to subclasses as well as to other classes in the same package.
4) What is interface? What is use of interface?
Ans : It is similar to class which may contain method’s signature only but not bodies.
Methods declared in interface are abstract methods. We can implement many interfaces on a class which support the multiple inheritance.
5) Is it is necessary to implement all methods in an interface?
Ans : Yes. All the methods have to be implemented.
6) Which is the default access modifier for an interface method?
Ans : public.
7) Can we define a variable in an interface ?and what type it should be ?
Ans : Yes we can define a variable in an interface. They are implicitly final and static.
8) What is difference between interface and an abstract class?
Ans : All the methods declared inside an Interface are abstract. Where as abstract class must have at least one abstract method and others may be concrete or abstract.
In Interface we need not use the keyword abstract for the methods.
9) By default, all program import the java.lang package.
True/False
Ans : True
10) Java compiler stores the .class files in the path specified in CLASSPATH
environmental variable.
True/False
Ans : False
11) User-defined package can also be imported just like the standard packages.
True/False
Ans : True
12) When a program does not want to handle exception, the ______class is used.
Ans : Throws
13) The main subclass of the Exception class is _______ class.
Ans : RuntimeException
14) Only subclasses of ______class may be caught or thrown.
Ans : Throwable
15) Any user-defined exception class is a subclass of the _____ class.
Ans : Exception
16) The catch clause of the user-defined exception class should ______ itsBase class catch clause.
Ans : Exception
17) A _______ is used to separate the hierarchy of the class while declaring an Import statement.
Ans : Package
18) All standard classes of Java are included within a package called _____.
Ans : java.lang
19) All the classes in a package can be simultaneously imported using ____.
Ans : *
20) Can you define a variable inside an Interface. If no, why? If yes, how?
Ans.: YES. final and static
21) How many concrete classes can you have inside an interface?
Ans.: None
22) Can you extend an interface?
Ans.: Yes
23) Is it necessary to implement all the methods of an interface while implementing the interface?
Ans.: No
24) If you do not implement all the methods of an interface while implementing , what specifier should you use for the class ?
Ans.: abstract
25) How do you achieve multiple inheritance in Java?
Ans: Using interfaces.
26) How to declare an interface example?
Ans : access class classname implements interface.
27) Can you achieve multiple interface through interface?
a)True
b) false
Ans : a.
28) Can variables be declared in an interface ? If so, what are the modifiers?
Ans : Yes. final and static are the modifiers can be declared in an interface.
29) What are the possible access modifiers when implementing interface methods?
Ans : public.
30) Can anonymous classes be implemented an interface?
Ans : Yes.
31) Interfaces can’t be extended.
a)True
b)False
Ans : b.
32) Name interfaces without a method?
Ans : Serializable, Cloneble & Remote.
33) Is it possible to use few methods of an interface in a class ? If so, how?
Ans : Yes. Declare the class as abstract.
Exception Handling
1) What is the difference between ‘throw’ and ‘throws’ ?And it’s application?
Ans : Exceptions that are thrown by java runtime systems can be handled by Try and catch blocks. With throw exception we can handle the exceptions thrown by the program itself. If a method is capable of causing an exception that it does not handle, it must specify this behavior so the callers of the method can guard
against that exception.
2) What is the difference between ‘Exception’ and ‘error’ in java?
Ans : Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. With exception class we can subclass to create our own custom exception.Error defines exceptions that are not excepted to be caught by you program. Example is Stack Overflow.
3) What is ‘Resource leak’?
Ans : Freeing up other resources that might have been allocated at the beginning of a method.
4)What is the ‘finally’ block?
Ans : Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute.
5) Can we have catch block with out try block? If so when?
Ans : No. Try/Catch or Try/finally form a unit.
6) What is the difference between the following statements?
Catch (Exception e),
Catch (Error err),
Catch (Throwable t)
Ans :
7) What will happen to the Exception object after exception handling?
Ans : It will go for Garbage Collector. And frees the memory.
8) How many Exceptions we can define in ‘throws’ clause?
Ans : We can define multiple exceptions in throws clause.
Signature is..type method-name (parameter-list) throws exception-list
9) The finally block is executed when an exception is thrown, even if no catch matches it.
True/False
Ans : True
10) The subclass exception should precede the base class exception when used within the catch clause.
True/False
Ans : True
11) Exceptions can be caught or rethrown to a calling method.
True/False
Ans : True
12) The statements following the throw keyword in a program are not executed.
True/False
Ans : True
13) The toString ( ) method in the user-defined exception class is overridden.
True/False
Ans : True
MULTI THREADING
1) What are the two types of multitasking?
Ans : 1.process-based
2.Thread-based
2) What are the two ways to create the thread?
Ans : 1.by implementing Runnable
2.by extending Thread
3) What is the signature of the constructor of a thread class?
Ans : Thread(Runnable threadob,String threadName)
4) What are all the methods available in the Runnable Interface?
Ans : run()
5) What is the data type for the method isAlive() and this method is available in which class?
Ans : boolean, Thread
6) What are all the methods available in the Thread class?
Ans : 1.isAlive() 2.join() 3.resume() 4.suspend() 5.stop() 6.start() 7.sleep() 8.destroy()
7) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?
Ans :1. wait(),notify() & notifyall()
2. Object class
8) What is the mechanisam defind by java for the Resources to be used by only one Thread at a time?
Ans : Synchronisation
9) What is the procedure to own the moniter by many threads?
Ans : not possible
10) What is the unit for 1000 in the below statement?
ob.sleep(1000)
Ans : long milliseconds
11) What is the data type for the parameter of the sleep() method?
Ans : long
12) What are all the values for the following level?
max-priority
min-priority
normal-priority
Ans : 10,1,5
13) What is the method available for setting the priority?
Ans : setPriority()
14) What is the default thread at the time of starting the program?
Ans : main thread
15) The word synchronized can be used with only a method.
True/ False
Ans : False
16) Which priority Thread can prompt the lower primary Thread?
Ans : Higher Priority
17) How many threads at a time can access a monitor?
Ans : one
18) What are all the four states associated in the thread?
Ans : 1. new 2. runnable 3. blocked 4. dead
19) The suspend()method is used to teriminate a thread?
True /False
Ans : False
20) The run() method should necessary exists in clases created as subclass of thread?
True /False
Ans : True
21) When two threads are waiting on each other and can't proceed the programe is said to be in a deadlock?
True/False
Ans : True
22) Which method waits for the thread to die ?
Ans : join() method
23) Which of the following is true?
1) wait(),notify(),notifyall() are defined as final & can be called only from with in a synchronized method
2) Among wait(),notify(),notifyall() the wait() method only throws IOException
3) wait(),notify(),notifyall() & sleep() are methods of object class
1
2
3
1 & 2
1,2 & 3
Ans : D
24) Garbage collector thread belongs to which priority?
Ans : low-priority
25) What is meant by timeslicing or time sharing?
Ans : Timeslicing is the method of allocating CPU time to individual threads in a priority schedule.
26) What is meant by daemon thread? In java runtime, what is it's role?
Ans : Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system.
Inheritance
1) What is the difference between superclass & subclass?
Ans : A super class is a class that is inherited whereas subclass is a class that does the inheriting.
2) Which keyword is used to inherit a class?
Ans : extends

3) Subclasses methods can access superclass members/ attributes at all times?
True/False
Ans : False
4) When can subclasses not access superclass members?
Ans : When superclass is declared as private.
5) Which class does begin Java class hierarchy?
Ans : Object class
6) Object class is a superclass of all other classes?
True/False
Ans : True
7) Java supports multiple inheritance?
True/False
Ans : False
8) What is inheritance?
Ans : Deriving an object from an existing class. In the other words, Inheritance is the process of inheriting all the features from a class
9) What are the advantages of inheritance?
Ans : Reusability of code and accessibility of variables and methods of the superclass by subclasses.
10) Which method is used to call the constructors of the superclass from the subclass?
Ans : super(argument)
11) Which is used to execute any method of the superclass from the subclass?
Ans : super.method-name(arguments)
12) Which methods are used to destroy the objects created by the constructor methods?
Ans : finalize()
13) What are abstract classes?
Ans : Abstract classes are those for which instances can’t be created.

14) What must a class do to implement an interface?
Ans: It must provide all of the methods in the interface and identify the interface in its implements clause.
15) Which methods in the Object class are declared as final?
Ans : getClass(), notify(), notifyAll(), and wait()
16) Final methods can be overridden.
True/False
Ans : False
17) Declaration of methods as final results in faster execution of the program?
True/False
Ans: True
18) Final variables should be declared in the beginning?
True/False
Ans : True
19) Can we declare variable inside a method as final variables? Why?
Ans : Cannot because, local variable cannot be declared as final variables.
20) Can an abstract class may be final?
Ans : An abstract class may not be declared as final.
21) Does a class inherit the constructors of it's super class?
Ans: A class does not inherit constructors from any of it's super classes.
22) What restrictions are placed on method overloading?
Ans: Two methods may not have the same name and argument list but different return types.
23) What restrictions are placed on method overriding?
Ans : Overridden methods must have the same name , argument list , and return type. The overriding method may not limit the access of the method it overridees.The overriding method may not throw any exceptions that may not be thrown by the overridden method.
24) What modifiers may be used with an inner class that is a member of an outer class?
Ans : a (non-local) inner class may be declared as public, protected, private, static, final or abstract.
25) How this() is used with constructors?
Ans: this() is used to invoke a constructor of the same class
26) How super() used with constructors?
Ans : super() is used to invoke a super class constructor
27) Which of the following statements correctly describes an interface?
a)It's a concrete class
b)It's a superclass
c)It's a type of abstract class
Ans: c

28) An interface contains __ methods
a)Non-abstract
b)Implemented
c)unimplemented
Ans:c




No comments:

Post a Comment