Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arrays

 
rengarajan vaikuntam
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am a beginer in java.In the below clode class Array1 is compilng whereas class Array2 is not compiling. in Array1 class i have declared and initialised the array inside the method foo whereas in the class Array2 i have initialised the array in the class itself.
public class Array1 {
public void foo(){
int[] j;
j = new int[10];
} //End method foo
} //End class

class Array2 {
int[] j1;
j1 = new int[10];
}
Why is it so?
Thanks
Renga.
 
David Ulicny
Ranch Hand
Posts: 724
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this
 
Krishnan Loganathan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try the following code snippet:


public class Array1 {
public void foo(){
int[] j;
j = new int[10];
} //End method foo
} //End class

class Array2 {
int[] j1;
{
j1 = new int[10];
}
}
we cann't assign values for variables/references separately in class level. whether we have to declare in the time of declaring or in construtor or anywhere in a code block, as shown above.

Regards,
Loga
 
rengarajan vaikuntam
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx loga,
But why?
A variable declared in a class level and when it is initiallised later is not compiling.And how it is compiling when initialised within a block.What significance it has?But whereas a variable declared within a method accepts initialisation later before it is being referred.
Ex:

Public class Test {
int k;
k=10;
} //this class not compiles

class Test1 {
int k;
{
k=10;
} //this class compiles

class Test2 {
public void comp() {
int k;
k=10;
}
} //this also compiles
A brief explination why and how?
Thanx
Renga
 
Sreenivasa Majji
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason is all 'executable statements' must be inside a method/constructor/static initializer.

The reason the previous one is compiled, because it's a static block.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assignment is an operation. So if the assignment is not done at the point of declaration, then it must be done within some type of executing code -- for example, initializer block or method block.
[ October 12, 2004: Message edited by: marc weber ]
 
rengarajan vaikuntam
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx sreeni & marc

It is very clear.

Thanq very much
Renga.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic