Lesson Objective
- Understand how to manipulate Strings in Java using the following methods:
- .length()
- .substring
- .indexOf
- .charAt()
- .toUpperCase()
- .toLowerCase()
- String Concatenation
- Be able to type cast from one data type to another.
KS3, GCSE, A-Level Computing Resources
To access a single item in an array, you refer to its index position. Each item is assigned a number, and the first item is denoted as position "0".
To extract one item from a string, you would refer to its index position. Like and Array, each item is given a number. The first item is referred to as position "0".
The length of a String can be found with the length() method:
public class Hello_World_1 { public static void main(String args[]){ String alp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; System.out.println("Length of the string is ") System.out.println(alp.length()); } } // NOTE: // .Length() is used for Strings // .Length is used for Arrays
Length of the string is: 26
The indexOf() method is used to find the index of a character or substring within a string. It returns the position of the first occurrence of the specified character or substring. If the character or substring is not found, it returns -1.
public class Hello_World_1 { public static void main(String args[]){ String sub = "Computer Science is the best"; System.out.println(sub.indexOf("r")); System.out.println(sub.indexOf("Science")); System.out.println(sub.indexOf("e", 7)); } } // Look for āeā starting from position 7.
7 9 12
The charAt() method returns the character at the specified index positions in a string.
public class Hello_World_1 { public static void main(String args[]){ String sub = "Computer Science is the best"; System.out.println(sub.charAt(2)); System.out.println(sub.charAt(sub.length-1)); } }
m t
Returns a new string which is the substring of a specified string.
public class Hello_World_1 { public static void main(String args[]){ String sub = "Computer Science is the best"; System.out.println(sub.substring(24)); System.out.println(sub.substring(9,15)); } } // Starts from position 24 and returns all following characters // Starts from position 9 and returns all characters up to 15
best Science
The ā+ā operator can be used between strings to join them together. This is called concatenation.
public class Hello_World_1 { public static void main(String args[]){ String a = "Computer"; String b = "Science"; System.out.println(a + " " + b); } } // Note that we have added an empty text (" ") to create a space between firstName and lastName on print. // You can also use the concat() method to concatenate two strings: // System.out.println(a.concat(b));
Computer Science
WARNING:
Java uses the + operator for both addition and concatenation. Numbers are added. Strings are concatenated. If you add a number and a string, the result will be a string concatenation.