vikkyhacks
vikkyhacks

Reputation: 3230

What is the "length" in the char[]?

char[] name = "VIKKYHACKS".toCharArray();
System.out.println(name.length);

In this program what is the "length" , If it were (new String("VIKKYHACKS")).length() then the length would be a method. But char[] is a datatype and cannot have fields or methods inside it. How does the second line of that program work ???

Upvotes: 4

Views: 180

Answers (7)

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

First you have a string "VIKKYHACKS". Then you turn that into an array with the following

char[] name = "VIKKYHACKS".toCharArray();

"char[] name = " part, assigns our char array to the variable name. Which has the type char array (char[])

Arrays have a variable named length which is accessed using .length. Which is used in the second line.

name.length

Upvotes: 2

Arpit
Arpit

Reputation: 373

Because name is an character array and arrays have property called length that fetches you the length of the array. In case of string,length() is a method which gets you the length of the string.

Upvotes: 1

Rong Nguyen
Rong Nguyen

Reputation: 4189

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.You can use the built-in length property to determine the size of any array. See also: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Upvotes: 2

Zoltán
Zoltán

Reputation: 22146

length is a public final field of the Array class. Its value is initialized upon creation of the array.

Upvotes: 1

Nimrod007
Nimrod007

Reputation: 9913

every array has "length" variable instance which contains size of array (were talking about java :) )

Upvotes: 1

rgettman
rgettman

Reputation: 178243

Arrays are Objects in Java. According to the JLS, section 10.3, length is a "final instance variable" that gives the array's length.

Upvotes: 2

rolfl
rolfl

Reputation: 17707

char[] is not a primitive data type. it is an Object, and it has a public field 'length'.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

That is a good start.

Because Arrays are Objects, they have all the other items, like an equals() and hashCode() method too. (as well as all the treats like notify(), wait(), etc.)

Upvotes: 6

Related Questions