0

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();
    }
}
3
  • 2
    add parentheses around (int_random + y). Commented Apr 20, 2020 at 8:39
  • 1
    + is left associative in Java, meaning "... is " + int_random + y is the same as ("... is " + int_random) + y Commented Apr 20, 2020 at 8:40
  • I've removed the random tag, you'd have the same issue with printing fixed values the way you've done it. Randomness has nothing to do with the result. Commented Apr 20, 2020 at 15:39

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

3 Comments

So if you write a + b + c, that means (a + b) + c - This is wrong. int x = 5, y = 10, z = 15; System.out.println("Hello" + x + y + z); will print Hello51015 . As per your explanation, it would have printed Hello1515.
@ArvindKumarAvinash As per his explanation, you would add "Hello" and x first, not x and y like you imply with a result Hello1515. His explanation is correct
I've got it. Thank you. As per his explanation, a is Hello in my expression and therefore it will be evaluated as ("Hello" + 5) + 10 and finally, "Hello510" + 15 which will be evaluated to Hello51015.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.