Java String

The String class represents a character string.

All Java strings are literals, e.g. “Hello, World” is an instance of a String class.

Until Java 8 inside of String class was a char array.

As you know each char needs 2 bytes because Java was using only UTF-16.

Since Java 9 compact strings were introduced, this means String contains byte array instead of char array and byte flag “coder” (0 is LATIN-1 encoding, 1 is UTF-16).

Java is smart enough to use LATIN-1 encoding where it’s possible because it takes just one byte instead of two.

A string is immutable (here is described why), this means you cannot change or extend it.

If you concatenate two strings this will produce a new third string (Java compiler string optimizations is a little bit more advanced topic).

You should prefer StringBuilder (not thread-safe) or StringBuffer (thread-safe) for concatenation.

Java String Methods

The most interesting String methods are:

  • charAt(index) – get character by index
  • format(str, args) – static method to format a string, e.g. String.foramt(“Hello, %s”, “World”) will return “Hello World”
  • indexOf(s) – returns index of the first occurrence of input string
  • join (delimiter, strings) – static method to join strings using delimiter, e.g. String.join(“,”, “1”, “2”, “3”) will return “1,2,3”
  • isEmpty() – returns true if string is “”
  • length() – returns a length of the string, e.g. “123”.length() returns 3
  • replace(target, replacement) – replaces first occurrence of a target string to replacement
  • replaceAll(regexp, replacement) – replaces all occerrences of regexp to replacement
  • split(regexp) – splits string by regexp, e.g. “1,2,3”.split(“,”) will return an array of strings [“1”, “2”, “3”] (more examples here)
  • substring(begin, end) – return a substring from begin index to end index (until Java 6 it was the same string will different offsets, since Java 7 it’s a new string)
  • toLowerCase() – changes all upper case characters to lower case and return result string
  • toUpperCase() – changes all lower case character to upper case and return result string
  • trim() – removes whitespace characters from the beginning and from the end of the string, e.g. ”  1 23 “.trim() will return “1 23”

Interesting Articles

Further, you can read about:

And of course, it’s important to read Java string interview questions and find answers.

Scroll Up