Why the following code produced this output ?<br /> <br /> int x = 5;<br /> int y = x;<br /> y = 10;<br />       <br /> System.out.println(x); // prints 5 and not 10
Javasearch.buggybread.com

Search Interview Questions


 More than 3000 questions in repository.
 There are more than 900 unanswered questions.
Click here and help us by providing the answer.
 Have a video suggestion.
Click Correct / Improve and please let us know.
Label / Company      Label / Company / Text

   



Interview Questions and Answers

 Q1. Why the following code produced this output ?

int x = 5;
int y = x;
y = 10;
      
System.out.println(x); // prints 5 and not 10
Core Java
Ans. Because when we say y = x, the value of x is copied to another memory location and then y points to that new memory location.

Unlike object references that once assigned point to same object in memory, value is copied in case of variable assignment.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     variable assignment


Related Questions

  What do you mean by "Java is a statically typed language" ?
  What are the advantages and disadvantages of static variables and static methods ?
  How does volatile affect code optimization by compiler?
 Can we declare static variables as transient ?
 Which of the following can be marked static ?

a. Methods , Variables and Initialization Blocks.
b. Methods , Variables , Initialization Blocks and Outer Classes and nested Classes.
c. Methods , Variables , Initialization Blocks and Outer Classes.
d. Methods , Variables , Initialization Blocks and nested Classes
  Can we access instance variables within static methods ?
  What is a Final Variable ?
  When are static variables loaded in memory ?
  Can we serialize static variables ?
  Which memory areas does instance and static variables use ?



Help us and Others Improve. Please let us know the questions asked in any of your previous interview.

Any input from you will be highly appreciated and It will unlock the application for 10 more requests.

Company Name:
Questions Asked: