Tuesday, June 26, 2018

Technical Tip #24 - Technical Tip of the day...


T24: Knowledge Tip Of The Day....
Array length
Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.
array.length :: length is a final variable applicable for arrays. With the help of length variable, we can obtain the size of the array.
string.length() :: length() method is a final variable which is applicable for string objects. length() method returns the number of characters presents in the string.
class ArrayLength_Demo{
public static void main(String[] args) {
int [] a = {1, 2, 3};
System.out.println("Length : " + a.length); //output is 3
a = new int [2];
System.out.println("Length : " + a.length); //output is 2
}
}
ArrayLength {
public static void main(String[] args) {
int [] a = {1, 2, 3};
System.out.println("Length : " + a.length);
a [3] = 4;
System.out.println("Length : " + a.length);
}
}
When above code is run, it will throw java.lang.ArrayIndexOutOfBoundsException
output:
Length : 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at com.quiz.questions.ArrayLength.main(TestArray.java:18)




No comments:

Post a Comment