Jesse Haniel
Lead Software Architect at Tribunal de Justiça da Paraíba

Java Strings

Published in the Java Developer group

What is String in Java?

In programming, strings are very commonly used. String in java is an object that represents a sequence of characters backed by a char array. String class is immutable in Java and implements Comparable, Serializable, and CharSequence interfaces. Let’s look at an example to understand.

String str = "string"
Here str is the sequence of 6 characters which are s, t, r, i, n, and g.
Char Array Index 0 1 2 3 4 5
Value s t r i n g
Memory Address 0x12824 0x12825 0x12826 0x12827 0x12828 0x12829
As we now know the array is immutable, which means that it can not be changed after initialization, therefore the string is immutable as well.

Ways of String initialization

There are two ways to initialize a string.
  1. String Literals
  2. New Operator

String Literal

The easiest and most direct way of declaring a string is used in the above example. Whenever the compiler interprets a string literal, it is always converted to the String object.

String str = "string";

New Operator

We can also initialize a string by using the new operator.

String strNew = new String("using new operator");

Example


import java.io.*;
import java.lang.*;
 
class StringInitializationExample {
    public static void main(String[] args)
    {
        //declare java string with a string literal
        String str = "a string literal";
 
        System.out.println("String str = " + str);
 
        //declare string using new operator
        String strNew = new String("using new operator");
 
        System.out.println("String strNew = " + strNew);
    }
}

Output

String str = a string literal String strNew = using new operator

String vs StringBuilder vs StringBuffer

We have already discussed what is the String class so we will discuss the other two classes and their purpose, along with the reason why Java introduced these two classes when it already has the String class for us. It’s better for you to go to the top and have a revision for the String class to understand it in a better way.

Reason

As we know that the String class object is immutable so whenever we need to change the string it never mutates the current object but the changed value is always stored as a new String object. So if we need to change the value, again and again, memory will be consumed as well. Keeping this point Java has provided us with StringBuilder and StringBuffer classes. Now we will see how they are useful in this scenario.

StringBuffer

String is a representation of an immutable sequence of characters but StringBuffer is a mutable sequence of characters. It uses most of the String class methods along with a few of its own to change the contents and sequence of characters. It is thread-safe because its methods are synchronized for use by multiple threads, maintaining the serial order. It implements the Serializable, Appendable, and CharSequence interfaces.

Syntax


StringBuffer str = new StringBuffer("Happy Java Programming");

StringBuilder

StringBuilder also represents the mutable sequence of characters. It provides an API, which is compatible with the StringBuffer class but it is not thread-safe. So where multiple threads are not involved, it is better to go with the StringBuilder class as it is faster than the StringBuffer class in many cases. The key methods of this class are the insert and append. It also implements the Serializable, Appendable, and CharSequence interfaces.

Syntax


StringBuilder str = new StringBuilder("Happy Java Programming");

String Operations

In Java we can perform string operations like Concatenation, Comparing, Splitting, Finding Length, Replacing Strings and so on.

String Methods

The Java String class provides various methods for manipulating the strings or performing the above discussed operations. Let’s have a look at the below table for some of these string methods.
Methods Description
Char charAt(int index) It returns the char value at the provided index.
String concat(String str) It returns a string by combining a specified string to the end of this string.
boolean contains(CharSequence s) It returns true if the string contains a specified sequence of char values.
boolean contentEquals(CharSequence cs) It matches the string with the provided char sequence.
boolean contentEquals(StringBuffer sb) It matches the string with the provided string buffer.
boolean endsWith(String suffix) It compares the string end with the provided suffix.
boolean equals(Object anObject) It matches the string with the provided object.
boolean equalsIgnoreCase(String anotherString) This method compares two strings without taking case sensitivity into consideration.
static String format(String format, Object… args) It returns the formatted string by using the provided format and the arguments.
byte getBytes() This method uses the platform’s default charset for encoding the string into a sequence of bytes, which is then stored into a new byte array.
void getChars(int begin, int end, char[] dst, int dstBegin) It copies the characters from the string into the destination character array.
int hashCode() It returns the hash code for the string.
int indexOf(int ch) It returns the index for the specified character that occurs first from the string.
int indexOf(int ch, int fromIndex) It returns the index for the specified character which occurs first starting from the provided index in this string.
int indexOf(String str) It searches for the provided substring in the string and returns the index on the first occurrence.
int indexOf(String str, int fromIndex) It starts searching for the provided substring in the string from the given index and returns the index on the first occurrence.
String intern() This method returns the canonical representation of the string.
int lastIndexOf(int ch) This method searches for the provided character in the string and returns the index of the last occurrence.
int lastIndexOf(int ch, int fromIndex) This method searches backward from the given index for the provided character in the string and returns the index of the last occurrence.
int lastIndexOf(String str) This method searches for the provided substring in the string and returns the index of the last occurrence.
int lastIndexOf(String str, int fromIndex) This method searches backward from the given index for the provided substring in the string and returns the index of the last occurrence.
int length() This method returns the length of the string.
boolean matches(String regex) It returns true or false by matching the string with the provided regular expression.
String replace(char oldValue, char newValue) This method returns a string after replacing all the provided oldValue with the newValue in the string.
String[] split(String regex) This method finds all the matches according to the provided regular expression in the string and splits it around these matches.
boolean startsWith(String prefix) It returns true or false by testing the string start with the provided prefix.
String substring(int beginIndex) This method returns a string which is the substring of this string.
String toLowerCase() It converts all the characters of the string into lowercase using the rules of the default locale.
String trim() This method removes all the leading and trailing whitespaces from the string and returns it.
static String valueOf(char c) It returns the string representation of the char argument.
Now with the help of a few examples, we will see how to use them. Java Strings - 1

Example


import java.io.*;
import java.lang.*;
 
class JavaStringsExample {
  public static void main(String[] args) {

    //create a string
    String greeting = "Hello! World";
    System.out.println("String: " + greeting);

    //getting the length of greeting object
    int length = greeting.length();
    System.out.println("Length: " + length);
    
    //create first string
    String first = "Java ";
    System.out.println("First String: " + first);

    //create second string
    String second = "Programming";
    System.out.println("Second String: " + second);

    //joining two strings
    String joinedString = first.concat(second);
    System.out.println("Joined String: " + joinedString);
    
    String jpf = "Java programming";
    String jps = "Java programming";
    String jpt = "Python programming";

    //compare jpf and jps strings
    boolean result1 = jpf.equals(jps);
    System.out.println("Strings jpf and jps are equal: " + result1);

    //compare jpf and jpt strings
    boolean result2 = jpf.equals(jpt);
    System.out.println("Strings jpf and jpt are equal: " + result2);
    
    //converting jpf to uppercase
    System.out.println("Upper case jpf: " + jpf.toUpperCase());
    
    //replacing g character with v in jpf
    System.out.println("Replacing g with v in jpf: "+jpf.replace("g", "v"));
  }
}

Output

String: Hello! World Length: 12 First String: Java Second String: Programming Joined String: Java Programming Strings jpf and jps are equal: true Strings jpf and jpt are equal: false Upper case jpf: JAVA PROGRAMMING Replacing g with v in jpf: java provramminv

Conclusion

We hope by now you understand what are strings in java, its classes and how to implement its different methods. Feel free to practice and get back whenever you need more assistance. Happy learning!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION