views:

151

answers:

4

The output of the fist System.out.println() is not same as the second System.out.println()
What may be the reason?

public class swapex{
    public static int var1, var2;

    public void badSwap(int var1, int var2){
        int temp = var1;
        this.var1 = var2;
        this.var2 = temp;
        System.out.println("var1 " + var1 + " var2 "+ var2);
    }

    public static void main(String args[])
    {
        swapex sw= new swapex();
        sw.badSwap(10,20);
        System.out.println("var1 " + var1 + " var2 "+ var2);
    }
}
+8  A: 

The first is outputting the parameter values, the second is outputting the static fields.

Let's look at all meaning of the relevant values.

public void badSwap(int var1, int var2){

var1 and var2 are arguments passed in to the method.

int temp = var1;

temp is set to the passed in var1.

this.var1 = var2;

The static field var1 is set to the passed in var2. This is poor style, because it is unnecessarily confusing. If you have reason to use a static, write swapex.var1.

this.var2 = temp;

Again, the static field is being set.

System.out.println("var1 " + var1 + " var2 "+ var2);

The locals are being printed.

Back in main, the line:

System.out.println("var1 " + var1 + " var2 "+ var2);

resolves to the static fields because there are no stack variables with those names. Again, this is also poor style. You would use swapex.var1 and swapex.var2.

So, the reason they print differently is that you first print the original unswapped arguments, then the swapped (inverse to the arguments) static fields.

Matthew Flaschen
+1  A: 

The variables you are setting in badswap are the local arguments, not the static members of swapex. Since the local scope takes precedence, the static members are unchanged

When you print the first time, you are printing the local arguments, the second time, you are printing the static members

to get the two to be the same, change the names of the arguments to badswap().

Nathan
This is wrong. badswap is setting the static variables, but printing the (unchanged) locals. Then, later, the (swapped) statics are printed.
Matthew Flaschen
Shoot your right
Nathan
A: 
In the method badswap the var1 and var2 that 

gets printed is the local variables of the said method namely

badswap(int var1, int var2)

and not that of class variables 

public static int var1,var2

and that is the cause for the difference.

abson
A: 

static fields are relative to a class. The this keyword is usually used to distinguish between an identically-named local variable and a class variable. It is advised to avoid using this to refer to static fields as this unnecessary but the compiler appears to accept it.

Additionally, var1 and var2 only exist within the scope of your badSwap() method. This is why you're getting a different output. The sysout within the method is displaying paramater values whereas the sysout in the main is displaying the values of class variables.

James P.