Strings

What are strings?

Strings are a sequence of characters, provided by the Java language as an Object. They are immutable, meaning it cannot be changed after you construct them. Strings have many methods that make it easy to manipulate the data.

Because strings are objects, you should use the .equals() method instead of == to compare equality. It will compare the contents of the two strings instead of the pointers.

String a = apple; String b = bananas; String a1 = apple;

a == a1 evaluates to false

a.equals(a1) evaluates to true

a.equals(b) evaluates to false

Common String Methods

int length() method returns the number of characters in the string, including spaces and special characters like punctuation

String substring(int from, into to) method returns a new string with the characters in the current string starting with the character at the from index and ending at the character before the to index (if the to index is specified, and if not specified it will contain the rest of the string). 

int indexOf(String str) method searches for the string str in the current string and returns the index of the beginning of str in the current string or -1 if it isn't found

int compareTo(string other) returns a negative value if the current string is less than the other string alphabetically, 0 if they have the same characters in the same order, and a positive value if the current string is greater than the other string alphabetically

boolean equals(String other) returns true when the characters in the current string are the same as the ones in the other string. This method is inherited from the Object class, but is overridden which means that the String class has its own version of that method.

Concatenation: adding two strings together. In Java, the “+” operator is used to combine two strings. For example String s = “a” + “b” 

Example Code

String x = “Hello World!”;
System.out.println(x.length()); 
 
String phase = “This is a String Test”;

Strong firstHalf = phase.substring(0,10);
String secondHalf = phase.substring(10, phase.length());
String s = firstHalf + secondHalf;
System.out.println(firstHalf + “+” + secondHalf + “=” + new);

The output is:

12
This is a  + String Test = This is a String Test

For a more detailed documentation, visit Oracle: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Full course
Next Lesson