0% found this document useful (0 votes)
15 views5 pages

Here': Example

java notes

Uploaded by

temp temp
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)
15 views5 pages

Here': Example

java notes

Uploaded by

temp temp
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
You are on page 1/ 5

1.

Enumerations (Enums)
Description: Enumerations, or enum types, are a special type of class in Java that represents
a group of constants. Enums are particularly useful when a variable can take one of a small
set of predefined values, such as days of the week, directions, or colors. Each constant in an
enum is a public, static, and final instance, which means that it is immutable and cannot be
modified.

Syntax:

enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3, ...
}

Example: Here’s an example of an enum that defines days of the week:

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

public class EnumExample {


public static void main(String[] args) {
Day today = Day.FRIDAY;
switch (today) {
case MONDAY:
System.out.println("Start of the work week!");
break;
case FRIDAY:
System.out.println("Almost weekend!");
break;
case SUNDAY:
System.out.println("Rest day.");
break;
default:
System.out.println("Regular day.");
}
}
}
Explanation: In this example, we defined an enum Day with seven constants. The switch
statement demonstrates how we can use enums for decision-making.

2. Autoboxing and Unboxing


Description: Autoboxing is the automatic conversion that the Java compiler makes between
primitive types (like int, double, boolean, etc.) and their corresponding object wrapper
classes (Integer, Double, Boolean, etc.). The reverse process, known as unboxing, converts
the wrapper classes back into primitives.

Example:

public class AutoboxingExample {


public static void main(String[] args) {
Integer integerObject = 5; // Autoboxing: int to Integer
int primitiveInt = integerObject; // Unboxing: Integer to int

System.out.println("Integer object: " + integerObject);


System.out.println("Primitive int: " + primitiveInt);
}
}

Explanation: In this example, the primitive int value 5 is automatically converted


(autoboxed) to an Integer object. When we assign integerObject to primitiveInt, it is
automatically unboxed back to a primitive.

3. Annotations in Java
Description: Annotations are a form of metadata added to Java code, primarily used to
provide information to the compiler, influence runtime behavior, or help with code
documentation. They don't change the code’s execution by themselves but can be
processed by tools, frameworks, or the compiler to add extra functionality. Java provides
several built-in annotations like @Override, @Deprecated, and @SuppressWarnings, but
custom annotations can also be created.

Built-in Annotations:

@Override: Indicates that a method overrides a method from a superclass. This helps the
compiler catch errors if the method signature doesn't match exactly.
@Deprecated: Marks a method or class as outdated, signaling to developers that a newer
version is preferred.
@SuppressWarnings: Suppresses specified compiler warnings, such as unchecked
operations or deprecated API usage.
Custom Annotations: Java also allows creating custom annotations, which can be used for
various purposes, like configuring methods for specific frameworks or for defining metadata
to be used at runtime.
Creating a Custom Annotation: A custom annotation can be defined with @interface.
Optionally, elements can be added to annotations, similar to attributes in a class. These
elements can have default values.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

// Define a custom annotation


@Retention(RetentionPolicy.RUNTIME) // Makes it accessible at runtime
@interface MyAnnotation {
String author();
String date();
String description() default "No description provided";
}
Explanation:

@Retention(RetentionPolicy.RUNTIME): Specifies that this annotation should be available at


runtime, which is useful when we need to process it using reflection.
String author(), String date(), and String description() default "No description provided"
define elements for the annotation. If description is not specified, it defaults to "No
description provided".

Using Custom Annotations: Here’s an example of how to apply the custom annotation.

public class AnnotationExample {

@MyAnnotation(author = "John Doe", date = "2024-11-05", description = "Example


method with annotation")
public void annotatedMethod() {
System.out.println("This method is annotated with MyAnnotation.");
}

public static void main(String[] args) {


AnnotationExample example = new AnnotationExample();
example.annotatedMethod();

// Accessing annotations at runtime


MyAnnotation annotation = example.getClass()
.getMethod("annotatedMethod")
.getAnnotation(MyAnnotation.class);

if (annotation != null) {
System.out.println("Author: " + annotation.author());
System.out.println("Date: " + annotation.date());
System.out.println("Description: " + annotation.description());
}
}
}
Explanation:
@MyAnnotation is applied to the annotatedMethod() method with specific values for each
element.
We use reflection (getMethod().getAnnotation()) to access the annotation and its values at
runtime.
Output:

This method is annotated with MyAnnotation.


Author: John Doe
Date: 2024-11-05
Description: Example method with annotation
Applications: Annotations are widely used in frameworks such as Spring and Hibernate. For
example:

@Entity (in Hibernate) marks a class as a database entity.


@Autowired (in Spring) allows dependency injection.
By using annotations, we can make code more readable, reduce boilerplate, and allow
frameworks to manage configurations automatically.

4. Generics

Description: Generics provide a way to create classes, interfaces, and methods with type
parameters. They allow code to be type-safe and reusable. For example, rather than writing
separate classes to handle Integer and String types, you can create a generic class that can
handle any type.

Syntax:

class ClassName<T> {
// Code using T
}
Example: Here’s a generic class Box that can hold any type:

class Box<T> {
private T content;

public void setContent(T content) {


this.content = content;
}

public T getContent() {
return content;
}
}

public class GenericsExample {


public static void main(String[] args) {
Box<Integer> integerBox = new Box<>();
integerBox.setContent(123);

Box<String> stringBox = new Box<>();


stringBox.setContent("Hello, Generics!");

System.out.println("Integer Box contains: " + integerBox.getContent());


System.out.println("String Box contains: " + stringBox.getContent());
}
}

Explanation: In this example, Box is a generic class with a type parameter T. This means Box
can store any type of data. We created Box objects to hold an Integer and a String,
demonstrating the flexibility of generics.

You might also like