Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Java String Class n Annotations (1)

Uploaded by

Venu Bobby
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Java String Class n Annotations (1)

Uploaded by

Venu Bobby
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Java String

In Java, string is basically an object that represents sequence of char values.


An array of characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings


such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.

The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can
create strings in Java by using these three classes.
The Java String is immutable which means it cannot be changed. Whenever
we change any string, a new instance is created. For mutable strings, you
can use StringBuffer and StringBuilder classes.

We will discuss immutable string later. Let's first understand what String in
Java is and how to create the String object.

What is String in Java?


Generally, String is a sequence of characters. But in Java, string is an object
that represents a sequence of characters. The java.lang.String class is used
to create a string object.

How to create a string object?


There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the pooled
instance is returned. If the string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not
find any string object with the value "Welcome" in string constant pool that is
why it will create a new object. After that it will find the string with the value
"Welcome" in the pool, it will not create a new object but will return the
reference to the same instance.

Note: String objects are stored in a special memory area known as the "string constant
pool".

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if
it exists already in the string constant pool).

2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference var
iable

In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool.
The variable s will refer to the object in a heap (non-pool).

Java String Example


StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}
Test it Now

Output:

java
strings
example

The above code, converts a char array into a String object. And displays the
String objects s1, s2, and s3 on console using println() method.
Java String class methods
The java.lang.String class provides many useful methods to perform
operations on sequence of char values.

No. Method Description

1 char charAt(int index) It returns char value for the


particular index

2 int length() It returns string length

3 static String format(String format, Object... It returns a formatted string.


args)

4 static String format(Locale l, String format, It returns formatted string with


Object... args) given locale.

5 String substring(int beginIndex) It returns substring for given


begin index.

6 String substring(int beginIndex, int It returns substring for given


endIndex) begin index and end index.

7 boolean contains(CharSequence s) It returns true or false after


matching the sequence of char
value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, It returns a joined string.


Iterable<? extends CharSequence>
elements)

10 boolean equals(Object another) It checks the equality of string


with the given object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified


string.

13 String replace(char old, char new) It replaces all occurrences of


the specified char value.
14 String replace(CharSequence old, It replaces all occurrences of
CharSequence new) the specified CharSequence.

15 static String equalsIgnoreCase(String It compares another string. It


another) doesn't check case.

16 String[] split(String regex) It returns a split string


matching regex.

17 String[] split(String regex, int limit) It returns a split string


matching regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char


value index.

20 int indexOf(int ch, int fromIndex) It returns the specified char


value index starting with given
index.

21 int indexOf(String substring) It returns the specified


substring index.

22 int indexOf(String substring, int fromIndex) It returns the specified


substring index starting with
given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase


using specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase


using specified locale.

27 String trim() It removes beginning and


ending spaces of this string.

28 static String valueOf(int value) It converts given type into


string. It is an overloaded
method.
Java Annotations
Java Annotation is a tag that represents the metadata i.e. attached with
class, interface, methods or fields to indicate some additional information
which can be used by java compiler and JVM.

Annotations in Java are used to provide additional information, so it is an


alternative option for XML and Java marker interfaces.

First, we will learn some built-in annotations then we will move on creating
and using custom annotations.

Built-In Java Annotations


There are several built-in annotations in Java. Some annotations are applied
to Java code and some to other annotations.

Built-In Java Annotations used in Java code

o @Override
o @SuppressWarnings
o @Deprecated

Built-In Java Annotations used in other annotations

o @Target
o @Retention
o @Inherited
o @Documented

Understanding Built-In Annotations


Let's understand the built-in annotations first.

ADVERTISEMENT
@Override
@Override annotation assures that the subclass method is overriding the
parent class method. If it is not so, compile time error occurs.

Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is
better to mark @Override annotation that provides assurity that method is
overridden.

1. class Animal{
2. void eatSomething(){System.out.println("eating something");}
3. }
4. class Dog extends Animal{
5. @Override
6. void eatsomething(){System.out.println("eating foods");}//should be eatSom
ething
7. }
8. class TestAnnotation1{
9. public static void main(String args[]){
10. Animal a=new Dog();
11. a.eatSomething();
12. }}
Test it Now
Output:Comple Time Error

@SuppressWarnings
@SuppressWarnings annotation: is used to suppress warnings issued by the
compiler.

1. import java.util.*;
2. class TestAnnotation2{
3. @SuppressWarnings("unchecked")
4. public static void main(String args[]){
5. ArrayList list=new ArrayList();
6. list.add("sonoo");
7. list.add("vimal");
8. list.add("ratan");
9.
10. for(Object obj:list)
11. System.out.println(obj);
12.
13. }}
Test it Now
Now no warning at compile time.

If you remove the @SuppressWarnings("unchecked") annotation, it will show


warning at compile time because we are using non-generic collection.

@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler
prints warning. It informs user that it may be removed in the future versions.
So, it is better not to use such methods.

1. class A{
2. void m(){System.out.println("hello m");}
3.
4. @Deprecated
5. void n(){System.out.println("hello n");}
6. }
7. class TestAnnotation3{
8. public static void main(String args[]){
9.
10. A a=new A();
11. a.n();
12. }}
Test it Now

At Compile Time:
Note: Test.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

At Runtime:
hello n

Java Custom Annotations


Java Custom annotations or Java User-defined annotations are easy to
create and use. The @interface element is used to declare an annotation. For
example:

1. @interface MyAnnotation{}

Here, MyAnnotation is the custom annotation name.

Points to remember for java custom annotation signature

There are few points that should be remembered by the programmer.

1. Method should not have any throws clauses


2. Method should return one of the following: primitive data types, String,
Class, enum or array of these data types.
3. Method should not have any parameter.
4. We should attach @ just before interface keyword to define annotation.
5. It may assign a default value to the method.

Types of Annotation
There are three types of annotations.

1. Marker Annotation
2. Single-Value Annotation
3. Multi-Value Annotation

1) Marker Annotation
An annotation that has no method, is called marker annotation. For example:

1. @interface MyAnnotation{}

The @Override and @Deprecated are marker annotations.

2) Single-Value Annotation
An annotation that has one method, is called single-value annotation. For
example:

1. @interface MyAnnotation{
2. int value();
3. }
We can provide the default value also. For example:

1. @interface MyAnnotation{
2. int value() default 0;
3. }

How to apply Single-Value Annotation

Let's see the code to apply the single value annotation.

1. @MyAnnotation(value=10)

The value can be anything.

3) Multi-Value Annotation
An annotation that has more than one method, is called Multi-Value
annotation. For example:

1. @interface MyAnnotation{
2. int value1();
3. String value2();
4. String value3();
5. }
6. }

We can provide the default value also. For example:

1. @interface MyAnnotation{
2. int value1() default 1;
3. String value2() default "";
4. String value3() default "xyz";
5. }
How to apply Multi-Value Annotation

Let's see the code to apply the multi-value annotation.

1. @MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")

Built-in Annotations used in custom annotations in java


o @Target
o @Retention
o @Inherited
o @Documented

@Target
@Target tag is used to specify at which type, the annotation is used.

The java.lang.annotation.ElementType enum declares many constants to


specify the type of element where annotation is to be applied such as TYPE,
METHOD, FIELD etc. Let's see the constants of ElementType enum:

Element Types Where the annotation can be applied

TYPE class, interface or enumeration

FIELD Fields

METHOD Methods

CONSTRUCTOR Constructors

LOCAL_VARIABLE local variables

ANNOTATION_TYPE annotation type

PARAMETER Parameter
Example to specify annoation for a class

1. @Target(ElementType.TYPE)
2. @interface MyAnnotation{
3. int value1();
4. String value2();
5. }

Example to specify annotation for a class, methods or fields

1. @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})


2. @interface MyAnnotation{
3. int value1();
4. String value2();
5. }

@Retention
@Retention annotation is used to specify to what level annotation will be
available.

RetentionPolicy Availability

RetentionPolicy.SOUR refers to the source code, discarded during compilation. It will


CE not be available in the compiled class.

RetentionPolicy.CLAS refers to the .class file, available to java compiler but not to
S JVM . It is included in the class file.

RetentionPolicy.RUNTI refers to the runtime, available to java compiler and JVM .


ME

Example to specify the RetentionPolicy

1. @Retention(RetentionPolicy.RUNTIME)
2. @Target(ElementType.TYPE)
3. @interface MyAnnotation{
4. int value1();
5. String value2();
6. }

Example of custom annotation: creating, applying and


accessing annotation
Let's see the simple example of creating, applying and accessing annotation.

File: Test.java

1. //Creating annotation
2. import java.lang.annotation.*;
3. import java.lang.reflect.*;
4.
5. @Retention(RetentionPolicy.RUNTIME)
6. @Target(ElementType.METHOD)
7. @interface MyAnnotation{
8. int value();
9. }
10.
11. //Applying annotation
12. class Hello{
13. @MyAnnotation(value=10)
14. public void sayHello(){System.out.println("hello annotation");}
15. }
16.
17. //Accessing annotation
18. class TestCustomAnnotation1{
19. public static void main(String args[])throws Exception{
20.
21. Hello h=new Hello();
22. Method m=h.getClass().getMethod("sayHello");
23.
24. MyAnnotation manno=m.getAnnotation(MyAnnotation.class);
25. System.out.println("value is: "+manno.value());
26. }}
Test it Now
Output:value is: 10

download this example

How built-in annotaions are used in real scenario?

In real scenario, java programmer only need to apply annotation. He/She


doesn't need to create and access annotation. Creating and Accessing
annotation is performed by the implementation provider. On behalf of the
annotation, java compiler or JVM performs some additional operations.

1.

You might also like