String startsWith method is used to check if a String starts with a specified substring. Startswith method has 2 variations and we will see both these.
1 2 |
public boolean startsWith(String prefix) public boolean startsWith(String prefix,int toffset) |
boolean startsWith(String prefix) checks if the String starts with the given prefix.
boolean startsWith(String prefix,int toffset) checks if the sub string of this string beginning at the specified index starts with the specified prefix.
startsWith is case sensitive. Please see the output of the example below.
String startsWith method example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.kscodes.sampleproject; public class StringStartsWithExample { public static void main(String[] args) { String testStr1 = "This is a test String for StartsWith"; System.out.println("Does the testStr1 starts with 'This' ::" + testStr1.startsWith("This") ); System.out.println("Does the testStr1 starts with 'this' ::" + testStr1.startsWith("this") ); System.out.println("Does the testStr1 starts with 'Test' ::" + testStr1.startsWith("Test") ); System.out.println("-----------------------------"); System.out.println("Does the testStr1 starts with 'This' after 10th character ::" + testStr1.startsWith("This",10) ); System.out.println("Does the testStr1 starts with 'test' after 10th character ::" + testStr1.startsWith("test",10) ); } } |
Output
1 2 3 4 5 6 |
Does the testStr1 starts with 'This' ::true Does the testStr1 starts with 'this' ::false Does the testStr1 starts with 'Test' ::false ----------------------------- Does the testStr1 starts with 'This' after 10th character ::false Does the testStr1 starts with 'test' after 10th character ::true |
Reference
1. String API