Nikunj Surya
Nikunj Surya

Reputation: 13

Adding to a random number

I have used the Random class to generate a random number and the number shows up, but when I try to add that generated random number with 10 it just get concatenated i.e if the random number is 20 it will show as 2010

import java.util.Random;

public class MainClass{
    static int x = 50;
    static  int y = 10;

    public class InnerClass {    
        double myDouble = x;

        void show() {
            System.out.println(myDouble + 5);
        }
    }

    public static void main(String args[]){
        Random rand = new Random();
        MainClass obj1 = new MainClass();
        MainClass.InnerClass obj2 = obj1.new InnerClass();

        int int_random = rand.nextInt(x);

        System.out.println(int_random + " :" + " This is the Random Number and its plus 10 is "+ int_random + y);

        // obj2.show();
    }
}

Upvotes: 0

Views: 65

Answers (1)

Thomas
Thomas

Reputation: 181745

The + operator in Java can do two very different things: adding two numbers, and concatenating two strings. If you "add" a number to a string, the number is first converted into a string, and then the two strings are concatenated.

The other piece of the puzzle is that + is applied left to right (it's left-associative). So if you write a + b + c, that means (a + b) + c and not a + (b + c). So if either a is a string and b and c are integers, (a + b) will be a string, and c is converted to a string before being added to it.

The solution is to force the order of evaluation using parentheses: write a + (b + c) explicitly, or in your case:

    System.out.println(int_random + " :" + " This is the Random Number and its plus 10 is "+ (int_random + y));

Upvotes: 3

Related Questions