1. Enum
2. For-Each Loop
3. Var-Arg Methods
4. Auto Boxing
& Un Boxing
5. Static Imports
Enum(enumeration):
An enum is a group
of named constants. enum can be used for defining user defined datatypes.
Ex:
enum Month
{
JAN,FEB,MAR,.......DEC;
}
enum concept has
introduced in 1.5 version. When compared with old languages enum, the java enum
ismore powerful
because, in java enum we are allowed to take instance members, constructors
..etc whichmay not be possible
in old languages enum.Every constant
inside enum is implicitly public static and final by default. And we can access
enumconstants by using
enum name.
Ex:
enum Beer
{
ko,rc,kf,fo;
}
class test
{
public static void
main(String [] args)
{
Beer b1 = Beer.fo;
System.out.println(b1);
}
}
we can take enum
either outside the class or with in the class but not inside method. Violation
leads to C.E.
Ex:
enum Beer
class test
class test
{
{
{
}
enum Beer
public void m1()
class test
{}
{
{
}
enum
Beer{}
....
}
}
}C.E :-enum type must not be local
Because By Default
enum constants are public static final. So in method we can’t declare any static
members
If we are declaring
the enum outside the class the allowed modifiers are public, <default>,
and strictfp.
If we are declaring
enum with in a class the allowed modifiers are public, private,
<default>, strictfp and
static.
Enum Vs Inheritance:
Every enum in java
should be the direct child class of java.lang.enum.
As every enum is
already extending java.lang.enum there is no chance of extending any other enum.Hence inheritance
concept is not applicable to the enum. This is the reason abstract and finalmodifiers are not
applicable for enum.
enum x
enum x extends
java.lang.enum
{
{
}
}
enum y extends x
{
}
C.E:-can’t inherit from final x.
enum x
interface x
{
{
}
....
class test extends
x
}
{
enum Beer implements x
}
{
.............
}
C.E:-can’t
inherit from final x. }
And enum types are
extensible.
java.lang.enum is
an abstract class and it is direct child class of Object.
it implements
comparable and serializble interfaces. For java enums the required
functionalities
defined in this
class only.
Enum Vs switch:
We can pass
enumtype as an argument to switch statement.From 1.5 versions on words the
following is the list of valid argument to the switch.
Ex:
enum Beer
{
kf,ko,fo;
}
class test
{
public static void main(String arg[])
{
Beer b1 = Beer.fo;
switch(b1)
{
case kf : System.out.println("kf is not found");
break;
case ko : System.out.println("ko is childrens
brand");
break;
case fo : System.out.println("Buy one get one
free");
break;
default : System.out.println("The Other Brands are
not good");
}
}
}
O/P:- Bye one get
one free.
Note:-
If we are passing
enum constants as the switch argument all the case labels should be valid enum
constantsotherwise we will
get compiler time error.values() method()
Every enum
implicitly contains values method to list all it’s constants.
Ex:
enum Months
{
JAN,FEB,MAR,APR;
}
class test
{
public
static void main(String arg[])
{
Months [] m = Months.values();
for
(Months m1 : m )
{
System.out.println(m1);
}
}
}
O/P:-
Ordinal value()
The position of
enum constant is important and it is described with ordinalvalue() we can find
ordinal value of an
enum constant by using following method.
Ex:
enum Months
{
JAN,FEB,MAR,APR;
}
class test
{
public static void
main(String arg[])
{
Months [] m =
Months.values();
for (Months m1 : m )
{
System.out.println(m1+"....."+m1.ordinal());
}
}
}
O/P:-
Note:- ordinal
values are 0 based.Speciality of java
enum
A java enum can
contain constructors, instance members, static members …etc in addition to
constants which may
not be possible in the old languages enum.
Ex:
enum Beer
{
kf(100),ko(120),rc(150),fo;
int price;
Beer(int price)
{
this.price = price;
System.out.println("constructor");
}
Beer()
{
this.price = 130;
System.out.println("No
Argumentconstructor");
}
public int
getPrice()
{
return price;
}
}
class test
{
public static void
main(String arg[])
{
Beer [] b =
Beer.values();
for(Beer b1 : b)
{
System.out.println(b1+"......"+b1.getPrice());
}
}
}
O/P:-
An enum can contain
constructors also and these will execute at the time of enum class loading.
Programmer is not
responsible to call constructors explicitly.With in enum we
can’t take abstract methods.If the enum
contains any thing other than constants(like instance variables, static
variables.. etc) thenthe list of
constants should end with semicolon.
Ex:
If the enum
contains anything else other than constants then the list of constants should
be the firstline.
Ex:
enum Month
{
C.Eàint num;
JAN,FEB,MAR;
}
enum in java
internally implemented as class concept only. We are allowed to declare main()
methodin enum and we can
involve directly from the command prompt.enum Month
enum Month
{
JAN,FEB,MAR ;
int num;
}
Mandatory
enum Month
{
JAN,FEB,MAR ;
}
Optional
{
JAN,FEB,MAR;
public static void
main(String arg[])
{
System.out.println("Hai
This is enum class method");
}
}
E:\> javac
Month.java
java Month;
O/P:- Hai This is
enum class method
Between enum
constants, we can apply equality operators (== & !=) and we can’t apply
relational
operators.Consider the
following enum declarations
enum Color
{
RED,GREEN,BLUE;
}
1) Color.RED ==
Color.GREEN
2) Color.RED >
Color.GREEN X
3)
Color.RED.ordinal() > Color.BLUE.ordinal();
Ex:
Consider the
following enum declaration
package pack1;
enum color
{
RED,GREEN,BLUE;
}
Assume the
following Test class is available outside of pack1
class Test
{
public static void
main(String arg[])
{
color c = color.RED;
System.out.println(c);
}
}
To Compile Test
Class Successfully, which of the following import statements we have to take.
1) import
pack1.color;
2) import
pack1.color.*;
3) import static
pack1.color;
4) import static
pack1.color.*;
class Test
{
enum color
{
RED,GREEN;
}
}
Which of the
following declarations are valid outside of Test Class.
color c = RED; X
color c =
color.RED; X
Test.color.c =
Test.color.RED;
Ex:
enum color
{
RED,GREEN,BLUE
{
public void m1()
{
System.out.println("Too
Good");
}
};
public void m1()
{
System.out.println("Too
Danger");
}
}
class Test
{
public static void
main(String arg[])
{
color.RED.m1();
color.BLUE.m1();
color.GREEN.m1();
}
}
O/P:- Too Danger
Too Good
Too Danger
Because we didn’t
put semicolon beside BLUE, and immediately we started the instance block so
BLUE executes the
instance block.
var- arg methods
From 1.5 version on
words we are allowed to declare a method with variable no of arguments such
type ofmethods are called
var-arg methods.We can declare a
var-arg methoda as follows
m1(int… i);this methods is
applicable for any no of int arguments including zero no of arguments.
Ex:
class Test
{
public static void
m1(int... i)
{
System.out.println("var-arg
methods");
}
public static void
main(String arg[])
{
var-arg methodsàm1();
var-arg methodsàm1(10);
var-arg methodsàm1(10,20);
var-arg methodsàm1(10,20,30);
}
}
‘var-arg’ methods
internally implemented by using single dimensional arrays. Hence we can
differentiatearguments by using
index.
Ex:
class Test
{
public static void
main(String arg[])
{
sum(10,20);
sum(10,20,30,40);
sum(10);
sum();
}
public static void
sum(int... a)
{
int total = 0;
for (int
i=0;i<a.length ;i++ )
{
total = total+a[i];
}
System.out.println("The
sum is:"+total);
}
}
O/P:-
We can mix general
parameter with var-arg parameter.
Ex:
m1(char ch, int…a)
If we are mixing
general parameters with var-arg parameter then var-arg parameter must be the
lastparameter otherwise
compile time error.
Ex:
m1(int… a, float f)
m1(float f, int… a)
we can’t take more
than one var-arg parameter in var-arg method otherwise C.E.
m1(int… a double… d)
which of the
following are valid var-arg declarations.
m1(int... a)
m1(int. ..a) C.E:
malformed function
m1(char ch, int...
a)
m1(int... a, char
ch)
m1(int...a,
boolean... b)
Ex:
class Test
{
public static void
m1(int i)
{
System.out.println("General
method");
}
public static void
m1(int... i)
{
System.out.println("var-arg
method");
}
public static void
m1(String arg[])
{
m1();
m1(10,20);
m1(10);
}
}
Var-arg method will
always get least priority i.e if no other method matched then only var-arg
method will
be executed.
AutoBoxing and
AutoUnBoxing:
Until 1.4 version,
in the place of wrapper object we are not allowed to pass primitive values.
Ex: ArrayList l = new
ArrayList();
C.E in 1.4 version.àl.add(10);
Integer I = new
Integer(10);
No C.Eàl.add(I);
Similarly in the
place of primitive we are not allowed to pass wrapper object.
Ex:-
Boolean B = new
Boolean("true");
Generates C.E hereàif(B)
{
System.out.println("Hello");
}
else
{
System.out.println("Hai");
}
In Compatible types
found :Boolean
required:Boolean
The Following code
is valid in 1.4 version.
boolean b =
b.booleanValue();
if(b)
{
System.out.println("Hello");
}
else
{
System.out.println("Hai");
}
But from 1.5
version on words we can pass primitives in the place of objects and wrapper
objects in theplace of
primitives. The required conversion will take by compiler Automatically. This
concept is nothingbut “AutoBoxing”
and “AutoUnBoxing”.
Eg:- ArrayList l =
new Arraylist();
l.add(10);
Eg:- Integer I = 10;
Eg:- Boolean b =
new Boolean(“true”);
If(b)
{
}
Because of this
AutoBoxing and AutoUnBoxing concept, the importance of wrapper class is bit low
from 1.5 version on
words
AutoBoxing
Automatic
conversion from primitive to wrapper object by the compiler is called
“AutoBoxing.”
Integer I = 10;
[Compiler
Automatically converts primitive to Integer Object form]
AutoUnBoxing
Automatic
conversion from wrapper object to primitive type by the compiler is calles
“AutoUnBoxing”
int i = new
Integer(10);
[Compiler
Automatically converts Integer Object to int primitive.]
Ex:-
class Test
{
public static
Integer I = 10;
public static void
main(String[] args)
{
AutoUnBoxingàint i
= I;
m1(i);
}
public static void
m1(Integer I)
{
System.out.println(I);
}
}
From 1.5 version on
words there is no difference Between wrapper Object and primitive. We can useinterchangeably.
Ex:
class Test
{
public static
Integer I = 0;
public static void
main(String[] args)
{
int i = I;
System.out.println(i);
}
}
Ex:
class Test
{
public static
Integer I;
public static void
main(String[] args)
{
NPE(NullPointerException)àint i
= I;
System.out.println(i);
}
}
Ex:
class test
{
public static void
main(String [] a)
{
Integer x = 10;
Integer y = x;
x++;
System.out.println(x);
System.out.println(y);
System.out.println(x==y);
}
}
AutoBoxing
Because wrapper
objects are immutable i.e once we constructed wrapper object we are not allowed
to change it’s content. If u r trying to
change, with those changes a new object will be created.
Case1:-
Integer I1 = new
Integer(10);
Integer I2 = new
Integer(10);
falseàSystem.out.println(I1 == I2);
Because new creates
new Object for every one.
Case2:-
Integer I1 = new
Integer(10);
Integer I2 = 10;
falseàSystem.out.println(I1
== I2);
Because one is
following normal and another is following AutoBoxing Concept.
Case3:-
Integer I1 = 10;
Integer I2 = 10;
trueàSystem.out.println(I1
== I2)
Because Both are
following AutoBoxing Concept.
Case4:-
Integer I1 = 100;
Integer I2 = 100;
trueàSystem.out.println(I1
== I2);
Because these are
also following AutoBoxing concept.
Case5:-
Integer I1 = 1000;
Integer I2 = 1000;
falseàSystem.out.println(I1
== I2);
10
I1 I2
100
I1 I2
Because for this
concept the range is -127 to 128 only. So different objects will be created.
By autoboxing if an
object is required to create ,compiler won’t create that object immediately.
First it will check .is there any
object already created with the same content by autoboxing or not.
If it is already
created. Compiler will gives existing object only instead of creating new
object.
But this rule is
applicable only in the following cases
Byte Always
Short -128 to 127
Integer -128 to 127
Long -128 to 127
Character 0 to 127
Boolean Always
But in all the
remaining cases new object will be created.
Long l1 = 126l;
Long l2 = 126l;
trueàSystem.out.println(l1
== l2);
Boolean b1 = true;
Boolean b2 = true;
trueàSystem.out.println(b1
== b2);
Float f1 = 10.5f;
Float f2 = 10.5f;
falseàSystem.out.println(f1
== f2);
Because it’s not
specified in the above list.
OverLoading in
AutoBoxing, Widening, and var-args methods
Case1:-
AutoBoxing Vs
Widening
100
I1 I2
100
class test
{
public void
m1(Integer I)
{
System.out.println("Integer");
}
public void m1(long
l)
{
System.out.println("long");
}
public static void
main(String [] a) {
test t = new test();
int i = 10;
t.m1(i);
}
AutoBoxing
Widening
O/P:- long
Because compiler
gives the precedence for widening when compared with autoboxing.
Case2:-
AutoBoxing Vs
var-args
Compiler gives the
precedence for the autoboxing over var-arg method. i.e var-args methods
will always get
least priority if there is no other method. Then only var-arg method will get a
chance.The following
example will demonstrates this concept.
O/P:- Integer
Case3:-
widening Vs var-args
O/P:- long
Because the
compiler will always gives chance to widening over var-arg.
Compiler gives the
precedence in the following order in the case of overloading method
resolution.
widening >
autoboxing > var-args
Observe the
following example carefully.
Ex:
class test
{
class test {
public void
m1(Integer I)
{
System.out.println("Integer");
}
public void m1(int…
i)
{
System.out.println(“int");
}
public static void
main(String [] a) {
test t = new test();
int i = 10;
t.m1(i);
}
AutoBoxing
Var-args
class test
{
public void m1(long
l)
{
System.out.println(“long");
}
public void m1(int…
i)
{
System.out.println(“int");
}
public static void
main(String [] a) {
test t = new test();
int i = 10;
t.m1(i);
}
widening
Var-args
public void m1(Long
l)
{
System.out.println("Long");
}
public static void
main(String[] args)
{
test t = new test();
int i =10;
t.m1(i);
}
}
O/P:- Generates
compiler error.
Because widening
followed by autoboxing is not possible in java
Like that Integer
to Long conversion is also not possible because Integer is not child class of
Lang
Consider the
following Example:
class test
{
public void
m1(Object o)
{
System.out.println("Object");
}
public static void
main(String[] args)
{
test t = new test();
int i =10;
t.m1(i);
}
}
O/P:- Object
Because Integer is
a child class of Object.
static imports:
This concept has
introduced in 1.5 version. According to sun people static imports improves
readability ofthe code but
according to world wide java expert static imports increases confusion instead
of improvingreadability.Hence if there is
no specific requirement it is not recommended to use static imports. The main
objective ofstatic imports is
to import static members of a particular class. So that with out using class
name we can access directly
static members.
Ex:
import static
java.lang.Integer.*;
import static
java.lang.Byte.*;
class Test
{
public static void
main(String arg[])
{
System.out.println(MAX_VALUE);
}
}
Reference to
MAX_VALUE is ambiguous. Compiler always resolves static members in the
following order.
4) Current class
static member
5) Explicit static
member
6) Implicit static
member
Ex:
2àimport static java.lang.Integer.MAX_VALUE;
import static
java.lang.Byte.*;
class Test
{
1àstatic int MAX_VALUE = 999;
public static void
main(String arg[])
{
System.out.println(MAX_VALUE);
}
}
O/P:- 999
If we are
commenting line 1 then the o/p is 2147483647. if we are commenting both lines 1
& 2 then the
O/P is 127.
class Test
{
public static void
main(String arg[])
{
System.out.println(Math.sqrt(4));
System.out.println(Math.random());
System.out.println(Math.max(10,20));
}
}
import static
java.lang.Math.sqrt;
import static
java.lang.Math.*;
class Test
{
public static void
main(String arg[])
{
System.out.println(sqrt(4));
System.out.println(random());
System.out.println(max(10,20));
}
}
Note:- It is not
recommended to extend import concept up to static members because several
classes can contain static
members with same name. which may cause compile time error.
Static imports also
reduces readability of the code. It is recommended to access static members by
using class name only.
Post a Comment
Post a Comment