A Java Q Unit1
A Java Q Unit1
The ordinal() method returns the index position of an enum constant in its enum declaration, starting from 0.
Syntax :- [Link]();
II) Once declared in the enum, no additional constants can be added at runtime.
An enumeration is a special data type in Java used to define a fixed set of named constants, and it is created using
the enum keyword.
// valueOf()
Day d1 = [Link]("MONDAY");
[Link]("Selected day: " + d1);
}
}
Qns 5. Provide an example of how to use the values() method to iterate through all the constants in an
enumeration.
Qns 6. Give the functionalities of compareTo(), and equals() methods in Java enumerations.
The compareTo() method compares two enum constants based on their ordinal position (their order in the
enum declaration).
It returns an integer value:
1. 0 → both constants are equal
Page 1 of 20
Advance Java Unit 1
2. Negative value → the calling constant appears before the specified constant
3. Positive value → the calling constant appears after the specified constan
.
In Java, type wrappers (wrapper classes) are used to convert primitive data types into objects. Each primitive
type has a corresponding wrapper class in the Java Wrapper Classes.
Examples:
int → Integer
char → Character
double → Double
boolean → Boolean
Qns 8. What is the purpose of the doubleValue() method in a numeric wrapper class?(similarly other methods)
The doubleValue() method is used to convert the value of a numeric wrapper object into the primitive double
type.
It extracts the numeric value stored in the wrapper object.
The result is returned as a double primitive value.
Qns 9. What is the benefit of autoboxing and auto-unboxing in Java?
a retention policy specifies how long annotations are retained and available during the program lifecycle. It
determines at what stage the annotation will be accessible (source code, compiled class file, or runtime).
import [Link].*;
@Retention([Link])
@interface MyAnnotation {
String value();
}
Page 2 of 20
Advance Java Unit 1
Qns 11. List any two retention policies with its purpose.
Qns 12. What is the purpose of setting default values to annotation member. Write the general form for setting
default values.
@Retention([Link])
@interface MyAnnotation {
String value() default "Default Value";
int count() default 1;
}
@MyAnnotation // Using defaults
public class Test {
public static void main(String[] args) {
[Link]("Annotation example");
}
}
a. Marker Annotation
A marker annotation is an annotation without any parameters, used to signal or “mark” a class, method, or field
for some special processing by the compiler or runtime
A single-member annotation is an annotation that has only one parameter, and when used, you can provide a value
without explicitly naming the member.
Qns 14. List any two built in annotations with its purpose.
1. @Override
• Purpose:
Indicates that a method overrides a method in a superclass.
o Helps the compiler check for errors, ensuring that the method signature matches the superclass
method.
2. @Deprecated
Page 3 of 20
Advance Java Unit 1
• Purpose:
Marks a method, class, or field as deprecated, indicating it should not be used in new code.
o The compiler generates a warning if the deprecated element is used.
Qns 15. Write any two restrictions on annotation.
Purpose of Annotations
1. Provide Metadata
o Annotations give information about the program to the compiler, tools, or frameworks.
2. Guide Compiler and Tools
o Annotations can instruct the compiler to generate warnings or errors.
3. Enable Runtime Processing
o Some annotations are retained at runtime and can be read using reflection to guide program
behaviour.
4. Simplify Configuration
o Annotations can replace verbose XML or configuration files.
@interface AnnotationName {
dataType memberName() default defaultValue; // optional members
}
@interface → keyword used to declare an annotation
AnnotationName → name of the annotation
memberName() → optional elements (members) of the annotation
defaultValue → optional default value for a member
Example:-
import [Link].*;
@Retention([Link])
@interface MyMarker {
}
@MyMarker
public class Test {
public static void main(String[] args) {
[Link]("Marker annotation example");
}
}
Qns 18. How can you retrieve all annotations with the RUNTIME retention policy associated with an element in Java
reflection? Give its syntax
Java Reflection, annotations that have @Retention([Link]) are available at runtime and can be
retrieved using reflection APIs from classes, methods, fields, constructors, etc.
Page 4 of 20
Advance Java Unit 1
Syntax : Annotation[] annotations = [Link]();
import [Link];
Qns 19. Name any two commonly used built-in annotations and briefly describe their purpose?
1. @Override
• Indicates that a method is intended to override a method in the superclass.
• The compiler checks whether the method actually overrides a parent method.
• If not, it generates a compile-time error, helping prevent mistakes.
2. @Deprecated
• Marks a class, method, or field as deprecated (no longer recommended for use).
• The compiler shows a warning when the deprecated element is used.
A Java Bean is a reusable Java class that follows certain conventions. Its key characteristics are:
1. The class must have a public default (no-argument) constructor so that objects can be created easily by
frameworks and tools.
2. All variables (properties) should be declared private to ensure encapsulation.
3. Properties are accessed and modified using public getter and setter methods.
a. getPropertyName()
b. setPropertyName()
4. Java Beans usually implement the Serializable interface so that objects can be saved and restored.
5. Method and property names follow JavaBean naming standards, which allows tools and frameworks to
recognize them automatically.
1. Reusability
Java Beans are reusable software components that can be used in different applications, which reduces
development time and effort.
2. Easy Maintenance and Encapsulation
Since properties are accessed through getter and setter methods, the internal data is protected, making
the code easier to maintain and modify.
Introspection is essential for Java Beans technology because it allows tools and frameworks to analyze a bean’s
properties, methods, and events automatically at runtime without needing explicit code.
1. Automatic Property Detection
Introspection enables tools to identify getter and setter methods, thereby discovering the bean’s
properties automatically.
2. Tool Support
Page 5 of 20
Advance Java Unit 1
Development tools (like IDEs and GUI builders) can examine Java Beans and manipulate their properties
visually without knowing the class details beforehand.
3. Simplifies Component Use
It allows frameworks to interact with beans dynamically, making them easier to integrate and reuse.
Qns 23. What is the difference between a simple property and an indexed property?
1. Simple Property
• A simple property represents a single value.
• It is accessed using standard getter and setter methods.
2. Indexed Property
• An indexed property represents a collection or array of values.
• It allows access to individual elements using an index.
Qns 24. What are the two main components used to define a simple property in a Java Bean. Briefly explain their
roles
The two main components used to define a simple property in a Java Bean are:
1. Private Instance Variable (Property Field)
This is the private variable that stores the value of the property.
It ensures data encapsulation, meaning the property cannot be accessed directly from outside the class.
Example: private int age;
Holds the actual value of the property inside the bean.
2. Getter and Setter Methods
These are public methods used to access and modify the private property.
Getter Method:
public int getAge() {
return age;
}
Returns the value of the property.
Setter Method:
public void setAge(int age) {
[Link] = age;
}
Updates or assigns a new value to the property.
Qns 25. What are the key differences between bound properties and constrained properties in Java Beans?
Page 6 of 20
Advance Java Unit 1
•
Persistence allows a bean to store its current state, such as property values, in a file or database.
•
Later, the bean can be reconstructed with the same state when the program runs again.
Persistence in JavaBeans is usually implemented by:
• Implementing the Serializable interface so the bean can be written to and read from a stream.
• Using serialization mechanisms like ObjectOutputStream and ObjectInputStream
Part B
Qns 1. With an example explain how enumeration values are used to control a switch statement.
In Java, enumeration values can be directly used in a switch statement to control program flow. This makes the
code more readable and type-safe compared to using integers or strings.
switch(today) {
case MONDAY:
[Link]("Start of the week");
break;
case TUESDAY:
[Link]("Second day of the week");
break;
case WEDNESDAY:
[Link]("Midweek day");
break;
case THURSDAY:
[Link]("Almost Friday");
break;
case FRIDAY:
[Link]("End of the week");
break;
default:
[Link]("Weekend!");
}
}
}
Page 7 of 20
Advance Java Unit 1
Qns 2. Demonstrate the usage of the valueOf() and values() methods with an example
In Java, enumeration classes provide built-in methods values() and valueOf() to work with enum constants
efficiently.
1. values() Method
• Returns an array of all enum constants in the order they are declared.
• Useful for iterating through all possible values.
2. valueOf() Method
• Returns the enum constant corresponding to the specified name (String).
• Throws IllegalArgumentException if the name does not match any constant.
Example
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY}
public class TestEnum {
public static void main(String[] args) {
// Using values() to iterate over all constants
[Link]("All days of the week:");
for (Day d : [Link]()) {
[Link](d);
}
// Using valueOf() to get a specific constant
Day today = [Link]("WEDNESDAY");
[Link]("\nToday is: " + today);
}
}
Qns 3. What does ordinal(), compareTo() and equals() method do in Enum? Give an example.
In Java, enums are class types that extend [Link]. This gives them several built-in methods, including
ordinal(), compareTo(), and equals(). Here’s what they do:
1. ordinal() : Returns the position (index) of an enum constant in the enum declaration.
• Index starts from 0.
2. compareTo() : Compares the ordinal values of two enum constants.
• Returns:
o 0 if both constants are the same
o Negative if the first constant appears before the second
o Positive if the first constant appears after the second
3. equals() : Checks if two enum constants are exactly the same.
• Returns true if both constants refer to the same enum constant, otherwise false.
Example
enum Day { MONDAY, TUESDAY, WEDNESDAY }
Page 8 of 20
Advance Java Unit 1
Qns 4. Java Enumerations Are Class Types. Explain with an example.
es! In Java, enumerations (enum) are actually special kinds of class types. Each enum you define is implicitly a
subclass of [Link], which means it can have fields, methods, and constructors, just like a regular class.
enum Day {
MONDAY("Weekday"),
TUESDAY("Weekday"),
WEDNESDAY("Weekday"),
THURSDAY("Weekday"),
FRIDAY("Weekday"),
SATURDAY("Weekend"),
SUNDAY("Weekend");
// Method
public String getType() {
return type;
}
@Override
public String toString() {
return name() + " is a " + type;
}
}
Page 9 of 20
Advance Java Unit 1
In Java, enumerations (enum) cannot directly inherit another enum, because all enums implicitly extend
[Link]. Java does not support multiple inheritance for classes, so extending one enum with another is not
allowed.
However, enums can implement interfaces, which allows sharing common behavior among multiple enums. This is
the recommended way to achieve a form of inheritance-like behavior.
interface Describable {
String getDescription();
}
// Constructor
Color(String description) {
[Link] = description;
}
In Java, wrapper classes are object representations of primitive data types. They allow primitives to be treated as
objects, which is essential for working with collections, generics, and reflection, since these only work with objects.
Wrapper Classes for Java Primitive Types
Page 10 of 20
Advance Java Unit 1
Primitive Type Wrapper Class Description
byte Byte Encapsulates a byte value in an object
short Short Encapsulates a short value in an object
int Integer Encapsulates an int value in an object
long Long Encapsulates a long value in an object
float Float Encapsulates a float value in an object
double Double Encapsulates a double value in an object
char Character Encapsulates a char value in an object
boolean Boolean Encapsulates a boolean value in an object
autoboxing and unboxing are features that allow automatic conversion between primitive types (like int, double)
and their corresponding wrapper classes (like Integer, Double).
1. Autoboxing
Autoboxing is the automatic conversion of a primitive type into its corresponding wrapper class object.
2. Unboxing
Unboxing is the automatic conversion of a wrapper class object back to its corresponding primitive type
import [Link];
Qns 8. With an example explain the steps involved to obtain annotation at run time using reflection.
Page 11 of 20
Advance Java Unit 1
2. Apply the annotation to a class, method, or field
3. Use reflection to get the Class, Method, or Field object
4. Call getAnnotation() or getAnnotations()
o getAnnotation(Class<Annotation>) → retrieves a specific annotation
o getAnnotations() → retrieves all annotations present
5. Access annotation values using its methods
Example Program
import [Link].*;
import [Link].*;
Qns 9. What Are Annotations? What are the three retention policies defined by the RetentionPolicy enumeration in
Java?
Annotations are metadata in Java that provide information about the code but do not directly affect program logic.
They can be applied to classes, methods, fields, parameters, or packages.
• Annotations help tools, frameworks, and the compiler to process code in a structured way.
• Examples of built-in annotations: @Override, @Deprecated, @SuppressWarnings.
Example:
Page 12 of 20
Advance Java Unit 1
@Override
public String toString() {
return "This is an example";
}
Here, @Override tells the compiler that the method is overriding a superclass method.
Retention Policies in Java
The @Retention annotation specifies how long annotations are retained. The retention policies are defined in the
[Link] enum:
Retention
Description Example Use
Policy
Annotation is discarded by the compiler and not
SOURCE @SuppressWarnings
included in the .class file. Used only in source code.
Annotation is stored in the .class file but not available Some tools may use it during bytecode
CLASS
at runtime via reflection. analysis
Annotation is stored in the .class file and available at Custom annotations for frameworks, e.g.,
RUNTIME
runtime. Can be accessed via reflection. @Entity, @MyAnnotation
Example of Setting Retention Policy:
import [Link];
import [Link];
@Retention([Link])
@interface MyAnnotation {
String value();
}
• Here, MyAnnotation is available at runtime.
import [Link];
import [Link];
Here are four commonly used built-in annotations in Java along with their purpose and usage:
1. @Override
Page 14 of 20
Advance Java Unit 1
void show() {
[Link]("Overridden method");
}
}
2. @Deprecated
Marks a class, method, or field as deprecated, meaning it is not recommended for use.
The compiler gives a warning when the deprecated element is used.
Example:
class Demo {
@Deprecated
void oldMethod() {
[Link]("This method is deprecated");
}
}
3. @SuppressWarnings
Instructs the compiler to ignore specific warnings in a block of code.
Helps reduce unnecessary warnings during compilation, e.g., unchecked casts or deprecations.
Example:
@SuppressWarnings("unchecked")
public void processList() {
List list = new ArrayList(); // unchecked warning suppressed
}
4. @FunctionalInterface
Marks an interface as a functional interface, i.e., it has exactly one abstract method.
The compiler ensures the interface meets the functional interface requirements, enabling use with lambda
expressions.
Example:
@FunctionalInterface
interface MyFunction {
void execute();
}
Qns 12. How do you specify a default value for an annotation member? Explain with suitable example
In Java, you can specify a default value for an annotation member by using the default keyword when defining the
annotation. If the user of the annotation does not provide a value, the default is automatically used.
1. Use default to specify a default value for an annotation member.
2. If the user does not provide a value, the default is used automatically.
3. Defaults make annotations optional, which increases flexibility.
Syntax to Specify Default Value
@interface AnnotationName {
DataType memberName() default defaultValue;
}
Example
import [Link];
import [Link];
Page 15 of 20
Advance Java Unit 1
Using the Annotation
1. Using default values (no values provided):
@Author
public class Book1 {
}
• Here, name = "Unknown" and year = 2026 are automatically used.
2. Overriding default values:
@Author(name = "Alice", year = 2023)
public class Book2 {
}
• Here, name = "Alice" and year = 2023 are used instead of defaults.
Retrieving the Values via Reflection
import [Link];
A marker annotation in Java is an annotation that does not have any elements. Its presence alone serves as a signal
or “marker” to the compiler, runtime, or tools.
1. No elements: A marker annotation has an empty body.
2. Indicates metadata: Its presence conveys information, e.g., @Override, @Deprecated, or @ThreadSafe.
3. Can be processed: Tools or reflection can detect its presence with methods like isAnnotationPresent().
Defining a Marker Annotation
import [Link];
import [Link];
// Marker annotation
@Retention([Link]) // Retain at runtime
@interface ThreadSafe {
// No elements
}
Using the Marker Annotation
@ThreadSafe
public class SafeCounter {
private int count = 0;
Page 16 of 20
Advance Java Unit 1
In Java, a single-member annotation is an annotation that has only one element, typically named value(). This
allows you to use a shorter syntax when applying the annotation.
import [Link];
import [Link];
Qns 15. How Can You Retrieve all Annotations that have RUNTIME retention by use of reflection? Explain with an
example
In Java, annotations that have @Retention([Link]) are available at runtime and can be retrieved
using reflection. Only annotations with RUNTIME retention can be accessed this way those with SOURCE or CLASS
retention are ignored at runtime.
Steps to Retrieve RUNTIME Annotations Using Reflection
1. Obtain the Class, Method, or Field object of the element you want to inspect.
2. Call getAnnotations() on the element.
o Returns an array of all runtime annotations present.
3. Optionally, loop through the array and process each annotation.
Syntax:
Annotation[] annotations = [Link]();
• element can be:
o Class<?> → for class-level annotations
o Method → for method-level annotations
o Field → for field-level annotations
Example
Suppose we have a custom annotation:
import [Link].*;
@MyAnnotation("Method Level")
public void myMethod() {
}
}
We can retrieve the annotations using reflection:
import [Link];
import [Link];
Qns 16. Discuss the key advantages that Java Beans provide to component developers
Page 18 of 20
Advance Java Unit 1
• This allows applications to remember user settings or component states between sessions.
6. Customizability
• JavaBeans can provide customizers (GUI panels) to allow users to configure properties in an intuitive way.
• This makes beans suitable for visual application development.
Qns 17. What are the different properties of a Java Bean? Explain with examples
1. Simple Property
• Holds a single value.
• Accessed via getter and setter methods.
Example:
public class Person {
private String name; // Simple property
public String getName() { // Getter
return name;
}
public void setName(String name) { // Setter
[Link] = name;
}
}
• Property name: name
• Usage: [Link]("Alice"); / String n = [Link]();
2. Indexed Property
• Holds a collection or array of values.
• Access individual elements using an index.
Example:
public class Scores {
private int[] marks; // Indexed property
3. Bound Property
• Notifies listeners when its value changes.
• Uses PropertyChangeListener to inform interested parties about changes.
Example:
import [Link].*;
Page 19 of 20
Advance Java Unit 1
}
public void setBalance(int balance) {
int old = [Link];
[Link] = balance;
[Link]("balance", old, balance); // Notify listeners
}
}
4. Constrained Property
• Notifies listeners before its value changes, allowing them to veto the change.
• Uses VetoableChangeListener.
Example:
import [Link].*;
Page 20 of 20