Ans. A cookie is a small piece of text stored on a user's computer by the browser for a specific domain. Commonly used for authentication, storing site preferences, and server session identification.
Ans. No
Ans. Simple Inner Class, Local Inner Class, Anonymous Inner Class , Static Nested Inner Class.
Ans. They are different the way they are stored in memory. TreeMap stores the Keys in order whereas HashMap stores the key value pairs randomly.
Ans. List - Members are stored in sequence in memory and can be accessed through index.
Set - There is no relevance of sequence and index. Sets doesn't contain duplicates whereas multiset can have duplicates. Map - Contains Key , Value pairs.
Set - There is no relevance of sequence and index. Sets doesn't contain duplicates whereas multiset can have duplicates. Map - Contains Key , Value pairs.
Ans. Private - Not accessible outside object scope.
Public - Accessible from anywhere.
Default - Accessible from anywhere within same package.
Protected - Accessible from object and the sub class objects.
Public - Accessible from anywhere.
Default - Accessible from anywhere within same package.
Protected - Accessible from object and the sub class objects.
Ans. Multiple servlets serving the request in chain.
Ans. boolean - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void
Ans. Generics , Enums , Autoboxing , Annotations and Static Import.
Ans. New operator in Java creates objects. Constructor is the later step in object creation. Constructor's job is to initialize the members after the object has reserved memory for itself.
Ans. Though Static methods cannot access the instance variables directly, They can access them using instance handler.
Ans. Interfaces does't facilitate inheritance and hence implementation of multiple interfaces doesn't make multiple inheritance. Java doesn't support multiple inheritance.
Ans. "equals" is the member of object class which returns true if the content of objects are same whereas "==" evaluate to see if the object handlers on the left and right are pointing to the same object in memory.
Ans. Checked exceptions and the exceptions for which compiler throws an errors if they are not checked whereas unchecked exceptions and caught during run time only and hence can't be checked.
Ans. Final variable is a variable constant that cannot be changed after initialization.
Q16. Which class does not override the equals() and hashCode() methods, inheriting them directly from class Object?show Answer
Ans. java.lang.StringBuffer.
Ans. Its a method which cannot be overridden. Compiler throws an error if we try to override a method which has been declared final in the parent class.
Ans. Java.util.Map
Ans. Iterator is an interface that provides methods to iterate over any Collection.
Ans. java.util.map
Ans. Hashtable is synchronized whereas HashMap is not.
HashMap allows null values whereas Hashtable doesn’t allow null values.
HashMap allows null values whereas Hashtable doesn’t allow null values.
Ans. No. Static methods belong to the class and not the objects. They belong to the class and hence doesn't fit properly for the polymorphic behavior.
Ans. They are loaded at runtime when the respective Class is loaded.
Ans. No. Only Object and its members are serialized. Static variables are shared variables and doesn't correspond to a specific object.
Q25. What will this code print ?
String a = new String ("TEST");
String b = new String ("TEST");
if(a == b) {
System.out.println ("TRUE");
} else {
System.out.println ("FALSE");
}show Answer
String a = new String ("TEST");
String b = new String ("TEST");
if(a == b) {
System.out.println ("TRUE");
} else {
System.out.println ("FALSE");
}show Answer
Ans. FALSE.
== operator compares object references, a and b are references to two different objects, hence the FALSE. .equals method is used to compare string object content.
== operator compares object references, a and b are references to two different objects, hence the FALSE. .equals method is used to compare string object content.
Q26. There are two objects a and b with same hashcode. I am inserting these two objects inside a hashmap.
hMap.put(a,a);
hMap.put(b,b);
where a.hashCode()==b.hashCode()
Now tell me how many objects will be there inside the hashmap?show Answer
hMap.put(a,a);
hMap.put(b,b);
where a.hashCode()==b.hashCode()
Now tell me how many objects will be there inside the hashmap?show Answer
Ans. There can be two different elements with the same hashcode. When two elements have the same hashcode then Java uses the equals to further differentation. So there can be one or two objects depending on the content of the objects.
Ans. They both represent the long primitive type. They are exactly the same.
Ans. No
Ans. "this" keyword is a reference to the current object and can be used for following -
1. Passing itself to another method.
2. Referring to the instance variable when local variable has the same name.
3. Calling another constructor in constructor chaining.
1. Passing itself to another method.
2. Referring to the instance variable when local variable has the same name.
3. Calling another constructor in constructor chaining.
Ans. 1. when an OS wants to start running program it creates new process means a process is a program that is currently executing and every process has at least one thread running within it.
2). A thread is a path of code execution in the program, which has its own local variables, program counter(pointer to current execution being executed) and lifetime.
3. When the JavaVirtual Machine (JavaVM, or just VM) is started by the operating system, a new process is created. Within that process, many threads can be created.
4. Consider an example : when you open Microsoft word in your OS and you check your task manger then you can see this running program as a process. now when you write something in opened word document, then it performs more than one work at same time like it checks for the correct spelling, it formats the word you enter , so within that process ( word) , due to different path execution(thread) all different works are done at same time.
5. Within a process , every thread has independent path of execution but there may be situation where two threads can interfere with each other then concurrency and deadlock come is picture.
6. like two process can communicate ( ex:u open an word document and file explorer and on word document you drag and drop another another file from file explorer), same way two threads can also communicate with each other and communication with two threads is relatively low.
7. Every thread in java is created and controlled by unique object of java.lang.Thread class.
8. prior to jdk 1.5, there were lack in support of asynchronous programming in java, so in that case it was considered that thread makes the runtime environment asynchronous and allow different task to perform concurrently.
2). A thread is a path of code execution in the program, which has its own local variables, program counter(pointer to current execution being executed) and lifetime.
3. When the JavaVirtual Machine (JavaVM, or just VM) is started by the operating system, a new process is created. Within that process, many threads can be created.
4. Consider an example : when you open Microsoft word in your OS and you check your task manger then you can see this running program as a process. now when you write something in opened word document, then it performs more than one work at same time like it checks for the correct spelling, it formats the word you enter , so within that process ( word) , due to different path execution(thread) all different works are done at same time.
5. Within a process , every thread has independent path of execution but there may be situation where two threads can interfere with each other then concurrency and deadlock come is picture.
6. like two process can communicate ( ex:u open an word document and file explorer and on word document you drag and drop another another file from file explorer), same way two threads can also communicate with each other and communication with two threads is relatively low.
7. Every thread in java is created and controlled by unique object of java.lang.Thread class.
8. prior to jdk 1.5, there were lack in support of asynchronous programming in java, so in that case it was considered that thread makes the runtime environment asynchronous and allow different task to perform concurrently.
Ans. By putting code within either static method or static block.
Ans. 1. Multithreading provides better interaction with the user by distribution of task
2. Threads in Java appear to run concurrently, so it provides simulation for simultaneous activities.
The processor runs each thread for a short time and switches among the threads to simulate sim-ultaneous execution (context-switching) and it make appears that each thread has its own processor.By using this feature, users can make it appear as if multiple tasks are occurring simultaneously when, in fact, each is
running for only a brief time before the context is switched to the next thread.
3. We can do other things while waiting for slow I/O operations.
In the java.iopackage, the class InputStreamhas a method, read(), that blocks until a byte is read from the stream or until an IOExceptionis thrown. The thread that executes this method cannot do anything elsewhile awaiting the arrival of another byte on the stream.
2. Threads in Java appear to run concurrently, so it provides simulation for simultaneous activities.
The processor runs each thread for a short time and switches among the threads to simulate sim-ultaneous execution (context-switching) and it make appears that each thread has its own processor.By using this feature, users can make it appear as if multiple tasks are occurring simultaneously when, in fact, each is
running for only a brief time before the context is switched to the next thread.
3. We can do other things while waiting for slow I/O operations.
In the java.iopackage, the class InputStreamhas a method, read(), that blocks until a byte is read from the stream or until an IOExceptionis thrown. The thread that executes this method cannot do anything elsewhile awaiting the arrival of another byte on the stream.
Ans. No. Java doesn't allow multi thread access to object constructors so synchronization is not even needed.
Ans. Yes , for Hashtable. Hashtable implements Map interface.
Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc. The value received from hashcode() is used as bucket number for storing elements. This bucket number is the address of the element inside the set/map. when you do contains() then it will take the hashcode of the element, then look for the bucket where hashcode points to and if more than 1 element is found in the same bucket (multiple objects can have the same hashcode) then it uses the equals() method to evaluate if object are equal, and then decide if contain() is true or false, or decide if element could be added in the set or not.
Ans. class A {
void test() {
System.out.println("test() method");
}
}
class B {
void test() {
System.out.println("test() method");
}
}
Suppose if Java allows multiple inheritance like this,
class C extends A, B {
}
A and B test() methods are inheriting to C class.
So which test() method C class will take? As A & B class test() methods are different , So here we would Facing Ambiguity.
void test() {
System.out.println("test() method");
}
}
class B {
void test() {
System.out.println("test() method");
}
}
Suppose if Java allows multiple inheritance like this,
class C extends A, B {
}
A and B test() methods are inheriting to C class.
So which test() method C class will take? As A & B class test() methods are different , So here we would Facing Ambiguity.
Ans. Threads enters to waiting state or block on I/O because other threads can execute while the I/O operations are performed.
Ans. Transient variables are variable that cannot be serialized.
Ans. When a object invokes yield() it returns to ready state. But when an object invokes sleep() method enters to not ready state.
Ans. They are wrappers to primitive data types. They allow us to access primitives as objects.
Ans. In preemptive scheduling, highest priority task continues execution till it enters a not running state or a higher priority task comes into existence. In time slicing, the task continues its execution for a predefined period of time and reenters the pool of ready tasks.
Ans. Ready state.
Ans. One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializable Exception.
Ans. String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
Ans. 1. String Pool
When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
2. To Cache its Hashcode
If string is not immutable, One can change its hashcode and hence not fit to be cached.
3. Security
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.
When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
2. To Cache its Hashcode
If string is not immutable, One can change its hashcode and hence not fit to be cached.
3. Security
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.
Ans. Cookie and Session are used to store the user information. Cookie stores user information on client side and Session does it on server side. Primarily, Cookies and Session are used for authentication, user preferences, and carrying information across multiple requests. Session is meant for the same purpose as the cookie does. Session does it on server side and Cookie does it on client side. One more thing that quite differentiates between Cookie and Session. Cookie is used only for storing the textual information. Session can be used to store both textual information and objects.
Ans. 1. Stack Segment - contains local variables and Reference variables(variables that hold the address of an object in the heap)
2. Heap Segment - contains all created objects in runtime, objects only plus their object attributes (instance variables)
3. Code Segment - The segment where the actual compiled Java bytecodes resides when loaded
2. Heap Segment - contains all created objects in runtime, objects only plus their object attributes (instance variables)
3. Code Segment - The segment where the actual compiled Java bytecodes resides when loaded
Ans. Code segment.
Ans. The window, Frame and Dialog classes use a border layout as their default layout.
Ans. Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.
Ans. When a thread terminates its processing, it enters the dead state.
Ans. Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
Ans. Garbage collection does not guarantee that a program will not run out of memory. 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
Ans. An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.
Ans. 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
Ans. Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.
Q57. How does a try statement determine which catch clause should be used to handle an exception?show Answer
Ans. 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 exception is executed. The remaining catch clauses are ignored.
Ans. 1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
Ans. A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The String class represents character strings. All string literals in Java programs, such as "abc" are constant and implemented as instances of this class; their values cannot be changed after they are created.
Ans. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically frees the memory used by
objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java's dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected.
objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java's dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected.
Ans. RMI stands for Remote Method Invocation. Traditional approaches to executing code on other machines across a network have been confusing as well as tedious and error-prone to implement. The nicest way to think about this problem is that some object happens to live on another machine, and that you can send a message to the remote object and get a result as if the object lived on your local machine. This simplification is exactly what Java Remote Method Invocation (RMI) allows you to do.
Ans. The JDBC is a pure Java API used to execute SQL statements. It provides a set of classes and interfaces that can be used by developers to write database applications.
The steps needed to execute a SQL query using JDBC:
1. Open a connection to the database.
2. Execute a SQL statement.
3. Process th results.
4. Close the connection to the database.
The steps needed to execute a SQL query using JDBC:
1. Open a connection to the database.
2. Execute a SQL statement.
3. Process th results.
4. Close the connection to the database.
Q63. Are constructors inherited? Can a subclass call the parent's class constructor? When?show Answer
Ans. You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses. One of the main reasons is because you probably don't want to override the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language.
Ans. JSON is "JavaScript Object Notation", primarily used for client-server or server-server communication. Its a much lighter and readable alternative to XML. JSON is language independent and is easily parse-able in all programming languages.
Ans. JSON.stringify() turns an object into a JSON text and stores that JSON text in a string.
So If we stringfy above notation , it will become
{"name":"xyz","gender":"male";"age":30}
So If we stringfy above notation , it will become
{"name":"xyz","gender":"male";"age":30}
Ans. Enums were introduced with java 5.
Ans. eval
Ans. Number
String
Boolean
Array
Object
null
String
Boolean
Array
Object
null
Ans. Lighter and faster than XML as on-the-wire data format
Object Representation - Information is presented in object notations and hence better understandable. Easy to parse and conversion to objects for information consumption.
Support multiple data types - JSON supports string, number, array, boolean whereas XML data are all string.
Object Representation - Information is presented in object notations and hence better understandable. Easy to parse and conversion to objects for information consumption.
Support multiple data types - JSON supports string, number, array, boolean whereas XML data are all string.
Ans. clone() - Creates and returns a copy of this object.
equals() - Indicates whether some other object is "equal to" this one.
finalize() - Called by the garbage collector on an object when garbage collection determines that there are no more references to the object
getClass() - Returns the runtime class of an object.
hashCode() - Returns a hash code value for the object.
toString() - Returns a string representation of the object.
notify(), notifyAll(), and wait() - Play a part in synchronizing the activities of independently running threads in a program.
equals() - Indicates whether some other object is "equal to" this one.
finalize() - Called by the garbage collector on an object when garbage collection determines that there are no more references to the object
getClass() - Returns the runtime class of an object.
hashCode() - Returns a hash code value for the object.
toString() - Returns a string representation of the object.
notify(), notifyAll(), and wait() - Play a part in synchronizing the activities of independently running threads in a program.
Ans. JMS Provides high-performance asynchronous messaging. It enables Java EE applications to communicate with non-Java systems on top of various transports.
Ans. EJB Provides a mechanism that make easy for Java developers to use advanced features in their components, such as remote method invocation (RMI), object/ relational mapping (that is, saving Java objects to a relational database), and distributed transactions across multiple data sources.
Ans. MVC2
Ans. An API is a kind of technical contract which defines functionality that two parties must provide: a service provider (often called an implementation) and an application. an API simply defines services that a service provider (i.e., the implementation) makes available to applications.
Ans. URL is Uniform Resource Locator which is representation of HTTP address.
Ans. 1) It is an Action based MVC based framework which has adopt mvc2.
2) Struts2 is a pull-MVC (or MVC2) framework where action takes the role of the model rather than the controller. The “pull” concepts means views ability to pull data from an action, rather than having a separate model object available.
3) The Model View-Controller pattern in Struts2 is implemented with five core components – actions, interceptors, value stack / OGNL, result types and results / view technologies.
4) XML configuration as well as Annotation option available.
5) POJO based action available so we can write test cases easily.
6) Integration with Spring, tiles and OGNL based expression langugae.
7) Theme based tag libraries integrated with struts tag as well as support of Ajax tag.
8) Can have various view options like jsp, velocity, freemarker etc.
9) We can embed plugin through which we can modify and extend framework features.
2) Struts2 is a pull-MVC (or MVC2) framework where action takes the role of the model rather than the controller. The “pull” concepts means views ability to pull data from an action, rather than having a separate model object available.
3) The Model View-Controller pattern in Struts2 is implemented with five core components – actions, interceptors, value stack / OGNL, result types and results / view technologies.
4) XML configuration as well as Annotation option available.
5) POJO based action available so we can write test cases easily.
6) Integration with Spring, tiles and OGNL based expression langugae.
7) Theme based tag libraries integrated with struts tag as well as support of Ajax tag.
8) Can have various view options like jsp, velocity, freemarker etc.
9) We can embed plugin through which we can modify and extend framework features.
Ans. HTTP or Hypertext Transfer Protocol is internet protocol for tranmission of hypertext ( text with meta data ) over internet.
Ans. Suppose we want to visit a site for any information, information can be represented in different languages like English,German or may be other and their format for presentation can also differ from HTML to PDF or may be Plain text. In this case when an client makes an HTTP request to a server, client can also specify the media types here. Client can specify what it can accept back from host and on the basis of availability the host will return to the client. This is called content negotiation because client and server negotiated on the language and format of the content to be shared.
Ans. Application server.
Ans. Web server.
Ans. boolean ---> false
byte ----> 0
short ----> 0
int -----> 0
long ------> 0l
char -----> /u0000
float ------> 0.0f
double ----> 0.0d
any object reference ----> null
byte ----> 0
short ----> 0
int -----> 0
long ------> 0l
char -----> /u0000
float ------> 0.0f
double ----> 0.0d
any object reference ----> null
Ans. 1.Abstraction solves the problem at design level while encapsulation solves the problem at implementation level
2.Abstraction is used for hiding the unwanted data and giving relevant data. while Encapsulation means hiding the code and data into a single unit to protect the data from outside world.
3. Abstraction lets you focus on what the object does instead of how it does it while Encapsulation means hiding the internal details or mechanics of how an object does something.
4.For example: Outer Look of a Television, like it has a display screen and channel buttons to change channel it explains Abstraction but Inner Implementation detail of a Television how CRT and Display Screen are connect with each other using different circuits , it explains Encapsulation.
2.Abstraction is used for hiding the unwanted data and giving relevant data. while Encapsulation means hiding the code and data into a single unit to protect the data from outside world.
3. Abstraction lets you focus on what the object does instead of how it does it while Encapsulation means hiding the internal details or mechanics of how an object does something.
4.For example: Outer Look of a Television, like it has a display screen and channel buttons to change channel it explains Abstraction but Inner Implementation detail of a Television how CRT and Display Screen are connect with each other using different circuits , it explains Encapsulation.
Q83. Can I import same package/class twice? Will the JVM load the package twice at runtime?show Answer
Ans. One can import the same package or same class multiple times. Neither compiler nor JVM complains wil complain about it. And the JVM will internally load the class only once no matter how many times you import the same class.
Ans. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
Ans. For top level class we can only use "public" and "default". We can use private with inner class.
Ans. Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate. Annotations have a number of uses, among them:
• Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
• Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
• Runtime processing — Some annotations are available to be examined at runtime.
• Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
• Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
• Runtime processing — Some annotations are available to be examined at runtime.
Ans. Suppose that a software group traditionally starts the body of every class with comments providing important information:
public class Generation3List extends Generation2List {
// Author: John Doe
// Date: 3/17/2002
// Current revision: 6
// Last modified: 4/12/2004
// By: Jane Doe
// Reviewers: Alice, Bill, Cindy
// class code goes here
}
To add this same metadata with an annotation, you must first define the annotation type. The syntax for doing this is:
@interface ClassPreamble {
String author();
String date();
int currentRevision() default 1;
String lastModified() default "N/A";
String lastModifiedBy() default "N/A";
// Note use of array
String[] reviewers();
}
The annotation type definition looks similar to an interface definition where the keyword interface is preceded by the at sign (@) (@ = AT, as in annotation type). Annotation types are a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces.
The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.
After the annotation type is defined, you can use annotations of that type, with the values filled in, like this:
@ClassPreamble (
author = "John Doe",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "Jane Doe",
// Note array notation
reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {
// class code goes here
}
public class Generation3List extends Generation2List {
// Author: John Doe
// Date: 3/17/2002
// Current revision: 6
// Last modified: 4/12/2004
// By: Jane Doe
// Reviewers: Alice, Bill, Cindy
// class code goes here
}
To add this same metadata with an annotation, you must first define the annotation type. The syntax for doing this is:
@interface ClassPreamble {
String author();
String date();
int currentRevision() default 1;
String lastModified() default "N/A";
String lastModifiedBy() default "N/A";
// Note use of array
String[] reviewers();
}
The annotation type definition looks similar to an interface definition where the keyword interface is preceded by the at sign (@) (@ = AT, as in annotation type). Annotation types are a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces.
The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.
After the annotation type is defined, you can use annotations of that type, with the values filled in, like this:
@ClassPreamble (
author = "John Doe",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "Jane Doe",
// Note array notation
reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {
// class code goes here
}
Ans. @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation.
@Override annotation informs the compiler that the element is meant to override an element declared in a superclass.
@SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate.
@SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargsparameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.
@FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.
@Override annotation informs the compiler that the element is meant to override an element declared in a superclass.
@SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate.
@SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargsparameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.
@FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.
Ans. Annotations that apply to other annotations are called meta-annotations.
Ans. @Retention annotation specifies how the marked annotation is stored:
@Documented annotation indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.)
@Target annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to.
@Inherited annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class' superclass is queried for the annotation type. This annotation applies only to class declarations.
@Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use. For more information, see Repeating Annotations.
@Documented annotation indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.)
@Target annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to.
@Inherited annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class' superclass is queried for the annotation type. This annotation applies only to class declarations.
@Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use. For more information, see Repeating Annotations.
Ans. To display the current CLASSPATH variable, use these commands in UNIX (Bourne shell):
% echo $CLASSPATH
To delete the current contents of the CLASSPATH variable,
In UNIX: % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable,
In UNIX: % CLASSPATH=/home/george/java/classes; export CLASSPATH
% echo $CLASSPATH
To delete the current contents of the CLASSPATH variable,
In UNIX: % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable,
In UNIX: % CLASSPATH=/home/george/java/classes; export CLASSPATH
Ans. Abstract classes are only meant to be sub classed and not meant to be instantiated whereas concrete classes are meant to be instantiated.
Ans. Overloading - Similar Signature but different definition , like function overloading.
Overriding - Overriding the Definition of base class in the derived class.
Overriding - Overriding the Definition of base class in the derived class.
Ans. Vectors are synchronized whereas Array lists are not.
Ans. Threads in Java can be implement either by Extending Thread class or implementing runnable interface.
Ans. Volatile is a declaration that a variable can be accessed by multiple threads and hence shouldn't be cached.
Ans. Storing the state of an object in a file or other medium is called serialization.
Ans. It in Java is used to indicate that a field should not be serialized.
Ans. Final variable is a constant variable. Variable value can't be changed after instantiation.
Ans. A Method that cannot be overriden in the sub class.
Ans. A Class that cannot be sub classed.
Ans. Object that can't be changed after instantiation.
Ans. Class using which only immutable (objects that cannot be changed after initialization) objects can be created.
Ans. We can make a class immutable by
1. Making all methods and variables as private.
2. Setting variables within constructor.
Public Class ImmutableClass{
private int member;
ImmutableClass(int var){
member=var;
}
}
and then we can initialize the object of the class as
ImmutableClass immutableObject = new ImmutableClass(5);
Now all members being private , you can't change the state of the object.
1. Making all methods and variables as private.
2. Setting variables within constructor.
Public Class ImmutableClass{
private int member;
ImmutableClass(int var){
member=var;
}
}
and then we can initialize the object of the class as
ImmutableClass immutableObject = new ImmutableClass(5);
Now all members being private , you can't change the state of the object.
Ans. Only declaring primitive types as final makes them immutable. Making objects final means that the object handler cannot be used to target some other object but the object is still mutable.
Ans. Though It's often confused with each other, Object Creation ( Instantiation ) and Initialization ( Construction ) are different things in Java. Construction follows object creation.
Object Creation is the process to create the object in memory and returning its handler. Java provides New keyword for object creation.
Initialization is the process of setting the initial / default values to the members. Constructor is used for this purpose. If we don't provide any constructor, Java provides one default implementation to set the default values according to the member data types.
Object Creation is the process to create the object in memory and returning its handler. Java provides New keyword for object creation.
Initialization is the process of setting the initial / default values to the members. Constructor is used for this purpose. If we don't provide any constructor, Java provides one default implementation to set the default values according to the member data types.
Ans. No.
Static methods belong to the class and not the objects. They belong to the class and hence doesn't fit properly for the polymorphic behavior.
A static method is not associated with any instance of a class so the concept of overriding for runtime polymorphism using static methods is not applicable.
Static methods belong to the class and not the objects. They belong to the class and hence doesn't fit properly for the polymorphic behavior.
A static method is not associated with any instance of a class so the concept of overriding for runtime polymorphism using static methods is not applicable.
Ans. Yes.
we cannot access them directly but we can access them using object reference.
Static methods belong to a class and not objects whereas non static members are tied to an instance. Accessing instance variables without the instance handler would mean an ambiguity regarding which instance the method is referring to and hence its prohibited.
we cannot access them directly but we can access them using object reference.
Static methods belong to a class and not objects whereas non static members are tied to an instance. Accessing instance variables without the instance handler would mean an ambiguity regarding which instance the method is referring to and hence its prohibited.
Ans. No.
Ans. ClassNotFoundException is checked exception whereas NoClassDefFoundError is a unchecked exception.
Ans. IndexOutofBound , NoClassDefFound , OutOfMemory , IllegalArgument.
Ans. Inheritence.
Q113. How can we make sure that a code segment gets executed even in case of uncatched exceptions ?show Answer
Ans. By putting it within finally.
Ans. Used in method declarations to specify that the method is not implemented in the same Java source file, but rather in another language
Ans. Used to access members of the base class.
Ans. Used to represent an instance of the class in which it appears.
Ans. boolean is a primitive type whereas Boolean is a class.
Ans. finalize() method is called just before an object is destroyed.
Ans. These are the interfaces which have no declared methods.
Serializable and cloneable are marker interfaces.
Serializable and cloneable are marker interfaces.
Ans. No , it has run method declared.
Ans. Process is a program in execution whereas thread is a separate path of execution in a program.
Ans. When two threads are waiting each other and can’t precede the program is said to be deadlock.
Ans. Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
Ans. Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes
Ans. An enum type is a special data type that enables for a variable to be a set of predefined constants
Ans. A wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component. A Wrapper Class that wraps or encapsulates the primitive data type is called Primitive Wrapper Class.
Ans. Adapter.
Ans. Enables the programmer to abbreviate the names of classes defined in a package.
Ans. Class , Heap , Stack , Register , Native Method Stack.
Ans. Part of JVM which is used to load classes and interfaces.
Bootstrap , Extension and System are the class loaders used by JVM.
Bootstrap , Extension and System are the class loaders used by JVM.
Ans. No.
Ans. By static import , we can access the static members of a class directly without prefixing it with the class name.
Ans. StringBuffer is synchronized whereas StringBuilder is not.
Ans. Map is an interface where HashMap is the concrete class.
Ans. The properties class is a subclass of Hashtable that can be read from or written to a stream.
Ans. If the Object value will not change in a scenario use String Class because a String object is immutable.
If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).
If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).
If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).
If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).
Ans. This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.
Ans. Yes by making entries in web.xml
Ans. Within message.properties file.
Ans. Its an interpretor.
Ans. An explicit conversion is where you use some syntax to tell the program to do a conversion whereas in case of implicit type casting you need not provide the data type.
Ans. loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize the object after loading it.
Ans. Finalize is used by Java for Garbage collection. It should not be done as we should leave the Garbage Collection to Java itself.
Ans. The assert keyword is used to make an assertion—a statement which the programmer believes is always true at that point in the program. This keyword is intended to aid in testing and debugging.
Ans. Factory Pattern deals with creation of objects delegated to a separate factory class whereas Abstract Factory patterns works around a super-factory which creates other factories.
Ans. Builder pattern is the extension of Factory pattern wherein the Builder class builds a complex object in multiple steps.
Ans. Adapter object has a different input than the real subject whereas Proxy object has the same input as the real subject. Proxy object is such that it should be placed as it is in place of the real subject.
Ans. The Difference between these patterns in only the intent. Adapter is used because the objects in current form cannot communicate where as in Facade , though the objects can communicate , A Facade object is placed between the client and subject to simplify the interface.
Ans. Builder is a creational Design Pattern whereas Composite is a structural design pattern. Composite creates Parent - Child relations between your objects while Builder is used to create group of objects of predefined types.
Ans. Exception Handling Throw mechanism.
Ans. Listeners.
Ans. Factory is a creational design pattern whereas Strategy is behavioral design pattern. Factory revolves around the creation of object at runtime whereas Strategy or Policy revolves around the decision at runtime.
Ans. Strategy deals only with decision making at runtime so Interfaces should be used.
Q154. Which kind of memory is used for storing object member variables and function local variables ?show Answer
Ans. Local variables are stored in stack whereas object variables are stored in heap.
Q155. Why do member variables have default values whereas local variables don't have any default value ?show Answer
Ans. member variable are loaded into heap, so they are initialized with default values when an instance of a class is created. In case of local variables, they are stored in stack until they are being used.
Ans. The no argument constructor provided by Java Compiler if no constructor is specified.
Q157. Will Compiler creates a default no argument constructor if we specify only multi argument constructor ?show Answer
Ans. No, Compiler will create default constructor only if we don't specify any constructor.
Ans. Yes.
Ans. We can't create the objects directly by invoking new operator.
Ans. We can do so through a static public member method or static block.
Ans. Program will compile but will give a "NoSuchMethodError" during runtime.
Ans. Pointers are vulnerable and slight carelessness in their use may result in memory problems and hence Java intrinsically manage their use.
Ans. No, because both this and super should be the first statement.
Ans. No, It is loaded by default by the JVM.
Ans. It should be followed by either catch or finally block.
Ans. Yes but should follow "try" block then.
Ans. Passing the exception object to the calling method.
Ans. Inner classes are non static nested classes.
Ans. Any interface declared inside a class or an interface. It is static by default.
Ans. Externalizable interface is used to write the state of an object into a byte stream in compressed format.
Ans. Serializable is a marker interface whereas externalizable is not.
Ans. It is the process of examining / modifying the runtime behaviour of an object at runtime.
Q173. Can we instantiate the object of derived class if parent constructor is protected ?show Answer
Ans. No
Ans. No Abstract methods can only be declared protected or public.
Q175. What are the design considerations while making a choice between using interface and abstract class ?show Answer
Ans. Keep it as a Abstract Class if its a "Is a" Relationsship and should do subset/all of the functionality. Keep it as Interface if its a "Should Do" relationship.
Ans. The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet. This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file location.
Ans. The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page. This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope.
Ans. suspend() method is used to suspend the execution of a thread for a period of time. We can then restart the thread by using resume() method.
Ans. Suspend method is used to suspend thread which can be restarted by using resume() method. stop() is used to stop the thread, it cannot be restarted again.
Ans. Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is that you do not need an EJB container product.
Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about ones you need and ignore the rest.
Spring does not reinvent the wheel instead, it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies.
Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBean-style POJOs, it becomes easier to use dependency injection for injecting test data.
Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.
Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources.
Spring provides a consistent transaction management interface that can scale down to a local transaction
Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about ones you need and ignore the rest.
Spring does not reinvent the wheel instead, it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies.
Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBean-style POJOs, it becomes easier to use dependency injection for injecting test data.
Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.
Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources.
Spring provides a consistent transaction management interface that can scale down to a local transaction
Ans. Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.
Q182. Will this code give error if i try to add two heterogeneous elements in the arraylist. ? and Why ?
List list1 = new ArrayList<>();
list1.add(5);
list1.add("5");show Answer
List list1 = new ArrayList<>();
list1.add(5);
list1.add("5");show Answer
Ans. If we don't declare the list to be of specific type, it treats it as list of objects.
int 1 is auto boxed to Integer and "1" is String and hence both are objects.
int 1 is auto boxed to Integer and "1" is String and hence both are objects.
Ans. Java Beans managed by Spring IoC are called Spring Beans.
Ans. System.console() returns null if your application is not run in a terminal (though you can handle this in your application)
System.console() provides methods for reading password without echoing characters
System.out and System.err use the default platform encoding, while the Console class output methods use the console encoding
System.console() provides methods for reading password without echoing characters
System.out and System.err use the default platform encoding, while the Console class output methods use the console encoding
Ans. Bootstrap - Loads JDK internal classes, java.* packages.
Extensions - Loads jar files from JDK extensions directory - usually lib/ext directory of the JRE
System - Loads classes from system classpath.
Extensions - Loads jar files from JDK extensions directory - usually lib/ext directory of the JRE
System - Loads classes from system classpath.
Ans. Class loaders are hierarchical. The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running.
Ans. Java does not support pointers.
Java does not support multiple inheritances.
Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method.
Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework.
C++ compiles to machine language , when Java compiles to byte code .
In C++ the programmer needs to worry about freeing the allocated memory , where in Java the Garbage Collector takes care of the the unneeded / unused variables.
Java is platform independent language but c++ is depends upon operating system.
Java uses compiler and interpreter both and in c++ their is only compiler.
C++ supports operator overloading whereas Java doesn't.
Internet support is built-in Java but not in C++. However c++ has support for socket programming which can be used.
Java does not support header file, include library files just like C++ .Java use import to include different Classes and methods.
There is no goto statement in Java.
There is no scope resolution operator :: in Java. It has . using which we can qualify classes with the namespace they came from.
Java is pass by value whereas C++ is both pass by value and pass by reference.
Java Enums are objects instead of int values in C++
C++ programs runs as native executable machine code for the target and hence more near to hardware whereas Java program runs in a virtual machine.
C++ was designed mainly for systems programming, extending the C programming language whereas Java was created initially to support network computing.
C++ allows low-level addressing of data. You can manipulate machine addresses to look at anything you want. Java access is controlled.
C++ has several addressing operators . * & -> where Java has only one: the .
We can create our own package in Java(set of classes) but not in c and c++.
Java does not support multiple inheritances.
Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method.
Java does not include structures or unions because the traditional data structures are implemented as an object oriented framework.
C++ compiles to machine language , when Java compiles to byte code .
In C++ the programmer needs to worry about freeing the allocated memory , where in Java the Garbage Collector takes care of the the unneeded / unused variables.
Java is platform independent language but c++ is depends upon operating system.
Java uses compiler and interpreter both and in c++ their is only compiler.
C++ supports operator overloading whereas Java doesn't.
Internet support is built-in Java but not in C++. However c++ has support for socket programming which can be used.
Java does not support header file, include library files just like C++ .Java use import to include different Classes and methods.
There is no goto statement in Java.
There is no scope resolution operator :: in Java. It has . using which we can qualify classes with the namespace they came from.
Java is pass by value whereas C++ is both pass by value and pass by reference.
Java Enums are objects instead of int values in C++
C++ programs runs as native executable machine code for the target and hence more near to hardware whereas Java program runs in a virtual machine.
C++ was designed mainly for systems programming, extending the C programming language whereas Java was created initially to support network computing.
C++ allows low-level addressing of data. You can manipulate machine addresses to look at anything you want. Java access is controlled.
C++ has several addressing operators . * & -> where Java has only one: the .
We can create our own package in Java(set of classes) but not in c and c++.
Ans. static loading - Classes are statically loaded with Java’s “new” operator.
dynamic class loading - Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.
Class.forName (Test className);
dynamic class loading - Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.
Class.forName (Test className);
Ans. A Buffer is a temporary storage area for data. The BufferedWriter class is an output stream.It is an abstract class that creates a buffered character-output stream.
Flush() is used to clear all the data characters stored in the buffer and clear the buffer.
Close() is used to closes the character output stream.
Flush() is used to clear all the data characters stored in the buffer and clear the buffer.
Close() is used to closes the character output stream.
Ans. Scanner class introduced in Java 1.5 for reading Data Stream from the imput device. Previously we used to write code to read a input using DataInputStream. After reading the stream , we can convert into respective data type using in.next() as String ,in.nextInt() as integer, in.nextDouble() as Double etc
Q191. Why Struts 1 Classes are not Thread Safe whereas Struts 2 classes are thread safe ?show Answer
Ans. Struts 1 actions are singleton. So all threads operates on the single action object and hence makes it thread unsafe.
Struts 2 actions are not singleton and a new action object copy is created each time a new action request is made and hence its thread safe.
Struts 2 actions are not singleton and a new action object copy is created each time a new action request is made and hence its thread safe.
Ans. sockets, RMI. EJB
Ans. They just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently.
Ans. final - constant variable, restricting method overloading, restricting class subclassing.
finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block. Use the finally block to close files or to release
other system resources like database connections, statements etc.
finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state.
finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block. Use the finally block to close files or to release
other system resources like database connections, statements etc.
finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state.
Ans. As we only downcast class in the hierarchy, The ClassCastException is thrown to indicate that code has attempted to cast an object to a subclass of which it is not an instance.
Ans. Runnable - waiting for its turn to be picked for execution by the thread schedular based on thread priorities.
Running - The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn.
Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.
Sleeping - Java threads are forcibly put to sleep (suspended) with Thread.sleep. they can resume using Thread.resume method.
Blocked on I/O - Will move to runnable after I/O condition like reading bytes of data etc changes.
Blocked on synchronization - Will move to Runnable when a lock is acquired.
Dead - The thread is finished working.
Running - The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn.
Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.
Sleeping - Java threads are forcibly put to sleep (suspended) with Thread.sleep. they can resume using Thread.resume method.
Blocked on I/O - Will move to runnable after I/O condition like reading bytes of data etc changes.
Blocked on synchronization - Will move to Runnable when a lock is acquired.
Dead - The thread is finished working.
Ans. Garbage Collector won’t remove a strong reference.
A soft reference will only get removed if memory is low.
A weak reference will get removed on the next garbage collection cycle.
A phantom reference will be finalized but the memory will not be reclaimed. Can be useful when you want to be notified that an object is about to be collected.
A soft reference will only get removed if memory is low.
A weak reference will get removed on the next garbage collection cycle.
A phantom reference will be finalized but the memory will not be reclaimed. Can be useful when you want to be notified that an object is about to be collected.
Ans. When a task invokes yield(), it changes from running state to runnable state. When a task invokes sleep(), it changes from running state to waiting/sleeping state.
Ans. These are threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced. garbage collector thread is daemon thread.
Ans. Swing provides both additional components like JTable, JTree etc and added functionality to AWT-replacement components.
Swing components can change their appearance based on the current “look and feel” library that’s being used.
Swing components follow the MVC paradigm, and thus can provide a much more flexible UI.
Swing provides extras for components, such as icons on many components, decorative borders for components, tool tips for components etc.
Swing components are lightweight than AWT.
Swing provides built-in double buffering ,which means an off-screen buffer is used during drawing and then the resulting bits are copied onto the screen.
Swing provides paint debugging support for when you build your own component.
Swing components can change their appearance based on the current “look and feel” library that’s being used.
Swing components follow the MVC paradigm, and thus can provide a much more flexible UI.
Swing provides extras for components, such as icons on many components, decorative borders for components, tool tips for components etc.
Swing components are lightweight than AWT.
Swing provides built-in double buffering ,which means an off-screen buffer is used during drawing and then the resulting bits are copied onto the screen.
Swing provides paint debugging support for when you build your own component.
Ans. public void init()
public void start()
public void stop()
public void destroy()
public void start()
public void stop()
public void destroy()
Ans. JProbe, OptimizeIt
Ans. instance variables are stored on stack whereas static variables are stored on heap.
Ans. J2EE or Java 2 Enterprise Edition is an environment for developing and deploying enterprise applications. The J2EE platform consists of J2EE components, services, Application Programming Interfaces (APIs) and protocols that provide the functionality for developing multi-tiered and distributed Web based applications.
Ans. applets
Client component like Client side Java codes.
Web component like JSP, Servlet WAR
Enterprise JavaBeans like Session beans, Entity beans, Message driven beans
Enterprise application like WAR, JAR, EAR
Client component like Client side Java codes.
Web component like JSP, Servlet WAR
Enterprise JavaBeans like Session beans, Entity beans, Message driven beans
Enterprise application like WAR, JAR, EAR
Ans. XML or eXtensible Markup Language is a markup languages for describing data and its metadata.
Ans. A DOM (Document Object Model) parser creates a tree structure in memory from an input document whereas A SAX (Simple API for XML) parser does not create any internal structure.
A SAX parser serves the client application always only with pieces of the document at any given time whereas A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client.
A SAX parser, however, is much more space efficient in case of a big input document whereas DOM parser is rich in functionality.
Use a DOM Parser if you need to refer to different document areas before giving back the information. Use SAX is you just need unrelated nuclear information from different areas.
Xerces, Crimson are SAX Parsers whereas XercesDOM, SunDOM, OracleDOM are DOM parsers.
A SAX parser serves the client application always only with pieces of the document at any given time whereas A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client.
A SAX parser, however, is much more space efficient in case of a big input document whereas DOM parser is rich in functionality.
Use a DOM Parser if you need to refer to different document areas before giving back the information. Use SAX is you just need unrelated nuclear information from different areas.
Xerces, Crimson are SAX Parsers whereas XercesDOM, SunDOM, OracleDOM are DOM parsers.
Ans. DTD or Document Type Definition is a standard agreed upon way of communication between two parties. Your application can use a standard DTD to verify that data that you receive
from the outside world is valid and can be parsed by your parser.
from the outside world is valid and can be parsed by your parser.
Ans. XSD or Xml Schema Definition is an extension of DTD. XSD is more powerful and extensible than DTD
Ans. Stands for Java API for XML Processing. This provides a common interface for creating and using SAX, DOM, and XSLT APIs in Java regardless of which vendor’s implementation is actually being used.
Ans. Stands for Java API for XML Binding. This standard defines a mechanism for writing out Java objects as XML and for creating Java objects from XML structures.
Ans. Its the process of creating XML structures out of Java Objects.
Ans. Its the process of creating Java Objects out of XML structures.
Ans. Rational Robot, JMeter, LoadRunner.
Ans. LDAP servers are typically used in J2EE applications to authenticate and authorise users. LDAP servers are hierarchical and are optimized for read access, so likely to be faster than database in providing read access.
Ans. Comparable interface is used for single sequence sorting i.e.sorting the objects based on single data member where as comparator interface is used to sort the object based on multiple data members.
Ans. There are seven core modules in spring
Spring MVC
The Core container
O/R mapping
DAO
Application context
Aspect Oriented Programming or AOP
Web module
Spring MVC
The Core container
O/R mapping
DAO
Application context
Aspect Oriented Programming or AOP
Web module
Ans. The DispatcherServlet configured in web.xml file receives the request.
The DispatcherServlet finds the appropriate Controller with the help of HandlerMapping and then invokes associated Controller.
Then the Controller executes the logic business logic and then returns ModeAndView object to the DispatcherServlet.
The DispatcherServlet determines the view from the ModelAndView object.
Then the DispatcherServlet passes the model object to the View.
The View is rendered and the Dispatcher Servlet sends the output to the Servlet container. Finally Servlet Container sends the result back to the user.
The DispatcherServlet finds the appropriate Controller with the help of HandlerMapping and then invokes associated Controller.
Then the Controller executes the logic business logic and then returns ModeAndView object to the DispatcherServlet.
The DispatcherServlet determines the view from the ModelAndView object.
Then the DispatcherServlet passes the model object to the View.
The View is rendered and the Dispatcher Servlet sends the output to the Servlet container. Finally Servlet Container sends the result back to the user.
Ans. Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.
Ans. The default scope of bean is Sing leton for Spring framework.
Ans. The Spring Framework supports following five scopes -
Singleton
prototype
request
session
global-session
Singleton
prototype
request
session
global-session
Ans. The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory without using and elements.
Ans. servlet is a small, server-resident program that typically runs automatically in response to user input.
A network socket is an endpoint of an inter-process communication flow across a computer network.
We can think of it as a difference between door and gate. They are similar as they both are entry points but they are different as they are put up at different areas.
Sockets are for low-level network communication whereas Servlets are for implementing websites and web services
A network socket is an endpoint of an inter-process communication flow across a computer network.
We can think of it as a difference between door and gate. They are similar as they both are entry points but they are different as they are put up at different areas.
Sockets are for low-level network communication whereas Servlets are for implementing websites and web services
Ans. 1.this is a reference to the current object in which this keyword is used whereas super is a reference used to access members specific to the parent Class.
2.this is primarily used for accessing member variables if local variables have same name, for constructor chaining and for passing itself to some method whereas super is primarily used to initialize base class members within derived class constructor.
2.this is primarily used for accessing member variables if local variables have same name, for constructor chaining and for passing itself to some method whereas super is primarily used to initialize base class members within derived class constructor.
Ans. Translation of JSP Page
Compilation of JSP Page
Classloading (class file is loaded by the classloader)
Instantiation (Object of the Generated Servlet is created).
Initialization ( jspInit() method is invoked by the container).
Reqeust processing ( _jspService() method is invoked by the container).
Destroy ( jspDestroy() method is invoked by the container).
Compilation of JSP Page
Classloading (class file is loaded by the classloader)
Instantiation (Object of the Generated Servlet is created).
Initialization ( jspInit() method is invoked by the container).
Reqeust processing ( _jspService() method is invoked by the container).
Destroy ( jspDestroy() method is invoked by the container).
Ans. The jsp scriptlet tag can only declare variables not methods whereas jsp declaration tag can declare
variables as well as methods.
The declaration of scriptlet tag is placed inside the _jspService() method whereas The declaration of jsp declaration tag is placed outside the _jspService() method.
variables as well as methods.
The declaration of scriptlet tag is placed inside the _jspService() method whereas The declaration of jsp declaration tag is placed outside the _jspService() method.
Ans. The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet.
There are three types of directives -
• page directive
• include directive
• taglib directive
There are three types of directives -
• page directive
• include directive
• taglib directive
Ans. “Java bytecode” is the usual name for the machine language of the Java Virtual
Machine. Java programs are compiled into Java bytecode, which can then be executed
by the JVM.
Machine. Java programs are compiled into Java bytecode, which can then be executed
by the JVM.
Ans. In GUI programming, an object that can be registered to be notified when events of
some given type occur. The object is said to “listen” for the events.
some given type occur. The object is said to “listen” for the events.
Ans. The Model/View/Controller pattern, a strategy for dividing responsibility in a GUI component. The model is the data for the component. The view is the visual presentation of the component on the screen. The controller is responsible for reacting to events by changing the model. According to the MVC pattern, these responsibilities should be handled by different objects.
Ans. A source of possible errors in parallel programming, where one thread can cause an error in another thread by changing some aspect of the state of the program that the second thread is depending on (such as the value of variable).
Ans. A way of encoding characters as binary numbers. The Unicode character set includes
characters used in many languages, not just English. Unicode is the character set that is
used internally by Java.
characters used in many languages, not just English. Unicode is the character set that is
used internally by Java.
Ans. ThreadFactory is an interface that is meant for creating threads instead of explicitly creating threads by calling new Thread(). Its an object that creates new threads on demand. Using thread factories removes hardwiring of calls to new Thread, enabling applications to use special thread subclasses, priorities, etc.
Ans. The memory pool containing all the reflective data of the java virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas. The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application. In addition, Java SE library classes and methods may be stored here.
Ans. The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace. The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError: PermGen error.
Ans. You can put related classes together as a single logical group.
Nested classes can access all class members of the enclosing class, which might be useful in certain cases.
Nested classes are sometimes useful for specific purposes. For example, anonymous inner classes are useful for writing simpler event-handling code with AWT/Swing.
Nested classes can access all class members of the enclosing class, which might be useful in certain cases.
Nested classes are sometimes useful for specific purposes. For example, anonymous inner classes are useful for writing simpler event-handling code with AWT/Swing.
Ans. The accessibility (public, protected, etc.) of the static nested class is defined by the outer class.
A static nested class is not an inner class, it's a top-level nested class.
The name of the static nested class is expressed with OuterClassName.NestedClassName syntax.
When you define an inner nested class (or interface) inside an interface, the nested class is declared implicitly public and static.
Static nested classes can be declared abstract or final.
Static nested classes can extend another class or it can be used as a base class.
Static nested classes can have static members.
Static nested classes can access the members of the outer class (only static members, obviously).
The outer class can also access the members (even private members) of the nested class through an object of nested class. If you don’t declare an instance of the nested class, the outer class cannot access nested class elements directly.
A static nested class is not an inner class, it's a top-level nested class.
The name of the static nested class is expressed with OuterClassName.NestedClassName syntax.
When you define an inner nested class (or interface) inside an interface, the nested class is declared implicitly public and static.
Static nested classes can be declared abstract or final.
Static nested classes can extend another class or it can be used as a base class.
Static nested classes can have static members.
Static nested classes can access the members of the outer class (only static members, obviously).
The outer class can also access the members (even private members) of the nested class through an object of nested class. If you don’t declare an instance of the nested class, the outer class cannot access nested class elements directly.
Ans. The accessibility (public, protected, etc.) of the inner class is defined by the outer class.
Just like top-level classes, an inner class can extend a class or can implement interfaces. Similarly, an inner class can be extended by other classes, and an inner interface can be implemented or extended by other classes or interfaces.
An inner class can be declared final or abstract.
Inner classes can have inner classes, but you’ll have a hard time reading or understanding such complex nesting of classes.
Just like top-level classes, an inner class can extend a class or can implement interfaces. Similarly, an inner class can be extended by other classes, and an inner interface can be implemented or extended by other classes or interfaces.
An inner class can be declared final or abstract.
Inner classes can have inner classes, but you’ll have a hard time reading or understanding such complex nesting of classes.
Ans. You can create a non-static local class inside a body of code. Interfaces cannot have local classes, and you cannot create local interfaces.
Local classes are accessible only from the body of the code in which the class is defined. The local classes are completely inaccessible outside the body of the code in which the class is defined.
You can extend a class or implement interfaces while defining a local class.
A local class can access all the variables available in the body of the code in which it is defined. You can pass only final variables to a local inner class.
Local classes are accessible only from the body of the code in which the class is defined. The local classes are completely inaccessible outside the body of the code in which the class is defined.
You can extend a class or implement interfaces while defining a local class.
A local class can access all the variables available in the body of the code in which it is defined. You can pass only final variables to a local inner class.
Ans. Anonymous classes are defined in the new expression itself, so you cannot create multiple objects of an anonymous class.
You cannot explicitly extend a class or explicitly implement interfaces when defining an anonymous class.
An anonymous inner class is always created as part of a statement; don't forget to close the statement after the class definition with a curly brace. This is a rare case in Java, a curly brace followed by a semicolon.
Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface
You cannot explicitly extend a class or explicitly implement interfaces when defining an anonymous class.
An anonymous inner class is always created as part of a statement; don't forget to close the statement after the class definition with a curly brace. This is a rare case in Java, a curly brace followed by a semicolon.
Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface
Ans. That would not be a problem as both are specifying the contract that implement class has to follow.
If class C implement interface A & interface B then Class C thing I need to implement print() because of interface A then again Class think I need to implement print() again because of interface B, it sees that there is already a method called test() implemented so it's satisfied.
If class C implement interface A & interface B then Class C thing I need to implement print() because of interface A then again Class think I need to implement print() again because of interface B, it sees that there is already a method called test() implemented so it's satisfied.
Ans. Arrays provide a structure wherein multiple values can be accessed using single reference and index. This helps in iterating over the values using loops.
Ans. Arrays are of fixed size and have to reserve memory prior to use. Hence if we don't know size in advance arrays are not recommended to use.
Arrays can store only homogeneous elements.
Arrays store its values in contentious memory location. Not suitable if the content is too large and needs to be distributed in memory.
There is no underlying data structure for arrays and no ready made method support for arrays, for every requriment we need to code explicitly
Arrays can store only homogeneous elements.
Arrays store its values in contentious memory location. Not suitable if the content is too large and needs to be distributed in memory.
There is no underlying data structure for arrays and no ready made method support for arrays, for every requriment we need to code explicitly
Ans. Class.getInstance doesn't call the constructor whereas if we create an object using new operator , we need to have a matching constructor or copiler should provide a default constructor.
Q245. Can we create an object if a Class doesn't have any constructor ( not even the default provided by constructor ) ?show Answer
Ans. Yes , using Class.getInstance.
Ans. It is not having any method because it is a MARKER interface.
Ans. When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
Q248. Are there any global variables in Java, which can be accessed by other part of your program?show Answer
Ans. No. Global variables are not allowed as it wont fit good with the concept of encapsulation.
Ans. Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.
Lifecycle methods of Applet -
init( ) method - Can be called when an applet is first loaded
start( ) method - Can be called each time an applet is started
paint( ) method - Can be called when the applet is minimized or maximized
stop( ) method - Can be used when the browser moves off the applet's page
destroy( ) method - Can be called when the browser is finished with the applet
Lifecycle methods of Applet -
init( ) method - Can be called when an applet is first loaded
start( ) method - Can be called each time an applet is started
paint( ) method - Can be called when the applet is minimized or maximized
stop( ) method - Can be used when the browser moves off the applet's page
destroy( ) method - Can be called when the browser is finished with the applet
Ans. Controls are components that allow a user to interact with your application and SWT / AWT supports the following types of controls:
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components.
These controls are subclasses of Component.
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components.
These controls are subclasses of Component.
Ans. A Stream is an abstraction that either produces or consumes information. There are two types of Streams :
Byte Streams: Provide a convenient means for handling input and output of bytes.
Character Streams: Provide a convenient means for handling input & output of characters.
Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream.
Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.
Byte Streams: Provide a convenient means for handling input and output of bytes.
Character Streams: Provide a convenient means for handling input & output of characters.
Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream.
Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.
Ans. Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are:
User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password
Hidden form fields - fields are added to an HTML form that are not displayed in the client's browser. When the form containing the fields is submitted, the fields are sent back to the server
URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change.
Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser.
HttpSession- places a limit on the number of sessions that can exist in memory.
User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password
Hidden form fields - fields are added to an HTML form that are not displayed in the client's browser. When the form containing the fields is submitted, the fields are sent back to the server
URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change.
Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser.
HttpSession- places a limit on the number of sessions that can exist in memory.
Ans. It's a technique to allow multiple clients to make use of a cached set of shared and reusable connection objects providing access to a database or other resource.
Ans. Collections are re-sizable in nature. We can increase or decrease the size as per recruitment.
Collections can hold both homogeneous and heterogeneous data's.
Every collection follows some standard data structures.
Collection provides many useful built in methods for traversing,sorting and search.
Collections can hold both homogeneous and heterogeneous data's.
Every collection follows some standard data structures.
Collection provides many useful built in methods for traversing,sorting and search.
Ans. Collections can only hold objects, It can't hold primitive data types.
Collections have performance overheads as they deal with objects and offer dynamic memory expansion. This dynamic expansion could be a bigger overhead if the collection class needs consecutive memory location like Vectors.
Collections doesn't allow modification while traversal as it may lead to concurrentModificationException.
Collections have performance overheads as they deal with objects and offer dynamic memory expansion. This dynamic expansion could be a bigger overhead if the collection class needs consecutive memory location like Vectors.
Collections doesn't allow modification while traversal as it may lead to concurrentModificationException.
Ans. Yes.
Ans. No.
Ans. Float can represent up to 7 digits accurately after decimal point, where as double can represent up to 15 digits accurately after decimal point.
Ans. Both bitwise right shift operator ( >> ) and bitwise zero fill right shift operator ( >>> ) are used to shift the bits towards right. The difference is that >> will protect the sign bit whereas the >>> operator will not protect the sign bit. It always fills 0 in the sign bit.
Ans. System.out and System.err both represent the monitor by default and hence can be used to send data or results to the monitor. But System.out is used to display normal messages and results whereas System.err is used to display error messages and System.in represents InputStream object, which by default represents standard input device, i.e., keyboard.
Ans. Yes, it is possible by using a static block in the Java program.
Ans. Using new operator - new xyzClass()
Using factory methods - xyzFactory.getInstance( )
Using newInstance( ) method - (Class.forName(“xyzClass”))emp.newInstance( )
By cloning an already available object - (xyzClass)obj1.clone( )
Using factory methods - xyzFactory.getInstance( )
Using newInstance( ) method - (Class.forName(“xyzClass”))emp.newInstance( )
By cloning an already available object - (xyzClass)obj1.clone( )
Ans. Generalization or UpCasting is a phenomenon where a sub class is prompted to a super class, and hence becomes more general. Generalization needs widening or up-casting. Specialization or DownCasting is a phenomenon where a super class is narrowed down to a sub class. Specialization needs narrowing or down-casting.
Ans. Yes, We can call garbage collector of JVM to delete any unused variables and unreferenced objects from memory using gc( ) method. This gc( ) method appears in both Runtime and System classes of java.lang package.
Ans. Volatile is an instruction that the variables can be accessed by multiple threads and hence shouldn't be cached. As volatile variables are never cached and hence their retrieval cannot be optimized.
Ans. Open ended Questions.
Ans. Open ended Questions.
Ans. Open ended Questions.
Q269. Should good code be self-documenting, or is it the responsibility of the developer to document it?show Answer
Ans. Open ended Questions.
Q270. What are points to consider in terms of access modifier when we are overriding any method?show Answer
Ans. 1. Overriding method can not be more restrictive than the overridden method.
reason : in case of polymorphism , at object creation jvm look for actual runtime object. jvm does not look for reference type and while calling methods it look for overridden method.
If by means subclass were allowed to change the access modifier on the overriding method, then suddenly at runtime—when the JVM invokes the true object's version of the method rather than the reference type's version then it will be problematic
2. In case of subclass and superclass define in different package, we can override only those method which have public or protected access.
3. We can not override any private method because private methods can not be inherited and if method can not be inherited then method can not be overridden.
reason : in case of polymorphism , at object creation jvm look for actual runtime object. jvm does not look for reference type and while calling methods it look for overridden method.
If by means subclass were allowed to change the access modifier on the overriding method, then suddenly at runtime—when the JVM invokes the true object's version of the method rather than the reference type's version then it will be problematic
2. In case of subclass and superclass define in different package, we can override only those method which have public or protected access.
3. We can not override any private method because private methods can not be inherited and if method can not be inherited then method can not be overridden.
Ans. co-variant return type states that return type of overriding method can be subtype of the return type declared in method of superclass. it has been introduced since jdk 1.5
Ans. 1)The overriding methods can throw any runtime Exception , here in the case of runtime exception overriding method (subclass method) should not worry about exception being thrown by superclass method.
2)If superclass method does not throw any exception then while overriding, the subclass method can not throw any new checked exception but it can throw any runtime exception
3) Different exceptions in java follow some hierarchy tree(inheritance). In this case , if superclass method throws any checked exception , then while overriding the method in subclass we can not throw any new checked exception or any checked exception which are higher in hierarchy than the exception thrown in superclass method
2)If superclass method does not throw any exception then while overriding, the subclass method can not throw any new checked exception but it can throw any runtime exception
3) Different exceptions in java follow some hierarchy tree(inheritance). In this case , if superclass method throws any checked exception , then while overriding the method in subclass we can not throw any new checked exception or any checked exception which are higher in hierarchy than the exception thrown in superclass method
Ans. Java is a portable-language because without any modification we can use Java byte-code in any platform(which supports Java). So this byte-code is portable and we can use in any other major platforms.
Ans. Java was initially found in 1991 by James Gosling, Sun Micro Systems. At first it was called as "Oak". In 1995 then it was later renamed to "Java". java is a originally a platform independent language. Currently Oracle, America owns Java.
Ans. You can find JVM - 32 bit or 64 bit by using System.getProperty() from Java program.
Ans. No. Every Class only needs to have one constructor - With parameters or without parameters. Compiler provides a default non parameterized constructor if no constructors is defined.
Ans. throw is used to explicitly throw an exception especially custom exceptions, whereas throws is used to declare that the method can throw an exception.
We cannot throw multiple exceptions using throw statement but we can declare that a method can throw multiple exceptions using throws and comma separator.
We cannot throw multiple exceptions using throw statement but we can declare that a method can throw multiple exceptions using throws and comma separator.
Ans. No. Even though "this" would mean a reference to current object id the method gets called using object reference but "this" would mean an ambiguity if the same static method gets called using Class name.
Ans. Both belong to the class as a whole and not to the individual objects. Static methods are explicitly called for execution whereas Static block gets executed when the Class gets loaded by the JVM.
Ans. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc
Ans. Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that turns Java bytecode into instructions that can be sent directly to the processor.
Ans. IDE stands of Integrated Development Environment. Few Java IDE's are WSAD ( Websphhere Application Developer ) , RAD ( Rational Application Developer ) , Eclipse and Netbeans.
Ans. Object is a run time entity whose state is stored in fields and behavior is shown via methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.
Ans. A class is a blue print or Mold using which individual objects are created. A class can contain fields and methods to describe the behavior of an object.
Q285. According to Java Operator precedence, which operator is considered to be with highest precedence?show Answer
Ans. Postfix operators i.e () [] . is at the highest precedence.
Ans. Variables used in a switch statement can only be a byte, short, int, or char.
Ans. The Exception class has two main subclasses : IOException class and RuntimeException Class.
Ans. The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.
Ans. All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
You want to write a runtime exception, you need to extend the RuntimeException class.
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
You want to write a runtime exception, you need to extend the RuntimeException class.
Ans. It 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.
Ans. It is a collection of element which cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.
Q292. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?show Answer
Ans. The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented
Ans. It is part of the analysis of a program and describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance.
Ans. The = operator is right associative.
Ans. Break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
Ans. The purpose of the System class is to provide access to system resources.
Ans. The default value of the boolean type is false.
Ans. Yes
Q299. What will happen if static modifier is removed from the signature of the main method?show Answer
Ans. Program throws "NoSuchMethodError" error at runtime .
Ans. The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region
Ans. It refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.
Ans. Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. It cause low network traffic.
Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.
Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.
Q303. What environment variables do I need to set on my machine in order to be able to run Java programs?show Answer
Ans. CLASSPATH and PATH are the two variables.
Ans. Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism.
Ans. The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.
Ans. An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It allows sequential access to all the elements stored in the collection.
Ans. A child object constructor always first needs to construct its parent. In Java it is done via an implicit call to the no-args constructor as the first statement
Q308. What is the best practice configuration usage for files - pom.xml or settings.xml ?show Answer
Ans. The best practice guideline between settings.xml and pom.xml is that configurations in settings.xml must be specific to the current user and that pom.xml configurations are specific to the project.
Ans. At the beginning of an object's life, the Java virtual machine (JVM) allocates memory on the heap to accommodate the object's instance variables. When that memory is first allocated, however, the data it contains is unpredictable. If the memory were used as is, the behavior of the object would also be unpredictable. To guard against such a scenario, Java makes certain that memory is initialized, at least to predictable default values before it is used by any code.
Q310. In a case where there are no instance variables what does the default constructor initialize?show Answer
Ans. Java expects the superclass ( Object Class ) constructor to be called while creation of any object. So super constructor is called in case there are no instance variables to initialize.
Q311. How can I change the default location of the generated jar when I command "mvn package"?show Answer
Ans. By default, the location of the generated jar is in ${project.build.directory} or in your target directory. We can change this by configuring the outputDirectory of maven-jar-plugin.
Ans. 1. parent pom
2. project pom
3. settings
4. CLI parameters
2. project pom
3. settings
4. CLI parameters
Ans. A mojo is a Maven plain Old Java Object. Each mojo is an executable goal in Maven, and a plugin is a distribution of one or more related mojos.
Ans. run mvn -X
Ans. Data Hiding is a broader concept. Encapsulation is a OOP's centri concept which is a way of data hiding in OOP's.
Ans. Implementation Hiding is a broader concept. Abstraction is a way of implementation hiding in OOP's.
Ans. Combine the data of our application and its manipulation at one place.
Encapsulation Allow the state of an object to be accessed and modified through behaviors.
Reduce the coupling of modules and increase the cohesion inside them.
Encapsulation Allow the state of an object to be accessed and modified through behaviors.
Reduce the coupling of modules and increase the cohesion inside them.
Ans. function calling - hides implementation details
wrapper classes
new operator - Creates object in memory, calls constructor
wrapper classes
new operator - Creates object in memory, calls constructor
Ans. String str = new String("abc");
String str1 = "abc";
When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.
String str1 = "abc";
When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.
When we use new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.
Ans. private static boolean isPalindrome(String str) {
if (str == null)
return false;
StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
return strBuilder.toString().equals(str);
}
if (str == null)
return false;
StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
return strBuilder.toString().equals(str);
}
Ans. private static String removeChar(String str, char c) {
if (str == null)
return null;
return str.replaceAll(Character.toString(c), "");
}
if (str == null)
return null;
return str.replaceAll(Character.toString(c), "");
}
Ans. toUpperCase and toLowerCase
Ans. We can use String getBytes() method to convert String to byte array and we can use String constructor new String(byte[] arr) to convert byte array to String.
Ans. String is immutable in java and stored in String pool. Once it’s created it stays in the pool until unless garbage collected, so even though we are done with password it’s available in memory for longer duration and there is no way to avoid it. It’s a security risk because anyone having access to memory dump can find the password as clear text.
Ans. Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.
Ans. getters and setters methods are used to store and manipulate the private variables in java beans. A getters as it has name, suggest retrieves the attribute of the same name. A setters are allows you to set the values of the attributes.
Q327. public class a {
public static void main(String args[]){
final String s1="job";
final String s2="seeker";
String s3=s1.concat(s2);
String s4="jobseeker";
System.out.println(s3==s4); // Output 1
System.out.println(s3.hashCode()==s4.hashCode()); Output 2
}
}
What will be the Output 1 and Output 2 ?show Answer
public static void main(String args[]){
final String s1="job";
final String s2="seeker";
String s3=s1.concat(s2);
String s4="jobseeker";
System.out.println(s3==s4); // Output 1
System.out.println(s3.hashCode()==s4.hashCode()); Output 2
}
}
What will be the Output 1 and Output 2 ?show Answer
Ans. S3 and S4 are pointing to different memory location and hence Output 1 will be false.
Hash code is generated to be used as hash key in some of the collections in Java and is calculated using string characters and its length. As they both are same string literals, and hence their hashcode is same.Output 2 will be true.
Hash code is generated to be used as hash key in some of the collections in Java and is calculated using string characters and its length. As they both are same string literals, and hence their hashcode is same.Output 2 will be true.
Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc.
Ans. Inheritance means a object inheriting reusable properties of the base class. Compositions means that an abject holds other objects.
In Inheritance there is only one object in memory ( derived object ) whereas in Composition , parent object holds references of all composed objects.
From Design perspective - Inheritance is "is a" relationship among objects whereas Composition is "has a" relationship among objects.
In Inheritance there is only one object in memory ( derived object ) whereas in Composition , parent object holds references of all composed objects.
From Design perspective - Inheritance is "is a" relationship among objects whereas Composition is "has a" relationship among objects.
Ans. The only time finally won't be called is if you call System.exit() or if the JVM crashes first.
Q331. Will the static block be executed in the following code ? Why ?
class Test
{
static
{
System.out.println("Why I am not executing ");
}
public static final int param=20;
}
public class Demo
{
public static void main(String[] args)
{
System.out.println(Test.param);
}
}show Answer
class Test
{
static
{
System.out.println("Why I am not executing ");
}
public static final int param=20;
}
public class Demo
{
public static void main(String[] args)
{
System.out.println(Test.param);
}
}show Answer
Ans. No the static block won't get executed as the referenced variable in the Test class is final. Compiler replaces the content of the final variable within Demo.main method and hence actually no reference to Test class is made.
Q332. Will static block for Test Class execute in the following code ?
class Test
{
static
{
System.out.println("Executing Static Block.");
}
public final int param=20;
public int getParam(){
return param;
}
}
public class Demo
{
public static void main(String[] args)
{
System.out.println(new Test().param);
}
}show Answer
class Test
{
static
{
System.out.println("Executing Static Block.");
}
public final int param=20;
public int getParam(){
return param;
}
}
public class Demo
{
public static void main(String[] args)
{
System.out.println(new Test().param);
}
}show Answer
Ans. Yes.
Ans. intern() method keeps the string in an internal cache that is usually not garbage collected.
Q334. Will the following program display "Buggy Bread" ?
class Test{
static void display(){
System.out.println("Buggy Bread");
}
}
class Demo{
public static void main(String... args){
Test t = null;
t.display();
}
}show Answer
class Test{
static void display(){
System.out.println("Buggy Bread");
}
}
class Demo{
public static void main(String... args){
Test t = null;
t.display();
}
}show Answer
Ans. Yes. static method is not accessed by the instance of class. Either you call it by the class name or the reference.
Ans. substring method would build a new String object keeping a reference to the whole char array, to avoid copying it. Hence you can inadvertently keep a reference to a very big character array with just a one character string.
Ans. Using String method -
new StringBuffer(str).reverse().toString();
Iterative -
public static String getReverseString(String str){
StringBuffer strBuffer = new StringBuffer(str.length);
for(int counter=str.length -1 ; counter>=0;counter--){
strBuffer.append(str.charAt(counter));
}
return strBuffer;
}
Recursive -
public static String getReverseString(String str){
if(str.length <= 1){
return str;
}
return (getReverseString(str.subString(1)) + str.charAt(0);
}
new StringBuffer(str).reverse().toString();
Iterative -
public static String getReverseString(String str){
StringBuffer strBuffer = new StringBuffer(str.length);
for(int counter=str.length -1 ; counter>=0;counter--){
strBuffer.append(str.charAt(counter));
}
return strBuffer;
}
Recursive -
public static String getReverseString(String str){
if(str.length <= 1){
return str;
}
return (getReverseString(str.subString(1)) + str.charAt(0);
}
Q337. If you have access to a function that returns a random integer from one to five, write another function which returns a random integer from one to seven.show Answer
Ans. We can do that by pulling binary representation using 3 bits ( random(2) ).
getRandom7() {
String binaryStr = String.valuesOf(random(2))+String.valuesOf(random(2))+String.valuesOf(random(2));
binaryInt = Integer.valueOf(binaryStr);
int sumValue=0;
int multiple = 1;
while(binaryInt > 0){
binaryDigit = binaryInt%10;
binaryInt = binaryInt /10;
sumValue = sumValue + (binaryDigit * multiple);
multiple = multiple * 2;
}
}
getRandom7() {
String binaryStr = String.valuesOf(random(2))+String.valuesOf(random(2))+String.valuesOf(random(2));
binaryInt = Integer.valueOf(binaryStr);
int sumValue=0;
int multiple = 1;
while(binaryInt > 0){
binaryDigit = binaryInt%10;
binaryInt = binaryInt /10;
sumValue = sumValue + (binaryDigit * multiple);
multiple = multiple * 2;
}
}
Ans. convert(int binaryInt) {
int sumValue=0;
int multiple = 1;
while(binaryInt > 0){
binaryDigit = binaryInt%10;
binaryInt = binaryInt /10;
sumValue = sumValue + (binaryDigit * multiple);
multiple = multiple * 2;
}
return sumValue;
}
int sumValue=0;
int multiple = 1;
while(binaryInt > 0){
binaryDigit = binaryInt%10;
binaryInt = binaryInt /10;
sumValue = sumValue + (binaryDigit * multiple);
multiple = multiple * 2;
}
return sumValue;
}
Q339. What will the following code print ?
String s1 = "Buggy Bread";
String s2 = "Buggy Bread";
if(s1 == s2)
System.out.println("equal 1");
String n1 = new String("Buggy Bread");
String n2 = new String("Buggy Bread");
if(n1 == n2)
System.out.println("equal 2"); show Answer
String s1 = "Buggy Bread";
String s2 = "Buggy Bread";
if(s1 == s2)
System.out.println("equal 1");
String n1 = new String("Buggy Bread");
String n2 = new String("Buggy Bread");
if(n1 == n2)
System.out.println("equal 2"); show Answer
Ans. equal 1
Ans. new operator is used to statically create an instance of object. newInstance() is used to create an object dynamically ( like if the class name needs to be picked from configuration file ). If you know what class needs to be initialized , new is the optimized way of instantiating Class.
Ans. Java bytecode is the instruction set of the Java virtual machine. Each bytecode is composed by one, or two bytes that represent the instruction, along with zero or more bytes for passing parameters.
Q342. How to find whether a given integer is odd or even without use of modules operator in java?show Answer
Ans. public static void main(String ar[])
{
int n=5;
if((n/2)*2==n)
{
System.out.println("Even Number ");
}
else
{
System.out.println("Odd Number ");
}
}
}
{
int n=5;
if((n/2)*2==n)
{
System.out.println("Even Number ");
}
else
{
System.out.println("Odd Number ");
}
}
}
Ans. Yes and No. JVM is an extra layer that translates Byte Code into Machine Code. So Comparing to languages like C, Java provides an additional layer of translating the Source Code.
C++ Compiler - Source Code --> Machine Code
Java Compiler - Source Code --> Byte Code , JVM - Byte Code --> Machine Code
Though it looks like an overhead but this additional translation allows Java to run Apps on all platforms as JVM provides the translation to the Machine code as per the underlying Operating System.
C++ Compiler - Source Code --> Machine Code
Java Compiler - Source Code --> Byte Code , JVM - Byte Code --> Machine Code
Though it looks like an overhead but this additional translation allows Java to run Apps on all platforms as JVM provides the translation to the Machine code as per the underlying Operating System.
Ans. We need to access values on the basis of an index in Binary search which is not possible with Sets.
Ans. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system. Its called Byte Code because each instruction is of 1-2 bytes.
Sample instructions in Byte Code -
1: istore_1
2: iload_1
3: sipush 1000
6: if_icmpge 44
9: iconst_2
10: istore_2
Sample instructions in Byte Code -
1: istore_1
2: iload_1
3: sipush 1000
6: if_icmpge 44
9: iconst_2
10: istore_2
Ans. LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically resizing array.
Q347. If you are given a choice to use either ArrayList and LinkedList, Which one would you use and Why ?show Answer
Ans. ArrayList are implemented in memory as arrays and hence allows fast retrieval through indices but are costly if new elements are to be inserted in between other elements.
LinkedList allows for constant-time insertions or removals using iterators, but only sequential access of elements
1. Retrieval - If Elements are to be retrieved sequentially only, Linked List is preferred.
2. Insertion - If new Elements are to be inserted in between other elements , Array List is preferred.
3. Search - Binary Search and other optimized way of searching is not possible on Linked List.
4. Sorting - Initial sorting could be pain but lateral addition of elements in a sorted list is good with linked list.
5. Adding Elements - If sufficiently large elements needs to be added very frequently ,Linked List is preferable as elements don't need consecutive memory location.
LinkedList allows for constant-time insertions or removals using iterators, but only sequential access of elements
1. Retrieval - If Elements are to be retrieved sequentially only, Linked List is preferred.
2. Insertion - If new Elements are to be inserted in between other elements , Array List is preferred.
3. Search - Binary Search and other optimized way of searching is not possible on Linked List.
4. Sorting - Initial sorting could be pain but lateral addition of elements in a sorted list is good with linked list.
5. Adding Elements - If sufficiently large elements needs to be added very frequently ,Linked List is preferable as elements don't need consecutive memory location.
Ans. 1. Collection should have an index for random access.
2. Collection should have ordered elements.
2. Collection should have ordered elements.
Q349. Can you provide some implementation of a Dictionary having large number of words ? show Answer
Ans. Simplest implementation we can have is a List wherein we can place ordered words and hence can perform Binary Search.
Other implementation with better search performance is to use HashMap with key as first character of the word and value as a LinkedList.
Further level up, we can have linked Hashmaps like ,
hashmap {
a ( key ) -> hashmap (key-aa , value (hashmap(key-aaa,value)
b ( key ) -> hashmap (key-ba , value (hashmap(key-baa,value)
....................................................................................
z( key ) -> hashmap (key-za , value (hashmap(key-zaa,value)
}
upto n levels ( where n is the average size of the word in dictionary.
Other implementation with better search performance is to use HashMap with key as first character of the word and value as a LinkedList.
Further level up, we can have linked Hashmaps like ,
hashmap {
a ( key ) -> hashmap (key-aa , value (hashmap(key-aaa,value)
b ( key ) -> hashmap (key-ba , value (hashmap(key-baa,value)
....................................................................................
z( key ) -> hashmap (key-za , value (hashmap(key-zaa,value)
}
upto n levels ( where n is the average size of the word in dictionary.
Ans. PATH is the variable that holds the directories for the OS to look for executables. CLASSPATH is the variable that holds the directories for JVM to look for .class files ( Byte Code ).
Ans. private , public and protected are access modifiers.
final and abstract are non access modifiers.
final and abstract are non access modifiers.
Q352. Which Java collection class can be used to maintain the entries in the order in which they were last accessed?show Answer
Ans. LinkedHashMap
Ans. No, Generic parameters cannot be primitives.
Q354. Which of the following syntax is correct ?
import static java.lang.System.*;
or
static import java.lang.System.*;show Answer
import static java.lang.System.*;
or
static import java.lang.System.*;show Answer
Ans. import static java.lang.System.*;
Q355. What will be the output of following code ?
public static void main(String[] args)
{
int x = 10;
int y;
if (x < 100) y = x / 0;
if (x >= 100) y = x * 0;
System.out.println("The value of y is: " + y);
}show Answer
public static void main(String[] args)
{
int x = 10;
int y;
if (x < 100) y = x / 0;
if (x >= 100) y = x * 0;
System.out.println("The value of y is: " + y);
}show Answer
Ans. The code will not compile raising an error that the local variable y might not have been initialized. Unlike member variables, local variables are not automatically initialized to the default values for their declared type.
Q356. What will be the output of following Code ?
class BuggyBread {
public static void main(String[] args)
{
String s2 = "I am unique!";
String s5 = "I am unique!";
System.out.println(s2 == s5);
}
}show Answer
class BuggyBread {
public static void main(String[] args)
{
String s2 = "I am unique!";
String s5 = "I am unique!";
System.out.println(s2 == s5);
}
}show Answer
Ans. true, due to String Pool, both will point to a same String object.
Q357. What will be the output of following code ?
class BuggyBread2 {
private static int counter = 0;
void BuggyBread2() {
counter = 5;
}
BuggyBread2(int x){
counter = x;
}
public static void main(String[] args) {
BuggyBread2 bg = new BuggyBread2();
System.out.println(counter);
}
}show Answer
class BuggyBread2 {
private static int counter = 0;
void BuggyBread2() {
counter = 5;
}
BuggyBread2(int x){
counter = x;
}
public static void main(String[] args) {
BuggyBread2 bg = new BuggyBread2();
System.out.println(counter);
}
}show Answer
Ans. Compile time error as it won't find the constructor matching BuggyBread2(). Compiler won't provide default no argument constructor as programmer has already defined one constructor. Compiler will treat user defined BuggyBread2() as a method, as return type ( void ) has been specified for that.
Q358. What will be the output of following code ?
class BuggyBread1 {
public String method() {
return "Base Class - BuggyBread1";
}
}
class BuggyBread2 extends BuggyBread1{
private static int counter = 0;
public String method(int x) {
return "Derived Class - BuggyBread2";
}
public static void main(String[] args) {
BuggyBread1 bg = new BuggyBread2();
System.out.println(bg.method());
}
}show Answer
class BuggyBread1 {
public String method() {
return "Base Class - BuggyBread1";
}
}
class BuggyBread2 extends BuggyBread1{
private static int counter = 0;
public String method(int x) {
return "Derived Class - BuggyBread2";
}
public static void main(String[] args) {
BuggyBread1 bg = new BuggyBread2();
System.out.println(bg.method());
}
}show Answer
Ans. Base Class - BuggyBread1
Though Base Class handler is having the object of Derived Class but its not overriding as now with a definition having an argument ,derived class will have both method () and method (int) and hence its overloading.
Though Base Class handler is having the object of Derived Class but its not overriding as now with a definition having an argument ,derived class will have both method () and method (int) and hence its overloading.
Ans. REST or Representational State Transfer is a flexible architecture style for creating web services that recommends the following guidelines -
1. http for client server communication,
2. XML / JSON as formatiing language ,
3. Simple URI as address for the services and,
4. stateless communication.
1. http for client server communication,
2. XML / JSON as formatiing language ,
3. Simple URI as address for the services and,
4. stateless communication.
Ans. XML and JSON ( Javascript Object Notation ).
Ans. Inner join is the intersection of two tables on a particular columns whereas Outer Join is the Union of two tables.
Ans. It's a facility that allows traversal over the records pulled from a table or combination of tables. Its like iterator in Java.
Ans. When multiple external resources are trying to access the DB locks and runs into cyclic wait, it may makes the DB unresponsive.
Deadlock can be avoided using variety of measures, Few listed below -
Can make a queue wherein we can verify and order the request to DB.
Less use of cursors as they lock the tables for long time.
Keeping the transaction smaller.
Deadlock can be avoided using variety of measures, Few listed below -
Can make a queue wherein we can verify and order the request to DB.
Less use of cursors as they lock the tables for long time.
Keeping the transaction smaller.
Ans. These are the tables that are created temporarily and are deleted once the Stored Procedure is complete.
For example - we may like to pull some info from a table and then do some operations on that data and then store the output in final output table. We can store the intermediary values in a temp table and once we have final output with us, we can just delete it.
For example - we may like to pull some info from a table and then do some operations on that data and then store the output in final output table. We can store the intermediary values in a temp table and once we have final output with us, we can just delete it.
Ans. With the advent of Internet, HTTP is the most preferred way of communication. Most of the clients ( web thin client , web thick clients , mobile apps ) are designed to communicate using http only. Web Services using http makes them accessible from vast variety of client applications.
Q366. what will be the output of this code ?
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Buggy");
test(s1);
System.out.println(s1);
}
private static void test(StringBuffer s){
s.append("Bread");
}show Answer
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Buggy");
test(s1);
System.out.println(s1);
}
private static void test(StringBuffer s){
s.append("Bread");
}show Answer
Ans. BuggyBread
Q367. what will be the output of this code ?
public static void main(String[] args)
{
String s1=new String("Buggy");
test(s1);
System.out.println(s1);
}
private static void test(StringBuffer s){
s.append("Bread");
}show Answer
public static void main(String[] args)
{
String s1=new String("Buggy");
test(s1);
System.out.println(s1);
}
private static void test(StringBuffer s){
s.append("Bread");
}show Answer
Ans. Buggy
Q368. what will be the output of this code ?
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Buggy");
test(s1);
System.out.println(s1);
}
private static void test(StringBuffer s){
s=new StringBuffer("Bread");
}show Answer
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Buggy");
test(s1);
System.out.println(s1);
}
private static void test(StringBuffer s){
s=new StringBuffer("Bread");
}show Answer
Ans. Buggy
Q369. what will be the output ?
class Animal {
public void eat() throws Exception {
}
}
class Dog2 extends Animal {
public void eat(){}
public static void main(){
Animal an = new Dog2();
an.eat();
}
}show Answer
class Animal {
public void eat() throws Exception {
}
}
class Dog2 extends Animal {
public void eat(){}
public static void main(){
Animal an = new Dog2();
an.eat();
}
}show Answer
Ans. Compile Time Error: Unhandled exception type Exception
Ans. Better Performance as Servlets doesn't require a separate process for a single request.
Servlets are platform independent as they are written in Java.
Servlets are platform independent as they are written in Java.
Ans. gfhhhhhhhhhhhhhhhhhhhhf
Ans. Yes , we can have null values for columns in SQL. Null value represent that the columns value is unknown or haven't been filled. Yes, We can use it within where clause to get the rows with null values.
Q373. Can we add duplicate keys in a HashMap ? What will happen if we attempt to add duplicate values ?show Answer
Ans. No, We cannot have duplicate keys in HashMap. If we attempt to do so , the previous value for the key is overwritten.
Ans. http protocol on its own is stateless. So it helps in identifying the relationship between multiple stateless request as they come from a single source.
Q375. Why using cookie to store session info is a better idea than just using session info in the request ?show Answer
Ans. Session info in the request can be intercepted and hence a vulnerability. Cookie can be read and write by respective domain only and make sure that right session information is being passed by the client.
Ans. Session cookies , which are deleted once the session is over.
Permanent cookies , which stays at client PC even if the session is disconnected.
Permanent cookies , which stays at client PC even if the session is disconnected.
Ans. stateless
Ans. Yes.
Ans. Yes
Q380. Which of the following is a canonical path ?
1. C:\directory\..\directory\file.txt
2. C:\directory\subDirectory1\directory\file.txt
3. \directory\file.txtshow Answer
1. C:\directory\..\directory\file.txt
2. C:\directory\subDirectory1\directory\file.txt
3. \directory\file.txtshow Answer
Ans. 2nd
Q381. What will the following code print when executed on Windows ?
public static void main(String[] args){
String parent = null;
File file = new File("/file.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer
public static void main(String[] args){
String parent = null;
File file = new File("/file.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer
Ans. \file.txt
C:\file.txt
C:\file.txt
C:\file.txt
C:\file.txt
Q382. What will be the output of following code ?
public static void main(String[] args){
String name = null;
File file = new File("/folder", name);
System.out.print(file.exists());
}show Answer
public static void main(String[] args){
String name = null;
File file = new File("/folder", name);
System.out.print(file.exists());
}show Answer
Ans. NullPointerException at line:
"File file = new File("/folder", name);"
"File file = new File("/folder", name);"
Q383. What will be the output of following code ?
public static void main(String[] args){
String parent = null;
File file = new File(parent, "myfile.txt");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer
public static void main(String[] args){
String parent = null;
File file = new File(parent, "myfile.txt");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer
Ans. It will create the file myfile.txt in the current directory.
Q384. What will be the output of following code ?
public static void main(String[] args){
String child = null;
File file = new File("/folder", child);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer
public static void main(String[] args){
String child = null;
File file = new File("/folder", child);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer
Ans. NullPointerException at line:
File file = new File("/folder", child);
File file = new File("/folder", child);
Q385. What will be the output of following code, assuming that currently we are in c:\Project ?
public static void main(String[] args){
String child = null;
File file = new File("../file.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer
public static void main(String[] args){
String child = null;
File file = new File("../file.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer
Ans. ..\file.txt
C:\Workspace\Project\..\file.txt
C:\Workspace\file.txt
C:\Workspace\Project\..\file.txt
C:\Workspace\file.txt
Ans. OutputStreamWriter
Ans. FileReader
Ans. FileInputStream
Ans. InputStream
Q390. Which of the following code is correct ?
a.
FileWriter fileWriter = new FileWriter("../file.txt");
File file = new File(fileWriter );
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);
b.
BufferedWriter bufferedOutputWriter = new BufferedWriter("../file.txt");
File file = new File(bufferedOutputWriter );
FileWriter fileWriter = new FileWriter(file);
c.
File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);
d.
File file = new File("../file.txt");
BufferedWriter bufferedOutputWriter = new BufferedWriter(file);
FileWriter fileWriter = new FileWriter(bufferedOutputWriter );show Answer
a.
FileWriter fileWriter = new FileWriter("../file.txt");
File file = new File(fileWriter );
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);
b.
BufferedWriter bufferedOutputWriter = new BufferedWriter("../file.txt");
File file = new File(bufferedOutputWriter );
FileWriter fileWriter = new FileWriter(file);
c.
File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);
d.
File file = new File("../file.txt");
BufferedWriter bufferedOutputWriter = new BufferedWriter(file);
FileWriter fileWriter = new FileWriter(bufferedOutputWriter );show Answer
Ans. c.
File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);
File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);
Q391. Which exception should be handled in the following code ?
File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);show Answer
File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);show Answer
Ans. IOException
Q392. Which exceptions should be handled with the following code ?
FileOutputStream fileOutputStream = new FileOutputStream(new File("newFile.txt"));show Answer
FileOutputStream fileOutputStream = new FileOutputStream(new File("newFile.txt"));show Answer
Ans. FileNotFoundException
Q393. Will this code compile fine ?
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));show Answer
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));show Answer
Ans. Yes.
Q394. What is the problem with this code ?
class BuggyBread1 {
private BuggyBread2 buggybread2;
public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}show Answer
class BuggyBread1 {
private BuggyBread2 buggybread2;
public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}show Answer
Ans. Though we are trying to serialize BuggyBread1 object but we haven't declared the class to implement Serializable.
This will throw java.io.NotSerializableException upon execution.
This will throw java.io.NotSerializableException upon execution.
Q395. Will this code run fine if BuggyBread2 doesn't implement Serializable interface ?
class BuggyBread1 implements Serializable{
private BuggyBread2 buggybread2 = new BuggyBread2();
public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}show Answer
class BuggyBread1 implements Serializable{
private BuggyBread2 buggybread2 = new BuggyBread2();
public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}show Answer
Ans. No, It will throw java.io.NotSerializableException.
Q396. Will this code work fine if BuggyBread2 doesn't implement Serializable ?
class BuggyBread1 extends BuggyBread2 implements Serializable{
private int x = 5;
public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}show Answer
class BuggyBread1 extends BuggyBread2 implements Serializable{
private int x = 5;
public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}show Answer
Ans. Yes.
Q397. Can we compose the Parent Class object like this ?
class BuggyBread1 extends BuggyBread2 {
private BuggyBread2 buggybread2;
public static void main(String[] args){
buggybread2 = new BuggyBread2();
}
}show Answer
class BuggyBread1 extends BuggyBread2 {
private BuggyBread2 buggybread2;
public static void main(String[] args){
buggybread2 = new BuggyBread2();
}
}show Answer
Ans. Yes.
Q398. Will this code Work ? If not , Why ?
java.util.Calendar c = new java.util.Calendar();show Answer
java.util.Calendar c = new java.util.Calendar();show Answer
Ans. No. It gives the error "Cannot Instantiate the type Calendar". Calendar is an abstract class and hence Calendar object should be instantiated using Calendar.getInstance().
Ans. Date is not a abstract class whereas Calendar is.
Q400. What will the following code print ?
java.util.Calendar c = java.util.Calendar.getInstance();
c.add(Calendar.MONTH, 5);
System.out.println(c.getTime());show Answer
java.util.Calendar c = java.util.Calendar.getInstance();
c.add(Calendar.MONTH, 5);
System.out.println(c.getTime());show Answer
Ans. Date and Time after 5 months from now.
Q401. Which of the following code is correct ?
a. DateFormat df = DateFormat.getInstance();
b. DateFormat df = DateFormat.getDateInstance();
c. DateFormat df = DateFormat.getInstance(DateFormat.FULL);
d. DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);show Answer
a. DateFormat df = DateFormat.getInstance();
b. DateFormat df = DateFormat.getDateInstance();
c. DateFormat df = DateFormat.getInstance(DateFormat.FULL);
d. DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);show Answer
Ans. All except c are correct.
Ans. It is used to parse String to get the Date Object with initialized date.
Q403. Which of the following is not a valid java.util.Locale initialization ?
a. new Locale ()
b. new Locale ( String language )
c. new Locale ( String language , String country )show Answer
a. new Locale ()
b. new Locale ( String language )
c. new Locale ( String language , String country )show Answer
Ans. a i.e new Locale()
Q404. Which of the following is not a valid NumberFormat initialization ?
a. NumberFormat.getInstance()
b. NumberFormat.getDateInstance()
c. NumberFormat.getCurrencyInstance()
d. NumberFormat.getNumberInstance()show Answer
a. NumberFormat.getInstance()
b. NumberFormat.getDateInstance()
c. NumberFormat.getCurrencyInstance()
d. NumberFormat.getNumberInstance()show Answer
Ans. b i.e NumberFormat.getDateInstance()
Q405. What will the following code print ?
public static void main(String[] args){
Integer i1 = new Integer("1");
Integer i2 = new Integer("2");
Integer i3 = Integer.valueOf("3");
int i4 = i1 + i2 + i3;
System.out.println(i4);
}show Answer
public static void main(String[] args){
Integer i1 = new Integer("1");
Integer i2 = new Integer("2");
Integer i3 = Integer.valueOf("3");
int i4 = i1 + i2 + i3;
System.out.println(i4);
}show Answer
Ans. 6
Q406. Which of the following syntax are correct ?
a. LinkedList l=new LinkedList();
b. List l=new LinkedList();
c. LinkedList l=new LinkedList();
d. List l = new LinkedList(); show Answer
a. LinkedList
b. List
c. LinkedList
d. List
Ans. c and d are correct.
Q407. Which of the following code is correct ?
a. Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).parse(str);
b. Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).format(str);
c. Date date = DateFormat.getDateInstance(DateFormat.LONG, Locale.US).parse(str);show Answer
a. Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).parse(str);
b. Date date = DateFormat.newInstance(DateFormat.LONG, Locale.US).format(str);
c. Date date = DateFormat.getDateInstance(DateFormat.LONG, Locale.US).parse(str);show Answer
Ans. c
Q408. What's wrong with this code ?
public static void main(String[] args) {
String regex = "(\\w+)*";
String s = "Java is a programming language.";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.next()) {
System.out.println("The e-mail id is: " + matcher.group());
}
}show Answer
public static void main(String[] args) {
String regex = "(\\w+)*";
String s = "Java is a programming language.";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.next()) {
System.out.println("The e-mail id is: " + matcher.group());
}
}show Answer
Ans. matcher.find() should have been used instead of matcher.next() within while.
Ans. split() and macthes()
Ans. Yes for the Wrapper class Integer but not for the primitive int.
Ans. The purpose of comparator interface is to compare objects of the same class to identify the sorting order. Sorted Collection Classes ( TreeSet, TreeMap ) have been designed such to look for this method to identify the sorting order, that is why class need to implement Comparator interface to qualify its objects to be part of Sorted Collections.
Ans. TreeSet and TreeMap
Ans. A Class must override the hashCode method if its overriding the equals method.
Ans. Collection is an interface whereas Collections is a utility class.
Ans. Statically typed
Ans. It means that the type of variables are checked at compile time in Java.The main advantage here is that all kinds of checking can be done by the compiler and hence will reduce bugs.
Ans. Using Collections.reverseOrder()
Map tree = new TreeMap(Collections.reverseOrder());
Map
Ans. Keys
Ans. As String implements Comparable, It refers to the String compareTo method to identify the order relationship among those elements.
Ans. No, Sorted collections don't allow addition of heterogeneous elements as they are not comparable.
Q421. Will it create any problem if We add elements with key as user defined object into the TreeMap ?show Answer
Ans. It won't create any problem if the objects are comparable i.e we have that class implementing Comparable interface.
Ans. No, results in exception.
Ans. Yes.
Ans. TreeMap implements NavigableMap, SortedMap, Serializable and Clonable.
Ans. No, because they are not longer required. As action classes are no more singleton in Struts 2, user inputs can be captured in action itself.
Ans. ConcurrentHashMap is a hashMap that allows concurrent modifications from multiple threads as there can be multiple locks on the same hashmap.
Q427. What is the use of double checked locking in createInstance() of Singleton class?
Double checked locking code:
public static Singleton createInstance() {
if(singleton == null){
synchronized(Singleton.class) {
if(singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
Single checked locking code:
public static Singleton createInstance() {
synchronized(Singleton.class) {
if(singleton == null) {
singleton = new Singleton();
}
}
return singleton;
}
What advantage does the first code offer compared to the second ?show Answer
Double checked locking code:
public static Singleton createInstance() {
if(singleton == null){
synchronized(Singleton.class) {
if(singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
Single checked locking code:
public static Singleton createInstance() {
synchronized(Singleton.class) {
if(singleton == null) {
singleton = new Singleton();
}
}
return singleton;
}
What advantage does the first code offer compared to the second ?show Answer
Ans. In First Case , Lock for the synchronized block will be received only if
singleton == null whereas in second case every thread will acquire the lock before executing the code.
The problem of synchronization with singleton will only happen when the object has not be instantiated. Once instantiated , the check singleton == null will always generate true and the same object will be returned and hence no problem. First condition will make sure that synchronized access ( acquiring locks ) will only take place if the object has not been created so far.
singleton == null whereas in second case every thread will acquire the lock before executing the code.
The problem of synchronization with singleton will only happen when the object has not be instantiated. Once instantiated , the check singleton == null will always generate true and the same object will be returned and hence no problem. First condition will make sure that synchronized access ( acquiring locks ) will only take place if the object has not been created so far.
Ans. 1. Methods can participate in runtime polymorphism whereas member variables cannot.
2. Validations can be performed before setting the variables.
3. If the input format changes , that can be absorbed by making change ( wrapping ) in the setter and getter.
2. Validations can be performed before setting the variables.
3. If the input format changes , that can be absorbed by making change ( wrapping ) in the setter and getter.
Ans. Yes, but the overloaded main methods without single String[] argument doesn't get any special status by the JVM. They are just another methods that needs to be called explicitly.
Ans. Singleton , Prototype , Request , Session , global-session
Ans. By Name , By Type and Constructor.
Ans. 1. First level cache is enabled by default whereas Second level cache needs to be enabled explicitly.
2. First level Cache came with Hibernate 1.0 whereas Second level cache came with Hibernate 3.0.
3. First level Cache is Session specific whereas Second level cache is shared by sessions that is why First level cache is considered local and second level cache is considered global.
2. First level Cache came with Hibernate 1.0 whereas Second level cache came with Hibernate 3.0.
3. First level Cache is Session specific whereas Second level cache is shared by sessions that is why First level cache is considered local and second level cache is considered global.
Ans. Evict() and clear(). Evist is used to clear a particular object from the cache whereas clear clears the complete local cache.
Ans. 1. EHCache ( Easy Hibernate )
2. OSCache ( Open Symphony )
3. Swarm Cache ( JBoss )
4. Tree Cache ( JBoss )
2. OSCache ( Open Symphony )
3. Swarm Cache ( JBoss )
4. Tree Cache ( JBoss )
Q435. Can we disable first level cache ? What should one do if we don't want an object to be cached ?show Answer
Ans. No.We can either call evict after the object retrieval or can use separate sessions.
Ans. 1. Configure Provider class in Hibernate configuration file.
2. Add Cache usage tag ( read-only or read-write ) in mapping files ( hbm ).
3. Create an XML file called ehcache.xml and place in classpath which contains time settings and update settings, behavior of cache , lifetime and idletime of Pojos, how many objects are allowed.
2. Add Cache usage tag ( read-only or read-write ) in mapping files ( hbm ).
3. Create an XML file called ehcache.xml and place in classpath which contains time settings and update settings, behavior of cache , lifetime and idletime of Pojos, how many objects are allowed.
Ans. Hibernate is a Java ORM Framework.
Ans. 1. No need to know SQL, RDBMS, and DB Schema.
2. Underlying Database can be changed without much effort by changing SQL dialect and DB connection.
3.Improved Performance by means of Caching.
2. Underlying Database can be changed without much effort by changing SQL dialect and DB connection.
3.Improved Performance by means of Caching.
Ans. Table Per Class , Table per Sub Class , Table per Concrete Class
Ans. It tells the framework which SQL varient to generate.
Q441. Please specify in what sequence the objects of following classes will be created ?
Session , SessionFactory, Query , Configurationshow Answer
Session , SessionFactory, Query , Configurationshow Answer
Ans. Configuration -> SessionFactory -> Session -> Query
Ans. There are 4 types of associations in Hibernate
One to One
One to Many
Many to One
Many to Many
One to One
One to Many
Many to One
Many to Many
Ans. hibernate.cfg.xml ( Main Configuration File )
and *.hbm.xml files ( Mapping Files )
and *.hbm.xml files ( Mapping Files )
Ans. HBM Files ( Mapping )
DB Connection ( DB Connection String , User Name , Password , Pool Size )
SQL Dialect ( SQL variant to be generated )
Show SQL ( Show / No show SQL on Console )
Auto Commit ( True / False )
DB Connection ( DB Connection String , User Name , Password , Pool Size )
SQL Dialect ( SQL variant to be generated )
Show SQL ( Show / No show SQL on Console )
Auto Commit ( True / False )
Ans. Configuration
SessionFactory
Session
Transaction
Query and Citeria
SessionFactory
Session
Transaction
Query and Citeria
Ans. Bag, Set , List , Array, Map
Ans. If id doesn't exist in the DB load throws an exception whereas get returns null in that case.
get makes the call to DB immediately whereas load makes the call to proxy.
get makes the call to DB immediately whereas load makes the call to proxy.
Ans. Lazy fetching is the technique of not loading the child objects when parent objects are loaded. By default Hibernate does not load child objects. One can specify whether to load them or not while doing the association.
Ans. Transient - In this state, an instance is not associated with any persistence context
Persistent - In this state, an instance is associated with a persistence context
Detached - This is a state for an instance which was previously associated with a persistence context an has been currently closed dissociated
Persistent - In this state, an instance is associated with a persistence context
Detached - This is a state for an instance which was previously associated with a persistence context an has been currently closed dissociated
Ans. no, It's like challenging the design of application.
Ans. Because it has to inspect the metadata in the bytecode instead of just using precompiled addresses and constants.
Ans. We should use singleton scope for beans when they are stateless and prototype when they are stateful.
Ans. Assert works only if assertions ( -ea ) are enabled which is not required for Verify.
Assert throws an exception and hence doesn't continue with the test if assert evaluates to false whereas it's not so with Verify.
Assert throws an exception and hence doesn't continue with the test if assert evaluates to false whereas it's not so with Verify.
Ans. Underlying data structure for ArrayList is Array whereas LinkedList is the linked list and hence have following differences -
1. ArrayList needs continuous memory locations and hence need to be moved to a bigger space if new elements are to be added to a filled array which is not required for LinkedList.
2. Removal and Insertion at specific place in ArrayList requires moving all elements and hence leads to O(n) insertions and removal whereas its constant O(1) for LinkedList.
3. Random access using index in ArrayList is faster than LinkedList which requires traversing the complete list through references.
4. Though Linear Search takes Similar Time for both, Binary Search using LinkedList requires creating new Model called Binary Search Tree which is slower but offers constant time insertion and deletion.
5. For a set of integers you want to sort using quicksort, it's probably faster to use an array; for a set of large structures you want to sort using selection sort, a linked list will be faster.
1. ArrayList needs continuous memory locations and hence need to be moved to a bigger space if new elements are to be added to a filled array which is not required for LinkedList.
2. Removal and Insertion at specific place in ArrayList requires moving all elements and hence leads to O(n) insertions and removal whereas its constant O(1) for LinkedList.
3. Random access using index in ArrayList is faster than LinkedList which requires traversing the complete list through references.
4. Though Linear Search takes Similar Time for both, Binary Search using LinkedList requires creating new Model called Binary Search Tree which is slower but offers constant time insertion and deletion.
5. For a set of integers you want to sort using quicksort, it's probably faster to use an array; for a set of large structures you want to sort using selection sort, a linked list will be faster.
Ans. Static and Transient.
Ans. @Entity
@Table
@Id
@Column
@Temporal
@Basic
@Enumerated
@Access
@Embeddable
@Lob
@AttributeOverride
@Embedded
@GeneratedValue
@ElementCollection
@JoinTable
@JoinColumn
@CollectionId
@GenericGenerator
@OneToOne
@OneToMany
@ManyToOne
@ManyToMany
@NotFound
@Table
@Id
@Column
@Temporal
@Basic
@Enumerated
@Access
@Embeddable
@Lob
@AttributeOverride
@Embedded
@GeneratedValue
@ElementCollection
@JoinTable
@JoinColumn
@CollectionId
@GenericGenerator
@OneToOne
@OneToMany
@ManyToOne
@ManyToMany
@NotFound
Q457. What entries we make in the hibernate config file if we are not using hbm files but Annotations ?show Answer
Ans. We configure Entity classes having annotated mappings.
Ans. Single SessionFactory object and multiple session objects for opening different session. Hibernate creates new Session object per thread.
Q459. What is the way to rollback transaction if something goes wrong using hibernate API ? show Answer
Ans. We can have the code calling Hibernate API within try block and can have transaction.rollback within Catch.
Ans. This configuration specifies if hibernate should creates the Schema / Table on its own if the respective table is not found.
"update" doesn't create the table if it's not found whereas configuration set as "create" creates the schema automatically.
"update" doesn't create the table if it's not found whereas configuration set as "create" creates the schema automatically.
Q461. What is the difference between these 2 annotations ?
@Entity
@Entity ( name="EMPLOYEES" )show Answer
@Entity
@Entity ( name="EMPLOYEES" )show Answer
Ans. The first annotation will try to map the Class with the Table as of same name as Class whereas the second annotation will specify the Entity name as "EMPLOYEES" and hence will try to map with Table Name "EMPLOYEES".
Q462. "What is the difference between these 2 annotations ?
@Entity ( name ="EMPLOYEES")
@Entity
@Table ( name=""EMPLOYEES"" )
@Entity ( name="EMP")
@Table ( name="EMPLPYEES" )show Answer
@Entity ( name ="EMPLOYEES")
@Entity
@Table ( name=""EMPLOYEES"" )
@Entity ( name="EMP")
@Table ( name="EMPLPYEES" )show Answer
Ans. First Annotation will set the Entity name as EMPLOYEES and hence will try to map with the same Table name.
The second annotation will make the Entity mapped to table EMPLOYEES irrespective of the Entity Name ( which is class name in this case ).
Third Annotations will set the different names for Enitity and Table and will explicitly map them.
The second annotation will make the Entity mapped to table EMPLOYEES irrespective of the Entity Name ( which is class name in this case ).
Third Annotations will set the different names for Enitity and Table and will explicitly map them.
Ans. Auto , Identity , Sequence and Table.
Ans. Using
lazy = false in hibernate config file
or
@Basic(fetch=FetchType.EAGER) at the mapping
lazy = false in hibernate config file
or
@Basic(fetch=FetchType.EAGER) at the mapping
Ans. It's a feature to lazily initialize dependencies , relationship and associations from the Database. Any related references marked as @OneToMany or @ManyToMany are loaded lazily i.e when they are accessed and not when the parent is loaded.
Ans. 1. Set lazy=false in the hibernate config file.
2. Set @Basic(fetch=FetchType.EAGER) at the mapping.
3. Make sure that we are accessing the dependent objects before closing the session.
4. Using Fetch Join in HQL.
2. Set @Basic(fetch=FetchType.EAGER) at the mapping.
3. Make sure that we are accessing the dependent objects before closing the session.
4. Using Fetch Join in HQL.
Ans. Instead of Saving Parent as well as Child Entities individually , Hibernate provides the option to persist / delete the related entities when the Parent is persisted.
Ans. Detach, Merge , Persist , Remove , Refresh
Ans. OneToOne
Ans. After Hibernate 3.0
Ans. Yes but as Hibernate creates the Proxy Classes inherited from the Entity Classes to communicate with Database for lazy initialization. Declaring entity classes as final will prohibit communication with database lazily and hence will be a performance hit.
Ans. 1. Entity classes should have default constructor.
2. Entity classes should be declared non final.
3. All elements to be persisted should be declared private and should have public getters and setters in the Java Bean style.
4. All classes should have an ID that maps to Primary Key for the table.
2. Entity classes should be declared non final.
3. All elements to be persisted should be declared private and should have public getters and setters in the Java Bean style.
4. All classes should have an ID that maps to Primary Key for the table.
Ans. No Difference. Both are the acceptable ways to declare an array.
Ans. @Test
The Test annotation indicates that the public void method to which it is attached can be run as a test case.
@Before
The Before annotation indicates that this method must be executed before each test in the class, so as to execute some preconditions necessary for the test.
@BeforeClass
The BeforeClass annotation indicates that the static method to which is attached must be executed once and before all tests in the class.
@After
The After annotation indicates that this method gets executed after execution of each test.
@AfterClass
The AfterClass annotation can be used when a method needs to be executed after executing all the tests in a JUnit Test Case class so as to clean-up the set-up.
@Ignores
The Ignore annotation can be used when you want temporarily disable the execution of a specific test.
The Test annotation indicates that the public void method to which it is attached can be run as a test case.
@Before
The Before annotation indicates that this method must be executed before each test in the class, so as to execute some preconditions necessary for the test.
@BeforeClass
The BeforeClass annotation indicates that the static method to which is attached must be executed once and before all tests in the class.
@After
The After annotation indicates that this method gets executed after execution of each test.
@AfterClass
The AfterClass annotation can be used when a method needs to be executed after executing all the tests in a JUnit Test Case class so as to clean-up the set-up.
@Ignores
The Ignore annotation can be used when you want temporarily disable the execution of a specific test.
Ans. It is a form of Input Output processing that permits other processing to continue before the I/O transmission has finished.
Q476. If there is a conflict between Base Class Method definition and Interface Default method definition, Which definition is Picked ?show Answer
Ans. Base Class Definition.
Ans. Lambda Expressions , Interface Default and Static Methods , Method Reference , Parameters Name , Optional , Streams, Concurrency.
Ans. No. Compiler will give error.
Q479. Does java allow implementation of multiple interfaces having Default methods with Same name and Signature ?show Answer
Ans. No. Compilation error.
Ans. With Java 8, We can provide method definitions in the Interfaces that gets carried down the classes implementing that interface in case they are not overridden by the Class. Keyword "default" is used to mark the default method.
Q481. Can we have a default method definition in the interface without specifying the keyword "default" ? show Answer
Ans. No. Compiler complains that its an abstract method and hence shouldn't have the body.
Q482. Can a class implement two Interfaces having default method with same name and signature ?
public interface DefaultMethodInterface {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface");
}
}
public interface DefaultMethodInterface2 {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface2");
}
}
public class HelloJava8 implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();
defMethIn.defaultMethod();
}
}show Answer
public interface DefaultMethodInterface {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface");
}
}
public interface DefaultMethodInterface2 {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface2");
}
}
public class HelloJava8 implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();
defMethIn.defaultMethod();
}
}show Answer
Ans. No. Compiler gives error saying "Duplicate Default Methods"
Q483. What If we make the method as abstract in another Interface ?
public interface DefaultMethodInterface {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface");
}
}
public interface DefaultMethodInterface2 {
public void defaultMethod(){
System.out.println("DefaultMethodInterface2");
}
}
public class HelloJava8 implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();
defMethIn.defaultMethod();
}
}show Answer
public interface DefaultMethodInterface {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface");
}
}
public interface DefaultMethodInterface2 {
public void defaultMethod(){
System.out.println("DefaultMethodInterface2");
}
}
public class HelloJava8 implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();
defMethIn.defaultMethod();
}
}show Answer
Ans. Even then the Compiler will give error saying that there is a conflict.
Q484. What if we override the conflicting method in the Class ?
public interface DefaultMethodInterface {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface");
}
}
public interface DefaultMethodInterface2 {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface2");
}
}
public class HelloJava8 implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();
defMethIn.defaultMethod();
}
public void defaultMethod(){
System.out.println("HelloJava8");
}
}show Answer
public interface DefaultMethodInterface {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface");
}
}
public interface DefaultMethodInterface2 {
default public void defaultMethod(){
System.out.println("DefaultMethodInterface2");
}
}
public class HelloJava8 implements DefaultMethodInterface,DefaultMethodInterface2 {
public static void main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();
defMethIn.defaultMethod();
}
public void defaultMethod(){
System.out.println("HelloJava8");
}
}show Answer
Ans. There won't be any error and upon execution the overriding class method will be executed.
Q485. What will happen if there is a default method conflict as mentioned above and we have specified the same signature method in the base class instead of overriding in the existing class ?show Answer
Ans. There won't be any problem as the Base class method will have precedence over the Interface Default methods.
Q486. If a method definition has been specified in Class , its Base Class , and the interface which the class is implementing, Which definition will be picked if we try to access it using Interface Reference and Class object ? show Answer
Ans. Class method definition is overriding both the definitions and hence will be picked.
Q487. If a method definition has been specified in the Base Class and the interface which the class is implementing, Which definition will be picked if we try to access it using Interface Reference and Class object ? show Answer
Ans. Base Class Definition will have precedence over the Interface Default method definition.
Ans. Yes, Effective Java 8.
Ans. No, only using Interface Name.
Q490. Can we have default method with same name and signature in the derived Interface as the static method in base Interface and vice versa ?show Answer
Ans. Yes , we can do that as static methods are not accessible using references and hence cannot lead to conflict. We cannot do inverse as Default methods cannot be overridden with the static methods in derived interface.
Ans. Its an anonymous method without any declaration. Lambda Expression are useful to write shorthand Code and hence saves the effort of writing lengthy Code. It promotes Developer productivity, Better Readable and Reliable code.
Ans. Predicate represents an anonymous function that accepts one argument and produces a result.
Supplier represents an anonymous function that accepts no argument and produces a result.
Consumer represents an anonymous function that accepts an argument and produces no result.
Supplier represents an anonymous function that accepts no argument and produces a result.
Consumer represents an anonymous function that accepts an argument and produces no result.
Ans. helloJava8 receives an Integer as argument and then returns the modulus of that Integer.
Ans. NameNode stores MetaData (No of Blocks, On Which Rack which DataNode is stored etc) whereas the DataNode stores the actual Data.
Ans. http://www.c4learn.com/c-programs/program-to-check-whether-number-is.html
Ans. We can't get the address of a reference like a pointer. Moreover we cannot perform pointer arithmetic with references.
Ans. http://www.cyberciti.biz/faq/key-differences-between-tcp-and-udp-protocols/
Q498. What things you would care about to improve the performance of Application if its identified that its DB communication that needs to be improved ?show Answer
Ans. 1. Query Optimization ( Query Rewriting , Prepared Statements )
2. Restructuring Indexes.
3. DB Caching Tuning ( if using ORM )
4. Identifying the problems ( if any ) with the ORM Strategy ( If using ORM )
2. Restructuring Indexes.
3. DB Caching Tuning ( if using ORM )
4. Identifying the problems ( if any ) with the ORM Strategy ( If using ORM )
Ans. http://www.buggybread.com/2014/03/java-design-pattern-singleton-interview.html