File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strange result in my programm JTEST

 
Thomas Markl
Ranch Hand
Posts: 192
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class jtest {
public static void main (String args[]) {
for (int j=0; j<4; ++j)
{
System.out.println(j);
System.out.println(j);
}
}
}
c:\jdk1.3\bin>java jtest
0
0
1
1
2
2
3
3
==============================================

class jtest1 {
public static void main (String args[]) {
int j;
for (j=0; j<4; ++j)
System.out.println(j);
System.out.println(j);
}
}
:\jdk1.3\bin>java jtest1
0
1
2
3
4
class jtest2 {
static int j;
public static void main (String args[]) {
for (j=0; j<4; ++j)
System.out.println(j);
System.out.println(j);
}
}
c:\jdk1.3\bin>java jtest2
0
1
2
3
4

My Questions:
=============
I. Why does jtest1 and jtest2 deliver the result
0,1,2,3,4 instead of 0,0,1,1,2,2,3,3
(as in jtest)?
II. In jtest2 the variable j is defined as a static variable. Why is this definition equivalent to a local variable in a static class?
Or let's put the question in another way: Why is the local variable in the main method static? Is it because j is defined in a static method? Is a variable automatically static if it is defined locally in an static method?
Thanks for your answers.
Thomas Markl
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're classes are more different than that... check out the parenthesis around your for loops:

 
Thomas Markl
Ranch Hand
Posts: 192
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
you are right.
JTEST1 can be written as follows:
public class jtest8a
{
public static void main (String args[])
{
int j;
for (j=0; j<4; ++j)
{System.out.println(j);}
System.out.println(j);
}
}
Then the result 0,1,2,3,4 is clearer because 0,1,2,3 comes from the print statement in the for loop and the 4 from the last print statement.
Do you have an answer for Question II?
Ciao
Thomas
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic