Java String Examples of Strings in the Java Lang

In the Java lang, Strings are actually Objects as opposed to primitive data. This means that there is a class, the String class described on this page, that has its properties and methods for manipulating Strings.
[ Home] [ Site Map ]


How to Declare and Initialize a String in Java

There are two main ways to create Java Strings. One is by creating a String literal (see top line in picture below). The other is to explicitly create a new Object in memory (See second line below). I will avoid going into detail about how these differ as it involves discussing aliasing and how Java saves memory. Note: Unlike some other programming languages, in Java Strings must be enclosed in double quotes. Single quotes are used for chars, a primitive data type.

Important Methods of a Java String

String Methods API

The index position of characters in Strings

Before we look at the String methods indexOf() and substring() we first should take a look at how Java thinks about the position of each character in a String. Consider the String "abcdef". "a" is in the first position; "b" in the second and so and so forth. The position of these letters is known as its index. Below is a picture of how each letter's position is indexed by Java. Note, that like Java arrays, Strings start with the number 0.
String methods that rely upon the index position

. substring(int startingPosition) returns String
The substring() method is an overloaded method. This version that takes only 1 parameter starts at the index position and goes to the end of the String.
toCharArray(); returns char[]
This is a handy little method that takes a String and breaks each letter up to create a Array of chars. A char is a primitive data type that represents a single character and is denoted with single quotes.
	String myStr = "abcdefg";
		char[] asCharArr = myStr.toCharArray();
		for(int i=0;i <asCharArr.length;i++)