Common String Practices

Strings are objects that represents a combination of characters.

Joining Two Strings

Two strings can be joined by using the concatenation operator or method.

// Using the operator
String first = "Mr. ";
String last = "Park";

String full_name = first + last;
System.out.println(full_name); // Outputs: Mr. Park

// Using the method
String a = "Hello";
String b = a.concat(" World!");

System.out.println(b); // Outputs: Hello World!

Get Individual Characters from a String

String objects are composed of individual character primitive values; therefore, we can obtain individual characters from a string by using charAt(index). Indexing starts at 0 for Strings.

Determine the number of characters in a String

.length() method is used to obtain the size of a string.

Check a String's prefix or suffix

We can determine if a string starts with a certain pattern or if it ends with a certain pattern.

Replace a certain pattern in a String

We can search for a pattern within a String and replace all occurrence of it.

Using a Loop on a String

Since Strings are indexable, we can utilize both a while loop and for loop to traverse individual characters one-by-one.

Last updated