String length method in java is used to get the length of a given string.
String length method example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.kscodes.sampleproject; public class StringLengthExample { public static void main(String[] args) { String testStr1 = "This is Test String for calculating length"; String testStr2 = "Another String"; System.out.println("The Length of testStr1 is ::" + testStr1.length()); System.out.println("The Length of testStr2 is ::" + testStr2.length()); } } |
Output
1 2 |
The Length of testStr1 is ::42 The Length of testStr2 is ::14 |
Please Note:
Before performing any operation on any dynamically generated String, check if the String is not null.
Else a NullPointerException is thrown.
Before performing any operation on any dynamically generated String, check if the String is not null.
Else a NullPointerException is thrown.
Reference
1. String length – API