wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Strange result in my programm JTEST Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Strange result in my programm JTEST" Watch "Strange result in my programm JTEST" New topic
Author

Strange result in my programm JTEST

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
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

Joined: Oct 17, 2001
Posts: 4313

You're classes are more different than that... check out the parenthesis around your for loops:

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
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
 
Don't get me started about those stupid light bulbs.
 
subject: Strange result in my programm JTEST
 
Similar Threads
why is the code complining
Question48 of Valentin Crettaz's mock exam
why does 'break' traverse one more time
Object Casting - Wyh is "i = 0"
Something is fishy out here..