-4

I'm trying to get more familiar with object arrays in Java and one thing I was attempting to do that is failing is declaring an object array on one line and then initializing it on a later line. Is this possible? Am I making a format mistake or just trying to do something I can't?

tl:dr; can a Java object array do something like this, below?

int[] s;
s = new int[]{ and put the list here..}

edit: adding my current code and error example

public class noncombatSKILLS {
        noncombatSKILLS ( String receivName , String receivDescription , int receivDamage )
        {
        name = receivName ;
        description = receivDescription ;
        damage = receivDamage ;
!
!
public class CHARACTER {
noncombatSKILLS[] noncombat;
noncombat[] = {  new noncombatSKILLS( "Scavenge" , "find some parts" , 123 ) } ;

this compiles correctly with just the declaration line under the CHARACTER class, but when I try to compile with the line added after it, I get 'error: not a statement' pointing the brackets following the 'noncombat'

A. Mulder
  • 1
  • 1
  • 5
    What happens when you try exactly the syntax you suggest? – khelwood Nov 22 '17 at 23:09
  • @khelwood updated question with code example and error – A. Mulder Nov 22 '17 at 23:20
  • @AdamS I know how to declare and initialize primitive data arrays, I even included one in my initial question. I'm asking this specifically because with a custom class it's not functioning within the same format – A. Mulder Nov 22 '17 at 23:24

1 Answers1

0

In a word - yes. This is possible both for primitives:

int[] s;
s = new int[] {1, 2, 3};

And for objects, such as Strings, for example:

String[] s;
s = new String[] {"a", "b", "c"};

EDIT:
Looking at the edited question, the problem is not with the array initialization, it's with the fact that you cannot place arbitrary statements under a class - they should either be in a method, a constructor or an initializer block, e.g.:

public class CHARACTER {
    // This is a member:
    noncombatSKILLS[] noncombat; 

    // And this is an initializer block:
    {
        noncombat[] = {  new noncombatSKILLS( "Scavenge" , "find some parts" , 123 ) } ;
    }
}
Mureinik
  • 252,575
  • 45
  • 248
  • 283