0% found this document useful (0 votes)
21 views

Advanced Java Programming M1

Uploaded by

sakshiam12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Advanced Java Programming M1

Uploaded by

sakshiam12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Advanced Java Programming

ADVANCED JAVA PROGRAMMING [21CS642]


BASICS
JAVA: Java is a high-level, class-based, object-oriented programming(oop)language known
for its platform independence & designed for implementation.

• Java can run on any device that has Java Virtual Machine(JVM).
• It’s widely used for developing desktop , web & mobile applications as well as large -
scale enterprise systems.
• Java was developed by “James Gosling” at Sun microsystems which is owned by
Oracle organization.
• Java is a OOP language i.e., it involves;
✓ Classes and Objects
✓ Inheritance
✓ Polymorphism
✓ Encapsulation
✓ Abstraction
• Java can be divided into 3 categories;
1. Core Java (or) J2SE[standard edition]
It includes fundamental concepts such as syntax, data types, control structures
& OOP concepts & exception handling.
2. Advanced Java (or) J2EE[Enterprise Edition]
It includes JDBC(Java Database Connectivity) for database access, Servlets,
JSP(Java Server Pages) & some frameworks.
3. Android Java (or) J2ME[Micro Edition]
It is used for developing applications for the android platform such as
Smartphones, Smartwatches & tabs.

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 1


Advanced Java Programming

MODULE – 1

ENUMERATIONS , AUTOBOXING & ANNOTATIONS

ENUMERATION: Enumeration refers to a ‘Class Type’ or special data type which is


used to define a set of named Constants.

➢ Enumeration is created using enum keyword.


➢ The values in the enum type are constant, hence it should be represent in uppercase
letters.
➢ To define Enum type, the ‘enum’ keyword is used rather than ‘class’ or ‘interface’.i.e.,

Enum Variable_Name{VALUE 1,VALUE 2,VALUE 3….}

Ex: enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland }


• The identifiers Jonathan, GoldenDel, and so on, are called enumeration constants.
• Each is implicitly declared as a public, static final member of Apple.
• Enumeration variable can be created like other primitive variable. It does not use the new
for creating object.
Ex: Apple ap;
Ap is of type Apple, the only values that it can be assigned (or can contain) are those defined
by the enumeration. For example, this assigns:
ap = Apple.RedDel;
Example Code-1
enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland }
class EnumDemo
{
public static void main(String args[])
{
Apple ap;
ap = Apple.RedDel;
System.out.println("Value of ap: " + ap);

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 2


Advanced Java Programming

// Value of ap: RedDel ap = Apple.GoldenDel;


if(ap == Apple.GoldenDel)
System.out.println("ap contains GoldenDel.\n");
// ap contains GoldenDel.
switch(ap)
{
case Jonathan:
System.out.println("Jonathan is red.");
break;
case GoldenDel:
System.out.println("Golden Delicious is yellow.");
break;
case RedDel:
System.out.println("Red Delicious is red.");
break;
case Winesap:
System.out.println("Winesap is red.");
break;
case Cortland:
System.out.println("Cortland is red.");
break;
}
}
}
The output is;
Value of ap : RedDel
ap contains GoldenDel
Golden Delicious is yellow

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 3


Advanced Java Programming

Example 2 :-
enum DayOfWeek {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Public class EnumExample{
Public static void main(String[] args)
{
DayofWeek today = DayofWeek.WEDNESDAY;
Switch(today){
Case MONDAY :
System.out.println(“It’s Monday!”);
break;
Case TUESDAY :
break;
System.out.println(“It’s Tuesday!”);
break;
default:
System.out.println(“It’s some other day of the week”);
}
}
}
Fundamental aspects of enumerations:-
❖ Definition:- Enumeration are declared using the enum keyword followed by a name &
list of constants within braces{}.
❖ Constants:- These are implicitly static & final.They cannot be changed once defined.
They are typically written in upper case letters.
❖ Usage:- Enums can be define variables,parameters & return types. They provide type
safety.
❖ It can be used in switch statements,loops & collections.
❖ Switch statements:- For easy handling of multiple cases.
❖ Methods & fields:-Enums can have Constructors, methods & fields like regular
classes.
❖ Iteration :- Here we can iterate over all Enum constants using the values() method.
❖ Enumerations helps the code more readable, maintainable & less error-free.

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 4


Advanced Java Programming

❖ Since Enum contains fixed set of constants, It can be days of the


week(SUNDAY,MONDAY,TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY), Directions(NORTH, SOUTH, EAST, WEST),
Season(SUMMER,WINTER,SPRING,FALL) and Planets and so on……
Example:-
Enum Planet{
MERCURY,VENUS,EARTH,MARS,JUPITER, SATURN, URANUS, NEPTUNE;
}
Public class main{
Public static void main(String[] args){
Planet myPlanet = Planet.EARTH ;
CanILiveHere(myPlanet);
}
Static void CanILiveHere(Planet myPlanet){
Switch(myPlanet){
Case EARTH :
S.O.P(“you can live here :”);
break;
default :
S.O.P(“you can’t live here:”);
break;
}
}
}
Output: you can live here
Here in the above example we have instantiated Planet myPlanet = Planet.EARTH; so, it will
check for switch case EARTH.
NOTE: Here S.O.P refers to System.Out.Println

The Values() and ValueOf() Methods


All enumerations contains 2 predefined methods:
1) Values() method
2) ValueOf() method

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 5


Advanced Java Programming

1. The Values() method returns an array that contains a list of the enumeration constants.
The general form is shown here:
public static enum-type[ ] values( )
2. The ValueOf() method returns the enumeration constant whose value corresponds to
the string passed in str.
The general form is shown here:
public static enum-type valueOf (String str)

Example1;

enum Day{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
Public class Enumexample{
Public static void main(String[] args){
Day[ ] days = Day. Values();
for(Day day : days) {
S.O.P(day);
}
}
}
Output:-SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

Example 2;
enum Season
{ WINTER, SPRING, SUMMER, FALL }
class EnumExample1
{
public static void main(String[] args)
{
for (Season s : Season.values())
System.out.println(s);

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 6


Advanced Java Programming

Season s = Season.valueOf("WINTER");
System.out.println("S contains " + s);
}
}

In both cases, enum-type is the type of the enumeration. For example, in the case of the
Season enumeration shown, the return type of Season.valueOf(“WINTER”) is WINTER.

Java Enumeration are Class Types


W.K.T Java enumeration is a class type. We don’t instantiate an enum using new keyword.

• Enumerations are of class type & have all the capabilities that a java class has.
• Enumerations can have Constructors, instance variables, methods & can even
implement Interfaces.

Example for creating Constructor & method in the enum & accessing its constants value.

enum Student

JOHN(10), PETER(11), SAM(12), RAM(13);

Private int age;

int getage() {return age;} // here method defined in enum Student

Private Student(int age) //Constructor defined in enum Student


{
this.age = age;
}
}
Class Example
{
Public static void main(String args[])
{
Student S;
S.O.P(“Age of John is” + Student.John.getage() + years);
}
}

Output:-
Age of John is 10 years.

In this example as soon as we declare an enum variable(Student S), the constructor is called
once, & it initializes age for every enumeration constant with values specified.

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 7


Advanced Java Programming

Enumerations Inherit Enum


We can’t inherit a SuperClass when declaring an enum, all enumerations
automatically inherit one: Java.lang.Enum.

❖ ordinal() method:
A value that indicates an enumeration constant‘s position in the list of constants.
This is called its ordinal value, and it is retrieved by calling the ordinal( ) method,
shown here:
final int ordinal( )

It returns the ordinal value of the invoking constant.


Ordinal values begin at zero.

❖ compareTo( ) method:
To compare the ordinal value of two constants of the same enumeration by using the
compareTo( ) method. It has this general form:

final int compareTo(enum-type e)

enum-type is the type of the enumeration and e is the constant being compared to the
invoking constant.

❖ equals( ) method :
equals method is overridden method from Object class, it is used to compare the
enumeration constant. Which returns true if both constants are same.
Example :
Public class Enum_OrdinalMethodExample{
enum Colours{
RED, GREEN, BLUE ;
}
Public static void main(String[ ] args){
Colours Red =Colours.Red;
Colours Green = Colours.Green;
Colours Blue = Colours.Blue;
S.O.P(“Red oridinal=”+Red.ordinal());
S.O.P(“Green ordinal=”+Green.ordinal());
S.O.P(“Blue ordinal=”+Blue.ordinal());
}
}

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 8


Advanced Java Programming

Output:
Red oridinal=0
Green ordinal=1
Blue ordinal=2

W.K.T ordinal value begin at zero. Thus, in Colours enumeration ,Red has an ordinal value
0, green has an ordinal value of 1 and blue has ordinal value of 2.

Similarly for compareTo() compare the two constants with 0 i.e., < 0 and >0 . for equals()
compare the constant = = 0. [refer textbook example apple enumeration page no. 262]
Type Wrappers
Type Wrappers are classes that encapsulate a primitive type within an object.
The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean.
✓ Character
Character is a wrapper around a char. The constructor for Character is ;
Character(char ch)
Here , ch specifies the character that will be wrapped by the character object being
created.
To obtain the char value contained in a Character object, call charValue(), shown here:
char charValue()
It returns the encapsulated character.
✓ Boolean
Boolean is a wrapper around Boolean values. It defines these constructors:
Boolean(Boolean boolValue)
Boolean(String boolString)
In the first version, boolValue must be either true or false.
In the second version, if boolString contains the string “true”, then the new Boolean
object will be true. Otherwise , it will be false.
To obtain a boolean value from a Boolean object, use booleanValue(), shown here:
boolean booleanValue()
It returns the boolean equivalent of the invoking object.

The Numeric Type Wrappers


The most commonly used type wrappers are those that represent numeric values. These
are Byte,Short, Integer, Long, Float, and Double.
All of the numeric type wrappers inherit the abstract class Number.
Number declares methods that return the value of an object in each of the different number
formats. These methods are shown here:
byte byteValue()
double doubleValue()
float floatValue()
int intValue()

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 9


Advanced Java Programming

long longValue()
short shortValue()
for example , here are the constructors defined for Integer
Integer(int num)
Integer(String str)

Example:
Class Wrap {
Public static void main(String args[ ])
{
Integer iob = new Integer(100);
int i = iob.intValue();
S.O.P(i + “ ” +iob );
}
}
Output:
100
This program wraps the integer value 100 inside an Integer object called iob. The program
then obtains this value by calling intValue() and stores the result in i.

The process of encapsulating a value within an object is called boxing.


Thus, in the program , this line boxes the value 100 into an Integer.
Integer iob = new Integer(100) ;

The process of extracting a value from a type wrapper is called unboxing.


The program unboxes the value in iob with this statement:
int i = iob.intValue() ;

Autoboxing
Autoboxing is the process by which a primitive type is automatically encapsulated
(boxed).

Auto-unboxing
Auto -unboxing is the process by which the value of a boxed object is automatically
extracted (unboxed).

Example :-
Class AutoBox {
Public static void main( String args[ ] )
{
Integer iob = 100;
int i = iob;

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 10


Advanced Java Programming

S.O.P(i + “ ”+iob);
}
}

Output:-
100
Autoboxing and Methods
Autoboxing automatically occurs whenever a primitive type must be converted
into an object.
Auto-unboxing takes place whenever an object must be converted into a
primitive type.
Autoboxing/unboxing might occur when an argument is passed to a method.
Class AutoBox
{
Static int m (Integer v) {
return v;
}
Public static void main (String args [ ] ) {
Integer iob = m(100);
S.O.P(iob);
}
}
This program displays the following result ;
100
In this program , notice that m( ) specifies an Integer parameter and returns an
int result. Inside main( ), m( ) is passed the value 100.

Autoboxing/Unboxing Occurs in Expressions


In general, autoboxing and unboxing take place whenever a conversion into an object or
form an object is required.This applies to expressions. Within an expression , a numeric object
is automatically unboxed.
Example:
Class AutoBox1 {
Public static void main(String args[ ]) {
Integer iob, iob2;
int i ;
iob = 100 ;
S.O.P(“ Original value of iob:” + iob);

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 11


Advanced Java Programming

++iob;
S.O.P(“ After ++iob:” + iob);
iob2 = iob + (iob / 3) ;
S.O.P(“ iob2 after expression :” + iob2);
i = iob + (iob / 3);
S.O.P(“ i after expression:” + i);
}
}
Output:
Original value of iob: 100
After ++iob : 101
iob2 after expression: 134
i after expression: 134

This causes the value in iob to be incremented. It works like this : iOb is unboxed, the value
is incremented, and the result is reboxed.
Example:-
Class AutoBox2 {
Public static void main(String args [ ])
{
Integer iob = 100 ;
Double dob = 98.6 ;

dob = dob + iob ;


System.out.println(“ dob after expression:” +dob);
}
}

Output:
dob after expression: 198.6

By Prof. Anusha B, Dept.of CSE,SJMIT,Chitradurga 12

You might also like