What is the difference between C++ and Java?
|C++ supports Enums, Structures or Unions as well as classes.||Java does not support Enums, structures or unions but it supports classes.|
|C++ supports pointers. ||Java does not support pointers.|
|C++ supports header files.||Java does not support header files.|
|C++ supports multiple inheritance or operator overloading. ||Java does not support multiple inheritance or operator overloading.|
|The scope resolution operator (::) is used in C++.||The scope resolution operator (::) is not used in Java.|
|C++ provide template classes.||Java does not support template classes.|
|Global data and functions are allowed in C++.||Global data and functions are not allowed in Java.|
What is the difference between a break statement and a continue statement?
|Break statement||Continue statement|
|A break statement discontinues the execution of the loop.||Continue statement skips the loop and re-executes loop with new condition.|
|Break statement is used in loop as well as in a switch statement.||Continue statement is used in loop control statement like for,while,do-while.|
Explain the difference between static and dynamic class loading?
|Static loading||Class loading|
|The static class loading is done through the 'new' keyword.||Dynamic class loading is done through run time identification.|
|In static loading the retrieval of class definition and instantiation of the object is done at compile time.||The dynamic class loading is not known at the compile time.|
|Methods used for static loading are|
|Methods used for dynamic loading are|
Explain the impact of private constructor?
- Private class constructor cannot be accessed in derived class or any other class.
- A private constructor in a class creates its objects within the class and does not allow to objects to be created outside the class.
- It must provide a public function that calls the private constructor if the object has not been initialized or return an instance to the object if it is initialized.
What are static initiators?
- A static initializer block resembles a method with no name, no argument and no return type.
- There is no need to refer it from outside the class definition.
- The code in static initializer block is executed by virtual machine when the class is loaded.
- When the class is loaded it executed automatically and the static initializer block does not have an argument list.
What is thread? What are the advantages we derived by programming with thread?
- A thread is a fork of a computer program into two or more concurrently running task.
- A thread is an independent path of execution in a program.
- Thread with a higher priority is executed first.
- Allows multiple programs to be executed concurrently.
- The cost of thread is low compared to processes in terms of space and communication.
- Threads are lightweight.
What is polymorphism?
Features of polymorphism:
- The polymorphism can be referred to as one name many forms.
- It is the ability of methods to behave differently, depending upon the object who is calling it.
- It allows one interface for multiple implementation.
- It supports the method overloading in this multiple methods with same name but different formal argument.
- It also supports method overriding it means multiple methods have the same name, same return type and same formal argument list.
Explain the difference between Overloading and Overriding.
|Overloading is also called static/early binding polymorphism.||Overriding is also called dynamic/late binding polymorphism.|
|It happens at compile time.||It happens at runtime.|
|It adds or extend more to the method functionality.||It changes the existing functionality of the method.|
|Methods have different parameter lists or type or the return type.||Methods have the same signature as the parent class method.|
|Static binding happens in overloading.||Dynamic binding happens in overriding.|
What are daemon thread?
- The threads that work in the background to support the runtime environment are called daemon thread.
- For example: Garbage collection threads. When the remaining thread in a process are the daemon thread then the interpreter exits. This makes sense because when only daemon threads remain, there are no other threads for which a daemon thread can provide a service.
- You cannot create a daemon method but you can use, public final void setDaemon(boolean is Daemon) method to run it into one.
What is multithreaded program? What is the importance of thread synchronization?
Importance of thread synchronization:
- Executing more than one thread parallel by using a processor is called multithreading.
- A multithreaded program involves multiple threads of control in a single program.
- Each thread has its own stack.
- Other resources of the process are shared by all threads and while trying to access them it should be synchronized.
- Avoids issues like deadlocks and starvation.
- Can be used for debugging multi threaded programs.
Does garbage collection guarantee that a program will not run out of memory?
- Garbage collection does not guarantee that a program will not run out of memory.
- The garbage collection is dependent on the JVM.
- Garbage collection cannot be predicted if it will happen or not.
- Hence it is possible for the resources to be used faster than they are garbage collected.
What is synchronization and why is it important?
- The access of sharing resources by multiple threads, in which only one thread can access a designated resource at a time, is known as synchronization.
- Synchronization prevents data corruption which may lead to dirty reads and other significant errors.
- Synchronization avoids memory consistence errors caused due to inconsistent view of shared memory.
- When a method is declared as synchronized then the thread holds the monitor for that method's object.
- If another thread is executing the synchronized method, your thread is blocked until that thread releases the monitor.
What are synchronized methods and synchronized statements?Synchronized methods:Synchronized Statement:
A synchronized Statement can only be executed once the thread has obtained a lock for the object or the class that has been referred to in the statement.
public void run()
//synchronize statement. P1 here is an object of some class P
What is serialization?
Uses of serialization:
- Serialization is an operation in which an object’s internal state is converted into a stream of bytes.
- This stream is then written to the disk.
- This stream can also be sent over a socket.
- Serialization is a very compact and accurate method for any object to be serialized.
- It must be an instance of a class that implements either the Serializable or Externalizable interface.
- Helps to persist data for future use.
- To exchange data between servlets and applets.
- To store users session.
What is JAR file?
- JAR is a Java Archived file which allows many files to be stored.
- All applets and classes can be stored in a JAR file thereby reducing the size.
- JAR files can be created using the JAR command that comes with JDK.
- This JAR file can also be digitally signed, then JAR file itself is not signed but, all the files inside it are signed.
What is JVM?
- JVM is the acronym stands for 'Java Virtual Machine'.
- It provides the execution environment.
- JVM is not platform independent.
- It is the Java run-time system.
- It is an interpreter of bytecode.
- JVM also makes the system secured.
What is bytecode?
- Bytecode is an instruction set.
- Bytecode extends with .class.
- 'javac' compiler translates the .java file into .class.
- JVM interpretes bytecode.
- Bytecode facility makes Java platform-independent.
- It also confirms security to the Java code.
Explain semaphore and monitors in java threading.
- A semaphore is a flag variable used to check whether a resource is currently being used by another thread or process.
- The drawback of semaphores is that there is no control or guarantee of proper usage.
- A Monitor defines a lock and condition variables for managing concurrent access to shared data.
- The monitor uses the lock to ensure that only a single thread is active in the monitor code at any time.
- A semaphore is a generalization of a monitor. A monitor allows only one thread to lock an object at once.
What is the difference between yielding and sleeping?
|Yield will cause the thread to rejoin the queue. ||Sleep holds the threads execution for the specified time. |
|When a task is invoked in sleeping, it returns to the waiting state.||When a task is invoked in yielding, it returns to the ready state.|
What is resource bundle?
- The place where an application stores its locale-specific data (isolated from source code).
- Internationalization is utilized by resource bundle in a Java application by making the code independent of locale.
- When program needs a local specific resource then the program can load it from the resource bundle that is appropriate for the current user's locale.
What are different types of inner classes?
- Local classes are like local variables, specific to a block of code.
- Their visibility is only within the block of their declaration.
- Member inner classes are just like other member methods and member variables and access of the member class is restricted, just like methods and variables.
- Anonymous classes have no name, you cannot even provide a constructor.
What is JNI?
- JNI is Java Native Interface.
- It is a framework that allows the Java code running in the Java Virtual Machine to interact and communicate with other applications and libraries written in some other languages.
- JNI is typically used when an application cannot be entirely written in Java.
- JNI can be invoked only by signed applets and applications.
What is meant by Stream Tokenizer?
- The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time.
- The parsing process is controlled by a table and a number of flags that can be set to various states.
- The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles.
What is JAVAdoc utility?
- Javadoc utility enables you to keep the code and the documentation in sync easily.
- The javadoc utility lets you put your comments right next to your code, inside your ".java" source files.
- All you need to do after completing your code is to run the Javadoc utility to create your HTML documentation automatically.
What are class loaders?
- 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 asClass r = loadClass(String className, boolean resolveIt);
What is 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.
Define the purpose of Externalizable Interface?
The two methods to be implemented are:
1. void readExternal(ObjectInput)
- The Externizable interface extends the serializable interface.
- The class is serialized automatically by default when you use the serialized interface. 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 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.
2. 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.
What are transient and volatile modifiers?Transient
- Volatile is a access modifier that informs to the compiler that the variable with this modifier can be changed unexpectedly by other elements of the program.
- When serializable interface is declared, the compiler knows that the object has to be handled so as to be able to serialize it.
- If variable declare in an object as transient, then it doesn’t get serialized.
- Specifying a variable as volatile tells the JVM that any threads using that variable are not allowed to cache that value at all.
- Volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
What are Checked and UnChecked Exception?
- The java.lang.Throwable class has two subclasses Error and Exception.
- There are two types of exceptions non runtime exceptions and runtime exceptions.
- Non runtime exceptions and its subclasses are called checked exceptions and the runtime exceptions and its subclasses are called unchecked exceptions.
- Runtime Exceptions occur when the code is not robust and non runtime exceptions occur due to the problems is environment, settings, etc.
How does thread synchronization occur inside a monitor?
- A thread is already acting in an object for preventing any other thread from acting on the same object is called as thread synchronization.
- A Monitor defines a lock and condition variables for managing concurrent access to shared data.
- The monitor uses the lock to ensure that only a single thread is active in the monitor code at any time.
- A monitor allows only one thread to lock an object at once.
- Synchronized object is like a locked object. A thread locks the object after entering it and the next thread cannot enter it till the first thread comes out.
- It means that object is locked mutually on thread and the objects are called 'Mutually Exckusive lock' (mutex) shows in figure.
How are this() and super() used with constructors?this() Constructors:
- It is used to pointing the current class instance.
- It can be used with variables or methods.
- It is used to call constructor of the same class.
- Private variable cannot be accessed using this().
- It is used to call constructor of parent class.
- It must be the first statement in the body of constructor.
- Using this constructor we can access the private variables in the super class.
What is an immutable object?
An immutable object is an object that cannot be changed once it is created.
Steps involved in the creation of object are:
- All of data fields should be kept private.
- Methods which can perform the change in any of data field after the construction of the object must be avoided.
What are the List interface and its main implementation?
The List helps in collections of objects. Lists may contain duplicate elements.
The main implementations of the List interface are as follows:
Resizable-array implementation of the List interface.
Synchronized resizable-array implementation of the List.
Doubly-linked list implementation of the List interface. Better performance than the ArrayList implementation when elements are inserted or deleted timely.
What is an Applet?
- Applets are the small java programs.
- They can be sent from one computer to another computer over the internet using the Applet viewer that supports java.
- Applets can run in a web browser as it is a java program.
- It is a fully functional java application because it has the entire java API at its disposal.
- It follows the security rules given by the web browser.
- Applet security is also known as sandbox security.
What is a HashSet and TreeSet?HashSet:
- The HashSet is an unsorted, unordered set.
- It is collection set that restrict duplicate elements and also repositioning of elements.
- It implements the set interface and extends AbstractSet.
- It uses hash code of the object being inserted.
- The TreeSet is a set implemented when we want a element in the sorted order.
- Sorting of element is done according to the natural order of elements or with the help of comparator provided at creation time.
What are the difference between throw and throws?
|Throw is used to trigger an exception.||Throws is used in the declaration of exception.|
|Throw is used inside the method.||Throws is used with the method signature.|
|Throw is followed by an instance. ||Throws is followed by class.|
Explain Java Thread Life cycle.
A Java thread can be in one of the following states:
- The life cycle of threads in Java is very similar to the life cycle of processes running in an operating system.
- During the life cycle of thread, it moves from one state to another depending on the operation performed by it or performed on it.
2. RUNNABLE (ready_running)
- A thread is just instantiated in new state.
- When a start () method is invoked, the thread moves to the ready state from which it is automatically moved to runnable state by the thread scheduler.
- A thread executing in the JVM is in running state.
- In this state a thread is blocked and waiting for a monitor lock.
- This occurs when a thread performs an I/O operation and moves to next (runnable) state.
5. TIMED_WAITING (sleeping)
- In this state a thread is waiting indefinitely for another thread to perform a particular action.
6. TERMINATED (dead)
- In this state a thread is waiting for another thread to perform an action up to the specified waiting time.
- In this state a thread is exited.
What is the difference between final, finally and finalize()?final:
- It is a modifier which can be applied to a class, method or variable.
- It is not possible to inherit the final class, override the final method and change the final variable.
- It is an exception handling code section.
- It gets executed whether an exception is raised or not by the try block code segment.
- finalize is a method of Object class.
- It is executed by the JVM just before the garbage collecting object gives a final chance for resource releasing activity.
What is order of precedence and associativity? What is the use of this() and super()?Order of precedence
It determines the order in which the operators in an expression should be evaluated.
It determines whether an expression should be evaluated left-to-right or right-to-left.
use of this() and super()
It is used to refer to another constructor in the same class with a different parameter list.
It is used to invoke the superclass constructor.
What are the types of statements in JDBC?
JDBC API has 3 Interfaces and their key features are as follows
- Statement is used to run simple SQL statements like select and update.
- It interfaces use for general-purpose access to your database.
- It is useful when you are using static SQL statements at runtime.
- This interface cannot accept parameters.
- A SQL statement is pre-compiled and stored in a PreparedStatement object.
- It is used to run Pre compiled SQL and then the object can be used to efficiently execute this statement multiple times.
- The object of Prepared Statement class can be created usingConnection.prepareStatement() method.
- This interface is used to execute the stored procedures and it extends Prepared Statement interface.
- The object of Callable Statement class can be created using Connection.prepareCall() method.
Explain basic steps in writing a Java program using JDBC.
JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access database:
- Load the RDBMS specific JDBC driver because this driver actually communicates with the database.
- Open the connection to database, for sending SQL statements and get results back.
- Create JDBC Statement object containing SQL query.
- Execute statement returns result set. ResultSet contains the tuples of database table as a result of SQL query.
- Process the result set.
- Close the connection.
Discuss the significances of JDBC.The significances of JDBC are given below:
- JDBC stands for Java Database Connectivity.
- Java Database Connectivity (JDBC) is a standard Java API.
- Its purpose is to interact with the relational databases in Java.
- JDBC is having a set of classes and interfaces which can be used from any Java application.
- It interacts with a database without the applications of RDBMS by using the database specific JDBC drivers.
Describe how the JDBC application works.A JDBC application divided into two layers:
1. Driver layer
2. Application layer
- The Driver layer consists of DriverManager class and the JDBC drivers.
- The Application layer begins after putting a request to the DriverManager for the connection.
- An appropriate driver is chosen and used for establishing the connection.
- This connection is linked to the application layer.
- The application needs the connection for creating the Statement kind of objects by which the results are obtained.
Explain the purpose of Event Object.
What is an ActionEvent?
- The EventObject represents the events.
- The super class of all event classes is java.util.EventObject.
Syntax: public EventObject(Object source)
public Object getSource(): Returns the object on which the event initially occurred.
public String toString(): Returns a String representation of this EventObject.
public int getID(): Returns the Integer value corresponding to the type of event.
- An action event is a semantic event which indicates that a component defined action occurred.
- The ActionListener interface gets this ActionEvent when the event occurs.
- Event like Button pressed is an action event.
- It is defined in 'java.awt.event' package.
- This event is generated when the button is clicked or the item of a list is double clicked.Declaration syntax of ActionEvent: public class ActionEvent extends AWTEvent
Explain the different kinds of event listeners.The different kinds of event listeners are:
|Event listener interface||Description|
|WindowEvent||This interface is used for receiving the window events.|
|ActionEvent||This interface is used for receiving the action events.|
|ComponentEvent||This interface is used for receiving the component events.|
|ContainerEvent||This interface is used for receiving the container events.|
|FocusEvent||This interface is used for receiving the focus events.|
|ItemEvent||This interface is used for receiving the item events.|
|KeyEvent||This interface is used for receiving the key events.|
|MouseEvent||This interface is used for receiving the mouse events.|
|TextEvent||This interface is used for receiving the text events.|
|AdjustmentEvent||This interface is used for receiving the adjustment events.|
What is event adapter class? When should we use an event adapter class?
Advantages of the Adapter class
- Event adapter class is a pattern which provides default implementation of interface or abstract class.
- It provides the default implementation of all the methods in an event listener interface.
- Usually adapter classes ease the programmers by providing the implementations of the listener interfaces instead of having to implement them. This is where the event adapter class comes into picture.
- These classes are useful when you want to process only few of the events that are handled by a particular event listener interface.
- Using adapters it helps to reduce the clutter in your code.
- It increases the transparency of classes.
- It makes a class highly reusable.
- It provides a pluggable kit for developing application.
- It provides a way to include related patterns in a class.
What is the difference between the paint() and repaint() methods?
|The paint() method is called when some action is performed on the window.||A repaint method is called when the update method is also called along with paint() method.|
|This method supports painting via graphics object.||This method is used to cause paint() to be invoked by the AWT painting thread.|
What is the difference between a Scrollbar and a ScrollPane?
|Scrollbar is a component.||Scrollpane is a container.|
|It does not handles its own events.||It handles its own events and performs its own scrolling.|
|Scrollbar cannot have a ScrollPane.||ScrollPane can have a scrollbar.|
What are methods that controls an applet’s life cycle, i.e. init, start, stop and destroy?
Life Cycle of an Applet: Basically, there are four methods in the Applet class on which any applet is built.
This method is intended for the initialization of your applet and is called after the param attributes of the applet tag.
This method is automatically called after init.
This method is automatically called whenever the user moves away from the page containing applets.
This method is only called when the browser shuts down normally.
What is paint method? What should we put in paint method? When is it invoked?
- The AWT(Abstract Window Toolkit) uses a Callback mechanism for painting which is the same for heavyweight and lightweight components.
- The components rendering code should be inside a program's overridden method so that the AWT can invoke it while painting.
- When AWT invokes this method, the Graphics object parameter is pre-configured with the appropriate state for drawing.
What is the purpose of repaint method? When should we use repaint method?
- The repaint() method is asynchronous.
- The repaint() requests an erase and redraw (update) after a small time delay.
- When repaint() method is invoked a message is sent to the native GUI requesting it to perform the action sometime in the distant future.
- This method does not invoke paint() method directly.
What is the difference between a Window and a Frame?
|Frame is a window with title bars and borders.||Window is an imaginary rectangle area on the monitor.|
|Frame is within a window.||Window will not be in a frame.|
|It has title bar, border, close button, minimize button, resizable and movable options.||It does not have title bar, border and any close button.|