Creating an executable jar file is not that tough if it does not involve any external jars. Create a manifest file and mention the main class path in the manifest file. Place all the class files in a folder along with the manifest file and run the following command:
jar -cfm [name of the jar file] [name of the manifest]
Flags Description:
c: Create new archive
f: Specify the archive name
m: include manifest
* means include all the files in the current folder and all the sub folders.
The manifest file look something like this:
Main-Class: [name of the main class along with the package details]
Example
If your project has two files a.class and main.class. which are placed in a package(abc.def). Then the manifest would look like this(mainClass.mf):
___________________
Main-Class: abc.def.main
___________________
and the command to create an executable jar will be
jar -cfm test.jar mainClass.mf *
Everything works ok if you are not using any external jars but the problem arises when you have externals jar like you have used the logging component log4j. The manifest attribute Class-Path attribute in which you can mention the paths of the external jars, but i tried it for log4j but it didn't work it gives me error 'Logger Class Def Not Found'. I had created the following manifest for that (Keeping the above exapmle in mind)
__________________
Main-Class: abc.def.main
Class-Path: lib\log4j.jar
__________________
but this didn't worked.
Then i came across a work around for this, which is you create a jar file of your project class files without adding the extenal libaries ie. using the following same manifest:
___________________
Main-Class: abc.def.main
___________________
Place the created jar files along with the external jar files in another folder and then use the following manifest to create the final jar file.
____________________
Main-Class: abc.def.main
Class-Path: main\test.jar lib\log4j.jar
____________________
Notice that test.jar is the jar file of your actual project. the final jar created using the above manifest will work for you.
Search Your Question
Friday, May 30, 2008
Executable Jar File in JAVA. Interview quations
Thursday, May 29, 2008
Executable Jar File in JAVA. Interview question
Creating an executable jar file is not that tough if it does not involve any external jars. Create a manifest file and mention the main class path in the manifest file. Place all the class files in a folder along with the manifest file and run the following command:
jar -cfm [name of the jar file] [name of the manifest] *
Flags Description:
c: Create new archive
f: Specify the archive name
m: include manifest
* means include all the files in the current folder and all the sub folders.
The manifest file look something like this:
Main-Class: [name of the main class along with the package details]
Example
If your project has two files a.class and main.class. which are placed in a package(abc.def). Then the manifest would look like this(mainClass.mf):
___________________
Main-Class: abc.def.main
___________________
and the command to create an executable jar will be
jar -cfm test.jar mainClass.mf *
Everything works ok if you are not using any external jars but the problem arises when you have externals jar like you have used the logging component log4j. The manifest attribute Class-Path attribute in which you can mention the paths of the external jars, but i tried it for log4j but it didn't work it gives me error 'Logger Class Def Not Found'. I had created the following manifest for that (Keeping the above exapmle in mind)
__________________
Main-Class: abc.def.main
Class-Path: lib\log4j.jar
__________________
but this didn't worked.
Then i came across a work around for this, which is you create a jar file of your project class files without adding the extenal libaries ie. using the following same manifest:
___________________
Main-Class: abc.def.main
___________________
Place the created jar files along with the external jar files in another folder and then use the following manifest to create the final jar file.
____________________
Main-Class: abc.def.main
Class-Path: main\test.jar lib\log4j.jar
____________________
Notice that test.jar is the jar file of your actual project. the final jar created using the above manifest will work for you.
Saturday, April 19, 2008
Java Interview Questions
What is the diffrence between an Abstract class and Interface ?
What is user defined exception ?
What do you know about the garbate collector ?
What is the difference between C++ & Java ?
Explain RMI Architecture?
How do you communicate in between Applets & Servlets ?
What is the use of Servlets ?
What is JDBC? How do you connect to the Database ?
In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?
What is the difference between Process and Threads ?
What is the difference between RMI & Corba ?
What are the services in RMI ?
How will you initialize an Applet ?
What is the order of method invocation in an Applet ?
When is update method called ?
How will you pass values from HTML page to the Servlet ?
Have you ever used HashTable and Dictionary ?
How will you communicate between two Applets ?
What are statements in JAVA ?
What is JAR file ?
What is JNI ?
What is the base class for all swing components ?
What is JFC ?
What is Difference between AWT and Swing ?
Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times? Where 3 processesare started or 3 threads are started ?
How does thread synchronization occurs inside a monitor ?
How will you call an Applet using a Java Script function ?
Is there any tag in HTML to upload and download files ?
Why do you Canvas ?
How can you push data from an Applet to Servlet ?
What are 4 drivers available in JDBC ?
How you can know about drivers and database information ?
If you are truncated using JDBC, How can you know ..that how much data is truncated ? And What situation , each of the 4 drivers used ?
How will you perform transaction using JDBC ?
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 ?
Suppose server object is not loaded into the memory, and the client request for it , what will happen?
What is serialization ?
Can you load the server object dynamically? If so, what are the major 3 steps involved in it ?
What is difference RMI registry and OSAgent ?
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 ?
What are the benefits of Swing over AWT ?
Where the CardLayout is used ?
What is the Layout for ToolBar ?
What is the difference between Grid and GridbagLayout ?
How will you add panel to a Frame ?
What is the corresponding Layout for Card in Swing ?
What is light weight component ?
Can you run the product development on all operating systems ?
What is the webserver used for running the Servlets ?
What is Servlet API used for conneting database ?
What is bean ? Where it can be used ?
What is difference in between Java Class and Bean ?
Can we send object using Sockets ?
What is the RMI and Socket ?
How to communicate 2 threads each other ?
What are the files generated after using IDL to Java Compilet ?
What is the protocol used by server and client ?
Can I modify an object in CORBA ?
What is the functionality stubs and skeletons ?
What is the mapping mechanism used by Java to identify IDL language ?
Diff between Application and Applet ?
What is serializable Interface ?
What is the difference between CGI and Servlet ?
What is the use of Interface ?
Why Java is not fully objective oriented ?
Why does not support multiple Inheritance ?
What it the root class for all Java classes ?
What is polymorphism ?
Suppose If we have variable ' I ' in run method, If I can create one or more thread each thread will occupy a separate copy or same variable will be shared ?
In servlets, we are having a web page that is invoking servlets username and password ? which is cheks in the database ?
Suppose the second page also If we want to verify the same information whethe it will connect to the database or it will be used previous information?
What are virtual functions ?
Write down how will you create a binary Tree ?
What are the traverses in Binary Tree ?
Write a program for recursive Traverse ?
What are session variable in Servlets ?
What is client server computing ?
What is Constructor and Virtual function? Can we call Virtual funciton in a constructor ?
Why we use OOPS concepts? What is its advantage ?
What is the middleware ? What is the functionality of Webserver ?
Why Java is not 100 % pure OOPS ? ( EcomServer )
When we will use an Interface and Abstract class ?
What is an RMI?
How will you pass parameters in RMI ? Why u serialize?
What is the exact difference in between Unicast and Multicast object ? Where we will use ?
What is the main functionality of the Remote Reference Layer ?
How do you download stubs from a Remote place ?
What is the difference in between C++ and Java ? can u explain in detail ?
I want to store more than 10 objects in a remote server ? Which methodology will follow ?
What is the main functionality of the Prepared Statement ?
What is meant by static query and dynamic query ?
What are the Normalization Rules ? Define the Normalization ?
What is meant by Servelet? What are the parameters of the service method ?
What is meant by Session ? Tell me something about HTTPSession Class ?
How do you invoke a Servelt? What is the difference in between doPost and doGet methods ?
What is the difference in between the HTTPServlet and Generic Servlet ? Expalin their methods ? Tell me their parameter names also ?
Have you used threads in Servelet ?
Write a program on RMI and JDBC using StoredProcedure ?
How do you sing an Applet ?
In a Container there are 5 components. I want to display the all the components names, how will you do that one ?
Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?
Tell me the latest versions in JAVA related areas ?
What is meant by class loader ? How many types are there? When will we use them ?
How do you load an Image in a Servlet ?
What is meant by flickering ?
What is meant by distributed Application ? Why we are using that in our applications ?
What is the functionality of the stub ?
Have you used any version control ?
What is the latest version of JDBC ? What are the new features are added in that ?
Explain 2 tier and 3 -tier Architecture ?
What is the role of the webserver ?
How have you done validation of the fileds in your project ?
What is the main difficulties that you are faced in your project ?
What is meant by cookies ? Explain ? Problem faced in your earlier project
How OOPS concept is achieved in Java
Features for using Java
How does Java 2.0 differ from Java 1.0
Public static void main – Explain
What are command line arguments
Explain about the three-tier model
Difference between String & StringBuffer
Wrapper class. Is String a Wrapper Class
What are the restriction for static method
Purpose of the file class
Default modifier in Interface
Difference between Interface & Abstract class
Can abstract be declared as Final
Can we declare variables inside a method as Final Variables
What is the package concept and use of package
How can a dead thread be started
Difference between Applet & Application
Life cycle of the Applet
Can Applet have constructors
Differeence between canvas class & graphics class
Explain about Superclass & subclass
Difference between TCP & UDP
What is AppletStub
Explain Stream Tokenizer
What is the difference between two types of threads
Checked & Unchecked exception
Use of throws exception
What is finally in exception handling
Vector class
What will happen to the Exception object after exception handling
Two types of multi-tasking
Two ways to create the thread
Synchronization
I/O Filter
How can you retrieve warnings in JDBC
Can applet in different page communicate with each other
Four driver Manager
Features of JDBC 20
Explain about stored procedures
Servlet Life cycle
Why do you go for servlet rather than CGI
How to generate skeleton & Stub classes
Explain lazy activation
Firewalls in RMI
Core Java Interview Questions
Q2.What's the difference between an interface and an abstract class?
Q3. Why would you use a synchronized block vs. synchronized method?
Q4. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces? Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
Q5. How can you force garbage collection?
Q6. How do you know if an explicit object casting is needed?
Q7. What's the difference between the methods sleep() and wait()
Q8. Can you write a Java class that could be used both as an applet as well as an application?
Q9. What's the difference between constructors and other methods?
Q10. Can you call one constructor from another if a class has multiple constructors
Q11. Explain the usage of Java packages.
Q12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0?
Q14. What's the difference between a queue and a stack?
Q15. Explain the usage of the keyword transient?
Q16. What comes to mind when you hear about a young generation in Java?
Q17. What comes to mind when someone mentions a shallow copy in Java?
Q18. If you're overriding the method equals() of an object, which other method you might also consider?
Q19. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?
Q20. What's the main difference between a Vector and ArrayList
Q21. When should the method invokeLater()be used?
Q22. How would you make a copy of an entire Java object with its state?
Q23. What would you use to compare two String variables - the operator == or the method equals()?
Q24. How can you minimize the need of garbage collection and make the memory use more effective?
Q25. How can a subclass call a method or a constructor defined in a superclass?
Q26. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
Q27. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
Q28. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
Q29. Can an inner class, declared inside of a method, access local variables of this method?
Q30. What can go wrong if you replace && with & in the following code:String a=null; if (a!=null && a.length()>10) {...} A. A single ampersand here would lead to a NullPointerException.
Thursday, April 17, 2008
Basic Java Interview Questions
1. What is the difference between private, protected, and public?
These keywords are for allowing privileges to components such as java methods and variables.
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.
Access specifiers are keywords that determines the type of access to the member of a class. These are:
* Public
* Protected
* Private
* Defaults
2. What's the difference between an interface and an abstract class? Also discuss the similarities. (Very Important)
Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. Interface is a Java Object containing method declaration and doesn't contain implementation. The classes which have implementing the Interfaces must provide the method definition for all the methods
Abstract class is a Class prefix with a abstract keyword followed by Class definition. Interface is a Interface which starts with interface keyword.
Abstract class contains one or more abstract methods. where as Interface contains all abstract methods and final declarations
Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented.
Differences are as follows:
* Interfaces provide a form of multiple inheritance. A class can extend only one other class.
* Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
* A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
* Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.
Similarities:
* Neither Abstract classes or Interface can be instantiated.
How to define an Abstract class?
A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
Example of Abstract class:
abstract class testAbstractClass {
protected String myString;
public String getMyString() {
return myString;
}
public abstract string anyAbstractFunction();
}
How to define an Interface?
Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Example of Interface:
public interface sampleInterface {
public void functionOne();
public long CONSTANT_ONE = 1000;
}
3. Question: How you can force the garbage collection?
Garbage collection automatic process and can't be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.
4. What's the difference between constructors and normal methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times and it can return a value or can be void.
5. Can you call one constructor from another if a class has multiple constructors
Yes. Use this() to call a constructor from an other constructor.
6. Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.
7. Explain in your own words the "bottom line" benefits of the use of an interface.
The interface makes it possible for a method in one class to invoke methods on objects of other classes, without the requirement to know the true class of those objects, provided that those objects are all instantiated from classes that implement one or more specified interfaces. In other words, objects of classes that implement specified interfaces can be passed into methods of other objects as the generic type Object, and the methods of the other objects can invoke methods on the incoming objects by first casting them as the interface type.
8. What are some advantages and disadvantages of Java Sockets?
Some advantages of Java Sockets:
Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.
Some disadvantages of Java Sockets:
Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.
9. Explain the usage of the keyword transient?
Transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
10. What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
11. What would you use to compare two String variables - the operator == or the method equals()?
I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.
12. Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.
13. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
You do not need to specify any access level, and Java will use a default package access level.
14. Can an inner class declared inside of a method access local variables of this method?
It's possible if these variables are final.
15. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A single ampersand here would lead to a NullPointerException.
16. What's the main difference between a Vector and an ArrayList?
Java Vector class is internally synchronized and ArrayList is not synchronized.
17. Describe the wrapper classes in Java.
Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void
18. How could Java classes direct program messages to the system console, but error messages, say to a file?
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);
19. How do you know if an explicit object casting is needed?
If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
20. When you assign a subclass to a variable having a supeclass type, the casting is performed automatically. Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.
21. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.javIn this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee
22. What's the difference between J2SDK 1.5 and J2SDK 5.0?
There's no difference, Sun Microsystems just re-branded this version.
23. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
24. Name the containers which uses Border Layout as their default layout?
Containers which uses Border Layout as their default are: window, Frame and Dialog classes.
25. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?
ArrayList
26. When should the method invokeLater()be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.
27. How can a subclass call a method or a constructor defined in a superclass?
Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.
28. What do you understand by Synchronization?
Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}
29. What's the difference between a queue and a stack?
Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule
30. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.
31. If you're overriding the method equals() of an object, which other method you might also consider?
hashCode()
32. What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
33. How would you make a copy of an entire Java object with its state?
Have this class implement Cloneable interface and call its method clone().
34. How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references.
35. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.
36. Explain the Encapsulation principle.
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
37. Explain the Inheritance principle.
Inheritance is the process by which one object acquires the properties of another object.
38. Explain the Polymorphism principle.
The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".
From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:
* Method overloading
* Method overriding through inheritance
* Method overriding through the Java interface
39. Is Iterator a Class or Interface? What is its use?
Iterator is an interface which is used to step through the elements of a Collection.
40. Explain the user defined Exceptions?
User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
/ The class simply has to exist to be an exception
}
41. What is OOPS?
OOP is the common abbreviation for Object-Oriented Programming.
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.
39. Read the following program:
public class test {
public static void main(String [] args) {
int x = 3;
int y = 1;
if (x = y)
System.out.println("Not equal");
else
System.out.println("Equal");
}
}
What is the result?
The output is “Equal”
B. The output in “Not Equal”
C. An error at " if (x = y)" causes compilation to fall.
D. The program executes but no output is show on console.
Answer: C
Answer: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.
Interview Questions On Java Servlets
Questions on Servlets.
=====================
1) What is servlet?
Ans: Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.
2) What are the classes and interfaces for servlets?
Ans: There are two packages in servlets and they are javax.servlet and javax.servlet.http.
Javax.servlet contains:
Interfaces Classes
Servlet Generic Servlet
ServletRequest ServletInputStream
ServletResponse ServletOutputStream
ServletConfig ServletException
ServletContext UnavailableException
SingleThreadModel
Javax.servlet.http contains:
Interfaces Classes
HttpServletRequest Cookie
HttpServletResponse HttpServlet
HttpSession HttpSessionBindingEvent
HttpSessionContext HttpUtils
HttpSeesionBindingListener
3) What is the difference between an applet and a servlet?
Ans: a) Servlets are to servers what applets are to browsers.
b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.
4)what is the lifecycle of a servlet.
Ans: Each Servlet has the same life cycle:
a) A server loads and initializes the servlet by init () method.
b) The servlet handles zero or more client’s requests through service( ) method.
c) The server removes the servlet through destroy() method.
5) What is the ServletConfig() and why are using ServletConfig ?
Ans:This interface is implemented by services in order to pass configuration information to a servlet when it is first loaded.A service writer implementing this interface must write methods
for the servlet to use to get its initialization parameters and the context in which it is running.
public interface ServletConfig
6) What is meant by the ServletContext() and use of the method ?
Ans: public interface ServletContext
The ServletContext interface gives servlets access to information about their environment ,and allows them to log significant events. Servlet writers decide what data to log. The interface is implemented by services, and used by servlets. Different virtual hosts should have different servlet
contexts.
7) What is use of parseQueryString ?
Ans:
Parses a query string and builds a hashtable of key-value pairs, where the values are arrays
of strings. The query string should have the form of a string packaged by the GET or POST method.
(For example, it should have its key-value pairs delimited by ampersands (&) and its keys
separated from its values by equal signs (=).)
Note:
public static Hashtable parseQueryString(String s)
8)what are the types of servlets.
Ans: Genereic Servlets,HttpServlets.
9)what are the different methods in HttpServlet.
Ans: doGet(),doPost(),doHead,doDelete(),deTrace()
10)What is the difference between GET and POST.
Ans:
a) doGet() method is used to get information, while doPost( ) method is used for posting information.
b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However,
doPost( )requests passes all of its data, of unlimited length.
c) A doGet( ) request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.
11) Why do you need both GET and POST method implementations in Servlet?
Ans: A single servlet can be called from differenr HTML pages,so Different method calls can be possible.
12)When init() and Distroy() will be called.
Ans:init() is called whenever the servlet is loaded for the first time into the webserver.Destroy will be called whenever the servlet is removed from the webserver.
13) Who is loading the init() method of servlet?
Ans: Web server
14)If you want to modify the servlet,will the Webserver need to be ShutDown.
Ans:No
15)What is the advantage of Servlets over other serverside technologies.
Ans:PlatForm independent, so once compiled can be used in any webserver.For different processes different threads will execute inbuilt mutithreaded.
16) What is Server-Side Includes (SSI)?
Ans: Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many
servlets that support servlets, a page can be processed by the server to include output from servlets at certain
points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes
the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested.
So HTML files that include server-side includes must be stored with an .shtml extension.
17)What is Single Threaded Model in Servlets and how is it useful give one practical example.
Ans: For every single user a differnt copy of this servlet is executed. Credit card transactions.
18) What is the uses Sessions ?
Ans:Its a part of the SessionTracking and it is for mainting the client state at server side.
19)What are the advantage of using Sessions over Cookies and URLReWriting?
Ans:
Sessions are more secure and fast becasue they are stored at serverside. But Sessions has to be used combindly with Cookies or URLReWriting for mainting the client id that is sessionid at client side.
Cookies are stored at client side so some clients may disable cookies so we may not sure that the
cookies which we are mainting may work or not but in sessions cookies are disable we can maintain
our sessionid using URLReWriting .
In URLReWriting we can't maintain large data because it leads to network traffic and access may be
become slow.Where as in seesions will not maintain the data which we have to maintain instead
we will maintain only the session id.
20) What is session tracking and how do you track a user session in servlets?
Ans: Session tracking is a mechanism that servlets use to maintain state about a series requests
from the same user across some period of time. The methods used for session tracking are:
a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password
b) Hidden form fields - fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent back to the server
c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change.
d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser.
e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session.maxresidents property
21)What is Cookies and what is the use of Cookies ?
Ans:Cookies are used to get user agents (web browsers etc) to hold small amounts of state
associated with a user's web browsing.Later that infromation read by server
22) What are cookies and how will you use them?
Ans: Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information
associated with the user.
a) Create a cookie with the Cookie constructor:
public Cookie(String name, String value)
b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of
HttpServletResponse:
public void HttpServletResponse.addCookie(Cookie cookie)
c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest:
public Cookie[ ] HttpServletRequest.getCookie( ).
23) How many Cookies is supported to the host ?
Ans: User agents excepted to support twenty per host.And its take four Kilobytes each.
24) What is the use of setComment and getComment methods in Cookies ?
Ans:
setComment:If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment. This is not supported by version zero cookies.
public void setComment(String use)
{
}
getComment:
Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.
25)Why we are used setMaxAge() and getMaxAge() in Cookies ?
Ans:setMaxAge
public void setMaxAge(int expiry)
Sets the maximum age of the cookie.The cookie will expire after that many seconds have passed.Negative values indicate the default behaviour:the cookie is not stored persistently, and will be deleted when the user agent exits.A zero value causes the cookie to be deleted
getMaxAge():
public int getMaxAge()
Returns the maximum specified age of the cookie. If none was specified, a negative value is returned, indicating the default behaviour described with setMaxAge.
26)What is the use of setSecure() and getSecure() in Cookies ?
Ans: setSecure
Indicates to the user agent that the cookie should only be sent using a secure protocol (https). This should only be set when the cookie's originating server used a secure protocol to set the cookie's value.
public void setSecure(boolean flag)
getSecure:
Returns the value of the 'secure' flag.
public boolean getSecure()
27)What is meant by Httpsession and what is the use of sessions ?
Ans:
The HttpSession interface is implemented by services to provide an association between an HTTP client and HTTP server. This session, persists over multiple connections and/or requests during a given time period. Sessions are used to maintain state and user identity across multiple page requests.
HttpSession session = req.getSession(true);
28) What are the methods in HttpSession and use of those methods?
Ans:
a) getCreationTime()
Returns the time at which this session representation was created.
b) getId()
Returns the identifier assigned to this session.
c) getLastAccessedTime()
Returns the last time the client sent a request carrying the identifier assigned to the session.
d) getSessionContext()
Returns the context in which this session is bound.
e) getValue(String)
Returns the object bound to the given name in the session's application layer data.
f) getValueNames()
Returns an array of the names of all the application layer data objects bound into the
session.
g) invalidate()
Causes this representation of the session to be invalidated and removed from its context.
h) isNew()
A session is considered to be "new" if it has been created by the server, but the client has
not yet acknowledged joining the session.
j) putValue(String, Object)
Binds the specified object into the session's application layer data with the given name.
k) removeValue(String)
Removes the object bound to the given name in the session's application layer data.
29) How do you communicate between the servlets.
Ans: a)servlet chaning
b)Servlet context(RequestDespatcher interface)
30)Can you send the mail from a servlet ,if yes tell how?
Ans:yes.using mail API
31)How do you access variables across the sessions.
Ans:Through ServletContext.
32)where the session data will store?
ans: session objects
33)What is Servlet Context?
Ans:This object represents resources shared by a group of servlets like servlet's environment,
Application attributes shared in the context level.
34)How do you trap the debug the errors in servlets.
Ans:error log file
35)How do you debug the Servlet?
Ans:through servlet log();
36)How do u implement threads in servlet?
Ans:Intenally implemented
37)How do you handle DataBase access and in which method of the servlet do you like to create connection.
Ans:init()
38)If you want to improve the performance how do you create connections for multiple users?
A.Connection Pooling.
39)what is connection pooling?
Ans:Class which manages no of user requests for connections to improve the performance.
40) What are the different servers available for developing and deploying Servlets?
Ans: a) JRun2.0--Allaire
b) Apache --jserv
c) jwsdk2.0 --sun
d) servletexec
e) Tomcat webserver--tomcat
f)Weblogic AS--BEA Systems
g)NetDynamics5.0--sun
h)Iplanet--sun&netscape
i)Netscape--netscape
g)IBM websphere--IBM
h)oracle--oracle
i)Proton-Pramati technologies
41) Is it possible to communicate from an applet to servlet and how many ways and how?
Ans: Yes, there are three ways to communicate from an applet to servlet and they are:
a) HTTP Communication(Text-based and object-based)
b) Socket Communication
c) RMI Communication
(You can say, by using URL object open the connection to server and get the InputStream from
URLConnection object).
Steps involved for applet-servlet communication:
step: 1 Get the server URL.
URL url = new URL();
step: 2 Connect to the host
URLConnection Con = url.openConnection();
step: 3 Initialize the connection
Con.setUseCatches(false):
Con.setDoOutput(true);
Con.setDoInput(true);
step: 4 Data will be written to a byte array buffer so that we can tell the server the length of the data.
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
step: 5 Create the OutputStream to be used to write the data to the buffer.
DataOutputStream out = new DataOutputStream(byteout);
42) Why should we go for interservlet communication?
Ans: Servlets running together in the same server communicate with each other in several ways.
The three major reasons to use interservlet communication are:
a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object)
b) Servlet reuse - allows the servlet to reuse the public methods of another servlet.
c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)
43) Is it possible to call servlet with parameters in the URL?
Ans: Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).
44) What is Servlet chaining?
Ans: Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.
In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the
last servlet is reached. Its output is then sent back to the client.
45) How do servlets handle multiple simultaneous requests?
Ans: The server has multiple threads that are available to handle requests. When a request comes in, it is
assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the
servlet. For this reason, a single servlet object can have its service methods called by many threads at once.
46) How are Servlets and JSP Pages related?
Ans: 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.
Servlets:
47).How do servlets handle multiple simultaneous requests?
Ans: Using Threads
48).How do I automatically reload servlets?
Ans:depends upon the server's servlet reload properites.
48).My servlet, which ran correctly under the Servlet 2.0 APIs (Java Web Server 1.1.3) is not running under the Servlet 2.1 APIs (Java Web Server 2.0). What's wrong?
Ans:You might have used servlet to servlet communication by using servletcontext methods like
getServlet(),getServlets() which are depricated and returns null from new release that is from
servlet2.1 API.
49) What are the types of ServletEngines?
Standalone ServletEngine: A standalone engine is a server that includes built-in support for servlets.
Add-on ServletEngine: Its a plug-in to an existing server.It adds servlet support to a server that was not originally designed with servlets in mind.
Embedded ServletEngine: it is a lightweight servlet deployment platform that can be embedded in another application.that application become true server.
50)what is httptunneling?
ans:
it is mechanism of performing both write and read operations using http protocol.it is extending the functionality of htp protocol.
48).How do I use native code in a servlet?
Ans:
49)What's with the javax.servlet package naming?
Ans:
50. List out Differences between CGI Perl and Servlet?
Servlet CGI
Platform independent Platform dependent.
Language dependent Language independent.
Core Java Interview Questions
Question: How could Java classes direct program messages to the system console, but error messages, say to a file?
Answer: The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);
Question: What's the difference between an interface and an abstract class?
Answer: An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.
Question: Why would you use a synchronized block vs. synchronized method?
Answer: Synchronized blocks place locks for shorter periods than synchronized methods.
Question: Explain the usage of the keyword transient?
Answer: This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
Question: How can you force garbage collection?
Answer: You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
Question: How do you know if an explicit object casting is needed?
Answer: If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.
Question: What's the difference between the methods sleep() and wait()
Answer: The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
Question: Can you write a Java class that could be used both as an applet as well as an application?
Answer: Yes. Add a main() method to the applet.
Question: What's the difference between constructors and other methods?
Answer: Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.
Question: Can you call one constructor from another if a class has multiple constructors
Answer: Yes. Use this() syntax.
Question: Explain the usage of Java packages.
Answer: This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.
Question: If a class is located in a package, what do you need to change in the OS environment to be able to use it?
Answer: You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee
Question: What's the difference between J2SDK 1.5 and J2SDK 5.0?
Answer: There's no difference, Sun Microsystems just re-branded this version.
Question: What would you use to compare two String variables - the operator == or the method equals()?
Servlet Interview Questions
What is the servlet?
Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently
What is the architechture of servlet package?
Servlet Interface is the central abstraction. All servlets implements this Servlet
Interface either direclty or indirectly
( may implement or extend Servlet Interfaces sub classes or sub interfaces)
Servlet
|
Generic Servlet
|
HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests
|
MyServlet
What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method to handle requests.
HttpServlet extends GenericServlet added new methods
doGet()
doPost()
doHead()
doPut()
doOptions()
doDelete()
doTrace() methods
Both these classes are abstract.
What's the difference between servlets and applets?
Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets have no graphical user interface.
What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers.
When doGET() method will going to execute?
When we specified method='GET' in HTML
Example : < name="'SSS'" method="'GET'">
When doPOST() method will going to execute?
When we specified method='POST' in HTML
< name="'SSS'" method="'POST'">
What is the difference between Difference between doGet() and doPost()?
GET Method : Using get method we can able to pass 2K data from HTML
All data we are passing to Server will be displayed in URL (request string).
POST Method : In this method we does not have any size limitation.
All data passed to server will be hidden, User cannot able to see this info
on the browser.
What is the servlet life cycle?
When first request came in for the servlet , Server will invoke init() method of the servlet. There after if any user request the servlet program, Server will directly executes the service() method. When Server want to remove the servlet from pool, then it will execute the destroy() method
Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set.
Which protocol will be used by browser and servlet to communicate ?
HTTP
In how many ways we can track the sessions?
Method 1) By URL rewriting
Method 2) Using Session object
Getting Session form HttpServletRequest object
HttpSession session = request.getSession(true);
Get a Value from the session
session.getValue(session.getId());
Adding values to session
cart = new Cart();
session.putValue(session.getId(), cart);
At the end of the session, we can inactivate the session by using the following command
session.invalidate();
Method 3) Using cookies
Method 4) Using hidden fields
How Can You invoke other web resources (or other servelt / jsp ) ?
Servelt can invoke other Web resources in two ways: indirect and direct.
Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource)
Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object.
You can get this object using getRequestDispatcher("URL") method. You can get this object from either a request or a Context.
Example :
RequestDispatcher dispatcher = request.getRequestDispatcher("/jspsample.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
}
How Can you include other Resources in the Response?
Using include method of a RequestDispatcher object.
Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example, setCookie) that affects the headers of the response.
Example : RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner");
 if (dispatcher != null)
 dispatcher.include(request, response);
}
What is the difference between the getRequestDispatcher(String path) ServletRequest interface and ServletContext interface?
The getRequestDispatcher(String path) method of ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.
The getRequestDispatcher(String path) method of ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition.
What is the use of ServletContext ?
Using ServletContext, We can access data from its environment. Servlet context is common to all Servlets so all Servlets share the information through ServeltContext.
Is there any way to generate PDF'S dynamically in servlets?
We need to use iText. A open source library for java. Please refer sourceforge site for sample servlet examples.
What is the difference between using getSession(true) and getSession(false) methods?
getSession(true) - This method will check whether already a session is existing for the user. If a session is existing, it will return that session object, Otherwise it will create new session object and return taht object.
getSession(false) - This method will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.
Java Interview Questions
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 is meant by pass by reference and pass by value in Java?
Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.
If you’re overriding the method equals() of an object, which other method you might also consider?
hashCode()
What is Byte Code?
Or
What gives java it’s “write once and run anywhere” nature?
All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.
Expain the reason for each keyword of public static void main(String args[])?
public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.
static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.
void: main does not return anything so the return type must be void
The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.
What are the differences between == and .equals() ?
Or
what is difference between == and equals
Or
Difference between == and equals method
Or
What would you use to compare two String variables - the operator == or the method equals()?
Or
How is it possible for two String objects with identical values not to be equal under the == operator?
The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.
public class EqualsTest{
public static void main(String[] args){
String s1 = "abc";
String s2 = s1;
String s5 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
// if we remove the brackets around "s1 == s5' it gives a different result.
System.out.println("== comparison : " +(s1 == s5));
System.out.println("== comparison : " +(s1 == s2));
System.out.println("Using equals method : " +s1.equals(s2));
System.out.println("== comparison : " +s3 == s4);
System.out.println("Using equals method : " +s3.equals(s4));
}
}
Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true
What if the static modifier is removed from the signature of the main method?
Or
What if I do not provide the String array as the argument to the method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
Why oracle Type 4 driver is named as oracle thin driver?
Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.
What is the difference between final, finally and finalize? What do you understand by the java final keyword?
Or
What is final, finalize() and finally?
Or
What is finalize() method?
Or
What is the difference between final, finally and finalize?
Or
What does it mean that a class or member is final?
o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection
Variables defined in an interface are implicitly final. A final class can't be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.
What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.
What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.
Why there are no global variables in Java?
Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
* The global variables breaks the referential transparency
* Global variables creates collisions in namespace.
How to convert String to Number in java program?
The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = "1000";
int id=Integer.valueOf(numString).intValue();
What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
What is the difference between a while statement and a do statement?
A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.
What is the Locale class?
The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.
Describe the principles of OOPS.
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.
Explain the Inheritance principle.
Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places
What is implicit casting?
Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.
Example
int i = 1000;
long j = i; //Implicit casting
Is sizeof a keyword in java?
The sizeof operator is not a keyword.
What is a native method?
A native method is a method that is implemented in a language other than Java.
In System.out.println(), what is System, out and println?
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.
What are Encapsulation, Inheritance and Polymorphism
Or
Explain the Polymorphism principle. Explain the different forms of Polymorphism.
Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.
Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
What is explicit casting?
Explicit casting in the process in which the complier are specifically informed to about transforming the object.
Example
long i = 700.20;
int j = (int) i; //Explicit casting
What is the Java Virtual Machine (JVM)?
The Java Virtual Machine is software that can be ported onto various hardware-based platforms
What do you understand by downcasting?
The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy
What are Java Access Specifiers?
Or
What is the difference between public, private, protected and default Access Specifiers?
Or
What are different types of access modifiers?
Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
• Public : accessible to all classes
• Protected : accessible to the classes within the same package and any subclasses.
• Private : accessible only to the class to which they belong
• Default : accessible to the class to which they belong and to subclasses within the same package
Which class is the superclass of every class?
Object.
Name primitive Java types.
The 8 primitive types are byte, char, short, int, long, float, double, and boolean.
What is the difference between static and non-static variables?
Or
What are class variables?
Or
What is static in java?
Or
What is a static method?
A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.
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 non-static method. In other words, you can't change a static method into an instance method in a subclass.
Non-static variables take on unique values with each object instance.
What is the difference between the boolean & operator and the && operator?
If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.
How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
What if I write static public void instead of public static void?
Program compiles and runs properly.
What is the difference between declaring a variable and defining a variable?
In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String ("bob"); Or String s = "bob"; are both definitions.
What type of parameter passing does Java support?
In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.
Explain the Encapsulation principle.
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
What do you understand by a variable?
Variable is a named memory location that can be easily referred in the program. The variable is used to hold the data and it can be changed during the course of the execution of the program.
What do you understand by numeric promotion?
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
What do you understand by casting in java language? What are the types of casting?
The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting.
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 we do not provide any arguments on the command line, then the String array of main method will be empty but not null.
How can one prove that the array is not null but empty?
Print array.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 array.length.
Can an application have multiple classes having main method?
Yes. 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.
When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?
Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields.
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.
Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes.
How can I swap two variables without using a third variable?
Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:
int a=5,b=10;a=a+b; b=a-b; a=a-b;
What is data encapsulation?
Encapsulation may be used by creating 'get' and 'set' methods in a class (JAVABEAN) which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is nothing but wrapping up the data and associated methods into a single unit in such a way that data can be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data hiding.
What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.
Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.
What is phantom memory?
Phantom memory is false memory. Memory that does not exist in reality.
Can a method be static and synchronized?
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class) {
}
What is difference between String and StringTokenizer?
A StringTokenizer is utility class used to break up string.
Example:
StringTokenizer st = new StringTokenizer("Hello World");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Output:
Hello
World
EJB And Java Interview Questions
1. What is Entity Bean and Session Bean ?
2. What are the methods of Entity Bean?
3. How does Stateful Session bean store its state ?
4. Why does Stateless Session bean not store its state even though it has ejbActivate and ejbPassivate ?
5. What are the services provided by the container ?
6. Types of transaction ?
7. What is bean managed transaction ?
8. Why does EJB needs two interface( Home and Remote Interface) ?
9. What are transaction attributes ?
10. What is the difference between Container managed persistent bean and Bean managed persistent entity bean ?
11. What is J2EE ?
12. What is JTS ?
13. How many entity beans used and how many tables can u use in EJB project ?
14. What is scalable,portability in J2EE?
15. What is Connection pooling?Is it advantageous?
16. Method and class used for Connection pooling ?
17. How to deploy in J2EE(i.e Jar,War file) ?
18. How is entity bean created using Container managed entity bean ?
19. Sotware architechture of EJB ?
20. In Entity bean will the create method in EJB home and ejbCreate in Entity bean have the same parameters ?
21. What methods do u use in Servlet – Applet communication ?
22. What are the types of Servlet ?
23. Difference between HttpServlet and Generic Servlets ?
24. Difference between doGet and doPost ?
25. What are the methods in HttpServlet?
26. What are the types of SessionTracking?
27. What is Cookie ? Why is Cookie used ?
28. If my browser does not support Cookie,and my server sends a cookie instance What will happen ?
29. Why do u use Session Tracking in HttpServlet ?
30. Can u use javaScript in Servlets ?
31. What is the capacity the doGet can send to the server ?
32. What are the type of protocols used in HttpServlet ?
33. Difference between TCP/IP and IP protocol ?
34. Why do you use UniCastRemoteObject in RMI ?
35. How many interfaces are used in RMI?
36. Can Rmi registry be written in the code, without having to write it in the command prompt and if yes where?
37. Why is Socket used ?
38. What are the types of JDBC drivers ?
39. Explain the third driver(Native protocol driver) ?
40. Which among the four driver is pure Java driver ?
41. What are the Isolation level in JDBC transaction ?
42. How do you connect with the database ?
43. How do you connect without the Class.forName (" ") ?
44. What does Class.forName return ?
45. What are the types of statement ?
46. Why is preparedStatement,CallableStatement used for?
47. In real time project which driver did u use ?
48. Difference between AWT and Swing compenents ?
49. Is there any heavy weight component in Swings ?
50. Can the Swing application if you upload in net, be compatible with your browser?
51. What should you do get your browser compatible with swing components?
52. What are the methods in Applet ?
53. When is init(),start() called ?
54. When you navigate from one applet to another what are the methods called ?
55. What is the difference between Trusted and Untrusted Applet ?
56. What is Exception ?
57. What are the ways you can handle exception ?
58. When is try,catch block used ?
59. What is finally method in Exceptions ?
60. What are the types of access modifiers ?
61. What is protected and friendly ?
62. What are the other modifiers ?
63. Is synchronised modifier ?
64. What is meant by polymorphism ?
65. What is inheritance ?
66. What is method Overloading ? What is this in OOPS ?
67. What is method Overriding ? What is it in OOPS ?
68. Does java support multi dimensional arrays ?
69. Is multiple inheritance used in Java ?
70. How do you send a message to the browser in JavaScript ?
71. Does javascript support multidimensional arrays ?
72. Why is XML used mainly?
73. Do use coding for database connectivity in XML?
74. What is DTD ?
75. Is there any tool in java that can create reports ?
JMS Interview Questions
What is JMS?
JMS is an acronym used for Java Messaging Service. It is Java's answer to creating software using asynchronous messaging. It is one of the official specifications of the J2EE technologies and is a key technology.
How JMS is different from RPC?
In RPC the method invoker waits for the method to finish execution and return the control back to the invoker. Thus it is completely synchronous in nature. While in JMS the message sender just sends the message to the destination and continues it's own processing. The sender does not wait for the receiver to respond. This is asynchronous behavior.
What are the advantages of JMS?
JMS is asynchronous in nature. Thus not all the pieces need to be up all the time for the application to function as a whole. Even if the receiver is down the MOM will store the messages on it's behalf and will send them once it comes back up. Thus at least a part of application can still function as there is no blocking.
Are you aware of any major JMS products available in the market?
IBM's MQ Series is one of the most popular product used as Message Oriented Middleware. Some of the other products are SonicMQ, iBus etc. Weblogic application server also comes with built in support for JMS messaging.
What are the different types of messages available in the JMS API?
Message, TextMessage, BytesMessage, StreamMessage, ObjectMessage, MapMessage are the different messages available in the JMS API.
What are the different messaging paradigms JMS supports?
Publish and Subscribe i.e. pub/suc and Point to Point i.e. p2p.
What is the difference between topic and queue?
A topic is typically used for one to many messaging i.e. it supports publish subscribe model of messaging. While queue is used for one-to-one messaging i.e. it supports Point to Point Messaging.
What is the role of JMS in enterprise solution development?
JMS is typically used in the following scenarios
1. Enterprise Application Integration: - Where a legacy application is integrated with a new application via messaging.
2. B2B or Business to Business: - Businesses can interact with each other via messaging because JMS allows organizations to cooperate without tightly coupling their business systems.
3. Geographically dispersed units: - JMS can ensure safe exchange of data amongst the geographically dispersed units of an organization.
4. One to many applications: - The applications that have to push data in packet to huge number of clients in a one-to-many fashion are good candidates for the use JMS. Typical such applications are Auction Sites, Stock Quote Services etc.
What is the use of Message object?
Message is a light weight message having only header and properties and no payload. Thus if the received are to be notified abt an event, and no data needs to be exchanged then using Message can be very efficient.
What is the basic difference between Publish Subscribe model and P2P model?
Publish Subscribe model is typically used in one-to-many situation. It is unreliable but very fast. P2P model is used in one-to-one situation. It is highly reliable.
What is the use of BytesMessage?
BytesMessage contains an array of primitive bytes in it's payload. Thus it can be used for transfer of data between two applications in their native format which may not be compatible with other Message types. It is also useful where JMS is used purely as a transport between two systems and the message payload is opaque to the JMS client. Whenever you store any primitive type, it is converted into it's byte representation and then stored in the payload. There is no boundary line between the different data types stored. Thus you can even read a long as short. This would result in erroneous data and
hence it is advisable that the payload be read in the same order and using the same type in which it was created by the sender.
What is the use of StreamMessage?
StreamMessage carries a stream of Java primitive types as it's payload. It contains some conveient methods for reading the data stored in the payload. However StreamMessage prevents reading a long value as short, something that is allwed in case of BytesMessage. This is so because the StreamMessage also writes the type information alonwgith the value of the primitive type
and enforces a set of strict conversion rules which actually prevents reading of one primitive type as another.
What is the use of TextMessage?
TextMessage contains instance of java.lang.String as it's payload. Thus it is very useful for exchanging textual data. It can also be used for exchanging complex character data such as an XML document.
What is the use of ObjectMessage?
ObjectMessage contains a Serializable java object as it's payload. Thus it allows exchange of Java objects between applications. This in itself mandates that both the applications be Java applications. The consumer of the message must typecast the object received to it's appropriate type. Thus the consumer should before hand know the actual type of the object sent by the sender. Wrong type casting would result in ClassCastException. Moreover the class definition of the object set in the payload should be available on both the machine, the sender as well as the consumer. If the class definition is not available in the consumer machine, an attempt to type cast would result in ClassNotFoundException. Some of the MOMs might support dynamic loading of the desired class over the network, but the JMS specification does not mandate this behavior and would be a value added service if provided by your vendor. And relying on any such vendor specific functionality would hamper the portability of your application. Most of the time the class need to be put in the classpath of both, the sender and the consumer, manually by the developer.
What is the use of MapMessage?
A MapMessage carries name-value pair as it's payload. Thus it's payload is similar to the java.util.Properties object of Java. The values can be Java primitives or their wrappers.
What is the difference between BytesMessage and StreamMessage??
BytesMessage stores the primitive data types by converting them to their byte representation. Thus the message is one contiguous stream of bytes. While the StreamMessage maintains a boundary between the different data types stored because it
also stores the type information along with the value of the primitive being stored. BytesMessage allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the StreamMessage. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.