I am having a problem with the following lines where car
is a String
array which has not been initialized/has no elements.
String c
As all the above answers have suggested it will throw a NullPointerException.
Please initialise it with some value(s) and then you can use the length property correctly. For example:
String[] str = { "plastic", "paper", "use", "throw" };
System.out.println("Length is:::" + str.length);
The array 'str' is now defined, and so it's length also has a defined value.
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
Since you haven't initialized car
yet so it has no existence in JVM(Java Virtual Machine) so you have to initialize it first.
For instance :
car = new String{"Porsche","Lamborghini"};
Now your code will run fine.
INPUT:
String car [];
car = new String{"Porsche","Lamborghini"};
System.out.println(car.length);
OUTPUT:
2
In Java, we declare a String of arrays (eg. car) as
String []car;
String car[];
We create the array using new operator and by specifying its type:-
String []car=new String[];
String car[]=new String[];
This assigns a reference, to an array of Strings, to car. You can also create the array by initializing it:-
String []car={"Sedan","SUV","Hatchback","Convertible"};
Since you haven't initialized an array and you're trying to access it, a NullPointerException is thrown.
This won't work. You first have to initialize the array. So far, you only have a String[] reference, pointing to null
.
When you try to read the length member, what you actually do is null.length
, which results in a NullPointerException.
String car [];
is a reference to an array of String-s. You can't see a length because there is no array there!