Defining String

Java 8
String str1 = "Hello World!";

Strings can be defined using String class.


String Literals

Java 8
String name = "Sam";

You can literally specify a string by wrapping it inside double-quotes ("").


Character Escape

Java 8
String text1 = "Sam's age:\t21";  // Sam's age:   21

To specify special characters or characters that make ambiguity for compiling String Literals, you need to escape them. This is a list of escaping characters:

  • \' Single quote
  • \" Double quote
  • \\ Backslash
  • \n Newline
  • \r Carriage return
  • \t Tab
  • \b Backspace
  • \f Form feed
  • \XXX Octal character code (0-377)
  • \uXXXX Unicode character (0000-FFFF)

String Length

Java 8
String str1 = "Hello World!";

int length = str1.length();  // 12

The length() method returns the number of characters inside a string.


Get Character

Java 8
String str1 = "Hello World!";

char firstCh = str1.charAt(0);  // H

You can get a character at any zero-based index using the charAt() method.


Set Character

Java 8
String str1 = "Hello World!";

String str2 = str1.substring(0,1)+'3'+str1.substring(2);
// H3llo World!

Strings are immutable in Java, so you can only get a character on an index, and not setting it.

To replace a character in a string, you need to create a new string.


Concatenating Strings

Java 8
String str1 = "Hello";
String str2 = "World!";

String str3 = str1 + " " + str2;  // Hello World!

You can concatenate strings using the + operator.


Find Substring

Java 8
String str1 = "Hello World";

int index = str1.indexOf("llo");   // 2

The indexOf() method searches for the index of the first occurrence of some string inside another one.

If the substring does not exist, it returns -1.


Get Substring

Java 8
String str1 = "Hello World!";

String substr1 = str1.substring(6); // World!
String substr2 = str1.substring(6, 8);  // Wo

The substring() method gets the starting index (inclusive) and ending index (exclusive) and returns the substring for those parameters.

If you don't specify the ending index, substring() will return the substring from the starting point to the end of the string.


Convert to String

Java 8
int num = 12;

String str1 = String.valueOf(num);  // 12

The valueOf() method converts most types to a string.