Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find length of a string array?

Tags:

java

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?

like image 713
aman_novice Avatar asked Feb 01 '11 11:02

aman_novice


People also ask

How do I get the length of a string array?

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.

How do I get the length of a string array in C++?

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.

How do you find length of a string?

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.

How do you find the size of an array?

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]);


1 Answers

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 
like image 55
João Silva Avatar answered Sep 20 '22 11:09

João Silva