What is JVM JRE JDK?
JVM:
JVM Java Virtual Machine It is
responsible to converting Byte code to the machine specific code. JVM is also
platform dependent and provides core java functions like memory management,
garbage collection, security etc.
JRE:
JRE is the implementation of JVM,
it provides platform to execute java programs. JRE consists of JVM and java
binaries and other classes to execute any program successfully. JRE doesn’t
contain any development tools like java compiler, debugger etc. If you want to
execute any java program, you should have JRE installed but we don’t need JDK
for running any java program.
JDK:
Java Development Kit is the core
component of Java Environment and provides all the tools, executables and
binaries required to compile, debug and execute a Java Program. JDK is platform
specific software and that’s why we have separate installers for Windows, Mac
and UNIX systems. We can say that JDK is superset of JRE since it contains JRE
with Java compiler, debugger and core classes. Current version of JDK is 1.7
also known as Java
What are the OPPs Concepts?
There are four main Opps concepts
are there in java
1. Inheritance
2. Abstraction
3. Encapsulation
4. Polymorphism
1. Inheritance:
When one object acquires all the
properties and behaviors of parent object i.e. known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.
2. Abstraction
Hiding the internal details and
just highlighting the set of services what they offering is called Abstraction
3. Encapsulation
Encapsulating data and
corresponding methods into a single module is called Encapsulation
Encapsulation=DataHiding+Abstraction
4. Polymorphism
Def:
The process of representing one form into multiple forms is known as
polymorphism.
A form is nothing but existence of
a method in a particular class and it can perform various operations.
In object oriented programming we
have two types of polymorphisms.
Static/ Compile time polymorphism: A static polymorphism is one in
which methods are binding with an object at compile time.
Dynamic polymorphism: Dynamic polymorphism is one in which methods
are binding with an object at run time.
What is method overloading?
If a class has multiple methods by
same name but different parameters, it is known as Method Overloading.
What is method overriding?
If a subclass provides a specific
implementation of a method that is already provided by its parent class, then
it is known as Method Overriding. It is used for runtime polymorphism and it
provides the specific implementation of the method.
What is difference between method overloading and method overriding?
Method Overloading
|
Method Overriding
|
If a class has multiple methods by same name with different types of
parameters, it is known
as Method Overloading
|
Method overriding is used to provide the specific implementation of the method
That is already provided by its super
class.
|
2) Method overloading is performed with in a class.
|
Method overriding occurs in two classes that have IS-A relationship.
|
3) In case of method overloading parameter must be different.
|
In case of method overriding parameter
must be same.
|
What is Garbage Collector?
A Garbage collector is one of the
inbuilt system background java program which will run along our regular java program
for collecting unused memory space for improving the performance of the java
applications
What is Abstract class in java?
Abstract Classes: Abstract classes
are those which containing some defined methods and some undefined methods.
Undefined methods of a class are known as unimplemented/abstract methods.
What is Interface in java?
Interface means the contract
between client and service provider is called Interface
The interface is a mechanism to
achieve fully abstraction and multiple inheritances in java. There can be only
abstract methods in the interface.
Interface also represents IS-A
relationship.
It cannot be instantiated just like
abstract class.
Why use Interface?
There are mainly three reasons to
use interface. They are given below.
It is used to achieve fully
abstraction.
By interface, we can support the
functionality of multiple inheritances.
It can be used to achieve loose
coupling.
What is difference between Abstract class and Interface?
Abstract Class
|
Interface
|
1.Multiple inheritance is not allowed through class
|
1.Multiple inheritance is possible through interface
|
2.Abstract class can contain concrete method and abstract method
|
2. Interface contain only abstract method
|
3. Abstract class can contain constructor
|
3.Interface can’t contain constructor
|
4. Abstract class contain instance block and static block
|
4. Interface can’t contain both instance
and static block
|
5. Abstract class can contain instance and static variables
|
5.Interface can contain only static variables
|
What is cloning?
The object cloning is a way to create exact
copy of an object. For this purpose, clone() method of Object class is used to
clone an object.
The java.lang.Cloneable interface
must be implemented by the class whose object clone we want to create. If we
don't implement Cloneable interface, clone () method generates
CloneNotSupportedException.
The clone() method is defined in
the Object class. Syntax of the clone() method is as follows:
What is Static in Java?
The static keyword is used in java
mainly for memory management. We may apply static keyword with variables,
methods, blocks and nested class. The static keyword belongs to the class than
instance of the class.
Static variable If you declare any
variable as static, it is known static variable.
The static variable can be used to
refer the common property of all objects (that is not unique for each object)
e.g. company name of employees, college name of students etc.
The static variable gets memory
only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it
saves memory).
A static method can be accessed
without creating an instance of the class .
Static method If you apply static
keyword with any method, it is known as static method.
Static block
It is used to initialize the static
data member.
It is executed before main method
at the time of class loading.
What is final Key word in java?
The final keyword in java is used
to restrict the user. The final keyword can be used in many context. Final can
be: variable method class
Final variable
If you make any variable as final,
you cannot change the value of final variable(It will be constant).
Final method
If you make any method as final,
you cannot override it.
Final class
If you make any class as final, you
cannot extend it.
What is
super keyword in java?
Super keyword:
Super is a keyword which is used to
differentiate base class features from derived class features. In java
programming super keyword is play a very important role in the three places.
Super at variable level:
Whenever we inherit the data
members of the super class into the derived class, there is a possibility that
base class data members are similar to derived class data members. In this
context JVM gets an ambiguity.
In order to differentiate base
class data members from derived class data members in this context of base
class members must be preceded by a keyword super.
Super at method level:
Whenever we inherit the base class
methods into the derived class, there is a possibility that the base class
methods are similar to derived class methods.
In this context JVM gets an
ambiguity. In order to differentiate base class methods and derived class
methods, in the context of derived class the base class methods must be
preceded by super keyword.
What is
this keyword in java?
This is the one of the implicit
keyword created by JVM and for supplied to every java program for two purposes
they are
1. It always pointing to current
class object.
2. Whenever we write a java program
there is possibility that formal parameters and instance variable of a class
are similar. In this context JVM gets ambiguity (not having clarity between
formal parameters and data members).
3.In order to differentiate the
formal parameters and data members of a class, data members of a class must be
preceded by a keyword „this?.
4. SYN: this. Current class data
members name.
What is Exception in java?
Exception: Exception means it is an event that disrupts the normal
flow of the program is called Exception. It is an object which is thrown at
runtime.
What is Exception Handling in java?
The process of converting the
system error messages into the user friendly error messages is known as
Exception Handling
Handling runtime errors is called Exception
handling. It is mainly used to handle checked exceptions.
What are Checked Exception and
Unchecked Exception?
Types of exceptions in java
There are two types of Exceptions
are there in java they are
Checked Exceptions and Un checked
Exceptions
1. Checked exceptions
Checked exceptions means the
exceptions which are checked by the compiler for smooth execution of the
program at run time is called checked Exceptions
FileNotFoundException
IOException
2. Unchecked exceptions
Unchecked exceptions means the exceptions
which are not checked by the compiler are called unchecked Exceptions such as
Arithmetic Exception, NumberFormatException, and
ArrayIndexOutOfBoundsExceptions
What is User Defined Exception in java?
User defined exceptions means the Exceptions
which are developed by the java programmer and supplied as a part of their
project to deal with the common specific problems is nothing but a User defined
Exceptions
What is Difference Between throw and throws in java?
throw
|
throws
|
1) Throw is used to explicitly throw an exception.
|
Throws is used to declare an exception.
|
2) Checked exceptions cannot be propagated with throw only.
|
Checked exception can be propagated with throws.
|
3) Throw is followed by an instance.
|
Throws is followed by class.
|
4) Throw is used within the method.
|
throws is used with the method
Signature.
|
5)You cannot throw multiple exception
|
You can declare multiple exception e.g. public void method()throws
IOException,SQLException.
|
What are the try catch and finally keywords in java?
Try: It is one of the predefined block here we can write the block
of statements those will causes problems at runtime.
Catch: Catch is one of the predefined block which is used to write
the block of statements which provides user friendly error messages by
suppressing system error messages.
Finally Blocks:
It is one of the predefined block
in which we write the block of statements which will terminates the resources
of files, database connections which are obtained in the try block. In
generally finally block contains resource relinquishing logic (terminating
logic).
Finally block will executes
compulsorily.
What is difference between Exception and Error?
An error is an irrecoverable
condition occurring at runtime like out of memory error. These kind of jvm
errors cannot be handled at runtime. Exceptions are because of condition
failures, which can be handled easily at runtime.
What is ClassNotFoundException in java?
As the name suggests
classNotFoundException in Java is a subclass of java.lang.Exception and Comes
when Java Virtual Machine tries to load a particular class and doesn't found
the requested class in class path. Another important point about this Exception
is that, It is a checked Exception and you need to provide explicitly Exception
handling while using methods which can possibly throw classnotfoundexception in
java either by using try-catch block or by using throws clause
How to deal with the ClassNotFoundException
How to deal with the ClassNotFoundException
Verify that the name of the
requested class is correct and that the appropriate .jar file exists in your
classpath. If not, you must explicitly add it to your application’s classpath.
In case the specified .jar file
exists in your classpath then, your application’s classpath is getting overriden
and you must find the exact classpath used by your application.
In case the exception is caused by
a third party class, you must identify the class that throws the exception and
then, add the missing .jar files in your classpath.
What is Volatile Keyword?
Volatile is modifier applicable
only for variables but not for methods and classes
If the value of the variable keeps
on changing such type of variables we have to declare with volatile modifier
What is Memory Leak:
If an object having the reference
then it is not eligible for Garbage collected even though we are not using that
object in our program still it is not destroyed by the G.C such type of object
is called Memory leak
Types of Relationships in java?
Based on reusing the data members
from one class to another class in JAVA we have three types of relationships.
They are is-a relationship, has-a relationship and uses-a relationship.
Is-a relationship: Is-a relationship is one in which data members
of one class is obtained into
Another class through the concept
of inheritance.
Has-a relationship: Has-a relationship is one in which an object of
one class is created as a data
Member in another class.
Uses-a relationship : Uses-a
relationship is one in which a method of one class is using an object
Of another class.
Inheritance is the technique which
allows us to inherit the data members and methods from base class to derived
class.
What is Composition?
Composition means whenever Container object is
destroyed all contained objects will be destroyed automatically that is without
existing Container object there is no chance of existing contained objects
Holding the reference of the other
class within some other class is known as composition.
What is Aggregation?
Aggregation means whenever
container object is destroyed there is no Guarantee of destruction of contained
objects without existing container object there is chance of existing contained
objects
What is difference between aggregation and composition?
Aggregation represents weak
relationship whereas composition represents strong relationship. For example:
bike has an indicator (aggregation) but bike has an engine (compostion).
What is String in java?
Generally, string is a sequence of
characters. But in java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create string object.
How to create String object?
There are two ways to create String
object:
1. by string literal
2. by new keyword
1).String Literal
Java String literal is created by
using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM
checks the string constant pool first. If the string already exists in the
pool, a reference to the pooled instance is returned. If string doesn't exist
in the pool, a new string instance is created and placed in the pool. For
example:
1. String s1="Welcome";
2. String s2="Welcome"; //will
not create new instance
In the above example only one object will be
created. Firstly JVM will not find any string object with the value
"Welcome" in string constant pool, so it will create a new object.
After that it will find the string with the value "Welcome" in the
pool, it will not create new object but will return the reference to the same
instance.
Note: String objects are stored in
a special memory area known as string constant pool.
Why java uses concept of string literal?
To make Java more memory efficient
(because no new objects are created if it exists already in string constant
pool).
2) By new keyword
String s=new
String("Welcome");//creates two objects and one reference va riable
In such case, JVM will create a new
string object in normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s
will refer to the object in heap(non pool).
Java String Example
public class StringExample{
public static void main(String args[]){
String
s1="java";//creating string by java string literal char
ch[]={'s','t','r','i','n','g','s'};
String s2=new
String(ch);//converting char array to string
String s3=new
String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
outpot
Java
Strings
Example
What is immutable in strings
In java, string objects are immutable.
Immutable simply means unmodifiable or unchangeable.
Once string object is created its
data or state can't be changed but a new string object is created.
Let's try to understand the
immutability concept by the example given below:
class Testimmutablestring{
public static void main(String
args[])
String s="Sachin";
s.concat("
Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print
Sachin because strings are immutable ob jects
}}
What is mutable in strings?
Java String literal is created by
using double quotes. For Example:
String s="welcome";
Each time you create a string
literal, the JVM checks the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance is returned. If string
doesn't exist in the pool, a new string instance is created and placed in the
pool. For example:
String s1="Welcome";
String
s2="Welcome";//will not create new instance
In the above example only one object will be
created. Firstly JVM will not find any string object with the value
"Welcome" in string constant pool, so it will create a new object.
After that it will find the string with the value "Welcome" in the
pool, it will not create new object but will return the reference to the same
instance.
Why java uses concept of string
literal?
To make Java more memory efficient (because no
new objects are created if it exists already in string constant pool).
What is difference between equals method and == operator in java
== -> is a reference comparison,
i.e. both objects point to the same memory location
.equals() -> evaluates to the
comparison of values in the objects
Main difference between == and
equals in Java is that "==" is used to compare primitives while
equals() method is recommended to check equality of objects. Another difference
between them is that, If
both "==" and equals() is
used to compare objects than == returns true only if both references points to
same object while equals() can return true or false based on its overridden implementation.One of the popular
cases is comparing two String in Java in which case == and equals() method
return different results.
Another scenario which creates
confusion between == and equals method is when you compare two Objects. When
you compare two references pointing to an object of type Object you should see
the same result from both ==
operator and equals method because default
implementation of equals method just compare memory address of two objects and
return true if two reference variable are pointing towards an exactly same
object. Here is example of == vs equals method for comparing two objects:
What
is toString and hash code in java?
We can use this method to
find string representation of an object
Whenever we are trying to
print any object reference internally to String() method will be executed
What is hashCode()?
For every object jvm will
assign one unique id which is nothing but hashcode
Jvm uses hashcode will
saving objects into hashtable or hashset or hashmap
Based on our requirement
we can generate hashcode by overriding hashcode method in our class
If we are not overriding
hashcode() method then Object class hashcode() method will be executed which
generate hashcode based on address of the object but whenever we are overriding
hashcode() method then hashcode is no longer related to Address of the object
What is difference between string and string buffer and string builder
in java?
If the content will not be
change frequently then we should go for string
StringBuffer
is synchronized i.e. thread safe. It means two threads can't
call the methods of StringBuffer simultaneously.
StringBuilder
is non-synchronized i.e. not thread safe. It means two threads
can call the methods of StringBuilder simultaneously.
How can we create immutable class in java ?
To create immutable class in java,
you have to do following steps.
Declare the class as final so it
can’t be extended.
Make all fields private so that
direct access is not allowed.
Don’t provide setter methods for variables
Make all mutable fields final so
that it’s value can be assigned only once.
Initialize all the fields via a
constructor performing deep copy.
Perform cloning of objects in the
getter methods to return a copy rather than returning the actual object
reference.
To understand points 4 and 5, let’s
run the sample Final class that works well and values doesn’t get altered after
instantiation.
public final class Employee{ final
String pancardNumber;
public Employee(String
pancardNumber){ this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}}
Why string objects are immutable in java?
Because java uses the concept of
string literal.Suppose there are 5 reference variables,all referes to one
object "sachin".If one reference variable changes the value of the
object, it will be affected to all the reference variables. That is why string
objects are immutable in java.
What is difference between path and Class path
Path:We can use path variable to
describes the location where the required Binary executable files are available
If we are not setting path variable then java and javac commands wont work
Class path:We can use Class path to describes the location where
required .class files are available
If we are not setting the class path our
program wont run
What is difference between enum, Enum and Enumeration?
enum: It is keyword which can be used to define a group of named
constants
Enum: It is a class present in
java.lang package which acts as a base class for all java enums
Enumeration: It is an Interface
present in java.util package which can be used for retrieving objects from
collection one by one
What is singleton class?
Singleton class means if any java
class it is allowed to create only one
object such type of class is called Singleton class
The main advantage of single ton
class is instead of creating a separate object for every requirement we can
create a single object and reuse that object for every requirement
This approach improves memory
utilization and performance of the system
Public class ContactDAO
{
private static ContactDAO me = null;
private ContactDAO()
{
}
public static ContactDAO
getInstance()
{
if (me == null) {
me = new ContactDAO();
}
return me;
}}
What is marker interface?
If an interface wont contain any
methods and by implementing that interface if our object will yet ability such
type of interface are called marker interface or tag interface or ability
interface
Ex: Serializable, Clonable, Randam
Access, Single Thread modul
What is difference between final finally and finalize()
final: final is a keyword which can be used to variables, methods
and classes
final variable is not changed
final methods are not override
final classes are not inherited
finally: finally is a block which is associated with try-catch to
maintain clean-up code which should be executed always irrespective of whether
exception raised or not raised and whether handled or not handled
finalize ():It is a method which should be executed by garbage
collector before destroying any object to perform clean-up activities
What is deep cloning: The process of creating exactly duplicate
independent object is called Deep cloning
Test t=new Test();
Test t2=t1; //shallow cloning
Test t4=(Test)t.clone(); //deep
cloning
What is shallow cloning?
The process of creating just
duplicate object reference variable but not duplicate object is called shallow
cloning
What is Serialization in java
Serialization in java is a
mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate,
RMI, JPA, EJB and JMS technologies.
The reverse operation of
serialization is called deserialization.
Advantage of Java Serialization
It is mainly used to travel
object's state on the network (known as marshaling).
java.io.Serializable interface
Serializable is a marker interface
(has no data member and method). It is used to "mark" java classes so
that objects of these classes may get certain capability. The Cloneable and Remote
are also marker interfaces.It must be implemented by the class whose object you
want to persist.
The String class and all the
wrapper classes implements java.io.Serializable interface by default.
Let's see the example given below:
import java.io.Serializable;
public class Student implements
Serializable{
int id;
String name;
public Student(int id, String name)
{
this.id = id;
this.name = name;
}}
In the above example, Student class
implements Serializable interface. Now its objects can be converted into
stream.
Example of Java Serialization
In this example, we are going to
serialize the object of Student class. The writeObject() method of
ObjectOutputStream class provides the functionality to serialize the object. We
are saving the state of the object in the file named f.txt.
import java.io.*;
class Persist{
public static void main(String
args[])throws Exception{
Student s1 =new
Student(211,"ravi");
FileOutputStream fout=new
FileOutputStream("f.txt");
ObjectOutputStream out=new
ObjectOutputStream(fout);
out.writeObject(s1);
out.flush(); System.out.println("success"); } }
What is Deserialization in java?
Deserialization is the process of
reconstructing the object from the serialized state.It is the reverse operation
of serialization.
Example of Java Deserialization
import java.io.*;
class Depersist{
public static void main(String
args[])throws Exception{
ObjectInputStream in=new
ObjectInputStream(new FileInputStream("f.txt" ));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name);
in.close();
}}
What is the transient keyword?
Java transient keyword is used in
serialization. If you define any data member as transient, it will not be
serialized.
Let's take an example, I have
declared a class as Student, it has three data members id, name and age. If you
serialize the object, all the values will be serialized but I don't want to
serialize one value, e.g. age then we can declare the age data member as
transient.
Example of Java Transient Keyword
In this example, we have created
the two classes Student and PersistExample. The age data member of the Student
class is declared as transient, its value will not be serialized.
If you deserialize the object, you
will get the default value for transient variable.
Let's create a class with transient
variable.
import java.io.Serializable;
public class Student implements
Serializable{
int id;
String name;
transient int age;//Now it will not
be serialized public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}}
What is Thread?
Thread: A flow control in java is
known as “Thread”.
Multithreading:
The basic aim of the multi
threading is to provide “concurrent execution”.
States/ Life cycle Thread:
New state: Once we create a thread object then is said to be in new
state
Ready: if we call start () method then the thread will be enter
into the ready state
Running State: if thread scheduler allocates CPU, then the thread
will entered into runnable state
Waiting state: When you call wait method on running thread then
thread will be moves to wait state
Halted State: A Halted State is one in which Thread has completed
its execution
There are two ways to create a thread:
By extending Thread class
By implementing Runnable interface.
1)By extending Thread class:
class Multi extends Thread{
public void run(){
System.out.println("thread is
running...");
}
public static void main(String
args[]){
Multi t1=new Multi(); t1.start(); } }
2)By implementing the Runnable interface:
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is
running...");
}
public static void main(String
args[]){ Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}}
Best Approach to define a Thread
Among the two ways of defining a
thread implements Runnable mechanism is recommended to use
If the first approach our class always
extending thread class and hence there is no chance of extending any other
class
But in case of second approach we
can extending some other class also while implementing Runnable interface hence
second approach is recommended to use
15. What is use of yield () method?
When yield() method is called on
running thread, that thread will give the chance to other threads which are in
ready to run state with the highest priority than the running thread.
16. What is use of join () method in java thread?
When you call join() on the running
thread then that thread will join at the end of other thread execution and
waits until all other threads finishes the execution.
14. Public static final void sleep(long milliseconds) throws Interrupted
Exception
This method is used for making the
currently executing Thread to sleep for a period of time
If threads don’t want to perform
any operation for a particular amount of time then we should go for sleep
public void wait(): This method is used for making the Thread to
wait without specifying any time.
public void notify(): This method is used for transferring one
Thread at a time from waiting state to Ready state.
public void notifyAll(): This method is used for transferring all
the Threads at a time from waiting state to ready state
What is deadlock in thread?
Deadlock can occur in a situation
when a thread is waiting for an object lock, that is acquired by another thread
and second thread is waiting for an object lock that is acquired by first
thread. Since, both threads are waiting for each other to release the lock, the
condition is called deadlock.
What are the prevention techniques in thread?
What is synchronization?
Synchronization Techniques:
Synchronization is used in
multithreading to eliminate inconsistent results
The concept of Synchronization must
be always applied on common tasks for getting consistent results. That is if
multiple Threads are performing common task then those Threads generates
inconsistent result. To avoid this inconsistent result it is recommended to
apply Synchronization concept.
DEF: The mechanism of allowing only one Thread among multiple
Threads into the sharable area to perform read and write operations known as
Synchronization.
What is synchronization block
Synchronized block can be used to
perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code
in your method, but you want to synchronize only 5 lines, you can use
synchronized block.
What is synchronization method?
Synchronized Methods: If any
ordinary method is accessed by more than one Thread then the ordinary method
generates an inconsistent result. To avoid this inconsistent result the
definition of ordinary method must be preceded by a keyword synchronized for
making the method as Synchronized. Based on Synchronized keyword we write
before the methods, they are classified into two types they are
a) Synchronized instance methods.
b) Synchronized static methods.
What is difference between wait and sleep method in thread?
wait()
|
sleep()
|
1) The wait() method is defined in Object class.
|
The sleep() method is defined in
Thread class.
|
2) wait() method releases the lock.
|
The sleep() method doesn't releases the lock.
|
What is collection?
A group of individual objects as a
single entity is called collection
What is collection Framework?
It defines several classes and
interfaces which can be used to represent a group of objects as a single entity
is called collection framework
What is difference between Array
List and Vector?
Array List
|
Vector
|
1).Array List is not synchronized.
|
1).Vector is synchronized.
|
2)Multiple threads can access Array List simultaneously hence Array
List object is not thread safe
|
2).At any point only one thread is allowed to operate on vector object
at a time hence vector object is thread safe
|
3) Array List increases its size by 50% of the array size.
|
3) Vector increases its size by doubling the array size.
|
4)threads are not required to wait and hence performance is high
|
4)It increases waiting time of a threads and hence performance is low
|
What is difference between arrays and collections in java?
Arrays
|
Collections
|
1. Arrays are fixed in size and hence once we created an array we are
not allowed to increase or decrease the size based on our requirement.
|
Collections are grow-able in nature and hence based on our requirement
we can increase or decrease the size.
|
2. Arrays can hold both primitives as well as objects.
|
Collections can hold only objects but not primitive.
|
3.Performance point of view arrays faster than collection
|
Performance point of view collections are slower than array
|
4. Arrays can hold only homogeneous elements.
|
Collections can hold both homogeneous and heterogeneous elements.
|
5. Memory point of view arrays are not recommended to use.
|
Memory point of view collections are recommended to use.
|
6. For any requirement, there is no ready method available.
|
For every requirement ready made method support is available.
|
What is difference between array List and Linked List?
ArrayList
|
LinkedList
|
1)
ArrayList internally uses dynamic array to store the elements.
|
LinkedList
internally uses doubly linked list to store the elements.
|
2)
Manipulation with ArrayList is slow because it internally uses
array. If any element is removed from the array, all the bits are shifted in
memory.
|
Manipulation
with LinkedList is faster than ArrayList because it uses doubly
linked list so no bit shifting is required in memory.
|
3)
ArrayList class can act as a list only because it implements List
only.
|
LinkedList
class can act as a list and queue both because it implements List
and Deque interfaces.
|
4)
ArrayList is better for storing and accessing data.
|
LinkedList
is better for manipulating data.
|
What is difference between list and set?
1) List is an ordered
collection it maintains the insertion order, which means upon displaying the
list content it will display the elements in the same order in which they got
inserted into the list.
Set is an unordered
collection, it doesn’t maintain any order. There are few implementations of Set
which maintains the order such as LinkedHashSet (It maintains the elements in
insertion order).
2) List allows duplicates
while Set doesn’t allow duplicate elements. All the elements of a Set should be
unique if you try to insert the duplicate element in Set it would replace the
existing value.
3) List implementations: ArrayList, LinkedList etc.
Set implementations: HashSet, LinkedHashSet, TreeSet etc.
4) List allows any number
of null values. Set can have only a single null value at most.
What is difference between hash map and hash table?
HashMap
|
Hashtable
|
1.
HashMap is non synchronized. It is not-thread safe and can’t be shared
between many threads without proper ynchronization code
|
Hashtable
is synchronized. It is thread-safe and can be shared with many threads.
|
2.
HashMap allows one null key and multiple null values
|
Hashtable
doesn’t allow any null key or value.
|
3)
HashMap is a new class introduced in JDK 1.2.
|
Hashtable
is a legacy class.
|
4)
HashMap is fast.
|
4)
HashMap is fast.
|
5)
We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap); |
Hashtable
is internally synchronized and can't be unsynchronized.
|
6)
Iterator in HashMap is fail-fast.
|
Enumerator
in Hashtable is not fail-fast.
|
What is hash set and hash map?
HashMap
|
Hash Set
|
HashMap
is an implementation of Map interface
|
HashSet is
an implementation of Set Interface
|
HashMap
Stores data in form of key-value pair
|
HashSet
Store only objects
|
Put method
is used to add element in map
|
Add method
is used to add element is Set
|
In hash map
hashcode value is calculated using key object
|
Here member
object is used for calculating hashcode value which can be same for two
objects so equal () method is used to check for equality if it returns false
that means two objects are different.
|
HashMap is
faster than HashSet because unique key is used to access object
|
HashSet is
slower than Hashmap
|
What is difference between hash map and tree map?
HashMap
|
TreeMap
|
implement
basic map interface
|
implement
navigable map interface
|
implemented
by an array of buckets, each bucket is a LinkedList of entries
|
running
time of basic operations: put(), get(), remove(), worst case O(lgn)
|
running
time of basic operations: put(), average O(1), worst case O(n), happens when
the table is resized; get(), remove(), average O(1)
|
running
time of basic operations: put(), get(), remove(), worst case O(lgn)
|
not
synchronized, to synchronize it: Map m = Collections.synchronizedMap(new
HashMap(...));
|
not
synchronized, to synchronize it: SortedMap m =
Collections.synchronizedSortedMap(new TreeMap(...));
|
Iteration
order of the map is unpredictable.
|
provide
ordered iteration. higherKey(), lowerKey() can be used to get the successor
and predecessor of a given key.
|
What
is difference between hash set and linkedhashset?
Hash
set
|
Linkedhashset
|
HashSet uses HashMap internally to store it’s elements.
|
LinkedHashSet uses LinkedHashMap
internally to store it’s elements.
|
HashSet doesn’t maintain any order of
elements.
|
LinkedHashSet maintains insertion order of
elements. i.e elements are placed as they are inserted.
|
HashSet gives better performance than the
LinkedHashSet and TreeSet.
|
The performance of LinkedHashSet is between
HashSet and TreeSet. It’s performance is almost similar to HashSet. But
slightly in the slower side as it also maintains LinkedList internally to
maintain the insertion order of elements.
|
HashSet gives performance of order O(1) for
insertion, removal and retrieval operations.
|
LinkedHashSet also gives performance of order
O(1) for insertion, removal and retrieval operations.
|
HashSet uses equals() and hashCode() methods
to compare the elements and thus removing the possible duplicate elements.
|
LinkedHashSet also uses equals() and
hashCode() methods to compare the elements.
|
HashSet allows maximum one null element.
|
LinkedHashSet also allows maximum one null
element.
|
What is difference between hash map and linked hash map?
Hash map
|
Linked hash
map
|
1)
Hashmap follows hashtable.
|
1)
LinkedHashmap follows hashtable and Linkedlist
|
2)Insertion
order is not preserved
|
2)Insertion
order is preserved
|
What is difference between hash set and tree set?
HashSet maintains no order whereas TreeSet maintains
ascending order.
What is difference between iterate and List Iterator?
Iterator traverses the
elements in forward direction only whereas ListIterator traverses the elements
in forward and backward direction.
What is difference between Iterator and enumerator?
Iterator
|
Enumerator
|
1)
Iterator can traverse legacy and non-legacy elements.
|
Enumeration
can traverse only legacy elements.
|
2)
Iterator is fail-fast.
|
Enumeration
is not fail-fast.
|
3)
Iterator is slower than Enumeration.
|
Iterator
is slower than Enumeration.
|
What is difference between
comparable and comparator?
comparable
|
comparator
|
1.
We can use comparable to define default Natural sorting order
|
1.We
can use Comparator to define customized sorting order
|
2.
This interface present in java.lang Package
|
2.This
interface present in java.util
Package
|
3.
Define only one method that is compareTo()
|
3.Define
only two methods that is
Compare()
and Equals()
|
4.
All wrapper classes and string class implements comparable interface
|
4.No
predefined class implements comparator interface
|
What is difference between collection and collections?
Collection is an interface
whereas Collections is a class. Collection interface provides normal
functionality of data structure to List, Set and Queue. But, Collections class
is to sort and synchronize collection elements.
What is difference between static import and normal import?
We can import normal
import to import classes and interfaces of a package when ever we are using
general import it is not required to use fyllyQualifiedName and we can use
short names directly
We can use static import
to import static variables and methods of a class .whenever we are using static
import then it is not required to class name to access static member we can
access directly
What are generics and what are the advantages?
Generics
in Java
The Java Generics programming is introduced in J2SE 5 to
deal with type-safe objects.
Before generics, we can store any type of objects in collection
i.e. non-generic.
Now generics,
forces the java programmer to store specific type of objects.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
1) Type-safety: We can hold only a single type of objects in generics. It doesn’t
allow to store other objects.
2) Type
casting is not required: There is no need to typecast
the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
3)
Compile-Time Checking: It is checked at compile time
so problem will not occur at runtime. The good programming strategy says it is
far better to handle the problem at compile time than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
Full Example of Generics
in Java
Here, we are using the ArrayList class, but you can use any
collection class such as ArrayList, LinkedList, HashSet, TreeSet, HashMap,
Comparator etc.
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
String s=list.get(1);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
What is JDBC?
JDBC is a Java API that is used to
connect and execute query to the database. JDBC API uses jdbc drivers to
connects to the database
How to connect with database or Steps to connect with database?
There are 5 steps to connect any
java application with the database in java using JDBC. They are as follows:
Register the driver class
Creating connection
Creating statement
Executing queries
Closing connection
1) Register the driver class
The forName() method of Class class
is used to register the driver class. This method is used to dynamically load
the driver class.
Syntax of forName() method
public static void forName(String
className)throws ClassNotFoundExcept ion
Example to register the
OracleDriver class
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of
DriverManager class is used to establish connection with the database.
Syntax of getConnection() method
1) public static Connection
getConnection(String url)throws SQLException
2) public static Connection
getConnection(String url,String name,String password) throws SQLException
Example to establish connection
with the Oracle database
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of
Connection interface is used to create statement. The object of statement is
responsible to execute queries with the database.
Syntax of createStatement() method
public Statement
createStatement()throws SQLException
Example to create the statement
object
Statement
stmt=con.createStatement();
4) Execute the query
The executeQuery() method of
Statement interface is used to execute queries to the database. This method
returns the object of ResultSet that can be used to get all the records of a
table.
Syntax of executeQuery() method
public ResultSet
executeQuery(String sql)throws SQLException
Example to execute query
ResultSet
rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+"
"+rs.getString(2));
}
5) Close the connection object
By closing connection object
statement and ResultSet will be closed automatically. The close() method of
Connection interface is used to close the connection.
Syntax of close() method
public void close()throws
SQLException
Example to close connection
con.close();
What is connection interface in jdbc?
A Connection is the session between
java application and database. The Connection interface is a factory of
Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection
can be used to get the object of Statement and DatabaseMetaData. The Connection
interface provide many methods for transaction management like commit(),
rollback() etc.
What is statement interface in jdbc?
The Statement interface provides
methods to execute queries with the database. The statement interface is a
factory of ResultSet i.e. it provides factory method to get the object of
ResultSet.
Commonly used methods of Statement
interface:
The important methods of Statement
interface are as follows:
1).public ResultSet
executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
2).public int executeUpdate(String
sql): is used to execute specified query, it may be create, drop, insert,
update, delete etc.
3).public boolean execute(String
sql): is used to execute queries that may return multiple results.
4) public int[] executeBatch(): is
used to execute batch of commands.
What is prepare statement in jdbc?
The PreparedStatement interface is
a subinterface of Statement. It is used to execute parameterized query.
Let's see the example of
parameterized query:
String sql="insert into emp
values(?,?,?)";
As you can see, we are passing
parameter (?) for the values. Its value will be set by calling the setter
methods of PreparedStatement.
Why use Prepared Statement?
Improves performance: The
performance of the application will be faster if you use PreparedStatement
interface because query is compiled only once.
What is difference between statement and prepared statement in jdbc?
In case of Statement, query is compiled
each time whereas in case of Prepared Statement, query is compiled only once.
So performance of Prepared Statement is better than Statement
What is
result set in jdbc?
Result Set is one of the predefined
interface which is used for holding the number of records after execution of
select query in the Database software.
What is callable statement in jdbc?
Callable Statement Interface
(Executing Stored Procedures orFunctions)
Callable Statement is used to call
the stored procedures and functions,
CallableStatement
stmt=con.prepareCall("{call insertR(?,?)}");
What is Batch Statement in jdbc?
Instead of executing a single
query, we can execute a batch (group) of queries. It makes the performance
fast.
The java.sql.Statement and
java.sql.PreparedStatement interfaces provide methods for batch processing.
Advantage of Batch Processing
Fast Performance
Methods of Statement interface
The required methods for batch
processing are given below:
Method Description
void addBatch(String query) It adds
query into batch.
int[] executeBatch() It executes the batch of queries.
What is jdbc driver and how many types of drivers are there in jdbc?
JDBC Driver is a software component
that enables for java application to interact with the database. There are 4
types of JDBC drivers:
JDBC-ODBC bridge driver
Native-API driver (partially java
driver)
Network Protocol driver (fully java
driver)
Thin driver (fully java driver)
What is servlet?
Servlet is a technology i.e. used to create web application.
Servlet is an API that provides many interfaces and classes
including documentations.
Servlet is an interface that must be implemented for creating any
servlet.
What is difference between get and post in servlets?
GET
|
POST
|
1)
In case of Get request, only limited amount of data can be sent
because data is sent in header.
|
In
case of post request, large amount of data can be sent because data
is sent in body.
|
2)
Get request is not secured because data is exposed in URL bar.
|
Post
request is secured because data is not exposed in URL bar.
|
3)
Get request can be bookmarked.
|
Post
request cannot be bookmarked.
|
4)
Get request is idempotent . It means second request will be ignored
until response of first request is delivered
|
Post
request is non-idempotent.
|
5)
Get request is more efficient and used more than Post.
|
Post
request is less efficient and used less than get.
|
What is servlet collaboration?
The RequestDispatcher
interface provides the facility of dispatching the request to another resource
it may be html, servlet or jsp. This interface can also be used to include the
content of another resource also. It is one of the way of servlet
collaboration.
There are two methods
defined in the RequestDispatcher interface.
Methods of RequestDispatcher interface
The RequestDispatcher
interface provides two methods. They are:
public void
forward(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Forwards a request
from a servlet to another resource (servlet, JSP file, or HTML file) on the
server.
public void
include(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Includes the content
of a resource (servlet, JSP page, or HTML file) in the response.
Can we call servlet destroy () from service ()?
As you know, destroy () is part of
servlet life cycle methods, it is used to kill the servlet instance. Servlet
Engine is used to call destroy (). In case, if you call destroy method from
service(), it just execute the code written in the destory(), but it wont kill
the servlet instance. destroy() will be called before killing the servlet
instance by servlet engine.
Can we override static method?
We cannot override static methods.
Static methods are belongs to class, not belongs to object. Inheritance will
not be applicable for class members
How to
destroy the session in servlets?
By calling invalidate () method on
session object, we can destroy the session.
What is transient variable?
Transient variables cannot be
serialized. During serialization process, transient variable states will not be
serialized. State of the value will be always defaulted after deserialization.
In case, there is a return at
the end of try block, will execute finally block?
Yes, the finally block will be
executed even after writing return statement at the end fo try block. It
returns after executing finally block.
Difference between WHERE and HAVING clause:
1. WHERE clause can be used with -
Select, Insert, and Update statements, where as HAVING clause can only be used
with the Select statement.
2. WHERE filters rows before
aggregation (GROUPING), whereas, HAVING filters groups, after the aggregations
are performed.
3. Aggregate functions cannot be
used in the WHERE clause, unless it is in a sub query contained in a HAVING
clause, whereas, aggregate functions can be used in Having clause
Difference
between Generic Servlet and HttpServlet?
Generic
Servlet
|
HttpServlet
|
GenericServlet class is direct
subclass of Servlet interface.
|
HttpServlet class is the direct
subclass of Generic Servlet.
|
Generic Servlet is protocol
independent.It handles all types of
protocol like http, smtp, ftp etc
|
HttpServlet is protocol dependent. It
handles only http protocol
|
Generic Servlet only supports service() method.It handles only simple
request
public void service(ServletRequest
req,ServletResponse res ).
|
HttpServlet supports public void service(ServletRequest
req,ServletResponse res ) and protected void service(HttpServletRequest
req,HttpServletResponse res).
|
Generic Servlet only supports service() method.
|
HttpServlet supports also
doGet(),doPost(),doPut(),doDelete(),doHead(),doTrace(),doOptions()etc.
|
What is Difference between include directive and include
action in JSP
Include
directive
|
Include
action
|
Resource
included by including directive is loaded during jsp translation time
|
resource
included by including action is loaded during request time.
|
Any
change on included resource will not be visible include directive until jsp
file compiles
again
|
While
in the case of include again any change in included resource will be visible
in next request.
|
include
directive is static import
|
while
include action is dynamic import
|
include
directive uses file attribute to specify resource to be included
|
while
including action use page attribute for the same purpose.
|
Syntax: <%@ include
file="loan.jsp" %>
|
Syntax: <jsp:include
page="loan.jsp" %>
|
Difference
between SendRedirect and Forward methods
Forward method
|
SendRedirect
|
When
we use forward method request is transfer to other resource within the same
server for further processing.
|
In
case of sendRedirect request is transfer to another resource to different
domain or different server for futher processing.
|
In
case of forward Web container handle all process internally and client or
browser is not involved.
|
When
you use SendRedirect container transfers the request to client or browser so
url given inside the sendRedirect method is visible as a new request to the
client.
|
When
forward is called on requestdispather object we pass request and response
object so our old request object is present on new resource which is going to
process our request
|
In
case of SendRedirect call old request and response object is lost because
it’s treated as new request by the browser.
|
Visually
we are not able to see the forwarded address, its is transparent
|
In
address bar we are able to see the new redirected address it’s not
transparent.
|
In
address bar we are able to see the new redirected address it’s not
transparent.
|
SendRedirect
is slower because one extra round trip is required beasue completely new
request is created and old request object is lost.Two browser request
requird.
|
What
is the main difference between servlet context and servlet config?
Servlet context
|
Servlet config
|
1.ServletConfig object is one per servlet class
|
ServletContext object is global to entire web
application
|
2.Object of ServletConfig will be created
during initialization process of the servlet
|
Object of ServletContext will be created at the
time of web application deployment
|
3. Destroyed once the servlet execution is
completed.
|
destroyed once the application is removed from
the server.
|
4.ServletConfig available in javax.servlet.*;
package
|
ServletConfig available in javax.servlet.*;
package
|
What
is Servlet life cycle?
Servlet interface defines
the life cycle methods of servlet such as init(), service() and destroy(). The
Web container invokes the init(), service() and destroy() methods of a servlet
during its life cycle.
The Web container loads
the servlet class and creates instances of the servlet class.
The Web container invokes
init() method of the servlet instance during initialization of the servlet. The
init() method is invoked only once in the servlet life cycle.
The Web container invokes
the service() method to allow a servlet to process a client request.
The service() method
processes the request and returns the response back to the Web container.
The servlet then waits to
receive and process subsequent requests
The Web container calls
the destroy() method before removing the servlet instance from the service. The
destroy() method is also invoked only once in a servlet life cycle.
How
to call Stored Procedure in Hibernate?
CREATE PROCEDURE 'getCustomers'(status varchar(20))
BEGIN
SELECT * FROM
customerInfo WHERE status = status;
END $$
=======================================
Query query = session.createSQLQuery
("CALL getCustomers (: status)")
.add Entity (Customer.
Class)
.setParameter
("status", "Active");
List result = query.
List ();
for
(int i=0; i<result.size(); i++){
Customer customer = (Customer)
result.get(i);
System.out.println(customer.getCustomerName());
}
How
to call Stored Procedure in JDBC?
String
getDBUSERByUserIdSql = "{call getDBUSERByUserId (?,?,?,?)}";
callableStatement
= dbConnection.prepareCall(getDBUSERByUserIdSql);
callableStatement.setInt(1, 10);
callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(3, java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(4, java.sql.Types.DATE);
callableStatement.executeUpdate();
String
userName = callableStatement.getString(2);
String
createdBy =
callableStatement.getString(3);
Date createdDate = callableStatement.getDate(4);
What
is two-phase commit?
Two-phase
commit is a transaction protocol designed for the complications that arise with
distributed resource managers. With a two-phase commit protocol, the
distributed transaction manager employs a coordinator to manage the individual
resource managers.
What
is java.lang.OutOfMemoryError in Java
OutOfMemoryError
in Java is a subclass of java.lang.VirtualMachineError and JVM throws java.lang.OutOfMemoryError when
it ran out
of memory in the heap. OutOfMemoryError in Java can come anytime in heap mostly
while you try to create an object and there is not enough space on the heap to
allocate that object
Types of OutOfMemoryError in Java
Types of OutOfMemoryError in Java
I have seen mainly
two types of OutOfMemoryError in Java:
1) The java.lang.OutOfMemoryError: Java heap space
2) The java.lang.OutOfMemoryError: PermGen space
Though both of them occur because JVM ran out of memory they are quite different to each other and their solutions are independent of each other.
Since in most of JVM default size of Perm Space is around "64MB" you can easily run out of memory if you have too many classes or a huge number of Strings in your project.
An important point to remember is that it doesn't depend on –Xmx value so no matter how big your total heap size you can run OutOfMemory in perm space. The good thing is you can specify the size of permanent generation using JVM options "-XX: PermSize" and "-XX: MaxPermSize" based on your project need.
1) The java.lang.OutOfMemoryError: Java heap space
2) The java.lang.OutOfMemoryError: PermGen space
Though both of them occur because JVM ran out of memory they are quite different to each other and their solutions are independent of each other.
Since in most of JVM default size of Perm Space is around "64MB" you can easily run out of memory if you have too many classes or a huge number of Strings in your project.
An important point to remember is that it doesn't depend on –Xmx value so no matter how big your total heap size you can run OutOfMemory in perm space. The good thing is you can specify the size of permanent generation using JVM options "-XX: PermSize" and "-XX: MaxPermSize" based on your project need.
How to solve java.lang.OutOfMemoryError:
PermGen space
As explained in
above paragraph this OutOfMemory error in java comes when Permanent generation
of heap filled up. To fix this OutOfMemoryError in Java, you need to increase
heap size of Perm space by using
JVM option "-XX:
MaxPermSize". You can also specify initial size of Perm space by
using "-XX: PermSize" and keeping both initial and
maximum Perm Space you can
prevent some full garbage collection which may occur when Perm Space gets
re-sized. Here is how you can specify initial and maximum Perm
size in Java:
export JVM_ARGS="-XX:PermSize=64M -XX:MaxPermSize=256m"
Some time java.lang.OutOfMemoryError in Java gets tricky and on those cases profiling remains ultimate solution.Though you have the freedom to increase heap size in java, it’s recommended that to follow memory management practices while coding and setting null to any unused references.
That’s all from me on OutOfMemoryError in Java I will try to write more about finding the memory leak in java and using profiler in some other post
export JVM_ARGS="-XX:PermSize=64M -XX:MaxPermSize=256m"
Some time java.lang.OutOfMemoryError in Java gets tricky and on those cases profiling remains ultimate solution.Though you have the freedom to increase heap size in java, it’s recommended that to follow memory management practices while coding and setting null to any unused references.
That’s all from me on OutOfMemoryError in Java I will try to write more about finding the memory leak in java and using profiler in some other post
A Java
program is written using either a Text Editor like Textpad or an
IDE like Eclipse and is saved as a .java file. (Program.java)
The
.java file is then compiled using Java compiler and a .class file is obtained
from it. (Program.class)
The
.class file is now portable and can be used to run this Java program in any
platform.
Class
file (Program.class) is interpreted by the JVM installed on a particular
platform. JVM is part of the JRE software.
The
figure below explains the lifecycle of a Java Program. In words, the figure can
be explained as:
What
is ClassNotFoundException
ClassNotFoundException in Java is a subclass
of java.lang.Exception and Comes when Java Virtual Machine tries to load a particular class and
doesn't found the requested class in class path.
What is NoClassDefFoundError in Java
NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time.
NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time.
NoClassDefFoundError
is an error that is thrown when the Java Runtime System tries to load the
definition of a class, and that class definition is no longer available. The
required class definition was present at compile time, but it was missing at
runtime.
What is NullPointerException?
NullPointerException is a RuntimeException. In Java, a
special null value can be
assigned to an object reference. NullPointerException is thrown when
an application attempts to use an object reference that has the null value. These
include:
Calling an instance method on the object referred by a null reference.
Accessing or modifying an instance field of the object referred by a null
reference.
If the reference type is an array type, taking the length of a null
reference.
If the reference type is an array type, accessing or modifying the slots
of a null reference.
If the reference type is a subtype of Throwable, throwing a null
reference.
What is Index Out of Bound
Exception
Index out of Bound Exception Occurs when a programmer tries to
access an element of beyond the storage capacity of the index.
Index Out of Bound Exception are further classified into two types-
1. Array Index Out of Bound
Exception-These
are the exception arises when a programmer tries to access an element beyond
the capacity of index of the array. This exception is seen at run-time
rather than the compile time. This causes the program to crash at
run-time.Inorder to overcome this problem, you write the exceptional -handler
that process the program. Now place the code in try block that cause exception
in program. If exception arises in try block, you pass the control to the
specific catch block preceding try block If there is no catch block, the
program will terminated.
2. String Index Out of Bound
Exception-
The String Index Out of Bound Exception is a subclass of Index out of Bound
Exception. This exception is thrown when a String object
detects an index out-of-range index. Usually, An string object occurs
out-of-range , when the index is less than zero, or greater than or equal to
the length of the string.
What is Different between
Page and PageContext in Jsp?
Page and page context are implicit objects in jsp.These are created at
JSP translated time. Page is used as a scope with in one jsp.pagecontext is
used to initialize all implicit objects.(for example
pagecontext.getServletConfig() etc.)
What are the Implicit Objects
in Jsp?
Object
|
Type
|
out
|
JspWriter
|
request
|
HttpServletRequest
|
response
|
HttpServletResponse
|
config
|
ServletConfig
|
application
|
ServletContext
|
session
|
HttpSession
|
page Context
|
PageContext
|
page
|
Object
|
exception
|
Throwable
|
Can you call JavaScript
method with one argument instead of two arguments in JavaScript?
Yes we can call the javascript method but second argument is undefined value will pass
jQuery html() Method
Definition and Usage
The html() method sets or returns the content (innerHTML) of the selected
elements.
When this method is used to return content, it returns the
content of the FIRST matched element.
When this method is used to set content, it overwrites the
content of ALL matched elements.
Tip: To set or return only the text content of the selected
elements, use the text() method.
jQuery text() Method
Definition and Usage
The text() method sets or returns the text content of the selected
elements.
When this method is used to return content, it returns the text
content of all matched elements (HTML markup will be removed).
When this method is used to set content, it overwrites the
content of ALL matched elements.
Tip: To set or return the innerHTML (text + HTML markup) of the
selected elements, use the html() method.
Example:
$("button").click(function(){
$("p").text("Hello world!");
});
$("p").text("Hello world!");
});
No comments:
Post a Comment