java interview questions part-1.docx

39
What are the principle concepts of OOPS? There are four principle concepts upon which object oriented design and programming rest. They are: a) Abstraction b) Encapsulation c) Inheritance d) Polymorphism What is Abstraction? Abstraction is the concept of exposing only the required essential characteristics and behavior with respect to a context. a) When we conceptualize a class b) When we write an ‘interface’ c) When we write an ‘abstract’ class, method d) When we write ‘extends’ e) When we apply modifiers like ‘private’, … 3.What is Encapsulation? Encapsulation is Binding the data with the code that manipulates it. It keeps the data and the code safe from external interference Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object. How to bring in Encapsulation 1) Make the instance variables protected.

Upload: rohit

Post on 29-Jan-2016

250 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Java Interview Questions Part-1.docx

What are the principle concepts of OOPS?

There are four principle concepts upon which object oriented design and programming rest. They are:

a) Abstractionb) Encapsulationc) Inheritanced) Polymorphism

What is Abstraction?

Abstraction is the concept of exposing only the required essential characteristics and behavior with respect to a context.

a) When we conceptualize a class

b) When we write an ‘interface’

c) When we write an ‘abstract’ class, method

d) When we write ‘extends’

e) When we apply modifiers like ‘private’, …

3.What is Encapsulation?

Encapsulation is Binding the data with the code that manipulates it.

It keeps the data and the code safe from external interference

Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.

How to bring in Encapsulation1) Make the instance variables protected.2) Create public accessor methods and use these methods from within the calling code.

3) Use the JavaBeans naming convention of getter and setter.

Advantages of encapsulation:

Page 2: Java Interview Questions Part-1.docx

It improves maintainability and flexibility and re-usability.

1. The fields can be made read-only (If we don’t define setter methods in

the class) or write-only (If we don’t define the getter methods in the

class). For e.g. If we have a field(or variable) which doesn’t need to

change at any cost then we simply define the variable as private and

instead of set and get both we just need to define the get method for that

variable. Since the set method is not present there is no way an outside

class can modify the value of that field.

2. User would not be knowing what is going on behind the scene. They

would only be knowing that to update a field call set method and to read a

field call get method but what these set and get methods are doing is

purely hidden from them.

Encapsulation is also known as “data Hiding”.

1. Objects encapsulate data and implementation details. To the outside

world, an object is a black box that exhibits a certain behavior.

2. The behavior of this object is what which is useful for the external world

or other objects.

3. An object exposes its behavior by means of public methods or functions.4. The set of functions an object exposes to other objects or external world acts as the interface of the object.

4. What is the difference between abstraction and encapsulation?

a) Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.

b) Abstraction solves the problem in the design side while Encapsulation is the Implementation.

c) Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.

What is Inheritance

Difination : Deriving new classes from existing classes such that the new classes acquire all the features of existing classes is called inheritance.

Page 3: Java Interview Questions Part-1.docx

Difination Inherit the feature of any class by making some relations between the class/interface is known as inheritance

Difination Inheritance is the process by which objects of one class acquire the properties of objects of another class.

a) A class that is inherited is called a super class.b) The class that does the inheriting is called a subclass.c) Inheritance is done by using the keyword extends.d) The two most common reasons to use inheritance are:

To promote code reuse

To use polymorphism

Inheritance with constructor and super()

Constructor cannot be inherited, Only the member of the class and methods can be inherited.

But, subclass constructor can access the super class constructor by using super() in its first line.

  Inheritance with static variables

There is no need for inheriting static variable, static variable are shared values they can be accessed in any class by specifying its class name. A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. In the below example

Private Members in a Super class

A subclass does not inherit the private members of its parent class.

private methods are not inherited (and therefore cannot be overriden) - non static class methods cannot be executed without instance of the class

  What is Polymorphism

Dfination: Polymorphism is briefly described as "one interface, many

implementations." Or one method with multiple implementation

There are two types of polymorphism one is Run time polymorphism. and the other is Compile time polymorphism 

Page 4: Java Interview Questions Part-1.docx

 Runtime time polymorphism is done using inheritance and interface.

Compile time polymorphism is method overloading.

a) Method overloadingb) Method overriding through inheritancec) Method overriding through the interface

11.What is method overloading?

Method Overloading means to have two or more methods with same name in the same class with different arguments.

The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.

a) Overloaded methods MUST change the argument listb) Overloaded methods CAN change the return typec) Overloaded methods CAN change the access modifierd) Overloaded methods CAN declare new or broader checked exceptionse) A method can be overloaded in the same class or in a subclass

Method overloading is also known as Static Polymorphism.

In Overloading having same method names and changing the arguments.

a) The Overloaded method must have different argument lists,

b) Can have different return types but in that case it is mandatory to have

different argument list.

c) Can have different access modifiers and

d) Can throw different exceptions

3) A Methods can be overloaded in the same as well as the sub classes.

1. Static Polymorphism is also known as compile time binding or early binding.

2. Static binding happens at compile time. Method overloading is an example of static

binding where binding of method call to its definition happens at Compile time.

Properties of method overloading

1) Overloaded methods are bonded by using static binding. Static binding happens at compile time.

Page 5: Java Interview Questions Part-1.docx

i.e. when you compile Java program. During compilation process, compiler bind method call to actual method.

2) Overloaded methods are fast because they are bonded during compile time and no check or binding is required during runtime.

3) Two overloaded method must have different signature.

1) Number of argument to a method is part of method signature.2) Type of argument to a method is also part of method signature3) Order of argument also forms part of method signature provided they are of different type.4) return type of method is not part of method signature in Java.

What is method overriding

Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass.

The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.

Binding of overridden methods happen at runtime which is known as dynamic binding

or late binding

a) The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).

b) You cannot override a method marked finalc) You cannot override a method marked static

9. What is runtime polymorphism or Dynamic method dispatch?

Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a super class. The determination of the method to be called is based on the object being referred to by the reference variable.

10.What is Dynamic Binding?

Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.

Page 6: Java Interview Questions Part-1.docx

Rules of Method Overriding

1. Method signature must be same including return type, number of method parameters, type of parameters and order of parameters.

The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.

2. Overriding method can not throw higher Exception than overridden method.

means if original method throws IOException than overriding method can not throw super class of IOException.

e.g. Exception but it can throw any sub class of IOException or simply does not throw any Exception. This rule only applies to checked Exception in Java, overridden method is free to throw any unchecked Exception.

overriding method can not throw checked Exception which is higher in hierarchy than overridden method. Which means if overridden method throws IOException than overriding method can not throw java.lang.Exception in its throws clause because java.lang.Exception comes higher than IOException in Exception hierarchy. This rule doesn't apply to RuntimeException in Java, which is not even need to be declared in throws clause in Java.

Overriding method (method of child class) can throw any unchecked exceptions, regardless of whether the overridden method(method of parent class) throws any exception or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. We will discuss this in detail with example in the upcoming tutorial.

a) An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.

4. Overriding method cannot reduce accessibility of overridden method.

For example if overridden method is declared public than overriding method cannot be declared protected, private or package-private, default;

But opposite is true overriding method can increase accessibility of overridden method

Page 7: Java Interview Questions Part-1.docx

i.e. if overridden method is declared protected than overriding method can be declared protected or public.

 For e.g. if the Access Modifier of base class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier as all of the three are more restrictive than public.For e.g. This is not allowed as child class disp method is more restrictive(protected) than base class(public)

b) Instance methods can be overridden only if they are inherited by the subclass.

c) private, static and final methods cannot be overridden as they are local to the class. private and static method are bonded during compile time using static binding

But static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.

d) overriding final method is compile time error. Though private and static method can be hidden if you declare another method with same and signature in sub class.

e) If a method cannot be inherited, then that method cannot be overridden.

f) A subclass within the same package as the instance's super class can override any super class method that is not declared private or final.

g) A subclass in a different package can only override the non-final methods declared public or protected.

h) Constructors cannot be overridden.

1) you can only override method in sub class. You can not override method in same class.

2) method name and method signaturs must be same in Super class and Sub class.

7) If you are extending abstract class or implementing interface than you need to override all abstract method unless your class is not abstract. abstract method can only be used by using method overriding.

1) Always use @Override annotation while overriding method. Though this is not rule but its one of the best Java coding practice to follow. From Java 6 you can use @Override annotation on method inherited from interface as well.

Page 8: Java Interview Questions Part-1.docx

Difference between Overloading and Overriding

1) The method overloading Argument list should be different. But The method Overriding Argument list should be same.

2) The Method overloading return type should be different. But The method Overriding return type should be same.

3) The Method overloading is done in the same class.But method Overring is done in super class and sup class.

4) private and final methods can be overloaded but they cannot be overridden. It means a class can have more than one private/final methods of same name but a child class cannot override the private/final methods of their base class.

5) Static methods can be overloaded which means a class can have more than one static method of same name. Static methods cannot be overridden, even if you declare a same static method in child class it has nothing to do with the same method of parent class.

6) Overloading happens at compile-time But Overriding happens at runtime: The binding of overloaded method call to its definition has happens at compile-time. But binding of overridden method call to its definition happens at runtime.

7) Binding of overridden methods happen at runtime which is known as dynamic binding

8) Static binding is being used for overloaded methods and dynamic binding is being used for overridden/overriding methods.

9) Overloading gives better performance compared to overriding. The reason is that the binding of overridden methods is being done at runtime

13.What are the differences between method overloading and method overriding?

  Overloaded Method Overridden Method

Arguments Must change Must not change

Return type Can change Can’t change except for covariant

Page 9: Java Interview Questions Part-1.docx

Returns

Exceptions Can change Can reduce or eliminate. Must not throw

new or broader checked exceptions

Access Can change Must not make more restrictive (can be

less restrictive)

Invocation Reference type determines which overloaded version is selected. Happens at compile time.

Object type determines which method is

selected. Happens at runtime.

14.Can overloaded methods be override too?

Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future.

15.Is it possible to override the main method?

NO, because main is a static method. A static method can't be overridden in Java.

16.How to invoke a super class version of an Overridden method?

To invoke a super class method that has been overridden in a subclass, you must either call the method directly through a super class instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the super class' implementation of the method.

// From subclassSuper .overridden Method();

17.What is super?

super is a keyword which is used to access the method or member variables from the super class. If a method hides one of the member variables in its super class, 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 super class, the method can invoke the overridden method through the use of the super keyword. 

Page 10: Java Interview Questions Part-1.docx

a) You can only go back one level.b) 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.c) a abstract class.

Usage of java super Keyword

1. super is used to refer immediate parent class instance variable.2. super() is used to invoke immediate parent class constructor.3. super is used to invoke immediate parent class method.

Super keyword in Overriding

super keyword is used for calling the parent class method/constructor. super.methodname() calling the specified method of base class while super() calls the constructor of base class. Let’s see the use of super in Overriding.

18.How do you prevent a method from being overridden?

To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.

                       public final void exampleMethod() {                         // Method statements                         }

19.What is an Interface?

An interface is a description of a set of methods that conforming implementing classes must have.

Important Points about Interface

a) An Interface can contain one or more abstract methods

b) An interface can contain members variables which are

public ,static and final by default.

c) All the methods of an Interface modifiers are public and abstract

by default.

Page 11: Java Interview Questions Part-1.docx

d) An interface cannot contain private or protected methods.

e) We cannot create an object to an interface.

f) We can create a reference of interface.

g) All the methods of an Interface are implemented in

implementation classes.

h) An interface can not implement another Interface.

i) An Interface can extend another Interface.

j) A class can implement multiple Interface

k) It is possible to write a class with in an interface.

What is the Driver

A driver is a software that contains one or more implementation classes.

20.Can we instantiate an Interface?

You can’t instantiate an interface directly, but you can instantiate a class that implements an interface.

21.Can we create an object for an interface?

Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.

22.Do interfaces have member variables?

Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example.

23.What modifiers are allowed for methods in an Interface?

Only public and abstract modifiers are allowed for methods in interfaces.

24.What is a marker interface?

An Interface with out any methods and members is called tagging interface or marking interface.

A tagging interface specifies special purpose for the class objects.

Page 12: Java Interview Questions Part-1.docx

Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializableinterface 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.

What is an abstract class?

Abstract classes are classes that contain one or more abstract methods.

An abstract method is a method that is not contain method body and it is not contains no implementation. 

Important Points about Abstract class

a) An abstract class is class that contain one or more abstract methods.

b) An abstract class can contain instance variables and concrete methods.

c) An abstract keyword is used to create an abstract class and abstract methods.

An abstract methods cannot have implementations abstract methods

implemented in sub classes.

d) If any abstract method is not implemented then that sub class should be declared

as abstract. In this case we cannot create an object to the sub class. We should

create anther sub class to this sub class and implement the remaining abstract

method.

e) We cannot create an object to abstract class.

f) We can create a reference of abstract class.

g) The reference of abstract class can be used to refer to object of its sub classes.

h) The reference of abstract class cannot refer to individual methods of its sub

classes.

i) An abstract classes not necessary to have abstract method.

j) If abstract class doesn’t have any method implementation, its better to use interface

because java doesn’t support multiple class inheritance.

k) Abstract classes can implement interfaces.

l) Abstract classes are used to provide common method implementation to all the

subclasses or to provide default implementation.

m) We can run abstract class. if it has main() method.

Page 13: Java Interview Questions Part-1.docx

Difference between Abstract Class and Interface

1. abstract keyword is used to create an abstract class and abstract methods. An

interface keyword is used to create an interface and it can’t be used with

methods.

2. Subclasses use extends keyword to extend an abstract class and they need to

provide implementation of all the declared methods in the abstract class unless the

subclass is also an abstract class.

But subclasses use implements keyword to implement interfaces and should

provide implementation for all the methods declared in the interface.

3. A subclass can extend only one abstract class but it can implement multiple

interfaces.

4. Abstract classes can have methods with implementation. But an interface provides

only abstract methods and can’t have any method implementations.

5. Abstract classes can have constructors. But interfaces can’t have constructors.

6. Abstract classes and methods can have access modifiers as public, private,

protected, static. But interface methods are implicitly public and abstract, we can’t

use any other access modifiers with interface methods. An interface can not

contain private or protected methods An interface can contain members

variables which are public ,static and final by default.

7. Abstract classes can extend other class and implement interfaces. But interface can

extend other interfaces only.

8. We can run an abstract class if it has main() method but we can’t run an interface

because they can’t have main method implementation.

Which should you use, abstract classes or interfaces?

Consider using abstract classes if any of these statements apply to your situation:

o You want to share code among several closely related classes.o You expect that classes that extend your abstract class have many

common methods or fields, or require access modifiers other than public (such as protected and private).

Page 14: Java Interview Questions Part-1.docx

o You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

Consider using interfaces if any of these statements apply to your situation:o You expect that unrelated classes would implement your interface. For

example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.

o You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.

o You want to take advantage of multiple inheritance of type.

26.Can we instantiate an abstract class?

An abstract class can never be instantiated. Its sole purpose is to be extended (sub classed).

27.What are the differences between Interface and Abstract class?

Abstract Class Interfaces

An abstract class can provide complete, default code and/or just the details that have to be overridden.

An interface cannot provide any code at all,just the signature.

In case of abstract class, a class may extend only one abstract class.

A Class may implement several

interfaces.

An abstract class can have non-abstract methods.

All methods of an Interface are

abstract.

An abstract class can have instance variables.

An Interface cannot have

instance variables.

An abstract class can have any

visibility: public, private, protected.

An Interface visibility must be

public (or) none.

Page 15: Java Interview Questions Part-1.docx

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

If we add a new method to an Interface then we have to track down

all the implementations of the

interface and define implementation for the new method.

An abstract class can contain constructors .

An Interface cannot contain

constructors .

Abstract classes are fast.

Interfaces are slow as it

requires extra indirection

to find corresponding method in

the actual class.

28.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. 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 non leaf classes in class hierarchies.

29.When you declare a method as abstract, can other non abstract methods access it?

Page 16: Java Interview Questions Part-1.docx

Yes, other non abstract methods can access a method that you declare as abstract.

30.Can there be an abstract class with no abstract methods in it?

Yes, there can be an abstract class without abstract methods.

What is constructor?

a) Constructor is block of code which is executed at the time of Object creation.b) Constructors are used to initialize the instance variables of an object.c) Constructors are required to create objects for a class. d) Constructor declaration looks like method declaration.e) constructor name and class name both are same.f) Constructor do not have return types, not even void also.g) Constructor can not be inherited and Overridden. h) Constructors can be classified into two types, default constructors and

parametarized constructors.i) If you don't define a constructor in a class, then the compiler creates a default

constructor. Default constructors do not contain any parameters. j) parametarized constructors are required to pass parameters on creation of

objects. We can overload constructors with different data types as its parameters.k) You can use any access modifier constructor. they can be public, protected or

private. Default or no argument. Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructor.

l) Use 'this()' to communicate from one constructor to another constructor in the same class.

m) Use 'super()' to communicate with super class constructor.

What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on the type.

Rules for creating constructor

There are basically two rules defined for the constructor.

1. Constructor name and its class name must be same.2. Constructor must have no explicit return type

32.How does the Java default constructor be provided?

If a class defined by the code does not have any constructor, compiler will automatically

Page 17: Java Interview Questions Part-1.docx

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.

33.Can constructor be inherited?

No, constructor cannot be inherited, though a derived class can call the base class constructor.

Difference between Default constructor and parameterized constructor.

a) Default constructor does not have any parameters. But parameterized constructor will have one or more parameters.

b) Default constructor is useful to initialize all object with same data. But parameterized constructor is useful to initialize each object with different data.

c) Data is not passed at the time of creating an object, default constructor is called. But Data is passed at the time of creating an object, parameterized constructor is called.

What is Constructor overloading

Writing two or more constructors with the same name but different parameters in same class is called constructor overloading.

Constructor in Java – things to remember

1) First and most important rule of declaring constructor is that name of constructor in Java must be exactly same with the class on which you declare constructor, if it doesn't then compiler will flag as error. A class in Java can have as many constructor as it and that is called constructor overloading in Java but signature of two constructor must not be same. here is an example of having multiple constructors in Java and how they are called using new() operator:

public class ConstructorDemo{

   public ConstructorDemo(){

      System.out.println("Inside no argument constructor");   }

Page 18: Java Interview Questions Part-1.docx

         public ConstructorDemo(String name){

      System.out.println("Inside one argument constructor in Java with name: " + name);   }

   public static void main(String args[]) throws IOException {           ConstructorDemo d = new ConstructorDemo(); //calling no argument constructor in java

     ConstructorDemo e = new ConstructorDemo("Testing"); //calling one argument constructor in java     }}

Output:Inside no argument constructorInside one argument constructor in Java with name: Testing

In above example we have create two separate object by calling two different constructors of class ConstructorDemo. If you notice carefully name of constructor is same as name of class. Also signature of two constructor is different to each other.

2) Another important rule of declaring constructor is that constructor in Java doesn't have return type. As I said constructor is different than methods in Java and doesn't return anything, Java Constructor are by default of type void. Though you can have return statement inside constructor without returning any value but can return control back to caller. See difference between method and constructor in Java for more differences.

Page 19: Java Interview Questions Part-1.docx

3) Here comes another interesting property of constructor which is tested in SCJP and various other Java Exams and Java Interviews. Every Class in Java has constructor, if no explicit constructor is specified by Programmer, Java Compiler inserts a no argument constructor inside class. This is also called default Constructor in Java. if you provide any constructor in Java e.g. with one argument or two argument than compiler will not add default constructor or no arguments constructor, which makes your class unusable with framework or library which uses reflection and follow Java Bean naming convention. So always provide no argument constructor in Java. Another drawback of not providing no argument constructor is chances of having restricted hierarchy. Suppose another sub class is created and you don't add constructor over there than compiler tries to create a default constructor which calls super() at first line. super() means call to no argument constructor of super class and since there is no such constructor in your class it will fail with compilation error. This is like making your class final in Java.

4) One more important property of constructor in Java is constructor chaining. Calling one constructor from another constructor in Java is called Constructor chaining. you can use keyword this for calling constructor of same class and keyword super for calling constructor of super class. Anyway call to constructor must be on the first line of any constructor or else you will get compilation error. Read more about constructor chaining and constructor overloading here.

5) You can use any access modifier with Java constructor. they can be public, protected or private. Default or no argument

constructor has same access modifier as class. You can also prevent a class from extension by making there constructor private. With private constructor instance of that class can only be created inside declaring class. Singleton pattern in Java is popular example of Class with private constructor.

6) Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructor.

7) Since parent class is initialized before child class in Java, Constructor of parent class is executed before constructor of child class, that explains why super() is

Page 20: Java Interview Questions Part-1.docx

first statement in default no argument constructor. To understand more about how class is loaded into memory read How ClassLoader works in Java and When class is loaded and initialized in JVM.

8) Constructor can throw Exception in Java in fact constructor can declare Exception in there throws clause but that makes caller to handle or re throw Exception while creating any instance of Class.

9) Creating object using new() keyword and constructor has there pros and cons. Its not good in terms of Encapsulation because if you directly create any instance of class you code is tied up with structure of Constructor and any change in constructor will require changes in all places where its object gets created. Standard way is to use factory design pattern in Java which encapsulate object creation logic and provides better maintenance over time.

10) Unlike C++ there is no destructor in Java. Though objects has finalize method which suppose to run before objects gets garbage collected but that is not guaranteed by Java language specification and it may run or may not.

That’s all on What is constructor in Java and important points about constructor in Java. As you see there is lot of rules and specific information around constructor but its an important aspect of Java programming language and you must have good grasp of all constructor specifics in Java. We have also touched concepts like constructor chaining and constructor overloading which is quite popular on various Java exams.

Difference between method and constructor

1) Constructor name and it’s class name both are same .But method name and it’s class name can be same or different.

2) constructor doesn't have any return type but method has return type and return something unless its void.

3) Constructors are used to initialize the instance variables of a class. But methods

Page 21: Java Interview Questions Part-1.docx

are used for any general purpose processing or calculations.

4) Constructor is called at the time of creating the object. But method can be called after creating the object.

5) Constructor is called only once per object. But method can be called several times on the object.

6) Constructor is called and executed automatically. But method is executed only when we call it.

7) Constructors are chained and they are called in a particular order, there is no such facility for methods.

8) this and super Keyword is used to call constructor explicitly. no such thing for method, they have there own name which can be used to call them.

9) Constructors are not inherited by child classes but methods are inherited by child classes

10) You can use any access modifier with Java constructor. they can be public, protected or private. Default or no argument. Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructor.

The Keyword this

The keyword this is useful when you need to refer to an instance of the class from its method. Let's consider an example:

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this keyword can be used to refer current class instance variable.2. this() can be used to invoke current class constructor.3. this keyword can be used to invoke current class method (implicitly)4. this can be passed as an argument in the method call.5. this can be passed as argument in the constructor call.6. this keyword can also be used to return the current class instance.

class Tax { double grossIncome;

Page 22: Java Interview Questions Part-1.docx

Tax(double grossIncome){ this.grossIncome = grossIncome; }}

The keyword this helps avoid name conflicts, for example this.grossIncome refers to a member variable grossIncome, while the grossIncome on the right refers to the argument's value.

34.What are the differences between Contructors and Methods?

  Constructors Methods

Purpose Create an instance of a class Group Java statements

Modifiers Cannot be abstract, final, native, static, or synchronized

Can be abstract, final, native,

static, or synchronized

Return Type No return type, not even void void or a valid return type

Name Same name as the class (first letter is capitalized by convention) -- usually a noun

Any name except the class.

Method names begin with

a lowercase letter by

convention -- usually the name

of an action

This Refers to another constructor in the same class. If used, it must be the first line of the constructor

Refers to an instance of the

owning class. Cannot be used

by static methods.

Super Calls the constructor of the parent class. If used, must be the first line of the constructor

Calls an overridden method

in the parent class

Inheritance Constructors are not inherited

Methods are inherited

Page 23: Java Interview Questions Part-1.docx

35.How are this() and super() used with constructors?

a) Constructors use this to refer to another constructor in the same class with a different parameter list.

b) Constructors use super to invoke the super class's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.

36.What are the differences between Class Methods and Instance Methods?

Class Methods Instance Methods

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

Instance methods on the other hand

require an instance of the class to exist

before they can be called, so an

instance of a class needs to be

created by using the new keyword.Instance methods operate on

specific instances of classes.

Class methods can only operate on class members and not on instance members as class methods are unaware of instance members.

Instance methods of the class can also

not be called from within a class

method unless they are being 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 of the class.

Instance methods are not declared as

static.

what are local, member, and class

Page 24: Java Interview Questions Part-1.docx

variables?

local variables - inside methods only. Cannot use any keyword other than 'final'. 

instance varibles - Non-static variables declared inside a class, but outside a method. 

class variables - Static variables declared inside a class, but outside a method. 

member variable - Both instance variables and class variables are generally called as

member variables.

Difference between class and instance variables

a) If you declare any variable as static, it is known static variable.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Class variables (Static variable) can have only one copy that is shared by

all the different objects of a class, class variables across different object

can have only one value

an instance variable (non static variable) can have every object has it’s

own personal copy. So, instance variables across different objects can have different

values.

b) Static variables are stored on method area. But Instance variables are

created in the object on heap memory.

c) The static variables are modified it will Effect all the object. But The

instance variables are modified it will not Effect other objects.

1.staticclass

2.staticblock

3.staticmethods

Page 25: Java Interview Questions Part-1.docx

4. static variables

Java static keyword

The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

The static can be:

1. variable (also known as class variable)2. method (also known as class method)3. block4. nested class

Static Class

A Class can be made static only if it is a nested Class. The nested static class can be

accessed without having an object of outer class.

Static inner class cannot access instance data of outer class.

Static Block

Static block is mostly used for changing the default values of static variables.Static block

gets executed when the class is loaded in the memory.

A class can have multiple Static blocks, which will execute in the same sequence in

which they have been written into the program. Before going to the main method the

static block will execute.

Java static block

Is used to initialize the static data member. It is executed before main method at the time of classloading.

Page 26: Java Interview Questions Part-1.docx

Static block which exactly executed once when the class is first loaded into JVM. Before going to the main method the static block will execute.

45.What are static methods?

Static keyword is used to create static Methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.

a) A static method can only call other static methods.b) A static method must access only static data.c) A static method cannot reference to the current object using

keywords super or this.

d) Static Methods can access class variables without using object of the class.

e) Static Methods can access non-static methods and non-static variables by using

objects.

f) Static methods can be accessed directly in static and non-static methods.

Restrictions for static methodThere are two main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static method directly.2. this and super cannot be used in static context.

43.What are static variables?

Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as

a whole. They are declared by using the static keyword as a modifier.

static type varIdentifier;

where, the name of the variable is varIdentifier and its data type is specified by type.

Page 27: Java Interview Questions Part-1.docx

Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.

a) Static variables are also known as Class Variables.b) Static variables get default values based on the data type.c) Data stored in static variables is common for all the objects( or instances ) of that

Class.d) Memory allocation for such variables only happens once when the class is

loaded in the memory.e) These variables can be accessed in any other class using class name.f) Unlike non-static variables, such variables can be accessed directly in static

and non-static methods.

What is the different between instance methods and static methods.

Instance methods are methods which act on the instance variables of a class. To call instance methods: Objetname.methodname().

Static methods are methods which do not act upon the instance variables of a class. Static methods are declared by using keywoard Static. To call static methods: Classname.methodname().

39.What are Access Specifiers available in Java?

a) Public- public classes, methods, and fields can be accessed from everywhere.b) 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.

c) Default(no specifier)- When no specifier is used java compiler internally uses default specifier. Default methods and fields of a class are available out side the class. But with in the same package.

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.

d) 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 

 Accessible to class  Yes Yes

Page 28: Java Interview Questions Part-1.docx

 from same package? 

 Accessible to class  from different package? 

Yes  no, unless it is a subclass 

40.What is final modifier?

The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:

1. variable2. method3. class

a) final Classes- A final class cannot have subclasses.b) final Variables- A final variable cannot be changed once it is initialized.c) final Methods- A final method cannot be overridden by subclasses.

41.What are the uses of final method?

There are two reasons for marking a method as final:

a) Disallowing subclasses to change the meaning of the method.b) Increasing efficiency by allowing the compiler to turn calls to the method into

inline Java code.

What is the default value of Boolean data type

False

What is the default value of String data type

Null.

Page 29: Java Interview Questions Part-1.docx

What is the different between a class and an object

A class is a model for creating an objects and does not exists physically. An object is any thing that exists physically. Both the class and objects contain variables and methods.

What is Inner class

a) A class written inside another class is called inner class.b) Inner class is a safety mechanism.c) Only inner class can be declared as private.d) An object to inner class can not be created in any other classes.e) An object to inner class can be created only in this outer class.f) Accessing inner class should be done through outer class only.g) Inner class object and outer class objects in separate memory blocks.h) Outer class members are directly available to inner class.