Java String Length
This is simple Java program to calculate the length of string with and without using length method. We use for each loop with toCharArray() method.
Java Length of string without method
class StringLength{ public static void main(String...s){ String s1 = "ptutorial"; int i = 0; for(char c: s1.toCharArray()){ i++; } System.out.println("Length of String="+i); } }
Output
Length of String=9
Java Length of string using length method
class StringLength1{ public static void main(String...s){ String s1 = "ptutorial"; int len=s1.length(); System.out.println("length of string="+len); } }
Output
Length of String=9