0

Can someone explain why i cannot use array={a,b}; :

public class Example {
 private final String a;
 private final String b;
 public final String[] array;

 public Example(){
  a="test";
  b="text";
  //String [] c = {a,b}; This is fine
  //array=c;
  array={a,b}; // this line throws an Exception
 }
}

Exception :

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - illegal start of expression
    at Example.<init>(Example.java:21)
    at hello.main(hello.java:26)
Java Result: 1

2 Answers 2

4

Yes in case of initializing an array using {..}, the declaration and initialization should be done at the same time.

Well, marking array as final complicates things.. You will not be able to initialize it later (you will have to do it inside the constructor) . Your code will not compile.

Yes you could use : arr = new String[5]; in your constructor to initialize your array.

Sign up to request clarification or add additional context in comments.

2 Comments

It is in the default constructor
@CodeCat - Hadn't seen that.. My bad .. Edited my answer :).. Lashane's answer will work as well :)
2

you should initialize array, like this:

array = new String[] {a,b};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.