23
package com.testProject;
public class JavaSample {

    public static void main(String[] args) {

        String myString1 = new String("Sample1");
        System.out.println(myString1);
        String myString2 = new String("Sample2");
        System.out.println(myString2);
    }
}

in the above piece of code how to print the address of these Strings which i created "Sample1" and "Sample2", i need to print the memory location of the String object myString1 and myString2

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103

8 Answers8

20

it seems like you all are INCORRECT! Ill try to explain :

        String s = new String("hi Mr. Buddy");
//        s = = "hi Mr. Buddy"; //is false
//        s.equals("hi Mr. Buddy"); //is true
        System.out.println( s.hashCode() );
        System.out.println( "hi Mr. Buddy".hashCode() );

        System.out.println( "hi Mr. Buddy" == s );

        System.out.println( "hi Mr. Buddy" );

result of this in my case :

1372880496
1372880496
false
hi Mr. Buddy

As we see the hashCode() are same, but String has differet addresses (bcs "hi Mr. Buddy" == s >>== false ) ? what do you think ?

I found :

System.out.println( "s=" + System.identityHashCode( s ) );
System.out.println( "..=" + System.identityHashCode( "hi Mr. Buddy" ) );

the result is:

s=733003674
..=1626549726
Andrew Niken
  • 606
  • 2
  • 8
  • 18
  • The explaining of that is here http://stackoverflow.com/questions/18396927/how-to-print-the-address-of-an-object-if-you-have-redefined-tostring-method – Andrew Niken Dec 06 '16 at 23:58
14

As pointed out my comment, this isn't recommended practise, but since you asked...

private static Unsafe unsafe;

static
{
    try
    {
        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        unsafe = (Unsafe)field.get(null);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

public static long addressOf(Object o)
throws Exception
{
    Object[] array = new Object[] {o};

    long baseOffset = unsafe.arrayBaseOffset(Object[].class);
    int addressSize = unsafe.addressSize();
    long objectAddress;
    switch (addressSize)
    {
        case 4:
            objectAddress = unsafe.getInt(array, baseOffset);
            break;
        case 8:
            objectAddress = unsafe.getLong(array, baseOffset);
            break;
        default:
            throw new Error("unsupported address size: " + addressSize);
    }       

    return(objectAddress);
}
hd1
  • 33,938
  • 5
  • 80
  • 91
13

Memory addresses aren't generally available through the Java language, but System.identityHashCode(myString1) might be close enough, depending on what you are trying to achieve.

clstrfsck
  • 14,715
  • 4
  • 44
  • 59
8

If you mean "address" as this:

System.out.println(new Object());

java.lang.Object@31ec0130

then you can just do,

String s = new String("one");
System.out.println(Integer.toHexString(s.hashCode()));

1ae66

Since what you think is the "address" is just the hashCode() converted to hex string.


Side Note
This answer was historically accepted as correct and will only work for classes that didn't override the hashCode() method, but (as mentioned in comments) it will not work for String classes since they override the hashCode() method. Readers looking for up-to-date information on the topic of this question should first go through all the comments/discussion on this answer and should consult further resources, or ask a new question citing this question and answer and explicitly asking for new information on things that have changed since they were written.

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
renz
  • 1,072
  • 3
  • 11
  • 21
  • Every object has a hashCode() method. A hashcode is an int value for an object, so that the object can be used in Collection classes that use hashing, including Hashtable, HashMap, and HashSet. – renz May 04 '13 at 05:49
  • 8
    I don't think hashcode is related to the actual memory address of the object. :) – renz May 04 '13 at 05:52
  • 6
    hashcode is a mathematically calculated value of the content of variable. Its not the address in any way. – sohil Sep 13 '13 at 19:13
  • 8
    @renz This works for any class that didn't override the hashcode method and uses the default implementation of the Object class, which prints the address in the memory. The String class overrides the hashcode method and hence doesnot return the memory location of the String. – Harsh Poddar Feb 17 '16 at 21:37
  • 1
    This is wrong, as the comment above me said. Ence my downvote – Ced Jun 08 '16 at 06:18
  • @renz Can you please provide the code for converting this "@ebec264" memory address to string ? Thanks in advance – Vinoth Vino Oct 23 '16 at 06:59
  • @renz I don't think so it's address "Integer.toHexString(s.hashCode())" – Kiran Kumar Kotari May 11 '17 at 15:05
  • String str = "hello"; // it's in string constant pool String str1 = new String("hello"); // in heap not in string constant pool - right System.out.println(Integer.toHexString(str.hashCode())); System.out.println(Integer.toHexString(str1.hashCode())); // How the memory location for both be same – Kiran Kumar Kotari May 11 '17 at 15:13
  • The "hashCode" method is overridden in the String class. It does NOT return anything like the "address" of anything in memory. The value it returns is a function of the characters in the string. Here is the source code that does this: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/java/lang/String.java#String.hashCode%28%29 – Jeff Grigg Dec 21 '17 at 20:02
  • 1
    This is not the way to find the actual address. To check it do `String s = "abc"; String s2 = new String("abc"); System.out.println(s1 == s2)` This will print `false` meaning that both the objects are different. But if you do your operations, you'll find that you're getting "same" address. – Raman Sahasi Jul 24 '18 at 06:21
  • Hello just consider this scenario String s1="abc"; and String s2= new String("abc"); then the above approach returns the same value which is not valid As the address should be different but hash can be same. – kushal Baldev Jun 01 '19 at 10:24
  • This is truly wrong. the actual memory of the String Object and the result of hashCode() is different from each other. – koo Sep 08 '19 at 16:19
3

I think answer by @AnNik should be considered as correct answer. Below is the comparison,

   String s1= "abc";
    String s2 = new String("abc");
    String s3= "abc";


    System.out.println(Integer.toHexString(s1.hashCode()));
    System.out.println(Integer.toHexString(s2.hashCode()));
    System.out.println(Integer.toHexString(s3.hashCode()));
    System.out.println(System.identityHashCode(s1));
    System.out.println(System.identityHashCode(s2));
    System.out.println(System.identityHashCode(s3));

Output:

17862
17862
17862
356573597
1735600054
356573597
Chintan Pandya
  • 338
  • 4
  • 14
0

Actually you cannot. JVM handles the memory and the gc can shift the data around when it sees fit.

So there is no "real" concept of a memory address within Java(it only is the concern of the JVM)

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
0

Why don't you use printf with %b:

String s= new String("Hello");
System.out.println(Integer.toHexString(s.hashCode()));
System.out.printf("address of the reference variable s holding string \"%s\" is %h%n", s,s);
chikitin
  • 762
  • 6
  • 28
-1

simply right ur string name followed by this code:

string object.getClass.getName()+'@'+Integer.toHexString(string boject.hashCode());

example:

String str=new String("Hello");
System.out.println(str.getClass.getName+'@'+Integer.toHexString(str.hashCode());
Sindhoo Oad
  • 1,194
  • 2
  • 13
  • 29