Interface: Abstraction in Java
Interface: Abstraction in Java
Interface: Abstraction in Java
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.
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
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
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.
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.
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.
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.
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.
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.
No. Interfaces can’t have constructors, SIB and IIB. They show 100% abstractness.
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.
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.
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.
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.
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 )
11) What are marker interfaces? What is the use of marker interfaces?
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.
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.
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 {
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?
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.
View Answer
Answer :
Yes. abstract classes can have any number of constructors.
4 }
View Answer
Answer :
abstract methods can’t be private.
View Answer
Answer :
No. only public methods are allowed in an interface.
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
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
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
?
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
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
?
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.
View Answer
Answer :
False. Abstract methods can’t be final.
?
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.
?
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
?
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.
View Answer
Answer :
Yes, abstract methods can be declared with throws clause.
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
View Answer
Answer :
b) Interfaces
?
1 abstract class A
2 {
3 synchronized abstract void method();
4 }
View Answer
Answer :
Abstract methods can not be declared as synchronized.
?
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
?
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.
?
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.
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.
1 interface A
2 {
3 private int i;
4 }
View Answer
Answer :
Illegal modifier for field i. Only public, static and final are allowed.
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
View Answer
Answer :
Yes, a class can implement more than one interfaces.
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.
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.
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.
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
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 {
4 {
5 return i =+ i * i;
}
6
}
7
8
interface B
9
{
10
int methodB(int i);
11 }
12
13 public class MainClass
14 {
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.
?
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.
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.
?
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
?
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.
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.
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
?
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
View Answer
Answer :
Yes, from Java 8, interfaces can have static methods and default methods other than
abstract methods.
?
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.
View Answer
Answer :
True.
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
?
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.
View Answer
Answer :
False. Interfaces are abstract by default but not public.
View Answer
Answer :
Yes, we can define generic interfaces.
?
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
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
?
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 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
?
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
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 {
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 {
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 {
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 {
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();
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(
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 {
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.
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 {
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 {
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 {
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 {
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.
class OuterClass
1
{
2
static
3
{
4 class LocalInnerClassOne
5 {
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 {
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 {
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 {
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
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, 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.
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 {
To use the methodOne(), we have to create an object of ‘SubClass’ type and call
‘methodOne()’ from that object.
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.
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 {
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?.
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 {
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
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.
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.
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,
2 {
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 {
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.
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.
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
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 {
15 {
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 {
27 {
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 {
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
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.
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.
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.
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.
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.
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.
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
12
13 long l = 25; //Primitive 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.
9
10 Integer I = new Integer(15); //Integer Object
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
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.
6
7 Short S = new Short((short) 20); //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
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.
Today we will discuss about constructors and parsing methods of Wrapper Classes In Java.
1
public class WrapperClasses
2 {
3 public static void main(String[] args)
4 {
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
19
20 Float F1 = new Float(12.2f); //Constructor which takes float va
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.
15 }
}
16
17
9
10 int i = Integer.parseInt("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");
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.
Every wrapper class in java has 3 forms of valueOf method. They are,
All these forms are public and static. The valueOf() methods are mainly used to wrap or box the
primitive content into wrapper class objects.
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);
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
2 {
15
16 Float F = Float.valueOf("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
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
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
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.
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
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
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.
2 {
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();
27 }
28
29
o longValue() Method :
It returns long value of the specified object. It may involve truncation of the value.
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 :
4 {
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 :
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();
15
16 Long L = new Long("125");
17 d = L.floatValue();
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 :
2 {
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 :
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();
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.
4 {
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.
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.
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 {
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.
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.
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.
1
public class IsNanAndIsInfinite
2 {
3 public static void main(String[] args)
4 {
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.
2 {
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
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.
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.
If you want to create an empty string object, then use no-arg constructor of String class.
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.
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'};
(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.
?
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.
?
2 {
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.
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.
?
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.
?
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
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.
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.
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.
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
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.
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.
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.
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.
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.
11
12 System.out.println(s1 == s2); //Output : false
}
13
}
14
15
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.
“==” 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.
1 String s1 = "JAVA";
2
3 String s2 = "JAVA";
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.
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.
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).
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.
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.
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.
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.
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
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
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.
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.
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.
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.
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.
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 :
?
2 {
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
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.
class EachCharCountInString
1
{
2
static void characterCount(String inputString)
3 {
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 :
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.
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 {
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 :
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.
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
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.
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
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.
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 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.
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)
[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.
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
15) How many objects will be created in the following code and where they will
be stored?
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.
Inside the heap memory. JVM reserves some part of the heap memory to store string
objects created using string literals. [more]
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.
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?
2
3 String s2 = new String("abc");
Two objects will be created and they will be stored in the heap memory.
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.