You are on page 1of 35

Object Oriented Concepts and Basics

1. What is the most important feature of Java?


 Java is a platform independent language

 Garbage Collection

 Multithreading

 Object oriented

2. What do you mean by platform independence?


← Platform independence means that we can write and compile the java code in one platform (eg
Windows) and can execute the class in any other platform eg (Linux,Solaris,etc). Here in Linux
and Solaris you need to have JVM installed.

3. Is JVM platform independent?


← JVM's are not platform independent. JVM's are platform specific run time implementation
provided by the vendor.

4.  What is the difference between a JDK and a JVM?


← JDK is Java Development Kit which is for development purpose and it includes execution
environment also. But JVM is purely a run time environment and hence you will not be able to
compile your source files using a JVM.

5. What is the use of bin and lib in JDK?


← Bin contains all tools such as javac, applet viewer, awt tool, etc., whereas lib contains API and
all packages.

1. What is difference between Path and Classpath?

Path and Classpath are operating system level environment variables. Path is used define
where :.class files.

2. Which part of JVM will allocate the memory for a java program?
Class loader subsystem of JVM will allocate the necessary memory needed by the java program.

3. What is JIT Compiler?


JIT compiler is the part of JVM which increases the speed of execution of a Java program.
4. What is the difference between procedural and object-oriented programs?

a) In procedural program, programming logic follows certain procedures and the instructions are
executed one after another. In OOP program, unit of program is object, which is nothing but
combination of data and code.

b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is
accessible within the object and which in turn assures the security of the code

Lakven Technologies
5. What is Object?

A Java object is a set of data combined with methods for manipulating that data. An object is
made from a class; a class is the blueprint for the object.

Each object made from a class will have its own values for the instance variables of that class.
Instance variables are things an object knows about itself.

Things an object can do are called methods.

The three steps to creating a Java object are:

 Object Declaration
 Object Instantiation

 Object Initialization

Object Declaration

Declaring an object associates a variable name with an object.

Object Instantiation

Instantiating an object allocated space in memory for the object. This is accomplished with the
new operator.

Object Initialization

Initializing an object fills the objects variables with an initial set of values. This is accomplished
using a constructor.

6. What is class?

A class is a group of variables and methods. In java class contains the logic to execute some task.

Real time definition:

Collection of attributes is called class, Real time example......human body

7. Explain the reason for each keyword of public static void main (String args[])?

public- main (..) is the first method called by java environment when a program is executed so it
has to accessible from java environment. Hence the access specifier has to be public.

Static: Java environment should be able to call this method without creating an instance of the
class, so this method must be declared as static.

Lakven Technologies
void: main does not return anything so the return type must be void

String args [] : The argument String indicates the argument type which is given at the command
line and arg is an array for string given during command line.

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

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

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

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

Program compiles and runs properly.

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

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

11. In System.out.println(), what is System, out and println?

System is a predefined final class,

Out is a PrintStream object and

Println is a built-in overloaded method in the out object.

12. What are the oops concepts in java, explain with real-time examples?

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphisam

Abstraction:-Hiding non-essential features and showing the essential features or Hiding


unnecessary data from the users details, is called abstraction.

Real Time example: TV Remote Button

In Remote there is number format, power buttons and other buttons. We can see the
buttons and we cannot see the button circuits, i.e buttons circuits and wirings all are
hidden.

Encapsulation:

Lakven Technologies
Writing Operations and methods stored in a single Unit is called Encapsulation. This
keeps the data safe from outside interface and misuse

Real Time Example: Medical Capsules

Capsule is the best real time example for it. In it we will have two types of drugs
combined as single capsule.

Advantage: Maintance will be good


Inheritance:

Using properties of one class in another class is called Inheritance.

Real Time Example: Father and Son Relationship

Advantages: Reusability of code

Polymorphism:

Single Form behaving differently in different Situations is called polymorphism.

Example: Person

Person in Office acts Employer and in Public Good Citizen.

13. What is the access specifies in java and explain those accessibility?

Java offers four access specifiers, listed below in decreasing accessibility:

 Public- public classes, methods, and fields can be accessed from everywhere.
 Protected- protected methods and fields can only be accessed within the same class to
which the methods and fields belong, within its subclasses, and within classes of the same
package.

 Default(no specifier)- If you do not set access to specific level, then such a class, method, or
field will be accessible from inside the same package to which the class, method, or field
belongs, but not from outside this package.

 Private- private methods and fields can only be accessed within the same class to which the
methods and fields belong. Private methods and fields are not visible within subclasses and
are not inherited by subclasses.

 Situation   public   protected   default   private 

 Accessible to class
yes yes yes no
 from same package? 

 Accessible to class yes  no, unless it is a subclass  no no

Lakven Technologies
 from different package? 
14. What is constructor?

A constructor is a special method whose task is to initialize the object of its class. It is special
because its name is the same as the class name. They do not have return types, not even void
and therefore they cannot return values.

They cannot be inherited, though a derived class can call the base class constructor. Constructor
is invoked whenever an object of its associated class is created.

15. How does the Java default constructor be provided?

If a class defined by the code does not have any constructor, compiler will automatically provide
one no-parameter-constructor (default-constructor) for the class in the byte code. The access
modifier (public/private/etc.) of the default constructor is the same as the class itself.

16. Explain overloading with example?

Writing more than one method in a class with the same name is called overloading.

Example of Overloading
     int add(int a,int b)
     float add(float a,int b)
     float add(int a ,float b)
     void add(float a)
     int add(int a)

In the overloading the return type can be same, but the parameters should be changed.

In case of overloading JVM decides which method to execute at compile time.

17. Explain overriding with example?

Writing the method in subclass which is already existing in super class is called overriding.

When you override methods, JVM determines the proper methods to call at the program’s run
time, not at the compile time.

Overriding occurs when a class method has the same name and signature as a method in parent
class

18. What is static and dynamic polymorphism?

Overloading the nothing but static polymorphism. Overriding is nothing but dynamic
polymorphism.

19. How can you override method which throws exception?

Lakven Technologies
Whenever we are overriding the method which throws exception in super class, in subclass we
need to throw the same exception or we can throw the subclass of the super class exception.
But we cannot throw the super class of the super class method’s exception.

20. What the access specifier’s hierarchy when you override method?

Whenever we are overriding the method the subclass method’s access specifier should be same
as super class’s method or it can be it can be higher level access specified.

But it should not be lesser level access specified.

That means in overriding we can increase the visibility of method but we cannot decrease the
visibility.

21. When is static variable loaded? Is it at compile time or runtime? When exactly a static block is
loaded in Java?

Static variable are loaded when class loader brings the class to the JVM. It is not necessary that
an object has to be created. Static variables will be allocated memory space when they have
been loaded. The code in a static block is loaded/executed only once i.e. when the class is first
initialized. A class can have any number of static blocks. Static block is not member of a class,
they do not have a return statement and they cannot be called directly. Cannot contain this or
super. They are primarily used to initialize static fields.

22.  What is the importance of static variable?

Static variables are class level variables where all objects of the class refer to the same variable.
If one object changes the value then the change gets reflected in all the objects.

23. What is static keyword in java?

Static is keyword in java.

We can apply static keyword for variables, methods and classes.

Static variables: the variable which defined with static keyword is called static variable.

If we create n number of objects to the class, only one copy of the memory will be allocated.

Static methods: the method which defined with static keyword is called static method. Static
methods will be loaded by jvm at the class loading time.

Static blocks will be executed by JVM before executing the main method. static lock looks like as
below

static {

// some statements

Lakven Technologies
}

Static classes: Top level classes cannot be static classes and inner classes can be static classes.

We cannot call or access the not static members in the static methods.

If we have static variables or methods, by using this and super we cannot access these variables
or methods. The reason is that static variable and methods are for class and loaded at class
loading time, but the this and super is for the object.

24. What is instance block?


If you write the code in open brace and close brace ( “{ “and “}”)then it is called instance block.

The instance block will be executed after creating the object for the class.

25. What are the differences between Class / static Methods and Instance Methods?

Class Methods Instance Methods

Instance methods on the other hand require an


instance of the class to exist before they can be called,
Class methods are methods which are declared as
so an instance of a class needs to be created by using
static. The method can be called without creating an
the new keyword.
instance of the class
Instance methods operate on specific instances of
classes.

Class methods can only operate on class members Instance methods of the class can also not be called
and not on instance members as class methods are from within a class method unless they are being
unaware of instance members. called on an instance of that class.

Class methods are methods which are declared as


static. The method can be called without creating an  Instance methods are not declared as static.
instance of the class.

26. What is this and super in java and explain?


this and super are the keywords in java.
this keyword refers the current object ,by using the this keyword we can access all the methods
and variables of that class.
Super refers the super class object, if you want to access the super class variables, methods and
constructors you can call them using the super keyword.
This or super should be the first statement in the constructor.

27. What is super Keyword in java?

Lakven Technologies
super is a keyword which is used to access the method or member variables from the
superclass. If a method hides one of the member variables in its superclass, the method can
refer to the hidden variable through the use of the super keyword. In the same way, if a method
overrides one of the methods in its superclass, the method can invoke the overridden method
through the use of the super keyword.
Note:

 You can only go back one level.


 In the constructor, if you use super(), it must be the very first code, and you cannot access any
this.xxx variables or methods to compute its parameters.

28. How can you call super class members in subclass?


By using the super keyword, we can call the super class members in its sub class.

29. What is JVM?

Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine
plays the central role in this concept.

The JVM is the environment in which Java programs execute. It is a software that is
implemented on top of real hardware and operating system.

When the source code (.java files) is compiled, it is translated into byte codes and then placed
into (.class) files. The JVM executes these byte codes. So Java byte codes can be thought of as
the machine language of the JVM.

A JVM can either interpret the byte code one instruction at a time or the byte code can be
compiled further for the real microprocessor using what is called a just-in-time compiler. The
JVM must be implemented on a particular platform before compiled programs can run on that
platform.

30. What is call by value and call by reference, whether the java uses call by value or call by
reference?

Pass by reference means, passing the address itself rather than passing the value. Pass by value
means passing a copy of the value. Java uses the pass by value instead of reference.

31. What is finalize () method?


finalize () is the method which is called by JVM before garbage collection.

finalize () method is used to clean up the unused references of the objects, then JVM executes
Garbage collection to clean up the memory.

Lakven Technologies
Finalize () method is the method of Object class. The syntax is as follows
protected void finalize () throws Throwable
{
}
32. What is the garbage collection?
The process of reclaiming the memory from the un used objects is called Garbage collection.
Garbage collection is the automatic process which Is called by JVM.

JVM executes the garbage collection whenever it is required.

We cannot force the JVM to call Garbage collection, but we can suggest the JVM to call GC by
using the System.gc () or Runtime.gc(). But JVM does not give guarantee.
33. Can we force JVM for garbage collection?
We cannot force the JVM to call Garbage collection, but we can suggest the JVM to call GC by
using the System.gc() or Runtime.gc(). But JVM does not give guarantee.
34. Which algorithm is used by garbage collector to remove the unused variables or objects from
memory?
Garbage collector uses many algorithems but the most commonly used algorithm is
mark andsweep
35. What is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any
cleanup processing before the object is garbage collected

36. Explain final keyword?


final is a keyword in java. We can apply final keyword for variables, methods and classes.
Final variables:
Once we have initialized the final variable, we cannot change that value.
Ex:

public class FinalTest {


final int X =10;
private void changeFinalVar() {

X =20; // gives error saying that final value can not be changed
}
}
Final methods:
Once we have defined the final method, we cannot override that method in subclass.
Ex:

public class Final {

Lakven Technologies
final int X =10;
final int m1() {
return X;
}

class FinalTest extends Final


{

int m1() // gives the error, saying that we can not override fina method
{
return 100;
}
}

Final Classes: Final class cannot be extended by any other class.

Example: All Wrapper classes in java, StringBuffer etc.

37. What is abstract class?


A class which starts with abstract keyword is called the abstract class.
Abstract class may or may not contain abstract methods.
Abstract class may contain all the concrete methods or all the abstract methods.
It also can contain some abstract methods and some concrete methods.

We can’t create the object for the abstract class. But we can create the reference variable to it.

Once we have created the abstract class

1. We have to extend the abstract class form any other class. (if no class is extending then
there is no use of defining abstract class)
2. If any class is extending the abstract class, then we have to provide the body for the abstract
methods in the sub class. Incase if we are not proving the body, then the subclass will also
becomes abstart class.

Advantage of the abstract class is that subclass can implement the method body as per his
requirement.

Ex: Let us assume a father (Base Class), he has some Land (Member Function), and he has not
done anything with it.

(Implementation) in it... As his Child (Derived Class), he Takes the Land(Member Function) from
the Father(Base) and does Agriculture(implementing the M.F. of Parent Class) in the Child...

Or he can build the house in it. It depends on his requirement.


38. What is Abstract method?
A method which does not contain body is called abstract method.

Lakven Technologies
Abstract method ends with semicolon.
Ex: void m1();
39. Can we apply final keyword abstract class?

No we cannot apply final keyword for abstract class. A final class means we cannot extend that
class.
But if you declare abstract class, you have to extend that class by another class; otherwise there
is no use with abstract class.
So we can not apply final class for abstract class.

40. What is Interface?


An interface is which it is having all the abstract methods in it. Interface starts with interface
keyword.
We cannot create the object for interface.

Once we have created the interface

1. We have to implement the interface form any other class. (if no class is implementing then
there is no use of defining interface)
2. If any class is implementing the interface, then we have to provide the body for the abstract
methods in the implementing class. Incase if we are not proving the body, then the subclass
will becomes abstract class.
41. What is similarities/difference between an Abstract class and Interface?
Differences are as follows:
• Interfaces provide a form of multiple inheritance. A class can extend only one other
class.
• Interfaces are limited to public methods and constants with no implementation.
Abstract classes can have a partial implementation, protected parts, static methods,etc.
• A Class may implement several interfaces. But in case of abstract class, a class may
extend only one abstract class.
• Interfaces are slow as it requires extra indirection to to find corresponding method in
the actual class. Abstract classes are fast.
Similarities:
• Neither Abstract classes or Interface can be instantiated.

42. When should I use abstract classes and when should I use interfaces?

Use Interfaces when…

 You see that something in your design will change frequently.

Lakven Technologies
 If various implementations only share method signatures then it is better to use
Interfaces.

 you need some classes to use some methods which you don't want to be included in the
class, then you go for the interface, which makes it easy to just implement and make use
of the methods defined in the interface.

Use Abstract Class when…

 If various implementations are of the same kind and use common behavior or status
then abstract class is better to use.
 When you want to provide a generalized form of abstraction and leave the
implementation task with the inheriting subclass.

 Abstract classes are an excellent way to create planned inheritance hierarchies. They're
also a good choice for nonleaf classes in class hierarchies

43. Why Java does not support multiple inheritance?

Java Doesnot support multiple inheritance because of Diamond problem, consider a class A
has foo() method and then B and C derived from A and has there own foo() implementation
and now class D derive from B and C using multiple inheritance and if we refer just foo()
compiler will not be able to decide which foo() it should invoke. This is also called Diamond
problem because structure on this inheritance scenario is similar to 4 edge diamond, see
below

           A foo()
           / \
          /   \
   foo() B     C foo()
          \   /
           \ /
            D
           foo()

44. What is implicit casting?

Implicit casting is the process of simply assigning one entity to another without any
transformation guidance to the compiler. This type of casting is not permitted in all kinds of
transformations and may not work for all scenarios.

int i = 1000;

long j = i; //Implicit casting

45. What is explicit casting?

Lakven Technologies
Explicit casting in the process in which the complier are specifically informed to about
transforming the object.

long i = 700.20;

int j = (int) i; //Explicit casting

46. What is widening and narrowing?


Converting lower data type into a higher data type is called widening and converting a higher
data type into a lower type is called narrowing. Widening is safe and hence even if the
programmer does not use cast operator, the Java compiler does not flag any error. Narrowing is
unsafe and hence the programmer should explicitly use cast operator in narrowing.

47. What is reflection API? How are they implemented?


Reflection is the process of introspecting the features and state of a class at runtime and
dynamically manipulate at run time.
This is supported using Reflection API with built-in classes like Class, Method, Fields, and
Constructors etc.
Example: Using Java Reflection API we can get the class name, by using the getName method.

48. Where and how can you use a private constructor?


Private constructor can be used if you do not want any other class to instantiate the class. This
concept is generally used in Singleton Design Pattern. The instantiation or object creation for
such classes is done from a static public method

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

A constructor is a member function of a class that is used to create objects of that class, invoked
using the new operator. It has the same name as the class and has no return type. They are only
called once, whereas member functions can be called many times. A method is an ordinary
member function of a class. It has its own name, a return type (which may be void), and is
invoked using the dot operator. Constructor will be automatically invoked when an object is
created whereas method has to be called explicitly.
super.method() is used to call a super class method from a sub class. To call a constructor of the
super class, we use the super(); statement as the first line of the subclass’s constructor.

50. What is the purpose of the Runtime class?


The purpose of the Runtime class is to provide access to the Java runtime system.
It returns the runtime information like memory availability.

Lakven Technologies
* Runtime.freeMemory() --> Returns JVM Free Memory
* Runtime.maxMemory() --> Returns the maximum amount of memory that the JVM will
attempt to use. It also helps to run the garbage collector
* Runtime.gc
51. What is an inner class?
Inner class is a class defined inside other class and act like a member of the enclosing class

52. How to access the inner class from code within the outer class?

The inner class is instantiated only through the outer class instance.
class EnclosingOuter {
private int noInnerClass = 1;
public void getNoOfInnerClasses(){
           Inner in = new Inner();
System.out.println(“No Of Inner classes is : “+ in.getNoOfClassesFromOuter());
}
class Inner{

public int getNoOfClassesFromOuter(){ return noInnerClass; }

Here the method getNoOfInnerClasses() is called on the outer class’s instance through this outer
class instance the inner class instance in is created.

53. How to create an inner class instance from outside the outer class instance code?

To create an instance of the inner class you must have the instance of its enclosing class.

class EnclosingOuter {
class Inner{ }
}
 To create the instance of inner class from class other than the enclosing class.
1) class OtherThanOuter{
EnclosingOuter out = new EnclosingOuter();
EnclosingOuter.Inner in = out.new Inner();
}

2) class OtherThanOuter{
EnclosingOuter.Inner out = new EnclosingOuter.Inner ();

54. Can Abstract Class have constructors? Can interfaces have constructors?

Lakven Technologies
Abstract class's can have a constructor, but you cannot access it through the object, since you
cannot instantiate abstract class. To access the constructor create a sub class and extend the
abstract class which is having the constructor.

Example
public abstract class AbstractExample {
public AbstractExample(){
System.out.println("In AbstractExample()");
}
}

public class Test extends AbstractExample{


public static void main(String args[]){
Test obj=new Test();
}
}

55. What is the difference between return and System.exit(0) ?

Return statement is used inside a method to come out of it. System.exit( 0) is used in any
method to come of the program.

56. What is the difference between System.exit(0) and System.exit(1) ?

System.exit(0) terminates the program normally. Whereas System.exit(1) terminates the


program because of some error encountered in the program.

57. What are different types of cloning in Java?


Java supports two type of cloning: - Deep and shallow cloning. By default shallow copy is used in
Java. Object class has a method clone () which does shallow cloning.
58. What is difference between DEEP and SHALLOW Cloning?

SHALLOW Cloning just allows cloning the object but not sub objects.

For ex, object of address contains street and city. To clone it, set references to the street
and city objects.
DEEP Cloning clones the objects as well as sub objects.
For example, a car has four wheels. To clone a car, four wheels must be cloned.
That distinction is better understood in terms of databases.
You need deep Cloning, if the entity requires "cascade deleting". You need shallow Cloning if
"cascade deleting" is not needed.

59. How to implement CLONING?


By default, classes in JAVA do not support CLONING.
You should override implementation of the clone() method & make it public.

Lakven Technologies
Inside the method, your first action must be super.clone().
Classes that want to allow CLONING must implement the marker interface Cloneable.

60. Whether java uses Pass by Value or Pass by Reference?


Java only supports pass by value
Pass by value in java means passing a copy of the value to be passed. Pass by reference in
java means the passing the address itself. In Java the arguments are always passed by value.
With Java objects, the object reference itself is passed by value and so both the original
reference and parameter copy both refer to the same Java object. Java primitives too are
passed by value.
61. What is a marker interface?
Marker interfaces are those which do not declare any required methods, but signify their
compatibility with certain operations. The java.io.Serializable interface and Cloneable are
typical marker interfaces. These do not contain any methods, but classes must implement
this interface in order to be serialized and de-serialized.

62. What is singleton class and where is it used?

Singleton is a design pattern meant to provide one and only one instance of an object. Other
objects can get a reference to this instance through a static method (class constructor is
kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to
create a single instance of a given class. This has advantages in memory management, and
for Java, in garbage collection. Moreover, restricting the number of instances may be
necessary or desirable for technological or business reasons--for example, we may only
want a single instance of a pool of database connections.
63. Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.

String and String Buffer


64. What is String?

Lakven Technologies
A string is s character array.
A String is a final class. String class is the part of java.lang package.

String is immutable. Once it is defined we cannot change the value of string without assigning to
another object.

String s = "Hello";
s.concat("world");
System.out.println(s);-> will print Hello only.

65. What is String Buffer?


String Buffer is mutable and final class.
Once it is defined we can change the contents without assigned to another object.

StringBuffer s = "Hello";
s.append(" world");
System.out.println(s);-> prints Hello World.

66. What is the difference between String and StringBuffer?

String objects are immutable whereas StringBuffer objects are not. StringBuffer support
growable and modifiable strings but String does not support.

67. Difference between String StringBuffer and StringBuilder?

String is immutable whereas StringBuffer and StringBuilder can change their values.

The only difference between StringBuffer and StringBuilder is that StringBuilder is


unsynchronized whereas StringBuffer is synchronized.

So when the application needs to be run only in a single thread then it is better to use
StringBuilder. StringBuilder is more efficient than StringBuffer.

Criteria to choose among String, StringBuffer and StringBuilder

1. If your text is not going to change use a string Class because a String object is
immutable.
2. If your text can change and will only be accessed from a single thread, use a
StringBuilder because StringBuilder is unsynchronized.
3. If your text can changes, and will be accessed from multiple threads, use a StringBuffer
because StringBuffer is synchronous
68. In how many ways we can create String Objects and what are they and explain?

We can create Strings in 2 ways.


1. Using constant pooling mechanism

Lakven Technologies
2. Using new operator

Constant pooling mechanism:

String s = “lakven”;

String s1 = “lakven”

In the constant pooling mechanism, once the String is created JVM creates the one reference id
for the string.

When the second String is creating, jvm first checks whether the string is available in memory (in
constant pool) and if it is available JVM refers the same reference id and it will not create new
one. As it is referring the same reference, the memory will be saved.

In the above example both the string s and s1 refers the same memory location.

Using new operator

String s = new String (“lakven”);

String s1 = new String (“lakven”);

If you create the Strings by using new operator, for each and every string JVM creates
one new memory location even though the String contents are same.

Note: Creating strings as literals instead of creating String objects using 'new' key word
whenever possible

69. Give some method names in String and explain with example?

The following program explains the usage of the some of the basic String methods like;

1. compareTo(String anotherString)
Compares two strings lexicographically.

2. charAt(int index)
Returns the character at the specified index.

3. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)


Copies characters from this string into the destination character array.

4. length()
Returns the length of this string.

5. equals(Object anObject)
Compares this string to the specified object.

Lakven Technologies
6. equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.

7. toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default
locale.

7. toLowerCase()
Converts all of the characters in this String to upper case using the rules of the default
locale.

9. concat(String str)
Concatenates the specified string to the end of this string.

10. indexOf(int ch)

Returns the index within this string of the first occurrence of the specified character.

11. indexOf(int ch, int fromIndex)

Returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index.

12. indexOf(String str)

Returns the index within this string of the first occurrence of the specified substring.

13. indexOf(String str, int fromIndex)

Returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.

14. lastIndexOf(int ch)

Returns the index within this string of the last occurrence of the specified character.

15. lastIndexOf(int ch, int fromIndex)

Returns the index within this string of the last occurrence of the specified character,
searching backward starting at the specified index.

16. lastIndexOf(String str)

Returns the index within this string of the rightmost occurrence of the specified
substring.

17. lastIndexOf(String str, int fromIndex)

Lakven Technologies
Returns the index within this string of the last occurrence of the specified substring,
searching backward starting at the specified index.

18. substring(int beginIndex)

Returns a new string that is a substring of this string.

19. substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

20. replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string
with newChar.

21. trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

70. Which method of String is used to find whether the part of string is exists in the string or not?
We can use the indexOf() method to check whether the string is available or not.
If the specified character or the string is found in the String, then the position will be returned.
If it is not found it returns the -1.
71. What is the difference between and == and equals method.

The == operator compares two objects to determine if they are the same object in memory i.e.
present in the same memory location. It is possible for two String objects to have the same
value, but located in different areas of memory.

== Compares references while .equals compares contents. For two String objects, value
equality means that they contain the same character sequence. For the Wrapper classes,
value equality means that the primitive values are equal.

 public class EqualsTest {

public static void main(String[] args) {

String s1 = "lakven";
String s2 = s1;
String s5 = " lakven ";
String s3 = new String("lakven ");
String s4 = new String("lakven ");
System.out.println("== comparison : " + (s1 == s5));
System.out.println("== comparison : " + (s1 == s2));
System.out.println("Using equals method : " + s1.equals(s2));

Lakven Technologies
System.out.println("== comparison : " + s3 == s4);
System.out.println("Using equals method : " + s3.equals(s4));
}
}

72. What is difference between String and StringTokenizer?

A StringTokenizer is utility class used to break up string.

StringTokenizer st = new StringTokenizer("Hello World");


   while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
     }
Output:
Hello
World
73. Explain the subString() method with example?
If you need the part of String from the existing String, we can use substring() method.

String str = "SubString Example";

String sub5 = str.substring(5); // returns "ring Example"

String sub3_6 = str.substring(3, 6); // returns "Str"

74. Difference between indexOf () and lastIndexOf () methods.


indexOf(String s) returns the index position of the first occurance of the String.

lastIndexOf(String s) returns the last index position of the first occurance of the String

String s= "lakven technologies";


System.out.println(s.indexOf("n")); // returns 5
System.out.println(s.lastIndexOf("n")); returns 11

Exception Handling
75. What is an exception?
An exception is an abnormal condition that arises in a code sequence at run time

76. Explain the exception hierarchy?

Lakven Technologies
77. What is an error?
Errors are irrecoverable exceptions, usually a program terminates when an error is encountered.
78. Difference between Exception and Error?
Errors are irrecoverable exceptions. Exceptions we can handle using the try catch block.

79. Difference between checked and unchecked exceptions?

A checked exception is some subclass of Exception (or Exception itself), excluding class
RuntimeException and its subclasses. Making an exception checked forces client programmers
to deal with the exception may be thrown. Checked exceptions must be caught at compile time.
Example: IOException.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its
subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't
force client programmers either to catch the exception or declare it in a throws clause. In fact,
client programmers may not even know that the exception could be thrown.

Example: ArrayIndexOutOfBoundsException. Errors are often irrecoverable conditions.

80. How can you handle exceptions?


We can catch the exceptions using try, catch, finally, throw and throws keywords.
81. Can we write more than one catch blocks for one try block? If yes, what should be the exception
hierarchy?
Yes, we can write more than 1 catch blocks for one try block.
But we have to follow the ascending order while catching the exceptions using multiple catches,
we need to catch the subclasses first then the next level of super class.

Lakven Technologies
82. Can we write finally without catch and vice versa?
Yes, we can write finally without catch as well as catch without finally for try block.
But try should have either catch or finally.

83. What is the difference between throw and throws?


 throw keyword (note the singular form) is used to force an exception. It can also pass a custom
message to your exception handling module. Moreover throw keyword can also be used to pass
a custom message to the exception handling module i.e. the message which we want to be
printed.
Throw is used to actually throw the exception, whereas throws is declarative for the method.
They are not interchangeable.
Throws: this is to be used when you are not using the try catch statement in your code but you
know that this particular class is capable of throwing so and so exception(only checked
exceptions). In this you do not use try catch block but write using the throw clause at
appropriate point in  you code and the exception is thrown to caller of the method and is
handled by it

84. Can we write try block in side catch block?


Yes we can write try block inside catch s well as in finally also.
85. Can we write try inside try block?

Yes we can write as many try blocks inside try block as long as it is following catch or finally.

86. What is finally block?


The finally is a block which you can place after catch block. The finally block contains code that
will be run whether or not an exception is thrown in a try block. The general syntax looks like:

Try {
// some code
}
Catch(ExceptionClass y) {
// some code
}
Finally{
//this code will be executed whether or not an exception
//is thrown or caught
}

87. Explain the user defined Exceptions?

User defined Exceptions are custom Exception classes defined by the user for specific purpose. A
user defined exception can be created by simply sub-classing an Exception class or a subclass of
an Exception class. This allows custom exceptions to be generated (using throw clause) and

Lakven Technologies
caught in the same way as normal exceptions.
Example:

class CustomException extends Exception {

88. What is NullPointerException and how to handle it?

When an object is not initialized, the default value is null. When the following things happen,
the NullPointerException is thrown:

Calling the instance method of a null object.


Accessing or modifying the field of a null object.
Taking the length of a null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.

NullPointerException is a runtime exception. The best practice is to catch such exception even if
it is not required by language design.

IO Streams
89. What is Serialization and deserialization?
Serializable is a marker interface. When an object has to be transferred over a network
( typically through rmi or EJB) or persist the state of an object to a file, the object Class needs
to implement Serializable interface. Implementing this interface will allow the object converted
into bytestream and transfer over a network.

The process of reconstructing the Object from the Bytestream is called deserialization.

90. What is the Common Usage of serialization?


Whenever an object is to be sent over the network or saved in a file, objects are serialized.

91. How to make a class or a bean serializable? How do I serialize an object to a file?

An object must implement the Serializable or Externalizable interface before it can be written to
a stream as an object. The class whose instances are to be serialized should implement an

Lakven Technologies
interface Serializable. Then you pass the instance to the ObjectOutputStream which is
connected to a fileoutputstream. This will save the object to a file.

92. What are Transient and Volatile Modifiers?


A transient variable is a variable that may not be serialized i.e. the value of the variable can’t be
written to the stream in a Serializable class. If you don't want some field to be serialized, you can
mark that field transient or static. In such a case when the class is retrieved from the
ObjectStream the value of the variable is null.
Volatile modifier applies to variables only and it tells the compiler that the variable modified by
volatile can be changed unexpectedly by other parts of the program.

93. What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream classhierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/
OutputStream class hierarchy is byte-oriented.

94. What is the difference between Serializalble and Externalizable interface? 

When you use Serializable interface, your class is serialized automatically by default. But you can
override writeObject() and readObject() two methods to control more complex object
serailization process. When you use Externalizable interface, you have a complete control over
your class's serialization process.

Multithreading
95. What is thread?
Thread is a small program which does some task.
96. What is the difference between process and thread?

A thread is a separate path of execution in a program. A Process is a program in execution.

97. How can we create threads and explain?

There are two ways to create a new thread.

Lakven Technologies
1) Extend the Thread class and override the run() method in your class. Create an instance of the
subclass and invoke the start() method on it, which will create a new thread of execution. e.g.
public class NewThread extends Thread{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
c.start();
}}
2)Implements the Runnable interface.The class will have to implement the run() method in the
Runnable interface. Create an instance of this class. Pass the reference of this instance to the
Thread constructor a new thread of execution will be created. e.g. class
public class NewThread implements Runnable{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}

98. Which is the best way to create threads?


It’s better to create the thread using the runnable interface. If you create the thread by
implementing the runnable interface, at the same time you can extend the other class whatever
you required.
But if you create thread by extending thread, you cannot extend another class.

1. What are the different states of a thread's lifecycle?

The different states of threads are as follows:

Lakven Technologies
1) New – When a thread is instantiated it is in New state until the start() method is called on the
thread instance. In this state the thread is not considered to be alive.
2) Runnable – The thread enters into this state after the start method is called in the thread
instance. The thread may enter into the Runnable state from Running state. In this state the
thread is considered to be alive.
3) Running – When the thread scheduler picks up the thread from the Runnable thread’s pool,
the thread starts running and the thread is said to be in Running state.
 4) Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable.
The thread switches to this state because of reasons like wait method called or sleep method
has been called on the running thread or thread might be waiting for some i/o resource so
blocked.

5)  Dead – When the thread finishes its execution i.e. the run() method execution completes, it
is said to be in dead state. A dead state can not be started again. If a start() method is invoked
on a dead thread a runtime exception will occur.

2. What is the purpose of the wait (), notify (), and notifyAll() methods?

Wait(): whenever the wait() is called on the particular thread, that thread will be in waiting state
and cannot come to running state till the notify() is called.
notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
highest priority thread will run first.

3. What is deadlock?

When two threads are waiting for each other and can’t proceed until the first thread obtains a
lock on the other thread or vice versa, the program is said to be in a deadlock.

4. What’s the difference between the methods sleep () and wait ()?

When the sleep () method calls the thread will sleep for specified time period.
Ex: sleep (1000), puts the thread aside for exactly one second.
When the sleep () method calls the thread will sleep for specified time period. But it can come to
running state before the specified time when the notify () method is called. The method wait ()
is defined in the Object and the method sleep() is defined in the class Thread.

5. What are Thread priorities?

Every thread has a priority, the higher priority thread gets preference over the lower priority
thread by the thread scheduler

6. What is synchronization and explain?

The process of allowing only one thread at a time is called Synchronization.

Lakven Technologies
Synchronized keyword provides a lock on the object.
We can apply Synchronized keyword for methods, blocks and static methods.

When we apply the synchronized keyword for the static method, then the class will be locked.
public void synchronized method(){} 
public void synchronized staticmethod(){}
public void myMethod(){

synchronized (this){      // synchronized keyword on block of  code


      }

7. What is daemon thread and which method is used to create the daemon thread?

Daemon threads are threads with low priority and runs in the back ground doing the garbage
collection operation for the java runtime system.
The setDaemon() method is used to create a daemon thread. These threads run without the
intervention of the user. To determine if a thread is a daemon thread, use the accessor method
isDaemon().

8. Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.

9. What is an object's locking?

Answer: when we add a synchronized keyword to the block or the method, the object will be
locked.
When object is locked at a time only one thread can access the method or block.

10. Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object. When we
add the synchronized keyword for the static method, the class will be locked.

11. Can a method be static and synchronized?

A static method can be synchronized. If you do so, the JVM will obtain a lock on the
java.lang.Class instance associated with the object. It is similar to saying:

       synchronized(XYZ.class) { }

Lakven Technologies
Collections Framework
12. What is collection API?

The Collections API is a set of classes and interfaces that support operations on collections of
objects.

A collection represents a group of objects, known as its elements. This framework is provided in
the java.util package. Objects can be stored, retrieved, and manipulated as elements of
collections.

Collection API Reduces programming efforts, Increases program speed and quality

13. What are differences between arrays and collections?

Collections
Arrays
1.  Arrays r fixed in size and hence once we created 1. Collections are growable in nature and hence
an array we are not allowed to increase or decrease based on our requirement we can increase or
the size based on our requirement. decrease the size.
2.  Memory point of view arrays are not 2. Memory point of view collections are
recommended to use recommended to use.
3. Performance point of view arrays are 3. Performance point of view collections are not
recommended to use recommended to use.
4.  Arrays can hold only homogeneous elements 4. Collections can hold both homogeneous and
heterogeneous elements.
5. Arrays can hold both primitives as well as objects 5. Collections can hold only objects.
6. For any requirement, there is no ready method 6. For every requirement ready made method
support compulsory programmer has to code support is available. Being a programmer we have to
explicitly. know how to use those methods and we are not
responsible to implement those.

14. What are the advantages of ArrayList over arrays?

Some of the advantages ArrayList has over arrays are:

 It can grow dynamically


 It provides more powerful insertion and search mechanisms than arrays.

15. What is the difference between Enumeration and Iterator?

Lakven Technologies
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a
remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it
has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate
the objects also like adding and removing the objects.

So Enumeration is used whenever we want to make Collection objects as Read-only

16. Difference between Vector and ArrayList? What is the Vector class?
ArrayList Vector

ArrayList is NOT synchronized by default. Vector List is synchronized by default.

Vector list can use Iterator and Enumeration Interface to


ArrayList can use only Iterator to access the elements.
access the elements.

The ArrayList increases its array size by 50 percent if it A Vector defaults to doubling the size of its array if it runs
runs out of room. out of room

ArrayList has no default size. While vector has a default size of 10.
17. What is the difference b/w Iterator and ListIterator?

 ListIterator is the child interface of the Iterator


 Iterator is the single direction cursor where as ListIterator is bidirectional cursor.
 While iterating the elements by Iterator we can perform only read and remove
operations. But by using ListIterator we can perform read,removal, replace and addition
of new objects also.
 Iterator is applicable for every Collecton implemented class object but ListIterator  is
applicable only for List implemented class objects.
 Iterator can be get by using iterator() of Collection interface where as ListIterator can be
get by using listIterator() method of List interface
 both are introduced in 1.2 version

18. Where will you use Vector and where will you use ArrayList?

The basic difference between a Vector and an ArrayList is that, vector is synchronized while
ArrayList is not.
Whenever there is a possibility of multiple threads accessing the same instance, one should use
Vector.
While if not multiple threads are going to access the same instance then use Array List. Non
synchronized data structure will give better performance than the synchronized one.

19. What is the List interface?

List interface is a child interface of Collection interface. This can be used to represent group of
individual objects in as a single entity where

Lakven Technologies
 Duplicates are allowed
 Insertion order is preserved

20. What is the Set interface?

Set is a child interface of Collection interface. it can be used to represent a group of individual
objects as a single entity where

 Duplicate objects are not allowed.


 Insertion order is not preserved

21. What is the Map interface?

Remember it is not a child Interface of Collection Interface and hence Map and Collection
Interfaces doesn’t have any relationship.

 It can be used for representing a group of Objects as key, value pairs.


 Both keys and values should be objects

 Keys can t be duplicated but values can be duplicated.

 it has  introduced in 1.2 version

22. What is the difference between Collections and Collection?

Collection is an interface which can be used for representing a group of individual objects as
single entity and it acts as root interface of collection frame  work.

A collection is utility class to define several utility methods for Collection implemented class
objects.

23. Why insertion and deletion in ArrayList is slow compared to LinkedList ?


 ArrayList internally uses and array to store the elements, when that array gets filled by
inserting elements a new array of roughly 1.5 times the size of the original array is created
and all the data of old array is copied to new array.
 During deletion, all elements present in the array after the deleted elements have to be
moved one step back to fill the space created by deletion. In linked list data is stored in
nodes that have reference to the previous node and the next node so adding element is
simple as creating the node an updating the next pointer on the last node and the previous
pointer on the new node. Deletion in linked list is fast because it involves only updating the
next pointer in the node before the deleted node and updating the previous pointer in the
node after the deleted node.

Lakven Technologies
24. Difference between HashMap and HashTable? Can we make hashmap synchronized?

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

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

25. What is the difference between ArrayList and LinkedList? (ArrayList vs LinkedList.)
1. ArrayList uses primitive object array for storing objects whereas LinkedList is made up of a
chain of nodes. Each node stores an element and the pointer to the next node. A singly
linked list only has pointers to next. A doubly linked list has a pointer to the next and the
previous element. This makes walking the list backward easier.
2. ArrayList implements the RandomAccess interface, and LinkedList does not. ArrayList is
much faster than a Linked List for random access, that is, when accessing arbitrary list
elements using the get method.
3. Adding and deleting at the start and middle of the ArrayList is slow, because all the later
elements have to be copied forward or backward. (Using System.arrayCopy()) Whereas
Linked lists are faster for inserts and deletes anywhere in the list, since all you do is update a
few next and previous pointers of a node.
4. Each element of a linked list (especially a doubly linked list) uses a bit more memory than its
equivalent in array list, due to the need for next and previous pointers.

26. If we are trying to insert duplicate values in Set what will happen?

If we are trying to insert duplicate objects to the HashSet  , we wont get any compile time or run
time errors just the add(Object o) returns false and it doesn’t add that object.

27. What is the difference between List and Set?

Set stores elements in an unordered way but does not contain duplicate elements, whereas List
stores elements in an ordered way but may contain duplicate elements.

When we required uniqueness then we can use set and setdoes not allow any duplications but
list may contain duplications set and list both extends collection interface.

Lakven Technologies
28. Why is it preferred to declare: List<String> list = new ArrayList<String>(), instead of
ArrayList<String> = new ArrayList<String>();

It is preferred because:

1. If later on code needs to be changed from Array List to Vector then only at the declaration
place we can do that.
2. The most important one – If a function is declared such that it takes list.
void show Details (List list);
When the parameter is declared as List to the function it can be called by passing any
subclass of List like ArrayList, Vector, LinkedList making the function more flexible

29. How do you sort an ArrayList (or any list) of user-defined objects ?

By default, the ArrayList’s elements are display according to the sequence it is put inside. Often
times, you may need to sort the ArrayList to make it alphabetically order. In this example, it
shows the use of Collections.sort(‘List’) to sort an ArrayList.

Incase of User defined objects like Employee, we have to create a new class which implements
the Comparator interface that knows how to order your objects and pass it to
java.util.Collections.sort(List, new EmployeeComparator).

30. What is the Comparable interface?

The Comparable interface is used to sort collections and arrays of objects using the
Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class
implementing the Comparable interface can be ordered.

The Comparable interface in the generic form is written as follows:

interface Comparable<T>

where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the compareTo() method
that has the return type as an integer. The signature of the compareTo() method is as follows:

int i = object1.compareTo(object2)
 If object1 < object2: The value of i returned will be negative.
 If object1 > object2: The value of i returned will be positive.

 If object1 = object2: The value of i returned will be zero.

Lakven Technologies
31. What are the differences between the Comparable and Comparator interfaces ?

Comparable Comparator

It uses the compareTo() method. t uses the compare() method.

int objectOne.compareTo(objectTwo). int compare(ObjOne, ObjTwo)

It is necessary to modify the class whose instance is A separate class can be created in order to sort the
going to be sorted. instances.

Only one sort sequence can be created. Many sort sequences can be created.

It is frequently used by the API classes. It used by third-party classes to sort instances.

32. What is the Contract between hashcode() and equals()?

The most significant contract between equals & hashcode is

 If two objects are equal then they must have the same hashcode, however the reverse is
not true.
 If two objects have the same hashcode does not mean that they are equal.

Note

 If you override equals method in the class, you must override the hashcode also.

 If a field is not used in equals(), then it must not be used inhashcode() method.

33. What is hashing algorithm in java?

This divides the elements in a Set into number of sub sets and the newly inserting element will
be compared to the elements within the one of the sub sets. So the number of comparisons
required to identify whether the newly inserting element is equivalent to any of existing element
will be very less.

Eg: If a set contains 1000 elements and hashing algorithm divides them into 10 number of subsets
( buckets) and each and every bucket will contains 100 elements. Now the newly inserting elements
will be compared elements in one of the buckets so the number of comparisons will be maximum
100.

Lakven Technologies
Where as in case List if we want to maintain the unique elements the newly inserting element
should be compared all existing 1000 elements.

Hashing algorithm uses hash code of the objects to create the number of buckets. All the elements
having same/equal hashcode will be stored in single bucket.

When we insert new element hashing algorithm will take the hashcode of the new element and try
to identify the bucket whose hashcode same as the new element.

a) If the bucket is identified with same hash code of new element then the new element will be
compared with all the elements in that bucket. New element will not be added to the Set if it is
equivalent any of the elements in that bucket otherwise it will added in that bucket.

b) If NO bucket is identified with the hashcode of new element then new bucket will be created for
this element and add this to that bucket.

Note: HashSet and LinkedHashSet uses hashing algorithm to maintain the unique elements.

34. Difference between HashMap and HashTable?

 The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and


permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t
allow). HashMap does not guarantee that the order of the map will remain constant over time. 

35. What is the Difference between Enumeration and Iterator interface?


Enumeration and Iterator are the interface available in java.util package. The functionality of
Enumeration interface is duplicated by the Iterator interface. New implementations should consider
using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:
 Enumeration contains 2 methods namely hasMoreElements() & nextElement() whereas
Iterator contains three methods namely hasNext(), next(),remove().
 Iterator adds an optional remove operation, and has shorter method names. Using
remove () we can delete the objects but Enumeration interface does not support this
feature.
 Enumeration interface is used by legacy classes. Vector.elements() &
Hashtable.elements () method returns Enumeration. Iterator is returned by all Java
Collections Framework classes. java.util.Collection.iterator() method returns an instance
of Iterator.

Lakven Technologies

You might also like