How does String works as Object in Java
) into a function, and we change the value of msg inside the function, when we get out of the function, the change of msg is kept. However, I think String is also considered as an Object in java. Why the change is not kept?
Thanks you for all you guys’ help~. I think I got a clear idea now. I admit my keyword search skill is pretty bad.
6 Answers 6
Java doesn’t have «out» function arguments; they are copies of references. Even though you change msg in the function, it does not affect the caller’s variable.
String is special, is immutable and is diffrent from normal Object. Java’s String is designed to be in between a primitive and a class.
String is passed by value, but unfortunately every change on String make new value, so your old reference has old value.
Anyone can create an immutable class. String is special in some regards (e.g. there are literals), but not in this case. It’s just another immutable class, and a reference type like every other class. And as I said before, mutability has no effect on what OP describes.
In Java, you cannot pass back a value to calling code by assigning to a method parameter. You are right that you can alter the internal structure of any parameter and that change will be seen in the calling code. However, assigning to a parameter is not the same thing as altering the internal structure. Also, a String is immutable—once created, its internal structure cannot be altered.
A common trick to do what you what is to use an array argument:
private boolean checkDateValue(Date d1, String[] msg) < if (d1 == null) < msg[0] = "d1 is null!"; return false; >return true; >
String[] msg = new String[1]; Date d1 = null; if (!checkDateValue(d1, msg))
Passing String objects as arguments Java
A newbie question. Can someone explain why s1 is not getting updated to «this is a test» ?. I thought in Java, object arguments are passed as references and if that is the case, then I am passing String s1 object as reference in Line 1. And s1 should have been set to «this is a test» via display() method.. Right ?
5 Answers 5
Java is pass-by-value always. For reference types, it passes a copy of the value of the reference.
static String display(String s)
The String s reference is reassigned, its value is changed. The called code won’t see this change because the value was a copy.
With String s, it’s hard to show behavior because they are immutable but take for example
public class Foo < int foo; >public static void main(String[] args) < Foo f = new Foo(); f.foo = 3; doFoo(f); System.out.println(f.foo); // prints 19 >public static void doFoo(Foo some)
public static void doFoo(Foo some)
the original would still show 3 , because you aren’t accessing the object through the reference you passed, you are accessing it through the new reference.
Of course you can always return the new reference and assign it to some variable, perhaps even the same one you passed to the method.
String is a reference which is passed by value. You can change where the reference points but not the caller’s copy. If the object were mutable you could change it’s content.
In short, Java ALWAYS passed by VALUE, it never did anything else.
As others mentioned String s1 is a reference which is passed by value, and hence s1 reference in your method still points to the old string.
I believe you want to do this to assign the returned value back to string s1:
String s1 = "another"; s1 = display(s1); System.out.println(display(s1))
Actually in the program you are having two reference string variable s1 and s when you are calling display(s1). Both s1 and s will be referencing to String «another».
but inside the display method you are changing the reference of s to point another String «this is a test» and s1 will still point to «another»
now s and s1 are holding refence to two different stings
display(s1) —> which hold reference of s, will print «this is a test»
Only if you assign s= display(s1) both variable will refer to same string
Because String is immutable so changes will not occur if you will not assign the returned value of function to the string.so in your question assign value of display(s1) to s.
s=display(s1);then the value of string s will change.
I was also getting the unchanged value when i was writing the program to get some permutations string(Although it is not giving all the permutations but this is for example to answer your question)
import java.io.*; public class MyString < public static void main(String []args)throws IOException< BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine().trim(); int n=0;int k=0; while(n!=s.length())< while(kn++; > > public static void swap(String s,int n1,int n2) < char temp; temp=s.charAt(n1); StringBuilder sb=new StringBuilder(s); sb.setCharAt(n1,s.charAt(n2)); sb.setCharAt(n2,temp); s=sb.toString(); >>
but i was not getting the permuted values of the string from above code.So I assigned the returned value of the swap function to the string and got changed values of string. after assigning the returned value i got the permuted values of string.
//import java.util.*; import java.io.*; public class MyString < public static void main(String []args)throws IOException< BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s=br.readLine().trim(); int n=0;int k=0; while(n!=s.length())< while(kn++; > > public static String swap(String s,int n1,int n2) < char temp; temp=s.charAt(n1); StringBuilder sb=new StringBuilder(s); sb.setCharAt(n1,s.charAt(n2)); sb.setCharAt(n2,temp); s=sb.toString(); return s; >>
How to turn a String value into a object reference in Java?
I am currently working on a very simple client-server-connection. The client and the server are connected through sockets and communicate by using streams. Now I want the client to be able to invoke methods on the server. Therefore the client should send a message to the server. This message is then split into two Strings. The first string methodName contains the name of the method to be called. The second String objectName contains the name of an object on which the method should be called. One way to this would be by using if-statements like if(methodName.equals(«mymethod»)); . This method works just fine and can be extended to check for objectName as well. Still I am very unhappy with this solution. I want to be able to invoke a lot of different methods on a lot of different objects (even on objects that don’t even exist yet). I just don’t want to write thousand of if-statements or cases. That’s why I try to find a different approach. I already found a partial solution for methodName by using this: java.lang.reflect.Method method = myObject.getClass().getMethod(methodName);
method.invoke(myObject); This would effectively turn the String value of methodName into a reference to the corresponding method. That’s just what I was looking for. But it comes with the problem that both instructions require an object reference. By now the «name» of that reference is still stored in objectName and most important, it is a String value and not a reference. What I am now looking for is a instruction like this: Object myObject = turnTheStringValueIntoAReference(objectName); For now we can just assume that there already exists an object reference with the name that is stored in objectName. Otherwise there might also be a way to do something like this: Object turnTheStringValueIntoAReference(objectName) = new Object(); I tried my best to find a way to turn a String value into a object reference but sadly I couldn’t find any solution. I now have reached to point where I was thinking that this «feature» purposely doesn’t exist in Java because it would basically eliminate type safety. Not to mention all the exceptions that might occur. However I still would be very happy and very thankful if anyone could tell me if there actually is a way to do this. Maybe I just didn’t figure it out yet. With further research I found out that RMI might be an alternative to this. I guess RMI would even be a much better way to this. The reason I still don’t want to RMI is that I plan on expanding the server in a way that it doesn’t only accept my own client but also clients that are written in different languages. I think managing this will be ways easier if the client only needs to send a message than somehow support Java RMI without being written in Java. Well, I think that’s it. I would really appreciate your help.
Isn’t Class.instanceOf() what you want? Class.forName() takes a String. All this has been part of the JDK since 1.0. A better question is: should you do this? Reflection might not be the best idea. Do your clients really need this kind of flexibility?
@duffymo Thanks for your answer. I don’t really understand how this would work. Class.forNanme returns a Class object. But having the class object doesn’t allow me to call a method on an instance of this class. What I would need is something like Object.forName(). Am I missing something?
@FrancisGodinho Thanks for your answer. Maybe there is some way to make it work but I cannot see it yet. What’s done here is creating a new object. That wouldn’t be what I intended but I would be acceptable. But in this case I would have to have some object holding the information for the constructor. This again rises the question on how to address that object. I cannot rely on using primitiv data types only.
A search through SO would get you the answer. It’s not a pretty one unless all the classes you want to invoke have similar constructor arguments: stackoverflow.com/questions/1782598/…
How do you get the «object reference» of an object in java when toString() and hashCode() have been overridden?
I would like to print the «object reference» of an object in Java for debugging purposes. I.e. to make sure that the object is the same (or different) depending on the situation. The problem is that the class in question inherits from another class, which has overriden both toString() and hashCode() which would usually give me the id. Example situation: Running a multi-threaded application, where I (during development) want to check if all the threads use the same instance of a resource object or not.
depending on if you can do it at all. == is the way to go. but I have no idea how the code in question is stuctured. Again hashCode is likely fine for what you are doing, but it could break depending on how the library is implemented.
6 Answers 6
What exactly are you planning on doing with it (what you want to do makes a difference with what you will need to call).
hashCode , as defined in the JavaDocs, says:
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.)
So if you are using hashCode() to find out if it is a unique object in memory that isn’t a good way to do it.
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object’s class overrides hashCode(). The hash code for the null reference is zero.
Which, for what you are doing, sounds like what you want. but what you want to do might not be safe depending on how the library is implemented.