Solved

memory address, immuatble

Posted on 2000-03-30
9
232 Views
Last Modified: 2012-05-04
Hi,
 If anybody know pls clarify it.

 1. Is it possible to see the memory address of the var./obj. in java ?
My friend told that System.identityHashCode(Object) will give the mem. address ?
if yes what is the difference between
obj.hashcode() & System.identityHashCode(obj) ???

 2. I konw that objects are passed by reference. So I passed String & StringBuffer to my function and I change the value but it is not reflected outside ?
 I know Strings - immutable
 StringBuffer   - mutable
 so my changes in function should affect my StringBuffer. but not. Y ?

Ex.
class Test {

 String s = "hi"
 StringBuffer sb = new StringBuffer("ho");

 public Test() {
 
  change(s, sb);
  System.out.print("s="+s+"sb="+sb);
 }

 void change(String s, StringBuffer sb) {

 s = "changed";
// sb.append("asdfgf");
 sb= new StringBuffer("new");
}
}
but if use only sb.append() the changes reflected outside also.

3. How to create immutable object ?
 [wheathere I have to make like 'String' class ???]

Thanx,
0
Comment
Question by:rameshaa
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 7

Expert Comment

by:Ravindra76
ID: 2670106

When ever U creates new StringBuffer(),

It will create another object reference and htat's why Ur changes are not reflecting back.

In this method,

void change(String s, StringBuffer sb) {

 s = "changed";
// sb.append("asdfgf");
 sb= new StringBuffer("new");
}

The last line created new Object reference. That is the reason for non reflection of changes

Best of luck
0
 
LVL 7

Expert Comment

by:Ravindra76
ID: 2670108

When ever U creates new StringBuffer(),

It will create another object reference and htat's why Ur changes are not reflecting back.

In this method,

void change(String s, StringBuffer sb) {

 s = "changed";
// sb.append("asdfgf");
 sb= new StringBuffer("new");
}

The last line created new Object reference. That is the reason for non reflection of changes

Best of luck
0
 
LVL 19

Accepted Solution

by:
Jim Cakalic earned 50 total points
ID: 2670126
Three questions deserves three answers.

1) Memory address of Java objects.
System.identityHashCode() is basically a way of calling Object.hashCode() and ensuring that the Object class method is called regardless of whether the class of the instance or any of its superclasses have overridden Object.hashCode(). What does Object.hashCode() give you? The documentation states, "As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)" In other words, the value is VM dependent and may change between versions of a VM from the same vendor. Finally, even if this were an internal JVM memory address of the object, what would you do with it?

2) Visibility of changes to method parameter objects
Actually, parameters are NOT passed by reference, they are passed by value. Values of parameter variables within a method are copies of the values specified as arguments. If you pass a boolean (primitive) to a method, the parameter received is a copy of whatever was passed as the argument. As a result, any changes to the parameter within the method are not visible to the invoker of the method. Now the tricky part, when an object reference is a parameter, a copy of the object reference is passed, not the object itself. If the method code changes the parameter to refer to a different object than the one supplied as an argument, that change will not be visible to the invoker. But if you change fields of the of the object parameter or invoke methods on the object that change it's state, then the object is changed for every part of the program that holds a reference to it.

The critical point here is to distinguish between a reference to an object and the actual object. An object exists only once within the memory of the JVM. But there could be many simultaneous references to that object. All the references are to the same physical memory (at some point). In your example:

    void change(String s, StringBuffer sb) {
        s = "changed";
        //sb.append("asdfgf");
        sb = new StringBuffer("new");
    }

the two assignments are changing the method's copy of the object reference to point to a new object. Saying 's = "changed"' is a more efficient (both typing and performance) way of saying 's = new String("changed")'. So in both cases, within the change() method, s and sb now point to different objects. But you have only changed the local object references, not the original references held by the invoker.

On the other hand, sb.append() changes the state of the object. Since the object reference being used within the method refers to the same object to as the invoker-held reference, the invoker can see this change when the method completes. When multiple object references refer to the same actual object, changes  made to the object through any of the references are visible through all the others.

3) How to create an immutable object.
I'll assume you mean that you want to define a class for which object instances are immutable. This is easy. Being immutable means that once the object is created, you cannot change the state of the object. String objects are confusing because of the special treatment given to them by the language/compiler. Lets consider instead the Integer class which is an object wrapper for the primitive int type. Integer is immutable. When you construct an Integer object, you set the state or value of the object during the construction. If you look at Integer you will notice that it does not have a no-arg constructor. You are required to supply a value if you want to make an instance of Integer. Next, although Integer has a good number of methods, there is no way to change the value of a a specific Integer object; i.e, there is not Integer.setValue(int value) method. This example highlights the steps you need to take to define a class of immutable objects:
    1. Make state (variables) private so they cannot be directly modified.
    2. All object state (variable values) must be set by the constructor.
    3. Do not define methods which modify the state of the object.

I hope these comments answer you questions. If not, I will be happy to expand on the topic(s) further.

Best regards,
Jim Cakalic
0
 
LVL 7

Expert Comment

by:Sasha_Mapa
ID: 2670129
1. When you extend Object, you can override the hashCode() method, and then it would return a different value than the one returned by Object's hashCode() method. System.identityHashCode() guarantees to return the same value as would have been returned by the default Object hashCode() method.
There is nowhere a requirement for System.identityHashCode() to return the memory address. The requirement is that for any 2 different objects it returns a different value and for the same object it returns the same value.
It is true that hashCode() uses somehow the memory address of the object to create the unique hash code, but this does NOT mean that any implementation will do that and it does NOT mean it returns the actual address.

2. All variables in java are pointers to objects (except primitive type variables, like int, double etc.) and not the objects themselves. When you pass ANY object to a method, you give that method a pointer to that object. Inside the method, the variable (sb in your case) is also a pointer (to a StringBuffer object in your case). When you set a value to the variable, you essentially make that pointer point to a different object, and the original object remains unchanged.
If you use sb.append(), you change the OBJECT itself, you append some other string to it, so what happens is that you change to OBJECT, while in your original code, you just change the value of the POINTER, not the object.

3. Just create a class that doesn't define methods for changing it's values, for example, a String doesn't have methods to modify itself in any way.
This is an example of an immutable class:


public class MyPoint{

  private int x,y;

  public MyPoint(int x, int y){
    this.x = x;
    this.y = y;
  }

  public int getX(){
    return x;
  }


  public int getY(){
    return y;
  }

  public int getSum(){
    return x+y;
  }

}


It's immutable because there is no way to change the object once it's created.


I lock the question because I think I answered all your questions completely, if I did not please post follow up questions and I will make the subject clear.

Sasha :-)
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2670401
I guess that will teach me to not lock questions.
0
 
LVL 7

Expert Comment

by:Sasha_Mapa
ID: 2670420
Sorry, I started typing and clicked "Submit" before seeing your post...Note there is only a minute difference between our posts -- It took me way longer than a minute to post the answer. I didn't copy it from you.
I'm withdrawing the proposed answer :-)
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2670449
Sasha, that's okay. It took me a lot longer than a minute to type my answer, too. I'll leave it to rameshaa to decide how points should be distributed. Since I have never asked a question I don't know -- is it easy to distribute points to multiple commenters? Sometimes, more than one person deserves to be rewarded for contributing toward an answer.

Jim
0
 
LVL 7

Expert Comment

by:Sasha_Mapa
ID: 2670458
I think the process for that is to ask one of the guys in support...
0
 

Author Comment

by:rameshaa
ID: 2670885
Really I got awesome explanation for my questions.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now