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

1.what Is Enum? Explain The Use of Values and Valueof Methods? Enumerations

The document discusses enums in Java and their methods. Enums define class types that can have constructors, methods and variables. The values() and valueOf() methods of enums are explained. Autoboxing and autounboxing of primitive types to their corresponding wrapper classes is also covered.

Uploaded by

Lipi's Khazana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

1.what Is Enum? Explain The Use of Values and Valueof Methods? Enumerations

The document discusses enums in Java and their methods. Enums define class types that can have constructors, methods and variables. The values() and valueOf() methods of enums are explained. Autoboxing and autounboxing of primitive types to their corresponding wrapper classes is also covered.

Uploaded by

Lipi's Khazana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

1.What is Enum? Explain the use of Values() and valueOf() methods?

Enumerations
An enum is a list of named constants. In Java, enumerations define class types. That is, in Java,
enumerations can have constructors, methods and variables. An enumeration is created using the
keyword enum. Following is an example:

enum Person
{
Married, Unmarried, Divorced, Widowed
}
The identifiers like Married, Unmarried etc. are called as enumeration Constants. Each such
constant is implicitly considered as a public static final member of Person.

Consider the following program to illustrate working of


enumerations:
enum Person

Married, Unmarried, Divorced, Widowed

}
Class EnumDemo{

Public static void main(string args[])

Person p1;

p1=Person.Unmarried;

System.out.println("Value of p1 :" +p1);


Person p2= Person.Widowed;
if(p1==p2)

System.out.println("p1 and p2 are same");

Else

System.out.println("p1 and p2 are different");


switch(p1){

case Married:

System.out.println("p1 is Married");
break;

case Unmarried:

System.out.println("p1 is Unmarried");
break;
case Divorced:
System.out.println("p1 is Divorced");
break;
case Widowed:
System.out.println("p1 is Widowed");
break;
}

The values( ) and valueOf( ) Methods


All enumerations contain two predefined methods: values() and valueOf(). Their general forms are
shown here:
public static enum-type[]
values() public static enum-
type valueOf(String str)
The values() method returns an array of enumeration constants. The valueOf() method returns the
enumeration constant whose value corresponds to the string passed in str.

enum Apple{
janarthan,goldendel,redel,winesap,cortland
}

public class EnumDemo3


{

public static void main(String[] args)


{
Apple ap;

System.out.println("Here are all Appleconstants:");

Apple allapples[]=Apple.values();
for(Apple a : allapples)
System.out.println(a);
System.out.println();
ap = Apple.valueOf("Winesap");
System.out.println("ap contains"+ap);

}
}

2. With an example explain how enumerations inherit enum?

We can’t inherit a superclass when declaring an enum, all


enumerations automatically inherit one: java.lang.Enum. This class
defines several methods that are available for use by all
enumerations. Most often you won’t need to use these methods, but
there are two that you may occasionally
employ: ordinal() and compareTo( ).
The ordinal( ) method obtains a value that indicates an
enumeration constant’s position in the list of constants. This is
called its ordinal value. The ordinal( ) method is shown here:
final int ordinal( ).It returns the ordinal value of the invoking
constant. Ordinal values begin at zero . We can 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)


The usage will be:
e1.compareTo(e2);
We can compare for equality an enumeration constant with any
other object by using equals( ), which overrides the equals( )
method defined by Object.

package sem3;
enum Apple{
janarthan,goldendel,redel,winesap,cortland
}
public class EnumDemo1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Apple ap,ap2,ap3;
System.out.println("here are all apple contains"+ "and their
ordinality");
for(Apple a:Apple.values())
System.out.println(a+""+a.ordinal());
ap=Apple.redel;
ap2=Apple.goldendel;
ap3=Apple.redel;
System.out.println();
if(ap.compareTo(ap2)<0)
System.out.println((ap+ "comesbefore" +ap2));
if(ap.compareTo(ap2)>0)
System.out.println((ap+ "comesbefore" +ap2));
if(ap.compareTo(ap3)==0)
System.out.println((ap+ "equals" +ap3));
System.out.println();
if(ap.equals(ap2))
System.out.println("error");
if(ap.equals(ap3))
System.out.println("ap equals ap3");

}
3. What is autoboxing? Explain its methods?

Autoboxing refers to the conversion of a primitive value into an object of the


corresponding wrapper class is called autoboxing. For example, converting
int to Integer class. The Java compiler applies autoboxing when a primitive
value is:
• Passed as a parameter to a method that expects an object of the
corresponding wrapper class.
• Assigned to a variable of the corresponding wrapper class.
OR

In addition to the simple case of assignments, 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. Thus,
autoboxing/unboxing might occur when an argument is passed to a method, or
when a value is returned by a method. For example, consider this:

Autoboxing/unboxing takes place with

method parameters and return values.

class AutoBox2 {
Take an Integer parameter and return an int value;
//

static int m(Integer v) {

return v ; // auto-unbox to int

public static void main(String args[])


{

Pass an int to m() and assign the return value

to an Integer. Here, the argument 100 is autoboxed

into an Integer. The return value is also autoboxed

into an Integer.

Integer iOb = m(100);


System.out.println(iOb);

}
This program displays the following result:
In the program, notice that m( ) specifies an Integer parameter and returns
an int result. Inside main( ), m( ) is passed the value 100. Because m( ) is
expecting an Integer, this value is automatically boxed. Then, m( ) returns
the int equivalent of its argument. This causes v to be auto-unboxed. Next,
this int value is assigned to iOb in main( ), which causes the int return value to
be autoboxed.
4. Explain how autoboxing and unboxing occurs in Boolean and
Character values?
Java also supplies wrappers for boolean and char. These
are Boolean and Character. Autoboxing/unboxing applies to these wrappers,
too. For example, consider the following program:
package sem3;

public class p6 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Boolean b=true;
if(b)
System.out.println("b is true");
Character ch='x';
char ch2=ch;
System.out.println("ch2 is:"+ch2);

}
The output is shown here:

b is true
ch2 is x

The most important thing to notice about this program is the auto-unboxing
of b inside the if conditional expression. As you should recall, the conditional
expression that controls an if must evaluate to type boolean. Because of auto-
unboxing, the boolean value contained within b is automatically unboxed when
the conditional expression is evaluated. Thus, with the advent of
autoboxing/unboxing, a Boolean object can be used to control an if statement.
Because of auto-unboxing, a Boolean object can now also be used to control any
of Java’s loop statements. When a Boolean is used as the conditional expression
of a while, for, or do/while, it is automatically unboxed into
its boolean equivalent. For example, this is now perfectly valid code:

Boolean b;
// ...
while(b) { // ...

5. What is an annotation? Explain how do you create an


annotation?
Annotations in Java provide additional information to the compiler and JVM. An
annotation is a tag representing metadata about classes, interfaces,
variables, methods, or fields. Annotations do not impact the execution of the code
that they annotate. Some of the characteristics of annotations are:

• Begin with ‘@’

• Do not alter the execution of the program

• Provide supplemental information and help to link metadata with elements


of a program such as classes, variables, constructs, methods, etc.

• Are different from comments since they can affect how the program is
treated by the compiler.

how can we create our own java annotations, for that refer to simple
steps sequentially as follows:

1. To create your own Java Annotation you must use @interface


Annotation_name, this will create a new Java Annotation for you.

2.The @interface will describe the new annotation type declaration.


3.After giving a name to your Annotation, you will need to create a
block of statements inside which you may declare some variables.

Here is the declaration for an annotation called MyAnno:

// A simple annotation type.


@interface MyAnno {

String str();
int val();

First, notice the @ that precedes the keyword interface. This tells the compiler
that an annotation type is being declared. Next, notice the two members str(
) and val( ).
Example:

// Java Programwhere Illustrating Declaration of

// Custom Marker Annotation

// Importing I/O classes

import java.io.*;

// Sample for marker Annotation:

// Custom annotation declaration

@interface books_data

// No variable declared here

// Main class

class books {

// Main driver method


public static void main(String[] args)

// Print statement

System.out.println("example of Marker Annotations.");

6. What are built in annotations? Explain with an example.


Java defines many built-in annotations.
Built-In Java Annotations used in Java code
o @Override
o @SuppressWarnings
o @Deprecated

Built-In Java Annotations used in other annotations


o @Target
o @Retention
o @Inherited
o @Documented

@Override
@Override is a marker annotation that can be used only on methods. A
method annotated with @Override must override a method from a
superclass. If it doesn’t, a compile-time error will result. It is used to ensure
that a superclass method is actually overridden, and not simply overloaded.
1. class Animal{
2. void eatSomething(){System.out.println("eating something");}
3. }
4.
5. class Dog extends Animal{
6. @Override
7. void eatsomething(){System.out.println("eating foods");}//should be eatSomet
hing
8. }
9.
10. class TestAnnotation1{
11. public static void main(String args[]){
12. Animal a=new Dog();
13. a.eatSomething();
14. }}

@SuppressWarnings

@SuppressWarnings specifies that one or more warnings that might be issued


by the compiler are to be suppressed. The warnings to suppress are specified by
name, in string form.

@SuppressWarnings annotation: is used to suppress warnings issued by the compiler.

package sem3;
import java.util.*;
class Addition
{
public static int sum(int n1,int n2)
{
return n1+n2;
}
public static int sum(int...nums)
{
int sum=0;
for(int i:nums)
{
sum+=i;
}
return sum;
}
}
public class Annotation2 {
@SuppressWarnings("unchecked")
public static void main(String args[])
{
Addition add=new Addition();
int sum=Addition.sum(10, 20);
System.out.println("sum of 10 and 20:"+sum);
@SuppressWarnings("rawtypes")
List list=new ArrayList();
list.add(12);
list.add(120);
System.out.println("list items:"+list);
}
}
If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at
compile time because we are using non-generic collection.

@Deprecated
Deprecated annotation is used for informing the compiler that the
particular method, class or field is unimportant and it indicates that
a declaration is outdated.

1. class A{
2. void m(){System.out.println("hello m");}
3.
4. @Deprecated
5. void n(){System.out.println("hello n");}
6. }
7.
8. class TestAnnotation3{
9. public static void main(String args[]){
10.
11. A a=new A();
12. a.n();
13. }}
@Target
Target Tags are used to specify the type of Annotation used. The
Annotation Library declares many constants to specify the type of
element where the annotation is needed to be applied, such as TYPE,
METHOD, FIELD etc. We can access the Target tags
from java.lang.annotation. ElementType
@Documented

It is a marker interface that tells a tool that an annotation is to be


documented. Annotations are not included in ‘Javadoc’ comments. The use
of @Documented annotation in the code enables tools like Javadoc to
process it and include the annotation type information in the generated
document.
@Retention Annotation
Retention Annotations are designed to indicate for how long a
particular annotation with the annotated type is to be retained. The 3
values that the @Retention annotation can have:
• SOURCE: Annotations will be retained at the source level and
ignored by the compiler.
• CLASS: Annotations will be retained at compile-time and ignored
by the JVM.
• RUNTIME: These will be retained at runtime.
@Inherited
@Inherited causes the annotation for a superclass to be inherited
by a subclass. Therefore, when a request for a specific annotation
is made to the subclass, if that annotation is not present in the
subclass, then its superclass is checked. If that annotation is
present in the superclass, and if it is annotated
with @Inherited, then that annotation will be returned.
7. What are the different types of retention policy? Explain with
code snippets.
Retention Annotations are designed to indicate for how long a
particular annotation with the annotated type is to be retained.
These retention policies determine at which point an annotation is
discarded. There are three types of retention policies: SOURCE, CLASS, and
RUNTIME.
• RetentionPolicy.SOURCE: The annotations annotated using the
SOURCE retention policy are discarded at runtime.
• RetentionPolicy.CLASS: The annotations annotated using the
CLASS retention policy are recorded in the .class file but are
discarded during runtime. CLASS is the default retention policy in
Java.
• RetentionPolicy.RUNTIME: The annotations annotated using the
RUNTIME retention policy are retained during runtime and can be
accessed in our program during runtime.
Example:
// Java Program to Illustrate Retention Annotations

// Importing required classes from java.lang package


import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

// Here we will be creating 3 annotations with


// RetentionPolicy as SOURCE, CLASS, & RUNTIME

// Retention Annotation 1
@Retention(RetentionPolicy.SOURCE)

// Interface
@interface SourceRetention
{
String value() default "Source Retention";
}

// Retention Annotation 2
@Retention(RetentionPolicy.CLASS)

// Interface
@interface ClassRetention
{
String value() default "Class Retention";
}

// Retention Annotation 3
@Retention(RetentionPolicy.RUNTIME)

// Interface
@interface RuntimeRetention
{
String value() default "Runtime Retention";
}

// Annotating classes A, B, and C


// with our custom annotations
@SourceRetention
class A {
}

@ClassRetention
class B {
}

@RuntimeRetention
class C {
};

// Main class
public class RetentionPolicyDemo {

// Main driver method


public static void main(String[] args)
{

// Obtaining the array of annotations used to


// annotate class A, B, and C. Array a and b will be
// empty as their annotation are attached before
// runtime while array c will contain the
// RuntimeRetention annotation as it was marked with
// RUNTIME retention policy
Annotation a[]
= new A().getClass().getAnnotations();
Annotation b[]
= new B().getClass().getAnnotations();
Annotation c[]
= new C().getClass().getAnnotations();

// Printing the number of retained annotations of


// each class at runtime
System.out.println(
"Number of annotations attached to "
+ "class A at Runtime: " + a.length);

System.out.println(
"Number of annotations attached to "
+ "class B at Runtime: " + b.length);

System.out.println(
"Number of annotations attached to "
+ "class C at Runtime: " + c.length);

// Since the class C is annotated with an annotation


// which has retention policy as runtime so it
// can be accessed during runtime while annotations
// of other two classes are discarded before runtime
// so they can't be accessed
System.out.println(
"Annotation attached to class C: " + c[0]);
}
}
Output
Number of annotations attached to class A at Runtime: 0
Number of annotations attached to class B at Runtime: 0
Number of annotations attached to class C at Runtime: 1
Annotation attached to class C: @RuntimeRetention(value="Runtime
Retention")

8. What are marker annotations? Explain their significance?


9. Where do we use single member annotations?
10. What are type wrappers? Explain in detail.
The type wrappers are Double, Float, Long, Integer, Short, Byte, Character,
and Boolean.
These classes offer a wide array of methods that allow you to fully integrate
the primitive types into Java’s object hierarchy. Each is briefly examined next.
Character
Character Wrappers: 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:

c
har charValue( ) It returns the encapsulated
character.

Boolean Wrappers: 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” (in uppercase or lowercase), then the new Boolean object will be true.
Otherwise, it will be false. To obtain a boolean value from a Boolean object, use

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. 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()

long longValue()

short shortValue()

For example, doubleValue( ) returns the value of an object as a double, floatValue( ) returns the
value as a float, and so on. These methods are implemented by each of the numeric type wrappers.

All of the numeric type wrappers define constructors that allow an object to be constructed from a
given value, or a string representation of that value. For example, here are the constructors defined
for Integer:

Integer(int num)
Integer(String str)
If str does not contain a valid numeric value, then a NumberFormatException is thrown. All of the
type wrappers override toString(). It returns the human-readable form of the value contained
within the wrapper.

This allows you to output the value by passing a type wrapper object to println(), for example,
without having to convert it into its primitive type.

Example:
class TypeWrap

{ public static void


main(String args[])

Character ch=new Character('#');

System.out.println("Character is " + ch.charValue());

Boolean b=new Boolean(true);

System.out.println("Boolean is " + b.booleanValue());


Boolean b1=new Boolean("false");

System.out.println("Boolean is " +
b1.booleanValue()); Integer iOb=new
Integer(12); //boxing int
i=iOb.intValue(); //unboxing

System.out.println(i + " is
same as " + iOb); Integer
a=new Integer("21"); int
x=a.intValue();

System.out.println("x is " + x);

String s=Integer.toString(25);

System.out.println("s is " +s);

Output:
Character is #

Boolean is true

Boolean is False

12 is same as 12

X is 21 s is 25

You might also like