0
public class arraChange {
    public static void main(String []args){
        int arr [] =  {2,3,4,5,6,7,8};


public class arrayCounter {
    public static void main(String args []){
        Random rand = new Random();
        int freq[] = new int [7];

considering the above two seperate lines of codes, i just want people to explain to me why i can't write:
int arr [] = {2,3,4,5,6,7,8}; // in the first lines like this:
int arr [] = new [2,3,4,5,6,7,8]; // just like the way that in second lines of codes was written

i.e int [] = new int [7];

cos i tried it like that just to try whether it will run too, cos i expect this "[7];" not to be a correct way to end a statement, but from the tutorial i got it, yhe code run fine, so i tried it in that first one to see if it will run too, but it gives error report, so please can anyone explain to me why is like that?

Its just in my quest to understand how java works, pls bear with me

2
Contributors
1
Reply
13
Views
3 Years
Discussion Span
Last Post by JamesCherrill
0

The kind of bracket is important, [] is not the same as {}
The number in [] defines the size of a new array... new int[7] is a new array of 7 ints, all zero
The numbers in {} are a quick way of specifying the initial values of a new array(the number of numbers defines the array size)... {2,3,4,5,6,7,8} defines an array of 7 ints, values 2...8
your middle example is not valid Java.

Edited by JamesCherrill

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.