[ 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:
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
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
}
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
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
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
No comments:
Post a Comment