array-length-string-length()
length Vs length():
length:This is a variable.applicable for only for array objects represents the number of elements or the size of the array.
Example:
int a=new int[6];
System.out.println(a.length); ------------------> output: 6
- length variable Can’t apply to String
Array length example:
public class LengthExample {
public static void main(String arg[])
{
int a[]=new int[6];
for(int i=0;i <a.length;i++)
{
a[i]=i;
System.out.print(a[i]);
// System.out.println(a[6]); //exception
}
System.out.println(".....length="+a.length);
}
}
output:012345 length=6
Example:
String s=”Laxman”;
System.out.println(s.length); //error
Given CTE because length variable applicable only for array objects.
- length(): It is a final method applicable for string objects.
- It represents the number of characters present in the String Object.
String s=”Laxman”;
System.out.println(s.length()); ---------> 6
System.out.println(s.length); ----------> //error
- In case string also index value start with zero only.
public class StringlengthEx {
public static void main(String arg[])
{
String mystring="abcde";
System.out.println(mystring.length()); //5
System.out.println(mystring.charAt(3)); //d
System.out.println(mystring.indexOf('4')); //2
}
}
Array of strings Example:
public class ArrayStrings {
public static void main(String arg[])
{
String stringarray[]=new String[6];
stringarray[0]="corejava";
stringarray[1]="jdbc";
stringarray[2]="hibernate";
stringarray[3]="servlets";
stringarray[4]="jsp";
stringarray[5]="ejb";
System.out.println("Array length"+stringarray.length);
for(int i=0;i
{
System.out.println(stringarray[i]+"....length="+stringarray[i].length());
}
}
}
output:
Array length6
corejava....length=8
jdbc....length=4
hibernate....length=9
servlets....length=8
jsp....length=3
ejb....length=3
0 comments:
Post a Comment