Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Substring
AP® Computer Science A (Java) Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source AP® (Advanced Placement®) Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency. It is a substantial amount of coursework that represents a typical year of high school-level study or a semester of a University computer science course. This course may also be used to prepare for the AP® Computer Science A exam.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
In Java, a "Substring" is a string that is comprised from another string, and there are two methods by which one is made. Take a look at the example below that shows us both substring(int startIndex) and substring(int startIndex, int endIndex).
SubStringExample.java
package exlcode;
public class SubStringExample {
public static String exampleVariableOne = "Hello World!";
// returns a String between the given indices and assigns
// it to String variables
public static String exampleVariableTwo = exampleVariableOne.substring(0, 5);
public static String exampleVariableThree = exampleVariableOne.substring(6);
public static void main(String[] args) {
System.out.println(exampleVariableTwo);
System.out.println(exampleVariableThree);
}
}
The first method, substring(int startIndex) returns a new String containing the characters between "startIndex" and the final index of the called String, so the statement exampleVariableOne.substring(6) returns the entire string "World!". If the "startIndex" is equal to the total length of the string, an empty string is created.
The second method, substring(int startIndex, int endIndex) returns a new String made up of the characters beginning at the "startIndex" and ending at the "endIndex - 1". This method includes the first character and excludes the last character of the parameters entered. As long as both inputs are valid indexes of the String you won't throw a runtime error.
As discussed before, strings are immutable, so a new String is created every time you call either of the substring() methods.