top of page

How to Use Annotations and Base64 Encoding in Java - A Complete Guide

Welcome to Codes with Pankaj! In this tutorial, we’ll explore two important topics in Java: Annotations and Base64 Encoding. We’ll break down each topic into simple, easy-to-understand sections with practical examples. Let's get started!


1. Annotations in Java


1.1 What Are Annotations?

Annotations are like labels or notes you can attach to your code. They provide information about your code but don’t change how it works. Think of annotations as sticky notes that give extra details about a class, method, or variable.

1.2 Commonly Used Annotations

Here are some annotations that are commonly used in Java:

  • @Override: This tells the compiler that a method is meant to override a method in a parent class.

  • @Deprecated: This marks a method as outdated, meaning it shouldn’t be used because there’s a better alternative.

  • @SuppressWarnings: This tells the compiler to ignore certain warnings for a piece of code.

Example :


class ParentClass {

    void display() {

        System.out.println("Parent class method");

    }

}

class ChildClass extends ParentClass {

    @Override

    void display() {  // Tells the compiler this method overrides a method from the parent class

        System.out.println("Child class method");

    }

}

1.3 Creating Your Own Annotation

You can also create your own annotations to add custom information to your code. Let’s create an annotation called @Author to show who wrote the code.

Step 1: Define the Annotation

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)  // Annotation is available at runtime

@Target({ElementType.TYPE, ElementType.METHOD})  // Can be used on classes and methods

public @interface Author {

    String name();

    String date();

}

Step 2: Use the Annotation

@Author(name = "Pankaj", date = "2024-09-02")

public class MyClass {

    @Author(name = "Pankaj", date = "2024-09-02")

    public void myMethod() {

        System.out.println("This method is annotated!");

    }

}

1.4 Reading Annotations at Runtime

You can use Java’s reflection to read annotations while your program is running.

Example :

import java.lang.reflect.Method;

public class AnnotationExample {

    public static void main(String[] args) {

        // Check if the class has the @Author annotation

        if (MyClass.class.isAnnotationPresent(Author.class)) {

            Author author = MyClass.class.getAnnotation(Author.class);

            System.out.println("Class Author: " + author.name() + ", Date: " + author.date());

        }

        // Check if the method has the @Author annotation

        try {

            Method method = MyClass.class.getMethod("myMethod");

            if (method.isAnnotationPresent(Author.class)) {

                Author author = method.getAnnotation(Author.class);

                System.out.println("Method Author: " + author.name() + ", Date: " + author.date());

            }

        } catch (NoSuchMethodException e) {

            e.printStackTrace();

        }

    }

}

2. Base64 Encoding and Decoding in Java

Base64 encoding is a way to convert data (like text or files) into a string of letters and numbers. This is useful for sending data over the internet, where certain characters might cause problems.

2.1 Base64 Encoding

Encoding means converting data into a different format. With Base64, we convert text or files into a string that’s safe to use in emails or URLs.

Example:

import java.util.Base64;

public class Base64Example {

    public static void main(String[] args) {

        String originalString = "codes with pankaj";

        String encodedString = Base64.getEncoder().encodeToString(originalString.getBytes());

        System.out.println("Original String: " + originalString);

        System.out.println("Encoded String: " + encodedString);

    }

}

Output:

Original String: codes with pankaj
Encoded String: Y29kZXMgd2l0aCBwYW5rYWo=

2.2 Base64 Decoding

Decoding is the reverse process of encoding. It means converting the Base64 string back to its original form.

Example :


import java.util.Base64;

public class Base64Example {

    public static void main(String[] args) {

        String encodedString = "Y29kZXMgd2l0aCBwYW5rYWo=";

        byte[] decodedBytes = Base64.getDecoder().decode(encodedString);

        String decodedString = new String(decodedBytes);

        System.out.println("Encoded String: " + encodedString);

        System.out.println("Decoded String: " + decodedString);

    }

}

Output:

Encoded String: Y29kZXMgd2l0aCBwYW5rYWo=
Decoded String: codes with pankaj

2.3 Encoding and Decoding Files

You can also encode files into a Base64 string and decode them back into a file.

Example :


import java.util.Base64;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.io.IOException;

public class FileBase64Example {

    public static void main(String[] args) {

        try {

            // Read file and encode it to Base64

            byte[] fileContent = Files.readAllBytes(Paths.get("example.txt"));

            String encodedString = Base64.getEncoder().encodeToString(fileContent);

            System.out.println("Encoded File String: " + encodedString);

            // Decode Base64 string back to file

            byte[] decodedBytes = Base64.getDecoder().decode(encodedString);

            Files.write(Paths.get("decoded_example.txt"), decodedBytes);

            System.out.println("File successfully decoded!");

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}




Conclusion

In this tutorial, we learned about Annotations and Base64 Encoding in Java. Annotations help add extra information to your code, making it easier to manage and understand. Base64 encoding is a useful tool for converting data into a format that can be easily shared or stored.

Thank you for joining me at




Related Posts

See All

Java Date and Time API Tutorial

Welcome to Code with Pankaj! In this tutorial, we'll explore the Java Date and Time API, introduced in Java 8. This API provides a...

Comments


bottom of page