0

1) int[] a={1}; //correct


2)

 int []b;
 b[]={1};   //wrong

Why initialization after declaration is showing compile-time error in java??

I didn't get satisfactory answer in previous related topic,so asking again.

TheLostMind
  • 34,842
  • 11
  • 64
  • 97
Stones
  • 13
  • 7
  • The linked question answers it – TheLostMind Nov 23 '15 at 11:48
  • 2
    Because the Java grammar does not allow it. – Alexis C. Nov 23 '15 at 11:48
  • @alexis but in case of primitive datatype this is correct then why not for array class? – Stones Nov 23 '15 at 11:55
  • Ask the language designers. – Alexis C. Nov 23 '15 at 11:59
  • @VinodMadyalkar I don't really see how your duplicate answers it. The question is _why_ `b={1};` does not compile (assuming the typo) - not _how_ to fix it. – Alexis C. Nov 23 '15 at 12:03
  • @AlexisC. - From the first answer of that question - *You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).*. That's the answer. This is Java syntax. To be fair even the question you have used has answer like - *But "why" is immaterial ... the restriction is there, and you have to live with it.* :). Do you still think I was wrong? :) – TheLostMind Nov 23 '15 at 12:09
  • @VinodMadyalkar Yes the answer just tells that you cannot. The question I used still provide some pointers in the comments (which I believe is what the OP is looking for). So not _"wrong"_ but not as accurate I would say. – Alexis C. Nov 23 '15 at 12:22
  • a) The name of the variable is b, not `b[]`. b) See comment 1 from Alexis C. c) What you can do, is `b = new int [] {1}; // correct` which means, that Ramanlfc's answer isn't accurate. – user unknown Nov 23 '15 at 12:38
  • @AlexisC. - Hmm.. Will try to find better / exact dups next time around :) – TheLostMind Nov 23 '15 at 12:39
  • @VinodMadyalkar It's fine :) (BTW good luck for the mod's election!) – Alexis C. Nov 23 '15 at 12:40
  • @AlexisC. - Thank You :) – TheLostMind Nov 23 '15 at 12:41

0 Answers0