Annotations In Java

Haneef Muhammad
2 min readJul 4, 2021

--

Annotations are nothing but a way we can highlight a piece of information, for e.g., during our school years, we would highlight or underline certain lines of our books through which we give an indication to ourselves that these lines are important. Also if some one else were to use your book after you, it would be a major help for them when they go through it.

This is what annotation is, it is a way to add extra information to certain things, the same applies to a code, annotations help in adding some information to our code which in-turn help us to avoid potential run-time errors by informing them during compilation.

Let us look at the below example to get a clear picture of how annotations help us,

Without annotation

Class example for annotations

The result of this example would give,

So as you can see we are using a method that was specified not to use using a comment, and this resulted in executing a piece of code that has not been decided not to use, which can cause unwanted run-time errors.

Now with the help of annotations, the previous example would become,
With annotation,

As you can see by using an in-build annotation “@Deprecated” we are able to warn the user that they are using a deprecated piece of code, by converting a potential run-time error into a compile-time warning.

Also you should note that all annotations in java begin with a “@”.

--

--

No responses yet