1

I was giving a exam when i got this question What is the Output of following question

 public class ClassicQuestion {
        public static void main(String[] args) 
        {
            int i = 25;
            double j = 95.0;
            System.out.println(j+=i);
            System.out.println(i+=j);

        }

}

And the option for answer was

  1. compile time error
  2. run time error
  3. 120.0 145
  4. 120.0 120

I don't know the correct answer but i thought correct answer would be one, but showed me incorrect answer? how can we assign one variable to different types of data types without conversion ?

user4834352
  • 35
  • 1
  • 4

1 Answers1

4

Correct Answer 3.

Because according to

jls

Compound Assignment operators of the form E1 op= E2 evalute to E1 = (T) ((E1) op (E2)) where T is the type of E1, except that E1 is evaluated only once

so your j+=i changes to j=(double)(j+i) and since now j value is 120.0 next time i does i+=j it changes to i=(int)(i+j) hence 145

so OUTPUT is 120.0 145

Ankur Anand
  • 3,873
  • 2
  • 23
  • 44