Are there other ways to concatenate inofrmation when I am going to print other than +, like System.out.println("hello" + etc + variable)) - java

Before I learnt the basics in python and there are several ways to concatenate information like:
name = "Eduardo"
surname = "Garcia"
print("Hello " + name + " " + surname)
print("Hello {} {}".format(name, surname))
I like this one
print(f"Hello {name} {surname}")
But I am making a course in java and the teacher says that the only way to do it is with +
But that sounds strange to me. Are there other ways to do it like in python with .format or f.
Thank you.
I am learning the basics in java. I just want to understand how it works.

Java has System.out.printf, which is more-or-less (not exactly) like every other printf that's out there (see documentation).
The String class has String.format (see documentation).
With respect to what your teacher tells you - literally, they are correct. Formatting is not concatenation; however, to achieve a particular result, you can often choose between formatting and concatenation.

Related

Generating Messages approaches

At https://docs.oracle.com/javase/tutorial/i18n/text/usage.html I found this:
// recommended
System.out.printf("Character %c is invalid.%n", codePoint);
// not recommended
System.out.println("Character " + String.valueOf(char) + " is invalid.");
Why is one recommend and why the other is not?
UPDATE
The arguments provided by the documentation have not much meaning for me excepting the localization one:
This following approach is simple and avoids concatenation, which
makes the text more difficult to localize as not all languages insert
numeric values into a string in the same order as English.
System.out.printf("Character %c is invalid.%n", codePoint); //Recommended
The above approach is recommended because of localization of string is easier in this way.
With respect to performance, this approach is not recommended as answered by #oleg.cherednik.
This is already answered (more details available here) Is it better practice to use String.format over string Concatenation in Java?
"Character " + String.valueOf(char) + " is invalid."
JVM transform this to StringBuilder. Bud DO NOT USE + for string IN LOOP. In this case, every when you use +, NEW STRING will be created and put into StringPool.

Writing java docs - showing an output example

I'm asking myself how to show an example of an output in java docs.
See here...
/**
* Returns the app's version-info (e.g.: "App 1.2").
*/
public static String getAppVersionInfo() {
return getAppName() + " " + getVersionName();
}
How to express the 'e.g.' in a convenient way?
As far as I know, Javadoc doesn't have a special tag for example values.
The closest thing to what you are describing that I remember encountering would be examples of hashing algorithms in MessageDigest#getAlgorithm(). In that case the authors simply say
... The name should be a standard Java Security name (such as "SHA", "MD5", and so on). ...
There is also the Javadoc HowTo, which specifically discourages using "e.g.":
Avoid Latin
use "also known as" instead of "aka", use "that is" or "to be specific" instead of "i.e.", use "for example" instead of "e.g.", and use "in other words" or "namely" instead of "viz."
Other than that, I'm not aware of any rules or best practices applicable to your situation.

Java concatenate to build string or format

I'm writing a MUD (text based game) at the moment using java. One of the major aspects of a MUD is formatting strings and sending it back to the user. How would this best be accomplished?
Say I wanted to send the following string:
You say to Someone "Hello!" - where "Someone", "say" and "Hello!" are all variables. Which would be best performance wise?
"You " + verb + " to " + user + " \"" + text + "\""
or
String.format("You %1$s to %2$s \"%3$s\"", verb, user, text)
or some other option?
I'm not sure which is going to be easier to use in the end (which is important because it'll be everywhere), but I'm thinking about it at this point because concatenating with +'s is getting a bit confusing with some of the bigger lines. I feel that using StringBuilder in this case will simply make it even less readable.
Any suggestion here?
If the strings are built using a single concatenation expression; e.g.
String s = "You " + verb + " to " + user + " \"" + text + "\"";
then this is more or less equivalent to the more long winded:
StringBuilder sb = new StringBuilder();
sb.append("You");
sb.append(verb);
sb.append(" to ");
sb.append(user);
sb.append(" \"");
sb.append(text );
sb.append('"');
String s = sb.toString();
In fact, a classic Java compiler will compile the former into the latter ... almost. In Java 9, they implemented JEP 280 which replaces the sequence of constructor and method calls in the bytecodes with a single invokedynamic bytecode. The runtime system then optimizes this1.
The efficiency issues arise when you start creating intermediate strings, or building strings using += and so on. At that point, StringBuilder becomes more efficient because you reduce the number of intermediate strings that get created and then thrown away.
Now when you use String.format(), it should be using a StringBuilder under the hood. However, format also has to parse the format String each time you make the call, and that is an overhead you don't have if you do the string building optimally.
Having said this, My Advice would be to write the code in the way that is most readable. Only worry about the most efficient way to build strings if profiling tells you that this is a real performance concern. (Right now, you are spending time thinking about ways to address a performance issue that may turn out to be insignificant or irrelevant.)
Another answer mentions that using a format string may simplify support for multiple languages. This is true, though there are limits as to what you can do with respect to such things as plurals, genders, and so on.
1 - As a consequence, hand optimization as per the example above might actually have negative consequences, for Java 9 or later. But this is a risk you take whenever you micro-optimize.
I think that concatenation with + is more readable than using String.format.
String.format is good when you need to format number and dates.
Concateneting with plus, the compilet can transforms the code in performatic way. With string format i don t know.
I prefer cocatenation with plus, i think that is easer to undersand.
The key to keeping it simple is to never look at it. Here is what I mean:
Joiner join = Joiner.on(" ");
public void constructMessage(StringBuilder sb, Iterable<String> words) {
join.appendTo(sb, words);
}
I'm using the Guava Joiner class to make readability a non-issue. What could be clearer than "join"? All the nasty bits regarding concatenation are nicely hidden away. By using Iterable, I can use this method with all sorts of data structures, Lists being the most obvious.
Here is an example of a call using a Guava ImmutableList (which is more efficient than a regular list, since any methods that modify the list just throw exceptions, and correctly represents the fact that constructMessage() cannot change the list of words, just consume it):
StringBuilder outputMessage = new StringBuilder();
constructMessage(outputMessage,
new ImmutableList.Builder<String>()
.add("You", verb, "to", user, "\"", text, "\"")
.build());
I will be honest and suggest that you take the first one if you want less typing, or the latter one if you are looking for a more C-style way of doing it.
I sat here for a minute or two pondering the idea of what could be a problem, but I think it comes down to how much you want to type.
Anyone else have an idea?
Assuming you are going to reuse base strings often Store your templates like
String mystring = "You $1 to $2 \"$3\""
Then just get a copy and do a replace $X with what you want.
This would work really well for a resource file too.
I think String.format looks cleaner.
However you can use StringBuilder and use append function to create the string you want
The best, performance-wise, would probably be to use a StringBuffer.

Using String.format with RPGLE

I would like to interface RPGLE with String.format which takes variable length arguments or an array, I also want to pass numbers as well as strings, so I will be using format like "hello %s, you are %d years old". Can someone give me some advide on how to prototype this in RPGLE?
UPDATE
It seems that some people were confused with the quesion. To make things clear, I want to prototype the following in RPGLE. Note that the second argument to the method is a varargs parameter, so any number of arguments can be supplied! RPGLE definitely does not support this, but it does support *nopass so this my be helpful in achieving the result I need.
String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
System.out.format(format, "FirstName", "Init.", "LastName");
or
String.format(format, "FirstName", "Init.", "LastName");
I am not interested in how I can format strings in RPGLE, I want to prototype a java method.
How about using message's to do the formatting ... they are quite powerful and the text is externalized (and CCSID aware).
You can use the QMHRTVM API to retrieve the formatted message.
When you're in RPG code, it's always faster to invoke native functionality than Java.
Is there a particular reason you want to use Java? The overhead of starting up a JVM can be killer on many applications. RPG itself can do that easily using concatenation.
/free
resultString = 'hello ' + %trim(name) + ', you are ' +
%trim(%char(years)) + ' years old';
/end-free

what is the style recommendation for the Java string concatenation operator "+"?

What is the style recommendation for the Java string concatenation operator "+"?
Edit: Specifically, should it be used or not?
Thinking in Java (Eckel) says that the overloaded + operator is implemented using StringBuilder (although not all compilers may be supporting this as per alphazero's answer) and thus multiple String objects and the associated memory use and garbage collection are avoided. Given this, I would answer my own question by saying that the + operator is probably fine, style-wise. The only caveat is that the + is the only instance of overloading in the language and that exceptionalism might count as a minor reason not to use it. In retrospect, the advantage of terseness is pretty significant in some situations and that has got to count for a lot of style.
As long as your team members are comfortable with it.
Because there is no "correct" coding style. But I agree that you should always use white-spaces between strings and operator for better readability.
Following Java's coding conventions Strings should be concatenated like:
String str = "Long text line "
+ "more long text.";
Make sure the '+' operator always begins the next line.
https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248
It is perfectly fine to use the '+' operator for String concatenation, there are different libraries that provide other structure for it, but for me it is the most simple way.
Hope this helps!
Happy coding,
Brady
Is this what you meant?
"string1" + "string"
or, if you have long lines
"a really long string....." +
"another really long string......" +
"ditto once again" +
"the last one, I promise"
If you have the time to format this right, then:
"a really long string....." +
"another really long string......" +
"ditto once again" +
"the last one, I promise"
Basically, every time you use the + operator, you should use it with at least one whitespace before and after. If you're using it when concatenating long strings, put it at the end of the line.
The overall recommendation is not to use this form (at all) if performance is of concern, and to instead use StringBuilder or StringBuffer (per your threading model). The reason is simply this: Strings in java are immutable and the '+' operator will create many intermediary String objects when processing expressions of form S1 + S2 + ... + Sn.
[Edit: Optimization of String Concatenation]

Categories