The String Methods


Premium Content - Free Preview

As mentioned, the String Class contains a large number of methods. Later, we'll see how to look up classes like String in the Official Java Documentation. I also created a String reference with example code to help beginners. However, since documentation can still be confusing for a beginner, this node will cover the most common String methods!

concatenate
Strings can be concatenated, or combined, with the + operator. For example:

String firstName = "Jim";
String lastName = "Jones";
String fullName = firstName + lastName;
System.out.println(fullName);

This will print out:

JimJones

The + operator is actually a shortcut for the concat() method. So the 3rd line in the above code can equivalently be written as:

String fullName = firstName.concat(lastName);

There's no reason to use the longer form, but you should realize + is really just concat(), an ordinary method of String.

Immutability
Unlike instances of most classes, Strings in Java are immutable, which means that a String cannot change after it has been created. Methods that look like they modify a String really just return a new String as a value. For example, the concat() method above does not change the initial String firstname, which is why a new variable fullName was needed to store the result. If you want to change the value of the current String, you can create a new String with the same variable name. For example:

String name = "Jim";
name = name.concat("Jones"); 

name now equals "JimJones".

charAt
charAt(i) - This method returns the char located at position i in the String. Strings are numbered like arrays, so the first letter in String str is at position 0, and the last letter is at position str.length()-1. For example, the following code grabs the characters 'a', 'b' and 'e':


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Comments

  • I'm having trouble with the BlueJ task. I've managed to get the tests to succeed for TheStringClassTest, but when I run the tests for TheStringMethodsTest, it fails. This is the code I've written for the addToNote and summarize methods:

    cont...
  • When you click on the test result in BlueJ, it will show you what your method returned and what it expected. This can help you find your error.

    Look at the definition of substring. What number do you want to go up to (but not including) to get the first 20 characters? (Remember that the first index is 0.)

    cont...
Contact Us
Sign in or email us at [email protected]