Gadgets

Showing posts with label length. Show all posts
Showing posts with label length. Show all posts

Sunday, 13 December 2015

length vs length() in java

length:- length is final variable, it is applicable for arrays and it returns the size of an array
Example:
int[ ] a={10,20,30};
System.out.print(a.length);
Here the above array size is 3.
In this case if we give length() instead of a.length then we will get compile time error.
length():- length() is final method, it is applicable for String Objects. Length() method returns number of characters present in the String.
Example:
String s="java";
System.out.print(s.length());
Here the above String length is 4(j,a,v,a)
Example:
String[ ] s={"java","html5","css"};
System.out.println(s.length);//3
System.out.println(s.length());//error
System.out.println(s[0].length());//4
System.out.println(s[0].length);//error
In the above example
‘s’ is an array and s[0] is String
s.length and s[0].length() are true 
Note: In multi dimensional arrays length variable represents only base size but not total size of an array.
int[ ] a=new int[2][3];
System.out.println(a.length);//2
System.out.println(a[0].length);//3
If we want find total size of multi dimensional array
System.out.println(a[0].length+a[1].length);//3+3=6