Answers for "length vs length() in java"

1

What is difference between length and length() method in java

length() : In String class we have length() method which is used 
to return the number of characters in string.
Ex : String str = “Hello World”;
System.out.println(str.length());
Str.length() will return 11 characters including space. 
  
length : we have length instance variable in arrays which will 
return the number of values or objects in array.
For example :
String days[]={” Sun”,”Mon”,”wed”,”thu”,”fri”,”sat”};
Will return 6 since the number of values in days array is 6
Posted by: Guest on November-30-2020
0

length method in java

public class LengthMethodDemo {

	public static void main(String[] args) {
		
        //declaring variables string1 & string2
		String string1 = "Java";
		String string2 = "Java Code";
	    
        //                 Java
        //count from left  1234  --> so length would be 4
		int lengthOfString1 = string1.length();  // 4
        //                 Java Code
        //count from left  123456789  --> so length would be 9
		int lengthOfString2 = string2.length();  // 9
		
		System.out.println("Length of String1 is : "+lengthOfString1);
		System.out.println("Length of String2 is : "+lengthOfString2);
		
		String string3="";
		System.out.println(string3.length());  //0
      
        String string4=null;
		System.out.println(string4.length());  //It will give NullPointerException
		
	}

}
Posted by: Guest on October-17-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language