String in Java
String in Java
When we create a new string object using string literal, that string
literal is added to the string pool, if it is not present there already.
import java.lang.CharSequence;
import java.lang.String;
class Example
{
public static void main(String[] args)
{
CharSequence x = new String("ABCDE");
// Interface method
System.out.println(x.toString());
System.out.println(x.charAt(0));
System.out.println(x.length());
System.out.println(x.subSequence(0, 2));
// IntStream of Unicode code points from this sequence
System.out.println(x.codePoints());
// IntStream of char values from this sequence
System.out.println(x.chars());
}
}
Implementation of Serializable interface by string class in java
In Java, the Serializable interface is used to indicate that a class can
be serialized, which means that its objects can be converted into a
stream of bytes and then saved to a file or sent over a network.
java
import java.io.*;
try {
// Serialize the object
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("message.ser"));
out.writeObject(message);
out.close();
System.out.println(deserializedMessage);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Implementation of comparable interface by string class in java
Concatenating String:
1. Using concat() method
2. Using + operator
Using concat() method:
String Comparison
1. Using equals() method
2. Using == operator
3. By CompareTo() method
By CompareTo() method
public class HelloWorld{
public static void main(String[] args) {
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
int a = s1.compareTo(s2); //return -21 because s1 < s2
System.out.println(a);
a = s1.compareTo(s3); //return 0 because s1 == s3
System.out.println(a);
a = s2.compareTo(s1); //return 21 because s2 > s1
System.out.println(a);
}
}
Methods of String:
Program:
class Main{
public static void main(String []args)
{
String s1="Adithya";
String s2="Adithya";
String s3="Adi";
boolean x=s1.equals(s2);
System.out.println("Compare s1 and s2:"+x);
System.out.println("Character at given position is:"+s1.charAt(5));
System.out.println(s1.concat(" the author"));
System.out.println(s1.length());
System.out.println(s1.toLowerCase());
System.out.println(s1.toUpperCase());
System.out.println(s1.indexOf('a'));
System.out.println(s1.substring(0,4));
System.out.println(s1.substring(4));
}
}