One of my assignments has this code:
System.out.println("" + x + y + count);
that outputs the value of x, y and count individually without any spaces. I would like to know more about it online. However, I can't seem to find the right keywords to search it up online. Can someone please explain to me the logic behind this or perhaps point to me a name or keyword for such a situation?
I have always known the " " as a tool to print out a string so I'm confused by this.
Thanks in advance.
If we apply standard Java precedence rules, the statement:
System.out.println("" + x + y + count);
is equivalent to
System.out.println((("" + x) + y) + count);
Then we look at the meaning of +
If the static types of both a and b are numeric types (either primitive numeric or their boxed types) then a + b is numeric addition.
Otherwise, a + b is string concatenation. The two arguments are converted to strings and the strings are concatenated.
Based on this we can say that all of the + operators in the example will be treated as string concatenations.
If you want spaces between x, y and count you need to add some string literals; e.g.
System.out.println("" + x + " " + y + " " + count);
or, more simply:
System.out.println(x + " " + y + " " + count);
If you wanted x, y and count to be added (assuming that they are numeric), then you could write this:
System.out.println("" + (x + y + count));
or, more simply:
System.out.println(x + y + count);
The latter is using a different overload of println.
I have always known the "" as a tool to print out a string so I'm confused by this.
Ummm ... it is actually an empty string literal. The usage "" + x is simply an idiom for converting x to a String. The empty string literal has other uses too. The main one is to represent a String with zero characters.
Or you can use String format like this:
System.out.printf("%d%d%d", x, y, count);
The "" is an empty String. In Java when you concatenate a String with other primitives that can be cast to String the result is a String. That means that the code
System.out.println("" + something);
is a different way to write
System.out.println(String.valueOf(something));
However in your scenario the "" + x + y + count means that the elements are converted to String and then concatenated - this means that if x==1, y==2, count==3 the result would be 123. If you wanted to just cast the result to String you would have to indicate that the computation should happen before casting to String for example by using brackets
System.out.println("" + (x+y+count));
The output of this would be 6.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm new to java and trying to print the values of multiple variables.But the quotes inside the System.out.println confusing me.Can anybody explain the following syntax?
Why "+ b1.cc" is outside the quotes ?
My code:
System.out.println("Bike data " + b1.brand + " " + b1.color + " " + b1.cc);
Let's say you have:
String one = "1";
String two = "2";
String three = "3";
System.out.println("one: " + stringOne + " and two: " + stringTwo + " and also a three: " + stringThree);
Will print
one: 1 and two: 2 and also a three: 3
It is called concatenation. I.e. you "create a new String".
Look at this answer too for mor information.
In you actual code " " will just add a white space between the values of your variables.
I think you need to learn about string concatenation in Java. You can call a method to concatenate (join together) two strings, but you can also use the + operator.
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
You can also use the concat() method with string literals, as in:
"My name is ".concat("Rumplestiltskin");
Strings are more commonly concatenated with the + operator, as in
"Hello," + " world" + "!"
which results in
"Hello, world!"
The + operator is widely used in print statements. For example:
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
which prints
Dot saw I was Tod
Such a concatenation can be a mixture of any objects. For each object that is not a String, its toString() method is called to convert it to a String.
You have presented an example of String concatenation, equally valid would be building a String reference separately like,
String str = "Bike data " + b1.brand + " " + b1.color + " " + b1.cc;
System.out.println(str);
Java also supports formatted printing. Assuming those fields are all String(s) you could use
System.out.printf("Bike data %s %s %s", b1.brand, b1.color, b1.cc);
or String.format()
String str = String.format("Bike data %s %s %s", b1.brand, b1.color, b1.cc);
The quotes create a String object for the JVM to use. The variables:
b1.brand
b1.color
b1.cc
will return a String object already so the quotes aren't necessary. If, for instance, b1.color was in quotes, it would print specifically b1.color and not what the variable holds.
So essentially I have an object of vectors and in a specific instance called 'comments' I have comments that actually have String in them and some that are just white space or have a single space. I tried to separate these from each other and I am running into trouble. Everything is outputted for some strange reason. Any thoughts? (display is a JTextArea)
for (int x = 0; x<dogParkProgramMain.infoVector.size(); x++)
{
if(dogParkProgramMain.infoVector.elementAt(x).getComment() == "//s" || dogParkProgramMain.infoVector.elementAt(x).getComment() == null){
System.out.println("Blank");
}
else{
display.append("Name: " + dogParkProgramMain.infoVector.elementAt(x).getFName() + " " + dogParkProgramMain.infoVector.elementAt(x).getLName() + newLine);
display.append("Comment: " + dogParkProgramMain.infoVector.elementAt(x).getComment() + newLine);
display.append("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + newLine);
}
} // end first for loop
Not sure what you mean by \\s it's since you're not using regular expressions there. The following check should work:
String comment = dogParkProgramMain.infoVector.elementAt(x).getComment();
if (comment == null || comment.trim().isEmpty()) {
System.out.println("Blank");
}
trim() function will remove all leading and trailing spaces from the string meaning that if your string only contains spaces it would end up empty after trim. This code will check for any number of spaces as opposed to only one space mentioned in your question.
I have array of strings, String[] data and it's 10 elements has value P and so data[10]={java.lang.String#587}"P"
When I do inspect on data[10], i get data[10].value[0] = 'P' 80, am not sure what that 80 is referring too.
In my program, am trying to check
if (data[10] == "P") {
lookUp = data[7] + "." + data[8]+ "." + "Old";
} else if (data[10] == "C") {
lookUpCode = data[7] + "." + data[8] + "." + "Old";
} else {
lookUpCode = data[7] + "." + data[8];
}
So challenge I have here is that even if data[10]="P" even then i hit last else and not first if loop, any suggestions?
You need to compare strings by value, not by reference:
if ("P".equals(data[10]))
In Java to compare strings you have to use the equals(String s) method. In your code:
data[10].equals("P")
This because strings are objects, and "==" compares the objects references.
I just found some sql query build like this in my project:
return (new StringBuilder("select id1, " + " id2 " + " from " + " table")).toString();
Does this StringBuilder achieve its aim, i.e reducing memory usage?
I doubt that, because in the constructor the '+' (String concat operator) is used. Will that take the same amount of memory as using String like the code below? s I understood, it differs when using StringBuilder.append().
return "select id1, " + " id2 " + " from " + " table";
Are both statements equal in memory usage or not? Please clarify.
Edit:
BTW, it is not my code. Found it in an old project. Also, the query is not so small as the one in my example. :)
The aim of using StringBuilder, i.e reducing memory. Is it achieved?
No, not at all. That code is not using StringBuilder correctly. (I think you've misquoted it, though; surely there aren't quotes around id2 and table?)
Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.
Will that take memory equal to using String like below?
No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder in the code is unnecessary and optimizes it out, if it can.)
If the author of that code wants to use StringBuilder (there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2 and table):
StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();
Note that I've listed some_appropriate_size in the StringBuilder constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append] each time it runs out of room).
You may have heard that string concatenation will use a StringBuilder under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder:
return "prefix " + variable1 + " middle " + variable2 + " end";
It roughly translates to:
StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();
So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.
But that's only for a single expression. Multiple StringBuilders are used for this:
String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;
That ends up becoming something like this:
String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;
...which is pretty ugly.
It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.
When you already have all the "pieces" you wish to append, there is no point in using StringBuilder at all. Using StringBuilder and string concatenation in the same call as per your sample code is even worse.
This would be better:
return "select id1, " + " id2 " + " from " + " table";
In this case, the string concatenation is actually happening at compile-time anyway, so it's equivalent to the even-simpler:
return "select id1, id2 from table";
Using new StringBuilder().append("select id1, ").append(" id2 ")....toString() will actually hinder performance in this case, because it forces the concatenation to be performed at execution time, instead of at compile time. Oops.
If the real code is building a SQL query by including values in the query, then that's another separate issue, which is that you should be using parameterized queries, specifying the values in the parameters rather than in the SQL.
I have an article on String / StringBuffer which I wrote a while ago - before StringBuilder came along. The principles apply to StringBuilder in the same way though.
[[ There are some good answers here but I find that they still are lacking a bit of information. ]]
return (new StringBuilder("select id1, " + " id2 " + " from " + " table"))
.toString();
So as you point out, the example you give is a simplistic but let's analyze it anyway. What happens here is the compiler actually does the + work here because "select id1, " + " id2 " + " from " + " table" are all constants. So this turns into:
return new StringBuilder("select id1, id2 from table").toString();
In this case, obviously, there is no point in using StringBuilder. You might as well do:
// the compiler combines these constant strings
return "select id1, " + " id2 " + " from " + " table";
However, even if you were appending any fields or other non-constants then the compiler would use an internal StringBuilder -- there's no need for you to define one:
// an internal StringBuilder is used here
return "select id1, " + fieldName + " from " + tableName;
Under the covers, this turns into code that is approximately equivalent to:
StringBuilder sb = new StringBuilder("select id1, ");
sb.append(fieldName).append(" from ").append(tableName);
return sb.toString();
Really the only time you need to use StringBuilder directly is when you have conditional code. For example, code that looks like the following is desperate for a StringBuilder:
// 1 StringBuilder used in this line
String query = "select id1, " + fieldName + " from " + tableName;
if (where != null) {
// another StringBuilder used here
query += ' ' + where;
}
The + in the first line uses one StringBuilder instance. Then the += uses another StringBuilder instance. It is more efficient to do:
// choose a good starting size to lower chances of reallocation
StringBuilder sb = new StringBuilder(64);
sb.append("select id1, ").append(fieldName).append(" from ").append(tableName);
// conditional code
if (where != null) {
sb.append(' ').append(where);
}
return sb.toString();
Another time that I use a StringBuilder is when I'm building a string from a number of method calls. Then I can create methods that take a StringBuilder argument:
private void addWhere(StringBuilder sb) {
if (where != null) {
sb.append(' ').append(where);
}
}
When you are using a StringBuilder, you should watch for any usage of + at the same time:
sb.append("select " + fieldName);
That + will cause another internal StringBuilder to be created. This should of course be:
sb.append("select ").append(fieldName);
Lastly, as #T.J.rowder points out, you should always make a guess at the size of the StringBuilder. This will save on the number of char[] objects created when growing the size of the internal buffer.
You are correct in guessing that the aim of using string builder is not achieved, at least not to its full extent.
However, when the compiler sees the expression "select id1, " + " id2 " + " from " + " table" it emits code which actually creates a StringBuilder behind the scenes and appends to it, so the end result is not that bad afterall.
But of course anyone looking at that code is bound to think that it is kind of retarded.
In the code you have posted there would be no advantages, as you are misusing the StringBuilder. You build the same String in both cases. Using StringBuilder you can avoid the + operation on Strings using the append method.
You should use it this way:
return new StringBuilder("select id1, ").append(" id2 ").append(" from ").append(" table").toString();
In Java, the String type is an inmutable sequence of characters, so when you add two Strings the VM creates a new String value with both operands concatenated.
StringBuilder provides a mutable sequence of characters, which you can use to concat different values or variables without creating new String objects, and so it can sometimes be more efficient than working with strings
This provides some useful features, as changing the content of a char sequence passed as parameter inside another method, which you can't do with Strings.
private void addWhereClause(StringBuilder sql, String column, String value) {
//WARNING: only as an example, never append directly a value to a SQL String, or you'll be exposed to SQL Injection
sql.append(" where ").append(column).append(" = ").append(value);
}
More info at http://docs.oracle.com/javase/tutorial/java/data/buffers.html
You could also use MessageFormat too