Java Strings

Java Strings is a non primitive data type that stores sequence of characters. It is used to store text or sentences in a variable. Strings are written in double quotes (“”).

Java String Class

In Java programming language there is class called String that helps to create and manipulate strings. Java strings are arrays of characters that are very commonly used in java programming.

Create String Variable

The syntax for declaring a java string variable is:

The syntax for initializing a string variable is:

The code below shows how to create a string variable and print the text stored in it:

public class MyProgram {
  public static void main(String[] args) {
    String var = "Hello World!";
    System.out.println(var);
  }
}

The output of the above code after compilation is:

The other syntax for defining a string variable is by using new keyword. The new keyword creates an object of the String class.

The code below converts char array into String object.

public class MyProgram {
   public static void main(String args[]) {
      char[] textArray = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!' };
      String textString = new String(textArray);  
      System.out.println( textString );
   }
}

The output of the above code after compilation is:

Java String Manipulations

Programmer can perform various manipulations on a String object. These built in methods are called accessor methods.

String Length

Each string that is defined in the program has a length. The length of string is useful to perform string manipulations. The String class provides a built in method length() to calculate the length of string. Each character in a string object has an index. The string index starts at 0.

In the code below, the length of the string variable var is stored in an int variable len. Note that the length of a string is equal to the number of characters in it, considering space as a character too.

public class MyProgram {
  public static void main(String[] args) {
    String var = "Hello World!";
    int len = var.length();
    System.out.println("The length of the var string is: " + len);
  }
}

The output of the above code after compilation is:


String Concatenation

The String class provides a method to join two strings. The method is concat(). The syntax for using concat() is:

The other way to join to strings is by using (+) operator. The syntax is:

The result is a concatenated string. The stringB is added at the end of stringA.

public class MyProgram {
  public static void main(String args[]) {
    String stringA = "Hello";
    String stringB = "World!";
    System.out.println(stringA + " " + stringB);
    System.out.println(stringA.concat(stringB));
  }
}

The output of the above code after compilation is:

String Formatting

The string class provides two methods to create formatted strings. The methods are printf() and format(). These strings take variable values using % sign. Instead of writing multiple print statements for each variable, programmer can write a generic print statement and add the values of variables in it.

In the example below, printf() method is used to create formatted string. Note that we use %d to access int type variable, %f to access float type variable and %s to access string.

public class MyProgram {
  public static void main(String[] args) {
    int varA = 41;
    float varB = 12;
    String varC = "Java";
    System.out.printf("The value of the integer variable is " +
                  "%d, the value of the float " +
                  "variable is %f, and the string variable " +
                  "is %s.", varA, varB, varC);
  }
}

The output of the above code after compilation is:

Other Java String Methods

Here is a list of String methods and their description provided by Java String class.

Sr.No.MethodDescription
1.toUpperCase()Converts all lower case alphabets in a string object to upper case.
2.toLowerCase()Converts all upper case alphabets in a string object to lower case.
3.indexOf()Takes string as input parameter and returns the index of first occurrence of the string in its parameter.
4.charAt()Take int as input and returns the character at the index value in its parameter.
5.compareTo()Performs comparison between a string and an object or between two strings.
6.compareToIgnoreCase()Compares to strings lexicographically and ignores the case difference
7.concat()Concatenates one string at the end of the other string and returns a string.
8.contentEquals()Compares two string and returns true if the sequence of characters of the two strings match.
9.copyValueOf()Takes char array as input and returns a string with same characters as that of the array.
10.endsWith()Returns true if the string ends with the input string suffix parameter. Otherwise returns false.
11.startsWith()Returns true if the string starts with the input string prefix parameter. Otherwise returns false.
12.equalsIgnoreCase()Compares two strings while ignoring case difference and returns either true or false.
13.getBytes()Takes a string and converts it to a sequence of bytes and returns bytes.
14.getChars()Copies characters of a string into char array.
15.hashCode()Returns an int hash code for a string.
16.intern()Returns a string that is a canonical representation of the input string.
17.lastIndexOf()Returns index of the last occurrence of specified character in the string.
18.length()Returns the length of the input string.
19.matches()Compares string with a regular expression and returns true if the match is successful.
20.regionMatches()Compares if two string regions match and returns true or false.
21.replace()Replaces all characters from one char array to another and returns a string.
22.replaceAll()Replaces all substrings matching a regex in a string, with another string.
23.replaceFirst()Replaces the first found match with regex in a string, with another string.
24.split()Splits the given string according to the input regular expression.
25.equals()Compares two strings and returns either true or false.
26.subSequence()It takes start and end indices as two input parameters and returns a new character sequence that is a subsequence of input sequence.
27.substring()Takes a starting index as input parameter and returns a substring of the main string.
28.toString()Takes a string and returns the same string.
29.toCharArray()Takes a string and converts it into a character char array.
30. trim()Returns a string after removing its white spaces from beginning and the end.
Java String Methods

Comments are closed.