By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,248 Members | 1,979 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,248 IT Pros & Developers. It's quick & easy.

Java declare variable

P: 3
What happens when the declare array like that?

Char arr[];

or what are there differences between them?

Char arr[] = new char[6];
3 Weeks Ago #1
Share this Question
Share on Google+
2 Replies

P: 77
char arr[] : It's a character array, which is different from a String in many manners. Like:
- String methods cannot be used
-'+' overloaded operator can't be used
- It is stored in heap memory whereas String literals are stored in the String constant pool.
-A string can't be iterated over characters using loop, etc.

char arr[] = new char[6]
I am not sure about this declaration. 'new' is used to dynamically allocate memory. So the right hand side of the expression is allocating memory and returning an address.
When we declare an array, its name points to the first element. Here I guess the returned address is stored in arr.

On a side note, new is used with jagged arrays like:
Expand|Select|Wrap|Line Numbers
  1. char[][] arr = new char[2][];
  2. arr[0] = "Hello".ToCharArray();
  3. arr[1] = "cat".ToCharArray();
But it's a 2D system with variable number of columns in each row.

Share the link of the resource/article you are referring if you could.
3 Weeks Ago #2

P: 4
Char arr[]; is a syntax used to declare a character array without specifying length or size of it.

We need to write the following in the next line,
arr=new Char[6];
In this, we do not need to write Char[], class, again because the array is declared already.

Char arr[]=new Char[6] will create an array of characters with length 6 from starting index 0 to 5.

So, there are two methods which come in this scenario:

Either you write this:

Expand|Select|Wrap|Line Numbers
  1. Char arr[];
  2. arr[] = new Char[6];

Expand|Select|Wrap|Line Numbers
  1. Char arr[] = new Char[6];
Hope this difference makes sense!
3 Weeks Ago #3

Post your reply

Sign in to post your reply or Sign up for a free account.