0% found this document useful (0 votes)
6 views

Java Interview

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Interview

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 146

http://www.instanceofjava.com/p/interview-questions.

html

Java programs : http://www.instanceofjava.com/2017/05/java-practice-programs-with-solutions.html

Static Keyword :

1.what is static in java?


 Static is a keyword in java.
 One of the Important keyword in java.
 Clear understanding of static keyword is required to build projects.
 We have static variables, static methods , static blocks.
 Static means class level.

2.Why we use static keyword in java?


 Static keyword is mainly used for memory management.
 Static variables get memory when class loading itself.
 Static variables can be used to point common property all objects.

3.What is static variable in java?


 Variables declared with static keyword is known as static variables.
 Static variables gets memory on class loading.
 Static variables are class level.
 If we change any static variable value using a particular object then its value
changed for all objects means it is common to every object of that class.
 static int a,b;

1. package com.instanceofjavastatic;

2. class StaticDemo{

3.

4. static int a=40;


5. static int b=60;

6.

7. }

 We can not declare local variables as static it leads to compile time error "illegal
start of expression".
 Because being static variable it must get memory at the time of class loading,
which is not possible to provide memory to local variable at the time of class
loading.

1. package com.instanceofjava;

2. class StaticDemo{

3.

4. static int a=10;

5. static int b=20;

6. public static void main(String [] args){

7.

8. //local variables should not be static

9. static int a=10;// compile time error: illegal start of expression

10. }

11. }

Read more : Explain about static variables in java?

4. what is static method in java with example


 Method which is having static in its method definition is known as static method.

1. static void show(){

2.

3. }

 JVM will not call these static methods automatically. Developer needs to call
these static methods from main method or static block or variable initialization.
 Only Main method will be called by JVM automatically.
 We can call these static methods by using class name itself no need to create
object.
Read more @ what is static method in java

5.what is static block in java?


 Static blocks are the blocks which will have braces and with static keyword.
 These static blocks will be called when JVM loads the class.
 Static blocks are the blocks with static keyword.
 Static blocks wont have any name in its prototype.
 Static blocks are class level.
 Static block will be executed only once.
 No return statements.
 No arguments.
 No this or super keywords supported.

1. static{
2.
3. }

Read more @ Static blocks in java with example programs

6.What is the need of static block?


 Static blocks will be executed at the time of class loading.
 So if you want any logic that needs to be executed at the time of class loading
that logic need to place inside the static block so that it will be executed at the
time of class loading.
7.Why main method is static in java?
 To execute main method without creating object then the main method should
be static so that JVM will call main method by using class name itself.

8.Can we overload static methods in java?


 Yes we can overload static methods in java.
Read more @ Can we overload static methods in java

9.Can we override static methods in java?


 NO we can not override static methods in java.
Read more @ Can we override static methods in java

10.Can we write static public void main(String [] args)?

 Yes we can define main method like static public void main(String[] args){}
 Order of modifiers we can change.

1. package instanceofjava;

2. public MainDemo{

3. static public void main(String [] args){

4.

5. }

6. }

11.Can we call super class static methods from sub class?

 Yes we can call super class static methods from sub class.

Calling static method from non static method in


java
Posted by: InstanceOfJava Posted date: Sep 24, 2016 / comment : 0
 Static means class level and non static means object level.
 Non static variable gets memory in each in every object dynamically.
 Static variables are not part of object and while class loading itself all static
variables gets memory.
 Like static variables we have static methods. Without creating object we can
access static methods.
 Static methods are class level. and We can still access static methods in side non
static methods.
 We can call static methods without using object also by using class name.
 And the answer to the question of "is it possible to call static methods from non
static methods in java" is yes.
 If we are calling a static method from non static methods means calling a single
common method using unique object of class which is possible.

Non static methods will be executed or called by using object so whenever we want to
call a non static method from static method we need to create an instance and call that
method.

Abstract Class :

Top 15 Java abstract class and abstract


method interview questions and programs
Posted by: InstanceOfJava Posted date: Feb 16, 2016 / comment : 2
1.What is abstract class in java?

 Hiding the implementation and showing the function definition to the user.
 Abstract class contains abstract methods and concrete methods(normal
methods)
2.How can we define an abstract class?
 Using abstract keyword we can define abstract class.
 Check below code for abstract class example program.

1. package Abstraction;

2. public abstract class AbstractDemo {

3. //

4. //

5. }
3. How to declare an abstract method?
 By Using abstract keyword in the method signature we can declare abstract
method.

1. package Abstraction;

2. public abstract class AbstractDemo {

3. //

4. abstract void show();


5.

6. }

4. Can we define abstract class without abstract method?


 Yes we can define abstract class without abstract methods.
 It is not mandatory to create at-least one abstract method in abstract class.

1. package Abstraction;

2. public abstract class AbstractDemo {

3. //

4.

5.

6. }

Read more at Can you define an abstract class without any abstract methods? if yes
what is the use of it?
5.Can we create object object for abstract class?

 Abstract class can not be instantiated directly.


 Means we can not create object for abstract class directly.
 Through sub class abstract class members will get memory. Whenever we create
sub class object of abstract class abstract class object will be created. i.e
abstract class members will get memory at that time.

1. package Abstraction;

2. public abstract class AbstractClass {

3.

4. abstract void add(); // abstract method

5.

6. void show(){ // normal method

7. System.out.println("this is concrete method present in abstract class");

8. }

9.

10. public static void main(String[] args){

11.

12. AbstractClass obj= new AbstractClass ();

13. // ERROR: Cannot instantiate the type AbstractClass

14.

15. }

16. }

6. Is is possible to declare abstract method as static?

 No. its not possible to declare abstract method with static keyword.
 If we declare abstract method with static compiler will throw an error.

1. package Abstraction;

2. public abstract class AbstractClass {

3.

4. static abstract void add(); // ERROR: illegal combination of modifiers

5.

6. void show(){ // normal method

7. System.out.println("this is concrete method present in abstract class");

8. }

9. }

7.Can we declare abstract method as final?

 No. its not possible to declare abstract method with final keyword.
 If we declare abstract method with final compiler will throw an error.
 Because abstract methods should be override by its sub classes.

1. package Abstraction;

2. public abstract class AbstractClassExample {

3.
4. final abstract void add(); // ERROR: illegal combination of modifiers

5.

6. void show(){ // normal method

7. System.out.println("this is concrete method present in abstract class");

8. }

9. }

8. Is it possible to declare abstract method as private?

 No. its not possible to declare abstract method with private .


 If we declare abstract method with private compiler will throw an error.
 Because abstract methods should be override by its sub classes.

1. package Abstraction;

2. public abstract class AbstractClassExample {

3.

4. private abstract void add(); // ERROR: illegal combination of modifiers

5.

6. void show(){ // normal method

7. System.out.println("this is concrete method present in abstract class");

8. }
9. }

9. Is it possible to declare abstract method as public ?

 Yes we can declare abstract methods as public.

1. package Abstraction;

2. public abstract class AbstractClassExample {

3.

4. public abstract void add();

5.

6. void show(){ // normal method

7. System.out.println("this is concrete method present in abstract class");

8. }

9. }

10. Is it possible to declare abstract method with default?

 Yes we can declare abstract methods with default.

1. package Abstraction;

2. public abstract class AbstractClassExample {

3.

4. abstract void add();

5.

6. void show(){ // normal method

7. System.out.println("this is concrete method present in abstract class");

8. }

9. }

11. Is it possible to declare abstract method with protected modifier?


 Yes we can declare abstract methods as protected.

1. package Abstraction;

2. public abstract class AbstractClassExample {

3.

4. protected abstract void add();

5.

6. void show(){ // normal method

7. System.out.println("this is concrete method present in abstract class");

8. }

9. }

12.What are the valid and invalid keywords or modifier with abstract class?

 public, protected and default are valid.


 static, final and private are invalid.
13.Can abstract method declaration include throws clause?

 Yes. We can define an abstract class with throws clause.

1. package Abstraction;

2. public abstract class AbstractClassExample {

3.

4. abstract void add() throws Exception;

5.

6. void show(){ // normal method

7. System.out.println("this is concrete method present in abstract class");

8. }

9. }
14.What happens if sub class not overriding abstract methods?

 If sub class which is extending abstract class not overriding abstract method
compiler will throw an error.

1. package Abstraction;

2. public abstract class AbstractClass {

3.

4. abstract void add() throws Exception;

5.

6.

7. }

1. package Abstraction;

2. public class Sample extends AbstractClass {

3.

4. //Compiler Error: The type Sub must implement the inherited abstract method
Super.add()

5. }

15. Can we escape of overriding abstract class in sub class which is extending
abstract class?

 Yes we can escape from overriding abstract method from super abstract class by
making our class again as abstract.
 The class which is extending our class will get responsibility of overriding all
abstract methods in our class and in super class.

1. package Abstraction;

2. public abstract class AbstractClass {

3.

4. abstract void add() throws Exception;


5.

6.

7. }

1. package Abstraction;

2. public abstract class Sample extends AbstractClass {

3.

4.

5. }

1. package Abstraction;

2. public class Example extends Sample{

3.

4. //Compiler Error: The type Sub must implement the inherited abstract method
Super.add()

5. }

This Keyword:

Home › Top 10 Java interview questions and programs on this keyword

Top 10 Java interview questions and programs


on this keyword
Posted by: InstanceOfJava Posted date: Mar 9, 2016 / comment : 14
1.What is this key word in java?

 "this"is a predefined instance variable to hold current object reference


2.What are the uses of this keyword in constructor?

1.this must be used to access instance variable if both instance and local variable
names are same.

1. package com.instanceofjava;

2.

3. public class ThisDemo {

4. int a, b;

5.

6. ThisDemo(int a, int b){

7.

8. a=a;

9. b=b;

10. }

11.

12. public static void main(String[] args){

13.

14. ThisDemo obj= new ThisDemo(1,2);

15.

16. System.out.println(obj.a);

17. System.out.println(obj.b);

18. }

19. }
Output:
1. 0

2. 0

using this keyword:

1. package com.instanceofjava;

2.

3. public class ThisDemo {

4. int a, b;

5.

6. ThisDemo(int a, int b){

7.

8. this.a=a;

9. this.b=b;

10. }

11.

12. public static void main(String[] args){

13.

14. ThisDemo obj= new ThisDemo(1,2);

15.

16. System.out.println(obj.a);

17. System.out.println(obj.b);
18. }

19. }

Output:
1. 1

2. 2

 We can use this keyword in constructor overloading.


 To call one constructor from another we need this(); and this(); call should be
first statement of the constructor.

2.Used to invoke current class constructor:

1. package com.instanceofjava;

2.

3. public class ThisDemo {

4. int a, b;

5.

6. ThisDemo(){

7. System.out.println("Default constructor called");

8. }

9.

10. ThisDemo(int a, int b){

11. this();
12. this.a=a;

13. this.b=b;

14. }

15.

16. public static void main(String[] args){

17.

18. ThisDemo obj= new ThisDemo(1,2);

19.

20. System.out.println(obj.a);

21. System.out.println(obj.b);

22. }

23. }

Output:

1. Default constructor called

2. 1

3. 2

3. Can we call methods using this keyword?

 Yes we can use this keyword to call current class non static methods .

1. package com.instanceofjava;
2.

3. public class Test{

4. int a, b;

5.

6.

7. Test(int a, int b){

8.

9. this.a=a;

10. this.b=b;

11. }

12.

13. void show(){

14.

15. System.out.println("Show() method called");

16.

17. }

18.

19. void print(){

20.

21. this.show();

22. System.out.println(a);

23. System.out.println(b);

24.

25. }

26. public static void main(String[] args){


27.

28. Test obj= new Test(1,2);

29.

30.

31. obj.print()

32. }

33. }

Output:

1. Show() method called

2. 1

3. 2

3. Can we call method on this keyword from constructor?

 Yes we can call non static methods from constructor using this keyword.
4.Is it possible to assign reference to this ?

 No we can not assign any value to "this" because its always points to current
object and it is a final reference in java.
 If we try to change or assign value to this compile time error will come.
 The left-hand side of an assignment must be a variable
5.Can we return this from a method?

 Yes We can return this as current class object.

1. public class B{

2.

3. int a;

4.

5. public int getA() {

6. return a;

7. }

8.

9. public void setA(int a) {

10. this.a = a;

11. }

12.
13. B show(){

14. return this;

15. }

16.

17. public static void main(String[] args) {

18.

19. B obj = new B();

20.

21. obj.setA(10);

22.

23. System.out.println(obj.getA());

24. B obj2= obj.show();

25. System.out.println(obj2.getA());

26.

27. }

28.

29. }

Output:
1. 10

2. 10

6.Can we pass this as parameter of method?


 Yes we can pass this as parameter in a method

7. Can we use this to refer static members?

 Yes its possible to access static variable of a class using this but its discouraged
and as per best practices this should be used on non static reference.

8.Is it possible to use this in static blocks?

 No its not possible to use this keyword in static block.

9.Can we use this in static methods?

 No we can not use this in static methods. if we try to use compile time error will
come:Cannot use this in a static context

10.What are all the differences between this and super keyword?
 This refers to current class object where as super refers to super class object
 Using this we can access all non static methods and variables. Using super we
can access super class variable and methods from sub class.
 Using this(); call we can call other constructor in same class. Using super we can
call super class constructor from sub class constructor.
11. write a java program on constructor overloading or constructor chaining
using this and super keywords

 Constructor chaining in java with example program

Constructor chaining example program in same class using this keyword.

Constructor chaining example program in same class using this keyword.

1. package instanceofjava;
2. class ConstructorChaining{
3. int a,b
4. ConstructorChaining(){
5. this(1,2);
6. System.out.println("Default constructor");
7.
8. }
9.
10. ConstructorChaining(int x , int y){
11.
12. this(1,2,3);
13. a=x;
14. b=y;
15. System.out.println("Two argument constructor");
16.
17. }
18.
19. ConstructorChaining(int a , int b,int c){
20. System.out.println("Three argument constructor")
21. }
22.
23. public static void main(String[] args){
24.
25. ConstructorChaining obj=new ConstructorChaining();
26. System.out.println(obj.a);
27. System.out.println(obj.b);
28.
29. }
30. }
Output:
1. Three argument constructor
2. Two argument constructor
3. Default argument constructor
4. 1
5. 2

Constructor chaining example program in same class using this and super
keywords.

1. package instanceofjava;
2. class SuperClass{
3.
4. SuperClass(){
5. this(1);
6. System.out.println("Super Class no-argument constructor");
7.
8. }
9.
10. SuperClass(int x ){
11.
12. this(1,"constructor chaining");
13. System.out.println("Super class one -argument constructor(int)");
14.
15. }
16.
17. SuperClass(int x , String str){
18. System.out.println("Super class two-argument constructor(int, String)");
19. }
20.
21. }

1. package instanceofjava;
2. class SubClass extends SuperClass{
3.
4. SubClass(){
5. this(1);
6. System.out.println("Sub Class no-argument constructor");
7.
8. }
9.
10. SubClass(int x ){
11.
12. this("Constructor chaining");
13. System.out.println("Sub class integer argument constructor");
14.
15. }
16.
17. ConstructorChaining(String str){
18. //here by default super() call will be there so it will call super class constructor
19. System.out.println("Sub class String argument constructor");
20. }
21.
22. public static void main(String[] args){
23.
24. SubClass obj=new SubClass();
25.
26.
27. }
28. }

Output:
1. Super class two-argument constructor(int, String)
2. Super class one -argument constructor(int)
3. Super Class no-argument constructor
4. Sub class String argument constructor
5. Sub class String argument constructor
6. Sub class integer argument constructor

Interface:

Top 10 interview questions on java interfaces


Posted by: InstanceOfJava Posted date: Mar 1, 2016 / comment : 8
1.What is an interface in Java.

 Before Java 8 interfaces are pure abstract classes which allow us to define public
static final variables and public abstract methods(by default).
 In java 8 introduced static methods and default methods in interfaces.
 Java 8 Interface Static and Default Methods
 We can develop interfaces by using "interface" keyword.
 A class will implements all the methods in an interface.

1. package com.instanceofjava;

2. interface JavaInterface{

3.

4. int x=12;

5. void show();

6.

7. }

1. package com.instanceofjava;

2. Class A implements JavaInterface {

3.

4. void show(){

5. // code

6. }

7.

8. }

1. package com.instanceofjava;

2. interface Java8Interface{

3.
4. int x=12;

5. void show();

6.

7.

8. default void display(){

9.

10. System.out.println("default method of interface");

11.

12. }

13.

14. Static void print(String str){

15.

16. System.out.println("Static method of interface:"+str);

17.

18. }

19.

20.

21. }

2.What will happen if we define a concrete method in an interface?

 By default interface methods are abstract.


 if we declare any concrete method in an interface compile time error will come.
 Error:Abstract methods do not specify a body
3.Can we create non static variables in an interface?

 No.We can not create non static variables in an interface.


 If we try to create non static variables compile time error comes.
 By default members will be treated as public static final variables so it expects
some value to be initialized.

1. package com.instanceofjava;

2. interface JavaInterface{

3.

4. int x, y; // compile time error


5.
6.

7. }

4.What will happen if we not initialize variables in an interface.

 Compile time error will come because by default members will be treated as
public static final variables so it expects some value to be initialized.
1. package com.instanceofjava;

2. interface JavaInterface{

3.

4. int x, y; // compile time error: The blank final field y may not have been initialized
5.
6.

7. }

5.Can we declare interface members as private or protected?

 No.

1. package com.instanceofjava;

2. interface JavaInterface{

3.

4. private int x; // compile time error: Illegal modifier for the interface field
Sample.x; only
5. public, static & final are permitted
6. protected int a; // compile time error: Illegal modifier for the interface field
Sample.a; only
7. public, static & final are permitted
8.

9. }

7.When we need to use extends and implements?

 A class will implements an interface.


 A class will extends another class.
 An interface extends another interface.

6.Can we create object for an interface?

 NO. We can not create object for interface.


 We can create a variable fro an interface
1. package com.instanceofjava;

2. interface JavaInterface{

3.

4. void show();

5.

6. }

1. package com.instanceofjava;

2. interface A implements JavaInterface {

3.

4. void show(){

5. // code

6. }

7. public static void main(String args[]){

8.

9. JavaInterface obj= new JavaInterface(); // Error: Cannot instantiate the type


JavaInterface

10.

11. }

12. }

7.Can we declare interface as final?

 No. Compile time error will come.


 Error: Illegal modifier for the interface Sample; only public & abstract are
permitted
8.Can we declare constructor inside an interface?

 No. Interfaces does not allow constructors.


 The variables inside interfaces are static final variables means constants and we
can not create object fro interface so there is no need of constructor in interface
that is the reason interface doesn't allow us to create constructor.

9.What will happen if we are not implementing all the methods of an interface
in class which implements an interface?

 A class which implements an interface should implement all the methods


(abstract) otherwise compiler will throw an error.
 The type Example must implement the inherited abstract method
JavaInterface.show()
 1If we declare class as abstract no need to implement methods.
 No need of overriding default and static methods.;

1. package com.instanceofjava;

2. interface JavaInterface{

3.

4. void show();

5.
 }

1. package com.instanceofjava;

2. interface A implements JavaInterface { // The type Example must implement the


inherited
3. abstract method JavaInterface.show()
4.

5. public static void main(String args[]){

6.

7.

8. }

9. }

10.How can we access same variables defined in two interfaces implemented


by a class?

 By Using corresponding interface.variable_name we can access variables of


corresponding interfaces.
11.If Same method is defined in two interfaces can we override this method
in class implementing these interfaces.

 Yes implementing the method once is enough in class.


 A class cannot implement two interfaces that have methods with same name but
different return type.
Java example program to print message
without using System.out.println()
Posted by: InstanceOfJava Posted date: Mar 10, 2016 / comment : 0
Is it possible to print message without using system.out.println?

 Yes its possible to print message without using System.out.println("");

1. System.out.write("www.instanceofjava.com \n".getBytes());
2. System.out.format("%s", "www.instanceofjava.com \n")
3. PrintStream myout = new PrintStream(new
FileOutputStream(FileDescriptor.out));
myout.print("www.instanceofjava.com \n");
4. System.err.print("This is custom error message");
5. System.console().writer().println("Hai");

Method Overriding :

Top 10 Interview Programs and questions on


method overriding in java
Posted by: InstanceOfJava Posted date: Feb 17, 2016 / comment : 2
1.What is method overriding in java?

 Defining multiple methods with same name and same signature in super class
and sub class known as method overriding.
 Method overriding is type of polymorphism in java which is one of the main
object oriented feature.
 Redefined the super class method in sub class is known as method overriding.
 method overriding allows sub class to provide specific implementation that is
already defined in super class.
 Sub class functionality replaces the super class method functionality
(implementation).
2. Can we override private methods in java?
 No. Its not possible to override private methods because private methods in
super class will not be inherited to sub class.
 ReadCan a private method in super class be overridden in Sub class?

3. Can we override static methods of super class in sub class?

 NO.Its not possible to override static methods because static means class level
so static methods not involve in inheritance.
 Can we override static methods in java

4. Can we change the return type of overridden method in sub class?

 No. Return type must be same in super class and sub class.

1. package MethodOverridingExamplePrograms;

2. public class Super{

3.

4. void add(){

5. System.out.println("Super class add method");

6. }

7.

8. }

1. package MethodOverridingInterviewPrograms;

2. public class Sub extends Super{


3.

4. int add(){ //Compiler Error: The return type is incompatible with Super.add()

5.

6. System.out.println("Sub class add method");

7. return 0;

8.

9. }

10.

11. }

5.Can we change accessibility modifier in sub class overridden method?

 Yes we can change accessibility modifier in sub class overridden method but
should increase the accessibility if we decrease compiler will throw an error
message.

Super class method Subclass method

protected protected, public

public public

default default , public

6.What happens if we try to decrease accessibility from super class to sub


class?

 Compile time error will come.

1. package MethodOverridingExamplePrograms;

2. public class Super{

3.

4. public void add(){


5. System.out.println("Super class add method");

6. }

7.

8. }

1. package MethodOverridingInterviewPrograms;

2. public class Sub extends Super{

3.

4. void add(){ //Compiler Error: Cannot reduce the visibility of the inherited method
5. from Super

6.

7. System.out.println("Sub class add method");

8.

9. }

10.

11. }
7.Can we override a super class method without throws clause to with throws
clause in the sub class?

 Yes if super class method throws unchecked exceptions.


 No need if super class method throws checked exceptions. But it is
recommended to add in sub class method in order to maintain exception
messages.

8.What are the rules we need to follow in overriding if super class method
throws exception ?

 Exception handling in method overriding

9.What happens if we not follow these rules if super class method throws
some exception.

 Compile time error will come.

1. package MethodOverridingExamplePrograms;

2. public class Super{


3.

4. public void add(){

5. System.out.println("Super class add method");

6. }

7.

8. }

1. package MethodOverridingInterviewPrograms;

2. public class Sub extends Super{

3.

4. void add() throws Exception{ //Compiler Error: Exception Exception is not


compatible with
5. throws clause in Super.add()
6.

7. System.out.println("Sub class add method");

8.

9. }

10.

11. }

1. package MethodOverridingExamplePrograms;

2. public class Super{

3.

4. public void add(){

5. System.out.println("Super class add method");

6. }
7.

8. }

1. package MethodOverridingInterviewPrograms;

2. public class Sub extends Super{

3.

4. void add() throws NullPointerException{ // this method throws unchecked


exception so no

5. isuues
6.

7. System.out.println("Sub class add method");

8.

9. }

10.

11. }

10.Can we change an exception of a method with throws clause from


unchecked to checked while overriding it?

 No. As mentioned above already


 If super class method throws exceptions in sub class if you want to mention
throws then use same class or its sub class exception.
 So we can not change from unchecked to checked
yes return type of overriding method can be different

Method Overloading :
 Yes. We can overload static methods in java.
 Method overriding is not possible but method overloading is possible for static
methods.
 1.What is Method in java?
 Method is a sub block of a class that contains logic of that class.
 logic must be placed inside a method, not directly at class level, if we place logic
at class level compiler throws an error.
 So class level we are allowed to place variables and methods.
 The logical statements such as method calls, calculations and printing related
statements must be placed inside method, because these statements are
considered as logic.
 For more information @ Methods in java

1. package com.instanceofjava;

2. class sample{

3.

4. int a;

5. int b;

6.

7. System.out.println("instance of java"); // compiler throws an error.

8.

9. }

10.

1. package com.instanceofjava;

2. class sample{

3.

4. static int a=10;

5.

6.

7. public static void main(String args[]){


8.
9. System.out.println(a); // works fine,prints a value:10
10.
11. }

12. }

2.What is meant by method overloading in java?

 Defining multiple methods with same name is known as polymorphism.


 Defining multiple methods with same name and with different arguments known
as method overloading.

1. package com.instanceofjava;

2. class A{

3.

4. public void show(int a){

5. System.out.println("saidesh");

6. }

7.

8. public void show(int a,int b){

9. System.out.println("ajay");

10. }

11.

12. public void show(float a){

13. System.out.println("vinod");

14. }

15. public static void main(String args[]){

16.

17. A a=new A();


18.

19. a.show(10);

20. a.show(1,2);

21. a.show(1.2);

22.

23. }

24. }

Output:

1. saidesh

2. ajay

3. vinod

3.What are the other names for method overloading?

 Method overloading also known as static polymorphism or compile time


polymorphism because at compile time itself we can tell which method going to
get executed based on method arguments.
 So method overloading also called as static binding.

4.What are the basic rules of method overloading?

 Defining a method with same name and differ in number of arguments


 Defining a method with same name and differ in type of arguments
 Defining a method with same name and differ in order of type of arguments
 Return type of the method not involved in method overloading.

5.Can we overload static methods in java?

 Yes. We can overload static methods in java.


 Method overriding is not possible but method overloading is possible for static
methods.
 Before that lets see about method overloading in java.
 lets see an example java program which explains static method overloading.

1. class StaticMethodOverloading{

2.

3. public static void staticMethod(){

4.

5. System.out.println("staticMethod(): Zero arguments");

6.

7. }

8.

9. public static void staticMethod(int a){

10.

11. System.out.println("staticMethod(int a): one argument");

12.

13. }

14.

15. public static void staticMethod(String str, int x){

16.

17. System.out.println("staticMethod(String str, int x): two arguments");

18.

19. }

20.

21. public static void main(String []args){

22.
23. StaticMethodOverloading.staticMethod();

24. StaticMethodOverloading.staticMethod(12);

25. StaticMethodOverloading.staticMethod("Static method overloading",10);

26.

27. }

28. }

Output:

1. staticMethod(): Zero arguments

2. staticMethod(int a): one argument

3. staticMethod(String str, int x): two arguments

6.Can we overload main method in java?

Yes we can overload main method in java

Java Program to overload main method in java


1. class mainMethodOverloading{

2.

3. public static void main(boolean x){

4.

5. System.out.println("main(boolean x) called ");

6.

7. }

8.
9. public static void main(int x){

10.

11. System.out.println("main(int x) called");

12.

13. }

14.

15. public static void main(int a, int b){

16.

17. System.out.println("main(int a, int b) called");

18.

19. }

20.

21. public static void main(String []args){

22.

23.

24. System.out.println("main(String []args) called ");

25.

26. mainMethodOverloading.main(true);

27. mainMethodOverloading.main(10);

28. mainMethodOverloading.main(37,46);

29.

30.

31. }

32. }
Output:

1. main(String []args) called

2. main(boolean x) called

3. main(int x) called

4. main(int a, int b) called

7.Can we overload constructors in java?


 Yes we can overload constructor in java

1. package instanceofjava;

2. class ConstructorChaining{

3. int a,b

4. ConstructorChaining(){

5. this(1,2);

6. System.out.println("Default constructor");

7.

8. }

9.

10. ConstructorChaining(int x , int y){

11.

12. this(1,2,3);

13. a=x;

14. b=y;

15. System.out.println("Two argument constructor");

16.

17. }

18.

19. ConstructorChaining(int a , int b,int c){

20. System.out.println("Three argument constructor")

21. }

22.
23. public static void main(String[] args){

24.

25. ConstructorChaining obj=new ConstructorChaining();

26. System.out.println(obj.a);

27. System.out.println(obj.b);

28.

29. }

30. }

Home › Top 20 Java Exception handling interview questions and answers

Top 20 Java Exception handling interview


questions and answers
Posted by: InstanceOfJava Posted date: Apr 26, 2016 / comment : 1
1.What is an exception?

 Exceptions are the objects representing the logical errors that occur at run time
and makes JVM enters into the state of "ambiguity".
 The objects which are automatically created by the JVM for representing these
run time errors are known as Exceptions

2.What are the differences between exception and error.

 An Error is a subclass of Throwable that indicates serious problems that a


reasonable application should not try to catch. Most such errors are abnormal
conditions.
 Difference between exception and error
3.How the exceptions are handled in java

 Exceptions can be handled using try catch blocks.


 The statements which are proven to generate exceptions need to keep in try
block so that whenever is there any exception identified in try block that will be
assigned to corresponding exception class object in catch block
 More information about try catch finally

4.What is the super class for Exception and Error

 Throwable.

1. public class Exception extends Throwable implements Serializable

1. public class Error extends Throwable implements Serializable

5.Exceptions are defined in which java package

 java.lang.Exception

6.What is throw keyword in java?

 Throw keyword is used to throw exception manually.


 Whenever it is required to suspend the execution of the functionality based on
the user defined logical error condition we will use this throw keyword to throw
exception.
 Throw keyword in java

7.Can we have try block without catch block

 It is possible to have try block without catch block by using finally block
 Java supports try with finally block
 As we know finally block will always executes even there is an exception
occurred in try block, Except System.exit() it will executes always.
 Is it possible to write try block without catch block

8.Can we write multiple catch blocks under single try block?

 Yes we can write multiple catch blocks under single try block.
 Multiple catch blocks in java

9. What are unreachable blocks in java

 The block of statements to which the control would never reach under any case
can be called as unreachable blocks.
 Unreachable blocks are not supported by java.
 Unreachable blocks in java
10.How to write user defined exception or custom exception in java

 By extending Exception class we can define custom exceptions.


 We need to write a constructor for passing message .
 User defined exception in java

1. class CustomException extends Exception { } // this will create Checked


Exception

2. class CustomException extends IOExcpetion { } // this will create Checked


exception

3. class CustomException extends NullPonterExcpetion { } // this will create


UnChecked

4. exception

11.What are the different ways to print exception message on console.

 In Java there are three ways to find the details of the exception .
 They are
1. Using an object of java.lang.Exception
2. Using public void printStackTrace() method
3. Using public String getMessage() method.

 3 different ways to print exception message in java

12.What are the differences between final finally and finalize in java

 Finally vs final vs finalize

13.Can we write return statement in try and catch blocks

 Yes we can write return statement of the method in try block and catch block
 We need to follow some rules to use it.Please check below link
 Return statement in try and catch blocks
14. Can we write return statement in finally block

 Yes we can write return statement of the method in finally block


 We need to follow some rules to use it.Please check below link
 Return statement in finally block
15. What are the differences between throw and throws

 throw keyword used to throw user defined exceptions.(we can throw predefined
exception too)
 Using throws keyword we can explicitly provide the information about unhand-led
exceptions of the method to the end user, Java compiler, JVM.
 Throw vs throws
16.Can we change an exception of a method with throws clause from
unchecked to checked while overriding it?

 No. As mentioned above already


 If super class method throws exceptions in sub class if you want to mention
throws then use same class or its sub class exception.
 So we can not change from unchecked to checked

17.What are the rules we need to follow in overriding if super class method
throws exception ?

 If sub class throws checked exception super class should throw same or super
class exception of this.
 If super class method throws checked or unchecked exceptions its not
mandatory to put throws in sub class overridden method.
 If super class method throws exceptions in sub class if you want to mention
throws then use same class or its sub class exception.

18.What happens if we not follow above rules if super class method throws
some exception.

 Compile time error will come.

1. package MethodOverridingExamplePrograms;

2. public class Super{

3.

4. public void add(){

5. System.out.println("Super class add method");

6. }

7.
8. }

1. package MethodOverridingInterviewPrograms;

2. public class Sub extends Super{

3.

4. void add() throws Exception{ //Compiler Error: Exception Exception is not


compatible with
5. throws clause in Super.add()
6.

7. System.out.println("Sub class add method");

8.

9. }

10.

11. }

1. package ExceptionHandlingInterviewPrograms;

2. public class Super{

3.

4. public void add(){

5. System.out.println("Super class add method");

6. }

7.

8. }

1. package ExceptionHandlingInterviewPrograms;

2. public class Sub extends Super{


3.

4. void add() throws NullPointerException{ // this method throws unchecked


exception so no

5. isuues
6.

7. System.out.println("Sub class add method");

8.

9. }

10.

11. }

19. Is it possible to write multiple exceptions in single catch block

 It is not possible prior to java 7.


 new feature added in java 7.

1. package exceptionsFreshersandExperienced;

2. public class ExceptionhandlingInterviewQuestions{

3.

4. /**

5. * @www.instanceofjava.com

6. **/

7. public static void main(String[] args) {

8.

9.

10. try {
11.

12. // your code here

13.

14. } catch (IOException | SQLException ex) {

15. System.out.println(e);

16. }

17.

18. }

19.

20. }

20. What is try with resource block

 One more interesting feature of Java 7 is try with resource


 In Java, if you use a resource like input or output streams or any database
connection logic you always need to close it after using.
 It also can throw exceptions so it has to be in a try block and catch block. The
closing logic should be in finally block. This is a least the way until Java 7. This
has several disadvantages:

1. You'd have to check if your ressource is null before closing it


2. The closing itself can throw exceptions so your finally had to
contain another try -catch
3. Programmers tend to forget to close their resources

 The solution given by using try with resource statement.

1. try(resource-specification)

2. {
3.

4. //use the resource

5.

6. }catch(Exception e)

7. {

8.

9. //code

10.

11. }

 Top 20 Java Exception handling interview questions and answers for freshers and
experienced

Can we call sub class methods using super


class object
Posted by: InstanceOfJava Posted date: Jul 12, 2015 / comment : 5
 Common coding interview question everybody facing in interviews is can we call
sub class method using super class object? or can we call child class method
using parent class? or can a super class call a subclass' method.
 The answer is No. but still we can say yes. so we need to what are all those
scenarios of calling sub class method from super class and lets discuss about
which is the actual possible case to call sub class method using super class
object.
 Before that let me explain what is inheritance and how the super and sub classes
related each other.

Inheritance:
 Getting the properties from one class object to another class object is known as
inheritance.
 Two types of inheritance
 Getting the properties from one class object to another with level wise and with
some priorities is known as multilevel inheritance.
 Getting the properties from one class object to another class object with same
priority is known as multiple inheritance
 Java does not supports multiple inheritance
Read this:

Why Java does not supports multiple inheritance

Creating super class object and calling methods


1. //Multilevel inheritance program

2. Class A{

3.

4. int a;

5.

6. public void print(){

7.

8. System.out.println("print method of super class A");

9.

10. }

11.

12. }

13. Class B extends A{

14.

15. public void show(){

16.

17. System.out.println("show method of sub class B");


18.

19. }

20. public static void main(String[] args){

21.

22. A obj= new A();

23. obj.a=10;

24.

25. obj.print();

26. //obj.show(); // compile time error

27.

28. System.out.println("a="obj.a);

29.

30. }

31. }

Output:

1. print method of super class A

2. 10

 In above program super class and sub class is there and sub class extending
super class.
 But we created object for super class so we can call only super class methods on
that object.
 If we create sub class object we can call super class and sub class methods on
that object now we can able to access super class A methods only.
 So by creating super class object we can call only super class methods
Creating super class object and calling methods
1. //Multilevel inheritance program

2. Class A{

3.

4. int a;

5.

6. public void print(){

7.

8. System.out.println("print method of super class A");

9.

10. }

11.

12. }

13. Class B extends A{

14.

15. public void show(){

16.

17. System.out.println("show method of sub class B");

18.

19. }

20. public static void main(String[] args){

21.

22. B obj= new B();


23. obj.a=10;

24.

25. obj.print();

26. obj.show();

27.

28. System.out.println("a="obj.a);

29.

30. }

31. }

Output:

1. print method of super class A

2. show method of sub class B

3. 10

 Above program shows sub class object using super class methods and variables
as we said in inheritance concept all super class members can accessed by the
sub class means all super class members are available to sub class if sub class
extending super class.
 So whenever we create object of sub class it will call sub class constructor and
from sub class constructor super class constructor will be called so memory will
be allocated to all super class non static member and sub class non static
members.
 So we can call super class methods using sub class.
 B obj= new B();
 obj.print();
 So by creating sub class object we can call both super class methods and sub
class methods.
Assigning sub class reference to super class object.
1. //Multilevel inheritance program

2. Class A{

3.

4. int a;

5.

6. public void print(){

7.

8. System.out.println("print method of super class A");

9.

10. }

11.

12. }

13. Class B extends A{

14.

15. public void show(){

16.

17. System.out.println("show method of sub class B");

18.

19. }

20. public static void main(String[] args){

21.

22. A obj= new B();

23. obj.a=10;

24.
25. obj.print();

26. //obj.show(); // compile time error

27.

28. System.out.println("a="obj.a);

29.

30. }

31. }

Output:

1. print method of super class A

2. 10

 Yes we can assign sub class object to super class reference.


 So here Sub class object is created so memory allocated to all super class
members
 so can we call all methods ? No eventhough sub class object is created we can
not call sub class methods because we assigned sub class object to super class
reference.
 Then how its possible to call sub class methods?
 Yes its possible to call sub class methods using super class by type casting to sub
class object .
 By type casting super class object to sub class object we can access all
corresponding sub class and all super class methods on that reference.

Assigning sub class reference to super class object.


1. //Multilevel inheritance program

2. Class A{

3.
4. int a;

5.

6. public void print(){

7.

8. System.out.println("print method of super class A");

9.

10. }

11.

12. }

13. Class B extends A{

14.

15. public void show(){

16.

17. System.out.println("show method of sub class B");

18.

19. }

20. public static void main(String[] args){

21.

22. A obj= new B();

23. obj.a=10;

24.

25. obj.print();

26. //obj.show(); compile time error

27. ((B)obj).show(); // works fine

28.
29.

30. System.out.println("a="obj.a);

31.

32. }

33. }

Output:

1. print method of super class A

2. show method of sub class B

3. 10

Assigning sub class reference to super class object. We can call sub class
methods if overridden

Otherwise we need to typecast to call sub class methods


1. //Multilevel inheritance program

2. Class A{

3.

4. int a;

5.

6. public void print(){

7.

8. System.out.println("print method of super class A");

9.

10. }
11.

12. }

13. Class B extends A{

14.

15. public void show(){

16.

17. System.out.println("show method of sub class B");

18.

19. }

20. public void print(){

21.

22. System.out.println("Print method of Sub class B");

23.

24. }

25.

26. public static void main(String[] args){

27.

28. A obj= new B();

29. obj.a=10;

30.

31. obj.print(); // print method is overridden in sub class so it will execute sub class
method.

32. //obj.show(); compile time error

33. ((B)obj).show(); // works fine

34.
35.
36. System.out.println("a="obj.a);

37.

38. }

39. }

Output:

1. Print method of Sub class B

2. show method of sub class B

3. 10

Difference between Collections and Collection


in java with example program
Posted by: InstanceOfJava Posted date: Jun 18, 2016 / comment : 0
 Famous java interview question: difference between collections and collection in
java
 Major difference between Collection and Collections is Collection is an interface
and Collections is a class.
 Both are belongs to java.util package
 Collection is base interface for list set and queue.
 Collections is a class and it is called utility class.
 Collections utility class contains some predefined methods so that we can use
while working with Collection type of classes(treeset, arraylist, linkedlist etc.)
 Collection is base interface for List , Set and Queue.

Collection vs Collections
1. public interface Collection<E>

2. extends Iterable<E>

1. public class Collections

2. extends Object

 Collections utility class contains static utility methods so that we can use those
methods by using class name without creating object of Collections class object
 Lest see some methods of Collections class.

1. addAll: public static <T> boolean addAll(Collection<? super T> c,T...


elements)
2. reverseOrder: public static <T> Comparator<T> reverseOrder()
3. shuffle: public static void shuffle(List<?> list)
4. sort:public static <T extends Comparable<? super T>> void sort(List<T> list)
How to Relate Collection and Collections

 ArrayList is a Collection type of class means it is implementing Collection


interface internally
 Now lets see a java example program to sort ArrayList of elements using
Collections.sort() method.

1. public class ArrayList<E>

2. extends AbstractList<E>

3. implements List<E>, RandomAccess, Cloneable, Serializable

1.Basic Java example program to sort arraylist of integers using


Collections.sort() method

1. package com.javasortarraylistofobjects;

2.

3. import java.util.ArrayList;

4. import java.util.Collections;

5. import java.util.Iterator;

6.

7. public class SortArrayListExample{

8.

9. public static void main(String[] args) {

10.

11. //create an ArrayList object

12. ArrayList<Integer> arrayList = new ArrayList<Integer>();

13.
14. //Add elements to Arraylist

15. arrayList.add(10);

16. arrayList.add(7);

17. arrayList.add(11);

18. arrayList.add(4);

19. arrayList.add(9);

20. arrayList.add(6);

21. arrayList.add(2);

22. arrayList.add(8);

23. arrayList.add(5);

24. arrayList.add(1);

25.

26.

27. System.out.println("Before sorting ArrayList ...");

28. Iterator itr=arrayList.iterator();

29.

30. while (itr.hasNext()) {

31.

32. System.out.println(itr.next());

33.

34. }

35.

36.

37. /*

38. To sort an ArrayList object, use Collection.sort method. This is a


39. static method. It sorts an ArrayList object's elements into ascending order.

40. */

41. Collections.sort(arrayList);

42.

43. System.out.println("After sorting ArrayList ...");

44.

45.

46.

47. Iterator itr1=arrayList.iterator();

48.

49. while (itr1.hasNext()) {

50.

51. System.out.println(itr1.next());

52.

53. }

54.

55.

56. }

57. }

Output:

1. Before sorting ArrayList ...

2. 10

3. 7
4. 11

5. 4

6. 9

7. 6

8. 2

9. 8

10. 5

11. 1

12. After sorting ArrayList ...

13. 1

14. 2

15. 4

16. 5

17. 6

18. 7

19. 8

20. 9

21. 10

22. 11

Unreachable Blocks in java


Posted by: InstanceOfJava Posted date: Apr 19, 2016 / comment : 1
Unreachable Catch Blocks:

 The block of statements to which the control would never reach under any case
can be called as unreachable blocks.
 Unreachable blocks are not supported by java.
 Thus catch block mentioned with the reference of "Exception" class should and
must be always last catch block. Because Exception is super class of all
exceptions.

Program:

1. package com.instanceofjava;

2. public class ExcpetionDemo {

3. public static void main(String agrs[])

4. {

5.

6. try

7. {

8. //statements

9. }

10. catch(Exception e)

11. {

12. System.out.println(e);

13. }

14. catch(ArithmeticException e)//unreachable block.. not supported by java. leads to


error

15. System.out.println(e);

16. }

17. }
Enum:

Enum in java Example


Posted by: InstanceOfJava Posted date: Apr 19, 2016 / comment : 0
Java Enum:

 In this tutorial I will explain what is enum, how to use enum in different areas of a
Java program and an example program on it.

 An Enum type is a special data type which is added in Java 1.5 version. It is an
abstract class in Java API which implements Cloneable and Serializable
interfaces. It is used to define collection of constants. When you need a
predefined list of values which do not represent some kind of numeric or textual
data, at this moment, you have to use an enum.
 Common examples include days of week (values of SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY), directions, and months in a
year. Etc.
 You can declare simple Java enum type with a syntax that is similar to the Java
class declaration syntax. Let’s look at several short Java enum examples to get
you started.

Enum declaration Example 1:

1. public enum Day {

2. SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

3. }

Enum declaration Example 2:

1. public enum Month{

2. JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER,

3. OCTOBER, NOVEMBER, DECEMBER


4. }

 Enums are constants; they are by default static and final. That’s why the names
of an enum type's fields are in uppercase letters.
 Make a note that the enum keyword which is used in place of class or interface.
The Java enum keyword signals to the Java compiler that this type definition is
an enum.
You can refer to the constants in the enum above like this:

1. Day day = Day.MONDAY;

 Here the ‘day’ variable is of the type ‘Day’ which is the Java enum type defined in
the example above. The ‘day’ variable can take one of the ‘Day’ enum
constants as value (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY). In this case ‘day’ is set to MONDAY.
 If you use enum instead of integers or String codes, you increase compile-time
checking and avoid errors from passing in invalid constants, and you document
which values are legal to use.
 How to use a Java enum type in various areas in a Java Program:
 We have seen how to declare simple Java enum types, let’s take a look at how to
use them in various areas. We have to use a Java enum type in a variety of
situations, including in a Java 5 for loop, in a switch statement, in an if/else
statement, and more. For simple, Enum comparison, there are 3 ways to do it.
They are, Switch-Case Statement, == Operator, .equals() method. Like that
there are other places where you have to use Enum.
 Let's take a look at how to use our simple enum types with each of these Java
constructs.
1. Enum in IF statement
2. Enum in Switch statement
3. Enum Iteration in for-each loop
4. Enum Fields
5. Enum Methods
1. Enum in IF statements:

 We know Java Enums are constants. Sometimes, we have a requirement to


compare a variable of Enum constant against the possible other constants in
the Enum type. At this moment, we have to use IF statement as follows.
 Day day = ----- //assign some Day constants to it.
1. If(day ==Day.MONDAY){

2. ….//your code

3. } else if (day == Day.TUESDAY){

4. ….//your code

5. } else if (day == Day.WEDNESDAY){

6. ….//your code

7. } else if (day == Day. THURSDAY){

8. ….//your code

9. } else if (day == Day.FRIDAY){

10. ….//your code

11. } else if (day == Day.SATURDAY){

12. ….//your code

13. } else if (day == Day.SUNDAY){

14. ….//your code

15. }

 Here, you can use “.equals()” instead of “==”. But, my preference is to use “==”
because, it will never throws NullPointerException, safer at compile-time,
runtime and faster.
 The code snippet compares the ‘day’ variable against each of the possible other
Enum constants in the ‘Day’ Enum.

2. Enums in Switch Statements:

 Just assume that your Enum have lot of constants and you need to check a
variable against the other values in Enum. For a small Enum IF Statement will
be OK. If you use same IF statement for lot of Enum constants then our program
will be increased and it is not a standard way to write a Java program. At this
Situation, use Switch Statement instead of IF statement.
 You can use enums in switch statements as follows:
 Day day = ... //assign some Day constant to it

1. switch (day) {

2.

3. case SUNDAY : //your code; break;

4. case MONDAY //your code; break;

5. case TUESDAY : //your code; break;

6. case WEDNESDAY : //your code; break;

7. case THURSDAY: //your code; break;

8. case FRIDAY : //your code; break;

9. case SATURDAY : //your code; break;

10.

11. }

 Here, give your code in the comments, “//your code”. The code should be a
simple Java operation or a method call..etc
3.Enum Iteration in for-each loop
4.Enum Fields
5.Enum Methods

Please click here Enum in java part 2

Can we create private constructor in java


Posted by: InstanceOfJava Posted date: Feb 25, 2016 / comment : 0
1.Can a constructor in Java be private?

 Yes we can declare private constructor in java.


 If we declare constructor as private we can not able to create object of the class.
 In singleton design pattern we use this private constructor.

2.In what scenarios we will use private constructor in java.

 Singleton Design pattern


 It wont allow class to be sub classed.
 It wont allow to create object outside the class.
 If All Constant methods is there in our class we can use private constructor.
 If all methods are static then we can use private constructor.

3.What will happen if we extends a class which is having private constructor.


 If we try to extend a class which is having private constructor compile time error
will come.
 Implicit super constructor is not visible for default constructor. Must define an
explicit constructor

Singleton Design pattern:

1. package com.privateConstructorSingleTon;

2.

3. public class SingletonClass {

4.

5. private static SingletonClass object;

6.

7. private SingletonClass ()

8. {

9. System.out.println("Singleton(): Private constructor invoked");


10. }

11.

12. public static SingletonClass getInstance()

13. {

14.

15. if (object == null)

16. {

17.

18. System.out.println("getInstance(): First time getInstance was called and object


created !");

19. object = new SingletonClass ();

20.

21. }

22.

23. return object;

24.

25. }

26.

27. }

1. package instanceofjava;

2.

3. public class SingletonObjectDemo {

4.
5. public static void main(String args[]) {

6.

7. SingletonClass s1= SingletonClass .getInstance();

8. SingletonClass s2= SingletonClass .getInstance();

9. System.out.println(s1.hashCode());

10. System.out.println(s2.hashCode());

11.

12. }

13. }

Output:

1. getInstance(): First time getInstance was called and object created !

2. Singleton(): Private constructor invoked

3. 655022016

4. 655022016

Singleton Design Pattern in java


Posted by: InstanceOfJava Posted date: May 17, 2015 / comment : 2

Problem:
 Instead of creating multiple objects of same class having same data and wasting
memory, degrading performance it is recommended to create only one object
and use it multiple times.

Solution:
 Use Singleton Java Class.
 Java class that allows us to create one object per JVM is is called as singleton java
class.
 The logger class of Log 4J API is given as singleton java class.

Rules:
 It must have only private constructors.
 It must have private static reference variable of same class.
 It must have public static factory method having the logic of singleton.
 Static method should create and return only one object.
 All these rules close all the doors of creating objects for java class and opens only
one door to create object.
 factory method where singleton logic is placed
 The method of a class capable of creating and returning same class or other
class object is known as factory method.

1. package com.instanceofjava;

2.

3. public class SingletonClass {

4.

5. private static SingletonClass object;

6.

7. private SingletonClass ()

8. {

9. System.out.println("Singleton(): Private constructor invoked");

10. }

11.

12. public static SingletonClass getInstance()

13. {

14.

15. if (object == null)


16. {

17.

18. System.out.println("getInstance(): First time getInstance was called and object


created !");

19. object = new SingletonClass ();

20.

21. }

22.

23. return object;

24.

25. }

26.

27. }

1. package instanceofjava;

2.

3. public class SingletonObjectDemo {

4.

5. public static void main(String args[]) {

6.

7. SingletonClass s1= SingletonClass .getInstance();

8. SingletonClass s2= SingletonClass .getInstance();

9. System.out.println(s1.hashCode());

10. System.out.println(s2.hashCode());

11.
12. }

13. }

Output:

1. getInstance(): First time getInstance was called and object created !

2. Singleton(): Private constructor invoked

3. 655022016

4. 655022016

Make the Factory method Synchronized to prevent from Thread Problems:

1. package com.instanceofjava;

2.

3. public class SingletonClass {

4.

5. private static SingletonClass object;

6.

7. private SingletonClass ()

8. {

9. System.out.println("Singleton(): Private constructor invoked");

10. }

11.

12. public static synchronized SingletonClass getInstance()


13. {

14.

15. if (object == null)

16. {

17.

18. System.out.println("getInstance(): First time getInstance was called and object


created !");

19. object = new SingletonClass ();

20.

21. }

22.

23. return object;

24.

25. }

26.

27. }

Override the clone method to prevent cloning:

1. package com.instanceofjava;

2.

3. public class SingletonClass {

4.

5. private static SingletonClass object;


6.

7. private SingletonClass ()

8. {

9. System.out.println("Singleton(): Private constructor invoked");

10. }

11.

12. public static synchronized SingletonClass getInstance()

13. {

14.

15. if (object == null)

16. {

17.

18. System.out.println("getInstance(): First time getInstance was called and object


created !");

19. object = new SingletonClass ();

20.

21. }

22. else

23. return object;

24.

25. }

26.

27. public Object clone() throws CloneNotSupportedException {

28.

29. throw new CloneNotSupportedException();


30.

31. }

32.

33. }

Eager Initialization:
 In eager initialization object of the class will be created when class loading itself
its easy way to create singleton but its having one disadvantage that even
though nobody needs it still it creates object.

1. package com.instanceofjava;

2.

3. public class SingletonClass {

4.

5. private static SingletonClass object= new SingletonClass ();

6.

7. private SingletonClass ()

8. {

9. System.out.println("Singleton(): Private constructor invoked");

10. }

11.

12. public static SingletonClass getInstance()

13. {

14.

15. return object;


16.

17. }

18.

19. }

Lazy Initialization:
 When ever client needs object it will check for whether object is created or not if
not it will create otherwise it will return created object
 First basic example shows lazy initialization.

Static Block Initialization:


 This is similar to eager initialization except that in this we create object in static
block and we can place exception logic.

1. package com.instanceofjava;

2.

3. public class StaticBlockSingleton {

4.

5. private static StaticBlockSingleton object;

6.

7. private StaticBlockSingleton(){}

8.

9. //static block initialization for exception handling

10. static{

11.
12. try{

13.

14. object = new StaticBlockSingleton();

15.

16. }catch(Exception e){

17.

18. throw new RuntimeException("Exception occured in creating singleton


object");

19. }

20. }

21.

22. public static StaticBlockSingleton getInstance(){

23. return object;

24. }

25.

26. }

Encapsulation in java with example program


Posted by: InstanceOfJava Posted date: Mar 6, 2015 / comment : 3
What is meant by encapsulation in java?

 Binding the data with its related functionalities known as encapsulation


 Here data means variables and functionalities means methods.
 So keeping the variable and related methods in one place.
 That place is "class". class is the base for encapsulation.
 Lets see example program on encapsulation, how the variables and methods
defined in a class
What is encapsulation in object oriented programming?

Basic java example program on data encapsulation:

1. package com.instanceofjava;

2.

3. public class EncapsulationDemo {

4.

5. String name;

6. int rno;

7. String address;

8.

9. public String getName() {

10. return name;

11. }

12.

13. public void setName(String name) {

14. this.name = name;

15. }

16.

17. public int getRno() {

18. return rno;

19. }

20.

21. public void setRno(int rno) {


22. this.rno = rno;

23. }

24.

25. public String getAddress() {

26. return address;

27. }

28.

29. public void setAddress(String address) {

30. this.address = address;

31. }

32.

33. public void showInfo(){

34.

35. System.out.println("Name: "+getName());

36. System.out.println("R.No: "+getRno());

37. System.out.println("Name: "+getAddress());

38.

39. }

40. }

Class:
 The above example program shows how the variables and methods will be there
in a class.
 So class is the base for encapsulation
 class is user defined data type in java means by using class we can structure our
own programs.
 Lest see a example program on class.

1. package com.instanceofjava;

2.

3. public class ClassDemo {

4.

5. //variables of a class

6. String empName;

7. int empId;

8. String Designation;

9.

10. //getter and setter methods for variables

11. //by using these methods we can set the value to the variable and gat the value
from the

12. //variables

13.

14. public String getEmpName() {

15. return empName;

16. }

17.

18. public void setEmpName(String empName) {

19. this.empName = empName;

20. }

21.

22. public int getEmpId() {


23. return empId;

24. }

25.

26. public void setEmpId(int empId) {

27. this.empId = empId;

28. }

29.

30. public String getDesignation() {

31. return Designation;

32. }

33.

34. public void setDesignation(String designation) {

35. Designation = designation;

36. }

37.

38. }

Object:
 Instance of class is known as object.
 Instance means dynamic memory allocation. So dynamic memory allocation to
class is called object.
 By using "new" keyword the object will be created dynamically.
 Class is a template. By using object we will get memory for all variables so that
we can use them.

 We can create number of objects for one class based on our requirements.
 Below an example program on class and object.
1. package com.instanceofjava;

2.

3. public class User {

4.

5. String Name;

6. int Id;

7. String address;

8.

9. public String getName() {

10. return Name;

11. }

12.

13. public void setName(String name) {

14. Name = name;

15. }

16.

17. public int getId() {

18. return Id;

19. }

20.

21. public void setId(int id) {

22. Id = id;

23. }
24.

25. public String getAddress() {

26. return address;

27. }

28.

29. public void setAddress(String address) {

30. this.address = address;

31. }

32.

33. public static void main(String [] args){

34.

35. User obj= new User();

36.

37. obj.setName("sai");

38. obj.setId(1);

39. obj.setAddress("xyz");

40.

41. System.out.println(obj.getName());

42. System.out.println(obj.getId());

43. System.out.println(obj.getAddress());

44.

45. }

46. }
Output:
1. sai

2. 1

3. xyz

Home › Top 20 collection framework interview questions and answers in java

Top 20 collection framework interview


questions and answers in java
Posted by: InstanceOfJava Posted date: Jul 21, 2015 / comment : 3
Java collections interview questions:

1.Why Map interface doesn’t extend Collection interface?


 Set is unordered collection and does not allows duplicate elements.
 List is ordered collection allows duplicate elements.
 Where as Map is key-value pair.
 It is viewed as set of keys and collection of values.
 Map is a collection of key value pairs so by design they separated from collection
interface.

2.What is difference between HashMap and Hashtable?


 Synchronization or Thread Safe
 Null keys and null values
 Iterating the values
 Default Capacity

Click here for the


Differences between HashMap and Hash-table

3.Differences between comparable and comparator?


 Comparable Interface is actually from java.lang package.
 It will have a method compareTo(Object obj)to sort objects
 Comparator Interface is actually from java.util package.
 It will have a method compare(Object obj1, Object obj2)to sort objects
Read more : comparable vs comparator

4.How can we sort a list of Objects?


 To sort the array of objects we will use Arrays.sort() method.
 If we need to sort collection of object we will use Collections.sort().

5.What is difference between fail-fast and fail-safe?


 Fail fast is nothing but immediately report any failure. whenever a problem
occurs fail fast system fails.
 in java Fail fast iterator while iterating through collection of objects sometimes
concurrent modification exception will come there are two reasons for this.
 If one thread is iterating a collection and another thread trying to modify the
collection.
 And after remove() method call if we try to modify collection object

6. What is difference between Iterator ,ListIterator and Enumeration?


 Enumeration interface implemented in java 1.2 version.So Enumeration is legacy
interface.
 Enumeration uses elements() method.
 Iterator is implemented on all Java collection classes.
 Iterator uses iterator() method.
 Iterator can traverse in forward direction only.
 ListIterator is implemented only for List type classes
 ListIterator uses listIterator() method.
Read more :

What is difference between Iterator ,ListIterator and Enumeration?

7.What is difference between Set and List in Java?


 A set is a collection that allows unique elements.
 Set does not allow duplicate elements
 Set allows only one null value.
 Set having classes like :
 HashSet
 LinkedHashSet
 TreeSet
 List having index. and ordered collection
 List allows n number of null values.
 List will display Insertion order with index.
 List having classes like :
 Vector
 ArrayList
 LinkedList

8.Differences between arraylist and vector?


 Vector was introduced in first version of java . that's the reason only
vector is legacy class.
 ArrayList was introduced in java version1.2, as part of java collections
framework.
 Vector is synchronized.
 ArrayList is not synchronized.
Read more: Differences between arraylist and vector

9.What are the classes implementing List interface?


 ArrayList
 LinkedList
 Vector

10. Which all classes implement Set interface ?


 HashSet
 LinkedHashSet
 TreeSet

11.How to make a collection thread safe?


 Vector, Hashtable, Properties and Stack are synchronized classes, so they are
thread-safe and can be used in multi-threaded environment.
 By using Collections.synchronizedList(list)) we can make list classes thread safe.
 By using
java.util.Collections.synchronizedSet() we can make set classes thread safe.

12.Can a null element added to a TreeSet or HashSet?


 One null element can be added to hashset.
 TreeSet does not allow null values

13. Explain Collection’s interface hierarchy?

14.Which design pattern Iterator follows?


 Iterator design pattern

15.Which data structure HashSet implements


 Hashset implements hashmap internally.

16.Why doesn't Collection extend Cloneable and Serializable?


 List and Set and queue extends Collection interface.
 SortedMap extends Map interface.

17.What is the importance of hashCode() and equals() methods? How they


are used in Java?
 equals() and hashcode() methods defined in "object" class.
 If equals() method return true on comparing two objects then hashcode() of
those two objects must be same.

18.What is difference between array & arraylist?


 Array is collection of similar type of objects and fixed in size.
 Arraylist is collection of homogeneous and heterogeneous elements.
19.What is the Properties class?
 Properties is a subclass of Hashtable. It is used to maintain lists of values in
which the key and the value is String.

20.How to convert a string array to arraylist?


 ArrayList al=new ArrayList( Arrays.asList( new String[]{"java", "collection"} ) );
 arrayList.toArray(); from list to array

ArrayList LinkedList

1) ArrayList internally uses a dynamic LinkedList internally uses a doubly linke


array to store the elements. list to store the elements.

2) Manipulation with ArrayList Manipulation with LinkedLis


is slow because it internally uses an array. If is faster than ArrayList because it uses
any element is removed from the array, all doubly linked list, so no bit shifting i
the bits are shifted in memory. required in memory.

3) An ArrayList class can act as a list only LinkedList class can act as a list an
because it implements List only. queue both because it implements Lis
and Deque interfaces.

4) ArrayList is better for storing and LinkedList is better fo


accessing data. manipulating data.

Top 20 Oops Concepts Interview Questions


Posted by: InstanceOfJava Posted date: Mar 30, 2015 / comment : 3

1.What are the oops concepts in java?


 Oop is an approach that provides a way of modularizing a program by creating
partitioned memory area for both data and methods that can be used as
template for creating copies of such modules on demand.
 The four oops concepts are
 Encapsulation
 Polymorphism
 Inheritance
 Abstraction

2. What is encapsulation?
 The process of binding the data with related methods known as encapsulation.
 Class is the base for encapsulation.
 Check here for more points on Encapsulation

3.What is class ?

 A class is a specification or blue print or template of an object.


 Class is a logical construct , an object has physical reality.
 Class is a structure.
 Class is a user defined data type in java
 Class will acts as base for encapsulation.
 Class contains variables and methods.

1. package com.instanceofjava;

2.

3. class Demo{

4.

5. int a,b;

6. void show(){

7. }

8.

9. }

4. What is an object?

 Object is instance of class.


 Object is dynamic memory allocation of class.
 Object is an encapsulated form of all non static variables and non static methods
of a particular class.
 The process of creating objects out of class is known as instantiation.

1. package com.instanceofjava;

2.

3. class Test{

4.

5. int a,b;
6. void print(){

7. System.out.println("a="+a);

8. System.out.println("b="+b);

9. }

10.

11. public static void main(String [] args){

12.

13. Test obj= new Test();

14. obj.a=10;

15. obj.b=20;

16. obj.print();

17. }

18. }

Output:

1. a=10

2. b=20

5. What are the Object Characteristics?


 The three key characteristics of Object are
 State
 Behavior
 Identity

State:
 Instance variables value is called object state.
 An object state will be changed if instance variables value is changed.

Behavior:
 Behavior of an object is defined by instance methods.
 Behavior of an object is depends on the messages passed to it.
 So an object behavior depends on the instance methods.

Identity:
 Identity is the hashcode of an object, it is a 32 bit integer number created
randomly and assigned to an object by default by JVM.
 Developer can also generate hashcode of an object based on the state of that
object by overriding hashcode() method of java.lang.Object class.
 Then if state is changed , automatically hashcode will be changed.

6.What is Inheritance?
 As the name suggests , inheritance means to take something that already made.
 One of the most important feature of Object oriented Programming. It is the
concept that is used for re usability purpose.
 Getting the properties from one class object to another class object.

7. How inheritance implemented in java?


 Inheritance can be implemented in JAVA using below two keywords.
1.extends
2.implements
 extends is used for developing inheritance between two classes or two
interfaces, and implements keyword is used to develop inheritance between
interface and class.

1. package com.instanceofjava;

2. class A{

3.

4. }

1. package com.instanceofjava;
2. class B extends A{

3.

4. }

8. What are the types of inheritances?


 There are two types of inheritance
1.Multilevel Inheritance
2.Multiple Inheritance

Multilevel Inheritance:
 Getting the properties from one class object to another class object level wise
with some priority is known as multilevel inheritance.

1. package com.instanceofjava;

2.

3. class A{

4.

5. }

6.

7. class B extends A{

8.

9. }

10.

11. class C extends B{

12.

13. }
Multiple Inheritance:
 The concept of getting multiple class objects to single class object is known as
multiple inheritance. multiple inheritance is not supported by java
 Check here for Why java does not supports multiple inheritance

9. What is polymorphism?
 Defining multiple methods with same name,
Static polymorphism:
 Defining multiple methods with same name with different parameters.
 Is also known as method overloading.

1. package com.instanceofjava;

2. class Demo{

3.

4. void add(){

5. }

6.

7. void add(int a, int b){

8. }

9.

10. void add(float a, float b){

11.

12. }

13. public static void main(String [] args){

14. Demo obj= new Demo();


15.

16. obj.add();

17. obj.add(1,2);

18. obj.add(1.2f,1.4f);

19.

20. }

21.

22. }

Dynamic Polymorphism:

 Defining multiple methods with same signature in super class and sub class.
 The sub most object method will be executed always.
 what is the difference between method overloading and method overriding?

10. Similarities and differences between this and super keywords?


this:

 This is a keyword used to store current object reference.


 It must be used explicitly if non -static variable and local variables name is same.
 System.out.print(this); works fine
super:

 Super is a keyword used to store super class non -static members reference in
sub class object.
 used to separate super class and sub class members if both have same name.
 System.out.println(super); compilation Error
 Check here for more differences between this and super
Top 10 Interview Programs and questions on
method overriding in java
Posted by: InstanceOfJava Posted date: Feb 17, 2016 / comment : 2
1.What is method overriding in java?

 Defining multiple methods with same name and same signature in super class
and sub class known as method overriding.
 Method overriding is type of polymorphism in java which is one of the main
object oriented feature.
 Redefined the super class method in sub class is known as method overriding.
 method overriding allows sub class to provide specific implementation that is
already defined in super class.
 Sub class functionality replaces the super class method functionality
(implementation).
2. Can we override private methods in java?
 No. Its not possible to override private methods because private methods in
super class will not be inherited to sub class.
 ReadCan a private method in super class be overridden in Sub class?

3. Can we override static methods of super class in sub class?

 NO.Its not possible to override static methods because static means class level
so static methods not involve in inheritance.
 Can we override static methods in java

4. Can we change the return type of overridden method in sub class?

 No. Return type must be same in super class and sub class.

1. package MethodOverridingExamplePrograms;

2. public class Super{

3.

4. void add(){
5. System.out.println("Super class add method");

6. }

7.

8. }

1. package MethodOverridingInterviewPrograms;

2. public class Sub extends Super{

3.

4. int add(){ //Compiler Error: The return type is incompatible with Super.add()

5.

6. System.out.println("Sub class add method");

7. return 0;

8.

9. }

10.

11. }

5.Can we change accessibility modifier in sub class overridden method?

 Yes we can change accessibility modifier in sub class overridden method but
should increase the accessibility if we decrease compiler will throw an error
message.

Super class method Subclass method

protected protected, public


Super class method Subclass method

public public

default default , public

6.What happens if we try to decrease accessibility from super class to sub


class?

 Compile time error will come.

1. package MethodOverridingExamplePrograms;

2. public class Super{

3.

4. public void add(){

5. System.out.println("Super class add method");

6. }

7.

8. }

1. package MethodOverridingInterviewPrograms;

2. public class Sub extends Super{

3.

4. void add(){ //Compiler Error: Cannot reduce the visibility of the inherited method
5. from Super

6.

7. System.out.println("Sub class add method");

8.

9. }

10.
11. }

7.Can we override a super class method without throws clause to with throws
clause in the sub class?

 Yes if super class method throws unchecked exceptions.


 No need if super class method throws checked exceptions. But it is
recommended to add in sub class method in order to maintain exception
messages.

8.What are the rules we need to follow in overriding if super class method
throws exception ?

 Exception handling in method overriding

9.What happens if we not follow these rules if super class method throws
some exception.

 Compile time error will come.


1. package MethodOverridingExamplePrograms;

2. public class Super{

3.

4. public void add(){

5. System.out.println("Super class add method");

6. }

7.

8. }

1. package MethodOverridingInterviewPrograms;

2. public class Sub extends Super{

3.

4. void add() throws Exception{ //Compiler Error: Exception Exception is not


compatible with
5. throws clause in Super.add()
6.

7. System.out.println("Sub class add method");

8.

9. }

10.

11. }

1. package MethodOverridingExamplePrograms;

2. public class Super{

3.
4. public void add(){

5. System.out.println("Super class add method");

6. }

7.

8. }

1. package MethodOverridingInterviewPrograms;

2. public class Sub extends Super{

3.

4. void add() throws NullPointerException{ // this method throws unchecked


exception so no

5. isuues
6.

7. System.out.println("Sub class add method");

8.

9. }

10.

11. }

10.Can we change an exception of a method with throws clause from


unchecked to checked while overriding it?

 No. As mentioned above already


 If super class method throws exceptions in sub class if you want to mention
throws then use same class or its sub class exception.
 So we can not change from unchecked to checked
Super keyword interview questions java
Posted by: InstanceOfJava Posted date: Mar 2, 2016 / comment : 0

Super Keyword:

 The functionality of super keyword is only to point the immediate super class
object of the current object.
 super keyword is applicable only in the non static methods and super keyword
not applicable in the static methods.
 super keyword used to access the members of the super class object.
 super.member;
 It is used to store super class non static members memory reference through
current sub class object for separating super class members from subclass
members.
 We can call super class constructor in sub class using super() call.
 We can access super class methods and variables in sub class using
super.variable_name, super.method();

Uses of super :

1. By using super keyword we can access super class variables in sub class.

 Using super keyword we can access super class variables from sub class.
 super.variable_name.

1. package com.superkeywordinjava;

2. public Class SuperDemo{

3.

4. int a,b;

5.

6. }

1. package com.superkeywordinjava;
2. public Class Subdemo extends SuperDemo{

3. int a,b;

4. void disply(){

5.

6. System.out.println(a);

7. System.out.println(b);

8. super.a=10;

9. super.b=20;

10.

11. System.out.println(super.a);

12. System.out.println(super.b);

13.

14. }

15.

16. public static void main (String args[]) {

17. Subdemo obj= new Subdemo();

18.

19. obj.a=1;

20. obj.b=2;

21.

22. obj.disply();

23.

24.

25.

26. }
27. }

Output:

1. 1

2. 2

3. 10

4. 20

2. By using super keyword we can access super class methods in sub class.

 Using super keyword we can call super class methods from sub class.
 super.method();.

1. package com.instanceofjavaforus;

2. public Class SuperDemo{

3. int a,b;

4.

5. public void show() {

6.

7. System.out.println(a);

8. System.out.println(b);

9.

10. }

11. }

1. package com.instanceofjavaforus;
2. public Class Subdemo extends SuperDemo{

3. int a,b;

4. void disply(){

5.

6. System.out.println(a);

7. System.out.println(b);

8.

9. super.a=10;

10. super.b=20;

11.

12. super.show();

13.

14. }

15.

16. public static void main (String args[]) {

17.

18. Subdemo obj= new Subdemo();

19.

20. obj.a=1;

21. obj.b=2;

22.

23. obj.disply();

24.

25.

26. }
27. }

Output:

1. 1

2. 2

3. 10

4. 20

3. We can call super class constructor from class constructor:

 By using super keyword we can able to call super class constructor from sub
class constructor.
 Using super();
 For the super(); call must be first statement in sub class constructor.

1. package com.superinterviewprograms;

2. public Class SuperDemo{

3.

4. int a,b;

5.

6. SuperDemo(int x, int y){

7. a=x;

8. b=y

9. System.out.println("Super class constructor called ");

10. }

11.

12.

13. }
1. package com.superinterviewprograms;

2.

3. public Class Subdemo extends SuperDemo{

4.

5. int a,b;

6.

7. SubDemo(int x, int y){

8. super(10,20);

9. a=x;

10. b=y

11. System.out.println("Sub class constructor called ");

12. }

13.

14. public static void main (String args[]) {

15. Subdemo obj= new Subdemo(1,2);

16.

17.

18. }

19. }

Output:

1. Super class constructor called

2. Sub class constructor called


key points:

 Super(); call must be first statement inside constructor.


 By default in every class constructor JVM adds super(); call in side the
constructor as first statement which calls default constructor of super class, if
we are not not calling it.
 If we want to call explicitly we can call at that time default call wont be there.

4.What will happen if we are calling super() in constructor but our class does
not extending any class?

 if our class not extending any class Yes still we can use super(); call in our class
 Because in java every class will extend Object class by default this will be added
by JVM.
 But make sure we are using only super(); default call we can not place
parameterized super call because Object class does not have any
parameterized constructor.

1. package com.superinterviewprograms;

2.

3. public Class Sample{

4.

5. Sample(){

6. super();

7. System.out.println("Sample class constructor called ");

8.

9. }

10.

11. public static void main (String args[]) {

12.

13. Sample obj= new Sample();


14.

15. }

16. }

Output:

1. Sample class constructor called

5.What if there is a chain of extended classes and 'super' keyword is used

1. package com.superinterviewprograms;

2. public Class A{

3.

4. A(){

5. System.out.println("A class constructor called ");

6. }

7.

8.

9. }

1. package com.superinterviewprograms;

2. public Class B extends A{

3.

4. B(){

5.
6. System.out.println("B class constructor called ");

7.

8. }

9.

10.

11. }

1. package com.superinterviewprograms;

2. public Class C extends B{

3.

4. C(){

5. System.out.println("C class constructor called ");

6. }

7.

8.

9. public static void main (String args[]) {

10. C obj= new C();

11.

12.

13. }

14.

15. }

Output:
1. A class constructor called

2. B class constructor called

3. C class constructor called

6. Can we call super class methods from static methods of sub class?

 No we can not use super in static methods of sub class Because super belongs to
object level so we can not use super in static methods.
 If we try to use in sub class static methods compile time error will come.
Top 10 Java interview questions on final
keyword
Posted by: InstanceOfJava Posted date: Mar 3, 2016 / comment : 0
1. What is the use of final keyword in java?

 By using final keyword we can make


 Final class
 Final method
 Final variables
 If we declare any class as final we can not extend that class
 If we declare any method as final it can not be overridden in sub class
 If we declare any variable as final its value unchangeable once assigned.

2. What is the main difference between abstract method and final method?

 Abstract methods must be overridden in sub class where as final methods can
not be overridden in sub class
3. What is the actual use of final class in java?

 If a class needs some security and it should not participate in inheritance in this
scenario we need to use final class.
 We can not extend final class.
4. What will happen if we try to extend final class in java?

 Compile time error will come.

1. package com.finalkeywordintweviewprograms;

2. public final Class SuperDemo{

3. int a,b;

4.

5. public void show() {

6.
7. System.out.println(a);

8. System.out.println(b);

9.

10. }

11. }

1. package com.finalkeywordintweviewprograms;

2. public Class Sample extends SuperDemo{ //The type Sample cannot subclass
the final class
3. SuperDemo
4.

5. }

5.Can we declare interface as final?

 No We can not declare interface as final because interface should be


implemented by some class so its not possible to declare interface as final.
6. Is it possible to declare final variables without initialization?

 No. Its not possible to declare a final variable without initial value assigned.
 While declaring itself we need to initialize some value and that value can not be
change at any time.

1. package com.finalkeywordintweviewprograms;

2. public final Class Sample{

3.

4. final int x=12,y=13;

5.

6. public void Method() {

7.

8. x=25;// compile time error:The final field Super.x cannot be assigned

9. y=33;// compile time error: The final field Super.y cannot be assigned

10.

11. }
12.

13. }

7. Can we declare constructor as final?

 No . Constructors can not be final.

8.What will happen if we try to override final methods in sub classes?

 Compile time error will come :Cannot override the final method from Super class
9.Can we create object for final class?

 Yes we can create object for final class.


10.What is the most common predefined final class object you used in your
code?

 String (for example)


Abstract Class and Interfaces


Posted by: InstanceOfJava Posted date: Oct 8, 2014 / comment : 0
Abstract Class:

 Abstract class means hiding the implementation and showing the function
definition to the user is known as Abstract class
 Abstract classes having Abstract methods and normal methods (non abstract
methods) will be there.
 Abstract classes having methods will be anything means
public ,private,protected.
In Abstract classes variables will be anything( public, private, protected)
For Abstract classes we not able to create object directly.But Indirectily we can
create object using sub calss object.
 A Java abstract class should be extended using keyword “extends”.
 A Java abstract class can have instance methods that implements a default
behavior.
If you know requirement and partially implementation you can go for Abstract
classes.
abstract class can extend from a class or from an abstract class.
 Abstract class can extend only one class or one abstract class at a time.
soAbstract classes can't support multiple inheritance.
 In comparison with java Interfaces, java Abstract classes are fast.
If you add new method to abstract class, you can provide default
implementation of it. So you don’t need to change your current code.
 Abstract classes can have constructors .
We can run an abstract class if it has main() method.
Example Program:
abstract class A{

abstract void display();


public void show(){
S.o.p("Indhu");
}

Public class B extends A{


void display();
}
Abstract class C Extends B{
//Escaping Here
}
public static void main(String args()){
A a= new B();
a.display();
a.show();

Interface :
 Interface nothing but some set of rules.
 Interfaces having only Abstract methods.it is purely Achive Abstraction.
 In Interfaces by default the methods will be public abstract methods.
 In Interfaces by default the variables will be static final .
 For Interfaces we can't create object directly or Indirectly but we can give sub
class object reference to interface .
 Java interface should be implemented using keyword “implements”.
 methods of a Java interface are implicitly abstract and cannot have
implementations.
 If u don't know Any requirement and any implementation you can go for
Interfaces.
 Interface can extend only from an interface
 Interface can extend any number of interfaces at a time. so interfaces can
support multiple inheritance(syntactical not implementation of multiple
inheritance).
 In comparison with java abstract classes, java interfaces are slow as it requires
extra indirection.
 if you add new method to interface, you have to change the classes which are
implementing that interface
 Interface having no constructor.
we can’t run an interface because they can’t have main method
implementation.
Example Program:

public interface Payment


{
void makePayment();//by default it is a abstract method
}
public class PayPal implements Payment
{
public void makePayment()
{
//some logic for paypal payment
//like paypal uses username and password for payment
}
}
public class CreditCard implements Payment
{
public void makePayment()
{
//some logic for CreditCard payment
//like CreditCard uses card number, date of expiry etc...
}

Instance variables in java with example


program
Posted by: InstanceOfJava Posted date: Jan 30, 2018 / comment : 0
 Variables declared inside a class and outside method without static keyword
known as instance variables.
 Instance variables will be used by objects to store state of the object.
 Every object will have their own copy of instance variables. where as static
variables will be single and shared(accessed) among objects.
 Instance variables will be associated with the instance(Object)
 Static variables will be associated with the class.

#1: Java example program on declaring and accessing instance variables.

1. package com.instanceofjava.instancevariables;

2.

3. /**

4. * @author www.Instanceofjava.com

5. * @category interview questions

6. *

7. * Description: Instance variables in java with example program

8. *

9. */

10. public class InstanceVariables {

11.
12. String websiteName;
13. String category;
14.
15. public static void main(String[] args) {
16.
17. InstanceVariables obj = new InstanceVariables();
18. obj.websiteName="www.InstanceOfJava.com";
19. obj.category="Java tutorial/interview questions";
20.
21.
22. }
23.

24. }

25.
 Instance variables allows all four type of access specifiers in java

 Instance variables can be final and transient


 Instance variables can not be declared as abstract, static strictfp, synchronized
and native

Benefits of arraylist in java over arrays


Posted by: InstanceOfJava Posted date: May 7, 2017 / comment : 0

Disadvantages of arrays:

 Check the disadvantages of arrays in below article.


 Advantages and disadvantages of arrays in java

Advantages / Benefits of arraylist in java:

 We have some disadvantages of arrays like arrays are fixed in length. and we
need to mention size of the array while creation itself.
 So we have some advantages of arraylist when compared to arrays in java.
 Here the major advantages of arraylist over arrays.

1.ArrayList is variable length

 One of the major benefit of arraylist is it is dynamic in size. we can increase as


well as decrease size of the arraylist dynamically.
 Resizable.
Program #1: Java example program to explain the advantages of ArrayList:
resizable

1. package collections;
2.
3. import java.util.ArrayList;
4.
5. public class ArrayListExample {
6. /**
7. * Advantages of arrayList over arrays in java
8. * @author www.instanceofjava.com
9. */
10. public static void main(String[] args) {
11.
12. ArrayList<Integer> list = new ArrayList<Integer>();
13.
14. list.add(1);
15.
16. list.add(2);
17.
18. list.add(3);
19.
20. System.out.println(list.size());
21. list.add(4);
22. list.add(5);
23.
24. System.out.println(list.size());
25. list.remove(1);
26.
27. System.out.println(list.size());
28. }
29. }

Output:

1. 3
2. 5
3. 4
 In the above program by using add and remove methods of ArrayList we can
change the size of the ArrayList
2.Default initial capacity is 10.

 One of the major benefit of arraylist is by default it will assign default size as 10.
 Whenever we create object of ArrayList constructor of ArrayList assign default
capacity as 10.

3.Insert and remove elements also at particular position of ArrayList

 Another advantage of ArrayList is it can add and remove elements at particular


position.

Program #2: Java example program to explain the advantages of


ArrayList:Add and remove elements at particular position.

1. package collections;
2.
3. import java.util.ArrayList;
4.
5. public class ArrayListExample {
6. /**
7. * Advantages of arrayList over arrays in java
8. * @author www.instanceofjava.com
9. */
10. public static void main(String[] args) {
11.
12. ArrayList<Integer> list = new ArrayList<Integer>();
13.
14. list.add(1);
15.
16. list.add(2);
17.
18. list.add(3);
19.
20. System.out.println(list);
21.
22. list.add(0,4);
23.
24. System.out.println(list);
25.
26. list.add(2,5);
27.
28.
29. System.out.println(list);
30. list.remove(3);
31.
32. System.out.println(list);
33. System.out.println(list.size());
34. }
35. }
Output:

1. [1, 2, 3]
2. [4, 1, 2, 3]
3. [4, 1, 5, 2, 3]
4. [4, 1, 5, 3]
5. 4

4.Add any type of data into ArrayList.

 We can add different type of objects in to the ArrayList.


 In this scenario avoid mentioning generics while declaring ArrayList.

Program #3: Java example program to explain the advantages of ArrayList:


Add any type of Object.

5.Traverse in both directions.


 We can traverse both direction using List Iterator.

Program #4: Java example program to explain the advantages of ArrayList:


Traverse in both directions.
1. package collections;
2.
3. import java.util.ArrayList;
4. import java.util.ListIterator;
5.
6. public class ArrayListExample {
7. /**
8. * Advantages of arrayList over arrays in java
9. * @author www.instanceofjava.com
10. */
11. public static void main(String[] args) {
12.
13. ArrayList<String> list = new ArrayList<String>();
14.
15. list.add("ArrayList Advantages");
16.
17. list.add("ArrayList benefits");
18.
19. list.add("ArrayList in java");
20.
21. ListIterator iterator = list.listIterator();
22.
23. System.out.println("**ArrayList Elements in forward direction**");
24.
25. while (iterator.hasNext())
26. {
27. System.out.println(iterator.next());
28. }
29.
30. System.out.println("**ArrayList Elements in backward direction**");
31.
32. while (iterator.hasPrevious())
33. {
34. System.out.println(iterator.previous());
35. }
36. }
37. }
Output:

1. **ArrayList Elements in forward direction**


2. ArrayList Advantages
3. ArrayList benefits
4. ArrayList in java
5. **ArrayList Elements in backward direction**
6. ArrayList in java
7. ArrayList benefits
8. ArrayList Advantages
6.ArrayList allows Multiple null values

 We can add multiple null elements to ArrayList

Program #5: Java example program to explain the benefits of ArrayList: Add
null elements
1. package collections;
2.
3. import java.util.ArrayList;
4.
5. public class ArrayListExample {
6. /**
7. * Advantages of arrayList over arrays in java
8. * @author www.instanceofjava.com
9. */
10. public static void main(String[] args) {
11.
12. ArrayList<String> arraylist = new ArrayList<String>();
13.
14. arraylist.add(null);
15.
16. arraylist.add(null);
17.
18. arraylist.add(null);
19.
20. System.out.println(arraylist);
21. }
22. }

Output:

1. [null, null, null]

7.ArrayList allows to add duplicate elements

 We can add duplicate elements into arrayList


Program #6: Java example program to explain the advantages of ArrayList:
Add any type of Object.
1. package collections;
2.
3. import java.util.ArrayList;
4.
5. public class ArrayListExample {
6. /**
7. * Advantages of arrayList over arrays in java
8. * @author www.instanceofjava.com
9. */
10. public static void main(String[] args) {
11.
12. ArrayList<String> arraylist = new ArrayList<String>();
13.
14. arraylist.add("ArrayList");
15.
16. arraylist.add("ArrayList");
17.
18. arraylist.add("ArrayList");
19.
20. System.out.println(arraylist);
21. }
22. }

Output:

1. [ArrayList, ArrayList, ArrayList]

8.ArrayList has many methods to manipulate stored objects.

 ArrayList has many methods to manipulate stored objects.


 addAll(), isEmpty(). lastIndexOf() etc.

Can we create private constructor in java


Posted by: InstanceOfJava Posted date: Feb 25, 2016 / comment : 0
1.Can a constructor in Java be private?

 Yes we can declare private constructor in java.


 If we declare constructor as private we can not able to create object of the class.
 In singleton design pattern we use this private constructor.
2.In what scenarios we will use private constructor in java.

 Singleton Design pattern


 It wont allow class to be sub classed.
 It wont allow to create object outside the class.
 If All Constant methods is there in our class we can use private constructor.
 If all methods are static then we can use private constructor.

3.What will happen if we extends a class which is having private constructor.

 If we try to extend a class which is having private constructor compile time error
will come.
 Implicit super constructor is not visible for default constructor. Must define an
explicit constructor
Singleton Design pattern:

1. package com.privateConstructorSingleTon;
2.
3. public class SingletonClass {
4.
5. private static SingletonClass object;
6.
7. private SingletonClass ()
8. {
9. System.out.println("Singleton(): Private constructor invoked");
10. }
11.
12. public static SingletonClass getInstance()
13. {
14.
15. if (object == null)
16. {
17.
18. System.out.println("getInstance(): First time getInstance was called and
object created !");
19. object = new SingletonClass ();
20.
21. }
22.
23. return object;
24.
25. }
26.
27. }

1. package instanceofjava;
2.
3. public class SingletonObjectDemo {
4.
5. public static void main(String args[]) {
6.
7. SingletonClass s1= SingletonClass .getInstance();
8. SingletonClass s2= SingletonClass .getInstance();
9. System.out.println(s1.hashCode());
10. System.out.println(s2.hashCode());
11.
12. }
13. }

Output:

1. getInstance(): First time getInstance was called and object created !


2. Singleton(): Private constructor invoked
3. 655022016
4. 655022016

You might also like