1

What's wrong with the below program?

package test;

public class Test {

    byte[] array = new byte[2];
    array[0] = 'A';
    array[1] = 'B';
}

Look,the IDE indicate some problems(click to enlarge) :

enter image description here

In the other word, why should I move the filler lines to another inner scope as follow :

package test;

public class Test {

    byte[] array = new byte[2];
    {
        array[0] = 'A';
        array[1] = 'B';
    }
}

The IDE doesn't have any problem with above program.

Ebrahim Ghasemi
  • 5,850
  • 10
  • 52
  • 113
  • With `array[0] = 'A';` you're not initializing a new variable, you are filling an existing array. I'm not a Java export but it don't surprize me you can't do it in class description as a new initialization. – Fractaliste Apr 29 '15 at 07:49
  • Screenshots of an IDE are a lousy way to share code. Try to find somewhere in your IDE (for example, the compiler output window) where you can grab the error messages as text to include in your question. – Andrew Janke Apr 29 '15 at 07:50
  • The answer is... because the JLS defines it so. You can have a look at the JLS 8.1.6 - https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.1.6. Also as a side note you could simply use an array initializer here (which is valid), i.e `byte[] array = {'A', 'B'}`; – Alexis C. Apr 29 '15 at 07:51
  • @AndrewJanke I can't see this kind of error messages any where else. In the compiler output window, I can only see compile time errors – Ebrahim Ghasemi Apr 29 '15 at 07:54
  • @Abraham This is a compile time error, like all syntax errors. The IDE is just doing a partial compile in the background so it can give you that syntax advice. Manually tell it to do a full build of your file or project, and you should see the errors in the Console output or a similar window. One of those toolbar buttons, or menu item (maybe under Project or File), or an item in a context menu you get from right-clicking on the class in the Package Explorer should do it. – Andrew Janke Apr 29 '15 at 08:09

3 Answers3

6

in this snippet you try to do some assignments (to the array: e.g. array[0] = 'A') outside any method

public class Test {
    byte[] array = new byte[2];
    array[0] = 'A';
    array[1] = 'B';
}

whereas in this snippet you do the assignments inside the instance initializer block

public class Test {
    byte[] array = new byte[2];
    {
        array[0] = 'A';
        array[1] = 'B';
    }
}

if you want to do it in your code you could do it for example in an init method

public class Test {
    byte[] array = new byte[2];

    void initArray() {
        array[0] = 'A';
        array[1] = 'B';
    }
}
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
  • So, the answer is : My first snippet is wrong because Java language defined in a way that we can't assign values to arrays elements in this way in the class scope, and we must move these assignments inside a method or inside instance initializer block (**i.e. `{...}` ?**). **Right?** (And also I can use `byte[] array = {'A', 'B'}; ` instead) – Ebrahim Ghasemi Apr 29 '15 at 08:06
  • @Abraham Your're absolutely right with both assumptions. And doing the declaration and assignment in one line `byte[] array = {'A', 'B'};` is a common way (for simple assignments). – SubOptimal Apr 29 '15 at 08:11
  • @vikingsteve There is no example for the `static initializer` block. The use itself depends on the case. But I agree it should not be overused if another approach suites better (to be avoided: long lasting initialisation, initialize havy weight objects, etc.). – SubOptimal Apr 29 '15 at 08:52
1

The {....} in your example are called initialization blocks. They are used to to set the value of "final" static variables whereas a constructor cannot. In your case you dont need them, you could well initialize your array in your constructor.

The reason why it is not working in the first place without the initializers is because it is simply not valid java syntax.

See also this and this for more info

Community
  • 1
  • 1
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
1

In contrast to using an instance initializer block, you could do what you want in a neat one-liner, like this:

// much better, and much smaller
public class Test {
    byte[] array = {'A', 'B'};
}
vikingsteve
  • 38,481
  • 23
  • 112
  • 156
  • *"Please don't use static initializer blocks wherever possible."* .. he isn't using one, so everything is alright. – Tom Apr 29 '15 at 09:13
  • Please read this: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html and see the difference between a _static initializer block_ and an _instance initializer block_. – Tom Apr 29 '15 at 09:16