Jay Sky
Jay Sky

Reputation: 143

What is difference between using "pure" String and String returned from method?

I'm new to programming and as I was using some strings in Java I could not figure out this probably simple question:

If we have method:

public static String str(String arg)
{
 return arg;
}

Is there any difference between those two samples below?

System.out.println("Hello");

vs

System.out.println(Someclass.str("Hello"));

What is processed faster? Is it better to set arguments of methods using return value of different method or using chosen datatype directly? Is there any practical use of second sample?

Thanks and sorry if it's dumb question.

Upvotes: 0

Views: 416

Answers (4)

River
River

Reputation: 9093

The first case is faster.

The second case is nonsensical. You are passing a String to a method which simply returns that same String object. There is absolutely no reason to do this. It will probably be a bit slower because of the unnecessary method call.

Using double quotes will already automatically create a String object.

And in any case, readable code far outweighs small performance boosts in all but the most demanding scenarios.

Upvotes: 1

Nathan Hughes
Nathan Hughes

Reputation: 96424

There is no difference, except that the second example is more obfuscatory, the method call doesn't add any value. Run this code:

"Hello".equals(Someclass.str("Hello"));

It will return true, that tells you that the strings are equivalent.

All the method in the second example does is take the reference passed in and return it, so the code

String s = "Hello";
System.out.println(Someclass.str(s) == s);

will print true; s and Someclass.str's return value should be the same reference.

Don't fixate on performance, try to write code that makes sense.

Upvotes: 2

Bobby StJacques
Bobby StJacques

Reputation: 734

In Java, all parameters are passed by value. This includes references to objects like Strings. When you call the str(String arg) method, you are not actually passing the String into the method, rather a copy of the reference that points to the String's location in memory. When you return arg, again, you are returning a copy of this reference to the String.

In your second example you are using a String literal. Java treats these in a special way (the compiler essentially creates a constant and substitutes that constant in place of the literal wherever you see it in code). So when you pass the literal in, you are actually passing a copy of the reference (memory location) of the literal, and then returning it. There is still only one String object.

In other words, all you are doing is adding a small amount of overhead by inserting the method call in the middle.

Upvotes: 1

Arda Keskiner
Arda Keskiner

Reputation: 792

The first case is slightly faster and it makes no sense using the second one unless you are modifying the string in Someclass's str method.

Upvotes: 1

Related Questions