JMA Module 1
JMA Module 1
SYLLABUS
ENUMERATIONS
✓ “Enumeration means a list of named constant, enum in java is a data type that
contains fixed set of constants.
✓ It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions
(NORTH, SOUTH, EAST and WEST) etc.
✓ It is available from JDK 1.5.
✓ An Enumeration can have constructors, methods and instance variables. It is
created using enum keyword.
✓ Each enumeration constant is public, static and final by default.
✓ Even though enumeration defines a class type and have constructors, you do not
instantiate an enum using new.
✓ Enumeration variables are used and declared in much a same way as you do a
primitive variable.
ENUMERATION FUNDAMENTALS
Example:
if(sub == Subject.JMA)
{
...
}
enum WeekDays
{
sun, mon, tues, wed, thurs, fri, sat
}
class Test
{
public static void main(String args[])
{
WeekDays wk; //wk is an enumeration variable of type WeekDays
wk = WeekDays.sun;
//wk can be assigned only the constants defined under enum type Weekdays
System.out.println("Today is "+wk);
}
}
case DOMINOS:
System.out.println("I AM " + r.DOMINOS);
break;
case KFC:
System.out.println("I AM " + r.KFC);
break;
case PIZZAHUT:
System.out.println("I AM " + r.PIZZAHUT);
break;
case PANINOS:
System.out.println("I AM " + r.PANINOS);
break;
case BURGERKING:
System.out.println("I AM " + r.BURGERKING);
break;
}
}
}
Output:
I AM KFC
values()
✓ The and
javavalueOf() Methods
compiler internally adds the values() method when it creates an enum.
✓ The values() method returns an array containing all the values of the enum.
✓ Its general form is,
✓ values() returns the values in the enumeration and stores them in an array. We can
process the array with a foreach loop
✓ example: Values value[] = Values.values();for (Values a : value)statement;
✓ valueOf() method is used to return the enumeration constant whose value is equal
to the string passed in as argument while calling this method.
✓ It's general form is,
public static enum-type valueOf (String str)
Output:
1. Enumerations are of class type, and have all the capabilities that a Java class has.
2. Enumerations can have Constructors, instance Variables, methods and can even
implement Interfaces.
3. Enumerations are not instantiated using new keyword.
4. All Enumerations by default inherit java.lang.Enum class.
5. enum may implement many interfaces but cannot extend any class because it
internally extends Enum class
// variable
int price;
// Constructor
Apple2(int p)
{
price = p;
}
//method
int getPrice()
{
return price;
}
}
Apple2 ap;
}
Output:
Winesap costs 15 cents. 9
All apple prices:
✓ If the invoking constant has an ordinal value greater than e’s, then a positive
value is returned.
enum Apple5
{
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
for(Apple5 a : Apple5.values())
System.out.println(a + " " + a.ordinal());
//System.out.println(a + " " + a);
ap = Apple5.RedDel; ap2
= Apple5.GoldenDel; ap3
= Apple5.RedDel;
System.out.println();
S ystem.out.println();
ATMECE, Dept of CSE Page 9
MODULE 1 Java for Mobile Application
.equals(ap3))
System.out.println(ap + " equals " + ap3);
i
f if(ap == ap3)
(
a System.out.println(ap + " == " + ap3);
p }
.
}e
q
u Output:
a
lHere are all apple constants and their
sordinal values: Jonathan 0
(
GoldenDel
a 1
p
RedDel 2
2
Winesap
) 3
)Cortland 4
S
y
GoldenDel
s
comes before
t
e
RedDel RedDel
m
equals RedDel
.
o
u
RedDel t
equals .
p
RedDel
r
RedDel i
==
n
t
RedDel l
n
(
"
E
r
r
o
r
!
"
)
;
i
f
(
a
p
TYPE WRAPPERS
✓ Java uses primitive data types such as int, double, float etc. to hold the basic data
types for the sake of performance.
✓ Despite the performance benefits offered by the primitive data types, there are
situations when you will need an object representation of the primitive data type.
✓ For example, many data structures in Java operate on objects. So you cannot use
primitive data types with those data structures.
✓ To handle such type of situations, Java provides type Wrappers which provide
classes that encapsulate a primitive type within an object.
• Above mentioned Classes comes under Numeric type wrapper. These classes
encapsulate byte, short, int, long, float, double primitive type.
Example:
class Wrap
{
public static void main(String args[])
{
Integer iOb = new Integer(100); int
i = iOb.intValue();
System.out.println(i + " " + iOb); // displays 100 100
}
}
✓ This program wraps the integer value 100 inside an Integer object called iOb. The
program then obtains this value by calling int Value() and stores the result in i.
✓ The process of encapsulating a value with in an object is called boxing.
✓ Thus, in the program, this line boxes the value 100 into an Integer:
✓ The process of extracting a value from a type wrapper is called unboxing. For
example, the program unboxes the value in iOb with this statement:
The same general procedure used by the preceding program to box and unbox values has
been employed since the original version of Java. However, with the release of JDK 5,
Java fundamentally improved on this through the addition of autoboxing, described next.
int i = iob;
//Auto-unboxing of Integer i.e converting Wrapper class Integer to a primitve type int
System.out.println(i+" "+iob);
char ch = cob;
//Auto-unboxing of Character i.e converting Wrapper class Character to a primitive type char
System.out.println(cob+" "+ch);
}
}
Output :
100 100
aa
Integer iOb;
iOb = 100; //Autoboxing of int
++iOb;
1. Autoboxing / Unboxing lets us use primitive types and Wrapper class objects
interchangeably.
2. We don't have to perform Explicit typecasting.
3. It helps prevent errors, but may lead to unexpected results sometimes. Hence must
be used with care.
4. Auto-unboxing also allows you to mix different types of numeric objects in an
expression. When the values are unboxed, the standard type conversions can be
applied.
class Test
{
public static void main(String args[])
{
Integer i = 35;
Double d = 33.3;
d = d + i;
System.out.println("Value of d is " + d);
}
}
Ouput: Value of d is 68.3
Note: When the statement d = d + i; was executed, i was auto-unboxed into int, d was
auto-unboxed into double, addition was performed and then finally, auto- boxing of d
was done into Double type Wrapper class.
class UnboxingError
{
public static void main(String args[])
{
Integer iOb = 1000; // autobox the value 1000
int i = iOb.byteValue(); // manually unbox as byte !!! System.out.println(i); //
does not display 1000 !
}
}
✓ This program displays not the expected value of 1000, but –24!
✓ The reason is that the value inside iOb is manually unboxed by calling byteValue(
), which causes the truncation of the value stored in iOb, which is 1,000.
✓ This results in the garbage value of –24 being assigned to i.
✓ Auto-unboxing prevents this type of error because the value in iOb will always
autounbox into a value compatible with int.
✓ In general, because autoboxing always creates the proper object, and auto-
unboxing always produces the proper value, there is no way for the process to
produce the wrong type of object or value.
ANNOTATION / METADATA
✓ An annotation is a kind of metadata in java which can be applied at various elements
of java source code so that later some tool, debugger or application program can take
advantage of these annotations; and help analysing the program in positive and
constructive way.
✓ We can annotate classes, methods, variables, parameters and packages in javaOR in
one word almost everything.
✓ It is important to learn that the annotations applied on java source code is compiled into
bytecode with other class members, and using reflection programmer can query this
metadata information to decide the appropriate action to perform in any particular
context.
What is this metadata in java language context? Why we even care about them?
✓ Now we have ‘final’ keyword in class declaration. And the impact of this
declaration is that you can’t extend this class or make a child class of it. How
compiler will understand this? Simply because of ‘final‘ keyword. Right? Well,
this is called metadata.
✓ A metadata is data about data. Metadata adds some additional flags/informations
on your actual data (i.e. in above case the class MyFinalClass), and in runtime either
you or JVM who understand these flags/information, can utilize this metadata
information to make appropriate decisions based on context.
✓ Java Annotation is a tag that represents the metadata i.e. attached with class,
interface, methods or fields to indicate some additional information which can be
used by java compiler and JVM.
✓ Obliviously you can define your own but java does provide some in-built
annotations too for ready-made use.
✓ Java defines many built-in annotations. Most are specialized, but seven are general
purpose.
✓ Some annotations are applied to java code and some to other annotations.
Built-In Java Annotations used in java code: Three are imported from java.lang.
• @Override
• @SuppressWarnings
• @Deprecated
Built-In Java Annotations used in other annotations: Four are imported from
java.lang.annotation
• @Target
• @Retention
• @Inherited
• @Documented
@Override
✓ @Override annotation assures that the subclass method is overriding the parent class
method. If it is not so, compile time error occurs.
✓ Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to
mark @Override annotation that provides assurity that method is overridden.
class Animal
{
void eatSomething()
{
System.out.println("eating something");
System.out.println("base class");
}
}
@Override
void eatsomething() //should be eatSomething
{
System.out.println("eating foods");
System.out.println("derived class");
}
}
@SuppressWarnings
✓ This annotation instructs the compiler to suppress the compile time warnings
specified in the annotation parameters.
✓ e.g. to ignore the warnings of unused class attributes and methods use
@SuppressWarnings("unused") either for a given attribute or at class level for all the
unused attributes and unused methods.
/**
* In the program if you remove the @SuppressWarnings("unchecked") annotation,
* it will show warning at compile time because we are using non-generic collection.
*/
import java.util.*;
class AnnotationDemo2
{
@SuppressWarnings("unchecked")
public static void main(String args[])
{
for(Object obj:list)
System.out.println(obj);
}
}
@Deprecated
✓ Generally below discussed four annotations are used inside other annotations to
hint compiler that how new annotation should be treated by JVM.
@Retention
✓ This annotation specifies how the marked annotation is stored in java runtime.
✓ Whether it is limited to source code only, embedded into the generated class file,
or it will be available at runtime through reflection as well.
java.lang.annotation.RetentionPolicy;
//@Retention(RetentionPolicy.CLASS)
@Retention(RetentionPolicy.RUNTIME)
//@Retention(RetentionPolicy.SOURCE)
//some code
@Documented
✓ This annotation indicates that new annotation should be included into java
documents generated by java document generator tools.
import java.lang.annotation.Documented;
@Documented
@Target
✓ Use @Target annotation to restrict the usage of new annotation on certain java
elements such as class, interface or methods.
✓ After specifying the targets, you will be able to use the new annotation on
given elements only.
✓ @Documented
import java.lang.annotation.Target;
@Target(value={ElementType.TYPE,ElementType.METHOD,ElementType.CONSTR
UCTOR,ElementType.ANNOTATION_TYPE,ElementType.FIELD,
ElementType.LOCAL_VARIABLE,ElementType.PACKAGE,ElementType.PARAM
E TER})
@Inherited
@Inherited
✓ Java allows you to create your own metadata in form of custom annotations. You
can create your own annotations for specific purposes and use them as well. Let’s
learn how to do create custom annotations.
To create a custom annotation, you must use the keyword “@interface“. Other
important things to remember while creating custom annotations are listed below:
Types of Annotation
1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation
1) Marker Annotation
@interface MyAnnotation
{
}
2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For example:
@interface MyAnnotation
{
int value();
}
@interface MyAnnotation
{
int value() default 0;
}
Let's see the code to apply the single value annotation. @MyAnnotation(value=10)
3) Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value annotation. For
example:
@interface MyAnnotation
{
int value1(); String
value2();
String value3();
}
}
@interface MyAnnotation
{
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}
@MyAnnotation(value1=10,value2="varun",value3="Bengaluru")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@interface MyAnnotation2
{
int value() default 2;
String name() default "cse";
}
//Applying annotation
class Hello
{
@MyAnnotation2(value=4,name="ise")
try
{
Hello h=new Hello();
System.out.println(c);
System.out.println(m);
System.out.println(anno);
}
catch(Exception e)
{
System.out.println("no such method exception"+e.getMessage());
}
QUESTIONS