Interface: Abstraction in Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 177

Abstraction In Java & Interface

In the computer science perspective, Abstraction is the process of separating ideas from
their action. (Courtesy : Wiki).

Yes, In the computer science, Abstraction is used to separate ideas from their
implementation. Abstraction in java is used to define only ideas in one class so that
the idea can be implemented by its sub classes according to their requirements. For
example,

?
1
2
3 abstract class Animal
4 {
abstract void soundOfAnimal(); // It is just an idea
5 }
6
7 class Cat extends Animal
8 {
9 void soundOfAnimal()
{
10 System.out.println("Meoh");
11 //Implementation of the idea according to requirements of sub class
12 }
}
13
14 class Dog extends Animal
15 {
16 void soundOfAnimal()
17 {
System.out.println("Bow Bow");
18 //Implementation of the idea according to requirements of sub class
19 }
20 }
21
22
Abstraction in java is implemented using Abstract classes and interfaces.

Today we will discuss only Abstract Classes. In the next concept, we will discuss about
interfaces.

Abstract Classes :

Abstract classes contain abstract methods (you can refer them as ideas) so that they can
be implemented in sub classes according to their requirements. They are also called as
incomplete classes as they have some unimplemented abstract methods(ideas).
Let’s discuss some rules need to follow while using abstract classes and abstract methods.

o Abstract classes and abstract methods are declared using ‘abstract‘ keyword. We
can’t create objects to those classes which are declared as abstract. But, we can
create objects to sub classes of abstract class, provided they must implement
abstract methods.
?
1
2
3 abstract class AbstractClass
4 {
abstract void abstractMethod();
5 }
6
7 class ConcreteClass extends AbstractClass
8 {
void abstractMethod()
9 {
10 System.out.println("Abstract Method Implemented");
11 }
12 }
13
public class Abstraction
14 {
15 public static void main(String[] args)
16 {
//AbstractClass A = new AbstractClass(); Can't create objects to
17 Abstract class
18 ConcreteClass C = new ConcreteClass();
19 //ConcreteClass implements abstract method,
20 //so we can create object to ConcreteClass
AbstractClass A1 = C;
21 //ConcreteClass object is auto-upcasted to AbsractClass
22 }
23 }
24
25
o The methods which are not implemented or which don’t have definitions must be
declared with ‘abstract’ keyword and the class which contains it must be also
declared as abstract.
?
// It gives compile time error
1 class AbstractClass
2 {
3 void abstractMethod(); //This method must be declared as abstract or mu
defined
4 abstract void abstractMethod(); //The Class must be also declared as ab
5 }
6
7 // ***** ***** ***** *****
8 // This is OK
abstract class AbstractClass
9 {
10 abstract void abstractMethod();
}
11
12
13
o It is not compulsory that abstract class must have abstract methods. It may or may
not have abstract methods. But the class which has at least one abstract method
must be declared as abstract.
?
1
2 abstract class AbstractClass
{
3 void methodOne()
4 {
5 //Concrete Method
}
6 //No Abstract methods but class is abstract
7 }
8
o You can’t create objects to abstract class even though it does not contain any
abstract methods.
?
1
2
3 abstract class AbstractClass
4 {
void methodOne()
5 {
6 //Concrete Method
7 }
8
9 void methodTwo()
{
10 //Concrete Method
11 }
12 }
13
public class Abstraction
14 {
15 public static void main(String[] args)
16 {
17 AbstractClass a = new AbstractClass(); //Compile time error
//You can't create objects to AbstractClass
18 //even though it does not contain any abstract methods.
19 }
20 }
21
22
o Abstract Class can be a combination of concrete and abstract methods.
?
abstract class AbstractClass
1 {
2 void methodOne()
3 {
//Concrete Method
4 }
5
6 void methodTwo()
7 {
//Concrete Method
8 }
9
10 abstract void methodThree(); //Abstract Method
11
12 abstract void methodFour(); //Abstract Method
13 }
14
15
16
o Any class extending an abstract class must implement all abstract methods. If it
does not implement, it must be declared as abstract.
?
1
2
3 abstract class AbstractClass
4 {
abstract void abstractMethodOne(); //Abstract Method
5
6 abstract void abstractMethodTwo(); //Abstract Method
7 }
8
9 class ConcreteClass extends AbstractClass
{
10 void abstractMethodOne()
11 {
12 //abstractMethodOne() is implemented
13 }
14
//This class must implement second abstract method also,
15 //otherwise, this class has to be declared as abstract
16
17 void abstractMethodTwo()
18 {
//abstractMethodTwo() is also implemented.
19 //No need to declare this class as abstract
20 }
21 }
22
23
o Inside abstract class, we can keep any number of constructors. If you are not
keeping any constructors, then compiler will keep default constructor.
?
1 abstract class AbstractClass
2 {
3 AbstractClass()
{
4 //First Constructor
5 }
6
7 AbstractClass(int i)
{
8 //Second Constructor
9 }
10
11 abstract void abstractMethodOne(); //Abstract Method
12 }
13
14
o Abstract methods can not be private. Because, abstract methods must be
implemented somehow in the sub classes. If you declare them as private, then you
can’t use them outside the class.
?
1 abstract class AbstractClass
2 {
3 private abstract void abstractMethodOne();
4 //Compile time error, abstract method can not be private.
}
5
o Constructors and fields can not be declared as abstract.
?
1
2 abstract class AbstractClass
{
3 abstract int i;
4 //Compile time error, field can not be abstract
5
6 abstract AbstractClass()
7 {
//Compile time error, constructor can not be abstract
8 }
9 }
10
o Abstract methods can not be static.
?
1 abstract class AbstractClass
2 {
3 static abstract void abstractMethod();
4 //Compile time error, abstract methods can not be static
}
5
That’s it for today. Tomorrow we will discuss about interfaces, another way of
implementing abstraction in java.
Interfaces In Java
pramodbablad May 23, 2014 14

Yesterday we have seen how the abstraction is implemented using abstract classes and
abstract methods. Today we will discuss about interfaces, another way of implementing
abstraction in java.

Interfaces in java are very much similar to abstract classes but interfaces contain only
abstract methods (you can refer to them as only ideas). Abstract classes may contain both
abstract methods as well as concrete methods. But interfaces must contain only abstract
methods. Concrete methods are not allowed in interfaces. Therefore, Interfaces
show 100% abstractness.

Let’s discuss some of the points regarding Interfaces.

o Interfaces are declared with keyword ‘interface‘ and interfaces are implemented
by the class using ‘implements‘ keyword.
?
1
2 interface InterfaceClass
{
3 //Some Abstract methods
4 }
5
6 class AnyClass implements InterfaceClass
7 {
//Use 'implements' while implementing Interfaces
8 //Don't use 'extends'
9 }
10
o Interfaces should contain only abstract methods. Interfaces should not contain a
single concrete method.
?
1
2 interface InterfaceClass
3 {
abstract void abstractMethodOne(); //abstract method
4
5 abstract void abstractMethodTwo(); //abstract method
6
7 void concreteMethod()
8 {
//Compile Time Error.
9 //Concrete Methods are not allowed in interface
10 }
11 }
12
o Interface can have two types of members. 1) Fields 2) Abstract Methods.
?
1 interface InterfaceClass
2 {
int i = 0; //Field
3
4 abstract void abstractMethodOne(); //abstract method
5
6 abstract void abstractMethodTwo(); //abstract method
7 }
8
o By default, Every field of an interface is public, static and final (we will discuss
about final keyword Later). You can’t use any other modifiers other than these
three for a field of an interface.
?
1
2 interface InterfaceClass
{
3 int i = 0;
4 //By default, field is public, static and final
5
6 //Following statements give compile time errors
7
8 private double d = 10;
protected long l = 15;
9
10 //You can't use any other modifiers other than public, static and final
11 }
12
o You can’t change the value of a field once they are initialized. Because they are
static and final. Therefore, sometimes fields are called as Constants. (We will
discuss this feature in detail while covering ‘final’ keyword)
?
1
2 interface InterfaceClass
3 {
4 int i = 0;
}
5
6 class AnyClass implements InterfaceClass
7 {
8 void methodOne()
9 {
//Following statement gives compile time error.
10
11 InterfaceClass.i = 10;
12
13 //final field can not be re-assigned
14 }
}
15
16
o By default, All methods of an interface are public and abstract.
?
1 interface InterfaceClass
2 {
void abstractMethodOne(); //Abstract method
3
4 void abstractMethodTwo(); //Abstract Method
5
6 //No need to use abstract keyword,
7 //by default methods are public and abstract
8 }
9
o Like classes, for every interface .class file will be generated after compilation.
o While implementing any interface methods inside a class, that method must be
declared as public. Because, according to method overriding rule, you can’t reduce
visibility of super class method. By default, every member of an interface is public
and while implementing you should not reduce this visibility.
?
1
2 interface InterfaceClass
3 {
4 void methodOne();
}
5
6 class AnyClass implements InterfaceClass
7 {
8 void methodOne()
{
9 //It gives compile time error.
10 //Interface methods must be implemented as public
11 }
12 }
13
o By default, Interface itself is not public but by default interface itself is abstract
like below,
?
1 abstract interface InterfaceClass
2 {
3 //By default interface is abstract
4 //No need to use abstract keyword
}
5
o SIB – Static Initialization Block and IIB – Instance Initialization Block are not allowed
in interfaces.
?
1 interface InterfaceClassOne
{
2 static
3 {
4 //compile time error
5 //SIB's are not allowed in interfaces
}
6
7 {
8 //Here also compile time error.
9 //IIB's are not allowed in interfaces
}
10
11 void methodOne(); //abstract method
12 }
13
14
15
o As we all know that, any class in java can not extend more than one class. But class
can implement more than one interfaces. This is how multiple inheritance is
implemented in java.
?
1
2
3 interface InterfaceClassOne
4 {
5 void methodOne();
}
6
7 interface InterfaceClassTwo
8 {
9 void methodTwo();
10 }
11
class AnyClass implements InterfaceClassOne, InterfaceClassTwo
12 {
13 public void methodOne()
14 {
//method of first interface is implemented
15 }
16
17 //method of Second interface must also be implemented.
18 //Otherwise, you have to declare this class as abstract.
19
20 public void methodTwo()
{
21 //Now, method of Second interface is also implemented.
22 //No need to declare this class as abstract
23 }
}
24
25
26

Does An Interface Extend Object Class In Java.?


Does an interface extend Object class in java.?
You may have come across this question while reading about interfaces in java. You may
also know that only classes in java are inherited from java.lang.Object class. Interfaces in
java don’t inherit from Object class. They don’t have default parent like classes in
java. But, following two cases may surprise you.

Case 1 :

If an interface does not extend Object class, then why we can call methods of Object class
on interface variable like below.

1
interface A
2
{
3
4
}
5
6
class InterfaceAndObjectClass
7 {
8 public static void main(String[] args)

9 {

10 A a = null;

11
12 a.equals(null);

13
a.hashCode();
14
15
a.toString();
16
}
17
}
18

Case 2 :

If an interface does not extend Object class, then why the methods of Object class are
visible in interface.?
?

1
interface A
2
{
3 @Override
4 public boolean equals(Object obj);

5
6 @Override

7 public int hashCode();

8
9 @Override
public String toString();
10
}
11

Explanation :

This is because, for every public method in Object class, there is an implicit abstract and
public method declared in every interface which does not have direct super interfaces.
This is the standard Java Language Specification which states like this,

“If an interface has no direct superinterfaces, then the interface implicitly declares
a public abstract member method m with signature s, return type r,
and throws clause tcorresponding to each public instance method mwith signature s,
return type r, and throws clause t declared in Object, unless a method with the same
signature, same return type, and a compatible throws clause is explicitly declared by the
interface.”

You can go through the Java language Specification 9.2 about interface members here.

13 Java Interview Questions On Abstract Class


pramodbablad November 11, 2014 3

13 Java Interview Questions On Abstract Class :


1) Abstract class must have only abstract methods. True or false?
False. Abstract methods can also have concrete methods.

2) Is it compulsory for a class which is declared as abstract to have at least one


abstract method?

Not necessarily. Abstract class may or may not have abstract methods.

3) Can we use “abstract” keyword with constructor, Instance Initialization Block and
Static Initialization Block?

No. Constructor, Static Initialization Block, Instance Initialization Block and variables can
not be abstract.

4) Why final and abstract can not be used at a time?

Because, final and abstract are totally opposite in nature. A final class or method can not
be modified further where as abstract class or method must be modified further. “final”
keyword is used to denote that a class or method does not need further improvements.
“abstract” keyword is used to denote that a class or method needs further improvements.

5) Can we instantiate a class which does not have even a single abstract methods but
declared as abstract?

No, We can’t instantiate a class once it is declared as abstract even though it does not
have abstract methods.

6) Can we declare abstract methods as private? Justify your answer?

No. Abstract methods can not be private. If abstract methods are allowed to be private,
then they will not be inherited to sub class and will not get enhanced.

7) We can’t instantiate an abstract class. Then why constructors are allowed in


abstract class?

It is because, we can’t create objects to abstract classes but we can create objects to
their sub classes. From sub class constructor, there will be an implicit call to super class
constructor. That’s why abstract classes should have constructors. Even if you don’t write
constructor for your abstract class, compiler will keep default constructor.

8) Can we declare abstract methods as static?

No, abstract methods can not be static.

9) Can a class contain an abstract class as a member?

Yes, a class can have abstract class as it’s member.

10) Abstract classes can be nested. True or false?

True. Abstract classes can be nested i.e an abstract class can have another abstract class
as it’s member.
11) Can we declare abstract methods as synchronized?

No, abstract methods can not be declared as synchronized. But methods which override
abstract methods can be declared as synchronized.

12) Can we declare local inner class as abstract?

Yes. Local inner class can be abstract.

13) Can abstract method declaration include throws clause?

Yes. Abstract methods can be declared with throws clause.

Java Interview Questions On Interfaces :


1) Can interfaces have constructors, SIB and IIB?

No. Interfaces can’t have constructors, SIB and IIB. They show 100% abstractness.

2) Can we re-assign a value to a field of interfaces?

No. The fields of interfaces are static and final by default. They are just like constants.
You can’t change their value once they got.

3) Can we declare an Interface with “abstract” keyword?

Yes, we can declare an interface with “abstract” keyword. But, there is no need to write
like that. All interfaces in java are abstract by default.

4) For every Interface in java, .class file will be generated after compilation. True or
false?

True. .class file will be generated for every interface after compilation.

5) Can we override an interface method with visibility other than public?

No. While overriding any interface methods, we should use public only. Because, all
interface methods are public by default and you should not reduce the visibility while
overriding them.

6) Can interfaces become local members of the methods?

No. You can’t define interfaces as local members of methods like local inner classes. They
can be a part of top level class or interface.

7) Can an interface extend a class?

No, a class can not become super interface to any interface. Super interface must be an
interface. That means, interfaces don’t extend classes but can extend other interfaces.
8) Like classes, does interfaces also extend Object class by default?

No. Interfaces don’t extend Object class. ( Click here for more )

9) Can interfaces have static methods?

No. Interfaces can’t have static methods.

10) Can an interface have a class or another interface as it’s members?

Yes. Interfaces can have classes or interfaces as their members.

11) What are marker interfaces? What is the use of marker interfaces?

30 Java Practice Coding Questions On Abstract Classes


pramodbablad November 18, 2015 0

1) Below class ABC doesn’t have even a single abstract method, but it has been
declared as abstract. Is it correct?

1
abstract class ABC
2
{
3
void firstMethod()
4 {
5 System.out.println("First Method");

6 }

7
8 void secondMethod()

9 {
System.out.println("Second Method");
10
}
11
}
12
View Answer
Answer :
Yes, it is correct. abstract classes may or may not have abstract methods.

2) Why the below class is showing compilation error?


?

1
abstract class AbstractClass
2 {
3 abstract void abstractMethod()
4 {

5 System.out.println("First Method");

6 }
}
7
View Answer
Answer :
Because, abstract methods must not have a body.

3) Which class is instantiable? Class A or Class B?

1 abstract class A
2 {
3
4 }

5
6 class B extends A

7 {

8
}
9
View Answer
Answer :
Class B.

4) Below code snippet is showing compilation error? Can you suggest the corrections?

1 abstract class A

2 {

3 abstract int add(int a, int b);


4 }

5
6 class B extends A
{
7
8
}
9
View Answer
Answer :
Class B must implement inherited abstract method A.add() or else it must be declared as
abstract.

5) Is the following program written correctly? If yes, what value “result” variable will
hold if you run the program?

1 abstract class Calculate


{
2
abstract int add(int a, int b);
3
}
4
5
public class MainClass
6
{
7 public static void main(String[] args)
8 {
9 int result = new Calculate()

10 {

11 @Override
int add(int a, int b)
12
{
13
return a+b;
14
}
15
}.add(11010, 022011);
16 }
17 }
18
19
View Answer
Answer :
Yes, program is written correctly. result = 20235.

6) Can we write explicit constructors in an abstract class?

View Answer
Answer :
Yes. abstract classes can have any number of constructors.

7) Can you identify the error in the below code?

1 abstract class AbstractClass


2 {

3 private abstract int abstractMethod();

4 }

View Answer
Answer :
abstract methods can’t be private.

8) Can we declare protected methods in an interface?

View Answer
Answer :
No. only public methods are allowed in an interface.

9) What will be the output of the following program?

abstract class A
1
{
2
abstract void firstMethod();
3
4
void secondMethod()
5
{
6 System.out.println("SECOND");
7
8 firstMethod();

9 }
}
10
11
abstract class B extends A
12
{
13
@Override
14
void firstMethod()
15 {
16 System.out.println("FIRST");
17
18 thirdMethod();

19 }

20
21 abstract void thirdMethod();
}
22
23
class C extends B
24
{
25
@Override
26
void thirdMethod()
27 {
28 System.out.println("THIRD");
29 }

30 }

31
32 public class MainClass
{
33
public static void main(String[] args)
34
{
35
36 C c = new C();

37
38 c.firstMethod();

39
c.secondMethod();
40
41
c.thirdMethod();
42
}
43
}
44
45
46
47
View Answer
Answer :
FIRST
THIRD
SECOND
FIRST
THIRD
THIRD

10) What will be the output of the below program?

1 abstract class X
{
2
public X()
3
{
4
System.out.println("ONE");
5
}
6
7 abstract void abstractMethod();
8 }
9
10 class Y extends X

11 {
public Y()
12
{
13
System.out.println("TWO");
14
}
15
16
@Override
17 void abstractMethod()
18 {
19 System.out.println("THREE");

20 }

21 }

22
public class MainClass
23
{
24
public static void main(String[] args)
25
{
26
X x = new Y();
27
28 x.abstractMethod();
29 }
30 }

31
32
33
View Answer
Answer :
ONE
TWO
THREE

11) Can we declare abstract methods as static?


View Answer
Answer :
No. abstract methods can’t be static.

12) Is the below program written correctly? If yes, what will be the output?

?
1
2
3
abstract class A
4 {
5 {
6 System.out.println("AAA");
7 }
}
8
9 abstract class B extends A
10 {
11 {
System.out.println("BBB");
12 }
13 }
14
15 class C extends B
16 {
{
17 System.out.println("CCC");
18 }
19 }
20
public class MainClass
21 {
22 public static void main(String[] args)
23 {
C c = new C();
24 }
25 }
26
27
28
View Answer
Answer :
Yes, program is written correctly. Output will be,
AAA
BBB
CCC

13) What will be the output of the following program?

?
abstract class A
1 {
2 abstract int firstMethod(int i);
3
abstract int secondMethod(int i);
4
5 int thirdMethod(int i)
6 {
7 return secondMethod(++i);
8 }
}
9
10 abstract class B extends A
11 {
12 @Override
int secondMethod(int i)
13 {
14 return firstMethod(++i);
15 }
16 }
17
class C extends B
18 {
19 @Override
20 int firstMethod(int i)
{
21 return ++i;
22 }
23 }
24
25 public
{
class MainClass

26 public static void main(String[] args)


27 {
28 C c = new C();
29
System.out.println(c.thirdMethod(121121));
30 }
31 }
32
33
34
35
36
37
38
39
View Answer
Answer :
121124

14) Can we keep static initialization blocks inside an abstract class?


View Answer
Answer :
Yes. Abstract classes can have static initialization blocks as well as instance initialization
blocks.

15) Is the below program written correctly? If yes, what will be the output?

?
1
2 abstract class XYZ
3 {
{
4 System.out.println(1);
5 }
6
7 public XYZ()
8 {
System.out.println(2);
9
10 abstractMethod();
11 }
12
13 abstract void abstractMethod();
}
14
15 class PQR extends XYZ
16 {
17 {
18 System.out.println(3);
}
19
20 public PQR()
21 {
22 System.out.println(4);
}
23
24 @Override
25 void abstractMethod()
26 {
27 System.out.println(5);
}
28 }
29
30 public class MainClass
31 {
public static void main(String[] args)
32 {
33 PQR pqr = new PQR();
34 }
35 }
36
37
38
39
40
41
View Answer
Answer :
Yes, program is written correctly. Output will be,
1
2
5
3
4

16) Can you identify the error in the below code?

?
1
2 class X
3 {
public X()
4 {
5 System.out.println("Constructor One");
6 }
7
8 abstract X(int i)
{
9 System.out.println("Constructor Two");
10 }
11 }
12
View Answer
Answer :
Constructors can’t be abstract.

17) Abstract methods can be declared as final. True or False?

View Answer
Answer :
False. Abstract methods can’t be final.

18) Is the below code written correctly?

?
class X
1 {
2 abstract class Y
3 {
class Z
4 {
5
6 }
}
7 }
8
9
10
View Answer
Answer :
Yes, code is written correctly.

19) What will be the output of the following program?

?
class ClassOne
1 {
2 int methodOne(int i, int j)
3 {
4 return i++ + ++j - ++i - j++;
}
5 }
6
7 abstract class ClassTwo extends ClassOne
8 {
abstract int methodOne(int i, int j, int k);
9
10 @Override
11 int methodOne(int i, int j)
12 {
13 return methodOne(i, j, i+j);
}
14 }
15
16 class ClassThree extends ClassTwo
17 {
@Override
18 int methodOne(int i, int j, int k)
19 {
20 return --i - j-- + ++k - i++ + ++j - k--;
21 }
}
22
23 public class MainClass
24 {
25 public static void main(String[] args)
{
26 ClassOne one = new ClassOne();
27
28 ClassThree three = new ClassThree();
29
30 System.out.println(three.methodOne(one.methodOne(10101, 20202), one
10101)));
31 }
32 }
33
34
35
36
37
38
39
View Answer
Answer :
0

20) Is the below code written correctly?

?
1
2 class A
{
3 void methodOfA()
4 {
5 abstract class B
6 {
7
}
8 }
9 }
10
View Answer
Answer :
Yes, code is written correctly. Local inner classes can be abstract.

21) Can we declare abstract method with throws clause?

View Answer
Answer :
Yes, abstract methods can be declared with throws clause.

22) What will be the output of the following program?

1 abstract class A
{
2 int i = 111, j = 222;
3
4 abstract void methodOne();
5
6 abstract void methodTwo();
}
7
8 abstract class B extends A
9 {
10 @Override
void methodOne()
11 {
12 System.out.println(i);
13
14 System.out.println(j);
15
16 i = ++i;
17
j = --j;
18 }
19 }
20
21 class C extends B
{
22 @Override
23 void methodTwo()
24 {
25 System.out.println(i);
26
System.out.println(j);
27
28 i = i++;
29
30 j = j--;
31 }
}
32
33 public class MainClass
34 {
35 public static void main(String[] args)
36 {
C c = new C();
37
38 c.methodOne();
39
40 c.methodTwo();
41
42 System.out.println(c.i);
43
System.out.println(c.j);
44 }
45 }
46
47
48
49
50
51
52
53
54
View Answer
Answer :
111
222
112
221
112
221

23) Which of the following shows 100% abstractness?


a) Abstract Classes b) Interfaces

View Answer
Answer :
b) Interfaces

Abstract classes are not 100% abstract because of concrete constructors.

24) Can you identify the error in the below code?

?
1 abstract class A
2 {
3 synchronized abstract void method();
4 }
View Answer
Answer :
Abstract methods can not be declared as synchronized.

25) What will be the output of the following program?

?
1 abstract class X
{
2 int i = 111;
3
4 int methodX()
5 {
6 return methodX(i);
}
7
8 abstract int methodX(int i);
9 }
10
11 class Y extends X
{
12 @Override
13 int methodX(int i)
14 {
15 return ++i + i++;
}
16 }
17
18 public class MainClass
19 {
public static void main(String[] args)
20 {
21 Y y = new Y();
22
23 System.out.println(y.methodX());
24 }
}
25
26
27
28
29
30
View Answer
Answer :
224

26) Is the below code written correctly?

?
1
2 class A
3 {
4 abstract class B
{
5 class C
6 {
7 abstract class D
8 {
abstract void method();
9 }
10 }
11 }
}
12
13
View Answer
Answer :
Yes, code is correct.

27) Write a code which implements abstract method “methodY()” of class Y in the
below code?

?
1 class X
2 {
3 abstract static class Y
{
4 abstract void methodY();
5 }
6 }
7
View Answer
Answer :
?

1
2 class Z extends X.Y
{
3 @Override
4 void methodY()
5 {
System.out.println("methodY implementation");
6 }
7 }
8
28) Can we instantiate a class which has only concrete methods but declared as
abstract?

View Answer
Answer :
No. We can’t instantiate an abstract class even though it has only concrete methods.

29) What will be the output of the following program?

?
1 abstract class ABC
{
2 abstract void methodOne();
3 }
4
5 abstract class XYZ extends ABC
6 {
int i;
7
8 @Override
9 void methodOne()
10 {
methodOne(i *= i);
11 }
12
13 abstract void methodOne(int i);
14 }
15
16 class PQR extends XYZ
{
17 public PQR(int i)
18 {
19 this.i = i;
}
20
21 @Override
22 void methodOne(int i)
23 {
24 System.out.println(i++ * ++i);
}
25 }
26
27 public class MainClass
28 {
public static void main(String[] args)
29 {
30 PQR pqr = new PQR(1);
31
32 pqr.methodOne();
33 }
}
34
35
36
37
38
39
40
41
View Answer
Answer :
3

30) Is the following program written correctly? If yes, what will be the output?

?
abstract class A
1 {
2 {
3 methodA();
}
4
5 abstract void methodA();
6 }
7
8 class B extends A
9 {
@Override
10 void methodA()
11 {
12 System.out.println("methodA");
}
13 }
14
15 public class MainClass
16 { public static void main(String[] args)
17 {
18 new B();
19 } }
20
21
22
23
24
25
View Answer
Answer :
Yes, program is correct. Output will be,
methodA

31) One class has a method with two overloaded forms. One form is abstract and
another one is concrete. Is it possible in java?

View Answer
Answer :
Yes. Overloaded methods can be abstract or concrete.

32) Which line in the below code shows compile time error?

?
1
2 abstract class X
3 {
4 public X()
{
5 methodX();
6 }
7
8 static
{
9 methodX();
10 }
11
12 abstract void methodX();
13 }
14
View Answer
Answer :
Line 10. Because, you can’t make a static reference to non-static method.

33) You know that we can’t create objects to an abstract class. Then, why it is allowed
to have constructors in an abstract class?
View Answer
Answer :
Because, these constructors will be called in constructor chaining.

34) You know that abstract methods can’t be static. Can we declare abstract inner
classes as static?

View Answer
Answer :
Yes, abstract inner classes can be static.

35 Java Practice Coding Questions On Interfaces


pramodbablad December 22, 2015 2

1) For every interface written in a java file, .class file will be generated after
compilation? True or False?

View Answer
Answer :
True. For every interface written in a java file, .class file will be generated after
compilation.

2) Can you identify the error in the below code?

1 interface A
2 {

3 private int i;

4 }

View Answer
Answer :
Illegal modifier for field i. Only public, static and final are allowed.

3) What will be the output of the following program?

interface A
1
{
2
void myMethod();
3
}
4
5 class B

6 {
public void myMethod()
7
{
8
System.out.println("My Method");
9
}
10
}
11
12 class C extends B implements A
13 {
14
15 }

16
17 class MainClass

18 {
public static void main(String[] args)
19
{
20
A a = new C();
21
22
a.myMethod();
23
}
24 }
25
26
27
View Answer
Answer :
My Method

4) Can a class implement more than one interfaces?

View Answer
Answer :
Yes, a class can implement more than one interfaces.

5) Why the below code is showing compile time error?

1
interface X
2
{
3
void methodX();
4 }
5
6 class Y implements X

7 {

8 void methodX()

9 {
System.out.println("Method X");
10
}
11
}
12
View Answer
Answer :
Interface methods must be implemented as public. Because, interface methods are public
by default and you should not reduce the visibility of any methods while overriding.

6) Does below code compile successfully? If not, why?

1 interface A
{
2
int i = 111;
3
}
4
5
class B implements A
6
{
7 void methodB()
8 {
9 i = 222;

10 }
}
11
12
View Answer
Answer :
No, because interface fields are static and final by default and you can’t change their
value once they are initialized. In the above code, methodB() is changing value of
interface field A.i. It shows compile time error.

7) Is the following code written correctly?

1
class A
2 {
3 //Class A
4 }

5
6 interface B extends A

7 {
//Interface B extending Class A
8
}
9
View Answer
Answer :
No. An interface can extend another interface not the class.

8) What will be the output of the following program?

interface P
1
{
2
String p = "PPPP";
3
4
String methodP();
5
}
6
7 interface Q extends P

8 {
String q = "QQQQ";
9
10
String methodQ();
11
}
12
13
class R implements P, Q
14
{
15 public String methodP()
16 {
17 return q+p;

18 }

19
20 public String methodQ()
{
21
return p+q;
22
}
23
}
24
25
public class MainClass
26 {
27 public static void main(String[] args)
28 {

29 R r = new R();

30
31 System.out.println(r.methodP());

32
System.out.println(r.methodQ());
33
}
34
35 }

36
37
38
View Answer
Answer :
QQQQPPPP
PPPPQQQQ

9) Can interfaces have constructors?

View Answer
Answer :
No. Interfaces can’t have constructors.

10) Is the below program written correctly? If yes, what will be the output?

1 class A implements B
2 {

3 public int methodB(int i)

4 {

5 return i =+ i * i;
}
6
}
7
8
interface B
9
{
10
int methodB(int i);
11 }
12
13 public class MainClass

14 {

15 public static void main(String[] args)

16 {
17 B b = new A();

18
19 System.out.println(b.methodB(2));
}
20
}
21
22
View Answer
Answer :
Yes, program is written correctly. Output will be,
4

11) Can you find out the errors in the following code?

1
interface A
2
{
3 {
4 System.out.println("Interface A");
5 }

6
7 static

8 {
System.out.println("Interface A");
9
}
10
}
11
View Answer
Answer :
Interfaces can’t have initializers.

12) How do you access interface field ‘i’ in the below code?

1 class P

2 {
3 interface Q

4 {
int i = 111;
5
}
6
}
7
View Answer
Answer :
P.Q.i

13) Like classes in java, Interfaces also extend java.lang.Object class by default. True
OR False?

View Answer
Answer :
False. Interfaces don’t extend Object class.

14) Does below program compile successfully?

?
1
2 interface ABC
3 {
public void methodOne();
4
5 public void methodTwo();
6 }
7
8 interface PQR extends ABC
{
9 public void methodOne();
10
11 public void methodTwo();
12 }
13
View Answer
Answer :
Yes, program compiles successfully.

15) Can interfaces have static methods?

View Answer
Answer :
Yes, from Java 8, interfaces can have static methods.

16) Is the following program written correctly? If yes, what will be the output?
?
1
2
3
4 interface ABC
5 {
6 void methodOne();
}
7
8 interface PQR extends ABC
9 {
10 void methodTwo();
11 }
12 abstract class XYZ implements PQR
13 {
14 public void methodOne()
15 {
methodTwo();
16 }
17 }
18
19 class MNO extends XYZ
{
20 public void methodTwo()
21 {
22 methodOne();
}
23 }
24
25 public class MainClass
26 {
27 public static void main(String[] args)
{
28 ABC abc = new MNO();
29
30 abc.methodOne();
31 }
32 }
33
34
35
View Answer
Answer :
Yes, program is written is correctly. But, it will throw StackOverflowError at run time.
Because, methodOne() and methodTwo() are cyclicly called.

17) What will be the output of the following program?

?
1 interface X
2 {
char c = 'A';
3
4 char methodX();
5 }
6
7 class Y implements X
8 {
{
9 System.out.println(c);
10 }
11
12 public char methodX()
{
13 char c = this.c;
14
15 return ++c;
16 }
17 }
18
public class MainClass
19 {
20 public static void main(String[] args)
21 {
Y y = new Y();
22
23 System.out.println(y.methodX());
24
25 System.out.println(y.c);
26
27 System.out.println(X.c);
28 }
}
29
30
31
32
33
34
View Answer
Answer :
A
B
A
A

18) Can you identify the error in the below code?

?
1 interface A
2 {
3 void methodA();
}
4
5 class B implements A
6 {
7 public void methodA()
{
8 interface C
9 {
10 int i = 123;
11 }
}
12 }
13
14
15
View Answer
Answer :
Interfaces can’t be local members of a method.

19) Can we declare an interface as ‘abstract’?

View Answer
Answer :
Yes, interfaces can be declared as ‘abstract’. But, there is no need to declare like that
because interfaces are ‘abstract’ by default.

20) What will be the output of the following program?

1 interface One
{
2 String s = "FINAL";
3
4 String methodONE();
5 }
6
interface Two
7 {
8 String methodONE();
9 }
10
11 abstract class Three
{
12 String s = "NOT FINAL";
13
14 public abstract String methodONE();
15 }
16
class Four extends Three implements One, Two
17 {
18 public String methodONE()
19 {
String s = super.s + One.s;
20
21 return s;
22 }
23 }
24
25 public class MainClass
{
26 public static void main(String[] args)
27 {
28 Four four = new Four();
29
System.out.println(four.methodONE());
30
31 One one = four;
32
33 System.out.println(one.s);
34 }
35 }
36
37
38
39
40
41
42
View Answer
Answer :
NOT FINALFINAL
FINAL

21) What will be the output of the below program?

?
1 interface X
{
2 void method();
3 }
4
5 class Y
{
6 public void method()
7 {
8 System.out.println("CLASS Y");
9 }
}
10
11 class Z extends Y implements X
12 {
13
14 }
15
16 public
{
class MainClass

17 public static void main(String[] args)


18 {
19 X x = new Z();
20
x.method();
21 }
22 }
23
24
25
26
27
View Answer
Answer :
CLASS Y

22) Can interfaces have methods other than abstract?

View Answer
Answer :
Yes, from Java 8, interfaces can have static methods and default methods other than
abstract methods.

23) What will be the output of the following program?

?
interface A
1 {
2 int methodA();
3 }
4
5 interface B
{
6 int methodB();
7 }
8
9 interface C
{
10 int methodC();
11 }
12
13 class D implements A, B, C
14 {
int i = 999+111;
15
16 public int methodA()
17 {
i =+ i / i;
18
19 return i;
20 }
21
22 public int methodB()
23 {
i =- i * i;
24
25 return i;
26 }
27
28 public int methodC()
{
29 i = ++i - --i;
30
31 return i;
32 }
33 }
34
public class MainClass
35 {
36 public static void main(String[] args)
37 {
D d = new D();
38
39 System.out.println(d.i);
40
41 System.out.println(d.methodA());
42
43 System.out.println(d.methodB());
44
45 System.out.println(d.methodC());
}
46 }
47
48
49
50
51
52
53
54
55
56
View Answer
Answer :
1110
1
-1
1

24) How do you print the value of field ‘i’ of interface ‘OneTwoThree’ in the below
example and what will be the it’s value?

?
1
2 interface One
3 {
4 int i = 222;
5
interface OneTwo
6 {
7 int i = One.i+One.i;
8
9 interface OneTwoThree
{
10 int i = OneTwo.i + OneTwo.i;
11 }
12 }
13 }
14
View Answer
Answer :
Printing ‘i’ value —> System.out.println(One.OneTwo.OneTwoThree.i)
Value of One.OneTwo.OneTwoThree.i will be 888.

25) All members of interface are public by default. True or false?

View Answer
Answer :
True.

26) What will be the output of the following program?

1 interface A
{
2 String A = "AAA";
3
4 String methodA();
5 }
6
interface B
7 {
8 String B = "BBB";
9
10 String methodB();
}
11
12 class C implements A, B
13 {
14 public String methodA()
{
15 return A+B;
16 }
17
18 public String methodB()
19 {
return B+A;
20 }
21 }
22
23 class D extends C implements A, B
{
24 String D = "DDD";
25
26 public String methodA()
27 {
28 return D+methodB();
}
29 }
30
31 public class MainClass
32 {
public static void main(String[] args)
33 {
34 C c = new C();
35
36 System.out.println(c.methodA());
37
38 System.out.println(c.methodB());
39
c = new D();
40
41 System.out.println(c.methodA());
42
43 System.out.println(c.methodB());
44 }
45 }
46
47
48
49
50
51
52
53
54
View Answer
Answer :
AAABBB
BBBAAA
DDDBBBAAA
BBBAAA

27) Is the below program written correctly? If yes, what will be the output?

?
1 interface X
2 {
3 void methodX();
4
interface Y
5 {
6 void methodY();
7 }
}
8
9 class Z implements X, X.Y
10 {
11 {
12 methodX();
13
System.out.println(1);
14 }
15
16 public void methodX()
17 {
methodY();
18
19 System.out.println(2);
20 }
21
22 public void methodY()
23 {
System.out.println(3);
24 }
25 }
26
27
28 public class MainClass
{
29 public static void main(String[] args)
30 {
31 Z z = new Z();
32
33 z.methodX();
34
35 z.methodY();
36
X x = z;
37
38 x.methodX();
39 }
40 }
41
42
43
44
45
46
47
View Answer
Answer :
Yes, program is correct. Output will be,
3
2
1
3
2
3
3
2

28) Can you identify the error in the below code?

?
1
2 class
{
A implements A.B

3 static interface B
4 {
5 void methodB();
}
6 }
7
View Answer
Answer :
Cycle detected. Any class can not extend itself or it’s member types.

29) Interfaces are abstract and public by default. True or False?

View Answer
Answer :
False. Interfaces are abstract by default but not public.

30) Can you identify the error in the below code?


?
1
2
interface X
3 {
4 void methodX();
5 }
6
interface Y extends X
7 {
8 void methodY();
9 }
10
11 class Z implements Y
{
12 public void methodY()
13 {
14 System.out.println("Method Y");
}
15 }
16
17
View Answer
Answer :
Class Z must implement methodX() also.

31) Can we define interfaces as generic?

View Answer
Answer :
Yes, we can define generic interfaces.

32) What will be the output of the following program?

?
abstract class A
1 {
2 abstract void myMethod(Number N);
3 }
4
interface B
5 {
6 abstract void myMethod(Object O);
7 }
8
9 class C extends A implements B
{
10 void myMethod(Number N)
11 {
12 System.out.println("Number");
}
13
14 public void myMethod(Object O)
15 {
System.out.println("Object");
16 }
17 }
18
19 public class MainClass
20 { public static void main(String[] args)
21 {
22 A a = new C();
23
24 a.myMethod(new Integer(121));
25
B b = new C();
26
27 b.myMethod(new Integer(121));
28
29 C c = new C();
30
31 c.myMethod(new Integer(121));
32 }
}
33
34
35
36
37
38
39
40
View Answer
Answer :
Number
Object
Number

33) Is the below program written correctly? If yes, what will be the output?

?
1 interface I
2 {
class C
3 {
4 int i;
5
6 public C(int i)
{
7 this.i = ++i;
8 }
9
10 int methodC()
11 {
return ++i;
12 }
13 }
14 }
15
16 public
{
class MainClass
17 public static void main(String[] args)
18 {
19 I.C c = new I.C(000);
20
System.out.println(c.methodC());
21 }
22 }
23
24
25
26
27
View Answer
Answer :
Yes, program is written correctly. Output will be,
2

34) What will be the output of the following program?

1 class A { }
2
class B extends A { }
3
4 class C extends B { }
5
6 interface ABC
7 {
void method(A a);
8 }
9
10 interface PQR
11 {
12 void method(B b);
}
13
14 class M implements ABC, PQR
15 {
16 public void method(A a)
{
17 System.out.println(2);
18 }
19
20 public void method(B b)
{
21 System.out.println(3);
22 }
23 }
24
25 public
{
class MainClass
26 public static void main(String[] args)
27 {
28 M m = new M();
29
m.method(new A());
30
31 m.method(new B());
32
33 m.method(new C());
34 }
35 }
36
37
38
39
40
41
42
View Answer
Answer :
2
3
3

35) Can you identify the errors in the below code?

?
1
2 interface I
3 {
class C implements I
4 {
5 public void methodI(int i)
6 {
7 System.out.println(i);
}
8 }
9
10 void methodI(int i);
11 }
12
View Answer
Answer :
No errors.

Nested Classes In Java


pramodbablad May 27, 2014 4

Nested classes in java can be defined as classes within the class. i.e A class can be a
member of another class. For example,

1
class OuterClass
2
{
3
int i; //Field as a member
4
5 void methodOne()
6 {
7 //method as a member

8 }

9
10 class NestedClass
{
11
//class as a member
12
}
13
}
14

There are 2 types of Nested Classes.

1. Static Nested Classes


2. Non-Static Nested Classes or Inner Classes

Today, we will discuss about Static Nested Classes.

Static Nested Classes In Java :


If nested class is declared as static, then that nested class is called as static nested class.

?
1
class OuterClass
2
{
3
int i; //Field as a member
4
5 void methodOne()
6 {
7 //method as a member

8 }

9
10 static class NestedClass
{
11
//class as a member which is declared as static
12
}
13
}
14

Let’s discuss some interesting points about Static Nested Classes.

o Static nested classes can contain both static and non-static members.
?

1 class OuterClass

2 {
//Some members of OuterClass
3
4
static class NestedClass
5
{
6
static int i; //Static Field
7
8
int j; //Non-static Field
9
10 void methodOne()
11 {
12 //Non-static method
13 }

14
15 static void methodTwo()
{
16
//Static Method
17
}
18
}
19
}
20
21
o We can access only static members of outer class inside a static nested class. We
can’t access non-static members of outer class inside a static nested class.
?

class OuterClass
1
{
2
static int i; //static field of OuterClass
3
int j; //Non-static field of OuterClass
4
5
void methodOne()
6
{
7 //Non-static method of OuterClass
8 }

9
10 static void methodTwo()

11 {

12 //static method of OuterClass


}
13
14
static class NestedClass
15
{
16
void methodOfInnerClass()
17
{
18 System.out.println(i); //static field can be accessed
19
20 System.out.println(j); //This gives Compile time error

21
22 //can't access non-static field

23
methodTwo(); //can access static method
24
25
methodOne(); //This gives Compile time error
26
27
//can't access non-static method
28
}
29
}
30 }
31
32
33
o We have seen that static methods can’t be abstract but static nested classes can
be abstract.
?

1 class OuterClass

2 {

3 //static and abstract inner class

4
abstract static class NestedClass
5
{
6
abstract void methodOne(); //abstract method of NestedClass
7
8
void methodTwo()
9
{
10 //concrete method of NestedClass
11 }

12 }
13 }

14
o Static nested class can be final.
?

1
class OuterClass
2
{
3
//final and static nested class
4
5 final static class NestedClass
6 {

7 void methodOne()

8 {

9 //concrete method of NestedClass


}
10
}
11
}
12
o Below example shows how to refer Objects of the static nested class.
?

1 class OuterClass

2 {
int i = 10; //Non-static Field of OuterClass
3
4
static void methodOne()
5
{
6
System.out.println("Static method of OuterClass");
7
}
8
9 static class NestedClassOne
10 {
11 int i = 20; //Non-static Field of NestedClassOne

12
13 static void methodOne()

14 {
System.out.println("Static method of NestedClassOne");
15
}
16
}
17
18
static class NestedClassTwo
19
{
20 int i = 30; //Non-static Field of NestedClassTwo
21
22 static void methodOne()
23 {

24 System.out.println("static method of NestedClassTwo");

25 }
}
26
}
27
28
public class NestedClasses
29
{
30
public static void main(String[] args)
31 {
32 OuterClass.methodOne(); //static member can be accessed direct
33 OuterClass outer = new OuterClass();

34 System.out.println(outer.i); //Instance member must be accessed th

35
36 OuterClass.NestedClassOne.methodOne(); //static member can be acce
class name.
37
OuterClass.NestedClassOne nestedOne = new OuterClass.NestedClassOne(
38 System.out.println(nestedOne.i); //Instance member must be acce
39 reference

40
OuterClass.NestedClassTwo.methodOne(); //static member can be acce
41 class name.
42 OuterClass.NestedClassTwo nestedTwo = new OuterClass.NestedClassTwo(

43 System.out.println(nestedTwo.i); //Instance member must be acce


reference
44
}
45 }
46
47
o Constructors and methods of nested classes can be overloaded.
?

1 class OuterClass

2 {
static class NestedClass
3
{
4
NestedClass()
5
{
6
//First constructor
7 }
8
9 NestedClass(int i)
10 {

11 //Second Constructor

12 }

13
NestedClass(int i, int j)
14
{
15
//Third Constructor
16
}
17
18
void methodOne()
19 {
20 //Overloaded method
21 }

22
23 void methodOne(int i)

24 {
//Overloaded method
25
}
26
27
void methodOne(int i, int j)
28
{
29
//Overloaded method
30 }
31 }
32 }

33
34
35
o Static Nested Classes can be chained. i.e Nested class may contain another
nested class and that nested class may contain another nested class and so on.
?

class OuterClass
1
{
2
static class NestedClass
3
{
4
static class NestedClassOne
5 {
6 static class NestedClassTwo
7 {

8 static class NestedclassThree

9 {
static void methodOne()
10
{
11
System.out.println("Chain Of Nested Classes");
12
}
13
}
14 }
15 }

16 }
}
17
18
public class NestedClasses
19
{
20
public static void main(String[] args)
21
{
22 OuterClass.NestedClass.NestedClassOne.NestedClassTwo.NestedclassThree.
23 }
24}
25
26
27

If you compile the above program, for each class, .class file will be generated. The
generated .class files are
– OuterClass.class, OuterClass$NestedClass.class, OuterClass$NestedClass$NestedClassOne
.class, OuterClass$NestedClass$NestedClassOne$NestedClassTwo.class, OuterClass$Nested
Class$NestedClassOne$NestedClassTwo$NestedclassThree.class.

If you observe names of generated .class files, you will come to know that name contains
name of outer class and nested classes seperated by $.

That’s it for today. Tomorrow, we will discuss about Non-static Nested Classes OR simply
Inner Classes.

Non-Static Nested Classes OR Inner Classes In Java


pramodbablad May 28, 2014 3

Non-Static Nested Classes In Java :


Nested classes which are declared as non-static or nested classes which can be accessed
only though instantiating it’s outer class are called non-static nested classes. Non-static
nested classes are also called as Inner Classes.

They are 3 types of Inner Classes in java.

1. Member Inner Classes


2. Local Inner Classes
3. Anonymous Inner classes

Today we will discuss about Member Inner Classes.

Member Inner Classes :


Member Inner Classes are non-static nested classes which are declared as non-static
members of outer class.

Let’s discuss important observations about member inner classes.

o Member inner classes must contain only non-static members. Static members are
not allowed inside member inner classes.
?

1 class OuterClass
{
2
//Member Inner Class : Class As a Non-Static Member
3
class InnerClass
4
{
5
int i; //can contain non-static field
6
7
static int j = 10; //It gives compile time error
8
9 //Should not contain static field
10
11 void methodOne()

12 {

13 //can have non-static method

14 }

15
static void methodTwo()
16
{
17
//Compile time error
18
//should not contain static method
19
}
20 }
21 }
22
23
o But, here is the interesting point. You can declare a static field inside a
member inner class if the field is final. And such field must be initialized at the
time of declaration only. Remember, this rule is only for the fields not for the
methods.
?

1
class OuterClass
2
{
3 class InnerClass
4 {

5 int i; //can contain non-static field

6
7 static final int j = 10; //can contain static and final field

8
9 //it must be initialized at the time of declaration.
}
10
}
11
o Member inner class may contain any number of IIB’s but should not contain any
SIB’s.
?

1 class OuterClass

2 {
class InnerClass
3
{
4
int i;
5
6
{
7
System.out.println("First IIB");
8 }
9
10 {
11 System.out.println("Second IIB");
12 }

13
14 static
{
15
//compile time error
16
//Member Inner Class should not contain SIB
17
}
18
}
19 }
20
21
o We can access both static and non-static members of outer class inside a
member inner class.
?

1 class OuterClass
2 {

3 int i; //Non-static field of OuterClass

4
5 static int j; //Static field of OuterClass

6
void methodOne()
7
{
8
System.out.println("Non-Static Method Of OuterClass");
9
}
10
11
static void methodTwo()
12 {
13 System.out.println("Static Method Of OuterClass");
14 }

15
16 class InnerClass

17 {
18 void methodOfInnerClass()

19 {
System.out.println(i); //can use non-static field of OuterClass
20
21
System.out.println(j); //can use static field of OuterClass
22
23
methodOne(); //can call non-static method of OuterClass
24
25
methodTwo(); //can call static method of OuterClass
26
}
27 }
28 }
29
30
o Below example shows how to instantiate member inner class and how to access it’s
members.
?

1 class OuterClass

2 {

3 class InnerClass
{
4
int i; //Non-static field of InnerClass
5
6
static final int j = 10; //static and final field of InnerClass
7
8
void methodOne()
9
{
10 System.out.println("Non-static method of InnerClass");
11 }
12 }

13 }

14
15 public class InnerClasses

16 {
public static void main(String args[])
17
{
18
OuterClass outer = new OuterClass(); //creating an instance of Oute
19
20
OuterClass.InnerClass inner = outer.new InnerClass(); //creating an
21
22
System.out.println(inner.i); //accessing non-static field of Inn
23
24 System.out.println(OuterClass.InnerClass.j); //static field can
25 through class name

26
inner.methodOne(); //accessing non-static method of InnerClass
27
}
28
}
29
30
o All members of outer class are accessible inside member inner class and all
members of member inner class are accessible inside the outer class irrespective of
their visibility.
?

1 class OuterClass
{
2
private int i; //private field of OuterClass
3
4
int j; //Default field of OuterClass
5
6
protected int k; //protected field of OuterClass
7
8
public int m; //public field of OuterClass
9
10 void methodOfOuterClass()
11 {

12 InnerClass inner = new InnerClass(); //creating instance of InnerCla

13
System.out.println(inner.a); //accessing private field of InnerCla
14
15
System.out.println(inner.b); //accessing default field of InnerCla
16
17
System.out.println(inner.c); //accessing protected field of InnerC
18
19
System.out.println(inner.d); //accessing public field of InnerClas
20
}
21
22 class InnerClass
23 {
24 private int a; //private field of InnerClass

25
26 int b; //Default field of InnerClass

27
28 protected int c; //protected field of InnerClass

29
public int d; //public field of InnerClass
30
31
void methodOfInnerClass()
32
{
33
OuterClass outer = new OuterClass(); //creating an instance of
34 OuterClass

35
36 System.out.println(outer.i); //accessing private field of
OuterClass
37
38
System.out.println(outer.j); //accessing default field of
39 OuterClass
40
41 System.out.println(outer.k); //accessing protected field of
OuterClass
42
43
System.out.println(outer.m); //accessing public field of
44 OuterClass

45 }
}
46
}
47
o Member inner classes can be abstract or can be final but not both.
?

1
class OuterClass
2
{
3
abstract class InnerClassOne
4 {
5 //abstract Inner Class

6 }

7
8 final class InnerClassTwo

9 {
//final inner class
10
}
11
}
12

This is all about Member Inner Classes. Tomorrow, we will discuss about Local Inner
Classes.

Local Inner Class In Java


pramodbablad May 29, 2014 3
Local Inner Class In Java :
Local inner class in java is non-static nested class which is declared inside a method or a
block.

Let’s discuss some of behaviors of Local Inner Class in java.

o Local inner classes must be defined inside a method or a block.


?

class OuterClass
1
{
2
static
3
{
4 class LocalInnerClassOne
5 {

6 //Class defined inside Static Initialization Block

7 }
}
8
9
{
10
class LocalInnerClassTwo
11
{
12
//Class defined inside Instance Initialization Block
13
}
14 }
15
16 void methodOne()

17 {

18 class LocalInnerClassThree

19 {
//Class defined inside a non-static method
20
}
21
}
22
23
static void methodTwo()
24 {

25 class LocalInnerClassFour
{
26
//Class defined inside a static method
27
}
28
}
29
30
void methodThree()
31 {
32 if(true)
33 {

34 class LocalInnerClassFive

35 {
//Class defined inside if-statement
36
}
37
}
38
39
for(int i=0; i<=5; i++)
40
{
41 class LocalInnerClassSix
42 {
43 //Class defined inside a for loop

44 }

45 }
}
46
}
47
48
49
50
51
52
o Local Inner Classes can’t be static. Because, local inner classes are nothing but
local variables and local variables can’t be static.
?

1
class OuterClass
2
{
3
void methodOne()
4 {
5 static class LocalInnerClass

6 {

7 //compile time error


//Local Inner class can't be static
8
}
9
}
10
}
11
o Local inner classes can’t have static members. Only non-static members are
allowed inside local inner classes. But local inner classes can contain static and
final field.
?

1 class OuterClass

2 {

3 void methodOne()
{
4
class LocalInnerClass
5
{
6
int i; //can contain Non-static field
7
8
static final int j = 10; //can contain static and final field
9
10 static int k; //Compile time error : can't have static field
11
12 {
13 //can contain instance initializer

14 }
15
16 static

17 {
//can't have static initializer
18
}
19
20
void methodOne()
21
{
22
//can contain non-static method
23 }
24
25 static void methodTwo()
26 {

27 //compile time error : can't have static method

28 }
}
29
}
30
}
31
32
33
o To access members of local inner class, you must create an instance of it.
?

1
class OuterClass
2 {
3 void methodOne()
4 {

5 class LocalInnerClass

6 {
int i; //Non-static field
7
8
static final int j = 10; //static and final field
9
10
11 void methodOne()

12 {
System.out.println("From LocalInnerClass");
13
}
14
}
15
16
System.out.println(LocalInnerClass.j); //static and final field ca
17 through class name

18
19 LocalInnerClass inner = new LocalInnerClass(); //Creatin an object

20
21 System.out.println(inner.i); //accessing non-static field throu

22
inner.methodOne(); //calling non-static method through object ref
23
}
24
}
25
26
public class InnerClasses
27
{
28 public static void main(String args[])
29 {
30 OuterClass outer = new OuterClass();

31 outer.methodOne();

32 }
}
33
34
o Local inner classes are local to a method or a block in which they are defined. i.e
you can’t use local inner classes outside the method or block in which they are
defined.
?

class OuterClass
1
{
2 void methodOne()

3 {
class LocalInnerClass
4
{
5
int i; //Non-static field
6
7
static final int j = 10; //static and final field
8
9
void methodOne()
10 {
11 System.out.println("From LocalInnerClass");
12 }

13 }

14
15 LocalInnerClass inner = new LocalInnerClass();

16
//can use LocalInnerClass within the method in which it is defined
17
}
18
19
void methodTwo()
20
{
21
LocalInnerClass inner = new LocalInnerClass(); //compile time error
22
23 //can't use LocalInnerClass outside the methodOne().
24 }
25 }

26
27
28
o Only final local variables of methods or blocks containing local inner class can be
used inside local inner class.
?
1
class OuterClass
2
{
3
void methodOne()
4
{
5
int i; //Non-final local variable
6
7
final int j; //final local variable
8
9 class LocalInnerClass
10 {

11 void methodOne()

12 {

13 System.out.println(i); //compile time error

14
//can't use non-final local variable
15
16
System.out.println(j); //can use final local variable
17
}
18
}
19
}
20 }
21
o Local inner classes can not be declared with access modifiers. i.e Local inner
classes can not be private, protected and public. But they can have private, public,
protected and default members in them.
?

class OuterClass
1
{
2
void methodOne()
3
{
4
private class LocalInnerClassOne
5 {
6 //Compile time error

7 //Local inner class can't be private


}
8
9
protected class LocalInnerClassTwo
10
{
11
//Compile time error
12
//Local inner class can't be protected
13 }
14
15 public class LocalInnerClassThree
16 {

17 //Compile time error

18 //Local inner class can't be public


}
19
20
class LocalInnerClassFour
21
{
22
private int i; //can have private member
23
protected int j; //can have protected member
24 public int k; //can have public member
25 int m; //can have default member
26 }

27 }

28 }

29
30
31
o Local inner classes can be abstract or can be final but not both.
?

1 class OuterClass

2 {
3 void methodOne()

4 {
abstract class LocalInnerClassOne
5
{
6
//abstract local inner class
7
}
8
9
final class LocalInnerClassTwo
10 {
11 //final local inner class
12 }

13 }

14 }

15

This is all about Local Inner Classes in java. Tomorrow, we will discuss about Anonymous
Inner Classes.

Anonymous Inner Class In Java


pramodbablad May 30, 2014 7

Anonymous inner class, the name itself suggest that it is a class without a name.
Anonymous inner class in java is an inner class or non-static nested class without a name.

Consider the below class definition.

class SuperClass
1
{
2
void methodOne()
3
{
4
System.out.println("From SuperClass");
5 }
6
7 void methodTwo()

8 {
System.out.println("From SuperClass");
9
}
10
}
11
12

Let’s consider that we have a requirement in which the above class ‘SuperClass’ has to be
re-used with little modification to the ‘methodOne()’. To do this, we have to create a
subclass to ‘SuperClass’ and override the ‘methodOne()’ method. Let’s implement this.

1
class SubClass extends SuperClass
2 {
3 @Override
4 void methodOne()

5 {

6 System.out.println("From Sub Class");


}
7
}
8

To use the methodOne(), we have to create an object of ‘SubClass’ type and call
‘methodOne()’ from that object.

1 public class InnerClasses


{
2
public static void main(String args[])
3
{
4
SubClass subclass = new SubClass();
5
subclass.methodOne();
6 }
7 }
8

This method of implementing is little bit lengthy. There is one more method of
implementing this requirement which takes less time than this and you need to write only
few lines of code to implement this requirement. That is called Anonymous Inner Class.

Let’s implement this requirement with anonymous inner class.

1
public class InnerClasses
2
{
3
public static void main(String args[])
4
{
5
SuperClass superclass = new SuperClass()
6 {
7 @Override

8 void methodOne()

9 {

10 System.out.println("From Anonymous Inner Class");


}
11
};
12
superclass.methodOne();
13
}
14
}
15

That’s it. You just have to create an object reference variable of type ‘SuperClass’ and
override the method which needs modification in the curly brackets and end with
semicolon. No need to create sub class separately. This method is easier than the above
method. isn’t it?.

Let’s discuss some of features of anonymous inner class.

o Anonymous inner classes don’t have name. They are nameless.


o You can create only one object to anonymous inner class. If you want to create
another object, you have to write the whole class again.
?

public class InnerClasses


1
{
2 public static void main(String args[])

3 {
//First Object Creation
4
SuperClass firstObject = new SuperClass()
5
{
6
@Override
7
void methodOne()
8 {
9 System.out.println("From First Object");
10 }

11 };

12
13 //Second Object Creation
SuperClass secondObject = new SuperClass()
14
{
15
@Override
16
void methodOne()
17
{
18 System.out.println("From Second Object");
19 }
20 };

21 }

22 }

23
24
25
o When you are creating an anonymous inner class, you are actually creating a sub
class to a class which needs to be modified. This sub class doesn’t have name and
it is declared in another class. That’s why it is called Anonymous Inner Class.
o While creating an anonymous inner class you are also creating an object to that
subclass and it is referenced by super class reference variable. This also shows the
polymorphism. Because, Super class reference variable can refer to super class
object and also it’s sub class object.
o Using anonymous inner class, you can implement both abstract classes and
interfaces.
?
1 abstract class AbstractClass
2 {
3 abstract void methodOne();

4
5 abstract void methodTwo();

6 }

7
interface InterfaceClass
8
{
9
abstract void methodOfInterface();
10
}
11
12
public class InnerClasses
13 {
14 public static void main(String args[])
15 {

16 //Implementing abstract class

17 AbstractClass a = new AbstractClass()


{
18
@Override
19
void methodOne()
20
{
21
System.out.println("From AbstractClass");
22
23 }
24
25 //You have to override second abstract method also,
26 //otherwise, you will get compile time error.

27 @Override

28 void methodTwo()
{
29
30 System.out.println("From AbstractClass");

31 }
};
32
33
//Implementing Interface
34
InterfaceClass i = new InterfaceClass()
35
{
36
@Override
37 public void methodOfInterface()
38 {
39 System.out.println("From Interface");

40 }

41 };
}
42
}
43
44
45
46

Variable Hiding OR Shadowing In Java


pramodbablad May 31, 2014 10

As we all know that there are two types of variables. One is Local Variables and another one is global
variables. Global variables may be static or non-static.

Have a look at the following example.

public class Shadowing


1
{
2
int x = 10;
3
4 void methodOne(int x)

5 {
//local x shadows or hides global x
6
7
System.out.println(x); //output : 20
8
}
9
10
public static void main(String[] args)
11
{
12 Shadowing shadow = new Shadowing();
13 shadow.methodOne(20);
14 }

15 }

16
17

In the above example, Class ‘Shadowing’ has global variabe ‘x’ and it’s scope is inside the class.
‘methodOne()’ of this class also has a local variable with the same name and it’s scope is inside the
method. If you try to print the ‘x’ inside the methodOne(), the value of local variable is printed but not
that of global variable. Because, local ‘x’ shadows or hides global ‘x’. This is called variable hiding or
shadowing.

Variable Hiding Or Shadowing In Java :


A variable is hidden or shadowed, if there is another variable exist with the same name in the nearer
scope.

How To access hidden or shadowed variable?.


o When a global variable is hidden or shadowed by local variable.

To access the hidden static variable inside a method or block – use class name and to access the
hidden non-static variable – use this keyword. this keyword refers to current instance of the class.

For example,

1 public class Shadowing

2 {

3 static int x = 10;


4
5 int y = 20;

6
7 void methodOne(int x, int y)
{
8
//accessing hidden static variable using class name
9
10
System.out.println(Shadowing.x); //output : 10
11
12
//accessing hidden non-static variable using this keyword.
13
14
System.out.println(this.y); //output : 20
15 }
16
17 public static void main(String[] args)
18 {

19 Shadowing shadow = new Shadowing();

20 shadow.methodOne(30, 40);
}
21
}
22
23

Note : Static hidden variable can be accessed using this keyword also, but only in non-static context.
Because, this can not be used in static context.

o When a Super Class variable is hidden or shadowed by sub class variable :

If sub class has variables with the same name as that of super class, it hides or shadows super class
variable. To access, Super class hidden variables, just refer sub class object through super class
reference variable. For example,

class SuperClass
1
{
2
int x = 10;
3
4 static int y = 20;

5 }

6
class SubClass extends SuperClass
7
{
8
//subclass hides superclass variables with same name
9
10
int x = 30;
11
12
static int y = 40;
13 }
14
15 public class Shadowing
16 {

17
18 public static void main(String[] args)

19 {
SubClass subClass = new SubClass(); //Creating object to SubClass
20
21
System.out.println(subClass.x); //Output : 30
22
System.out.println(subClass.y); //Output : 40
23
24
//accessing super class hidden variables in the same object.
25
26
SuperClass superClass = subClass; //casting from subclass to supe
27
28 System.out.println(superClass.x); //Output : 10
29 System.out.println(superClass.y); //Output : 20
30 }

31 }
32
33
34

From the above example, it is clear that super class variables are not overridden in the sub class but
they are hidden.

Note : If you want to access super class variable in sub class itself, use super keyword.

o When Outer Class Variable is hidden in Inner Class :

If inner class has a variable with the same name as that of an outer class, then it hides or shadows
outer class variable. To access non-static hidden outer class variable in inner class, use this syntax
: OuterClassName.this.variableName and to access static hidden outer class variable in inner class
use the same syntax or use OuterClassName.variableName. For example,

1 class OuterClass

2 {

3 int x = 10;

4
static int y = 20;
5
6
class InnerClass
7
{
8
int x = 30;
9
10
static final int y = 40;
11
12
void methodOfInnerClass()
13 {
14 System.out.println(x); //output : 30
15
16 System.out.println(y); //output : 40

17
18 //accessing non-static hidden outer class variable in inner cla
19
20 System.out.println(OuterClass.this.x); //Output : 10

21
22 //accessing static hidden outer class variable in inner class

23
System.out.println(OuterClass.this.y); //Output : 20
24
25
//OR
26
27
System.out.println(OuterClass.y); //Output : 20
28
29
}
30
}
31 }
32
33 public class Shadowing
34 {

35
36 public static void main(String[] args)

37 {
OuterClass outer = new OuterClass();
38
39
OuterClass.InnerClass inner = outer.new InnerClass();
40
41
inner.methodOfInnerClass();
42
43
}
44
}
45
46
47
Inheritance Of Inner Classes In Java
pramodbablad June 1, 2014 7

Today we will see various scenarios of inheritance of inner classes in java.

o One inner class can extend another inner class of the same class.
?

1
class OuterClass
2
{
3 class InnerClassOne
4 {
5 int x = 10;

6
7 void methodOfInnerClassOne()

8 {
System.out.println("From InnerClassOne");
9
}
10
}
11
12
class InnerClassTwo extends InnerClassOne
13
{
14 //One Inner Class can extend another inner class
15 }
16 }

17
18 public class InnerClasses

19 {
public static void main(String args[])
20
{
21
OuterClass outer = new OuterClass(); //Instantiating OuterClass
22
23
24 OuterClass.InnerClassTwo innerTwo = outer.new InnerClassTwo(); //In
InnerClassTwo
25
26
System.out.println(innerTwo.x); //Accessing inherited field x fr
27
innerTwo.methodOfInnerClassOne(); //calling inherited method from
28 }
29 }
30
o An inner class can be extended by another class outside of it’s outer class. If you
are extending static inner class (Static nested class), then it is a straight forward
implementation. If you are extending non-static inner class, then sub class
constructor must explicitly call super class constructor using an instance of outer
class. Because, you can’t access non-static inner class without the instance of
outer class.
?

1 class OuterClass
2 {
3 static class InnerClassOne

4 {

5 //Class as a static member


}
6
7
class InnerClassTwo
8
{
9
//Class as a non-static member
10
}
11 }
12
13 //Extending Static inner class or static nested class
14 class AnotherClassOne extends OuterClass.InnerClassOne

15 {

16 //static nested class can be referred by outer class name,


}
17
18
19 //Extending non-static inner class or member inner class

20 class AnotherClassTwo extends OuterClass.InnerClassTwo


{
21
public AnotherClassTwo()
22
{
23
new OuterClass().super(); //accessing super class constructor throu
24 instance

25 }

26 }

27
o When an outer class is extended by it’s sub class, Member inner classes will not be
inherited to sub class. To use inner class properties inside the sub class of outer
class, sub class must also have an inner class and that inner class must extend inner
class of the outer class. For example,
?

1 class OuterClass
2 {

3 int x;

4
5 void methodOfOuterClass()
{
6
System.out.println("From OuterClass");
7
}
8
9
//Class as a member
10
class InnerClass
11 {
12 int y;
13 }

14 }

15
16 class AnotherClass extends OuterClass
17 {

18 //Only fields and methods are inherited.


// To use inner class properties,
19
//it's inner class must extend inner class of it's super class
20
class AnotherInnerClass extends InnerClass
21
{
22
//Inner Class of AnotherClass extends Inner Class of OuterClass
23 }
24 }
25
26 public class InnerClasses

27 {

28 public static void main(String args[])


{
29
AnotherClass anotherClass = new AnotherClass(); //creating AnotherC
30
31
System.out.println(anotherClass.x); //accessing inherited field
32 OuterClass
33
34 anotherClass.methodOfOuterClass(); //calling inherited method fr
OuterClass
35
36
//Using the properties of InnerClass
37
38
AnotherClass.AnotherInnerClass anotherInnerClass = anotherClass.new
39 AnotherInnerClass();

40
41 //creating object to AnotherInnerClass

42
System.out.println(anotherInnerClass.y); //accessing inherited fie
43
InnerClass
44
45 }
46 }

47
o Inner class can extend it’s outer class. But, it does not serve any meaning.
Because, even the private members of outer class are available inside the inner
class. Even though, When an inner class extends its outer class, only fields and
methods are inherited but not inner class itself.
?

1 class OuterClass

2 {

3 int x;

4
void methodOfOuterClass()
5
{
6
System.out.println("From OuterClass");
7
}
8
9
//Class as a member
10 class InnerClass extends OuterClass
11 {
12 //only fields and methods are inherited, but not member Inner Class

13 }

14
15 class InnerClassOne
{
16
//another class as a member
17
}
18
}
19
20
public class InnerClasses
21 {
22 public static void main(String args[])
23 {

24 OuterClass outer = new OuterClass();


25 //You have to create OuterClass object to access non-static inner c

26
27 OuterClass.InnerClass inner = outer.new InnerClass(); //creating ob
InnerClass
28
29
System.out.println(inner.x); //accesiing inherited field x
30
31 inner.methodOfOuterClass(); //accessing inherited method
32 }
33 }

34
35

Java Interview Questions On Nested Classes


pramodbablad April 23, 2015 0

Java Interview Questions On Nested Classes :


1) How many types of nested classes are there in java?

Java supports 2 types of nested classes. They are,

a) Static Nested Classes

b) Non-static Nested Classes OR Inner Classes

Non-static nested classes can be of 3 type,

a) Member Inner Classes

b) Local Inner Classes

c) Anonymous Inner Classes

2) Can we access non-static members of outer class inside a static nested class?

No, we can’t access non-static members of outer class inside a static nested class. We can access only
static members of outer class inside a static nested class.

3) What are member inner classes in java?


Member inner classes are the classes which are declared as non-static members of another class.
Member inner classes can be accessed only by instantiating the outer class.

4) Can member inner classes have static members in them?

No, member inner classes can’t have static members in them. They can have only non-static members.
But, exception being the static and final field. i.e member inner class can have static and final field,
but it must be initialized at the time of declaration only.

5) Can we access all the members of outer class inside a member inner class?

Yes, we can access all the members, both static and non-static, of outer class inside a member inner
class.

6) Can we declare local inner classes as static?

No. Local inner classes can’t be static.

7) Can we use local inner classes outside the method or block in which they are defined?

No. Local inner classes are local to method or block in which they are defined. We can’t use
them outside the method or block in which they are defined.

8) Can we declare local inner classes as private or protected or public?

No. Local inner classes can’t be declared with access modifiers.They can’t be private or protected or
public.

9) What is the condition to use local variables inside a local inner class?

The condition is that local variables must be final. We can’t use non-final local variables inside a local
inner class.

10) What are anonymous inner classes in java?

Anonymous inner classes are the inner classes without a name. You can instantiate an anonymous
inner class only once. Click here for more info on anonymous inner classes.

11) What is the main difference between static and non-static nested classes?

The main difference between static and non-static nested classes is that you need not to instantiate the
outer class to access static nested classes. But, to access non-static nested classes, you have to
instantiate the outer class.

Wrapper Classes In Java


pramodbablad June 5, 2014 7
Java is an object oriented language and java treats everything as an object. For example, A simple file
(java.io.File), a Calendar (java.util.Calendar), a date (java.util.Date), an image (java.awt.Image), a
color (java.awt.Color) are represented by the classes and their objects. Primitive data types like int,
float, double, boolean, char etc. are also represented by the classes called Wrapper Claases. For
every primitive data type, there is a Wrapper Class in java. All wrapper classes are placed
in java.lang package. Below is the list of primitive data types and their corresponding wrapper
classes.

Primitive Data Type Corresponding Wrapper Class

byte java.lang.Byte

short java.lang.Short

int java.lang.Integer

long java.lang.Long

float java.lang.Float

double java.lang.Double

boolean java.lang.Boolean

char java.lang.Character

Wrapper classes are mainly used to wrap the primitive content into an object. This operation of
wrapping primitive content into an object is called boxing. The reverse process i.e unwrapping the
object into corresponding primitive data is called Unboxing.

Boxing :
Following example shows the boxing i.e wrapping primitive content into corresponding
wrapper object.

1 public class WrapperClasses

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

4 {
byte b = 10; //Primitive byte data
5
Byte B = new Byte(b); //Wrapping primitive byte data into Byte Obj
6
7
short s = 15; //Primitive short data
8
Short S = new Short(s); //Wrapping of primitive short data into Sh
9
10
int i = 20; //Primitive int Data
11 Integer I = new Integer(i); //Wrapping of primitive int data into
12 Object

13
long l = 25; //Primitive long data
14
Long L = new Long(l); //Wrapping primitive long data into Long Obj
15
16
float f = 12; //Primitive float data
17
Float F = new Float(f); //Wrapping primitive float data into Float
18
19
double d = 18.58; //Primitive double data
20 Double D = new Double(d); //Wrapping primitive double data into Do
Object
21
22
boolean bln = true; //Primitive boolean data
23
Boolean BLN = new Boolean(bln); //Wrapping primitive boolean data
24 Boolean Object
25
26 char c = 'C'; //Primitive char data

27 Character C = new Character(c); //Wrapping primitive char data int


Character Object
28
}
29
}
Auto-Boxing :
From JDK 1.5 onwards, Auto-Boxing is introduced. According to this feature, you need not to
explicitly wrap the primitive content into an object. Just assign primiive data to corresponding
wrapper class reference variable, java automatically wraps primitive data into corresponding wrapper
object.

1 public class WrapperClasses


{
2
public static void main(String[] args)
3
{
4
byte b = 10; //Primitive byte data
5
Byte B = b; //Auto-Boxing of byte data
6
7
short s = 15; //Primitive short data
8 Short S = s; //Auto-Boxing of short data
9
10 int i = 20; //Primitive int Data
11 Integer I = i; //Auto-Boxing of int data

12
13 long l = 25; //Primitive long data

14 Long L = l; //Auto-Boxing of long data

15
float f = 12; //Primitive float data
16
Float F = f; //Auto-Boxing of float data
17
18
double d = 18.58; //Primitive double data
19
Double D = d; //Auto-Boxing of double data
20
21
boolean bln = true; //Primitive boolean data
22 Boolean BLN = bln; //Auto-Boxing of boolean data
23
24 char c = 'C'; //Primitive char data
25 Character C = c; //Auto-Boxing of char data

26 }
}
27
28
29

Unboxing :
All wrapper classes have methods to unwrap the object to corresponding primitive data. Go through
the following example, it shows unboxing i.e unwrapping wrapper object into corresponding primitive
data.

public class WrapperClasses


1
{
2
public static void main(String[] args)
3
{
4
Byte B = new Byte((byte) 10); //Byte Object
5 byte b = B.byteValue(); //Unwrapping Byte object to byte dat
6
7 Short S = new Short((short) 20); //Short Object
8 short s = S.shortValue(); //Unwrapping Short object to shor

9
10 Integer I = new Integer(15); //Integer Object

11 int i = I.intValue(); //Unwrapping Integer object to int d

12
Long L = new Long(50); //Long Object
13
long l = L.longValue(); //Unwrapping Long object to long data
14
15
Float F = new Float(20); //Float Object
16
float f = F.floatValue(); //Unwrapping Float object to float data
17
18
Double D = new Double(20.5); //Double Object
19 double d = D.doubleValue(); //Unwrapping Double object to double
20
21 Boolean BLN = new Boolean(true); //Boolean Object

22 boolean bln = BLN.booleanValue(); //Unwrapping Boolean object to


boolean data
23
24
Character C = new Character('C'); //Character Object
25 char c = C.charValue(); //Unwrapping Character object t
data
26
}
27
}
28
29

Auto-Unboxing :
From JDK 1.5 onwards, Auto-Unboxing is introduced. According to this feature, you need not to call
method of wrapper class to unbox the wrapper object. Java implicitly converts wrapper object to
corresponding primitive data if you assign wrapper object to primitive type variable.

public class WrapperClasses


1
{
2
public static void main(String[] args)
3 {
4 Byte B = new Byte((byte) 10); //Byte Object
5 byte b = B; //Auto-Unboxing of Byte Object

6
7 Short S = new Short((short) 20); //Short Object

8 short s = S; //Auto-Unboxing of Short Object

9
Integer I = new Integer(15); //Integer Object
10
int i = I; //Auto-Unboxing of Integer Object
11
12
Long L = new Long(50); //Long Object
13
long l = L; //Auto-Unboxing of Long Object
14
15 Float F = new Float(20); //Float Object

16 float f = F; //Auto-Unboxing of Float Object

17
Double D = new Double(20.5); //Double Object
18
double d = D; //Auto-Unboxing of Double Object
19
20
Boolean BLN = new Boolean(true); //Boolean Object
21
boolean bln = BLN; //Auto-Unboxing of Boolean Obje
22
23
Character C = new Character('C'); //Character Object
24 char c = C; //Auto-Unboxing of Character Obj
25 }
26 }

27
28
29

That’s it for today. Tomorrow we will discuss about constructors and some other methods of Wrapper
Classes In Java.

Constructors And Parsing Methods Of Wrapper Classes


In Java
pramodbablad June 6, 2014 0

Today we will discuss about constructors and parsing methods of Wrapper Classes In Java.

Constructors Of Wrapper Classes In Java:


Every wrapper class in java has two constructors,

1. First constructor takes corresponding primitive data as an argument


2. Second constructor takes string as an argument.
Notes :
o The string passed to second constructor should be parse-able to number , otherwise you will
get run time NumberFormatException.
o Wrapper Class Character has only one constructor which takes char type as an argument. It
doesn’t have a constructor which takes String as an argument. Because, String can not be
converted into Character.
o Wrapper class Float has three constructors. The third constructor takes double type as an
argument.

Following example shows constructors in wrapper classes.

1
public class WrapperClasses
2 {
3 public static void main(String[] args)

4 {

5 Byte B1 = new Byte((byte) 10); //Constructor which takes byte va

6 Byte B2 = new Byte("10"); //Constructor which takes String

7
//Byte B3 = new Byte("abc"); //Run Time Error : NumberFormatEx
8
9
//Because, String abc can not be parse-able to byte
10
11
Short S1 = new Short((short) 20); //Constructor which takes short
12
Short S2 = new Short("10"); //Constructor which takes String
13
14
Integer I1 = new Integer(30); //Constructor which takes int valu
15 Integer I2 = new Integer("30"); //Constructor which takes String a
16
17 Long L1 = new Long(40); //Constructor which takes long value as

18 Long L2 = new Long("40"); //Constructor which takes String as an

19
20 Float F1 = new Float(12.2f); //Constructor which takes float va

21 Float F2 = new Float("15.6"); //Constructor which takes String as


Float F3 = new Float(15.6d); //Constructor which takes double val
22
23
24 Double D1 = new Double(17.8d); //Constructor which takes doubl

25 Double D2 = new Double("17.8"); //Constructor which takes String

26
Boolean BLN1 = new Boolean(false); //Constructor which takes b
27
Boolean BLN2 = new Boolean("true"); //Constructor which takes S
28
29
Character C1 = new Character('D'); //Constructor which takes ch
30
Character C2 = new Character("abc"); //Compile time error : Strin
31 to character

32 }

33 }

34

Important Note :
If you pass a string other than true or false to the second constructor of Boolean wrapper class, the
object is initialized with false.

1 public class WrapperClasses


{
2
public static void main(String[] args)
3
{
4
Boolean BLN1 = new Boolean("true"); //passed string "true"
5
6
System.out.println(BLN1); //output : true
7
8
Boolean BLN2 = new Boolean("false"); //passed string "false"
9
10 System.out.println(BLN2); //output : false
11
12 Boolean BLN3 = new Boolean("abc"); //passed string "abc"
13
14 System.out.println(BLN3); //output : false

15 }
}
16
17

Parsing Methods Of Wrapper Classes In Java :


All wrapper classes in java have methods to parse the given string to corresponding primitive data
provided the string should be parse-able. If the string is not parse-able, you will get
NumberFormatException. All parsing methods of wrapper classes are static i.e you can refer them
directly using class name.

public class WrapperClasses


1
{
2
public static void main(String[] args)
3
{
4
byte b = Byte.parseByte("10");
5 System.out.println(b); //Output : 10
6
7 short s = Short.parseShort("25");
8 System.out.println(s); //Output : 25

9
10 int i = Integer.parseInt("123");

11 System.out.println(i); //Output : 123

12
long l = Long.parseLong("100");
13
System.out.println(l); //Output : 100
14
15
float f = Float.parseFloat("12.35");
16
System.out.println(f); //Output : 12.35
17
18
double d = Double.parseDouble("12.87");
19 System.out.println(d); //Output : 12.87
20
21 boolean bln = Boolean.parseBoolean("true");

22 System.out.println(bln); //Output : true

23
boolean bln1 = Boolean.parseBoolean("abc");
24
System.out.println(bln1); //Output : false
25
26
char c = Character.parseChar("abc"); //compile time error
27
28
//parseChar() is not defined for Character wrapper class
29
}
30 }
31
32
33

Today we will conclude here. Tomorrow, we will discuss about some other methods of wrapper
classes in java.

ValueOf() Method Of Wrapper Classes In Java


pramodbablad June 7, 2014 0

Every wrapper class in java has 3 forms of valueOf method. They are,

1. A valueOf() method which takes primitive type as an argument


2. A valueOf() method which takes String type as an argument
3. A valueOf() method which takes two arguments. One is String type and another one is int
type.

All these forms are public and static. The valueOf() methods are mainly used to wrap or box the
primitive content into wrapper class objects.

Let’s discuss these three forms in detail.

A valueOf() method with primitive type as an argument :


This form of valueOf method takes primitive type data as an argument and returns corresponding
wrapper class object. The template of this form looks like :
public static return_type valueOf ( primitive_type )

where return_type is any Wrapper Class.

Following example shows the usage of this form of valueOf() method.

1 public class WrapperClasses

2 {
public static void main(String[] args)
3
{
4
Byte B = Byte.valueOf((byte) 123);
5
System.out.println(B); //Output : 123
6
7
Short S = Short.valueOf((short) 25);
8 System.out.println(S); //Output : 25
9
10 Integer I = Integer.valueOf(46);
11 System.out.println(I); //Output : 46

12
13 Long L = Long.valueOf(235);

14 System.out.println(L); //Output : 235

15
Float F = Float.valueOf(23.5f);
16
System.out.println(F); //Output : 23.5
17
18
Double D = Double.valueOf(15.4d);
19
System.out.println(D); //Output : 15.4
20
21
Boolean BLN = Boolean.valueOf(true);
22 System.out.println(BLN); //Output : true
23
24 BLN = Boolean.valueOf(false);
25 System.out.println(BLN); //Output : false
26
27 Character C = Character.valueOf('C');

28 System.out.println(C); //Output : C
}
29
}
30
31
32

valueOf() Method with string as an argument :


This form of valueOf method takes string as an argument and returns corresponding wrapper class
object. It throws NumberFormatException, if string is not a valid numeric value. Character wrapper
class doesn’t have this method as string can not be converted to character. The template of this
form looks like :

public static return_type valueOf(String s) throws NumberFormatException

where return_type is any wrapper class.

1 public class WrapperClasses

2 {

3 public static void main(String[] args)


{
4
Byte B = Byte.valueOf("123");
5
System.out.println(B); //Output : 123
6
7
Short S = Short.valueOf("25");
8
System.out.println(S); //Output : 25
9
10 Integer I = Integer.valueOf("46");
11 System.out.println(I); //Output : 46
12
13 Long L = Long.valueOf("235");

14 System.out.println(L); //Output : 235

15
16 Float F = Float.valueOf("23.5");

17 System.out.println(F); //Output : 23.5

18
Double D = Double.valueOf("15.4");
19
System.out.println(D); //Output : 15.4
20
21
Boolean BLN = Boolean.valueOf("true");
22
System.out.println(BLN); //Output : true
23
24
BLN = Boolean.valueOf("false");
25 System.out.println(BLN); //Output : false
26
27 BLN = Boolean.valueOf("abc");
28 System.out.println(BLN); //Output : false

29
30 //Character C = Character.valueOf("C"); //Compile Time Error : C
this method
31
}
32
}
33
34

valueOf() Method with string and int as an arguments :


This form of valueOf method takes two arguments. One is String type which holds valid numeric
value to be converted into wrapper class object and second argument is int type which indicates the
radix or base of that numeric value. This form also throws NumberFormatException if String is not a
valid numeric value. This method is available only in Byte, Short, Integer and Long wrapper
classes. The template of this form is,

public static return_type valueOf(String s, int radix) throws NumberFormatException

where return_type is any wrapper class.

1 public class WrapperClasses

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

4 {
Byte B = Byte.valueOf("10110", 2); //A number with base 2 is conve
5
System.out.println(B); //Output : 22
6
7
B = Byte.valueOf("43", 5); //A number with base 5 is conver
8
System.out.println(B); //Output : 23
9
10
Short S = Short.valueOf("12043", 8); //A number with base 8 is
11 value

12 System.out.println(S); //Output : 5155

13
S = Short.valueOf("4751", 10); //A number with base 10 is conv
14
value
15 System.out.println(S); //Output : 4751
16
17 Integer I = Integer.valueOf("4673AB", 12); //A number with base
decimal value
18
System.out.println(I); //Output : 1132403
19
20
I = Integer.valueOf("6489CDF", 16); //A number with base 16 is
21 value

22 System.out.println(I); //Output : 105422047

23
24 Long L = Long.valueOf("GHFTDJ", 36); //A number with base 36 is
value
25
System.out.println(L); //Output : 996750199
26
27 L = Long.valueOf("DFGCHJ", 36); //A number with base 36 is con
value
28
System.out.println(L); //Output : 812017207
29
}
}
Following example shows some cases where you may get NumberFornatException.

1 public class WrapperClasses

2 {
public static void main(String[] args)
3
{
4
Byte B = Byte.valueOf("1012", 2);
5
6
//NumberFormatException : Because, Number with base 2 must contain
7
8
Byte B = Byte.valueOf("12043", 5);
9
10
//NumberFormatException : Value is out of range for Byte Type.
11
12 Short S = Short.valueOf("12043", 5); //No Run time error : value i
of Short
13
System.out.println(S); //Output : 898
14
15
Integer I = Integer.valueOf("1891BGH", 16);
16
17
//NumberFormatException : Because, Number with base 16 must contain
18 to 9

19 //and any character in A, B, C, D, E and F.

20
21 Long L = Long.valueOf("GHJBDFR", 36);

22
//No Run Time error : A number with base 36 can contain any digits
23
from A to Z
24 System.out.println(L); //Output : 35888885703
25 }
26 }
Number Class In Java
pramodbablad June 9, 2014 2

Number Class in java is an abstract class. It is placed in java.lang package. It has four abstract
methods and two concrete methods. The definition of Number Class Looks like this,

1
public abstract class Number extends Object implements Serializable
2
{
3
//Four Abstract Methods
4
public abstract int intValue();
5
public abstract long longValue();
6
public abstract float floatValue();
7 public abstract double doubleValue();
8
9 //Two Concrete Methods

10 public byte byteValue()

11 {
return (byte)intValue();
12
}
13
14
public short shortValue()
15
{
16
return (short)intValue();
17
}
18 }
19

You can notice that, even concrete methods byteValue() and shortValue() call abstract intValue()
method from their body. That means, to use these two methods, abstract intValue() method must be
implemented.

All wrapper classes which represent numeric values i.e Byte, Short, Integer, Long, Float and Double
are sub classes of Number class and they implement all four abstract methods.
Let’s see these methods one by one.

o intValue() Method :

This method returns int value of the specified object. It may involve truncation of the value.

1 public class WrapperClasses

2 {

3 public static void main(String[] args)


{
4
Byte B = new Byte("55");
5
int i = B.intValue();
6
System.out.println(i); //Output : 55
7
8
Short S = new Short("23");
9 i = S.intValue();
10 System.out.println(i); //Output : 23
11
12 Integer I = new Integer("56");

13 i = I.intValue();

14 System.out.println(i); //Output : 56

15
Long L = new Long("125");
16
i = L.intValue();
17
System.out.println(i); //Output : 125
18
19
Float F = new Float("23.56");
20
i = F.intValue();
21 System.out.println(i); //Output : 23 (Value is truncated)
22
23 Double D = new Double("521.56");
24 i = D.intValue();

25 System.out.println(i); //Output : 521 (Value is truncated)


26 }

27 }

28
29
o longValue() Method :

It returns long value of the specified object. It may involve truncation of the value.

1 public class WrapperClasses


{
2
public static void main(String[] args)
3
{
4
Byte B = new Byte("55");
5
long l = B.longValue();
6
System.out.println(l); //Output : 55
7
8 Short S = new Short("23");
9 l = S.longValue();

10 System.out.println(l); //Output : 23

11
12 Integer I = new Integer("56");

13 l = I.longValue();
System.out.println(l); //Output : 56
14
15
Long L = new Long("125");
16
l = L.longValue();
17
System.out.println(l); //Output : 125
18
19
Float F = new Float("23.56");
20 l = F.longValue();
21 System.out.println(l); //Output : 23 (Value is truncated)
22
23 Double D = new Double("521.56");

24 l = D.longValue();
System.out.println(l); //Output : 521 (Value is truncated)
25
}
26
}
27
28
29
o floatValue() Method :

It returns float value of the specified object.

1 public class WrapperClasses


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

4 {

5 Byte B = new Byte("55");


float f = B.floatValue();
6
System.out.println(f); //Output : 55.0
7
8
Short S = new Short("23");
9
f = S.floatValue();
10
System.out.println(f); //Output : 23.0
11
12 Integer I = new Integer("56");
13 f = I.floatValue();
14 System.out.println(f); //Output : 56.0

15
16 Long L = new Long("125");

17 f = L.floatValue();
System.out.println(f); //Output : 125.0
18
19
20 Float F = new Float("23.56");

21 f = F.floatValue();
System.out.println(f); //Output : 23.56
22
23
Double D = new Double("521.56");
24
f = D.floatValue();
25
System.out.println(f); //Output : 521.56
26
}
27 }
28
29
o doubleValue() Method :

It returns double value of the specified object.

1 public class WrapperClasses


2 {

3 public static void main(String[] args)

4 {
Byte B = new Byte("55");
5
double d = B.doubleValue();
6
System.out.println(d); //Output : 55.0
7
8
Short S = new Short("23");
9
d = S.floatValue();
10 System.out.println(d); //Output : 23.0
11
12 Integer I = new Integer("56");
13 d = I.floatValue();

14 System.out.println(d); //Output : 56.0

15
16 Long L = new Long("125");
17 d = L.floatValue();

18 System.out.println(d); //Output : 125.0

19
Float F = new Float("23.56");
20
d = F.floatValue();
21
System.out.println(d); //Output : 23.559999465942383
22
23
Double D = new Double("521.56");
24
d = D.floatValue();
25 System.out.println(d); //Output : 521.5599975585938
26 }
27 }

28
29
o byteValue() Method :

It returns byte value of the specified object. It may involve truncation.

1 public class WrapperClasses

2 {

3 public static void main(String[] args)


{
4
Byte B = new Byte("55");
5
byte b = B.byteValue();
6
System.out.println(b); //Output : 55
7
8
Short S = new Short("23");
9 b = S.byteValue();
10 System.out.println(b); //Output : 23
11
12 Integer I = new Integer("56");

13 b = I.byteValue();
14 System.out.println(b); //Output : 56

15
16 Long L = new Long("125");
b = L.byteValue();
17
System.out.println(b); //Output : 125
18
19
Float F = new Float("23.56");
20
b = F.byteValue();
21
System.out.println(b); //Output : 23 (Value is truncated)
22
23 Double D = new Double("521.56");
24 b = D.byteValue();
25 System.out.println(b); //Output : 9

26 }

27 }

28
29
o shortValue() Method :

It returns short value of specified object. It may involve truncation.

1 public class WrapperClasses

2 {
public static void main(String[] args)
3
{
4
Byte B = new Byte("55");
5
short s = B.shortValue();
6
System.out.println(s); //Output : 55
7
8 Short S = new Short("23");
9 s = S.shortValue();
10 System.out.println(s); //Output : 23
11
12 Integer I = new Integer("56");

13 s = I.shortValue();
System.out.println(s); //Output : 56
14
15
Long L = new Long("125");
16
s = L.shortValue();
17
System.out.println(s); //Output : 125
18
19
Float F = new Float("23.56");
20 s = F.shortValue();
21 System.out.println(s); //Output : 23 (value is truncated)
22
23 Double D = new Double("521.56");

24 s = D.shortValue();

25 System.out.println(s); //Output : 521 (value is truncated


}
26
}
27
28
29

Auto-Widening Vs Auto-Boxing Vs Auto-UpCasting In


Java
pramodbablad June 10, 2014 6

Just go through the following example,

1 public class WrapperClasses

2 {
3 static void overloadedMethod(Integer I)

4 {
System.out.println("Integer Wrapper Class Type");
5
}
6
7
static void overloadedMethod(long l)
8
{
9
System.out.println("long primitive type");
10 }
11
12 public static void main(String[] args)
13 {

14 int i = 21;

15
16 overloadedMethod(i);
}
17
}
18
19

In the above example, ‘overloadedMethod’ is overloaded. One method takes Integer wrapper class
type as an argument and another method takes primitive long type as an argument. In the main
method, we are calling this ‘overloadedMethod’ by passing primitive int type as an argument. When
you run this program, you will get “long primitive type” as output. That means, auto-widening is
happening not auto-boxing.

Now, make little modification to the above example. Change the argument of second method from
primitive long type to Long wrapper class type.

1 public class WrapperClasses


2 {
3 static void overloadedMethod(Integer I)

4 {

5 System.out.println("Integer Wrapper Class Type");


}
6
7
8 static void overloadedMethod(Long L)

9 {
System.out.println("Long Wrapper Class Type");
10
}
11
12
public static void main(String[] args)
13
{
14
int i = 21;
15
16 overloadedMethod(i);
17 }
18 }

19

Now run this program. you will get “Integer Wrapper Class Type” as output. That means auto-boxing
is happening.

Now, make one more modification to the above program. Change the argument of first method from
Integer Wrapper Class Type to Double Wrapper Class Type.

1 public class WrapperClasses

2 {
static void overloadedMethod(Double D)
3
{
4
System.out.println("Double Wrapper Class Type");
5
}
6
7
static void overloadedMethod(Long L)
8 {
9 System.out.println("Long Wrapper Class Type");
10 }

11
12 public static void main(String[] args)

13 {
int i = 21;
14
15
overloadedMethod(i); //compile time error
16
}
17
}
18
19

Above example gives compile time error. Because, there is no method definition which takes int type
as an argument. Primitive int type can be auto-widened to big sized primitive types or can be auto-
boxed to Integer wrapper class type but can not be converted into Double or Long wrapper class type.

Now, add one more overloadedMethod which takes Number Class type as an argument to the above
class.

1 public class WrapperClasses


2 {

3 static void overloadedMethod(Number N)

4 {
System.out.println("Number Class Type");
5
}
6
7
static void overloadedMethod(Double D)
8
{
9
System.out.println("Double Wrapper Class Type");
10 }
11
12 static void overloadedMethod(Long L)
13 {

14 System.out.println("Long Wrapper Class Type");

15 }

16
17 public static void main(String[] args)

18 {
int i = 21;
19
20
overloadedMethod(i);
21
}
22
}
23
24

Now run this program, you will get “Number Class Type” as output. What happened here is,
internally primitive int type is auto-boxed to Integer type and Integer type is auto-UpCasted to
Number type as Integer wrapper class is a sub class of Number class.

Above examples can be summarized like below,

o If you are passing primitive data type as an argument to the method call, compiler first
checks for a method definition which takes same data type as an argument.
o If such method does not exist, then it checks for the method definition which takes big sized
primitive data type than passed data type. i.e It tries to perform auto-widening
conversion of passed data type.
o If auto-widening conversion is not possible, then it checks for method definition which takes
corresponding wrapper class type as an argument. i.e It tries to perform auto-boxing
conversion.
o If such method does not exist, then it checks for the method which takes super class type
(Number or Object type) as an argument.
o If such method also does not exist, then compiler gives compile time error.

It can be diagrammatically represented as,


isNaN() And isInfinite() Methods In Java
pramodbablad July 10, 2014 0

isNaN() and isInfinite() methods are the static members of java.lang.Double and
java.lang.Float classes. Both these two wrapper classes have their own version of these
two methods.

Before discussing about these two methods, let’s get to know


about NaN, POSITIVE_INFINITY and NEGATIVE_INFINITY.

NaN, POSITIVE_INFINITY and NEGATIVE_INFINITY are static and final constants of


java.lang.Double and java.lang.Float wrapper classes.

NaN : This constant holds Not-a-Number value of specified type. It represents


mathematically undefined or unrepresentable number such as number obtained by dividing
zero by zero or square root of a negative number.
POSITIVE_INFINITY : This constant holds positive infinity value.

NEGATIVE_INFINITY : This constant holds negative infinity value.

Following example shows usage of these three constants.

1
public class IsNanAndIsInfinite
2 {
3 public static void main(String[] args)
4 {

5 //Assigning Not-A-Number value of type double to d1

6 double d1 = Double.NaN;

7
System.out.println(d1); //Output : NaN
8
9
//Assigning positive infinity value of type double to d2
10
double d2 = Double.POSITIVE_INFINITY;
11
12
System.out.println(d2); //Output : Infinity
13
14
//Assigning negative infinity value of type double to d3
15 double d3 = Double.NEGATIVE_INFINITY;
16
17 System.out.println(d3); //Output : -Infinity
18
19 //Assigning Not-A-Number value of type float to f1

20 float f1 = Float.NaN;

21
22 System.out.println(f1); //Output : NaN

23
//Assigning positive infinity value of type float to f2
24
float f2 = Float.POSITIVE_INFINITY;
25
26
27 System.out.println(f2); //Output : Infinity

28
29 //Assigning negative infinity value of type float to f3
float f3 = Float.NEGATIVE_INFINITY;
30
31
System.out.println(f3); //Output : -Infinity
32
}
33
}
34
35

isNaN() :
This method returns true, if the specified number is Not-a-Number i.e mathematically
undefined or unrepresentable number. Otherwise it returns false. Both, Double and Float
wrapper classes have this method.

1
public class IsNanAndIsInfinite
2
{
3 public static void main(String[] args)
4 {
5 double d = 0.0/0.0;

6
7 System.out.println(Double.isNaN(d)); //Output : true

8
9 d = Math.sqrt(-1.2);

10
System.out.println(Double.isNaN(d)); //Output : true
11
12
float f = 0.0f/0.0f;
13
14
System.out.println(Float.isNaN(f)); //Output : true
15
16
17 f = 0 * Float.POSITIVE_INFINITY;

18
19 System.out.println(Float.isNaN(f)); //Output : true
}
20
}
21

isInfinite() :
This method returns true if the specified number is positively or negatively infinite. Both
Double and Float wrapper classes have this method.

1 public class IsNanAndIsInfinite

2 {

3 public static void main(String[] args)

4 {
double d = Double.POSITIVE_INFINITY / 0.0;
5
6
System.out.println(Double.isInfinite(d)); //Output : true
7
8
d = Double.NEGATIVE_INFINITY / 0.0;
9
10
System.out.println(Double.isInfinite(d)); //Output : true
11
12
float f = Float.POSITIVE_INFINITY * 2.2f;
13
14 System.out.println(Float.isInfinite(f)); //Output : true
15
16 f = Float.NEGATIVE_INFINITY * 4.12f;

17
18 System.out.println(Float.isInfinite(f)); //Output : true

19 }
20 }

21

Introduction To Strings
pramodbablad August 25, 2014 17

String represents sequence of characters enclosed within the double


quotes. “abc”, “JAVA”, “123”, “A” are some examples of strings. In many languages, strings are
treated as character arrays. But In java, strings are treated as objects. To create and manipulate the
strings, Java provides three classes.

1) java.lang.String (From JDK 1.0)

2) java.lang.StringBuffer (From JDK 1.5)

3) java.lang.StringBuilder (From JDK 1.5)

Let’s discuss some introductory points about these three classes.

1) All these three classes are members of java.lang package and they are final classes. That means
you can’t create subclasses to these three classes.

2) All three classes implement Serializable and CharSequence interface.

3) java.lang.String objects are immutable in java. That is, once you create String objects, you can’t
modify them. Whenever you try to modify the existing String object, a new String object is created
with modifications. Existing object is not at all altered. Where
as java.lang.StringBuffer and java.lang.StringBuilder objects are mutable. That means, you can
perform modifications to existing objects.

4) Only String and StringBuffer objects are thread safe. StringBuilder objects are not thread safe.
So whenever you want immutable and thread safe string objects, use java.lang.String class and
whenever you want mutable as well as thread safe string objects then use java.lang.StringBuffer class.

5) In all three classes, toString() method is overrided. So. whenever you use reference variables of
these three types, they will return contents of the objects not physical address of the objects.

6) hashCode() and equals() methods are overrided only in java.lang.String class but not
in java.lang.StringBuffer and java.lang.StringBuilder classes.

7) There is no reverse() and delete() methods in String class. But, StringBuffer and StringBuilder
have reverse() and delete() methods.

8) In case of String class, you can create the objects without new operator. But in case of StringBuffer
and StringBuilder class, you have to use new operator to create the objects.
Exploring java.lang.String Class : Constructors Of
String Class
pramodbablad August 26, 2014 1

In the previous article, we have seen that java.lang.String class is a final class. It’s objects are
immutable. As they are immutable, they are also thread safety. In this article, we will discuss some of
the methods and constructors of the String class which are used to create and manipulate the string
objects.

Constructors Of java.lang.String Class :


There are total 13 constructors in java.lang.String class. It provides many ways to create the string
objects. You can refer all constructors of String class here.

Here are some mostly used constructors of String class.

If you want to create an empty string object, then use no-arg constructor of String class.

String s = new String(); //It creates a string object without characters


1 it.

Below constructor takes character array as an argument.

char[] chars = {'J', 'A', 'V', 'A'}; //Character Array


1
String s = new String(chars); //Creating a String object by passing charac
2 argument

Below constructor takes string as an argument.

String s = new String("JAVA"); //Creating a string object by passing string


1 argument

This constructor takes StringBuffer type as an argument.

StringBuffer strBuff = new StringBuffer("abc");


1
String s = new String(strBuff); //Creating a string object by passing Strin
2 an argument
This constructor takes StringBuilder type as an argument.

StringBuilder strBldr = new StringBuilder("abc");


1
String s = new String(strBldr); //Creating a string object by passing Strin
2 argument.

String Literals :
In Java, all string literals like “java”, “abc”, “123” are treated as objects of java.lang.String class. That
means, all methods of String class are also applicable to string literals.
You can also create the objects of String class without using new operator. This can be done by
assigning a string literal to reference variable of type java.lang.String class.

1
public class StringExamples
2
{
3
public static void main(String[] args)
4
{
5 //Creating String objects without using new operator
6
7 String s1 = "abc";
8
9 String s2 = "abc"+"def";

10
11 String s3 = "123"+"A"+"B";

12
13 System.out.println(s1); //Output : abc

14
System.out.println(s2); //Output : abcdef
15
16
System.out.println(s3); //Output : 123AB
17
}
18
}
19
Finding The Length Of The String :
length() method of String class is used to find the length of the string. The length of the string is the
number of characters in it.

1 public class StringExamples

2 {
public static void main(String[] args)
3
{
4
String s = new String(); //Creating an empty stri
5 object
6 System.out.println(s.length()); //Output : 0

7
8 char[] chars = {'J', 'A', 'V', 'A'};

9 String s1 = new String(chars); //Creating string object o


characters
10 System.out.println(s1.length()); //Output : 4
11
12 String s2 = new String(s1+"J2EE"); //Creating string object of
characters
13
System.out.println(s2.length()); //Output : 8
14
15
//Using String.length() method on string literals
16
17
System.out.println("abc".length()); //Output : 3
18
19
System.out.println("123456".length()); //Output : 6
20
21 System.out.println("A".length()); //Output : 1
22 }
23 }

(Contd…)
Exploring java.lang.String Class : Concatenation Of
Strings
pramodbablad August 29, 2014 4

Concatenation Of Strings :
o The “+” operator is used to concatenate two or more string objects or string literals.
?

public class StringExamples


1
{
2
public static void main(String[] args)
3
{
4 //Concatenating five string literals using "+" operator
5
6 String s = "Java"+"Concept"+"Of"+"The"+"Day";
7
8 System.out.println(s); //Output : JavaConceptOfTheDay

9
10 //Creating five string objects

11
12 String s1 = new String("Java");

13
String s2 = new String("Concept");
14
15
String s3 = new String("Of");
16
17
String s4 = new String("The");
18
19
String s5 = new String("Day");
20
21
//Concatenating five string objects using "+" operator
22
23 System.out.println(s1+s2+s3+s4+s5); //Output : JavaConceptOfTh

24 }
}
25
26
27
o You can concatenate a string object with other data types like int, double, long, char etc
using “+” operator. There is a one rule of “+” operator which states that “If any one
operand of ‘+’ operator is a string, then it will be string concatenation otherwise it will be
a normal addition”. The same rule applies here also.
?

1 public class StringExamples

2 {

3 public static void main(String[] args)

4 {
//Concatenating a string object with int type
5
6
int i = 1000;
7
8
String s = "Java"+i;
9
10
System.out.println(s); //Output : Java1000
11
12
//Concatenating a string object with double type
13
14 double d = 523.69;
15
16 String s1 = "Java"+d;

17
18 System.out.println(s1); //Output : Java523.69

19
20 //Concatenating a string object with char type

21
22 char c = 'A';

23
24 String s2 = "Java"+c;

25
System.out.println(s2); //Output : JavaA
26
27
//Concatenating a string object with boolean type
28
29
boolean b = true;
30
31
String s3 = "Java"+b;
32
33
System.out.println(s3); //Output : Javatrue
34 }
35 }
36
37
o You can concatenate a string object not only with primitive types but also with the derived
types. When you use derived type in the string concatenation, the string returned by the
toString() method of that derived type is used.
?

1 package strings;

2
class A
3
{
4
int i;
5
6
public A(int i)
7
{
8 this.i = i;
9 }
10
11 //toString() method is not overrided.

12 //So, it will return physical address of the object


}
13
14
class B
15
{
16
int i;
17
18
public B(int i)
19 {
20 this.i = i;
21 }

22
23 //Overriding toString() method

24
25 @Override
public String toString()
26
{
27
return "i = "+i;
28
}
29
}
30
31 public class StringExamples
32 {
33 public static void main(String[] args)

34 {

35 A a = new A(50);

36
String s = "Java";
37
38
//Concatenating a string object with A-type
39
40
41 System.out.println(s+a); //Output : Javastrings.A@42719c

42
43 B b = new B(100);

44
//Concatenating string object with B-type
45
46
System.out.println(s+b); //Output : Javai = 100
47
}
48
}
49
50
51
52
o When you are adding two or more objects of different types using “+” operator, addition of
the objects takes place from left to right. While adding, if any one operand is string then it
will be string concatenation otherwise it will be normal addition.
?

1 public class StringExamples

2 {
public static void main(String[] args)
3
{
4
int i = 5000;
5
6
double d = 6000.0006;
7
8
String s = "Java";
9
10 System.out.println(i+d+s); //Output : 11000.0006Java
11
12 System.out.println(s+i+d); //Output : Java50006000.0006
13
14 System.out.println(i+s+d); //Output : 5000Java6000.0006

15 }
}
16
17
o Can we concatenate the string objects without using “+” operator?.
Yes, we can concatenate string objects without using “+” operator. This can be done
using concat() method of java.lang.String class. But using concat() method, we can
concatenate only two string objects. It is not possible to concatenate more than two string
objects using concat() method. And also using concat() method we can’t concatenate a
string object with other type of object. Because, concat() method takes only String type as
an argument.
?

1
public class StringExamples
2
{
3 public static void main(String[] args)
4 {

5 String s1 = "JAVA";

6
7 String s2 = "J2EE";

8
System.out.println(s1.concat(s2)); //Output : JAVAJ2EE
9
}
10
}
11
o Here is one special example of String concatenation. You can add two null objects referred
by two String type reference variables (Like in Line 9 in the below example) , but you can’t
add two hard coded null objects (Like in Line 15 in the below example). It gives compile time
error.
?

public class StringExamples


1
{
2
public static void main(String[] args)
3
{
4
String s1 = null;
5
6 String s2 = null;
7
8 System.out.println(s1+s2); //Output : nullnull

9
10 System.out.println("null"+"null"); //Output : nullnull

11
System.out.println(s1+"JAVA"+s2); //Output : nullJAVAnull
12
13
// System.out.println(null+null); //Compile Time Error
14
}
15
}
16
17

Exploring java.lang.String Class : Character Extraction


pramodbablad August 30, 2014 0

java.lang.String class provides many methods to extract the characters from a string object. The
characters in the string object are not stored like character array where each character is indexed. But,
many string methods use indexes to address the characters in the string object. Like array, The index
of string also starts from 0 (Zero).

Below are some methods which are used to extract characters from a string object.

1) charAt() Method :
This method returns character at the specified index. Here is signature of this method.

public char charAt(int index)

Where index must be between 0 and length() – 1. This method will


throw StringIndexOutOfBoundsException if index passed is negative or not less than the length of
the string.

1 public class StringExamples

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

4 {
String s = "Java Concept Of The Day";
5
6
System.out.println(s.charAt(5)); //Output : C
7
8
System.out.println(s.charAt(10)); //Output : p
9
10
System.out.println(s.charAt(25)); //This statement will throw
11 StringIndexOutOfBoundsException

12 }

13 }

2) getChars() Method
This method copies the set of characters from the string into specified character array. Here is the
signature of this method.

public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

This method copies characters of a string object starting from ‘srcBegin’ to ‘srcEnd’ into character
array ‘dst’ at the index ‘dstBegin’. This method will also
throw StringIndexOutOfBoundsException if ‘srcBegin’ or ‘srcEnd’ are not between 0 and length()
– 1 or if characters extracted does not fit into destination array.

1 public class StringExamples


{
2
public static void main(String[] args)
3
{
4
String s = "Java Concept Of The Day";
5
6
//Defining destination char array
7
8 char[] dst = new char[10];
9
10 //Copying the set of characters from s into dst.
11
12 s.getChars(5, 11, dst, 2);

13
14 for (char c : dst)
{
15
System.out.print(c); //Output : --Concep--
16
}
17
}
18
}
19
20

3) toCharArray() Method :
This method converts whole string into a character array. Below is the signature of this method.

public char[] toCharArray()

public class StringExamples


1
{
2
public static void main(String[] args)
3
{
4 String s = "Java Concept Of The Day";
5
6 //Converting string 's' into character array.

7
8 char[] dst = s.toCharArray();

9
10 for (char c : dst)

11 {
System.out.print(c); //Output : Java Concept Of The Day
12
}
13
}
14
}
15
16

4) subString() Method
This method returns a sub string of the specified string. This method has two forms.

public String substring(int beginIndex) –> This form returns sub string starting
from ‘beginIndex’ to the end of the specified string.

public String substring(int beginIndex, int endIndex) –> This form returns sub string starting
from ‘beginIndex’ to ‘endIndex’ of the specified string.

1
public class StringExamples
2
{
3
public static void main(String[] args)
4 {
5 String s = "Java Concept Of The Day";

6
7 String subString1 = s.substring(11);

8
9 System.out.println(subString1); //Output : t Of The Day

10
11 String subString2 = s.substring(5, 15);

12
System.out.println(subString2); //Output : Concept Of
13
}
14
}
15

How The Strings Are Stored In The Memory?


pramodbablad September 1, 2014 25

In Java, strings are special. Java gives some special attention to string types that no other types enjoy
such attention. For example, to create the string objects you need not to use ‘new‘ keyword. Where as
to create other type of objects you have to use ‘new’ keyword. Like this, strings enjoy some special
attention by the java. This attention is worth the while, because the strings are used almost
everywhere while developing any kind of applications.

While storing the string objects in the memory also, they are specially treated by the Java. After
reading this article, you will come to know how they are specially treated in the memory.

We all know that JVM divides the allocated memory to a Java program into two parts. one
is Stack and another one is heap. Stack is used for execution purpose and heap is used for storage
purpose. In that heap memory, JVM allocates some memory specially meant for string literals. This
part of the heap memory is called String Constant Pool.

Whenever you create a string object using string literal, that object is stored in the string
constant pool and whenever you create a string object using new keyword, such object is stored in
the heap memory.

For example, when you create string objects like below, they will be stored in the String Constant
Pool.

?
1 String s1 = "abc";
2
3 String s2 = "xyz";
4
5 String s3 = "123";
6
String s4 = "A";
7
And when you create string objects using new keyword like below, they will be stored in the heap
memory.

?
1 String s5 = new String("abc");
2
3 char[] c = {'J', 'A', 'V', 'A'};
4
5 String s6 = new String(c);
6
String s7 = new String(new StringBuffer());
7
This is how String Constant Pool looks like in the memory.

One more interesting thing about String Constant Pool is that, pool space is allocated to an object
depending upon it’s content. There will be no two objects in the pool having the same content.

This is what happens when you create string objects using string literal,

“When you create a string object using string literal, JVM first checks the content of to be
created object. If there exist an object in the pool with the same content, then it returns the
reference of that object. It doesn’t create new object. If the content is different from the existing
objects then only it creates new object.”

But, when you create string objects using new keyword, a new object is created whether the content is
same or not.

This can be proved by using “==” operator. As “==” operator returns true if two objects have same
physical address in the memory otherwise it will return false. In the below example, s1 and s2 are
created using string literal “abc”. So, s1 == s2 returns true. Where as s3 and s4 are created using new
operator having the same content. But, s3 == s4 returns false.

?
1 public class StringExamples
{
2 public static void main(String[] args)
3 {
4 //Creating string objects using literals
5
6 String s1 = "abc";
7
String s2 = "abc";
8
9 System.out.println(s1 == s2); //Output : true
10
11 //Creating string objects using new operator
12
13 String s3 = new String("abc");
14
15 String s4 = new String("abc");
16 System.out.println(s3 == s4); //Output : false
17 }
18 }
19
20
21
In simple words, there can not be two string objects with same content in the string constant
pool. But, there can be two string objects with the same content in the heap memory.

An Example To Prove Strings Are Immutable


pramodbablad September 2, 2014 12

One more interesting thing about String objects in java is that they are immutable. That means once
you create a string object, you can’t modify the contents of that object. If you try to modify the
contents of string object, a new string object is created with modified content.

In this article, We will discuss the examples which prove that strings are immutable.

An Example To Prove Strings Are Immutable :


First, create one string object ‘s1’ using string literal “JAVA”.

1 String s1 = "JAVA";

Create one more string object ‘s2’ using the same string literal “JAVA”.

?
1 String s2 = "JAVA";

We have seen in the previous article that string objects created using string literal are stored in
the String Constant Pool and any two objects in the pool can’t have same content. Here s1 and s2 are
created using same literal. Therefore, they will be pointing to same object in the pool. Then s1 == s2
should return true.

1 System.out.println(s1 == s2); //Output : true

Now, I want to make little modification to this object through ‘s1’ reference. I want to append “J2EE”
at end of this string through ‘s1’. That can be done like below,

1 s1 =s1 + "J2EE";

This statement appends “J2EE” to the object to which s1 is pointing and re-assigns reference of that
object back to s1.

Now, compare physical address of s1 and s2 using “==” operator. This time it will return false.

1 System.out.println(s1 == s2); //Output : false

That means now both s1 and s2 are pointing to two different objects in the pool. Before modifications
they are pointing to same object. Once we tried to change the content of the object using ‘s1’, a new
object is created in the pool with “JAVAJ2EE” as it’s content and it’s reference is assigned to s1. If
the strings are mutable, both s1 and s2 should point to same object even after modification. That never
happened here. That proves the string objects are immutable in java.

The whole program can be written like this,

public class StringExamples


1
{
2
public static void main(String[] args)
3
{
4
String s1 = "JAVA";
5
6
String s2 = "JAVA";
7
8 System.out.println(s1 == s2); //Output : true
9
10 s1 = s1 + "J2EE";

11
12 System.out.println(s1 == s2); //Output : false
}
13
}
14
15

This is how it looks like in the memory.

is new String() also immutable?


After seeing the above example, one more question may left in your mind. Are string objects
created using new operator also immutable? The answer is Yes. String objects created using new
operator are also immutable although they are stored in the heap memory. This can be also proved
with help of an example.

1 public class StringExamples


2 {

3 public static void main(String[] args)


{
4
String s1 = new String("JAVA");
5
6
System.out.println(s1); //Output : JAVA
7
8
s1.concat("J2EE");
9
10
System.out.println(s1); //Output : JAVA
11 }
12 }
13

In this example, a string object is created with “JAVA” as it’s content using new operator and it’s
reference is assigned to s1. I have tried to change the contents of this object using concat() method.
But, these changes are not reflected in the object as seen in Line 11. Even after the concatenation,
content of the object is same as before. This is because the strings are immutable. Once I tried to
concatenate “J2EE” to an existing string “JAVA”, a new string object is created with “JAVAJ2EE” as
it’s content. But we don’t have reference to that object in this program.

Conclusion :
Immutability is the fundamental property of string objects. In whatever way you create the
string objects, either using string literals or using new operator, they are immutable.

When To Use “==”, equals() And hashCode() On


Strings
pramodbablad September 3, 2014 4

“==” operator, equals() method and hashcode() methods are used to check the equality of any type
of objects in Java. In this article, we will discuss which is the better way to check the equality of two
string objects.
“==” operator compares the two objects on their physical address. That means if two references are
pointing to same object in the memory, then comparing those two references using “==” operator will
return true. For example, if s1 and s2 are two references pointing to same object in the memory, then
invoking s1 == s2 will return true. This type of comparison is called “Shallow Comparison”.

equals() method, if not overrided, will perform same comparison as “==” operator does i.e
comparing the objects on their physical address. So, it is always recommended that you should
override equals() method in your class so that it provides field by field comparison of two objects.
This type of comparison is called “Deep Comparison”.

In java.lang.String class, equals() method is overrided to provide the comparison of two string objects
based on their contents. That means, any two string objects having same content will be equal
according to equals() method. For example, if s1 and s2 are two string objects having the same
content, then invoking s1.equals(s2) will return true.

hashCode() method returns hash code value of an object in the Integer form. It is recommended that
whenever you override equals() method, you should also override hashCode() method so that two
equal objects according to equals() method must return same hash code values. This is the general
contract between equals() and hashCode() methods that must be maintained all the time.

In java.lang.String class, hashCode() method is also overrided so that two equal string objects
according to equals() method will return same hash code values. That means, if s1 and s2 are two
equal string objects according to equals() method, then invoking s1.hashCode() ==
s2.hashCode() will return true.

Let’s apply these three methods on string objects and try to analyse their output.

Define two string objects like below,

1 String s1 = "JAVA";

2
3 String s2 = "JAVA";

Now apply above methods on these two objects.

s1 == s2 —> will return true as both are pointing to same object in the constant pool.
s1.equals(s2) —> will also return true as both are referring to same object.
s1.hashCode() == s2.hashCode() —> It also returns true.

This type of comparison is straight forward. There is no speculation about this


comparison. Let’s define the string objects like below,

1 String s1 = new String("JAVA");

2
3 String s2 = new String("JAVA");
s1 == s2 —> will return false because s1 and s2 are referring to two different objects in the memory.
s1.equals(s2) —> will return true as both the objects have same content.
s1.hashCode() == s2.hashCode() —> It will also return true because two equals string objects
according to equals() method will have same hash code values.

Comparing the string objects defined like below will also give same result as the above.

1 String s1 = "JAVA";

2
3 String s2 = new String("JAVA");

s1 == s2 —> will return false because s1 and s2 are referring to two different objects in the memory.
s1.equals(s2) —> will return true as both the objects have same content.
s1.hashCode() == s2.hashCode() —> It will also return true.

Now, you may conclude that If there is a requirement of comparing two string objects on their
physical address, then use “==” operator and if there is a requirement of comparing two string objects
on their contents, then use equals() method or hashCode() method.

Hold on…. Before jumping onto conclusion, compare these two string objects.

1 String s1 = "0-42L";

2
3 String s2 = "0-43-";

s1 == s2 —> will return false as s1 and s2 are referring to two different objects in the
memory. (Expected…)
s1.equals(s2) —> It will also return false as both the objects have different content. (Expected…)
s1.hashCode() == s2.hashCode() —> It will return true. (???….)

This is because, two unequal string objects according to equals() method may have same hash
code values. Therefore, it is recommended not to use hashCode() method to compare two string
objects. You may not get expected result.

Conclusion :
When you want to check the equality of two string objects on their physical existence in the memory,
then use “==” operator. If you want to check the equality of two string objects depending upon their
contents, then use equals() method. It is recommended not to use hashCode() method to check the
equality of two string objects. You may get unexpected result.
How StringBuffer And StringBuilder Differ From
String Class
pramodbablad September 4, 2014 2

String objects created using java.lang.String class are immutable. Once they are created,
they can not be modified. If you try to modify them, a new string object will be created
with modified content. This property of String class may cause some memory issues for
applications which need frequent modification of string objects. To overcome this
behavior of String class, two more classes are introduced in Java to represent the strings.
They are StringBuffer and StringBuilder. Both these classes are also members
of java.lang package same as String class.

In this article, I have tried to figure out how these two classes differ from String class.

Immutability :
This is main reason why StringBuffer and StringBuilder are introduced. As objects of String
class are immutable, objects of StringBuffer and StringBuilder class are mutable. You can
change the contents of StringBuffer and StringBuider objects at any time of execution.
When you change the content, new objects are not created. Instead of that the changes
are applied to existing object. Thus solving memory issues may caused by String class.

Object Creation :
You have to use ‘new‘ operator to create objects to StringBuffer and StringBuilder classes.
You can’t use string literals to create objects to these classes. For example, you can’t
write StringBuffer sb = “JAVA” or StringBuilder sb = “JAVA”. It gives compile time
error. But, you can use both string literals and new operator to create objects to String
class.

Storage Area :
As objects of StringBuffer and StringBuilder are created using only new operator, they are
stored in heap memory. Where as objects of String class are created using both string
literals and new operator, they are stored in string constant pool as well as heap memory.

Thread Safety :
Any immutable object in java is thread safety. Because they are unchangeable once they
are created. Any type of thread can’t change the content of immutable object. This
applies to objects of String class also. Of the StringBuffer and StringBuilder objects, only
StringBuffer objects are thread safety. All necessary methods in StringBuffer class are
synchronized so that only one thread can enter into it’s object at any point of time.
Where as StringBuilder objects are not thread safety.
Performance :
Because of thread safety property of String and StringBuffer classes, they reduces the
performance of multithreaded applications. Because, multiple threads can’t enter into
objects of these classes simultaneously. One thread has to wait until another thread is
finished with them. But, you will not find performance problems if you use StringBuilder
class. Becuase, multiple threads can enter into objects of this class. But, be aware that
StringBuilder is not thread safety.

String Concatenation :
There will be serious performance issues when you are performing lots of string
concatenation using String class. This is because, each time you perform string
concatenation using string class, a new object will be created with the
concatenated string. This slows down an application. But, if you use either StringBuffer or
StringBuilder instead of String class, your application will perform better. Below program
shows time taken by all three classes to perform string concatenation 10000 times.

1 public class StringExamples


{
2
public static void main(String[] args)
3
{
4
String s = "JAVA";
5
6
long startTime = System.currentTimeMillis();
7
8 for(int i = 0; i <= 10000; i++)
9 {
10 s = s + "J2EE";

11 }

12
13 long endTime = System.currentTimeMillis();

14
System.out.println("Time taken by String class : "+(endTime - start
15
ms");
16
17 StringBuffer sb = new StringBuffer("JAVA");
18
19 startTime = System.currentTimeMillis();

20
21 for(int i = 0; i <= 10000; i++)
{
22
sb.append("J2EE");
23
}
24
25
endTime = System.currentTimeMillis();
26
27
System.out.println("Time taken by StringBuffer class : "+(endTime -
28 startTime)+" ms");

29
30 StringBuilder sb1 = new StringBuilder("JAVA");

31
startTime = System.currentTimeMillis();
32
33
for(int i = 0; i <= 10000; i++)
34
{
35
sb1.append("J2EE");
36
}
37
38 endTime = System.currentTimeMillis();
39
40 System.out.println("Time taken by StringBuilder class : "+(endTime
startTime)+" ms");
41
}
42
}
43
44

Output :
Time taken by String class : 429 ms
Time taken by StringBuffer class : 2 ms
Time taken by StringBuilder class : 0 ms
Therefore, when you are performing lots of string concatenation in your application, it is
better to use StringBuffer class (if you need thread safety) or StringBuilder class (If you
don’t need thread safety).

equals() and hashCode() Methods :


In StringBuffer and StringBuilder classes, equals() and hashCode methods are not
overrided. Where as in String class they are overrided.

toString() Method :
toString() method is overrided in all three classes. You can also convert StringBuffer and
StringBuilder objects to String type by calling toString() method on them.

What Is String Intern In Java?


pramodbablad September 5, 2014 7

String objects in java are stored in two places in memory. One is String Constant Pool and
another one is Heap Memory. String objects created using string literals are stored in
String Constant Pool where as string objects created using new operator are stored in heap
memory.

Why You Need String Constant Pool? :


String objects are most used objects in the development of any kind of applications.
Therefore, there has to be a special arrangement to store these objects. String Constant
Pool is one such special arrangement. In string constant pool, there will be no two objects
with the same content. Heap memory can have any number of objects with same content.

Just imagine creating 1000 string objects with same content in heap memory and one
string object with that content in String Constant Pool. Which one saves the memory?.
which one will save the time?. Which one will be accessed faster?. It is, of course, String
Constant Pool. That’s why you need String Constant Pool.

What Is String Intern? :


String intern or simply intern refers to string object in the String Constant
Pool. Interning is the process of creating a string object in String Constant Pool which will
be exact copy of string object in heap memory.

intern() Method :
intern() method of java.lang.String class is used to perform interning i.e creating an exact
copy of heap string object in string constant pool. When you call this method on a string
object, first it checks whether there exist an object with the same content in the String
Constant Pool. If object does not exist in the pool, it will create an object with the same
content in the string constant pool and returns the reference of that object. If object exist
in the pool than it returns reference of that object without creating a new object.

Look at the below example. Object ‘s1’ will be created in heap memory as we are using
new operator to create it. When we call intern() method on s1, it creates a new string
object in the string constant pool with “JAVA” as it’s content and assigns it’s reference to
s2. So, s1 == s2 will return false because they are two different objects in the memory
and s1.equals(s2) will return true because they have same content.

1
public class StringExamples
2
{
3 public static void main(String[] args)
4 {
5 String s1 = new String("JAVA");

6
7 String s2 = s1.intern(); //Creating String Intern

8
9 System.out.println(s1 == s2); //Output : false

10
System.out.println(s1.equals(s2)); //Output : true
11
}
12
}
13

Look at this example. Object s1 will be created in string constant pool as we are using
string literal to create it and object s2 will be created in heap memory as we are using
new operator to create it. When you call intern() method on s2, it returns reference of
object to which s1 is pointing as it’s content is same as s2. It does not create a new object
in the pool. So, S1 == s3 will return true as both are pointing to same object in the pool.

1 public class StringExamples


2 {

3 public static void main(String[] args)

4 {

5 String s1 = "JAVA";

6
7 String s2 = new String("JAVA");

8
9 String s3 = s2.intern(); //Creating String Intern

10
System.out.println(s1 == s3); //Output : true
11
}
12
}
13

String Literals Are Automatically Interned :


When you call intern() on the string object created using string literals it returns reference
of itself. Because, you can’t have two string objects in the pool with same content. That
means string literals are automatically interned in java.

1
public class StringExamples
2
{
3 public static void main(String[] args)
4 {

5 String s1 = "JAVA";

6
7 String s2 = s1.intern(); //Creating String Intern

8
9 System.out.println(s1 == s2); //Output : true
}
10
}
11

What is the use of interning the string?


To Save The memory Space :

Using interned string, you can save the memory space. If you are using lots of string
objects with same content in your code, than it is better to create an intern of that string
in the pool. Use that intern string whenever you need it instead of creating a new object
in the heap. It saves the memory space.

For Faster Comparison :


Assume that there are two string objects s1 and s2 in heap memory and you need to
perform comparison of these two objects more often in your code. Then using s1.intern()
== s2.intern() will be more fast then s1.equals(s2). Because, equals() method performs
character by character comparison where as “==” operator just compares references of
objects.

20 Things You Should Know About Strings In Java


pramodbablad February 17, 2015 6

Strings in java are most used data types while developing any kind of applications. Hence, strings are
treated as very special in java. This article contains 20 important points about strings in java. These
points are also most discussed ones in the java interviews.

1) In Java, you can create string objects in two ways. One is using new operator and another one is
using string literals.

?
String s1 = "abc"; //Creating string object using string literal
1
2 String s2 = new String("abc"); //Creating string object using new
3 operator

2) String objects created using string literals are stored in String Constant Pool and string objects
created using new operator are stored in the heap memory. Click here to see how strings are stored in
the memory.

3) What Is String Constant Pool?

String objects are most used data objects in Java. Hence, java has a special arrangement to store the
string objects. String Constant Pool is one such arrangement. String Constant Pool is the memory
space in heap memory specially allocated to store the string objects created using string literals. In
String Constant Pool, there will be no two string objects having the same content.

Whenever you create a string object using string literal, JVM first checks the content of the object to
be created. If there exist an object in the string constant pool with the same content, then it returns the
reference of that object. It doesn’t create a new object. If the content is different from the existing
objects then only it creates new object.

4) String is a derived type, not a primitive type like int, double etc. Strings are objects in java.

5) String objects in java are immutable. That means, once you create String objects, you can’t modify
them. If you try to modify them, a new object will be created with modifications.

6) To overcome the immutability of String objects, two more classes are introduced in Java. They
are StringBuffer and StringBuilder classes. Objects of StringBuffer and StringBuilder class are
mutable.
7) All three classes – String, StringBuffer and StringBuilder are final. That means you can’t extend
them. All three classes are members of java.lang package.

8) In all three classes – String, StringBuffer and StringBuilder, toString() method is overridden. That
means, whenever you use references to objects of these classes, actual content of those objects will be
retrieved.

9) equals() and hashCode() methods are overridden in String class but they are not overridden in
StringBuffer and StringBuilder classes.

10) String and StringBuffer objects are thread safety where as StringBuilder objects are not thread
safety.

11) Using “==“, equals() and hashCode() on String objects.

All three – “==”, equals() and hashCode() are used to check the equality of two string objects. If you
want to check the equality of two string objects based on their physical address, then use “==”
operator. If you want to check the equality of two string objects based on their content, then use
equals() method. It is recommended not to use hashCode() method to compare the string objects. You
may get unexpected results. Click here to see when to use “==”, equals() and hashcode() on strings.

12) Strings in java are backed by character array. You can retrieve this array using toCharArray()
method of String class.

13) If you are performing lots of string concatenation in your code, then use either StringBuffer or
StringBuilder classes. These two classes give better performance than String class. Click here to see
the differences between String, StringBuffer and StringBuilder classes.

14) Java doesn’t support operator overloading except ‘+‘ operator. ‘+‘ can be used for number
addition as well as to concatenate two string objects. This is the special treatment given by the Java to
string objects.

15) Java provides 4 methods to compare the strings.

1) equals() – This method returns true if contents of two string objects are same.
2) equalsIgnoreCase() – This method compares two string objects but ignores the case of the
characters when comparing.
3) compareTo() – This method compares one string with another and returns an integer if the string is
smaller or equal or greater than the other string.
4) compareToIgnoreCase() – This method is same as compareTo() but ignores the case of the
characters when comparing.

16) You need not to create objects to access the String class methods. You can do so using string
literals also. Look at the below example.

?
1 public class MainClass
2 {
public static void main(String[] args)
3 {
4 System.out.println("abc".charAt(0)); //Output : a
5
6 System.out.println("abc".equalsIgnoreCase("ABC")); //Output :
7
8 System.out.println("abc".compareTo("abc")); //Output : 0
9
System.out.println("abc".indexOf('c')); //Output : 2
10 }
11 }
12
13
17) What Is String Intern?

String object in the string constant pool is called as String Intern. You can create an exact copy of
heap memory string object in string constant pool. This process of creating an exact copy of heap
memory string object in string constant pool is called interning. intern() method is used for interning.
Click here to see more about string intern in java.

18) indexOf(), lastIndexOf() and matches(String regex) are the methods to perform search within a
string.

19) Unlike in C and C++, Strings in java are not terminated with null character. Strings are treated as
objects in java.

20) Java provides lots of in built methods to manipulate the string objects. click here to see the
documentation of String class.

How To Find Largest Number Less Than Given


Number And Without Given Digit?
pramodbablad March 14, 2015 1

Question :
Write a java program to find the largest number ‘L’ less than a given number ‘N’ which should not
contain a given digit ‘D’. For example, If 145 is the given number and 4 is the given digit, then you
should find the largest number less than 145 such that it should not contain 4 in it. In this
case, 139 will be the answer.

Logic Used :
We keep on decrementing the given number by 1 until we get the number which does not contain a
given digit. For this, we convert the given number to string ( Integer.toString(i) ) and given digit to
character ( char c = Integer.toString(digit).charAt(0) ). And check whether that string contains the
character ‘c’ or not ( Integer.toString(i).indexOf(c) ). If it contains, again we decrement the given
number and convert it to string and check whether this string contains the character ‘c’ or not. We will
continue this until we get the number which does not contain a given digit.
Flowchart :

Java Program To Find Largest Number Less Than Given Number And Without A
Given DIgit :
?

1 public class LargestNumber

2 {

3 static int getLLessThanN(int number, int digit)


4 {

5 //Converting digit to char

6
char c = Integer.toString(digit).charAt(0);
7
8
//Decrementing number & checking whether it contains digit
9
10
for (int i = number; i > 0; --i)
11
{
12
if(Integer.toString(i).indexOf(c) == -1)
13 {
14 //If 'i' doesn't contain 'c'
15
16 return i;

17 }

18 }

19
return -1;
20
}
21
22
public static void main(String[] args)
23
{
24
System.out.println(getLLessThanN(123, 2));
25
26 System.out.println(getLLessThanN(4582, 5));
27
28 System.out.println(getLLessThanN(98512, 5));
29
30 System.out.println(getLLessThanN(548624, 8));

31 }

32 }
33
34

Output :

119
4499
98499
547999

How To Count Occurrences Of Each Character In


String In Java?
pramodbablad March 25, 2015 16

Problem :
Given a string , you have to count the number of occurrences of each character in it. For example,
If “Java J2EE Java JSP J2EE” is the given string then occurrences of each character in this string
is E=4, 2=2, v=2, =4, P=1, S=1, a=4, J=5.

Logic Used To Find Occurrences Of Each Character In String :


To find the number of occurrences of each character in a given string, we have used HashMap with
character as a key and it’s occurrences as a value. First, we convert the given string to char array and
check each character one by one. And update it’s count in HashMap.
Flowchart :

Java Program To Count Occurrences Of Each Character In String :


?

class EachCharCountInString
1
{
2
static void characterCount(String inputString)
3 {

4 //Creating a HashMap containing char as a key and occurrences as a

5
HashMap<Character, Integer> charCountMap = new HashMap<Character,
6
Integer>();
7
8 //Converting given string to char array
9
10 char[] strArray = inputString.toCharArray();
11
12 //checking each char of strArray

13
14 for (char c : strArray)

15 {
if(charCountMap.containsKey(c))
16
{
17
//If char is present in charCountMap, incrementing it's cou
18 1

19
20 charCountMap.put(c, charCountMap.get(c)+1);

21 }
else
22
{
23
//If char is not present in charCountMap,
24
//putting this char to charCountMap with 1 as it's value
25
26
charCountMap.put(c, 1);
27
}
28 }
29
30 //Printing the charCountMap

31
32 System.out.println(charCountMap);

33 }

34
public static void main(String[] args)
35
{
36
characterCount("Java J2EE Java JSP J2EE");
37
38
characterCount("All Is Well");
39
40
characterCount("Done And Gone");
41 }
42 }
43
44
45

Output :

{E=4, 2=2, v=2, =4, P=1, S=1, a=4, J=5}


{W=1, =2, e=1, s=1, A=1, l=4, I=1}
{D=1, d=1, =2, G=1, e=2, A=1, n=3, o=2}

Note :

Above program is a case sensitive i.e it treats ‘A’ and ‘a’ as two different characters. If you want your
program not to be case sensitive, convert the input string to either lowercase or uppercase
using toLowerCase() or toUpperCase() methods.

How To Find Duplicate Characters In A String In Java?


pramodbablad March 30, 2015 14

Problem :
Write a java program to find duplicate characters and their count in a given string? For example, in a
string “Better Butter”, duplicate characters and their count is t : 4, e : 3, r : 2 and B : 2.
Logic Used To Find Duplicate Characters In A String In Java :
We use HashMap and Set to find the duplicate characters in a string. First, we convert the given
string to char array. We then create one HashMap with Character as a key and it’s number of
occurrences as a value. Then we extract a Set containing all keys of this HashMap
using keySet() method. Then we use this keySet to get the duplicate characters i.e characters which
have appeared more than once in the given string.
Flowchart :
Java Program To Find Duplicate Characters In A String :
?

1 import java.util.HashMap;

2 import java.util.Set;

3
class DuplicateCharactersInString
4
{
5
static void duplicateCharCount(String inputString)
6
{
7
//Creating a HashMap containing char as key and it's occurrences as
8
9 HashMap<Character, Integer> charCountMap = new HashMap<Character,
Integer>();
10
11
//Converting given string to char array
12
13
char[] strArray = inputString.toCharArray();
14
15
//checking each char of strArray
16
17
for (char c : strArray)
18
{
19 if(charCountMap.containsKey(c))
20 {

21 //If char is present in charCountMap, incrementing it's cou


1
22
23
charCountMap.put(c, charCountMap.get(c)+1);
24
}
25 else
26 {
27 //If char is not present in charCountMap,
28 //putting this char to charCountMap with 1 as it's value

29
30 charCountMap.put(c, 1);
}
31
}
32
33
//Getting a Set containing all keys of charCountMap
34
35
Set<Character> charsInString = charCountMap.keySet();
36
37
System.out.println("Duplicate Characters In "+inputString);
38
39 //Iterating through Set 'charsInString'
40
41 for (Character ch : charsInString)
42 {

43 if(charCountMap.get(ch) > 1)

44 {
//If any char has a count of more than 1, printing it's cou
45
46
System.out.println(ch +" : "+ charCountMap.get(ch));
47
}
48
}
49
}
50
51 public static void main(String[] args)
52 {
53 duplicateCharCount("JavaJ2EE");

54
55 duplicateCharCount("Fresh Fish");

56
57 duplicateCharCount("Better Butter");

58 }
}
59
60
61
62

Output :

Duplicate Characters In JavaJ2EE


E:2
a:2
J:2
Duplicate Characters In Fresh Fish
F:2
s:2
h:2
Duplicate Characters In Better Butter
t:4
e:3
r:2
B:2

String To Integer And Integer To String Conversion In


Java
pramodbablad September 28, 2015 5

In most of time, user gives his input through either textfield or textarea. The input user enters via
textfield or textarea is always in the string format. You often need this input in the integer form. For
example – age, mobileNo etc. To make the conversion easy from string to integer or integer to string,
Java provides some useful and easy to use methods. In this post, we will discuss different methods to
convert string to integer and also from integer to string.

How To Convert String To Integer In Java?


There are two methods available in java to convert string to integer. One is Integer.parseInt() method
and another one is Integer.valueOf() method. Both these methods are static methods
of java.lang.Integer class. Both these methods throw NumberFormatException if input string is not a
valid integer. The main difference between Integer.parseInt() and Integer.valueOf() method is
that parseInt() method returns primitive int where as valueOf() method
returns java.lang.Integer object.

Java Program To Convert String To Integer Using Integer.parseInt() method :

1
public class StringToInteger
2
{
3 public static void main(String[] args)
4 {

5 String s = "2015";

6
7 int i = Integer.parseInt(s);

8
9 System.out.println(i); //Output : 2015
}
10
}
11

Java Program To Convert String To Integer Using Integer.valueOf() method :

1
public class StringToInteger
2
{
3 public static void main(String[] args)
4 {

5 String s = "2015";

6
7 int i = Integer.valueOf(s);

8
9 System.out.println(i); //Output : 2015
}
10
}
11
How To Convert Integer To String In Java?
You are also often need to do the reverse conversion i.e converting from integer to string. Java
provides couple of methods to do that also. one is Integer.toString() method and another one
is String.valueOf() method. Both these methods return string representation of the given integer.

Java Program To Convert Integer To String Using Integer.toString() Method :

1
public class IntegerToString
2
{
3 public static void main(String[] args)
4 {

5 int i = 2015;

6
7 String s = Integer.toString(i);

8
9 System.out.println(s); //Output : 2015
}
10
}
11

Java Program To Convert Integer To String Using String.valueOf() method :

1 public class IntegerToString


{
2
public static void main(String[] args)
3
{
4
int i = 2015;
5
6
String s = String.valueOf(i);
7
8
System.out.println(s); //Output : 2015
9 }
10 }
11

35 Java String Interview Questions And Answers


pramodbablad November 24, 2015 12

Top 35 Java String Interview Questions And Answers


:
1) Is String a keyword in java?

No. String is not a keyword in java. String is a final class in java.lang package which is
used to represent the set of characters in java.

2) Is String a primitive type or derived type?

String is a derived type.

3) In how many ways you can create string objects in java?

There are two ways to create string objects in java. One is using new operator and
another one is using string literals. The objects created using new operator are stored in
the heap memory and objects created using string literals are stored in string constant
pool.

String s1 = new String("abc"); //Creating string object using new


1
operator
2
3 String s2 = "abc"; //Creating string object using string literal

4) What is string constant pool?

String objects are most used data objects in Java. Hence, java has a special arrangement
to store the string objects. String Constant Pool is one such arrangement. String Constant
Pool is the memory space in heap memory specially allocated to store the string objects
created using string literals. In String Constant Pool, there will be no two string objects
having the same content.

Whenever you create a string object using string literal, JVM first checks the content of
the object to be created. If there exist an object in the string constant pool with the same
content, then it returns the reference of that object. It doesn’t create a new object. If
the content is different from the existing objects then only it creates new object.

5) What is special about string objects as compared to objects of other derived types?
One special thing about string objects is that you can create string objects without using
new operator i.e using string literals. This is not possible with other derived types (except
wrapper classes). One more special thing about strings is that you can concatenate two
string objects using ‘+’. This is the relaxation java gives to string objects as they will be
used most of the time while coding. And also java provides string constant pool to store
the string objects.

6) What do you mean by mutable and immutable objects?

Immutable objects are like constants. You can’t modify them once they are created. They
are final in nature. Where as mutable objects are concerned, you can perform
modifications to them.

7) Which is the final class in these three classes – String, StringBuffer and
StringBuilder?

All three are final. (Interviewer will ask this type of questions to confuse you)

8) What is the difference between String, StringBuffer and StringBuilder?

[Answer]

9) Why StringBuffer and StringBuilder classes are introduced in java when there
already exist String class to represent the set of characters?

The objects of String class are immutable in nature. i.e you can’t modify them once they
are created. If you try to modify them, a new object will be created with modified
content. This may cause memory and performance issues if you are performing lots of
string modifications in your code. To overcome these
issues, StingBuffer and StringBuilder classes are introduced in java.

10) How many objects will be created in the following code and where they will
be stored in the memory?

1 String s1 = "abc";

2
3 String s2 = "abc";

Only one object will be created and this object will be stored in the string constant pool.

11) How do you create mutable string objects?

Using StringBuffer and StringBuilder classes. These classes provide mutable string objects.

12) Which one will you prefer among “==” and equals() method to compare two string
objects?

I prefer equals() method because it compares two string objects based on their content.
That provides more logical comparison of two string objects. If you use “==” operator, it
checks only references of two objects are equal or not. It may not be suitable in all
situations. So, rather stick to equals() method to compare two string objects. [more]

13) Which class will you recommend among String, StringBuffer and StringBuilder
classes if I want mutable and thread safe objects?

StringBuffer

14) How do you convert given string to char array?

Using toCharArray() method.

15) How many objects will be created in the following code and where they will
be stored?

1 String s1 = new String("abc");

2
3 String s2 = "abc";

Here, two string objects will be created. Object created using new operator(s1) will be
stored in the heap memory. The object created using string literal(s2) is stored in the
string constant pool.

16) Where exactly string constant pool is located in the memory?

Inside the heap memory. JVM reserves some part of the heap memory to store string
objects created using string literals. [more]

17) I am performing lots of string concatenation and string modification in my code.


which class among string, StringBuffer and StringBuilder improves the performance of
my code. Remember I also want thread safe code?

StringBuffer class gives better performance in this scenario. As String class is immutable,
if you use this class, a new object will be created after every string concatenation or
string modification. This will lower the performance of the code. You can
use StringBuilder also, but it is not thread safe. So, StringBuffer will be optimal choice
here.

18) What is string intern?

String object in the string constant pool is called as String Intern. You can create an exact
copy of heap memory string object in string constant pool. This process of creating an
exact copy of heap memory string object in the string constant pool is called
interning. intern() method is used for interning. [more]

19) What is the main difference between Java strings and C, C++ strings?

In C and C++, strings are terminated with null character. But in java, strings are not
terminated with null character. Strings are treated as objects in java.
20) How many objects will be created in the following code and where they will be
stored?

1 String s1 = new String("abc");

2
3 String s2 = new String("abc");

Two objects will be created and they will be stored in the heap memory.

21) Can we call String class methods using string literals?

Yes, we can call String class methods using string literals. Here are some examples,

1 "abc".charAt(0)

2
3 "abc".compareTo("abc")

4
5 "abc".indexOf('c')

22) do you have any idea why strings have been made immutable in java?

a) Immutable strings increase security. As they can’t be modified once they are created,
so we can use them to store sensitive data like username, password etc.

b) Immutable strings are thread safe. So, we can use them in a multi threaded code
without synchronization.

c) String objects are used in class loading. If strings are mutable, it is possible that wrong
class is being loaded as mutable objects are modifiable.

[More]

23) What do you think about string constant pool? Why they have provided this pool as
we can store string objects in the heap memory itself?

String constant pool increases the reusability of existing string objects. When you are
creating a string object using string literal, JVM first checks string constant pool. If that
object is available, it returns reference of that object rather creating a new object. This
will also speed up your application as only reference is returned and also saves the
memory as no two objects with same content are created.

24) What is the similarity and difference between String and StringBuffer class?
The main similarity between String and StringBuffer class is that both are thread safe. The
main difference between them is that String objects are immutable where
as StringBuffer objects are mutable.

25) What is the similarity and difference between StringBuffer and StringBuilder class?

The main similarity between StringBuffer and StringBuilder class is that both produces
mutable string objects. The main difference between them is that StringBuffer class is
thread safe where as StringBuilder class is not thread safe.

Some Java strings interview coding questions….

You might also like