Java Interview Questions -29

Java Interview Questions -29

1.Explain different layout manager in Java.

There are following types of layouts are used to organize or to arrange objects:
Border Layout: Have five areas for holding components: north, east, west, south and center.
Flow Layout: Default layout manager, lays out the components from left to right
Card Layout: Different components at different times are laid out, Controlled by a combo box.
Grid Layout: Group of components are laid out I equal size and displays them in certain rows and columns.
Grid Bag Layout: Flexible layout for placing components within a grid of cells.

2.What is the basic difference between the 2 approaches to exception handling.

1> try catch block and 2> specifying the candidate exceptions in the throws clause?

3.What do you understand by JSP actions?

JSP actions are XML tags that forces the server to directly use the server to the existing components or control the behavior of the JSP engine.
JSP actions are executed when a JSP page is requested.
Actions are inserted in the jsp page using XML syntax to control the behavior of the servlet engine.
By using JSP actions, we can reuse bean components, dynamically insert a file and switch the user to another page.
Some of the available actions are as follows:

<jsp: include> – include a file at the time the page is requested.
<jsp: useBean> – find or instantiate a JavaBean.
<jsp: setProperty> – set the property of a JavaBean.
<jsp: getProperty> – insert the property of a JavaBean into the output.
<jsp: forward> – forward the requester to a new page.
<jsp: plugin> – generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.

4.If I write System.exit (0); at the end of the try block, will the finally block still execute?

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

5.How are Observer and Observable used?

Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

6.What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.

7.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.

8.Objects are passed by value or by reference?

Java only supports pass 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 .

9.What is serialization?

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

10.What happens to the static fields of a class during serialization?

There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are 1. Serialization ignores static fields, because they are not part of ay particular state state. 2. Base class fields are only hendled if the base class itself is serializable. 3. Transient fields.

11.What are different types of inner classes?

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

12.Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?

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

13.Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?

No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it’s subpackage.

14.What is the difference between declaring a variable and defining a variable?

In declaration we just mention the type of the variable and it’s name. We do not initialize it. But defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String (“abcd”); Or String s = “abcd”; are both definitions.

15.What is the default value of an object reference declared as an instance variable?

null unless we define it explicitly.

16.Can a top level class be private or protected?

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

17.What type of parameter passing does Java support?

In Java the arguments are always passed by value .

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

Primitive data types are passed by value.

19.That is chained exceptions in java?

When in a program the first exception causes another exception that is termed as Chained Exception. Chained exceptions helps in finding the root cause of the exception that occurs during application’s execution. The constructors that support chained exceptions in Throwable classes are:
Throwable initCause(Throwable)
Throwable(String, Throwable)
Throwable getCause()

20.When is the main thread stop in java?

When we execute the java program, it call the main() method because main() method is the first thread in the program. This main() method or thread invokes the other thread which is required for the complete execution of the program. The main thread should be the last thread in the program to end. so to make main() method to be last we make sure when we called to another function by giving execution control to that must return the control back to the main() method.

21.What are the ways to create child threads?

There are two ways to create java threads:
Implementing the Runnable interface: this overcomes the limitation of inheriting from only one parent class Thread. Using Runnable interface, lays a path to ground work of a class that utilizes threads
Extending Thread class: It inherits the methods and data members, fields from the class tread. In this process only one class can be inherited from the parent class Thread.
The advantage is a class can extend Thread class and also implements the Runnable interface, if required. The Runnable interface is set for implementing a thread and the class that implements the interface performs all the work.

22. What environment variables do I need to set on my machine in order to be able to run Java programs?

CLASSPATH and PATH are the two variables.

23.Can an application have multiple classes having main method?

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

24.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.

25.Why bytecode is important to Java?

The compiled Java source code is known as byte code. We need bytecode due to following reasons:
Is independent of the input language.
Plays an important role in the execution speed of the application.
Can run on any platform irrespective of system architecture.
Can be used for internet applications where security is important
Enable us to load classes which are required for the execution of the application.
allows the web applications to run on various platforms, on various browsers on different infrastructures.

26.When is class garbage collected?

Java uses the garbage collector to free memory which is occupied by those objects which is no more reference by any of the program. An object becomes eligible for Garbage Collection when no live thread can access it. There are many ways to make a class reachable and thus prevent it from being eligible for Garbage Collection:
Objects of that class are still reachable.
Class object representing the class is still reachable.
ClassLoader that loaded the class is still reachable.
Other classes loaded by the ClassLoader are still reachable.
When all of the above are false, then the ClassLoader together with all classes it loaded are eligible for Garbage Collection.

27.What is the difference between a Choice and a List?

The between Choice and list are following:
Choice class presents a pop-up menu of choices whereas List is a collection of different visible item.
Choice is displayed in a compact form, to see the list of available choices we need to scroll down whereas list displays the entire available items.
Choice allows selecting only one items but List supports the selection of one or more List items.
Lists typically allow duplicate elements selection. List allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all.

28.Can you explain Native methods in Java?

The Java native method is used to merge the power of C or C++ programming into Java.
To enhance to high performance language, when efficient native Java compilers are not fully implemented, use of native method boosts the performance to at least the speed of C compiled code.
Java applications can call code written in C, C++, or assembler. This is sometimes done for performance and sometimes to access the underlying host operating system or GUI API using the JNI.

29.Explain class loaders in Java with an example.

The class loader describes the behavior of converting a named class into the bits responsible for implementing that class.
Class loaders eradicate the JREs need to know anything about files and file systems when running Java programs.
A class loader creates a flat name space of class bodies that are referenced by a string name and are written as:
Class r = loadClass(String className, boolean resolveIt);

30.What is Reflection API in Java?

The Reflection API allows Java code to examine classes and objects at run time.
The new reflection classes allow you to call another class’s methods dynamically at run time.
With the reflection classes, you can also examine an instance’s fields and change the fields’ contents.
It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.
The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method, Constructor, Array, and Modifier.
Static class loading vs. dynamic class loading

31.Do I need to import java.lang package any time? Why ?

No. It is by default loaded internally by the JVM.

32.Can I import same package/class twice? Will the JVM load the package twice at runtime?

One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.

33.What are Checked and UnChecked Exception?

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

34.What is Overriding?

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

35.Can we compare String using equality operator (==) operator?

We can compare String using equality operator. But we mostly use equals() method because of following reasons:
The equality operator is used to compare primitives values only where as equals method() should be used to compare objects.
The equality operator can invoke subtle issue while comparing primitive to Object. Where as equals() method is used to perform character based comparison.
equals() return true if two String represent to the same object or when both strings contents are exactly same but equality() perator returns true if two String object represents to same object but return false if two different String object contains same contents

36.What is intern() method in Java?

The intern() method is of String class. The intern() method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.

String str1 = “hello”;
String str2 = “hello”;
String str3 = “hello”.intern();
if ( s1 == s2 ){
System.out.println(“str1 and str2 are same”);
if ( str1 == str3 ){
System.out.println(“str1 and str3 are same” );
We are assuming that str1 and str3 are same will be printed as str3 is interned, and str1 and str2 are same will not be printed. Actual output is: both lines are printed.

37.What is JCA in java?

Java Cryptography Architecture term from Sun for implementing security functions for the Java platform. It provides a platform and gives architecture and APIs for encryption and decryption. JCA is used by the developer to combine the application with the security measure. A programmer uses the JCA to meet the security measure. It helps in performing the third partly security rules. It uses the hash table, encryption message digest, etc to implement the security.

38.What is JPA in java?

The Java Persistence API is enabling us to create the persistence layer for desktop and web applications. Java Persistence deals in following:
Java Persistence API
Query language
Java Persistence Criteria API
Object mapping metadata

39.What is difference between eager and lazy loading?

The difference between eager and loading are:
Eager loading means to load the data before the requirement whereas lazy loading mean that load the data only when required.
Eager loading fetch the data in one query whereas lazy loading fetch the data when needed by triggering the sub query.

40.What is JMS in Java?

Java Message Service (JMS) is used for creating the communication interface between two clients by using the message passing services. This helps the application to interact with other components irrespective of components location whether they rely on same system or connect to the main system through LAN or internet.

41.What is shallow cloning and deep cloning?

Shallow copy: in this object is copied without its contained objects. Shallow clone only copies the top level structure of the object not the lower levels. It is an exact bit copy of all the attributes.
Deep copy: In this object is copied along with the objects it refers to. Deep clone copies all the levels of the object from top to the bottom recursively.

42.What are Class loaders?

Class loader enables the program to load the class at run time. This is located in the java.lang package.
Using Class Loader we can also load the customize classes which is required for the application execution. The class loaders in Java are organized in a tree. When JVM is started three class loaders are used:
Bootstrap class loader: the core java libraries. It is written in native code.
Extensions class loader: loads the code in the extension directories. It is implemented by ExtClassLoader class.
System class loader: code found on the java.class.path which map to the system class path variables. It is implemented by AppClassLoader class. All user classes by default are load by the system class loader.

43.What is the Comparable interface?

The Comparable interface is used to sort collections and arrays of objects using the collections.sort() and java.utils. The objects of the class implementing the Comparable interface can be ordered. All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be negative.
If object1 > object2: The value of i returned will be positive.
If object1 = object2: The value of i returned will be zero.
What is Single Threaded Model in Servlets?
Single Thread Model is a marker interface which contains no methods and variable in it.
When using Single thread model with Servlet, it make sure that that only one thread can be executed at a time. It avoids running of two or more thead simultaneously.
If we wants to make single threaded we can implement this interface in the following fashion.
public class SingleThreadedTest implements SingleThreadModel
//some code

44.What are the different Authentication Options available in Servets?

Authentication options available in Servlets: There are four different options for authentication in servlet:
1. Basic Authentication: Username and password provided by the client to authenticate the user.
2. Form-based authentication- In this the login form is made by the programmer by using HTML.
3. Digest Authentication- It is similar to basic authentication but in this the passwords are encrypted using Hash formula. This makes digest more secured.
4. Client certificate Authentication- It requires that each client accessing the resource has a certificate that it send to authenticate itself. This requires SSL protocol.

45.What is the disadvantage of garbage collector?

Garbage Collector runs in its own thread which affects the performance of the system. It increases the workload of JVM because it constantly monitor the object which is not referenced.. The two main disadvantages of garbage collector are:
TIME: to collect all those no referenced object JVM spends a considerable amount of time by scanning the entire heap.
Mark and sweep: some time it is difficult to implement mark and sweep in the application.

46.Does java support global variable?

No, java does not support global variable because of the following reasons:
Globally accessible: global variables are globally accessible.
Referential transparency:global variable breaks the referential transparency and also a global variable generate problem in the namespace.
Object oriented: As JAVA is object oriented language so where each variable is declared inside the class. To use this variable, object should be initialized.

47.How do I serialize an object to a file?

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

48.Which methods of Serializable interface should I implement?

The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.

49.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.

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

It is empty. But not null.

51.How can one prove that the array is not null but empty using one line of code?

Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.

52.What is an Iterator and explain traversing through a collector using Iterator?

We can access each element in the Collection by using Iterators irrespective of how they are organized in the collector. Iterator can be implemented a different way for every Collection. To use an iterator to traverse through the contents of a collection we do:
Obtain an iterator by calling the collections iterator() method to the start of the collection.
Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext()returns true.
Within the loop, obtain each element by calling next().
remove() method is used to remove the current element in the iteration.

53.What is Race condition?

Race Condition: it is the situation when two threads raise the request for the same resource allocation, but the manner in which resources are allocated are significant, is called race conditions.
Race condition is created in program in order to run the parallel execution of program by using multiple threads in a same period.
A race condition occurs when two threads operate on same object without proper synchronization and there operation interleaves on each other.
The risk of Race condition is higher in Java.

54.How can I customize the seralization process? i.e. how can one have a control over the serialization process?

Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

55.What is the common usage of serialization?

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

56.What if I write static public void instead of public static void?

Program compiles and runs properly.

57.What if I do not provide the String array as the argument to the method?

Program compiles but throws a runtime error “NoSuchMethodError”.

58.What is difference between Java and JavaScript?

The difference between java and java scripts are:
Java is an Object Oriented Programming Language and capable of running on multiple operating systems with the help of interpreter whereas Java Script is the object oriented scripting language and it is embedded in HTML and runs directly on the browser.
JVM is used to executed java program on different program whereas Java Script code is not compiled they are directly run on the browser.
Java language is used to develop the software whereas java script is used providing interactivity to the simple HTML pages.

59.What is Externalizable interface?

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

60.When you serialize an object, what happens to the object references included in the object?

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

61.What one should take care of while serializing the object?

One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.

62.What is the difference between factory and abstract factory pattern?

The differences between factory and abstract factory are following:
Factory pattern is a single method but abstract factory is an object.
The Abstract Factory pattern is one level of abstraction higher than the factory pattern.
Factory pattern generally returns the common parent class or method whereas the abstract factory pattern returns the one of the several factories.

63.What is static in java?

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

64.What is final?

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

65.What is Singleton?

Singleton in Java is a class with just one instance in whole Java application.

This make sure that only one instance of a class is created.
getInstance() method is used to get single instance of the class.
It creates a global point to access all object

66.What is the difference between JAR and WAR files?

The differences between JAR and WAR files are:
JAR files (Java Archive) allows combining many files into one whereas WAR files (Web Application Archive) stores XML, java classes, and JavaServer pages for Web Application purposes.
JAR is used to hold Java classes in a library whereas in WAR files are stored in lib directory of the application.
In this EJB module which contains enterprise java beans class files and EJB deployment descriptor are packed as JAR files with .jar extension whereas in WAR web modules which contains Servlet class files, JSP Files, GIF and HTML files are packaged as JAR file with .war extension.

67. What is an Iterator?

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

68.State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.

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

69.What is an abstract class?

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

70.What if the main method is declared as private?

The program compiles properly but at runtime it will give “Main method not public.” message.

71.What if the static modifier is removed from the signature of the main method?

Program compiles. But at runtime throws an error “NoSuchMethodError”.

72.What is the purpose of the File class?

The File class provides access to the files and directories of a local file system.
The static class loading is done through the new operator.
Dynamic class loading is achieved through Run time type identification. Also called as reflection
This is done with the help of the following methods:
getClass(); getName(); getDeclaredFields();
Instance can also be created using forName() method. It loads the class into the current class memory.

73.Can you explain shallow cloning and deep cloning?

Cloning of objects can be very useful if you use the prototype pattern or if you want to store an internal copy of an object inside an aggregation class for example.
Deep cloning – You clone the object and their constituent parts.
It should be used when it is inappropriate to separate the parts; the object is formed of, from it.
Shallow cloning – You clone only the object, not their parts. You add references to their parts.
It should be used when it is adequate to have the references added to the cloned object

74.Explain the purpose of Comparator Interface.

Comparators can be used to control the order of certain data structures and collection of objects too.
The interface can be found in java.util.Comparator
A Comparator must define a compare function which takes two Objects and returns a -1, 0, or 1
Sorting can be done implicitly by using data structures of by implementing sort methods explicitly.

75.What is the impact of private constructor?

Private Constructors can’t be access from any derived classes neither from another class.
So you have to provide a public function that calls the private constructor if the object has not been initialized, or you have to return an instance to the object, if it was initialized.
This can be useful for objects that can’t be instantiated.

76.Can you explain static Initializers in Java?

A static initializer block resembles a method with no name, no arguments, and no return type. There is no need to refer to it from outside the class definition.

The code in a static initializer block is executed by the virtual machine when the class is loaded.
Because it is executed automatically when the class is loaded, parameters don’t make any sense, so a static initializer block doesn’t have an argument list.

77.Define Externalizable Interface and explain its purpose.

The Externizable interface extends the serializable interface.
When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process.
When you use Externalizable interface, you have a complete control over your class’s serialization process. The two methods to be implemented are : void readExternal(ObjectInput)
The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.
void writeExternal(ObjectOutput)
The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays. < /LI> < /UL>

77.Explain java beans and what are its advantages.

It is a software component which can be used on variety of environment
Advantages of beans are:
Beans are written only once and can be used many times
Configuration setting of beans can be saved in persistant storage
We can control the exposure of properties methods and events of beans
It can send and receive events from another objects
We can easily configure beans using auxiliary software and it is not included in run time environment
It may or may not be visible to another user.

78.In Java, what are the basic differences between an Interface and an Abstract class?

Only a interface can extend a interface but any class can extend abstract class
All the variables in interface are set as final by default
Interface execution is slow as compared to abstract class
Abstract scope is only upto the derived class and scope of Interface is upto any level
Abstract class can implement method but interface cannot because a interface contains only the signature of a method but not the body of a method
In a class we can implement many interfaces but only one abstract class

79.Explain connection pooling in java

In connection pooling several context instances have been created for the same database.
As application server starts a pool of connection object has been created
These objects are managed by pool manager
Pool manager provides context instance as the request comes and when the context instance is done with connection, it is retured in the pool for future use
The class is use to provide connections available to calling program in its getConnection method. This method searches for a connection and if not available then a new connection is created.

80.Explain difference between get and post method.

Visibility – GET request is sent via the URL string which is visible whereas POST request cant be seen as it is encapsulated in the body of the HTTP request
Length – there is limitation of length for GET request as it goes through URL and its character length cant be more than 255 but in POST request no such limitation.
Performance –As no time is spend on encapsulation in GET request so it is comparatively faster and relatively simpler. In addition, the maximum length restriction facilitates better optimization of GET implementation.
Type of Data – GET request can carry only text data as we know URL only contain text data on the other hand post request can carry both text as well as binary
Caching/Bookmarking – as we know now that GET request is nothing but a URL hence it can be cached as well as bookmarked. No such options are available with a POST request.
FORM Default – GET is the default method of the HTML FORM element. To submit a FORM using POST method, we need to specify the method attribute and give it the value “POST”.
Data Set – GET requests are restricted to use ASCII characters only whereas no such restrictions are in POST requests

81.What are the ways in which a thread can enter the waiting state?

A thread can enter the waiting state by:
By sleep() method invocation
By blocking its input and output
By invoking an object’s wait() method.
It can also enter the waiting state by invoking its suspend() method.

82.ive a brief description of RMI

RMI(remote method innovation) allows a java object to be executed on another machine.
It helps in building distributed applications
RMI uses object serialization to marshal and unmarshal objects
RMI mechanism is basically a object oriented RPC mechanism
To deal with client communication Code skeleton is used at skeleton end
small example of RMI which returns the various information about European (EU)countries
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface EUStats extends Remote {
String getMainLanguages(String CountryName)
throws RemoteException;
int getPopulation(String CountryName)
throws RemoteException;
String getCapitalName(String CountryName)
throws RemoteException;

83.How does an exception permeate through the code?

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

84.What are the different ways to handle exceptions?

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

85.Explain daemon thread in Java and which method is used to create the daemon thread?

Deamon thread runs in the back ground doing the garbage collection operation for the java runtime system.
It has the low priority
These threads run without the involvement of the user.
We can use the accessor method isDaemon() to determine if a thread is a daemon thread.
Daemon threads exist only to serve user threads.
The setDaemon() method is used to create a daemon thread

86.Define reflection in java

It allows you to analyze a software component like java beans
It helps in describing software component capability dynamically, at run time rather than at compile time
This is provided by java.lang.reflect package which includes several interfaces
Various classes in this package and their functions are:
AccessibleObject : Allows you to bypass the default access control checks.
Array : Allows you to dynamically create and manipulate arrays.
Constructor : Provides information about a constructor.
Field : Provides information about a field.
Method : Provides information about a method.
Modifier : Provides information about class and member access modifiers.
Proxy : Supports dynamic proxy classes.
ReflectPermission : Allows reflection of private or protected members of a class.

87.When should you use which approach?

In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it’s own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

88.If I write return at the end of the try block, will the finally block still execute?

Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

89.Which is better from Extending Thread class and implementing Runnable Interface?

• Implementing runnable interface is more advantageous because when you are going for multiple inheritance, then only interface can help.
• If you are already inheriting a different class, then you have to go for Runnable Interface. Otherwise you can extend Thread class.
• Also, if you are implementing interface, it means you have to implement all methods in the interface.
• If we implement runnable interface it will provide better object oriented design
• Implementing also gives consistency
• By using runnable interface we can run the class several times whereas thread have start() method that can be called only once.

90.Is it necessary that each try block must be followed by a catch block?

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

91. Explain different way of using thread?

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

92. What are pass by reference and passby value?

Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

93. What is the purpose of garbage collection in Java, and when is it used?

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

94. Describe synchronization in respect to multithreading.

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

95. Explain different way of using thread?

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

96. What are pass by reference and passby value?

Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

97. What is HashMap and Map?

Map is Interface and Hashmap is class that implements that.

98. What is HashMap and Map?

Map is Interface and Hashmap is class that implements that.

99. Difference between HashMap and HashTable?

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

100. Difference between Vector and ArrayList?

Vector is synchronized whereas arraylist is not.

101. Difference between Swing and Awt?

AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.

102. What is the difference between a constructor and a method?

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

103. What is an Iterator?

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

104. What is the difference between an Interface and an Abstract class?

An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

105. What is the purpose of garbage collection in Java, and when is it used?

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

106. Describe synchronization in respect to multithreading.

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

107.what is the difference between applet and application?

The differences between an Applet and an application are as follows:
Applets can be embedded in HTML pages and downloaded over the Internet whereas Applications have no special support in HTML for embedding or downloading.
Application starts execution with its main method whereas applet starts execution with its init method.
Application must be run on local machine whereas applet needs no explicit installation on local machine.
Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser.
Application can run with or without graphical user interface whereas applet must run within a graphical user interface.

Also Read:



This site uses Akismet to reduce spam. Learn how your comment data is processed.