Implementing a thread-safe JSP page

We can make a thread-safe JSP by having them implement the SingleThreadModel interface. This is done by adding the below directive within your JSP page.

<%@ page isThreadSafe="false" %>


By this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine.

More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition.

SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use . You should try really hard to make them thread-safe the old fashioned way by making them thread-safe.

Implementing a thread-safe JSP page

We can make a thread-safe JSP by having them implement the SingleThreadModel interface. This is done by adding the below directive within your JSP page.

<%@ page isThreadSafe="false" %>


By this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine.

More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition.

SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use . You should try really hard to make them thread-safe the old fashioned way by making them thread-safe.

Java Server Pages (JSP) in breif

JavaServer Pages (JSP) is a technology based on the Java language and enables the development of dynamic web sites. JSP was developed by Sun Microsystems to allow server side development. JSP files are HTML files with special Tagscontaining Java source code that provide the dynamic content.

JSP source code runs on the web server in the JSP Servlet Engine. The JSP Servlet engine dynamically generates the HTML and sends the HTML output to the client’s web browser.

JSP is based on Java, an objectoriented language. JSP offers a robust platform for web development. JSP code on the server is classed as the implementation. By having a separation of presentation and implementation, designers work only on the presentation and developers concentrate on implementing the application.

JSPs are built on top of SUN’s servlet technology. JSPs are essential an HTML page with special JSP tags embedded. These JSP tags can contain Java code. The JSP file extension is .jsp rather than .htm or .html. The JSP engine parses the .jsp and creates a Java servlet source file. It then compiles the source file into a class file, this is done the first time and this why the JSP is probably slower the first time it is accessed. Any time after this the special compiled servlet is executed and is therefore returns faster.

Java Server Pages (JSP) in breif

JavaServer Pages (JSP) is a technology based on the Java language and enables the development of dynamic web sites. JSP was developed by Sun Microsystems to allow server side development. JSP files are HTML files with special Tagscontaining Java source code that provide the dynamic content.

JSP source code runs on the web server in the JSP Servlet Engine. The JSP Servlet engine dynamically generates the HTML and sends the HTML output to the client’s web browser.

JSP is based on Java, an objectoriented language. JSP offers a robust platform for web development. JSP code on the server is classed as the implementation. By having a separation of presentation and implementation, designers work only on the presentation and developers concentrate on implementing the application.

JSPs are built on top of SUN’s servlet technology. JSPs are essential an HTML page with special JSP tags embedded. These JSP tags can contain Java code. The JSP file extension is .jsp rather than .htm or .html. The JSP engine parses the .jsp and creates a Java servlet source file. It then compiles the source file into a class file, this is done the first time and this why the JSP is probably slower the first time it is accessed. Any time after this the special compiled servlet is executed and is therefore returns faster.

Hybrid Server Pages beyond JSP

Hybrid Server Pages beyond the Java Server Pages

JSP combined HTML and Java in one source text but did not go far enough. Hybrid Java Language (HJL) is the next step in the same direction. HJL supports code reuse in the form of widgets written in same Hybrid Java Pages. Generated Java code gets built into a natural pages and components framework wrapped around Servlet API.

Hybrid Java Language incorporates Java and HTML operators into a single formal grammar.We may consider the language as consisting of three parts – subset of Java, subset of HTML and all the rest. The latter serves for code factorization and reuse as well as for ‘gluing’ Java and HTML. Widgets are the units of code reuse.

The Hybrid Java Pages code of an application is provided as a set of .page files (one per Web page) and a set of .widget files. A widget may define named attributes and/or named slots (or one anonymous slot). A slot is somewhat similar to the position between opening and closing a ‘library tag’. The code inHybrid Java Pages slots has Java context of the point of call of the widget, so widgets are transparent for Java context (same as HTML elements are by the way).

The rest of the .widget file is just ARBITRARY Hybrid Java Pages code – no other programming support or configuration is necessary to define a widget.

Technology suggests a very natural framework that includes application, page and widget data persistent in the scope of HTTP session. Developer defines such data as members of ‘code-behind’ classes, which may contain handlers of those states called by the framework with a proper dispatching in case of widgets.

Compiler resolves the identifiers used in widgets and pages against Java definitions in Java blocks, definitions of widget attributes, in instances of widgets and page state classes. Widgets may send signals to parent and page.

Source: http://www.hybridserverpages.com/

Hybrid Server Pages beyond JSP

Hybrid Server Pages beyond the Java Server Pages

JSP combined HTML and Java in one source text but did not go far enough. Hybrid Java Language (HJL) is the next step in the same direction. HJL supports code reuse in the form of widgets written in same Hybrid Java Pages. Generated Java code gets built into a natural pages and components framework wrapped around Servlet API.

Hybrid Java Language incorporates Java and HTML operators into a single formal grammar.We may consider the language as consisting of three parts – subset of Java, subset of HTML and all the rest. The latter serves for code factorization and reuse as well as for ‘gluing’ Java and HTML. Widgets are the units of code reuse.

The Hybrid Java Pages code of an application is provided as a set of .page files (one per Web page) and a set of .widget files. A widget may define named attributes and/or named slots (or one anonymous slot). A slot is somewhat similar to the position between opening and closing a ‘library tag’. The code inHybrid Java Pages slots has Java context of the point of call of the widget, so widgets are transparent for Java context (same as HTML elements are by the way).

The rest of the .widget file is just ARBITRARY Hybrid Java Pages code – no other programming support or configuration is necessary to define a widget.

Technology suggests a very natural framework that includes application, page and widget data persistent in the scope of HTTP session. Developer defines such data as members of ‘code-behind’ classes, which may contain handlers of those states called by the framework with a proper dispatching in case of widgets.

Compiler resolves the identifiers used in widgets and pages against Java definitions in Java blocks, definitions of widget attributes, in instances of widgets and page state classes. Widgets may send signals to parent and page.

Source: http://www.hybridserverpages.com/

Struts and JSP

Struts makes it possible for JSP pages to externalize flow control, rather than specify physical links to various JSP pages within the JSP file, the JSP file contains a Struts-defined logical URI. The Struts URI defines a logical page request mapped to actions that may return different physical JSP pages depending on the context of the HTTP request.

Struts simplifies the development of the actual JSP file content by limiting it to user interface generation only. Java that would otherwise appear inside the JSP files appears in separate servlet action classes that the JSP page invokes at runtime.

Struts helps to separate the development roles into user interface designer (HTML or tag library user) and JSP action-handler developer. For example, one person can write JSP page using only HTML or suitable tag libraries, while another person works independently to create the page action handling classes in Java.

Struts externalizes JSP actions that would otherwise appear inside all the JSP pages of your project into a single configuration file. This greatly simplifies debugging and promotes reuse. Struts consolidates String resources that would otherwise appear inside all the JSP pages of your project into a single file. This simplifies the task of localizing JSP applications.

JSP Tags

Tags in JSP

JSP is a serverside technology to make content generation a simple appear. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.

JSP contains the following tags

* Declaration tag
* Expression tag
* Directive Tag
* Scriptlet tag

Declaration tag ( <%! %> )

A declaration tag declares one or more variables or methods for use later in the JSP source file. A declaration tag must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration tag must be valid in the scripting language used in the JSP file.

This tag allows the developer to declare variables or methods. Before the declaration you must have
<%! At the end of the declaration, the developer must have %> Code placed in this tag must end in a semicolon ( ; ). Declarations do not generate output so are used with JSP expressions or scriptlets.

<%! private int counter = 0 ; private String get Account ( int accountNo) ; %>

Expression tag ( <%= %>)

An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file.

This tag allows the developer to embed any Java expression and is short for out.println(). A semicolon ( ; ) does not appear at the end of the code inside the tag. Example to show the current date and time

Date : <%= new java.util.Date() %>

Directive tag ( <%@ directive … %>)

A JSP directive tag gives special information about the page to the JSP Engine.

There are three main types of directives:

* page – processing information for this page.
* Include – files to be included.
* Tag library – tag library to be used in this page.

Directives do not produce any visible output when the page is requested but change the way the JSP Engine processes the page.

Scriptlet tag ( <% … %> )

A scriptlet tag can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. We can declare variables or methods to use later in the file. Write expressions valid in the page scripting language. Use any of the JSP implicit objects or any object declared with a tag. You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. Scriptlets are executed at request time, when the JSP engine processes the client request.

If the scriptlet produces output, the output is stored in the out object, from which you can display it. Between <% and %> tags, any valid Java code is called a Scriptlet. This code can access any variable or bean declared. For example, to print a variable.

<% String username = “visualbuilder” ; out.println ( username ) ; %>

Struts and JSP

Struts makes it possible for JSP pages to externalize flow control, rather than specify physical links to various JSP pages within the JSP file, the JSP file contains a Struts-defined logical URI. The Struts URI defines a logical page request mapped to actions that may return different physical JSP pages depending on the context of the HTTP request.

Struts simplifies the development of the actual JSP file content by limiting it to user interface generation only. Java that would otherwise appear inside the JSP files appears in separate servlet action classes that the JSP page invokes at runtime.

Struts helps to separate the development roles into user interface designer (HTML or tag library user) and JSP action-handler developer. For example, one person can write JSP page using only HTML or suitable tag libraries, while another person works independently to create the page action handling classes in Java.

Struts externalizes JSP actions that would otherwise appear inside all the JSP pages of your project into a single configuration file. This greatly simplifies debugging and promotes reuse. Struts consolidates String resources that would otherwise appear inside all the JSP pages of your project into a single file. This simplifies the task of localizing JSP applications.

JSP Tags

Tags in JSP

JSP is a serverside technology to make content generation a simple appear. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.

JSP contains the following tags

* Declaration tag
* Expression tag
* Directive Tag
* Scriptlet tag

Declaration tag ( <%! %> )

A declaration tag declares one or more variables or methods for use later in the JSP source file. A declaration tag must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration tag must be valid in the scripting language used in the JSP file.

This tag allows the developer to declare variables or methods. Before the declaration you must have
<%! At the end of the declaration, the developer must have %> Code placed in this tag must end in a semicolon ( ; ). Declarations do not generate output so are used with JSP expressions or scriptlets.

<%! private int counter = 0 ; private String get Account ( int accountNo) ; %>

Expression tag ( <%= %>)

An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file.

This tag allows the developer to embed any Java expression and is short for out.println(). A semicolon ( ; ) does not appear at the end of the code inside the tag. Example to show the current date and time

Date : <%= new java.util.Date() %>

Directive tag ( <%@ directive … %>)

A JSP directive tag gives special information about the page to the JSP Engine.

There are three main types of directives:

* page – processing information for this page.
* Include – files to be included.
* Tag library – tag library to be used in this page.

Directives do not produce any visible output when the page is requested but change the way the JSP Engine processes the page.

Scriptlet tag ( <% … %> )

A scriptlet tag can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. We can declare variables or methods to use later in the file. Write expressions valid in the page scripting language. Use any of the JSP implicit objects or any object declared with a tag. You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. Scriptlets are executed at request time, when the JSP engine processes the client request.

If the scriptlet produces output, the output is stored in the out object, from which you can display it. Between <% and %> tags, any valid Java code is called a Scriptlet. This code can access any variable or bean declared. For example, to print a variable.

<% String username = “visualbuilder” ; out.println ( username ) ; %>

JSP Program to Delete a Cookie Values

JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology - you can’t do any client side validation with it. The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. It is easy to make a change and then let the JSP capability of the web server you are using deal with
compiling it into a servlet and running it.

Sample JSP Program to Delete a Cookie Value:

<% Cookie killCookie = new Cookie(“Ck”, null); KillCookie.setPath(“/”); killCookie.setMaxAge(0); response.addCookie(killCookie); %>

JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed. Read more...
You might also like:

* Java Server Pages (JSP) in breif
* Struts and JSP
* JSP Tags

JSP Program to Delete a Cookie Values

JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology - you can’t do any client side validation with it. The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. It is easy to make a change and then let the JSP capability of the web server you are using deal with
compiling it into a servlet and running it.

Sample JSP Program to Delete a Cookie Value:

<% Cookie killCookie = new Cookie(“Ck”, null); KillCookie.setPath(“/”); killCookie.setMaxAge(0); response.addCookie(killCookie); %>

JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed. Read more...
You might also like:

* Java Server Pages (JSP) in breif
* Struts and JSP
* JSP Tags

Java Interview Questions - part 7 of 7

What are the steps involved in Applet development?
Following are the steps involved in Applet development:
Create/Edit a Java source file. This file must contain a class which extends Applet class.
Compile your program using javac
Execute the appletviewer, specifying the name of your applet’s source file or html file. In case the applet information is stored in html file then Applet can be invoked using java enabled web browser.
----------------------------------------------------------------------------------------------------------------

Which method is used to output a string to an applet?
Which function is this method included in?
drawString( ) method is used to output a string to an applet. This method is included in the paint method of the Applet.
----------------------------------------------------------------------------------------------------------------

Why we can not extends two classes in Java?
Trying to extend 2 classes, or multiple inheritence, would result in a few problems. One of it is when you use the super() method. If you use that while extending more then 1 class, which superclass are you referring to then? Java solves this problem by thus using implementations for its multiple inheritence purposes.
----------------------------------------------------------------------------------------------------------------

What gives Java its “write once and run anywhere” nature?
Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platorm specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent.
----------------------------------------------------------------------------------------------------------------

What are the four corner stones of OOP?
Abstraction, Encapsulation, Polymorphism and Inheritance.
----------------------------------------------------------------------------------------------------------------

Difference between a Class and an Object?
A class is a definition or prototype whereas an object is an instance or living representation of the prototype.
----------------------------------------------------------------------------------------------------------------

What is the difference between method overriding and overloading?
Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments.
----------------------------------------------------------------------------------------------------------------

What is a “stateless” protocol?
Without getting into lengthy debates, it is generally accepted that protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a single request response combination.
----------------------------------------------------------------------------------------------------------------

What is constructor chaining and how is it achieved in Java?
A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement.
----------------------------------------------------------------------------------------------------------------

What is passed by ref and what by value?
All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references
----------------------------------------------------------------------------------------------------------------

Can RMI and Corba based applications interact?
Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP.
You can create a String object as String str = “abc"; Why cant a button object be created as Button bt = “abc";? Explain - The main reason you cannot create a button by Button bt1= “abc"; is because “abc” is a literal string (something slightly different than a String object, by the way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String. Important to note that you are NOT calling a java.lang.String constuctor when you type String s = “abc";
----------------------------------------------------------------------------------------------------------------

What does the “abstract” keyword mean in front of a method? A class?
Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it,it is called abstract method.Abstract method hs no body.It has only arguments and return type.Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can’t be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract.
----------------------------------------------------------------------------------------------------------------

How many methods do u implement if implement the Serializable Interface?
The Serializable interface is just a “marker” interface, with no methods of its own to implement. Other ‘marker’ interfaces are
java.rmi.Remote
java.util.EventListener
----------------------------------------------------------------------------------------------------------------

What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import java.net.* versus import java.net.Socket)?
It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. There is another practical benefit to importing single classes, and this arises when two (or more) packages have classes with the same name. Take java.util.Timer and javax.swing.Timer, for example. If I import java.util.* and javax.swing.* and then try to use “Timer", I get an error while compiling (the class name is ambiguous between both packages). Let’s say what you really wanted was the javax.swing.Timer class, and the only classes you plan on using in java.util are Collection and HashMap. In this case, some people will prefer to import java.util.Collection and import java.util.HashMap instead of importing java.util.*. This will now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified class names in.
----------------------------------------------------------------------------------------------------------------

What is the difference between logical data independence and physical data independence?
Logical Data Independence - meaning immunity of external schemas to changeds in conceptual schema. Physical Data Independence - meaning immunity of conceptual schema to changes in the internal schema.
----------------------------------------------------------------------------------------------------------------

What is a user-defined exception?
Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.
----------------------------------------------------------------------------------------------------------------

Describe the visitor design pattern?
Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The root of a class hierarchy defines an abstract method to accept a visitor. Subclasses implement this method with visitor.visit(this). The Visitor interface has visit methods for all subclasses of the baseclass in the hierarchy.
----------------------------------------------------------------------------------------------------------------

What methods can be overridden in Java?
In C++ terminology, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private.
---------------------------------------------------------------------------------------------------------------

Can there be an abstract class with no abstract methods in it?
Yes
----------------------------------------------------------------------------------------------------------------

Can an Interface be final?
No

Java Interview Questions - part 7 of 7

What are the steps involved in Applet development?
Following are the steps involved in Applet development:
Create/Edit a Java source file. This file must contain a class which extends Applet class.
Compile your program using javac
Execute the appletviewer, specifying the name of your applet’s source file or html file. In case the applet information is stored in html file then Applet can be invoked using java enabled web browser.
----------------------------------------------------------------------------------------------------------------

Which method is used to output a string to an applet?
Which function is this method included in?
drawString( ) method is used to output a string to an applet. This method is included in the paint method of the Applet.
----------------------------------------------------------------------------------------------------------------

Why we can not extends two classes in Java?
Trying to extend 2 classes, or multiple inheritence, would result in a few problems. One of it is when you use the super() method. If you use that while extending more then 1 class, which superclass are you referring to then? Java solves this problem by thus using implementations for its multiple inheritence purposes.
----------------------------------------------------------------------------------------------------------------

What gives Java its “write once and run anywhere” nature?
Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platorm specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent.
----------------------------------------------------------------------------------------------------------------

What are the four corner stones of OOP?
Abstraction, Encapsulation, Polymorphism and Inheritance.
----------------------------------------------------------------------------------------------------------------

Difference between a Class and an Object?
A class is a definition or prototype whereas an object is an instance or living representation of the prototype.
----------------------------------------------------------------------------------------------------------------

What is the difference between method overriding and overloading?
Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments.
----------------------------------------------------------------------------------------------------------------

What is a “stateless” protocol?
Without getting into lengthy debates, it is generally accepted that protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a single request response combination.
----------------------------------------------------------------------------------------------------------------

What is constructor chaining and how is it achieved in Java?
A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement.
----------------------------------------------------------------------------------------------------------------

What is passed by ref and what by value?
All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references
----------------------------------------------------------------------------------------------------------------

Can RMI and Corba based applications interact?
Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP.
You can create a String object as String str = “abc"; Why cant a button object be created as Button bt = “abc";? Explain - The main reason you cannot create a button by Button bt1= “abc"; is because “abc” is a literal string (something slightly different than a String object, by the way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String. Important to note that you are NOT calling a java.lang.String constuctor when you type String s = “abc";
----------------------------------------------------------------------------------------------------------------

What does the “abstract” keyword mean in front of a method? A class?
Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it,it is called abstract method.Abstract method hs no body.It has only arguments and return type.Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can’t be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract.
----------------------------------------------------------------------------------------------------------------

How many methods do u implement if implement the Serializable Interface?
The Serializable interface is just a “marker” interface, with no methods of its own to implement. Other ‘marker’ interfaces are
java.rmi.Remote
java.util.EventListener
----------------------------------------------------------------------------------------------------------------

What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import java.net.* versus import java.net.Socket)?
It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. There is another practical benefit to importing single classes, and this arises when two (or more) packages have classes with the same name. Take java.util.Timer and javax.swing.Timer, for example. If I import java.util.* and javax.swing.* and then try to use “Timer", I get an error while compiling (the class name is ambiguous between both packages). Let’s say what you really wanted was the javax.swing.Timer class, and the only classes you plan on using in java.util are Collection and HashMap. In this case, some people will prefer to import java.util.Collection and import java.util.HashMap instead of importing java.util.*. This will now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified class names in.
----------------------------------------------------------------------------------------------------------------

What is the difference between logical data independence and physical data independence?
Logical Data Independence - meaning immunity of external schemas to changeds in conceptual schema. Physical Data Independence - meaning immunity of conceptual schema to changes in the internal schema.
----------------------------------------------------------------------------------------------------------------

What is a user-defined exception?
Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.
----------------------------------------------------------------------------------------------------------------

Describe the visitor design pattern?
Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The root of a class hierarchy defines an abstract method to accept a visitor. Subclasses implement this method with visitor.visit(this). The Visitor interface has visit methods for all subclasses of the baseclass in the hierarchy.
----------------------------------------------------------------------------------------------------------------

What methods can be overridden in Java?
In C++ terminology, all public methods in Java are virtual. Therefore, all Java methods can be overwritten in subclasses except those that are declared final, static, and private.
---------------------------------------------------------------------------------------------------------------

Can there be an abstract class with no abstract methods in it?
Yes
----------------------------------------------------------------------------------------------------------------

Can an Interface be final?
No

Java Interview Questions - Part 6 of 7

How do Applets differ from Applications?
Following are the main differences: Application: Stand Alone, doesn’t need
web-browser. Applet: Needs no explicit installation on local machine. Can be transferred through Internet on to the local machine and may run as part of web-browser. Application: Execution starts with main() method. Doesn’t work if main is not there. Applet: Execution starts with init() method. Application: May or may not be a GUI. Applet: Must run within a GUI (Using AWT). This is essential feature of applets.
---------------------------------------------------------------------------------------------------------------

Can we pass parameters to an applet from HTML page to an applet? How?
We can pass parameters to an applet using tag in the following way:


Access those parameters inside the applet is done by calling getParameter() method inside the applet. Note that getParameter() method returns String value corresponding to the parameter name.
----------------------------------------------------------------------------------------------------------------

How do we read number information from my applet’s parameters, given that Applet’s getParameter() method returns a string?
Use the parseInt() method in the Integer Class, the Float(String) constructor or parseFloat() method in the Class Float, or the
Double(String) constructor or parseDoulbl() method in the class Double.
----------------------------------------------------------------------------------------------------------------

How can I arrange for different applets on a web page to communicate with each other?
Name your applets inside the Applet tag and invoke AppletContext’s getApplet() method in your applet code to obtain references to the other applets on the page.
----------------------------------------------------------------------------------------------------------------

How do I select a URL from my Applet and send the browser to that page?
Ask the applet for its applet context and invoke showDocument() on that context object.

URL targetURL;
String URLString
AppletContext context = getAppletContext();
try
{
targetURL = new URL(URLString);
}
catch (MalformedURLException e)
{
// Code for recover from the exception
}
context. showDocument (targetURL);
Can applets on different pages communicate with each other?
- No, Not Directly. The applets will exchange the information at one meeting place either on the local file system or at remote system.

----------------------------------------------------------------------------------------------------------------

How do I determine the width and height of my application?
Use the getSize() method, which the Applet class inherits from the Component class in the Java.awt package. The getSize() method returns the size of the applet as a Dimension object, from which you extract separate width, height fields. The following code snippet explains this:

Dimension dim = getSize();
int appletwidth = dim.width();
int appletheight = dim.height();
----------------------------------------------------------------------------------------------------------------

Which classes and interfaces does Applet class consist?
Applet class consists of a single class, the Applet class and three interfaces: AppletContext, AppletStub, and AudioClip.
----------------------------------------------------------------------------------------------------------------

What is AppletStub Interface?
The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface.
----------------------------------------------------------------------------------------------------------------

What tags are mandatory when creating HTML to display an applet?
name, height, width
code, name
codebase, height, width
code, height, width
Correct answer is d.
----------------------------------------------------------------------------------------------------------------

What are the Applet’s information methods?
The following are the Applet’s information methods: getAppletInfo() method: Returns a string describing the applet, its author, copyright information, etc. getParameterInfo( ) method: Returns an array of string describing the applet’s parameters.

Java Interview Questions - Part 6 of 7

How do Applets differ from Applications?
Following are the main differences: Application: Stand Alone, doesn’t need
web-browser. Applet: Needs no explicit installation on local machine. Can be transferred through Internet on to the local machine and may run as part of web-browser. Application: Execution starts with main() method. Doesn’t work if main is not there. Applet: Execution starts with init() method. Application: May or may not be a GUI. Applet: Must run within a GUI (Using AWT). This is essential feature of applets.
---------------------------------------------------------------------------------------------------------------

Can we pass parameters to an applet from HTML page to an applet? How?
We can pass parameters to an applet using tag in the following way:


Access those parameters inside the applet is done by calling getParameter() method inside the applet. Note that getParameter() method returns String value corresponding to the parameter name.
----------------------------------------------------------------------------------------------------------------

How do we read number information from my applet’s parameters, given that Applet’s getParameter() method returns a string?
Use the parseInt() method in the Integer Class, the Float(String) constructor or parseFloat() method in the Class Float, or the
Double(String) constructor or parseDoulbl() method in the class Double.
----------------------------------------------------------------------------------------------------------------

How can I arrange for different applets on a web page to communicate with each other?
Name your applets inside the Applet tag and invoke AppletContext’s getApplet() method in your applet code to obtain references to the other applets on the page.
----------------------------------------------------------------------------------------------------------------

How do I select a URL from my Applet and send the browser to that page?
Ask the applet for its applet context and invoke showDocument() on that context object.

URL targetURL;
String URLString
AppletContext context = getAppletContext();
try
{
targetURL = new URL(URLString);
}
catch (MalformedURLException e)
{
// Code for recover from the exception
}
context. showDocument (targetURL);
Can applets on different pages communicate with each other?
- No, Not Directly. The applets will exchange the information at one meeting place either on the local file system or at remote system.

----------------------------------------------------------------------------------------------------------------

How do I determine the width and height of my application?
Use the getSize() method, which the Applet class inherits from the Component class in the Java.awt package. The getSize() method returns the size of the applet as a Dimension object, from which you extract separate width, height fields. The following code snippet explains this:

Dimension dim = getSize();
int appletwidth = dim.width();
int appletheight = dim.height();
----------------------------------------------------------------------------------------------------------------

Which classes and interfaces does Applet class consist?
Applet class consists of a single class, the Applet class and three interfaces: AppletContext, AppletStub, and AudioClip.
----------------------------------------------------------------------------------------------------------------

What is AppletStub Interface?
The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface.
----------------------------------------------------------------------------------------------------------------

What tags are mandatory when creating HTML to display an applet?
name, height, width
code, name
codebase, height, width
code, height, width
Correct answer is d.
----------------------------------------------------------------------------------------------------------------

What are the Applet’s information methods?
The following are the Applet’s information methods: getAppletInfo() method: Returns a string describing the applet, its author, copyright information, etc. getParameterInfo( ) method: Returns an array of string describing the applet’s parameters.

Java Interview Questions - Part 5 of 7

Is “abc” a primitive value?
The String literal “abc” is not a primitive value. It is a String object.
---------------------------------------------------------------------------------------------------------------------

What restrictions are placed on the values of each case of a switch statement?
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
---------------------------------------------------------------------------------------------------------------------

What is the query used to display all tables names in SQL Server (Query analyzer)?
select * from information_schema.tables
---------------------------------------------------------------------------------------------------------------------

Is it possible to write two EJB’s that share the same Remote and Home interfaces, and have different bean classes? if so, what are the advantages/disadvantages?
It’s certainly possible. In fact, there’s an example that ships with the Inprise Application Server of an Account interface with separate implementations for CheckingAccount and SavingsAccount, one of which was CMP and one of which was BMP.
---------------------------------------------------------------------------------------------------------------------

What is garbage collection?
What is the process that is responsible for doing that in java? - Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
---------------------------------------------------------------------------------------------------------------------

What kind of thread is the Garbage collector thread?
It is a daemon thread.
---------------------------------------------------------------------------------------------------------------------

What is a Marker Interface?
An interface with no methods. Example: Serializable, Remote, Cloneable
---------------------------------------------------------------------------------------------------------------------

What interface do you implement to do the sorting?
Comparable
---------------------------------------------------------------------------------------------------------------------

What is the eligibility for a object to get cloned?
It must implement the Cloneable interface
---------------------------------------------------------------------------------------------------------------------

J2EE EJB interview questions

What is the relationship between local interfaces and container-managed relationships?
Entity beans that have container-managed relationships with other entity beans, must be accessed in the same local scope as those related beans, and therefore typically provide a local client view. In order to be the target of a container-managed relationship, an entity bean with container-managed persistence must provide a local interface.
---------------------------------------------------------------------------------------------------------------------

What does a remove method do for different cases of beans?
Stateless Session : Does not do anything to the bean as moving the bean from free pool to cache are managed by the container depending on load. Stateful Session: Removes the bean from the cache. Entity Bean: Deletes the bean (data) from persistent storage
---------------------------------------------------------------------------------------------------------------------

How does a container-managed relationship work?
An entity bean accesses related entity beans by means of the accessor methods for its container-managed relationship fields, which are specified by the cmr-field elements of its abstract persistence schema defined in the deployment descriptor. Entity bean relationships are defined in terms of the local interfaces of the related beans, and the view an entity bean presents to its related beans is defined by its local home and local interfaces. Thus, an entity bean can be the target of a relationship from another entity bean only if it has a local interface.
---------------------------------------------------------------------------------------------------------------------

What is an Applet? Should applets have constructors?
Applets are small programs transferred through Internet, automatically installed and run as part of web-browser. Applets implements functionality of a client. Applet is a dynamic and interactive program that runs inside a Web page displayed by a Java-capable browser. We don’t have the concept of Constructors in Applets. Applets can be invoked either through browser or through Appletviewer utility provided by JDK.
---------------------------------------------------------------------------------------------------------------------

What are the Applet’s Life Cycle methods? Explain them?
Following are methods in the life cycle of an Applet:
init() method - called when an applet is first loaded. This method is called only once in the entire cycle of an applet. This method usually intialize the variables to be used in the applet.
start( ) method - called each time an applet is started.
paint() method - called when the applet is minimized or refreshed. This method is used for drawing different strings, figures, and images on the applet window.
stop( ) method - called when the browser moves off the applet’s page.
destroy( ) method - called when the browser is finished with the applet.
---------------------------------------------------------------------------------------------------------------------

What is the sequence for calling the methods by AWT for applets?
When an applet begins, the AWT calls the following methods, in this sequence:
init()
start()
paint()
When an applet is terminated, the following sequence of method calls takes place :

stop()
destroy()

Java Interview Questions - Part 5 of 7

Is “abc” a primitive value?
The String literal “abc” is not a primitive value. It is a String object.
---------------------------------------------------------------------------------------------------------------------

What restrictions are placed on the values of each case of a switch statement?
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
---------------------------------------------------------------------------------------------------------------------

What is the query used to display all tables names in SQL Server (Query analyzer)?
select * from information_schema.tables
---------------------------------------------------------------------------------------------------------------------

Is it possible to write two EJB’s that share the same Remote and Home interfaces, and have different bean classes? if so, what are the advantages/disadvantages?
It’s certainly possible. In fact, there’s an example that ships with the Inprise Application Server of an Account interface with separate implementations for CheckingAccount and SavingsAccount, one of which was CMP and one of which was BMP.
---------------------------------------------------------------------------------------------------------------------

What is garbage collection?
What is the process that is responsible for doing that in java? - Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
---------------------------------------------------------------------------------------------------------------------

What kind of thread is the Garbage collector thread?
It is a daemon thread.
---------------------------------------------------------------------------------------------------------------------

What is a Marker Interface?
An interface with no methods. Example: Serializable, Remote, Cloneable
---------------------------------------------------------------------------------------------------------------------

What interface do you implement to do the sorting?
Comparable
---------------------------------------------------------------------------------------------------------------------

What is the eligibility for a object to get cloned?
It must implement the Cloneable interface
---------------------------------------------------------------------------------------------------------------------

J2EE EJB interview questions

What is the relationship between local interfaces and container-managed relationships?
Entity beans that have container-managed relationships with other entity beans, must be accessed in the same local scope as those related beans, and therefore typically provide a local client view. In order to be the target of a container-managed relationship, an entity bean with container-managed persistence must provide a local interface.
---------------------------------------------------------------------------------------------------------------------

What does a remove method do for different cases of beans?
Stateless Session : Does not do anything to the bean as moving the bean from free pool to cache are managed by the container depending on load. Stateful Session: Removes the bean from the cache. Entity Bean: Deletes the bean (data) from persistent storage
---------------------------------------------------------------------------------------------------------------------

How does a container-managed relationship work?
An entity bean accesses related entity beans by means of the accessor methods for its container-managed relationship fields, which are specified by the cmr-field elements of its abstract persistence schema defined in the deployment descriptor. Entity bean relationships are defined in terms of the local interfaces of the related beans, and the view an entity bean presents to its related beans is defined by its local home and local interfaces. Thus, an entity bean can be the target of a relationship from another entity bean only if it has a local interface.
---------------------------------------------------------------------------------------------------------------------

What is an Applet? Should applets have constructors?
Applets are small programs transferred through Internet, automatically installed and run as part of web-browser. Applets implements functionality of a client. Applet is a dynamic and interactive program that runs inside a Web page displayed by a Java-capable browser. We don’t have the concept of Constructors in Applets. Applets can be invoked either through browser or through Appletviewer utility provided by JDK.
---------------------------------------------------------------------------------------------------------------------

What are the Applet’s Life Cycle methods? Explain them?
Following are methods in the life cycle of an Applet:
init() method - called when an applet is first loaded. This method is called only once in the entire cycle of an applet. This method usually intialize the variables to be used in the applet.
start( ) method - called each time an applet is started.
paint() method - called when the applet is minimized or refreshed. This method is used for drawing different strings, figures, and images on the applet window.
stop( ) method - called when the browser moves off the applet’s page.
destroy( ) method - called when the browser is finished with the applet.
---------------------------------------------------------------------------------------------------------------------

What is the sequence for calling the methods by AWT for applets?
When an applet begins, the AWT calls the following methods, in this sequence:
init()
start()
paint()
When an applet is terminated, the following sequence of method calls takes place :

stop()
destroy()