• Post Reply Bookmark Topic Watch Topic
  • New Topic

String and int behavior based on assignment  RSS feed

 
Chinmoy Padhi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi JavaRanch,
I have came across a code and below are my queries based on the output of the program

1. what does 1st two system.out.println() means?
2. If String class is immutable then how is possible ?
3. How int value didn't get changed when it has been assigned with ?




Output of the program
--------------------------
value of i is com.sanujava.Project@1db9742
value of s is com.sanujava.Project@106d69c
*************
+++++++++++++++
value of d.i:70
value of d.s:seed
10
sid
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chinmoy Padhi wrote:
1. what does 1st two system.out.println() means?


The first two println() doesn't do what it claims. It is supposed to print the value of "i" and "s", but it just creates a new Project object to be printed. And since the Project class never overridden the toString() method, those two calls yield the first two printouts with the identity hash values of those objects.

Henry
 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry already answered to your first question.

Second and third question have nothing to do with strings immutability.

2.
On the line 8 you have created Project object which is being refered to by the variable "d".
On line 15 and 16 you reassign Project class instance variables which were declared and initialized on lines 3 and 4.

3.
On line 23 and 24 you're creating new Project objects and printing their instance field values, which are declared and initialized again on lines 3 and 4, and these values are "10" and "sid".
 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the  Ranch
 
Ganesh Patekar
Bartender
Posts: 726
23
Eclipse IDE Hibernate jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One click here --> Strings, Literally by Corey McGlone  and couple of minutes of perusing it might clear all your doubts of String in Java.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and remember...a String is immutable. But a reference to a string can be directed to point to a different String.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!