Java - Strings


Advertisements

Previous Page Next Page

Java Strings

Strings are one of the most common data types in Java. It is used for storing text. It can be created by enclosing characters in double quotation marks. It can be assigned to a variable using = sign.

String MyString = "Hello World!";

String Length

A String in Java is an object and the String object has a method called length() which can be used to find the total number of characters in the String.

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

Output

12

Check a character in the String

Java String has indexOf() method which returns index position of first occurrence of specified text in the string. Please note that, Java counts index position from 0.

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Hello World!";
    System.out.println(MyString.indexOf("Wor"));  
  }
}

Output

6

String Concatenation

In Java, two strings can be joined using + operator. Along with this, Java String has concat() method which can also be used to combine two strings.

public class MyClass {
  public static void main(String[] args) {
    String text_1 = "Learn ";
    String text_2 = "Java ";
    String text_3 = "with AlphaCodingSkills.com";
    System.out.println(text_1 + text_2 + text_3); 
    System.out.println(text_1.concat(text_2).concat(text_3));  
  }
}

Output

Learn Java with AlphaCodingSkills.com
Learn Java with AlphaCodingSkills.com

Special Strings in String

The backslash \ escape character is used to convert special character like single quote, double quote, new line, etc. into the string character. The below mentioned table describes special characters in Java:

Escape CharacterResultExample
\' ' "\'Java\'" is converted into: 'Java'
\" " "\"World\"" is converted into: "World"
\\ \ "A\\C" is converted into: A\C
\n new line "Hello\nJohn" is converted into:
Hello
John
\t Tab "Hello\tMarry" is converted into: Hello    Marry
\b Backspace "Hello J\bava" is converted into: Hello ava
\r Carriage Return "Hello\rJohn" is converted into:
Hello
John

Note:Carriage return is not same as new line. It simply means return to the left margin.

String Methods

For complete list of string methods, please refer to string methods page. Here, few very common string methods are discussed.

  • toLowerCase(): Returns string in lowercase
  • toUpperCase(): Returns string in uppercase
  • trim(): Removes whitespaces from start and end of the string
  • replace(): replace specified character(s) with another specified character(s)

Example: toLowerCase() and toUpperCase() String Methods


public class MyClass {
  public static void main(String[] args) {
    String MyString = "Learn Java";
    System.out.println(MyString.toLowerCase()); 
    System.out.println(MyString.toUpperCase());  
  }
}

Output

learn java
LEARN JAVA

Example: trim() and replace() String Methods


public class MyClass {
  public static void main(String[] args) {
    String MyString = "  Hello World!  ";
    System.out.println(MyString.trim()); 
    System.out.println(MyString.replace("World!", "Java"));  
  }
}

Output

Hello World!
  Hello Java 

Java String Methods
MethodDescription
charAt() Returns the character at the specified index (position)
codePointAt() Returns the Unicode of the character at the specified index
codePointBefore() Returns the Unicode of the character before the specified index
codePointCount() Returns the Unicode in the specified text range of this String
compareTo() Compares two strings lexicographically
compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences
concat() Appends a string to the end of another string
contains() Checks whether a string contains a sequence of characters
contentEquals() Checks whether a string contains the exact same sequence of characters of the specified CharSequence or StringBuffer
copyValueOf() Returns a String that represents the characters of the character array
endsWith() Checks whether a string ends with the specified character(s)
equals() Compares two strings. Returns true if the strings are equal, and false if not
equalsIgnoreCase() Compares two strings, ignoring case considerations
format() Returns a formatted string using the specified locale, format string, and arguments
getBytes() Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array
getChars() Copies characters from a string to an array of chars
hashCode() Returns the hash code of a string
indexOf() Returns the position of the first found occurrence of specified characters in a string
intern() Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index
isEmpty() Checks whether a string is empty or not
lastIndexOf() Returns the position of the last found occurrence of specified characters in a string
length() Returns the length of a specified string
matches() Searches a string for a match against a regular expression, and returns the matches
offsetByCodePoints() Returns the index within this String that is offset from the given index by codePointOffset code points
regionMatches() Tests if two string regions are equal
replace() Searches a string for a specified value, and returns a new string where the specified values are replaced
replaceFirst() Replaces the first occurrence of a substring that matches the given regular expression with the given replacement
replaceAll() Replaces each substring of this string that matches the given regular expression with the given replacement
split() Splits a string into an array of substrings
startsWith() Checks whether a string starts with specified characters
subSequence() Returns a new character sequence that is a subsequence of this sequence
substring() Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
toCharArray() Converts this string to a new character array
toLowerCase() Converts a string to lower case letters
toString() Returns the value of a String object
toUpperCase() Converts a string to upper case letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object

Previous Page Next Page
Advertisements