Interview questions
What is the Java Collection framework? List down its
advantages ?
·
Collection is an
object that contains a group of objects within it.
·
Collection in Java is a framework that provides architecture to store and
manipulate the group of objects
·
Java is API Document.
What is a
framework in Java?
·
It provides readymade
architecture.
·
It represents a set of
classes and interfaces.
What are
advantages of Java Collection framework?
·
Reduced programming effort due to ready to use
code
·
Increased performance
because of high-performance implementations of data structures and algorithms
·
Provides interoperability
between unrelated APIs by establishing a common language to pass collections back
and forth
·
Easy to learn APIs by
learning only some top level interfaces and supported operations
Java assertion interview questions
what is Assertion?
·
Assertion is a statement in
java. It can be used to test your assumptions about the program.
·
Java is the high-level,
object-oriented programming language.
·
Java is API Document.
Syntax:
assert expression;
or
assert expression1 : expression2;
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.
Is Iterator a Class or Interface? What is its use?
Answer: Iterator is an interface which is used to step through the elements of a Collection.
What is similarities/difference between an Abstract class and Interface?
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.
A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
abstract class testAbstractClass {
protected String myString;
public String getMyString() {
return myString;
}
public abstract string anyAbstractFunction();
}
Emaple of Interface:
public interface sampleInterface {
public void functionOne();
public long CONSTANT_ONE = 1000;
}
c:\>java com.xyz.hr.Employee
There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().
A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you can mark that field transient or static.
The Window, Frame and Dialog classes use a border layout as their default layout.
Java is an object-oriented programming language developed initially by James Gosling and colleagues at Sun Microsystems. The language, initially called Oak (named after the oak trees outside Gosling's office), was intended to replace C++, although the feature set better resembles that of Objective C. Java should not be confused with JavaScript, which shares only the name and a similar C-like syntax. Sun Microsystems currently maintains and updates Java regularly.
A well-written OO program exhibits recurring structures that promote abstraction, flexibility, modularity and elegance.
Yes, all functions in Java are virtual by default. This is actually a pseudo trick question because the word "virtual" is not part of the naming convention in Java (as it is in C++, C-sharp and VB.NET), so this would be a foreign concept for someone who has only coded in Java. Virtual functions or virtual methods are functions or methods that will be redefined in derived classes.
If Jack made a clone of the map, any changes to the clone or the original map would be seen on both maps, because the clone of Map is a shallow copy. So Jack made a wrong decision.
What is NullPointerException and how to handle it?
--Calling the instance method of a null object.
--Accessing or modifying the field of a null object.
--Taking the length of a null as if it were an array.
--Accessing or modifying the slots of null as if it were an array.
--Throwing null as if it were a Throwable value.
The NullPointerException is a runtime exception. The best practice is to catch such exception even if it is not required by language design.
One option is to use a static block to load a library before anything is called. For example,
class Test {
static {
System.loadLibrary("path-to-library-file");
}
....
}
When you call new Test(), the static block will be called first before any initialization happens. Note that the static block position may matter.
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);
Containers which uses Border Layout as their default are: window, Frame and Dialog classes.
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.
}
}
Synchronized methods are methods that are used to control access to a method or an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
The preferred size of a component is the minimum component size that will allow the component to display normally.
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.
Multi-threading means various threads that run in a system.
The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.
The high-level thread states are ready, running, waiting, and dead.
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.
A process can contain multiple threads. In most multithreading operating systems, a process gets its own memory address space; a thread doesn't. Threads typically share the heap belonging to their parent process. For instance, a JVM runs in a single process in the host O/S. Threads in the JVM share the heap belonging to that process; that's why several threads may access the same object. Typically, even though they share a common heap, threads have their own stack space. This is how one thread's invocation of a method is kept separate from another's. This is all a gross oversimplification, but it's accurate enough at a high level. Lots of details differ between operating systems. Process vs. Thread A program vs. similar to a sequential program an run on its own vs. Cannot run on its own Unit of allocation vs. Unit of execution Have its own memory space vs. Share with others Each process has one or more threads vs. Each thread belongs to one process Expensive, need to context switch vs. Cheap, can use process memory and may not need to context switch More secure. One process cannot corrupt another process vs. Less secure. A thread can write the memory used by another thread
A single ampersand here would lead to a NullPointerException.
The Iterator interface is used to step through the elements of a Collection.
No, it doesn't. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.
The Canvas, Frame, Panel, and Applet classes support painting.
This method is used to ensure that Swing components are updated through the event-dispatching thread.
This question is not asked to test your memory. It tests you how well you know Java. Ten in total.
clone()
equals() & hashcode()
getClass()
finalize()
wait() & notify()
toString()
It uses low order bytes of the result that can fit into the size of the type allowed by the operation.
If a binary bitwise operator has one long operand, the other operand is converted to a long value.
The type of the result of a bitwise operation is the type to which the operands have been promoted. For example:
short a = 5;
byte b = 10;
long c = 15;
The type of the result of (a+b) is int, not short or byte. The type of the result of (a+c) or (b+c) is long.
Yes. Because Java is implemented using a platform-independent virtual machine, bitwise operations always yield the same result, even when run on machines that use radically different CPUs.
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. 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. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.
The SimpleTimeZone class provides support for a Gregorian calendar.
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
The purpose of the Runtime class is to provide access to the Java runtime system.
The purpose of the System class is to provide access to system resources.
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
An abstract method is a method whose implementation is deferred to a subclass. Or, a method that has no implementation.
interface contains methods that must be abstract; abstract class may contain concrete methods. interface contains variables that must be static and final; abstract class may contain non-final and final variables. members in an interface are public by default, abstract class may contain non-public members. interface is used to "implements"; whereas abstract class is used to "extends". interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance. interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces. interface is absolutely abstract; abstract class can be invoked if a main() exists. interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces. If given a choice, use interface instead of abstract class.
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.
A protected method is a method that can be accessed by any method in its package and inherited by any subclass of its class.
An object reference can be cast to an interface reference when the object implements the referenced interface.
javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.
The peerless components are called light weight components.
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object
The throws keyword is a modifier of a method that designates that exceptions may come out of the method, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.
The primitive types are byte, char, short, int, long, float, double, and Boolean.
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).
One can not do anything in this scenario. Because Java does not allow multiple inheritance and does not provide any exception interface as well.
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.
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 handle those exceptions.
2. specifying the candidate exceptions in the throws clause?
In the first approach as a programmer of the method, you yourself 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.
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.
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.
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.
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
A thread is in the ready state after it has been created and started.
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement 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 body of a loop at least once.
This() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.
An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members.
It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial.
While making a JDBC connection we go through the following steps :
Step 1 : Register the database driver by using :
Class.forName(\" driver classs for that specific database\" );
Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\"select * from TABLE NAME\");
Step 4 : Exceute the query :
stmt.exceuteUpdate();
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.
An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
Only public and abstract modifiers are allowed for methods in interfaces.
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work out is a static field in the java.lang.System class.
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
Yes, a .java file contain more than one java classes, provided at the most one of them is a public class.
No, delete is not a keyword in Java. Java does not make use of explicit destructors the way C++ does.
No. To exit a program explicitly you use exit method in System object.
The scope of a Java variable is determined by the context in which the variable is declared. Thus a java variable can have one of the three scopes at any given point in time.
1. Instance : - These are typical object level variables, they are initialized to default values at the time of creation of object, and remain accessible as long as the object accessible.
2. Local : - These are the variables that are defined within a method. They remain accessible only during the course of method execution. When the method finishes execution, these variables fall out of scope.
3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance.
The local variables are not initialized to any default value, neither primitives nor object references. If you try to use these variables without initializing them explicitly, the java compiler will not compile the code. It will complain about the local variable not being initialized..
c1 = new MyClass ();
c3 = new MyClass ();
Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.
No the source file name, if it contains a public class, must be the same as the public class name itself with a .java extension.
Yes, the main method can be declared final, in addition to being public static.
It will print 13.
very usefull
ReplyDeletethank you sir its really useful;
ReplyDeleteplease give me suggestions to improve this blog
DeleteThanks for sharing this nice Java Interview Questions .
ReplyDelete