3 Replies - 296 Views - Last Post: 25 December 2012 - 10:40 PM Rate Topic: *---- 1 Votes

#1 Gisengryl  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 129
  • Joined: 08-September 12

Variable Initialisation error.

Posted 25 December 2012 - 08:08 PM

  int num;
        String numx;   // compiler states that numx isn't initialised.
        for (int count=0;count<4;count++){
        num = (int)(Math.random()*9);
        numx += num+" ";
        }


I realised I have to insert a arbitrary String numx=""; for it to work.

Why is this so ?

I know that a local variable must be declared before it can be used, but does it need to be initialised before use as well ?

Is This A Good Question/Topic? 0
  • +

Replies To: Variable Initialisation error.

#2 rnty  Icon User is offline

  • D.I.C Head

Reputation: 20
  • View blog
  • Posts: 158
  • Joined: 14-August 12

Re: Variable Initialisation error.

Posted 25 December 2012 - 08:55 PM

Hi Gisengryl

String numx is a declaration and not a definition.It tells the JVM that this is a string object(or correctly,this is a reference to a string object as objects are reference types in java).The String numx is allocated a space in memory only when you do something like

String numx=""; or String numx=new String();



Without an allocated memory,String objects are useless because no allocated memory implies that the object cannot store data.

Initializing any type of variable(local,global) before using it is a good practice and sometimes necessary.

Hope this clears your doubts

This post has been edited by rnty: 25 December 2012 - 08:59 PM

Was This Post Helpful? 1
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Variable Initialisation error.

Posted 25 December 2012 - 09:51 PM

View PostGisengryl, on 25 December 2012 - 11:08 PM, said:

I know that a local variable must be declared before it can be used, but does it need to be initialised before use as well ?

Yes

numx = numx + "whatever";
you need something in numx before being able to use it
Was This Post Helpful? 1
  • +
  • -

#4 Gisengryl  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 129
  • Joined: 08-September 12

Re: Variable Initialisation error.

Posted 25 December 2012 - 10:40 PM

Thanks rnty and pbl. :red_indian:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1