Java System.out.println syntax help for multiple variables [closed] - java

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.

Related

String intern's behaviour?

String string1="Hello Snehal";
String string2=new String("Hello Snehal");
String string3=string2.intern();
System.out.println("string1==string2 " + string1==string2); // false. OK.
System.out.println("string2==string3 " + string2==string3); // false. OK.
System.out.println("string1==string3 " + string1==string3); // false. why not TRUE?
When searched other questions for clarification, e.g. When should we use intern method of String on String constants, still not getting clue about 3rd case.
All of them are false, because what's happening are few checks whether:
"string1==string2 " + string1 refers to string2 (for the first statement)
"string2==string3 " + string2 refers to string3 (for the second one)
"string1==string3 " + string1 refers to string1 (for the last one).
You need to wrap the stringX == stringY pieces, because otherwise String concatenation will take place first (as you might already know, the statements in Java are evaluated from left to right and wrapping some of them with brackets () gives them priority).
So, having this:
System.out.println("string1==string2 " + (string1==string2));
System.out.println("string2==string3 " + (string2==string3));
System.out.println("string1==string3 " + (string1==string3));
should behave differently and then you should be able to investigate the output.
String.intern() on a string will ensure that all strings having same contents share same memory . Refer to javadoc for more detail.

Why does the expression x+x not print the same result in the two places it appears? [duplicate]

This question already has answers here:
Java: sum of two integers being printed as concatenation of the two
(10 answers)
Closed 7 years ago.
Why does the expression x+x not print the same result in the two places it appears?
String s = args[0];
System.out.println("Hello "+s);
int x = 40;
System.out.println(x);
System.out.println(x+x);
System.out.println(s+" "+x+x);
The result of this code is when I execute in cmd java EG1 kaan
Hello kaan
40
80
kaan4040
why is the last result of the print displaying kaan4040 and not kaan80?
Because of automatic conversion to String.
On this line you "start printing" an integer, so adding another integer to it will again produce integer that is then converted to String and printed out:
System.out.println(x + x); // integer + integer
However on this line you "start printing" a String, so all other values you add to it are at first converted to String and then concatenated together:
System.out.println(s + " " + x + x); // String + String + integer + integer
If you want the two integers to be added together before the concatenation is done, you need to put brackets around it to give it a higher priority:
System.out.println(s + " " + (x + x)); // String + String + integer
In your last print statement, you are doing a string concatenation instead of an arithmetic addition.
Change System.out.println(s+" "+x+x) to System.out.println(s+" "+(x+x)).
Make changes System.out.println(s+" "+x+x); to System.out.println(s+" "+(x+x)); Because it need to add the value and then string concatenation
Because java does some work with your code. When you do System.out.println(x+x);, it sees x+x as an expression with two ints and evaluates it (which is 80). When you do ""+x+x, it sees 3 String, and thus evaluates this expression as a String concatenation.
(btw, by it, I mean javac, and "sees", I mean, well "reads")
Or change print code to System.out.println(x +x+" " +s );
You are performing concatenation instead of addition
Whenever you append anything to string then it will result to string only. You have appended x+x to " " which will append 40 after name. You can use System.out.println(s+" "+(x+x)).
On the last print statement:
System.out.println(s+" "+x+x);
s is a string and is concatenated with " ", from left to right the expression formed by concatenation with s and " ", is then concatenated with x and then ( s + " " + x ) is concatenated with x, yielding kaan4040.
If the + operator is used with:
2 Strings, concatenation occurs
1 String and 1 int, concatenation occurs
2 ints, arithmetic addition
Consider the following scenario:
System.out.println(x + x + " " + "hello");
In this example 80Kaan is printed as arithmetic addition occurs between x and x, then the resulting value (80) is concatenated with the space and hello.
Read from left to right.
int x = 40;
System.out.println(x);
System.out.println(x + x);
System.out.println("" + x + x);
40
80
4040
40 is int 40
80 is int 40 + int 40 (Maths)
4040 is String 40 concat String 40 (because add "" String)
String s = args[0];
System.out.println("Hello "+s);
int x = 40;
System.out.println(x); //1st statement
System.out.println(x+x); //2nd statement
System.out.println(s+" "+x+x); //3rd statement
The first statement simply converts x into String
The second satatement added the numbers because there aren't strings, the compiler thinks of plus sign as addition of two numbers.
the third one sees that there is a string so the compiler thinks like:
print the value of s, add space(" "), add the value of x (convert x into string), add the value of x (convert x into string ).
Hence, Kaan4040.
If you want to print 80, you can do it in two ways:
int sum = x+x;
System.out.println(s+" "+sum); //more readable code
or
System.out.println(s+" "+ (x+x) ); //may confuse you
the compiler will think of x+x as integers since it doesn't find any string inside the parenthesis. I prefer the first one though. :)
why is the last result of the print displaying kaan4040 and not kaan80?
This is because this is how String behaves when used with the + symbol. and it can mean differently when used in a println method.
It means String concatenation when you use it with a String
The 5 even though being an integer will be implicitly converted to String.
E.g:
System.out.println("Hello" + 5); //Output: Hello5
It become mathematical operation:plus when used within a pair of brackets because the brackets will be operated first (add first), then convert to String.
The 1st + is concatenation, and 2nd + is add (Refer to codes below).
E.g:
System.out.println("Hello" + (5+7)); //Output: Hello12
If any one of the '+' operator operand is string, then java internally create 'StringBuilder' and append those operands to that builder. for example:
String s = "a" + 3 + "c";
it's like
String s = new StringBuilder("a").append(3).append("c").toString(); //java internally do this

Java String formatting a line with different variable types

I need to put for example 5 spaces after the first variable
2 spaces_go_here 300 batch ordered (due on day 7)
this is the format of the line and it consists of an Integer + Integer + String
I've tried the following but without success.
System.out.printf("%-5d%d%s",i + " " + testProduct.getQuantity() + " batch");
Although printf("%-5s%s",.. works if I'm trying to put spaces in between two Strings
The arguments to the Variadic function PrintStream.printf(String, Object...) are comma separated, this
System.out.printf("%-5d%d%s",i + " " + testProduct.getQuantity() + " batch");
should be something like
System.out.printf("%-5d%d%s",i, testProduct.getQuantity()," batch");
Or
System.out.printf("%-5d%d batch",i, testProduct.getQuantity());

ToString () in java Can't make a \t [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I have a to string method and I want to print an Arraylist with a tab after each one
public String toString() {
return plate + " " + year + " " + mfg + " " + style + " " + color + "\\t";
}
This is where I'm calling
System.out.println(resultList.toString());
And I get result all in one line with [ ].
Use "\t" not "\\t". The latter outputs a literal \ followed by a t.
However, this is a little bit of a code smell. You generally shouldn't be doing output formatting like this in toString(), it may be OK for your simple use case but if you make a habit out of it it can cause issues and confusion in larger applications. At minimum, consider the tab to be part of your UI, and keep it at a slightly higher level, e.g.:
for (Result r : resultList) {
System.out.println(r + "\t");
}
Even better, consider doing all formatting at a higher level rather than in toString(), e.g.:
for (Result r : resultList) {
System.out.println(r.getPlate() + " " + r.getYear() + " " +
r.getMfg() + " " + r.getStyle() + " " +
r.getColor() + "\t");
}
Your usage of toString() is certainly convenient and may make sense for your application, and it isn't inherently evil, but just be aware of what you are doing. Generally (but certainly not always), toString() is used for debugging, not formatting of composite objects.
You need to unescape the Tab. Change \\t to \t
Your version has Java escaping the \, so \\ produces the character literal \ which goes adjacent to the following t. You want to escape the t, not the \, so write \t which produces a tab character.
If you're looking to write every result on a new line, then you need to replace \t with the newline character \n.

Something crazy happens with StringBuilder.append(String str);

I've got a problem with my java-project.
following function should deliver a String for a SQL-Statement:
private static String createInsertString(Pat p)
{
StringBuilder x = new StringBuilder();
x.append("" + p.getPatnr() +","+ p.getSvnr());
java.sql.Date andat = null,gebdat;
if(p.getAndat()==null)
andat=null;
else
andat=new java.sql.Date(p.getAndat().getTimeInMillis());
if(p.getGebdat()==null)
gebdat=null;
else
gebdat=new java.sql.Date(p.getGebdat().getTimeInMillis());
x.append("," + andat==null?"null":andat);
x.append("," + p.getTele()==null?"null":p.getTele());
x.append("," + p.getVName() +","+ p.getNname());
x.append("," + p.getKk()==null?"null":p.getKk());
x.append("," + gebdat==null?"null":gebdat);
x.append("," + p.getAdrplzort()==null?"null":6);
x.append("," + p.getAdrstr()==null?"null":p.getAdrstr());
x.append("," + p.getAdrhnr()==null?"null":p.getAdrhnr());
s.append("," + p.getReplzort()==null?"null":p.getReplzort().getPlzortnr());
x.append("," + p.getRestr()==null?"null":p.getRestr());
x.append("," + p.getRehnr()==null?"null":p.getRehnr());
x.append("," + p.getLevel());
x.append("," + p.getCon()==null?"null":p.getCon());
x.append("," + (p.isPa()?"y":"n")+","+ (p.isLonly()?"y":"n") +","+ (p.isGest()?"y":"n"));
x.append("," + p.getBem()==null?"null":p.getBem());
x.append("," + (p.isKat1()?'y':'n') +","+ (p.isKat2()?'y':'n') +","+ (p.isKat3()?'y':'n'));
System.out.println(x);
return x.toString();
}
the output is
6,6465136nullnull,Jürgen,Wieslernullnull6nullnullnullnull,0null,n,n,nnull,n,n,n
but it should be like this:
6,6465136,null,null,Jürgen,Wiesler,null,null,6,null,null,null,null,0,null,n,n,n,null,n,n,n
Anyone an Idea?
I'm using jdk 1.7 on debian(64-bit)
The problem is how the operators bind. Look at this:
x.append("," + andat==null?"null":andat);
Now think of it as:
x.append(("," + andat) == null ? "null" : andat);
The LHS is never going to be null, so it's always just appending andat... and that still converts to "null" if the reference is null, because that's the default behaviour of StringBuilder.
Your code is much more complicated - and inefficient - than it needs to be. Consider rewriting it as:
private static String createInsertString(Pat p)
{
StringBuilder x = new StringBuilder();
java.sql.Date andat = p.andat == null ? null
: new java.sql.Date(p.getAndat().getTimeInMillis());
java.sql.Date gebdat = p.getGebdat() == null ? null
: new java.sql.Date(p.getGebdat().getTimeInMillis());
x.append(p.getPatnr()).append(",")
.append(p.getSvnr()).append(",")
.append(andat).append(",")
.append(p.getTele()).append(",")
// etc
return x.toString();
}
Note that I think you had a bug in the original:
x.append("," + p.getVName() +","+ p.getNname());
Where these meant to be calling two different getters?
You are misusing .append() by putting concatenations inside them! This misses the entire point of what StringBuilder is supposed to be used for.
x.append("," + andat==null?"null":andat);
should be
x.append(",").append( andat == null ? "null" : andat);
which would be the correct logic to make your ternary operator work as you intended.
.append() returns a reference to the StringBuilder so that you can chain .append() calls as much as you need.
Anytime you are putting a string concatenation inside of .append() you are just creating more intermediate String objects that eat up memory, cpu cycles and then use more resources as they now need to be garbage collected.
Also you should pre-allocate your StringBuilder with a default size that is slightly bigger than what you expect your contents to be to avoid wasted allocations and garbage creation.
See the Javadoc for the StringBuilder(int) constructor.
The problem comes from your '+'.
If you use a StringBuilder, don't use '+': it is not efficient
"," + andat==null?"null":andat results in ",null"==null?"null":andat if andat is null.
The '+' string concatenation has priority over the ternary operator
When you use the '+' with String your compiler actually translates that to a StringBuilder (or a StringBuffer before Java5)
So having
String s = a + b + c;
is actually translated to:
String s = new StringBuilder().append(a).append(b).append(c).toString().
Therefore using + within a StringBuilder is counter-productive as you create additional unecessary StringBuilder.

Categories