user3499932
user3499932

Reputation: 9

Simple java why variable doesn't change?

public class Practice {
    public static void main( String args[] )
    {
        int lowest= 5;
        int sum = 2;
        if (lowest>sum){
            sum=lowest; 
        }
        System.out.println( lowest );
    }   
}

From this code I, get 5 but shouldn't I get 2? how should I change the code to make it equal to 2 instead of "sum=lowest;"?

Upvotes: 0

Views: 83

Answers (5)

chad martin
chad martin

Reputation: 31

lowest = sum.

by doing "sum = lowest" you are assigning the value of lowest to sum. Assignments work right to left

Upvotes: 0

kyle
kyle

Reputation: 155

Change

if (lowest > sum){
    sum = lowest; 
}

to

if (lowest > sum){
    lowest = sum; 
}

if you are trying to get lowest to be equal to 2.

Upvotes: 0

merlin2011
merlin2011

Reputation: 75545

If you want 2, just do:

    if (lowest>sum){
        lowest=sum; 
    }

Upvotes: 0

DaveH
DaveH

Reputation: 7335

I'm not sure what you're trying to do, but you never alter the value of lowest, but you assign lowest to sum

Do you mena to print the value of sum ?

Upvotes: 0

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

Because assignment is the other way around. It is like:

variable = new value;

So, you want:

lowest = sum;

Upvotes: 3

Related Questions