0% found this document useful (0 votes)
19 views

String in Java

The document discusses the String class in Java. Some key points: 1) A String represents a sequence of characters. It is represented by the String class in the java.lang package. 2) String objects are immutable once created. 3) The String class implements interfaces like Serializable, Comparable, and CharSequence. CharSequence provides methods to access characters without specifying the implementation.

Uploaded by

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

String in Java

The document discusses the String class in Java. Some key points: 1) A String represents a sequence of characters. It is represented by the String class in the java.lang package. 2) String objects are immutable once created. 3) The String class implements interfaces like Serializable, Comparable, and CharSequence. CharSequence provides methods to access characters without specifying the implementation.

Uploaded by

Kaushik Ray
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

String is an 

object that represents sequence of characters. In Java,


String is represented by String class which is located
into java.lang package

In java, every string that we create is actually an object of


type String. One important thing to notice about string object is that
string objects are immutable that means once a string object is
created it cannot be changed.

The Java String class implements Serializable, Comparable and


CharSequence interface.

CharSequence Interface is used for representing a sequence of


characters. CharSequence interface is implemented by String,
StringBuffer and StringBuilder classes. This three classes can be used
for creating strings in java.
Creating a String object

1) Using a String literal

2) Using new Keyword

Using a String literal:

String literal is a simple string enclosed in double quotes " ". A string


literal is treated as a String object.

public class Demo{


public static void main(String[] args) {
String s1 = "Hello Java";
System.out.println(s1);
}
}

Using new Keyword:

We can create a new string object by using new operator that


allocates memory for the object.

public class Demo{


public static void main(String[] args) {
String s1 = new String("Hello Java");
System.out.println(s1);
}
}
String object and How they are stored

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.

String str= "Hello";


CharSequence interface in java
java.lang.CharSequence is an interface in the Java programming
language that represents a sequence of characters. It defines a set of
methods for accessing the characters in a string or other character
sequence, without specifying the underlying implementation.

The CharSequence interface is implemented by many classes in the


Java Standard Library, including String, StringBuilder, StringBuffer,
and CharBuffer. It provides a uniform way to work with character
sequences, regardless of the specific implementation.

Some of the methods defined by the CharSequence interface


include charAt(), length(), and subSequence(), which allow you to
access and manipulate the characters in a character sequence. These
methods are used extensively in Java programming for tasks such as
searching, sorting, and manipulating strings.

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.

However, the String class in Java is already serializable, which means


that it can be saved to a file or sent over a network without any
additional implementation of the Serializable interface.

Here is an example of how to serialize a String object:

java
import java.io.*;

public class SerializationExample {


public static void main(String[] args) {
String message = "Hello World!";

try {
// Serialize the object
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("message.ser"));
out.writeObject(message);
out.close();

// Deserialize the object


ObjectInputStream in = new ObjectInputStream(new
FileInputStream("message.ser"));
String deserializedMessage = (String) in.readObject();
in.close();

System.out.println(deserializedMessage);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Implementation of comparable interface by string class in java

In Java, the java.lang.String class already implements the


java.lang.Comparable interface, which means that instances of the
String class can be compared using the compareTo() method.

The compareTo() method is used to compare two strings


lexicographically. It returns an integer value that indicates whether
the string being compared is less than, equal to, or greater than the
other string. The method signature is as follows:

public int compareTo(String anotherString)

Concatenating String:

1. Using concat() method
2. Using + operator

Using concat() method:

public class Demo{


public static void main(String[] args) {
String s = "Hello";
String str = "Java";
String str1 = s.concat(str);
System.out.println(str1);
} }
Using + operator:

public class Demo{


public static void main(String[] args) {
String s = "Hello";
String str = "Java";
String str1 = s+str;
String str2 = "Java"+11;
System.out.println(str1);
System.out.println(str2);
} }

String Comparison

To compare string objects, Java provides methods and operators


both. So we can compare string in following three ways.

1. Using equals() method
2. Using == operator
3. By CompareTo() method

Using equals() method:

public class Demo{


public static void main(String[] args) {
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
boolean b = s1.equals(s2); //true
System.out.println(b);
b = s.equals(s1) ; //false
System.out.println(b);
} }
Using == operator

public class Demo{


public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
String s3 = new String ("Java");
boolean b = (s1 == s2); //true
System.out.println(b);
b = (s1 == s3); //false
System.out.println(b);
}
}

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:

 charAt(): It returns a character at a specified position.


 equals(): It compares the two given strings and returns
a Boolean, that is, True or False.
 concat(): Appends one string to the end of another.
 length(): Returns the length of a specified string.
 toLowerCase(): Converts the string to lowercase letters.
 toUpperCase(): Converts the string to uppercase letters.
 indexOf(): Returns the first found position of a character.
 substring(): Extracts the substring based on index values,
passed as an argument.

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));  
 }
}

You might also like