0% found this document useful (0 votes)
2 views20 pages

A Java Q Unit1

Mangalore University lecturers prescribed answers

Uploaded by

Sindhoor J K
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

A Java Q Unit1

Mangalore University lecturers prescribed answers

Uploaded by

Sindhoor J K
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Advance Java Unit 1

Qns 1. With the syntax write the purpose of ordinal() method.

The ordinal() method returns the index position of an enum constant in its enum declaration, starting from 0.

Syntax :- [Link]();

Qns 2. List two key characteristics of enumeration constants in Java.

They are implicitly public static final in Java.

I) Enumeration constants represent a fixed set of predefined values.

II) Once declared in the enum, no additional constants can be added at runtime.

Qns 3. What is an enumeration? How enumeration can be created?

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.

enum Day { MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY }

Qns 4. Differentiate values() and valueOf() methods in Java enumerations.

values() → returns all enumeration constants as an array.


valueOf() → returns a specific enum constant using its name.
enum Day { MONDAY, TUESDAY, WEDNESDAY }
public class Test {
public static void main(String[] args) {
// values()
for (Day d : [Link]()) {
[Link](d);
}

// 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.

enum Day { MONDAY, TUESDAY, WEDNESDAY }


public class Test {
public static void main(String[] args) {
// values()
for (Day d : [Link]()) {
[Link](d);
}
}

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
.

equals() → checks if two enum constants are identical.


The equals() method checks whether two enum constants are exactly the same.
It returns a boolean value:
true → if both constants are the same
false → if they are different

Qns 7. Why are type wrappers used in Java?

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?

Autoboxing: Automatic conversion of a primitive type to its wrapper object.


Auto-unboxing: Automatic conversion of a wrapper object to its primitive type.
Benefits of Autoboxing and Auto-Unboxing
1. Reduces Code Complexity
2. Improves Readability
3. Easy Use with Collections
4. Automatic Conversion in Expressions
Qns 10. What is retention policy? How to set retention policy? Give an example

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();
}

public class Test {


@MyAnnotation(value = "Example Annotation")
public void display() {
[Link]("Hello");
}
}

Page 2 of 20
Advance Java Unit 1
Qns 11. List any two retention policies with its purpose.

Two Retention Policies and Their Purpose


1. SOURCE
o Purpose: The annotation is available only in the source code and is discarded by the compiler.
o It is mainly used for compile-time processing or documentation.
2. RUNTIME
o Purpose: The annotation is retained during program execution.
o It can be accessed using reflection at runtime.

Qns 12. What is the purpose of setting default values to annotation member. Write the general form for setting
default values.

Purpose of Setting Default Values


1. Avoid Mandatory Values:
o The user does not need to specify every member when using the annotation.
2. Provide Fallback Behaviour:
o If no value is provided, the default ensures the annotation still works correctly.
3. Simplify Annotation Usage:
o Makes annotations more flexible and easier to use.
import [Link].*;

@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");
}
}

Qns 13. Define

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

b. Single Member Annotation.

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.

1. Cannot Contain Constructors


• An annotation cannot have constructors.
• Java automatically provides a default constructor for annotations.
• You cannot explicitly define a constructor in an annotation.
2. Members Cannot Be Void
• Annotation members cannot have void as a return type.
• Every member must return a primitive type, String, Class, enum, annotation, or array of these types.

Qns 16. What is the primary purpose of annotations in Java code?

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.

Qns 17. How are annotations declared in Java?Give example

@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];

Class<?> clazz = [Link];

Annotation[] annotations = [Link]();

for (Annotation annotation : annotations) {


[Link](annotation);
}

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.

Qns 20. What are some key characteristics of a Java Bean?

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.

Qns 21. List two advantages of Java Beans

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.

Qns 22. Why is introspection essential for Java Beans technology?

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?

Feature Bound Property Constrained Property


A property that notifies listeners before the
A property that notifies listeners
Definition value changes and allows them to reject the
after its value has changed
change
Notification time After the property value is changed Before the property value is changed
Listener type Uses PropertyChangeListener Uses VetoableChangeListener
Uses PropertyChangeEvent, but can throw
Event class Uses PropertyChangeEvent
PropertyVetoException
Control over Listeners cannot prevent the
Listeners can veto (cancel) the change
change change

Qns 26. What is persistence in JavaBeans?

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

Qns 27. What are customizers?

• A customizer provides a graphical interface (GUI) to change the properties of a bean.


• It is used when standard property editors are not sufficient to configure complex properties.
• The customizer class usually implements the [Link] interface.
• Allows advanced or complex configuration of a bean.

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.

How Enum Values Are Used in Switch


• Each enum constant can act as a case label in the switch statement.
• This allows you to perform different actions based on the enum value.
• No need for EnumName. prefix inside case labels
Example :-

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }

public class Test {


public static void main(String[] args) {
Day today = [Link];

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 }

public class EnumMethodsDemo {


public static void main(String[] args) {
Day d1 = [Link];
Day d2 = [Link];
// ordinal()
[Link](d1 + " ordinal: " + [Link]());
// compareTo()
[Link](d1 + " compareTo " + d2 + ": " + [Link](d2));
// equals()
[Link](d1 + " equals " + d2 + "? " + [Link](d2));
}
}

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.

Key Points That Show Enums Are Class Types


1. Enums can have fields and methods
2. Enums can have constructors (implicitly private)
3. Each enum constant is an object of the enum type
4. Enums can implement interfaces
5. Enums extend [Link] internally
Example of Enum as a Class

enum Day {
MONDAY("Weekday"),
TUESDAY("Weekday"),
WEDNESDAY("Weekday"),
THURSDAY("Weekday"),
FRIDAY("Weekday"),
SATURDAY("Weekend"),
SUNDAY("Weekend");

private String type; // Field

// Constructor (implicitly private)


Day(String type) {
[Link] = type;
}

// Method
public String getType() {
return type;
}

@Override
public String toString() {
return name() + " is a " + type;
}
}

Using the Enum

public class EnumTest {


public static void main(String[] args) {
for (Day day : [Link]()) { // values() method from [Link]
[Link](day); // Calls toString() method
}
}
}

Qns 5. Explain with example how Enumerations can Inherit Enum?

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.

1. Using Interfaces with Enums

Step 1: Define an Interface

interface Describable {
String getDescription();
}

Step 2: Enum Implements Interface

enum Color implements Describable {


RED("Red color"),
GREEN("Green color"),
BLUE("Blue color");

private String description;

// Constructor
Color(String description) {
[Link] = description;
}

// Implement interface method


@Override
public String getDescription() {
return description;
}
}

Step 3: Using the Enum

public class EnumDemo {


public static void main(String[] args) {
for (Color c : [Link]()) {
[Link](c + ": " + [Link]());
}
}
}

Qns 6. Describe the Wrapper classes available for primitive types.

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

Qns 7. What Is Autoboxing and Unboxing? Explain with an example.

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

Example Shows Autoboxing and Unboxing

import [Link];

public class AutoboxingUnboxingDemo {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();

// Autoboxing: adding primitive int directly to ArrayList


[Link](5);
[Link](10);

// Unboxing: retrieving values as int


int sum = 0;
for (Integer n : numbers) {
sum += n; // n is automatically unboxed to int
}

[Link]("Sum = " + sum); // Output: Sum = 15


}
}

Qns 8. With an example explain the steps involved to obtain annotation at run time using reflection.

Steps to Obtain Annotations at Runtime


1. Define an annotation with RUNTIME retention
o Only annotations with @Retention([Link]) can be accessed at runtime.

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].*;

// Step 1: Define a runtime annotation


@Retention([Link])
@interface Author {
String name();
int year();
}
// Step 2: Apply the annotation
@Author(name = "Alice", year = 2026)
class Book {
@Author(name = "Bob", year = 2025)
public void display() {
[Link]("Display method");
}
}
// Step 3: Retrieve annotation at runtime
public class AnnotationReflectionDemo {
public static void main(String[] args) throws Exception {
// Get Class object
Class<Book> clazz = [Link];

// Step 4a: Get class-level annotation


if ([Link]([Link])) {
Author author = [Link]([Link]);
[Link]("Class Author: " + [Link]() + ", Year: " + [Link]());
}
// Step 4b: Get method-level annotation
Method method = [Link]("display");
if ([Link]([Link])) {
Author methodAuthor = [Link]([Link]);
[Link]("Method Author: " + [Link]() + ", Year: " + [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.

Qns 10. Write an example program to illustrate reflection.

import [Link];
import [Link];

// Sample class to inspect


class Person {
private String name;
private int age;
public Person() {
[Link] = "Unknown";
[Link] = 0;
}
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
public int getAge() { return age; }
public void setAge(int age) { [Link] = age; }
public void display() {
[Link]("Name: " + name + ", Age: " + age);
}
Page 13 of 20
Advance Java Unit 1
}
public class ReflectionDemo {
public static void main(String[] args) throws Exception {
// 1. Obtain Class object
Class<Person> clazz = [Link];
// 2. Display class name
[Link]("Class Name: " + [Link]());
// 3. Get and display declared fields
[Link]("\nFields:");
Field[] fields = [Link]();
for (Field field : fields) {
[Link](" " + [Link]() + " (" + [Link]().getSimpleName() + ")");
}
// 4. Get and display declared methods
[Link]("\nMethods:");
Method[] methods = [Link]();
for (Method method : methods) {
[Link](" " + [Link]());
}
// 5. Create instance using default constructor
Person person = [Link]().newInstance();
// 6. Invoke a method using reflection
Method setName = [Link]("setName", [Link]);
[Link](person, "Alice");
Method setAge = [Link]("setAge", [Link]);
[Link](person, 25);
Method display = [Link]("display");
[Link](person);
}
}

1. Class<?> clazz = [Link]; → Get the Class object for reflection.


2. getDeclaredFields() → Retrieve all fields of the class.
3. getDeclaredMethods() → Retrieve all methods.
4. [Link]().newInstance() → Create an instance dynamically.
5. [Link]() → Call a method at runtime without direct access.

Qns 11. Explain any four Built-in annotations.

Here are four commonly used built-in annotations in Java along with their purpose and usage:
1. @Override

Indicates that a method is intended to override a method in the superclass.


The compiler checks if the method actually overrides a parent method and generates an error if it does not,
preventing mistakes.
Example:
class Parent {
void show() {}
}

class Child extends Parent {


@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];

// Define annotation with default value


@Retention([Link])
@interface Author {
String name() default "Unknown"; // default value
int year() default 2026;
}

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];

public class Test {


public static void main(String[] args) {
Author author = [Link]([Link]);
[Link]([Link]()); // Outputs: Unknown
[Link]([Link]()); // Outputs: 2026
}
}

Qns 13. Write an example of defining a marker annotation

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;

public synchronized void increment() {


count++;
}

public synchronized int getCount() {


return count;
}
}

Page 16 of 20
Advance Java Unit 1

Qns 14. Write an example of defining a single-member annotation

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.

Defining a Single-Member Annotation

import [Link];
import [Link];

// Define a single-member annotation


@Retention([Link]) // Available at runtime
@interface Author {
String value(); // Single element named "value"
}

Using the Single-Member Annotation

@Author("Alice") // No need to specify "value="


public class Book {
// Class implementation
}

Equivalent longer form:

@Author(value = "Alice") // Explicitly specifying the element


public class Book {
}

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].*;

@Retention([Link]) // Available at runtime


@Target({[Link], [Link]})
Page 17 of 20
Advance Java Unit 1
@interface MyAnnotation {
String value();
}
And a class that uses it:
@MyAnnotation("Class Level")
public class MyClass {

@MyAnnotation("Method Level")
public void myMethod() {
}
}
We can retrieve the annotations using reflection:
import [Link];
import [Link];

public class AnnotationDemo {


public static void main(String[] args) throws Exception {
// Get the Class object
Class<MyClass> clazz = [Link];
// Retrieve class-level annotations
Annotation[] classAnnotations = [Link]();
for (Annotation annotation : classAnnotations) {
[Link]("Class Annotation: " + annotation);
}
// Retrieve method-level annotations
Method method = [Link]("myMethod");
Annotation[] methodAnnotations = [Link]();
for (Annotation annotation : methodAnnotations) {
[Link]("Method Annotation: " + annotation);
}
}
}

Qns 16. Discuss the key advantages that Java Beans provide to component developers

JavaBeans provide several key advantages to component developers


1. Reusability
• JavaBeans are designed as self-contained, modular components.
• They can be used across multiple applications without modification.
• Developers can build libraries of reusable beans, saving time and effort.
2. Encapsulation
• Properties of a bean are private and accessed only through getter and setter methods.
• This protects the internal state of the bean from direct access, improving code safety and maintainability.
3. Tool Support and Introspection
• JavaBeans follow standard naming conventions for properties (getX, setX).
• This allows development tools (IDEs, GUI builders) to automatically discover and manipulate properties,
events, and methods.
• Developers can configure beans visually without writing code.
4. Event Handling
• Beans can generate and respond to events through bound and constrained properties.
• Developers can decouple components, allowing flexible communication between beans.
5. Persistence
• Beans can save their state to a file or database and restore it later (serialization).

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

public int getMarks(int index) { // Indexed getter


return marks[index];
}
public void setMarks(int index, int value) { // Indexed setter
marks[index] = value;
}
}
• Property name: marks
• Usage: [Link](0, 95); / int mark = [Link](0);

3. Bound Property
• Notifies listeners when its value changes.
• Uses PropertyChangeListener to inform interested parties about changes.
Example:
import [Link].*;

public class Account {


private int balance;
private PropertyChangeSupport support = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener listener) {
[Link](listener);
}
public int getBalance() {
return balance;

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].*;

public class Employee {


private int salary;
private VetoableChangeSupport support = new VetoableChangeSupport(this);
public void addVetoableChangeListener(VetoableChangeListener listener) {
[Link](listener);
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) throws PropertyVetoException {
int old = [Link];
[Link]("salary", old, salary); // Can throw veto
[Link] = salary;
}
}

Page 20 of 20

You might also like