2 Replies - 185 Views - Last Post: 17 May 2014 - 03:28 AM Rate Topic: -----

#1 pulp_fiction  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 36
  • Joined: 03-February 13

Array reference instantiation weird problem

Posted 17 May 2014 - 02:52 AM

I am currently learning Java basic concepts and this is a very simple code which produces error depending on the way I write. It is as follows:

package testPackage;

interface ArrayInsideClassShock {
	
}

class Check{
	ArrayInsideClassShock var[];  //Error line
	var= new ArrayInsideClassShock[10];
}


Error in eclipse:Syntax error on token ";", , expected

But if I write it as:

package testPackage;

interface ArrayInsideClassShock {
	
}

class Check{
	ArrayInsideClassShock var[]=new ArrayInsideClassShock[10];
}


It doesn't show any error.Could you please explain me this behavior?

Is This A Good Question/Topic? 0
  • +

Replies To: Array reference instantiation weird problem

#2 mike73  Icon User is offline

  • D.I.C Addict

Reputation: 164
  • View blog
  • Posts: 630
  • Joined: 24-April 10

Re: Array reference instantiation weird problem

Posted 17 May 2014 - 02:56 AM

Either put the variable declaration on one line:
ArrayInsideClassShock var[] = new ArrayInsideClassShock[10];


or initialise it in a constructor:
class Check{
   ArrayInsideClassShock var[];
   
   public Check() {
      var[]=new ArrayInsideClassShock[10];
   }
}

This post has been edited by mike73: 17 May 2014 - 03:01 AM

Was This Post Helpful? 0
  • +
  • -

#3 astonecipher  Icon User is offline

  • Major DIC Head
  • member icon

Reputation: 726
  • View blog
  • Posts: 3,165
  • Joined: 03-December 12

Re: Array reference instantiation weird problem

Posted 17 May 2014 - 03:28 AM

You can define a variable in a class, but to initialize it it needs to be on the same line or in a method.

This post has been edited by astonecipher: 17 May 2014 - 03:28 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1