Java Interview
Java Interview
html
Static Keyword :
1. package com.instanceofjavastatic;
2. class StaticDemo{
3.
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.
7.
10. }
11. }
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
1. static{
2.
3. }
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{
4.
5. }
6. }
Yes we can call super class static methods from sub class.
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 :
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;
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;
3. //
6. }
1. package Abstraction;
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?
1. package Abstraction;
3.
5.
8. }
9.
11.
14.
15. }
16. }
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;
3.
5.
8. }
9. }
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;
3.
4. final abstract void add(); // ERROR: illegal combination of modifiers
5.
8. }
9. }
1. package Abstraction;
3.
5.
8. }
9. }
1. package Abstraction;
3.
5.
8. }
9. }
1. package Abstraction;
3.
5.
8. }
9. }
1. package Abstraction;
3.
5.
8. }
9. }
12.What are the valid and invalid keywords or modifier with abstract class?
1. package Abstraction;
3.
5.
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;
3.
5.
6.
7. }
1. package Abstraction;
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;
3.
6.
7. }
1. package Abstraction;
3.
4.
5. }
1. package Abstraction;
3.
4. //Compiler Error: The type Sub must implement the inherited abstract method
Super.add()
5. }
This Keyword:
1.this must be used to access instance variable if both instance and local variable
names are same.
1. package com.instanceofjava;
2.
4. int a, b;
5.
7.
8. a=a;
9. b=b;
10. }
11.
13.
15.
16. System.out.println(obj.a);
17. System.out.println(obj.b);
18. }
19. }
Output:
1. 0
2. 0
1. package com.instanceofjava;
2.
4. int a, b;
5.
7.
8. this.a=a;
9. this.b=b;
10. }
11.
13.
15.
16. System.out.println(obj.a);
17. System.out.println(obj.b);
18. }
19. }
Output:
1. 1
2. 2
1. package com.instanceofjava;
2.
4. int a, b;
5.
6. ThisDemo(){
8. }
9.
11. this();
12. this.a=a;
13. this.b=b;
14. }
15.
17.
19.
20. System.out.println(obj.a);
21. System.out.println(obj.b);
22. }
23. }
Output:
2. 1
3. 2
Yes we can use this keyword to call current class non static methods .
1. package com.instanceofjava;
2.
4. int a, b;
5.
6.
8.
9. this.a=a;
10. this.b=b;
11. }
12.
14.
16.
17. }
18.
20.
21. this.show();
22. System.out.println(a);
23. System.out.println(b);
24.
25. }
29.
30.
31. obj.print()
32. }
33. }
Output:
2. 1
3. 2
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?
1. public class B{
2.
3. int a;
4.
6. return a;
7. }
8.
10. this.a = a;
11. }
12.
13. B show(){
15. }
16.
18.
20.
21. obj.setA(10);
22.
23. System.out.println(obj.getA());
25. System.out.println(obj2.getA());
26.
27. }
28.
29. }
Output:
1. 10
2. 10
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.
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
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:
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;
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.
9.
11.
12. }
13.
15.
17.
18. }
19.
20.
21. }
1. package com.instanceofjava;
2. interface JavaInterface{
3.
7. }
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. }
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. }
2. interface JavaInterface{
3.
4. void show();
5.
6. }
1. package com.instanceofjava;
3.
4. void show(){
5. // code
6. }
8.
10.
11. }
12. }
9.What will happen if we are not implementing all the methods of an interface
in class which implements an interface?
1. package com.instanceofjava;
2. interface JavaInterface{
3.
4. void show();
5.
}
1. package com.instanceofjava;
6.
7.
8. }
9. }
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 :
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?
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
No. Return type must be same in super class and sub class.
1. package MethodOverridingExamplePrograms;
3.
4. void add(){
6. }
7.
8. }
1. package MethodOverridingInterviewPrograms;
4. int add(){ //Compiler Error: The return type is incompatible with Super.add()
5.
7. return 0;
8.
9. }
10.
11. }
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.
public public
1. package MethodOverridingExamplePrograms;
3.
6. }
7.
8. }
1. package MethodOverridingInterviewPrograms;
3.
4. void add(){ //Compiler Error: Cannot reduce the visibility of the inherited method
5. from Super
6.
8.
9. }
10.
11. }
7.Can we override a super class method without throws clause to with throws
clause in the sub class?
8.What are the rules we need to follow in overriding if super class method
throws exception ?
9.What happens if we not follow these rules if super class method throws
some exception.
1. package MethodOverridingExamplePrograms;
6. }
7.
8. }
1. package MethodOverridingInterviewPrograms;
3.
8.
9. }
10.
11. }
1. package MethodOverridingExamplePrograms;
3.
6. }
7.
8. }
1. package MethodOverridingInterviewPrograms;
3.
5. isuues
6.
8.
9. }
10.
11. }
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.
8.
9. }
10.
1. package com.instanceofjava;
2. class sample{
3.
5.
6.
12. }
1. package com.instanceofjava;
2. class A{
3.
5. System.out.println("saidesh");
6. }
7.
9. System.out.println("ajay");
10. }
11.
13. System.out.println("vinod");
14. }
16.
19. a.show(10);
20. a.show(1,2);
21. a.show(1.2);
22.
23. }
24. }
Output:
1. saidesh
2. ajay
3. vinod
1. class StaticMethodOverloading{
2.
4.
6.
7. }
8.
10.
12.
13. }
14.
16.
18.
19. }
20.
22.
23. StaticMethodOverloading.staticMethod();
24. StaticMethodOverloading.staticMethod(12);
26.
27. }
28. }
Output:
2.
4.
6.
7. }
8.
9. public static void main(int x){
10.
12.
13. }
14.
16.
18.
19. }
20.
22.
23.
25.
26. mainMethodOverloading.main(true);
27. mainMethodOverloading.main(10);
28. mainMethodOverloading.main(37,46);
29.
30.
31. }
32. }
Output:
2. main(boolean x) called
3. main(int x) called
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.
11.
12. this(1,2,3);
13. a=x;
14. b=y;
16.
17. }
18.
21. }
22.
23. public static void main(String[] args){
24.
26. System.out.println(obj.a);
27. System.out.println(obj.b);
28.
29. }
30. }
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
Throwable.
java.lang.Exception
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
Yes we can write multiple catch blocks under single try block.
Multiple catch 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
4. exception
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.
12.What are the differences between final finally and finalize in java
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
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?
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.
1. package MethodOverridingExamplePrograms;
3.
6. }
7.
8. }
1. package MethodOverridingInterviewPrograms;
3.
8.
9. }
10.
11. }
1. package ExceptionHandlingInterviewPrograms;
3.
6. }
7.
8. }
1. package ExceptionHandlingInterviewPrograms;
5. isuues
6.
8.
9. }
10.
11. }
1. package exceptionsFreshersandExperienced;
3.
4. /**
5. * @www.instanceofjava.com
6. **/
8.
9.
10. try {
11.
13.
15. System.out.println(e);
16. }
17.
18. }
19.
20. }
1. try(resource-specification)
2. {
3.
5.
6. }catch(Exception e)
7. {
8.
9. //code
10.
11. }
Top 20 Java Exception handling interview questions and answers for freshers and
experienced
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:
2. Class A{
3.
4. int a;
5.
7.
9.
10. }
11.
12. }
14.
16.
19. }
21.
23. obj.a=10;
24.
25. obj.print();
27.
28. System.out.println("a="obj.a);
29.
30. }
31. }
Output:
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.
7.
9.
10. }
11.
12. }
14.
16.
18.
19. }
21.
24.
25. obj.print();
26. obj.show();
27.
28. System.out.println("a="obj.a);
29.
30. }
31. }
Output:
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.
7.
9.
10. }
11.
12. }
14.
16.
18.
19. }
21.
23. obj.a=10;
24.
25. obj.print();
27.
28. System.out.println("a="obj.a);
29.
30. }
31. }
Output:
2. 10
2. Class A{
3.
4. int a;
5.
7.
9.
10. }
11.
12. }
14.
16.
18.
19. }
21.
23. obj.a=10;
24.
25. obj.print();
28.
29.
30. System.out.println("a="obj.a);
31.
32. }
33. }
Output:
3. 10
Assigning sub class reference to super class object. We can call sub class
methods if overridden
2. Class A{
3.
4. int a;
5.
7.
9.
10. }
11.
12. }
14.
16.
18.
19. }
21.
23.
24. }
25.
27.
29. obj.a=10;
30.
31. obj.print(); // print method is overridden in sub class so it will execute sub class
method.
34.
35.
36. System.out.println("a="obj.a);
37.
38. }
39. }
Output:
3. 10
Collection vs Collections
1. public interface Collection<E>
2. extends Iterable<E>
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.
2. extends AbstractList<E>
1. package com.javasortarraylistofobjects;
2.
3. import java.util.ArrayList;
4. import java.util.Collections;
5. import java.util.Iterator;
6.
8.
10.
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.
29.
31.
32. System.out.println(itr.next());
33.
34. }
35.
36.
37. /*
40. */
41. Collections.sort(arrayList);
42.
44.
45.
46.
48.
50.
51. System.out.println(itr1.next());
52.
53. }
54.
55.
56. }
57. }
Output:
2. 10
3. 7
4. 11
5. 4
6. 9
7. 6
8. 2
9. 8
10. 5
11. 1
13. 1
14. 2
15. 4
16. 5
17. 6
18. 7
19. 8
20. 9
21. 10
22. 11
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;
4. {
5.
6. try
7. {
8. //statements
9. }
10. catch(Exception e)
11. {
12. System.out.println(e);
13. }
15. System.out.println(e);
16. }
17. }
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.
3. }
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:
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:
2. ….//your code
4. ….//your code
6. ….//your code
8. ….//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.
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.
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
1. package com.privateConstructorSingleTon;
2.
4.
6.
7. private SingletonClass ()
8. {
11.
13. {
14.
16. {
17.
20.
21. }
22.
24.
25. }
26.
27. }
1. package instanceofjava;
2.
4.
5. public static void main(String args[]) {
6.
9. System.out.println(s1.hashCode());
10. System.out.println(s2.hashCode());
11.
12. }
13. }
Output:
3. 655022016
4. 655022016
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.
4.
6.
7. private SingletonClass ()
8. {
10. }
11.
13. {
14.
17.
20.
21. }
22.
24.
25. }
26.
27. }
1. package instanceofjava;
2.
4.
6.
9. System.out.println(s1.hashCode());
10. System.out.println(s2.hashCode());
11.
12. }
13. }
Output:
3. 655022016
4. 655022016
1. package com.instanceofjava;
2.
4.
6.
7. private SingletonClass ()
8. {
10. }
11.
14.
16. {
17.
20.
21. }
22.
24.
25. }
26.
27. }
1. package com.instanceofjava;
2.
4.
7. private SingletonClass ()
8. {
10. }
11.
13. {
14.
16. {
17.
20.
21. }
22. else
24.
25. }
26.
28.
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.
4.
6.
7. private SingletonClass ()
8. {
10. }
11.
13. {
14.
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.
1. package com.instanceofjava;
2.
4.
6.
7. private StaticBlockSingleton(){}
8.
10. static{
11.
12. try{
13.
15.
17.
19. }
20. }
21.
24. }
25.
26. }
1. package com.instanceofjava;
2.
4.
5. String name;
6. int rno;
7. String address;
8.
11. }
12.
15. }
16.
19. }
20.
23. }
24.
27. }
28.
31. }
32.
34.
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.
4.
5. //variables of a class
6. String empName;
7. int empId;
8. String Designation;
9.
11. //by using these methods we can set the value to the variable and gat the value
from the
12. //variables
13.
16. }
17.
20. }
21.
24. }
25.
28. }
29.
32. }
33.
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.
4.
5. String Name;
6. int Id;
7. String address;
8.
11. }
12.
15. }
16.
19. }
20.
22. Id = id;
23. }
24.
27. }
28.
31. }
32.
34.
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
ArrayList LinkedList
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.
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 ?
1. package com.instanceofjava;
2.
3. class Demo{
4.
5. int a,b;
6. void show(){
7. }
8.
9. }
4. What is an object?
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.
12.
14. obj.a=10;
15. obj.b=20;
16. obj.print();
17. }
18. }
Output:
1. a=10
2. b=20
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.
1. package com.instanceofjava;
2. class A{
3.
4. }
1. package com.instanceofjava;
2. class B extends A{
3.
4. }
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.
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.
8. }
9.
11.
12. }
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?
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?
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
No. Return type must be same in super class and sub class.
1. package MethodOverridingExamplePrograms;
3.
4. void add(){
5. System.out.println("Super class add method");
6. }
7.
8. }
1. package MethodOverridingInterviewPrograms;
3.
4. int add(){ //Compiler Error: The return type is incompatible with Super.add()
5.
7. return 0;
8.
9. }
10.
11. }
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.
public public
1. package MethodOverridingExamplePrograms;
3.
6. }
7.
8. }
1. package MethodOverridingInterviewPrograms;
3.
4. void add(){ //Compiler Error: Cannot reduce the visibility of the inherited method
5. from Super
6.
8.
9. }
10.
11. }
7.Can we override a super class method without throws clause to with throws
clause in the sub class?
8.What are the rules we need to follow in overriding if super class method
throws exception ?
9.What happens if we not follow these rules if super class method throws
some exception.
3.
6. }
7.
8. }
1. package MethodOverridingInterviewPrograms;
3.
8.
9. }
10.
11. }
1. package MethodOverridingExamplePrograms;
3.
4. public void add(){
6. }
7.
8. }
1. package MethodOverridingInterviewPrograms;
3.
5. isuues
6.
8.
9. }
10.
11. }
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;
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.
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;
3. int a,b;
4.
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.
17.
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
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;
3.
4. int a,b;
5.
7. a=x;
8. b=y
10. }
11.
12.
13. }
1. package com.superinterviewprograms;
2.
4.
5. int a,b;
6.
8. super(10,20);
9. a=x;
10. b=y
12. }
13.
16.
17.
18. }
19. }
Output:
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.
4.
5. Sample(){
6. super();
8.
9. }
10.
12.
15. }
16. }
Output:
1. package com.superinterviewprograms;
2. public Class A{
3.
4. A(){
6. }
7.
8.
9. }
1. package com.superinterviewprograms;
3.
4. B(){
5.
6. System.out.println("B class constructor called ");
7.
8. }
9.
10.
11. }
1. package com.superinterviewprograms;
3.
4. C(){
6. }
7.
8.
11.
12.
13. }
14.
15. }
Output:
1. A 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?
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?
1. package com.finalkeywordintweviewprograms;
3. int a,b;
4.
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. }
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;
3.
5.
7.
9. y=33;// compile time error: The final field Super.y cannot be assigned
10.
11. }
12.
13. }
Compile time error will come :Cannot override the final method from Super class
9.Can we create object for final 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{
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:
1. package com.instanceofjava.instancevariables;
2.
3. /**
4. * @author www.Instanceofjava.com
6. *
8. *
9. */
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
Disadvantages of arrays:
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. 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.
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
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:
Output:
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: