Enter your keyword

post

JAVA Interview Questions-2

1.What is the use of static import?
Ans:If you use static imports we can access static methods and static variables without the reference of class name.

2.Relation between List and LinkedList?
Ans:List is an interface , LinkedList is a class which implements it
3. Why Set interface contains unique elements, what internally is
Ans:implemented for this so that it contains unique elements?
Because it implements hashCode() and equals() methods implicitly.
4. Difference between overriding and overloading ?
Ans:1.With overloading there is no restriction on return types where as in overriding return types should be same upto 1.4 but with the release of 1.5 co-variant return types were also allowed.

2.Either order or type of arguments in overloaded methods should be different whereas they should be same in overridden methods.

3.Methods having private,static and final modifiers cannot participate in overriding whereas there is no such restriction for overloading

4.Overriding is possible only when classes are part of inheritance whereas overloading is possible both in inheritance and in the same class.

5. Overloading is also known as compile time or static polymorphism and early binding whereas overriding is also known as run time or dynamic polymorphism and late binding.

6. The overriding methods may not limit the access of the method it overrides and couldn’t throw any exceptions that may not be thrown by the overridden method where there is no such restriction for overloaded methods.

5.What is a native method?
Ans:native is a keyword which is applicable only for methods.
A native method is a method which is implemented in a language other than java. They are used for performance and accessing hardware which java is not aware of . native methods should always be terminated with a semicolon , curly brace will provide a compiler error

6.Why String class is immutable?
Ans:Once a String object is created no changes can be made to it. If at all we are trying to make any changes in the existing string object , with those changes a new String object will be created that’s the reason String class is immutable.

7.Can we override the start() of Thread class?
Ans:Yes we can override start() but it is not recommended . Why because the start() of Thread class first instantiates and then registers our new thread with the thread scheduler and finally invokes run() method all on its owns

8. Which one is performance wise advantageous from List,Set ?
Ans:Set cares about uniqueness,so each time u add an object it checks whether it exists or not calling equals() which in turn calls the hashCode()

List : Incase we are using ArrayList or Vector , since both implement RandomAccess interface hence retrieval is faster but insertion or deletion is slower.

LinkedList enables faster insertion or deletion and slower retrieval as it does not implement RandomAccess interface.

9.Difference between StringBuffer and StringBuilder ?

Ans:Methods in StringBuffer are synchronized whereas the same is not true with StringBuilder.

StringBuffer was introduced in jdk 1.0 where as StringBuilder came in java5.0.

As methods in StringBuffer are thread-safe StringBuffer is bad in performance whereas as StringBuilder is good in performance as its methods are not synchronized.

10.Difference between ListIterator and Iterator ?
Ans:1.ListIterator allows the programmer to traverse the list in either direction so it’s a bidirectional interface whereas Iterator allows accessing of elements only in forward direction so its an unidirectional interface.

2. ListIterator allows insertion of elements into the collection whereas the same is not true using Iterator.

3. ListIterator is restricted to iterate over collection objects only for List implemented classes whereas Iterator allows to iterate over collection objects both for Set and List implemented classes

10.Difference between array and collection?
1.arrays are fixed in size whereas collections are growable in nature.

2.For arrays memory allocation is static and continuos whereas for collection memory allocation is dynamic and random.
3.array can store homogeneous elements whereas collection can hold heterogeneous elements.

4.arrays can be used to store both primitives and objects whereas collection can be used to store only objects.

11.How to invalidate a session?
Ans:1.A session may be explicitly invalidated by calling HttpSession.invalidate()
2.It times out after a

If the client doesn’t make any any requests on this session for certain amount of time

12.How does the container know who the client is?
Ans:1.On the client’s first request ,the container generates a unique session ID and gives it back to the client with the response.
2.The client sends back the session ID with each subsequent request.
3.The container sees the ID, finds the matching session and associates the session with the client.

13.What is URL Rewriting?
Ans:URL Rewriting takes the session ID that’s in the cookie and sticks it right onto the end of each and every urls that is part of the response . The session ID then comes back with the request as extra info at the end of the request URL.
:response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL()

14.How to communicate from jsp to servlet ?
Ans:Using or we can dispatch the request from a jsp to servlet & nbsp;

15.When we will use the sendRedirect method instead of forward?
Ans:When there is no need to record or maintain the previous data of the user.Like in Google we are searching some information and after clicking on the searched item it will forward to some other site or link i.e where
there is no need to maintain any previous information of user.

16.Difference between Comaparator and comparable ?
Ans:1.A Comparator implemented class must contain a method called compare to compare two objects whereas a Comparable implemented class must implement a method called compareTo.
2.Comparable interface is for objects with a natural ordering.The object itself knows how it is to be ordered. Whereas Comparator is for objects without a natural ordering or when you wish to use a different ordering i.e custom ordering.

17.Difference between jsp and servlet ?
Ans:1.In servlets we have html embedded in java code and in case of jsps it is java code that is embedded in html.
2.It is because incase of servlets both business logic and presentation logic are given by the same java file ,any change in presentation logic will lead to the entire compilation of the java file and replacing the .class file back in the servlet container. When it comes to jsps we have both presentation and application logic separated . So even if we modify the presentation logic we need not compile or modify any content of servlet.
3.As servlet is best suited for request processing , handling the business logic while jsp is suitable for content generating so in many frameworks servlet acts as controller and while jsp as a view.
4.Unlike jsps for getting objects like HttpSession and PrintWriter we have to explicitly instantiate them but they are implicitly provided by the Container.

18.How to print a string without using out.println()?
Ans:Using expression
<%=”Hi”%>
Using jstl’s core tag library’s out tag

19.Can we override service method in jsp?
Ans:No we cannot override the final method from HttpJspBase

20.Can we use methods in JSP? If so where the methods are stored in servlet class file?
Ans:Yes we can write methods inside jsp files within the declarations tag.

<%! //the method %>
This part of code is compiled by the servlet engine and inserted outside the _jspService method

21.How to set a cookie in JSP?
Ans:<% Cookie myCookie = new Cookie(“aName”,“aValue”); response.addCookie(myCookie); %>
22.What is session?
Ans:Session is an object which keeps client specific state across multiple requests.

23.What is encapsulation , abstraction , inheritance and polymorphism ?
Ans:Encapsulation is the technique of making fields in a class private and providing access to the fields via public methods.
Abstraction is nothing but highlighting essential features while hiding the non essential features to the user. A programmer does not need to worry about all the details of how it performs its computations , he should only needs to know how to call it and what it computes.
Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality
Polymorphism is the capability of an action or method to do different things based on the object it is acting upon.

24. What is serialization and deserialization ?
Ans:Serialization is a process by which an object is converted into stream of bytes but strictly speaking serialization is the process of converting an object from java supported form to either network supported form or file supported form.
By using FileOutputStream and ObjectOutputStream we can perform serialization.
The process of reading an object from the file is deserialization but strictly speaking it is the process of converting an object from either file supported format or network supported format
to java supported format.
By using FileInputStream and ObjectInputStream we can perform deserialization.

25.How do we implement serialization actually?
Ans:In order to implement serialization and deserialization we need to use two classes from java.io.package ObjectOutputStream and ObjectInputStream . ObjectOutputStream has a method called writeObject , while ObjectInputStream has a method called readObject.Using writeObject we can write and readObject can be used to read an object from stream.

public class TransientDemo implements Serializable{

private int i =10;
private int j =30;
public static void main(String[] args) {
TransientDemo td = new TransientDemo();
try {
// serialization
FileOutputStream fos = new FileOutputStream(“abc.txt”);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(td);

// deserialization
FileInputStream fis = new FileInputStream(“abc.txt”);
ObjectInputStream ois = new ObjectInputStream(fis);
TransientDemo tdemo=(TransientDemo)ois.readObject();
System.out.println(tdemo.i+”…..”+tdemo.j);

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

26. What are abstract classes ?
Ans:Abstract classes are the classes that contain one or more abstract methods or a class that is declared with abstract modifier. An abstract method is a method that is declared but doesn’t contain any implementation . Abstract classes cannot be instantiated
and require subclasses to provide implementation for the abstract
methods i.e the class must be inherited , this class is mostly used as a base class.

27.Difference between user calling start and run method ?
Ans:In case of start() a new thread will be created which is responsible for the execution of run()
But incase of run() , no new thread will be created and run() method will be executed just like any other method called by the main thread.

28.How many ways are there to create a thread ? Which approach is recommended and why?
Ans:There are two ways for creating a thread
1.Making your class “extends” Thread class
2.Making your class “implements” Runnable interface

public class ExtendingAThread extends Thread {
public void run()
{
System.out.println(” run() got called “);
}
public static void main(String[] args) {

ExtendingAThread thread = new ExtendingAThread();
thread.start();
}
}

public class ThreadWithRunnable implements Runnable {

public void run() {
System.out.println(” run method got called…..”);
}
public static void main(String[] args) {

ThreadWithRunnable threadObj = new ThreadWithRunnable();
Thread thread = new Thread(threadObj);
thread.start();
}
}
When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:
Extending the Thread class means that the subclass cannot extend any other class as multiple inheritance is not allowed in java whereas a class implementing the Runnable interface has this option.
A class might only be interested in being runnable and therefore inherting the full overhead of the Thread class would be excessive.
So if you just want to achieve basic functionality of a thread you can simply implement Runnable interface and override run() but if you want to do something serious with thread object as it has other methods like sleep,join etc extend Thread class as they are not available in Runnable.

29 What is a thread?
Ans:A thread is a single sequential flow of control within a program

30.What is join() ?
Ans:A thread invokes the join() method on another thread in order to wait for the other thread to complete its execution.
public class JoinThread extends Thread {

public void run()
{
List list = new ArrayList();
list.add(“100”);
list.add(“200”);
for(String o : list)
System.out.println(o);
}

}
public class TestJoinThread {
public static void main(String[] args) {
JoinThread jt = new JoinThread();
jt.start();
System.out.println(“….Calling join on JoinThread….”);
try {
jt.join(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(“….Returned after completing run method….”);
}
}

If any executing thread t1 calls join() on t2 i.e t2.join() immediately t1 will enter into the waiting state until t2 completes its execution.
public final void join(long millis)
throws InterruptedException
Waits at most milliseconds for this thread to die . A timeout of 0 means to wait forever.
public final void join(long millis,int nanos)
throws InterruptedException
waits for this thread to die
Waits at most milliseconds plus nanoseconds for this thread to die .

31.What is a yield method ?
Ans:Causes the currently executing thread object to temporarily pause and allow other threads to execute.

The static method is essentially used to notify the system that the current thread is willing to give up the CPU for a while.The general idea is that the thread scheduler will select a different thread to run instead of the current one.

public class YieldThread implements Runnable {
public void run() {
List list = new ArrayList();
list.add(“111”);
list.add(“222”);
for(String o : list)
System.out.println(o);
}
}

public class TestYieldThread {
public static void main(String[] args) {
YieldThread yt = new YieldThread();
Thread thread = new Thread(yt);
thread.start();
System.out.println(“….Calling yield on JoinThread….”);
Thread.yield();
System.out.println(“….Returned after completing run method….”);
}
}

32. What is a sleep method()?
Ans:The sleep method causes the current thread to suspend execution for a specified period.

public class SleepThread extends Thread {
public void run()
{
System.out.println(“thread “+Thread.currentThread().getName()+”is executing “);
for(int i =0;i<5;i++)
{
System.out.println(” SleepThread…”);
}
}
}
public class TestSleepThread {
public static void main(String[] args) {
SleepThread st = new SleepThread();
st.setName(“lavanya”);
st.start();
System.out.println(“Calling sleep method …!!!!!!”);

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(“thread”+Thread.currentThread().getName()+”…woke up “);
}
}

33.What is synchronization?
With respect to multithreading synchronization is the process of controlling the access of shared resources by the multiple threads
in such a manner that only one thread can access that resource at a time.

34. Explain thread life cycle
Ans:New : It is the state when the thread instance has been just created.In this state the thread is not considered alive.
Ready to run/Runnable: This is the state when the thread is eligible to run.A thread starts its life cycle with a call to start().A call to start will not immediately start thread’s execution but rather will move it to pool of threads waiting for their turn to be picked by thread scheduler for execution .The thread scheduler picks one of the ready to run threads based on thread priorities.
A thread can return to the Runnable state either from running,waiting ,sleeping or coming back from blocked state.
Running:It is the state when the thread scheduler selects the thread to be currently executing process.It runs until it is swapped out , becomes blocked or voluntarily gives up its turn with its static method yield.There are several ways to enter in Runnable state but there is only way to enter in running state : i.e only when thread scheduler selects a thread from runnable pool.
Waiting:It is also known as blocked or sleeping state.In this state the thread is not eligible to run but it might return to runnable state if particular event occurs like calling of notify(),notifyAll(),interrupt() or availability of resources.A thread can enter in this state because of waiting for the resources that are held by another thread i.e because of waiting to acquire the lock of an object or waiting for the completion of another thread or while waiting for data from I/O device.
Dead : A thread can be considered as dead when its run method completes or when it is finished working. If any thread comes on this state that means it cannot ever run again.105.Collection Hierarchy

35.What is multithreading?
Ans:Multithreading is the mechanism in which more than one thread run independent of each other within the process.

36.Difference between Exception and Error?
Ans:An Error is an irrecoverable condition occurring at runtime while exception can be caught and recovered .
Examples of Error are
OutOfMemoryError,StackOverflowError

37.Is it necessary that each try block must be followed by a catch block?
Ans:It is not necessary that each try block must be followed by a catch block.It should be followed by either a catch block or a finally block.

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

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

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

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

42.What is association?
Ans:An association represent relationship between instances of one class and instances of another.

43.What is composition?
Ans:In a composition relationship a class holds the reference to another class in one of its instance variable.

44.Difference between HTML and XML?
Ans:1. HTML was designed to display data and to focus on how data looks whereas XML was designed to carry data and to focus on what data is
2. HTML is case-insensitive whereas XML is case sensitive .
3. HTML contains predefined tags whereas in XML we have to define our own tags .
4. In HTML it is optional to close each and every tag whereas it is mandatory in XML.

45.What is well formed XML document?
Ans:Well formed means that your document follows rules which allow data to be read by any commercial paraser.We should ensure that our document
contains
a)a root element b)xml elements must be closed in the order they are opened

46.What is the difference between well-formed and valid XML document?
Ans:XML with correct syntax is well formed XML whereas XML validated against a DTD is valid XML
W3C , in the XML specification , has defined certain rules that need to be followed while creating XML documents.The examples of such rules include : having exactly one root element , having end tag for each start tag, using single/double quotes for attribute values and so on .If an XML document follows all these rules , it is said to be well formed document and XML parsers can be used to parse and process such documents.
Document type definitions (DTDs) or XML schemas can be used to define the structure and content of a specific class of XML documents.This includes the parent child relationship details , attribute lists,data type information , value restrictions etc. In addition to well formedness rules , if an XML document also follows the rules specified in the associated DTD/schema , it is said to be a valid XML document.
All valid XML documents are well formed
Design patterns
MVC design pattern isolates the application logic for the user from the user interface , permitting independent development , testing and maintenance of each

47.What are EL implicit objects?
Ans:There are 11 EL implicit objects .
a) pageScope b) requestScope c) sessionScope d)applicationScope
e) header f)headerValues g)param h)paramValues i)cookie j)initParam k) pageContext

48.Difference between String and StringBuffer ?
Ans:Objects of type String are read only and immutable whereas StringBuffer is mutable.
StringBuffer concatenation is significantly faster than String concatenation.

49.Difference between forward and sendRedirect?
Ans:1.forward works within the application whereas sendRedirect can also work outside of the application.
2. forward is faster than sendRedirect.
3.If you use sendRedirect then no request and response objects will be available to you on the forwarded page while it can be available through forward.
4.If we use sendRedirect() the url of the browser gets changed while it is not changed by forward
5. forward happens on the server whereas sendRedirect happens on the client side.

50.Explain the different scope values for the tag?
Ans:
page

request

session and

application

51.Explain about the ServletContext ?
Ans:It is an interface that defines a set of methods that a servlet uses to communicate with its servlet container for example to get the MIME type of a file , dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object which the web server provides the servlet when the servlet is initiailzed

52.What is an interface?
Ans:An interface is a named collection of method definitions without implementations.

53.What is the difference between an application server and web server?
Ans:Everything in web server must be achieved programmatically .But application servers provide a lot of services like security , transaction , scalability . Application server will be having EJB support whereas webserver doesn’t have EJB support.
Examples of application server are IBM’s WebSphere Application Server
BEA Weblogic Application Server
Example of web server is Tomcat

54.What is casting ?
Ans:Explicit conversion from one data type to another

55.What is finally?
Ans:A java keyword that executes a block of statements regardless of whether a java exception or run time error occurred in a block defined
Previously by the try keyword.

56.What is volatile ?
Ans:A java keyword used in variable declarations that specifies that the variable is modified asynchronously by concurrently running threads.

57.What is the difference between yielding and sleeping in java programming?
Ans:When a task invokes its yield() it returns to the ready state.When a task invokes its sleep() method it returns to the waiting state.
Sleep will pause the current thread for the specified number of milliseconds.
Yield will give an opportunity for other threads to execute , if you use multiple threads.If there are no other threads , or other threads have nothing to do , after a yield the current thread will continue executing almost immediately.

58.What is the purpose of finalization in java programming?
Ans:The purpose of finalization is to give an unreachable object the opportunity to perform any clean up processing before the object is garbage collected.

59.What is the purpose of the finally clause of try catch finally statement in java programming?
Ans:The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

60.What are the high level thread states in java programming?
Ans:The high level thread states are ready,running,waiting and dead.

61.Difference between Collection and Collections ?
Ans:Collection is a base interface for most collection classes whereas Collections is a utility class

61.What is a cookie?
Ans:A cookie is a small amount of information sent by a servlet to a web browser , saved by the browser and later sent back to the server along with each subsequent request . A cookie’s value can uniquely identify a client so cookies are commonly used for session management.

62.What is ServletConfig ?
Ans:A servlet configuration object used by a servlet container to pass the initialization information to a servlet during initialization. The object is built by the servlet container by using the information mentioned in the element of the Deployment Descriptor(web.xml) for that particular servlet.

63.What are the methods available in ServletConfig ?
Ans:
1. java.lang.String getInitParameter(java.lang.String name)

2. java.lang.Enumeration getInitParameterNames()

3. ServletContext getServletContext()

4. java.lang.String getServletName()

64. How to get individual elements in a String?
Ans:
public class JavaStringSplitExample {

public static void main(String[] args) {
/* String to split */
String str=”one-two-three”;
String[] temp;

/* delimiter */
String delimiter = “-“;

/* given string will be split by the argument delimiter provided */
temp = str.split(delimiter);

/* print substrings */
for(int i=0;i<temp.length;i++)
{
System.out.println(temp[i]);
}

/*For getting three */
String third = temp[2];
System.out.println(“..The third element is..”+third);
}
}

65. How do I convert a String to an int ?
Ans: public class ConvertStringToInt {

public static void main(String[] args) {
String s = “100”;
try
{
// The String to int conversion happens here
int i = Integer.parseInt(s.trim());
//print out the value after conversion
System.out.println(“int i=”+i);
int i2 = Integer.valueOf(s.trim()) ;

}
catch(NumberFormatException nfe)
{
System.out.println(“NumberFormatException: ” + nfe.getMessage());
}
}
}

66.How do I convert numeric value to String ?
Ans:The String class contains a method named “valueOf()” that can be used,and the numeric(wrapper) classes also contain “toString()” method that can be used for the conversion.

public class ConvertIntToString {

public static void main(String[] args) {
int intToConvert = 50;
//one way of converting from int to String
String convertedValue1 = Integer.toString(intToConvert);
//another way of converting from int to String
String convertedValue2 = String.valueOf(intToConvert);
}
}

67.How do I convert array to Set ?
Ans:To convert an array into a Set first we need to convert the given array into a List.Next with the List we need to create a HashSet passing the List as the constructor argument.
public class ArrayToSet {
public static void main(String[] args) {
Integer[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4};
List list = Arrays.asList(numbers);
Set set = new HashSet(list);

//Display what we get in the set
for(Iterator iterator=set.iterator();iterator.hasNext();)
{
Object o = iterator.next();
System.out.println(o+”,”);
}
}
}

68.How do I know the number of times AB occurred in the input string
ABCBSABDCAAB ?
Ans:
public class PatternMatcher {

private static String REGEX = “AB”;
private static String INPUT = “ABCBSABDCAAB”;

public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT);
int count=0;
while(m.find())
{
count++;
}
System.out.println(REGEX+” occured “+ count+”times”);
}
}

69.How to get individual elements in a String?

Ans:A StringTokenizer is utility class used to break up string.

public class StringTokenizerExample {

public static void main(String[] args) {
/* There are two ways to specify a delimiter for a StringTokenizer object
* 1.At creation time by specifying in the StringTokenizer constructor
* 2.specify it in nextToken()
*/

/* 1. Using StringTokenizer constructor */
StringTokenizer st1 = new StringTokenizer(“Java|StringTokenizer|Example1″,”|”);

//iterate through tokens
while(st1.hasMoreTokens())
{
System.out.println(st1.nextToken());
}

/*Using nextToken().Note that the new delimiter set remains the
default after this method call */
StringTokenizer st2 = new StringTokenizer(“Java|StringTokenizer|Example2”);

//iterate through tokens
while(st2.hasMoreElements())
{
System.out.println(st2.nextToken(“|”));
}
}
}

70.How do I know the number of times the character A occurred in the input string ABCBSABDCAAB ?
Ans:public class FindCharInString {
private static char findChar = ‘A’;
private static String sourceString = “ABCBSABDCAAB”;
public static void main(String[] args) {
char[] strArray = sourceString.toCharArray();
int count = 0;
for(int i=0;i<strArray.length;i++)
{
if(strArray[i]==findChar)
{
count++;
}
}
System.out.println(findChar+” occured “+count+”times”);
}
}

71. How to get GHI element and its position in the String String str=” ABC^DEF^GHI^JKL^MNO “?
Ans:import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringPattern {

private static final String MATCHER = “ABC^DEF^GHI^JKL^MNO”;
private static final String REGEX = “MNO”;

public static void main(String[] args) {

Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(MATCHER);

while(matcher.find())
{
System.out.println(“Position of “+REGEX+” is “+matcher.start());
System.out.println(“String is “+matcher.group());

72.What is ServletRequest?
Ans:Defines an object to provide client request information to a servlet.The servlet container creates a ServletRequest object and passes it as an an argument to the servlet’s service method.A ServletRequest object provides data including parameter names and values , attributes and an input stream.

73.What is a static variable ?
Ans:Static variable is a variable declared with the static modifier , this tells the compiler that there is exactly one copy of this variable in existence , regardless of how many times the class has been instantiated.

74.Difference between static and instance variables ?
Ans:Memory allocation for static variables happens when the class is loaded into memory for first time whereas for instance variables memory allocation happens whenever the class is instantiated.
A static variable is shared among all instances of class whereas a non-static variable also called an instance variable – is specific to a single instance of that class.
Instance variable can be accessed only by the instance methods only.Whereas , Static variables can be accessed by both static and instance methods.

75.What is an Iterator?
Ans:This interface allows you to walk through a collection of objects ,operating on each object in turn.

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

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

78.What happens to the static fields of a class during serialization?
Ans:There are three exceptions in which serialization doesn’t necessarilay read and write to the stream.

1.serialization ignores static fields because they are not part of any State state.
2.Base class fields are only handled if the base class itself is serializable.
3.Transient fields.

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

80.What is a wrapper class ?
Ans:Wrapper classes are classes that allow primitive types to be accessed as objects.

81.What is a marker interface?
Ans:An interface that contains no methods .It is used to mark java classes that support certain capability.

Serializable
Cloneable
SingleThreadModel

82.What are static blocks and instance blocks?
Ans:Static blocks are blocks of code enclosed in braces defined within the body of a class and preceded by using the static keyword . They are executed once when the class is loaded and has a restriction that it can only initialize static data members of the class.They are executed in the order in which they appear textually in the source code.
An instance block is a block of code enclosed in braces defined within the body of a class that is excecuted before the constructor. It is dependent on the object creation and thus the initialization block run each time when the instance of the class is created.It can initialize instance member variables of the class.

83. What is a package?
Ans:Packages are nothing more than the way of organizing files into different directories according to their functionality , usability as well as category they should belong to.

84.What is the difference between jdk and jre?
Ans:Simply put if you need to execute any java program you need JRE as the name says Runtime Environment.
If you need to compile some java code you will need JDK as the name says development kit
One more thing to be noted is JRE will always be shipped with JDK .

Java Runtime Environment contains JVM , class libraries and other supporting files. It does not contain any development tools such as compiler , debugger etc. Actually JVM runs the program and it uses the class libraries , and other supporting files provided in JRE.
Typically each JDK contains JRE along with various development tools like the java source compiler , bundling and deployment tools ,debuggers , profilers , development libraries etc .

85.What is String Literal pool?
Ans:To cut down the number of String objects created in the JVM , the String class keeps a pool of strings. Each time your code creates a string literal , the JVM checks the string literal pool first.If the String already exists in the pool , a reference to the pooled instance returns.If the String doesn’t exist in the pool a new String object gets instantiated , then is placed in the pool.

86.What is a Servlet Container?
Ans:A web server or an application server that provides built in support and facilities for running java servlets. Also called a servlet engine , examples of servlet containers are tomcat , jboss . Today servlet containers also support JSP by converting them to servlets.

87.Difference between static and instance methods ?
Ans:1.Unlike instance methods static methods cannot access instance variables or instance methods directly , they must use an object reference .
2.Unlike instance methods,static methods cannot participate in overriding.
3.Instance methods can be called by the object of a class whereas static method are called by the class.

88.What is the use of final keyword in java?
Ans:final keyword if used with a variable in its declaration then the variable can be initialized for once and its value can never be changed. All final variable should be initialized at the time of declaration.

A class if declared as final cannot be subclassed similarly a method if declared as final cannot be overridden.
Port change in jboss and tomcat ?
In JBoss
C:\Program Files\jboss-4.0.5.GA\server\default\deploy\jbossweb-tomcat55.sar

89.What is the difference between SAX parser and DOM parser?
Ans:Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation.

SAX:

1.Parses node by node.

2.Does not store the XML in memory.

3.We cant insert or delete a node.

4.Top to bottom traversing.
DOM

1.Stores the entire XML document into memory before processing

2.Stores more memory

3.We can insert or delete nodes.

4.traverse in any direction.

If we need to find a node and does not need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

No Comments

Add your review

Your email address will not be published.