In modern IDEs there is the autocompletion feature that offers Java keywords or variables declared in our class, and without this feature, how Know The size of a table? And how do you know the size of a Thong? Developers of all levels (beginner or expert) can't distinguish between
lenght and
lenght() correctly, and since the IDE corrects this problem, it still remains incomprehensible. In this article we will look at some concepts about arrays, strings in Java.
The simplest answer is that
lenght is used to retrieve the size of an array, and
lenght() is a method that returns the size of a string.
int[] array = new int[5];
System.out.println(array.length);//length for arrays
String str = "string";
System.out.println(str.length()); length() for string
The question is why the array has an attribute
lenght but not string and vice-vers-that?
Why do arrays in Java have the lening property?
An array is a container of objects of a specific type that stores a limited number of elements. Once the board is created, its size will never change and remains fixed. That's why the
lenght is declared as a variable
final And that is why
lenght is considered an attribute that defines an array when it is created.
An array can be created with two methods:
- Initialize a new array with values.
- Instantiate a new array by specifying its size.
Initializing an array with values creates a new array with a size corresponding to the number of comma-separated elements.
int[] tab = {1,2,3};
The second method is to instantiate a new array by specifying the type, number of elements:
String[] tab = new String[3];
Why is there no Array class defined as String?
An array is an object and each array has a class
Object The following statement is legal:
Object obj = new String[20];
An array encompasses all the methods and attributes inherited from the class Object (except clone). Why is there no definition of the Array class? We can't find the definition of the Array class, one explanation is that it is hidden from us. If you think about it a bit, if there's an Array class, what did it look like? She would still need a board to store the items, right? That's why it's a bad idea to define such a class. In fact, you can get the class of an array by calling the method getClass():
int[] tab = new int[2];
System.out.println(tab.getClass());
Output:
class [I
Why does String have the length()?
The data structure of a
String is a table of
Char. There is no need to define an attribute that is not needed for each application. Unlike the C language, a character array is not a String in Java.
String is dynamic in nature, but the
length. The designers of java have thought of it and they decided to make it easier and avoid mistakes for developers by creating the method.
length().
References:
Javadoc: ArraysStackOverFlow: Why isn't there a java.lang.Array class?