I am having a problem with the following lines where car
is a String
array which has not been initialized/has no elements.
String car []; System.out.println(car.length);
What is a possible solution?
With the help of the length variable, we can obtain the size of the array. Examples: int size = arr[]. length; // length can be used // for int[], double[], String[] // to know the length of the arrays.
Using sizeof() function to Find Array Length in C++ The sizeof() operator in C++ returns the size of the passed variable or data in bytes. Similarly, it returns the total number of bytes required to store an array too.
To calculate the length of a string in Java, you can use an inbuilt length() method of the Java string class. In Java, strings are objects created using the string class and the length() method is a public member method of this class. So, any variable of type string can access this method using the . (dot) operator.
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
Since car
has not been initialized, it has no length, its value is null
. However, the compiler won't even allow you to compile that code as is, throwing the following error: variable car might not have been initialized.
You need to initialize it first, and then you can use .length
:
String car[] = new String[] { "BMW", "Bentley" }; System.out.println(car.length);
If you need to initialize an empty array, you can use the following:
String car[] = new String[] { }; // or simply String car[] = { }; System.out.println(car.length);
If you need to initialize it with a specific size, in order to fill certain positions, you can use the following:
String car[] = new String[3]; // initialize a String[] with length 3 System.out.println(car.length); // 3 car[0] = "BMW"; System.out.println(car.length); // 3
However, I'd recommend that you use a List
instead, if you intend to add elements to it:
List<String> cars = new ArrayList<String>(); System.out.println(cars.size()); // 0 cars.add("BMW"); System.out.println(cars.size()); // 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With