You are on page 1of 39

Abstract class constructor & Interface abstract::

These are two different concepts which can be explained easily by a


novice having a little bit knowledge of abstract classes and interfaces.

It is advised to read abstract classes before going through this topics.


It gives thorough understanding of abstract classes where some concepts
you may not aware of, perhaps.

Before going further let us know the difference between constructor and a
method.

1. What is the difference between a constructor and method?

A constructor is called implicitly whenever an object is created. But a


method is to be called explicitly.

A constructor cannot be static but a method can be. When the following
code is compiled. the compiler complains "modifier static not allowed
here".

public class Demo extends Test


{
public static Demo() {}
}
2. Can an abstract class have a constructor?

Yes, it can have and moreover can be overloaded as constructor is special


type of method where return type is missing (and class name and
constructor name should be same).

Following program compiles successfully and executes happily.

abstract class Test


{
public Test()
{
this("way2java.com");
System.out.println("Abstract class default constructor");
}
public Test(String str)
{
System.out.println("My name is " + str);
}
}
public class Demo extends Test
{
public static void main(String args[])
{
new Demo();
}
}
The above program proves an abstract class can have constructors. The
same technique of "this" can be used to access another constructor as in
concrete classes.
Using subclass constructor, the super class abstract methods are
accessed. The principle used is subclass constructor calls superclass
default constructor implicitly.

3. Can an interface be abstract?


Infact, interface is an abstract class with one restriction – all methods
should be abstract. With this small constraint, designers allowed
multiple inheritance. Declaring an interface as abstract (not allowed by
the compiler) does not carry any special meaning as interface implicitly
is an abstract class.

4. Can an interface have constructors?

Sorry, not possible as constructor is nothing but a concrete (non-


abstract) method that carries a body. Interface cannot have concrete
methods.

What access modifiers a constructor cannot be?


"A constructor cannot be abstract, static, final, native, strictfp, or
synchronized". Explained clearly in Java Constructor Properties

Extends Implements::
We know earlier that Java does not support multiple inheritance but
supports partially through interfaces.

After extends there must be only one class of either concrete (non-
abstract) or abstract. After implements there must be interfaces only and
can be of any number. But if a class would like to extend a number of
concrete classes then, how it can? The following program illustrates.

class A { }
class B extends A { }
interface C { }
interface D { }

public class Demo extends B implements C, D


{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
The above program is a combination of multilevel (between A and B) and
multiple (with C and D) inheritance. Demo extends B and in turn B extends
A. Now Demo can make use of the methods of A and B. Demo implements the
interfaces C and D.

Even though Java does not support multiple inheritance directly, it can
achieve all the benefits using extends and implements as in the above
program

Play with Implements::


As Java does not support direct multiple inheritance, it introduced
interfaces to support partial utility of multiple inheritance. For
inheriting multiple interfaces one more keyword (apart "extends") used is
"implements".

Let us list some rules which are already stated in "Extends Implements"
topic. Take some classes and interfaces.

1. After extends there must be only one class either concrete (non-
abstract) or abstract.

2. After implements there can be any number of interfaces.


3. One interface can extend any number of interfaces.

Let us see the coding for the above rules.

class A { }
class B { }
interface C { }
interface D { }
interface E { }

Let us see the combinations of the above.

1st option (it is valid)

class A extends B implements C, D, E

2nd option (it is valid)

interface C extends D

3rd option (it is valid)

interface C extends D, E

Observe, after extends more than one interface.

4th option (it is valid), Java multiple extends

interface C extends D, E
class A implements C

5th option (it is valid)

interface C extends D, E
class A extends B implements C

Java extends vs implements

Even though the keywords "extends" and "implements" are used with
inheritance, they differ a lot in their usage.

Public methods and Private Variables::


Declaring methods as public and variables as private is a programming
technique and comes with its own advantages.

We know private variables or methods cannot be accessed by composition


(has-a relationship) by another class where as public members can be
accessed. A private variable can be accessed through a public method by
another class. The advantage is the other class cannot assign wrong
values to the variables. The values passed by other class can be checked
in a public method and if found correct, assigned to the private
variables; else rejected.

Following program illustrates.

class CheckDemo
{
private int date;
public void validate(int d1)
{
if( d1 > 0 && d1 < 32)
{
date = d1;
System.out.println("Yes, your birth date is " + date + " and
is valid");
}
else
{
System.out.println("Sorry, your birth date is " + d1 + " and
is invalid");
}
}
}
public class BirthDate
{
public static void main(String args[])
{
CheckDemo cd1 = new CheckDemo();
cd1.validate(15);
cd1.validate(35);
}
}

CheckDemo class includes one private variable date and one public method
validate(). The validate() method validates the date send by the other
class BirthDate. If it is within the range of 1 to 31, it assigns the
value to the private variable date, else gives a message.
The other class BirthDate, can not assign to date directly as it is
private. So, the BirthDate class accesses the private variable through
public method, validate().

Similar explanation is available in Java Private variable accessibility


(Private access specifier)
Call by value and Call by reference in Java Tutorial ::
Does Java support call by reference?

This is a very basic question asked in every interview and should known
to each programmer also.

Everyone says "no" as Java does not support pointers. No one actually see
the address of the object in Java. No one can dream of call by reference
without pointers with their experience of C/C++.

Of course, they are very correct.

In Java the method parameters can be primitive data types or object


references. Both are passed as value only but small tricky explanation is
here for object references. I repeat, when primitive data types are
passed as method parameters, they are passed by value (a copy of the
value) but incase of object references, the reference is copied (of
course, here also a copy only) and passed to the called method. That is,
object reference is passed as a value. So, original reference and the
parameter copy both will refer the same Java object. As both refer the
same object, if the calling method changes the value of its reference
(passed from calling method), the original object value itself changes.
Note that object itself is not passed, but it’s references is passed.

Object reference is a handle to a Java object. Do not compare this


reference term with the used in C/C++. In C/C++, the reference directly
points to the memory address of a variable and can be used for pointer
manipulations.

Finally to say, in Java, everyone is passed by value. But with objecct,


the value of the reference is passed.

Let us see two programs on call by value and call by reference.

Case 1: Call-by-value or Pass-by-value

In the following program, a data type int is passed as parameter to a


method call.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class CallByValue
{
public void display(int y)
{
y = 20;
}
public static void main(String args[])
{
CallByValue cbv = new CallByValue();
int x = 10;
cbv.display(x);
System.out.println(x); // prints 10 and not 20
}
}

The variable x value 10 is passed to parameter of y of display() method.


As copy of x is passed, changing y does not change x value in main()
method.

Case 2: Call-by-reference or Pass-by-reference

Here, for display() method the reference of StringBuffer object is


passed.

public class CallByReference


{
public void display(StringBuffer sb2)
{
sb2.append("World");
System.out.println(sb2); // prints HelloWorld
}
public static void main(String args[])
{
CallByReference cbr = new CallByReference();
StringBuffer sb1 = new StringBuffer("Hello");
cbr.display(sb1);
System.out.println(sb1); // prints HelloWorld
}
}
The value of object reference sb1 is passed to sb2. sb1 literal value
"Hello" is passed to sb2. Now sb1 reference and sb2 reference refer the
same object. Changing sb2 affects sb1 also. Both sb1 and sb2 prints
"HelloWorld".

Aggregation and Composition::


Aggregation and Composition are very closely related terms where a novice
gets confused and some examples are of good debate too.

Observe the code.

class Test
{
public void display() { System.out.println("Hello 1"); }
}
class Demo
{
public static void main(String args[])
{
Test t1 = new Test();
t1.display();
}
}
We say, class Demo has the object t1 of Test class. Or say, Demo "has-a"
object of Test. This is known as "has-a" relationship and is known as
composition in Java. This, we know earlier in detail in "Composition –
“has-a” Relationship". Other name of composition is aggregation.

Between composition and aggregation, a small difference exists. It is


simply if Demo can exist without Test, it is known as aggregation and if
Demo cannot exist without Test object, it is known as composition.

With good examples, we can know better.

1. Heart and human body. Heart exists within a human body. It is an


association between two. They are dependent. Can a heart exist without
human body? Simply no. It is known as composition. That is, a child
cannot exist without parent. Heart is completely controlled human body
(organs).

2. Library and book. It is also an association. Can a book exist


without library? Yes, it can; I have got only one book in my hand, it is
possible. That is, delete (remove) the library, still book can exist. It
is an aggregation. But a library cannot exist without books. So here, you
should consider the direction also. From book to library it is
aggregation but from library to book it is composition. Dependency
matters.

In UML diagrams we represent aggregation as


A restricted aggregation is composition. The literal meaning of
aggregation is collection of things together. An aggregation is nothing
but a collection.
In brief, in aggregation association, child can exist independently
without the parent. In composition association, a child cannot exist
without parent. Child is completely controlled by parent.

Suppose take another example, say car. A car HAS-A engine, which states
in car object we will define engine object.

Composition is a STRONGER relationship whereas Aggregation is a WEAKER


relationship. Composition depicts dependency between objects but
Aggregation depicts related objects can exist independently.

Now check yourself with some examples.

Java Constructor from Constructor:::

What is a constructor and what is its role in programming?

A constructor is that one which is called implicitly when an object is


created in Java. A constructor gives properties to an object while it is
being created itself. Else, separate methods are required to give
properties to the object after it is created. Both styles are given
hereunder

Observe the code where properties for a Student object is given using a
constructor at the time of object creation.

public class Student


{
int marks;
String name;
public Student(int marks, String name)
{
this.marks = marks;
this.name = name;
}
public static void main(String args[])
{
Student std1 = new Student(50, "Jyostna"); // while std1 is being
created, marks and name are given
System.out.println(std1.marks + " : " + std1.name);
}
}
Through constructor, std1 object is given properties of marks and name
(in Spring, it is known as constructor injection; injecting the
properties to an object through constructor).

Let us repeat the same code with methods, say setter methods (in Spring,
it is known as setter injection; injecting the properties to an object
through setter methods).

public class Student


{
int marks;
String name;
public void setMarks(int marks)
{
this.marks = marks;
}
public void setName(String name)
{
this.name = name;
}
public static void main(String args[])
{
Student std1 = new Student(); // first object is created
std1.setMarks(50); // then properties are assgined
std1.setName("Jyostna");
System.out.println(std1.marks + " : " + std1.name);
}
}
See how much code increases with methods. This is the importance of
constructor in Java. In Java, String constructor is overloaded many folds
and is discussed in Java String Constructors.

Constructors is good concept in Java and must be studied elaborately;


should be known how to write a constructor, constructor overloading,
calling same class constructor and super class constructor etc. and all
are discussed very clearly with code examples in Constructors and
Constructor overloading.

Abstract Static Method::

1. Can we declare abstract methods as static?

Before answering this question, let us brief about abstract methods.

Following points are to be remembered with abstract methods.

1. First of all, an abstract method cannot be static as static methods


should have a body and abstract methods should not.

2. An abstract class can have the following combinations of methods.

All methods abstract


All methods concrete (non-abstract)
A mixture of abstract and non-abstract methods
Now we have a different question to be answered.

2. Can an abstract class have static methods?

Yes, definitely can have as a static method is special flavor of concrete


method. We know a static method can be called with object name (not
possible here), class name and directly without the help of an object.
Following program explains.

abstract class Test


{
public static void display()
{
System.out.println("Hello 1");
}
}
public class Demo extends Test
{
public static void main(String args[])
{
display();
Test.display();
}
}

In the above code, the display() method is declared static. It is called


in the subclass directly and with abstract class name.

Now another confusing question is to be answered.

3. Can an interface have static methods?

No, impossible. A person having a little knowledge of interfaces can


answer.

All methods of an interface must be public and abstract (by default takes
also if not mentioned). As static methods should have a body, the
interface methods cannot be static.

Can we instantiate an abstract class?::

Put the same question for an interface. Everyone says anonymously, "no"
because there is no implementation (body) of methods as all are abstract.
Coming to an abstract class, the question arises as one case variation of
abstract class is that it can contain all abstract methods. I mean, an
abstract class with all concrete (non-abstract) methods. People ask (of
course it is a good question for interviews also for freshers) why we
cannot create an instance of an abstract class when all methods are non-
abstract.

Only one answer from me.

Can you force an abstract class to contain only abstract methods? No,
designers did not provide a way. In general, you cannot create an
instance of an abstract class. The same rule applies for all the three
variations of abstract class – a) containing all concrete methods b)
containing all abstract methods and c) containing a mixture of abstract
and concrete methods.

Now let us come to a general discussion (answer).

Because an abstract class is an incomplete class (incomlete in the sense


it contains abstract methods without body and output) we cannot create an
instance or object; the same way you say for an interface.

Can you create instance of Interface?::

No, it is not possible. Designers did not provide a way. Of course, it is


of common sense also. Because interface contains only abstract methods
and as abstract methods do not have a body (of implementation code), we
cannot create an object.

Suppose even if it is permitted, what is the use. Calling the abstract


method with object does not yield any purpose as no output. No
functionality to abstract methods.
Then, what is the use of interfaces in Java design and coding. They can
be used as prototypes from which you can develop new classes easily. They
work like templates for other classes that implement interface just like
a blue print to construct a building.

But, it is possible with inner classes and anonymous objects as in the


following code.

interface Test
{
void greet();
}
public class Demo
{
public static void main(String[] args)
{
Test t = new Test()
{
public void greet()
{
System.out.print("\nHi, Best wishes to way2java.com\n");
}
};
t.greet();
}
}
Let us answer one more question.
Can we create an object of abstract class where all methods are non-
abstract (concrete)? Answer for this is also "no". The answer for this is
already discussed in Can we instantiate an abstract class?

public static void main(String args[])::

In Java, the execution starts from main() method. But for compilation,
main() is not required. Java's main() method syntax is quiet different
from C/C++.

Following is the main() method signature

public static void main(String args[])

Every word in the above statement has got a meaning to the JVM.

1. public: It is a keyword and denotes that any other class (JVM) can
call the main() method without any restrictions.

2. static: It is a keyword and denotes that any other class (JVM) can
call the main() method without the help of an object. More about static
is available at static Keyword – Philosophy.

3. void: It is a keyword and denotes that the main() method does not
return a value.

4. main(): It is the name of the method.

5. String args[]: The parameter is a String array by name args. The


string array is used to access command-line arguments.

The Java program under execution takes some context area (execution area)
in the RAM. JVM is in another context area. To call the main(), the JVM
requires an object. When the JVM has not entered into the program, how it
can create an object or get an object. To overcome this, allow the JVM to
access the main() without object just by declaring static. Once the JVM
enters, it can create hundreds of objects later.

Whether you pass right now command-line arguments or not, you must have
the string array as parameter as it is the part of syntax.

Any word is missed in the above statement, the program compiles, but does
not execute.
A program using main() is discussed in "Basic Class Structure,
Compilation and Execution".

1. public static void main(String args[]) throws IOException: This sort


of main() method is used in "BufferedInputStream and
BufferedOutputStream" and in many places.

2. public static void main(String args[]) throws Exception: This type of


main() method is used in "Communication with TCP/IP Protocol" and also in
many places.

Static Constructor::
Java does not permit to declare a constructor as static. Following are
the reasons.

1. Static means for the same class. For example, static methods cannot be
inherited.

2. With static, "this" reference (keyword) cannot be used. "this" is


always linked to an object. A constructor always belongs to some object.

3. If a constructor is static, an object of subclass cannot access. If


static is allowed with constructor, it is accessible within the class but
not by subclass.

The following program raises compilation error.

public class Demo


{
public static Demo()
{
System.out.println("Hello 1");
}
public static void main(String args[])
{
Demo d1 = new Demo();
}
}

Observe, the compiler error message. It says, static is not allowed with
constructor.

What other access modifiers a constructor cannot be?

"A constructor cannot be abstract, static, final, native, strictfp, or


synchronized". Explained clearly in Java Constructor Properties

Private Constructor::
Declaring a private constructor is a very rare usage. First of all can we
do it?

Yes, a constructor can be private and a private constructor can be


overloaded also.

Following program illustrates.

public class Test


{
private Test()
{
System.out.println("I am default private constructor");
}
private Test(int x)
{
System.out.println("I am overloaded private constructor. " +x);
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(10);
}
}

In the above program, Test class created two private constructors –


default and overloaded with int parameter. Program works nice. Observe
the above screenshot.

Then, what is the use of declaring a constructor private?

Programmer can achieve two functionalities with a private constructor.

1. Composition (or has-a relationship) is not possible with default


constructor. That is, you cannot create an object of the class in another
class with default constructor.
2. The class with private constructor is not fit for inheritance. That
is, the class cannot be extended.

The above two statements are proved programmatically hereunder.

1. Composition is not possible

In the following code, Test class includes a private default constructor.

class Test
{
private Test()
{
System.out.println("I am default private constructor");
}
}
public class Demo
{
public static void main(String args[])
{
Test t1 = new Test();
}
}

The Demo class cannot create an object of Test in its main() method.
Observe the screenshot about the compiler message. If the constructor is
not private, the Demo can do it within no time as usual.

2. Not fit for inheritance

The class with private constructor cannot be extended. Observe the


following code.

public class Test


{
private Test()
{
System.out.println("I am default private constructor");
}
}
public class Demo extends Test
{
public static void main(String args[])
{
Demo d1 = new Demo();
}
}

The above program raises compilation error. Why? We know a subclass


constructor class super class constructor implicitly.

Demo d1 = new Demo();

The subclass Demo() constructor calls super class Test() constructor


implicitly. But it cannot as Test() constructor has private access. For
this reason, Test() cannot be extended by any other class,

Can you make class not to be extended by another without declaring it


final?

Yes, simple, declare the constructor as private.

What other access modifiers a constructor cannot be?

"A constructor cannot be abstract, static, final, native, strictfp, or


synchronized". Explained clearly in Java Constructor Properties

Overload Main::

Method overloading is nothing but using the same method in the same class
a number of times with different parameters. Just like any other method,
the main() method also can be overloaded. Following program llustrates.

public class Demo


{
public static void main()
{
System.out.println("Hello World");
}
public static void main(int x)
{
System.out.println(x);
}
public static void main(String args) // observe, no [ ]
{ // it is simply a string and not
array
System.out.println(args);
}
public static void main(String args[])
{ System.out.println();
main();
main(10);
main("way2java");
}
}

The JVM does not find ambiguity to call which main() method is to be
called. It knows clearly, it requires such main() that includes the
parameter String args[]. Other main() methods are treated as user-
defined. As all the main() methods are static in the above code, they are
called without the help of an object.

Abstract class with main()::

The question is can you have a main() method in the abstract class. Yes,
definitely, because main() is a concrete method and abstract class allows
concrete methods. But what you can you do with the main() when you are
not allowed to create objects of abstract classes. But, you can create
objects of another class and use other class methods by composition.

Following program illustrates.

class Test
{
int x = 10;
public void display()
{
System.out.println("Hello 1");
}
}
public abstract class Demo
{
public static void main(String args[])
{
Test t1 = new Test();
System.out.println("From abstract class main(): " + t1.x);
t1.display();
}
}

Observe, Demo is declared abstract and contains main() method. In the


main() method, object of Test class t1 is created and the members of Test
are called.

Why Java does not support Multiple Inheritance?::

Java designer, Mr.James Gosling, committed to keep Java very simple to


practice even for novices; infact, it is one of goals and features of
Java language. Towards this goal, he avoided multiple inheritance,
operator overloading, pointers and prototype declaration etc. which adds
unnecessary problems in coding like making the code complex to read,
debug and practice.

He discarded multiple inheritance to avoid the problems that occur. See


this diamond problem of multiple inheritance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Snake // this program does not
compile
{
void swim()
{
System.out.println("Swims with the whole body");
}
}
class Duck extends Snake
{
void swim()
{
System.out.println("Swims with legs");
}
}
class Fish extends Snake
{
void swim()
{
System.out.println("Swims with fins");
}
}
// once class extending two classes
public class Animal extends Duck, Fish
{
public static void main(String args[])
{
Animal a1 = new Animal();
a1.swim();
}
}
diagramm

The above code is an example of a problem with multiple inheritance


(popularly known as diamond problem; diamond with four edges). Now think,
the Animal should inherit what type of swimming behaviour from its three
parents Snake, Duck and Fish. It is ambiguous. For this reason, Java
avoided multiple inheritance. Of course, C++ have an alternative
solution. Following is the error message the compiler displays.
But we know Java supports partially multiple inheritance with interfaces.
Let us see the same above problem with interfaces multiple inheritance.

interface Snake
{
public abstract void swim();
}
interface Duck extends Snake // between two interfaces, it is
extends and not implements
{
public abstract void swim();
}
interface Fish extends Snake
{
public abstract void swim();
}
public class Animal implements Duck, Fish
{
public void swim()
{
System.out.println("Swim with legs and hands");
}
public static void main(String args[])
{
Animal a1 = new Animal();
a1.swim();
}
}
How the ambiguity diamond problem solved now through interfaces (an idea
taken from Objective C)? Interface methods being abstract do not carry
any body of implementation. So, Animal is inheriting the same three
swim() methods (can I call dummy methods, fancily) from its three parents
without implementation. As the method is the same, the subclass Animal
gives the body as it likes. Compiler thinks all the three swim methods
are overridden.

Let us see the problem through multi-level inheritance.

class Snake
{
void swim()
{
System.out.println("Swims with the whole body");
}
}
class Duck extends Snake
{
void swim()
{
System.out.println("Swims with legs");
}
}
class Fish extends Duck
{
void swim()
{
System.out.println("Swims with fins");
}
}
public class Animal extends Fish
{
public static void main(String args[])
{
Animal a1 = new Animal();
a1.swim();
}
}
diagram

The above swim() method prints "Swims with fins". Then how the Animal
uses Duck or Snake’s swim() methods. Simply use composition as follows.
Duck d1 = new Duck();
d1.swim();

or
Snake s1 = new Snake();
s1.swim();

Another reason for avoidance is Java would like to discard the problems
of object casting between super classes and subclasses, ambiguity in
constructor chaining etc.

Java supports single inheritance, multi-level inheritance and


hierarchical inheritanc

Why Java does not support operator overloading?::

Java is relatively a very simple language to use compared C/C++ with the
non-support of complex and confusing features like pointers, multiple
inheritance and operator overloading. These features are rarely used in
practice and at the same time poorly understood by the language
beginners.

Every operator has a good meaning with its arithmetic operation it


performs. Operator overloading allows you to do something extra than what
for it is expected for. You see + (plus) in some arithmetic operation
doing - (minus) operation. With the avoidance of operator overloading, +
operator anywhere works for addition only, thus programmer need not think
of - (minus) or some other operation. This non-support gives programmer
the avoidance programming errors and also a simple, cleaner and neat
code.

There is one more real advantage of elimination of operator overloading.


It becomes easy for the tool developers to develop a processing tool like
JVM or an IDE tool to process the language. A simpler JVM increases the
performance also.

It is a wise decision and contribution of designers not to support


overloading to lead to a greater simplification of code. Designers did
not provide any handles to overload the operator if thought by the
programmer.

It is a good design move, the Java designers adapted. Java also proved
that a language can exist happily without the support of operator
overloading.

Why Java does not support Pointers?::

Java designers keep only two things in their mind while language is being
developed – a) to make programming simple to practice and 2) to increase
performance.

1. The first and very important reason is the security. The concept of
Pointers in C-lang is often misused and is probably the biggest reason
for people considering C-lang a complicated programming language.

The creators of Java did not like to introduce this complexity into their
programming language and intentionally excluded the concept of pointers.
This was an intentional decision by the creators of Java, because most
people would agree that having pointers creates a lot of potential for
bugs in the code – pointers can be quite confusing, especially to new
programmers. Because arrays and strings are given the status of classes
with methods of manipulating the elements, there is no need for pointers
to those constructs.

2. By not allowing pointers, Java effectively provides another level of


abstraction to the programmer. No pointer support make Java more secure
because they point to memory location or used for memory management that
loses the security as we use them directly.

3. To make program simple, they have eliminated pointers. Java proved a


language can exist without the support of pointers. Pointers is a big
menace in C/C++ and many books are written exclusively on pointers. Non-
support of pointers eliminate (unnecessary) changing the value from a
different location. The code becomes clean and understandable reducing
complexity.

For example, pointers allow the other function values to change which the
function may not like. For example, some function would like the $ value
as Rs.61.5. The other function may change the value of $ with pointer
support. Then the original function looses its value integrity.

4. The simplest explanation is that it would be almost impossible to


create a working of a Garbage Collector (GC), if pointers are available.
With only references, it is possible to construct efficient garbage
collector algorithms that can eliminate memory fragmentation, especially
in case of long running processes.
In case of pointers, if a GC moves an object in the memory, it would need
a way locate and update all pointers pointing to the moved object. The
garbage collection process becomes very slow and error prone.

With the introduction of the JVM, the use of GC has eliminated the need
to explicitly de-allocate memory like in C/C++. The explicit means of de-
allocating memory from an object in Java is handled implicitly by the GC
daemon thread, which means that an object that reaches out of scope in
memory is automatically sent to the GC for garbage collection. This
feature of Java coupled with the original intent of the creators made it
a necessity to eliminate complexity and thus introduced a more managed
approach to dynamic memory.

Which concept is used instead of pointer in Java?

References (which are quite similar to pointers if you disregard from


pointer arithmetic).

In Java we have references which are close to pointers but not same.
References store the address of the object in memory. Pointers can be
manipulated (like arithmetic operations of addition etc.) but references
cannot be manipulated.

Java Interfaces Tutorial::

Many think that abstract methods are waste and interfaces are still more
waste. If you understand correctly, you find their immense usage. Let us
see one.

Suppose I would like to construct a house. I take the help of a Java


interface as follows.

public interface Structure


{
public abstract void use53GradePortlandCement();
// some more methods exist that help to construct a house
}
Observe, the method use53GradePortlandCement() does not have a body, at
least empty braces. These type methods without body are known as abstract
methods. I want to implement the interface to may class as follows.

public class RaoHouse implements Structure


{
public void use53GradePortlandCement()
{
System.out.println("Use Ultratech 53 grade cement");
}
}

My class RaoHouse implements the interface Structure and overrides the


abstract method in the way it is suitable for it. Because I preferred
Ultratech cement because the shop owner gives me the credit. It is 53
grade cement only as required by the interface. If you implement the
interface, you will override the abstract method in your own way like
Orient Gold cement as it is available plenty in your area at that time.

Interface is like a blue print for a house to construct. Using the blue
print we construct the house. Blue print (paper) is not itself a house.
Similarly, interface gives a blue print (template) of methods from which
new classes can be developed easily.
Java Class vs Interface::

We know Java supports three types of classes – Concrete, abstract and


interfaces. After summarizing the difference between abstract classes and
interfaces, let us tabulate the difference between classes and
interfaces.

Class
Interface
Supports only multilevel and hierarchical inheritances but not multiple
inheritance Supports all types of inheritance – multilevel, hierarchical
and multiple
"extends" keyword should be used to inherit "implements" keyword should
be used to inherit
Should contain only concrete methods (methods with body) Should contain
only abstract methods (methods without body)
The methods can be of any access specifier (all the four types) The
access specifier must be public only
Methods can be final and static Methods should not be final and static
Variables can be private Variables should be public only
Can have constructors Cannot have constructors
Can have main() method Cannot have main() method as main() is a concrete
method
Know also the differences between abstract class vs interface.

Java Types of Classes::

After learning "what is class in Java", let us go to see how many types
of classes exist in Java.

Java supports basically three types of classes.

1. Classes (known as concrete classes)


2. Abstract classes
3. Interfaces

1. Classes

Java comes with classes and abstract classes. What we call, generally a
class in Java, is known as concrete class. Other way, to say, a Java
class which is not abstract, is a concrete class. A concrete class can be
final also.

a) public class Employee


b) public final class Employee

"public" is known as an access specifier. A class can have only two


access specifiers – public or default. In the second statement, final
adds extra meaning and purpose (known as functionality) to Employee.

To know further use the following links of this Web site.


1. Java Learning

After going though the above link, follow the following links in an order
to know about other classes.
2. Abstract Classes
3. Interfaces

To know more: final, static, Inheritance, super, constructor.


After going through the above tutorial links, refer this site for deep
study of Java.

What is a class in Java?:::


A class in Java is a structure which contains programming constructs.
Programming constructs are small pieces of code with which a program is
built; like bricks, cement and sand are constructs to construct a
building. The programming constructs are mainly constructors, methods and
variables. So finally, to say, a class is made up of or embeds
constructors, methods and variables.

To access these constructs, we require a handle which points (refer) all


these. This handle is known as object. So, it is necessary to create an
object of the class to access these constructs. A class gives a boundary
for the whole code. Java demands you to write any amount of code within
its boundaries delimited by two braces like { and }.

Following gives a specimen of a class.

class Employee
{ // starting brace of the class
(delimiter)
int empid; // variables
String name; // three are given here
double salary;

Employee() // constructor
{
// some code here that assigns
values to the above 3 variables
}

void calculate() // method


{
// some code here to calculate the
total salary of an employee
}
} // closing brace of the class
(delimiter)

Following is the way to create an object of class Employee.

Employee emp1 = new Employee();


We create objects on class names in Java. Using emp1 we can access the
constructor, variable and method.

Data Type Casting (Type Conversion)::

Java supports two types of castings – primitive data type casting and
reference type casting. Reference type casting is nothing but assigning
one Java object to another object. It comes with very strict rules and is
explained clearly in Object Casting. Now let us go for data type casting.

Java data type casting comes with 3 flavors.

Implicit casting
Explicit casting
Boolean casting.

1. Implicit casting (widening conversion)

A data type of lower size (occupying less memory) is assigned to a data


type of higher size. This is done implicitly by the JVM. The lower size
is widened to higher size. This is also named as automatic type
conversion.

Examples:

int x = 10; // occupies 4 bytes


double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.0
In the above code 4 bytes integer value is assigned to 8 bytes double
value.

2. Explicit casting (narrowing conversion)

A data type of higher size (occupying more memory) cannot be assigned to


a data type of lower size. This is not done implicitly by the JVM and
requires explicit casting; a casting operation to be performed by the
programmer. The higher size is narrowed to lower size.

double x = 10.5; // 8 bytes


int y = x; // 4 bytes ; raises compilation
error
In the above code, 8 bytes double value is narrowed to 4 bytes int value.
It raises error. Let us explicitly type cast it.

double x = 10.5;
int y = (int) x;
The double x is explicitly converted to int y. The thumb rule is, on both
sides, the same data type should exist.

3. Boolean casting

A boolean value cannot be assigned to any other data type. Except


boolean, all the remaining 7 data types can be assigned to one another
either implicitly or explicitly; but boolean cannot. We say, boolean is
incompatible for conversion. Maximum we can assign a boolean value to
another boolean.

Following raises error.

boolean x = true;
int y = x; // error
boolean x = true;
int y = (int) x; // error
byte –> short –> int –> long –> float –> double

In the above statement, left to right can be assigned implicitly and


right to left requires explicit casting. That is, byte can be assigned to
short implicitly but short to byte requires explicit casting.

Following char operations are possible.

public class Demo


{
public static void main(String args[])
{
char ch1 = 'A';
double d1 = ch1;

System.out.println(d1); // prints 65.0


System.out.println(ch1 * ch1); // prints 4225 , 65 * 65

double d2 = 66.0;
char ch2 = (char) d2;
System.out.println(ch2); // prints B
}
}
Object casting (reference casting) discusses casting between objects of
different classes involved in inheritance.

Java byte to short::

After knowing the Java rules of Data Type Casting (Type Conversion), let
us cast byte to short. The byte takes 1 byte of memory and short takes
two bytes of memory. Assignment 1 byte value to 2 bytes is done
implicitly by the JVM.
byte –> short –> int –> long –> float –> double

The left-side value can be assigned to any right-side value and is done
implicitly. The reverse requires explicit casting.

Examples:

short x = 10;
int y = x;

byte x = 10;
short y = x;
Following program explains.

public class ByteToShort


{
public static void main(String args[])
{
byte b1 = 10; // 1 byte
short s1 = b1; // one byte to 2 bytes
System.out.println(s1); // prints 10
}
}
1 byte value b1 is assigned to 2 bytes s1 and is type casted implicitly.

Java short to byte::

After knowing primitive data types and Java rules of Data Type Casting
(Type Conversion), let us cast short to byte. The byte takes 1 byte of
memory and short takes 2 bytes of memory. Assigning 2 bytes of memory to
1 byte of memory requires explicit casting.

byte –> short –> int –> long –> float –> double

The left-side value can be assigned to any right-side value and is done
implicitly. The reverse like short to byte requires explicit casting.
Examples of implicit casting

short x = 10;
int y = x;

byte x = 10;
short y = x;

Following program explains explicit casting, Java style where a short is


assigned to byte.

public class ShortToByte


{
public static void main(String args[])
{
short s1 = 10;
// byte b1 = s1;

byte b1 = (byte) s1;


System.out.println(b1); // prints 10
}
}
byte b1 = s1;

The above statement raises a compilation error "possible loss of


precision".

byte b1 = (byte) s1;

The short s1 is explicitly type casted to byte b1. Observe, the syntax of
explicit casting. On both sides, it should be byte.


Java int to long:

After knowing primitive data types and Java rules of Data Type Casting
(Type Conversion), let us cast int to long. The int takes 4 byte of
memory and long takes 8 bytes of memory. Assignment 4 bytes of memory to
8 byte of memory is done implicitly (automatic conversion).

byte –> short –> int –> long –> float –> double
The left-side value can be assigned to any right-side value and is done
implicitly. The reverse like long to int requires explicit casting.

Examples of implicit casting

int x = 10;
longt y = x;

byte x = 10;
short y = x;

Following program explains where int is assigned to long.

public class IntToLong


{
public static void main(String args[])
{
int i1 = 10; // 4 bytes
long l1 = i1; // 4 bytes assigned to 8 bytes
System.out.println(i1); // prints 10
}
}

long l1 = i1;

The int i1 is assigned to long l1. This is done implicitly by JVM.

Predefined Packages – Java API::

Definition and Importance

A package is Java's style of bundling classes together. A package is a


collection of related classes and interfaces. A package does not mean
only predefined classes; a package may contain user defined classes also.
A package is equivalent to a header file of C-lang. Packages can be
compressed into JAR files for fast traversal in a network or to download
from Internet.

Advantages of Packages

Like header files, packages come with many advantages.

With a single import statement, all the classes and interfaces can be
obtained into our program.
Unlike a header file, Java permits to import even a single class also.
Avoids namespace problems. Two classes of the same name cannot be put in
the same package but can be placed in two different packages.
Access between the classes can be controlled. Using packages,
restrictions can be imposed on the access of other package classes.
Access specifiers work on package boundaries (between the classes of
other packages).
We can find all the related classes and interfaces in a single space.
Searching and identification will be easier.
Packages and sub-packages are the easiest way to organize the classes.
Importing All/Single Class

Packages have an advantage over header files of C-lang. A package allows


importing a single class also instead of importing all. C-lang does not
have this ease of getting one function from a header file.

import java.net.*; // imports all the classes and interfaces


import java.awt.evnet.*; // imports all the classes and interfaces

import java.net.Socket; // imports only Socket class


import java.awt.event.WindowEvent; // imports only WindowEvent class

Note: While importing a single class, asterisk (*) should no be used.

Resolving Namespace Problems

By placing the same class in two different packages, which Java permits,
namespace problems can be solved. Namespace is the area of execution of a
program in RAM. The Date class exists in two packages – java.util and
java.sql. Importing these two packages in a program gives ambiguity
problem to the compiler. In the following program compiler gets ambiguity
problem and is solved with fully-qualified name.
import java.util.*;
import java.sql.*;

public class NSProblem


{
public static void main(String args[])
{
// Date d1 = new Date(); // raises compilation error
java.util.Date d1 = new java.util.Date(); // no error
System.out.println("Today is: " + d1);
}
}
Fully Qualified Class Name

In the above program, if comments are removed, it is a compilation error


as JVM is unable to judge which class should be given to the programmer.
To solve the ambiguity problem, the class name is given along with
package name and is known as fully qualified class name. Here,
java.util.Date is known as fully qualified name. Another advantage of
fully qualified name is that we can know to what package the class
belongs immediately on the spot.

Note: When fully qualified name is included, importing the package is not
necessary.

Package Naming Conventions

Like identifiers have conventions, the packages come with their own
naming conventions. Like keywords and protocols, packages are also of
lowercase letters. In a single project, a number of programmers may be
involved assigned with different modules and tasks. To avoid namespace
problems in storing their work, naming conventions are followed. While
creating packages, they may follow company name, project name or personal
name etc. to precede their package. Following are a few examples.

jyothi.solutions: solutions is the package (folder) preceded by


individual name, jyothi.
forecastingtool.jyothi.solutions: Preceded by the project
name(forecastingtool) and individual name.
mindspace.forecastingtool.jyothi.solutions: Preceded by company name
(mindspace), project name and individual name.
This package naming convention never clashes with the others work in a
big project involving many programmers. The same convention is also
followed in working on a domain also.

Java Class Libraries – Java API

All the classes and interfaces that come with the installation of JDK are
put together are known as Java API (Application Programming Interface).
All the Java API packages are prefixed with java or javax. Following
table gives some important packages, a few prominent classes and their
functionality.

Random, Date, GregorianCalendar and the DS like Stack,


Vector, LinkedList, HashMap etc.

Package Name Example Classes Functionality (Purpose)


java.lang System, String, Object, Thread, Exception etc. These
classes are indispensable for every Java program. For this reason, even
if this package is not imported, JVM automatically imports.
java.util These are called as utility (service) classes and are used
very frequently in coding.
java.io FileInputStream, FileOutputStream, FileReader, FileWriter,
RandomAccessFile, BufferedReader, BufferedWriter etc. These classes are
used in all I/O operations including keyboard input.
java.net URL, ServerSocket, Socket, DatagramPacket, DatagramSocket etc.
Useful for writing socket programming (LAN communication).
java.applet AppletContext, Applet, AudioStub, AudioClip etc Required
for developing applets that participate on client-side in Internet (Web)
programming.
java.awt Button, Choice, TextField, Frame, List, Checkbox etc.
Essential for developing GUI applications.
java.awt.event MouseListener, ActionListener, ActionEvent,
WindowAdapter etc. Without these classes, it is impossible to handle
events generated by GUI components
java.sql DriverManager, Statement, Connection, ResultSet etc
Required for database access in JDBC applications.
Table : Java API Packages
Package vs Directory

The package of Java, at execution time, is converted into a directory


(folder) by the operating system. The java.util is converted as java\util
and java.awt.event is treated as java\awt\event by the OS. The asterisk *
is a wild character of Windows which means all the files (means all the
classes).

Creating Custom-Defined Packages::

Java is a friendly language and permits to create our own packages and
use in programming. We know earlier, Java allows us to create our
exceptions. Creating packages are indispensable in project development
where number of developers are involved doing different modules and
tasks. We know packages avoid name collision problems. Package naming
conventions are very helpful to locate the applications developed by a
single individual or team.

Following steps are to be followed in creating and using packages.

Create a package with a .class file


set the classpath from the directory from which you would like to access.
It may be in a different drive and directory. Let us call it as a target
directory.
Write a program and use the file from the package.
Let us create a package called forest and place a class called Tiger in
it. Access the package from a different drive and directory.

1st Step: Create a package (forest) and place Tiger.class in it.

Let us assume C:\snr is the current directory where we would like to


create the package.

C:\snr > notepad Tiger.java

1
2
3
4
5
6
7
8
9
10
package forest;
import java.util.*;
public class Tiger
{
public void getDetails(String nickName, int weight)
{
System.out.println("Tiger nick name is " + nickName);
System.out.println("Tiger weight is " + weight);
}
}
Order of Package Statement

The above program codingwise is very simple but is important to know the
steps of package creation.

package forest;
import java.util.*;
public class Tiger

package is a keyword of Java followed by the package name. Just writing


the package statement followed by the name creates a new package; see how
simple Java is to practice. For this reason, Java is known as a
production language.

While creating packages, the order of statements is very important. The


order must be like this, else, compilation error.

Package statement
Import statement
Class declaration
If exists, the package statement must be first one in the program. If
exists, the import statement must be the second one. Our class
declaration is the third. Any order changes, it is a compilation error.

When the code is ready, the next job is compilation. We must compile with
package notation. Package notation uses –d compiler option as follows.

C:\snr > javac -d . Tiger.java


The –d compiler option creates a new folder called forest and places the
Tiger.class in it. The dot (.) is an operating system's environment
variable that indicates the current directory. It is an instruction to
the OS to create a directory called forest and place the Tiger.class in
it.

Using Custom-Defined Packages

After creating the package let us use it.

2nd step: Set the classpath from the target directory.

Let us assume D:\sumathi is the target directory. Let us access


Tiger.class in forest package from here.

From the target directory set the classpath following way.


D:\sumathi> set classpath=C:\snr;%classpath%;
classpath is another environment variable which gives the address of the
forest directory to the OS. %classpath% informs the OS to append the
already existing classpath to the current classpath that is right now
set.

3rd Step: Now finally, write a program from the target directory
D:/sumathi and access the package.

D:\sumathi> notepad Animal.java


The above statement creates a file called Animal.java and write the code
in it, say, as follows.

import forest.Tiger;
public class Animal
{
public static void main(String args[])
{
Tiger t1 = new Tiger ();
t1.getDetails("Everest", 50);
}
}
The compilation and execution is as usual as follows.

D:\sumathi> javac Animal.java


D:\sumathi> java Animal

Following is the output screen.

Importing the Package – Precautions

The following statement raises compilation error.

import forest.*;

To work with the above statement, remove the source file Tiger.java file
from C:\snr directory; else use as import forest.Tiger.

Java Import Classes::

A package is the style of Java to group the classes and interfaces


together, or to say, a package is a collection of related predefined
classes and interfaces. Packages are sets of classes and interfaces built
into Java Development Kit (JDK). A package places restrictions (to the
classes of other packages) to access its enclosed classes. Access
specifiers work on package boundaries (between the classes of different
packages).

Definition and Importance

A package is a group of related classes and interfaces. The JDK software


is organized through packages. It is equivalent to a header file of C-
lang and module of Modula language (Modula is a descendent of Pascal).
Packages can be compressed into JAR files (refer xxxx) so that they can
be downloaded or sent across the network fast.
Advantages of Packages

1. With a simple import statement, all the classes and interfaces can
be imported.
2. Java includes a provision to import only one class from a package.
3. It avoids namespace problems (name conflicts). Two classes with the
same name cannot be put in the same package but can be put in two
different packages because a package creates its own namespace (folder).
4. Access for the classes can be controlled.
5. Classes and interfaces of same functionality can be grouped
together.
6. Because functionally all the classes are related, later their
identification and determining the location become easier.
7. Java packages are used to group and organize the classes.

Importing All/Single Class

Java permits to import all the classes or only one class from a package.
C-lang does not have this facility of including only one function from a
header file.

import java.util.*; // imports all the


classes and interfaces
import java.awt.event.*; // imports all the classes
and interfaces

import java.util.Stack; //
imports only Stack class
import java.awt.event.ActionEvent; // imports only
ActionEvent class
// observe, no asterisk, *
Importing Classes – Different Approaches

There are three ways to access a class or an interface that exits in a


different package.

1. Using fully qualified name


2. Importing only one class
3. Importing all the classes

1. Using Fully Qualified Name

Fully qualified name includes writing the names of the packages along
with the class name as follows.

java.awt.event.ActionListener
java.util.Stack

Objects can be created as follows.

java.util.Stack st = new java.util.Stack();

This way of using may not look nice when we use the same class a number
of times in the code as readability becomes boredom. This will be a nice
approach and justified when the class is used only once.

2. Importing Only One Class


Java permits to import only one class also from a package as follows.

import java.awt.event.ActionListener;
import java.util.Stack;

After importing, the objects of the classes can be created straightaway.

Stack st = new Stack();

This type of approach is the best and beneficial when only one class is
required from the same package. Importing one class (when other classes
are not required) saves a lot of RAM space usage on the client’s machine.

3. Importing All The Classes

One of the advantages of packages is to include all the classes and


interfaces of a package with a single import statement.

import java.awt.event.*;
import java.util.*;

The asterisk (*) mark indicates all the classes and interfaces of the
package. After importing, the objects of the cl
asses can be created straightaway.

Stack st = new Stack();

This type of approach is beneficial when many classes and interfaces are
required from a package.

Access Specifiers – Accessibility Permissions & Restrictions ::

Access specifiers, as the name indicates, specify the access to our code
for other classes – whether other classes can access or not and if
permitted, to what extent they can access. Java includes access modifiers
also which are quiet different from access specifiers.

Java comes with four access specifiers. They are

public
protected
default
private

All the Access specifiers are keywords and thereby should be written in
lowercase letters only. Java does not have the confusing combinations of
public protected etc. which C++ does. All specifiers are straight to
their meaning. To understand the specifiers easily, let us take a small
scenario where two packages exist – animal and bird. Let us imagine two
classes Lion and Tiger exist in animal package and Parrot and Peacock
exist in bird package. It is illustrated in the following figure.

Let us think that there exists a method called void eat() in the Tiger
class of animal package. Now the question is who can access this eat()
method; Lion of same package or Peacock of different package. The access
specifiers, in Java, act on package boundaries.
1. public

Let us assume that the eat() method is public. If a member of a class is


public

1. It can be accessed by the classes of the same package. That is, Lion
of the same package can access it.
2. It can also be accessed by the classes of other packages also. That
is, Peacock of other package also can access.

public member of a class can be accessed by any class of any package as


every one has got equal right to access. public gives maximum permissions
among all access specifiers with no restrictions. public means, think
like a public park; anybody can come in and anybody can go out; no ticket
and no restrictions. Do not think always public, we can put restrictions
with other access specifiers. Let us go to the other.

2. protected

Let us assume that the eat() method is protected. If a member of a class


is protected

1. It can be accessed by the classes of the same package as if public.


That is, Lion of the same package can access it.
2. Only the subclasses of other packages can access. That is, Peacock
should extend Tiger class and use eat() method, else not permitted.

protected gives a small restriction for the classes of other package


only, but not to the classes of the same package.

3. default

Let us assume that the eat() method is default. Default means we do not
specify any specifier at all; that is we write simply void eat() without
any specifier.

Generally, novices think default is public; it is not correct. Default


has its own restrictions.

If a member of a class is default

1. It can be accessed by the classes of the same package as if public.


That is, Lion of the same package can access it.
2. It is impossible for the classes of other package to access (even if
they extend also). That is, Peacock cannot access.

The specifiers, public, protected and default does not make any
difference for the classes of the same package, but makes to the classes
of other packages only. We can say that access specifiers act on package
boundaries.

The default specifier is known as package-level access specifier as the


classes of the same package only are allowed to access.

Note: Actually there exist a default keyword in Java, but used with
switch statement. Do not get confused here with the default specifier.

4. private

Let us assume that the eat() method is private in Tiger class.


If a member of a class is private, it can be accessed by the objects of
the same class only but not by the classes of the other package or even
of the same package. private means, it is purely for the private usage of
the same class. Other classes, even of the same package, cannot access by
composition. That is, private member should be used within the same class
with the same class objects. More information on private is available at
Java Private variable accessibility (Private access specifier)

Why both java.awt & java.awt.event::

Why java.awt.event is to be imported separately when already java.awt


package is imported?

It is a very general doubt uncleared in many minds. To get the clear


answer, first you must know how the packages are maintained by Java with
the colloboration of OS. A package of Java is treated as a directory by
the OS. It is proved with -d option of javac utility. On the name of the
package, a directory is created by the OS, which you can see practically.
All this we know in "Creating user-defined packages".

Now come to our point.

java.awt is treated as /java/awt>


java.awt.event is treated as /java/awt/event>

When we look into "/java/awt>" with dir command, the OS shows the files
and subdirectories of awt. It shows clearly that event subdirectory
exists; but it is not opened. To see the files of event directory, we
must go to "/java/awt/event>" and give the dir command.

That is, with java.awt, the event subpackage is imported but it classes
are not opened and thereby not available to the program. To use the
classes of event sub package, it is necessary to import explicitly
java.awt.event package; else compiler raises error saying "cannot resolve
symbol".

JDK 1.5 (Java SE 5) Version::

Every version adds new packages and classes. JDK 1.5 version started its
work under the codename Project Tiger and the version was released on
September, 2004. JDK 1.5 version adds the following features to Java
language. These features are programmatically very important.

Autoboxing
Generics
Enhanced for loop
Varargs
Enums
Static imports
C-lang printf()
StringBuilder
Metadata
Autoboxing – Automatic Conversion

Upto JDK 1.4, all the data structures of Java stores only objects and
when retrieved returns objects. The problem is, even simple data types
are to be converted into objects (using wrapper classes) and stored. The
retrieved objects are to be converted back to data types to use in
arithmetic operations in coding. This is a big nuisance to the
programmer. This is overcome in JDK 1.5 with the introduction of
autoboxing concept. Autoboxing permits to store data types directly in DS
and retrieve back data types. Autoboxing is discussed clearly in data
structures topic.

Generics – Type-Safe Addition

A data structure in Java accepts any data type or object as input. If


only whole numbers are required to be stored, they must be validated
before added to the DS. This requires extra validation code of users
input. This extra code is avoided in JDK 1.5 and named as Generics.
Generics allow adding one type of data only; compiler raises error if
other types are added. Generics is discussed clearly in DS.

Enhanced for Loop

Generally to print the values, we take a for loop. The for loop includes
initialization, test condition and incrementing/decrementing. These are
avoided in enhanced for loop and this loop works in arrays and DS only.
enhanced for loop is illustrated in data structures topic.

Varargs – Variable Number of Arguments

The Varargs concept permits the user to pass any number of arguments to a
method depending on the requirement at runtime. The arguments are stored
as an array internally. Following program illustrates.

public class VarargsTest


{
public static void add(int... marks)
{
int total = 0;
for(int x : marks)
{
total += x;
System.out.print(x + ", ");
}
System.out.print(" and total is " + total + "\n");
}
public static void main(String args[])
{
add(10, 20);
add(10, 20, 30);
add(10, 20, 30, 40);
}
}

public static void add(int… marks)

Observe the special syntax of parameter of add() method. It takes three


dots. Internally, the parameters are stored in an int array. Enhanced for
loop is used to print the arguments and their total.

Enums

enum is a keyword from JDK 1.5. enum is a different flavor of a class;


enum replaces class prefix. Enums are type-safe as they are by default
static and final integer values. Generally enum values are written in
uppercase, by convention, as they are final.
enum EmployeeSalaries
{
HIGH, MEDIUM, LOW, POOR
}
public class EnumTest
{
public static void main(String args[])
{
EmployeeSalaries es;
es = EmployeeSalaries.LOW;
// knowing enum value
System.out.println("Salary of es is " + es + "\n");
// one more value can be assigned
es = EmployeeSalaries.HIGH;
// comparing two values
if(es == es.HIGH)
{
System.out.println("Employee is of high salary\n");
}

switch(es)
{
case HIGH:
System.out.println("High salary"); break;
case MEDIUM:
System.out.println("Medium salary"); break;
case LOW:
System.out.println("Low salary"); break;
case POOR:
System.out.println("Poor salary");
}
}
}

switch(es)

As enum represents an integer value always, it can be used with switch


statement.

Static Imports

Many methods of classes like Math and Character are static. If the
variables and methods of these classes are used very often, all are must
be prefixed with Math or Character which is tedious. To overcome this,
the JDK 1.5 comes with static imports. With static imports, the static
keyword need not be used in coding as in the following program.

import static java.lang.Math.*;


public class StaticUsage
{
public static void main(String args[])
{
int radius = 10;
System.out.println("Perimeter: " + ceil(2 * PI * radius));
System.out.println("Area: " + floor(PI * pow(radius, 2)));
System.out.println("Raised 3 times: " + pow(radius, 3));
}
}

import static java.lang.Math.*;

Normal import statement imports all classes and interfaces of a package.


But static import imports only static members of a single class. It
avoids usage of the class name multiple times in coding. The above
statement avoids Math class name to prefix every variable or method used.

ceil(), floor(), pow are the static methods of Math class and PI is a
static variable. All these are used without using prefix Math name.

Supporting C-lang printf()

printf() is an extra method added to PrintStream class from JDK 1.5


version. printf() is used to print at command-prompt. The printf() uses
java.util.Formatter class internally. Following program illustrates a few
ways.

public class PrintfDemo


{
public static void main(String args[])
{
boolean hot = false;
char alphabet = 'A';
int rate = 5;
float temperature = 12.3456789f;

System.out.printf("The boolean hot: %b", hot); //


place holder b for boolean
System.out.printf("\nThe char alphabet: %c", alphabet);
// c for char
System.out.printf("\nThe int rate: %d", rate);
// d for int
System.out.printf("\nThe float marks is %f", temperature);
// f for float
System.out.printf("\nThe int value prefixed with 4 zeros: %04d",
rate); // filling with zeros
System.out.printf("\nThe float temparature is %.3f",
temperature); // precision to three decimal values
System.out.printf("\nThe float temperature in exponential form:
%e", temperature);

System.out.printf("\n%s, %s and also %s belong to java.lang


package", "System","String","Math");
System.out.printf("\ntemperature is %4.2f", temperature); //
width is 4 and precision to 2 decimal points
}
}

The terminology used to print the values is quiet familiar to C/C++


programmers.

More on Number Formatting

Java’s capability of number formatting is far superior to C/C++. The


following program illustrates.
import java.text.*; // for DecimalFormat
and NumberFormat classes
public class FormattingDemo
{
public static void main(String args[])
{
DecimalFormat df1 = new DecimalFormat("Rs 0.00");
int rate = 25;
System.out.println(df1.format(rate));
// Rs 25.00
System.out.println(df1.format(34.45682)); //
Rs 34.46 (rounded)

NumberFormat nf1 = NumberFormat.getInstance();


nf1.setMinimumFractionDigits(2);
// gives minimum two decimal points; 0 gives no decimal part
nf1.setMaximumFractionDigits(5);
// gives maximum 5
decimal points
System.out.println(nf1.format(Math.PI));
// prints 3.14159
}
}

The classes DecimalFormat and NumberFormat from java.text package gives


more flexibility in number formatting.

NumberFormat nf1 = NumberFormat.getInstance();

NumberFormat being an abstract class cannot be instantiated directly. The


static getInstance() method returns an object of NumberFormat.

nf1.setMinimumFractionDigits(2);
nf1.setMaximumFractionDigits(5);

The first statement gives two minimum decimal points and the second
statement gives five maximum decimal points. They are given if required
only.

High-performance StringBuilder

We know String is immutable and StringBuffer is mutable. When a string is


to be manipulated in the program, it is advised to choose StringBuffer
for performance reasons. But StringBuffer comes with its own demerits.
StringBuffer methods are synchronized and thus allowing thread-safe
operations. To overcome this, designers introduced StringBuilder with JDK
1.5 where the methods are not synchronized. Same methods of StringBuffer
work with StringBuilder also. For a program and more discussion refer
String topic.

Metadata and Annotations

Metadata replaces the usage of templates. Metadata is declarative


programming. Annotations are useful for tool developers to generate
documentation of a project.

Access Specifier vs Access Modifier in Java::


For a novice, both the words specifier and modifier looks one and the
same and may be confusing. If you go by the literal meaning, it is more
confusing, say, an access specifier specifies the access and access
modifier modifies the access. Of course, if the meaning and functionality
is known clearly, it is not confusing at all. Let us explain practically
with examples.

A) Access Specifier – Meaning

Observe.

1. public void display() { }


2. private void display() { }

There are two display() methods with public and private. These two words
give permissions to other classes to access display() method. public
means any class from anywhere can access (like a public park; any one can
enter or leave without ticket). private means not accessible to other
classes; the method can be used by the same class (in which it is
declared, like a private property used by the same family for which it
belongs). Now I think it is clear. The public and private are known as
access specifiers because they specify the access.

There are four access specifiers Java supports, public, protected,


default (not specified at all) and private with different access
restrictions (permissions). Infact, these four are keywords also.

B) Access Modifier – Meaning

Observe the following code.

1
2
3
4
5
6
7
8
class Test
{
public void display() { }
}
class Demo extends Test
{
public void display() { }
}
In the above code, the display() method of Test class is overridden by
Demo class. Infact, Demo class is at liberty to override or not. Now let
us apply a small modifier to display() method of Test class. See the
following code.

1
2
3
4
5
6
7
8
class Test
{
public final void display() { }
}
class Demo extends Test
{
public void display() { }
}
In the super class Test, observe, the display() method is added with
final keyword. In the super class, if a method is declared as final, it
cannot be overridden by subclass. That is, super class by declaring
method as final does not allow the subclass to override. This is the
modification given to the method in super class with final. final is
known as access modifier.

Now let us see one more modifier to have better understanding. Observe
the following code.

class Demo
{
int marks = 50;
static int price = 70;
public static void main(String args[])
{
Demo d1 = new Demo();
System.out.println(d1.marks); // marks called with object d1
System.out.println(price); // price called without object d1
}
}
In Demo class, marks is a non-static variable and price is static
variable. marks (non-static variable) requires object to call from main()
method where as static variable price does not require object. So, now
what is the modification static gave. static modifies the access and
gives the facility to call without the help of an object.

I am sure, you are very clear with the difference between specifier and
modifier.

Access specifiers and access modifiers are applied to variables, methods


and classes. Note, you cannot apply all specifiers to all (variables,
methods and classes) and all modifiers to all. That is, for example, a
local variable cannot be static and a variable cannot be abstract.
Similarly, a class cannot be static.

Following links gives you the indepth knowledge of both.

You might also like