I'm learning to code on Codecademy and keep coming up with a concatenating issue.
For example, when I wrote:
System.out.println(lemonadeStand + cookieShop);
I got back the error:
Store.java:32: error: bad operand types for binary operator '+'
System.out.println(lemonadeStand + cookieShop);
But when I wrote:
System.out.println(lemonadeStand);
System.out.println(cookieShop);
The code worked. Can someone tell me why doesn't the first one work? (And thanks)
---edit---
Thanks for all the help everyone! This was my first time posting a question here and I'm amazed at how kind and helpful the community is!
please before concatening two variable you must verify they are
same type
or try System.out.println(first + " " + second);
Because the single variables alone cause a call to their .toString() method. When you add the operand between two non-string variables, it's not sure exactly what you mean. You will sometimes see this ...
System.out.println(lemonadeStand + cookieShop + "");
That + "" in there confirms this is all boiling down to a string (if that's any way to explain it technically to you.)
What would also work is ...
System.out.println(lemonadeStand.toString() + cookieShop);
or...
System.out.println(String.valueOf(lemonadeStand) + cookieShop);
It depends what those variables actually are. But if they aren't strings ... it's ambiguous as to what you are telling it to do ... add them together maybe?
Placing a single + "" somewhere in there is a common way to force it all to be interpreted as a string concatenation.
Hope that explains it in non technical terms.
Too broad...
But, a method accepting a String needs a String as a parameter.
The println is overloaded in PrintStream class so it accepts all of the primitive types, String and the Object type.
bad operand types for binary operator '+'
The point is in "binary" operator. The plus "+" is normally considered as arithmentic (a binary) operator between two numbers. And secondly, the "+" COULD BE CONSIDERED as String concatenation operator.
[Side note, Java doesn't allow overloading of operators]
Binary, therefore arithmetic, logical and bitwise operators expects the defined types for them selfs.
In the case of "+" operator, it is most ofen considered as addition operator.
Expressions with numeric types are being automatically promoted to larger primitive types if needed.
So again, the call to a + b is only possible with numeric or String operands. If one of a or b is not numeric or String operand, the error will be thrown.
It's the implementations of println/print methods of PrintStream class that tries to get a default result of toString method for given parameter.
The System.out.print(...) is kind of combination of objects and calls. The System is static object representing a System in runtime environment, the out represents standard output stream for a current thread and print is a method called on that out PrintStream. There are several different streams, just for example an err which is standard error output stream.
The standard print or println method is overloaded to accept a Object type where those methods tries to call the toString method on given Object as a parameter. But it cannot evaluate the given expression with + operand, if the whole expression is not evaluated to Number or String.
Cutting to the chase,
the "+" at first works as arithmetic operator, if next operator is a String it converts the rest of expression to String.
When "+" has two object or incompatibile operators, it cannot determine how the operands should be handled. How it could add list to an array or simply true + true? For the second (true + true) the logical && must be used.
In your case, when you tried to + between the different types, the println gave you an error, because the "+" is only able to concatenate Strings or sum both of the opearands which inherits from Number class.
Answer from #Moyebang is kind of good, because the expression given as parameter in printnl method evaluates to String type. The answer from #Lotsa isn't very good because the operands are evaluated from left to right, so if the operands before + are incompatible, the program would throw an error (the second part of an answer is ok).
Such expressions at first are evaluated in their compile time.
They are evaluaded on standard basics from left to right:
System.out.println(1 + 1 + ""); //this gives 2
System.out.println("" + 1 + 1); //this gives 11
System.out.println(1 + "" + new ArrayList<>()); //this gives 1[]
System.out.println(new ArrayList<>() + "" + 1); //this gives []1
System.out.println(new ArrayList<>() + 1 + ""); //and this gives an error
So, from left the mathematical equasions are being evaluated, when it's a String the others are being addeded to that String. The last shows an error because at first the ArrayList object is being added to "1", where there's no common approach on how to add the List to an object.
Related
to test myself in Java, I wrote up a program where I needed to display the contents of double[] measurements, containing: {8.0, 7.7474, 7.4949, 7.7474, 8.0, 7.7474, 7.4949, 7.7474, 8.0}. A simple enhanced for loop and a println() seems to work fine, but
for(double measure: measurements)
{
System.out.println(measure + '"');
}
prints out 42, 41.7474, 41.4949, etc. Exactly 34 more than the value of measure. Changing the code to
for(double measure: measurements)
{
System.out.println(measure + '\"');
}
prints out 18,17.7474, 17.4949, etc. Exactly 10 more than the correct value. It only prints correctly when the println statement is split into two lines:
System.out.print(measure);
System.out.println("\"");
Why is it that the first two examples add to the value of measure? I'm fairly new to programming, but it seems to me that they would all have worked because Java uses both apostrophes and quotes to declare a string. Why does splitting it into two statements work correctly while connotating the two add to the value of measure? Thanks!
It's because you are printing the result of the expression measure + '"'. At the moment, you're performing an addition between a double and a char. If you instead use " instead of ' it will work.
Like this: System.out.println(measure + "\"");
Another option is to first convert measure to a string. That's rarely the best alternative, but the whole gist here is that you need to know the types of the operands and what the resulting type of the operation will be. Addition between a double and a char will result in a double. Addition between a double (or int or char among others) and a String will result in a String.
Apostrophes are used to declare char not String remember that. You can't have more than one char within single quotes.
Just do measure + "\""
This question already has answers here:
Getting strange output when printing result of a string comparison
(3 answers)
Closed 2 years ago.
Let's see the following simplest code snippet in Java.
final public class Parsing
{
public static void main(String[] args)
{
int p=10;
int q=10;
System.out.println(p==q);
}
}
The above code in Java is fine and displays true as both p and q of the same type (int) contain the same value (10). Now, I want to concatenate the argument of println() so that it contains a new line escape sequence \n and the result is displayed in a new line as below.
System.out.println("\n"+p==q);
Which is not allowed at all because the expression p==q evaluates a boolean value and a boolean type in Java (not Boolean, a wrapper type) can never be converted to any other types available in Java. Therefore, the above mentioned statement is invalid and it issues a compile-time error. What is the way to get around such situations in Java?
and surprisingly, the following statements are perfectly valid in Java.
System.out.println("\n"+true);
System.out.println("\n"+false);
and displays true and false respectively. How? Why is the same thing in the statement System.out.println("\n"+p==q); not allowed?
You have to add parentheses () around p==q (the way you write it, it will be interpreted as ("\n"+p) == q, and String cannot be compared to a boolean). This operator precedence is desired for expressions like
if(a+b == c+d)
etc. So,
System.out.println("\n"+(p==q));
Should work just fine.
System.out.println("\n"+p==q);
compiler treat it as
System.out.println(("\n"+p)==q);
Use
System.out.println("\n"+(p==q));
Which is not allowed at all because the expression p==q evaluates a boolean value and a boolean type in Java (not Boolean, a wrapper type) can never be converted to any other types available in Java.
This is completely wrong. Concatenating anything to a String is implemented by the compiler via String.valueOf(), which is also overloaded to accept booleans.
The reason for the compiler error is simply that + has a higher operator precedence than ==, so your code is equivalent to
System.out.println(("\n"+p)==q);
and the error occurs because you have a String and an int being compared with ==
On the other hand, this works just as intended:
System.out.println("\n"+(p==q));
The order of precedence of operators means that your expression gets evaluated as
("\n" + p) == q
It is nonsensical to compare a string to an int so compilation fails, try:
"\n" + (p == q)
Ah. The statement is wrong.
System.out.println("\n"+(p==q));
~Dheeraj
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]
Java can't do operator overloading, but + works okay for String and Integer and some other classes. How is this possible?
update:
Why does this work?
Integer i = 4;
Integer p = 5;
System.out.println(i*p); // prints 20
+ is not an example of operator overloading. + is built into the language as a concatentation operator and an arithmetic-addition operator.
What this means is that a person writing a program with Java cannot overload operators, but as far as the grammar of the Java language is concerned, + is defined as a concatenation and an addition operator.
EDIT
It works for other classes such as Integer and Double because of autoboxing.
If you take a look at the bytecode of a Java program that performs string concatenation, you'll see that it creates StringBuilder and uses the append() method. The Java compiler sees the + operator and realizes that the operands are strings and not primitive types (like int).
If you look at the bytecode of a program that does integer addition, you will see that it uses the iadd instruction to perform integer addition. This is because the compiler realizes that the operands to the + operation are integers.
As far as doing something like Integer i = 4, the bytecode will show that you're actually doing Integer i = Integer.valueOf(4). This is called autoboxing. Later on, when you do something like i + p, where both i and p are of type Integer, the generated bytecode will show that you're doing i.intValue() + p.intValue(), where the return types of both methods are int (the actual bytecode instruction again, is iadd).
This is why + works Integer even though they are not actual primitive types.
It works for primitive wrappers like Integer because of autoboxing.
It works for String because that's a special case for concatenating strings:
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.
+ is a built-in operation. It's an exception, not a rule.
Java doesn't allow custom operator overloading, but the compiler can still be told by the compiler developer that String1 + String2 == String1String2, and to substitute the proper concatenation method call for the + operator.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings.
String s = "string 1" + "string 2";
What actually is execute is
(new StringBuilder()).append("string 1").append("string 2").toString()
As #yan said, this is the exception, not the rule. Strings have a special status in Java. There's a whole subsection of the Java Language Specification devoted to + in its role as the string concatenation operator: §15.18.1.
Regarding your update, that's another special case. Java is sometimes, depending on the case, smart enough to convert things that are not Strings into Strings when Strings are needed. One of these special cases is the one you described, where primitives are showing up in a place that needs a String. The primitives are first converted to their reference types — Integer, Double, &c. — and then into Strings via the toString() method.
Another special case is when one String and one non-String are being combined with the string concatenation operator +, as described in JLS §5.4 — String Conversion.
For completeness: + in its more common "adding numbers together" role is described in the other part of of §15.18, §15.18.2 — Additive Operators (+ and -) for Numeric Types.
I asked about this array a little while ago, and I can't see what the problem is. Too tired. What have I done wrong? Basically, I am taking a string array and trying to check to see if it contains numbers or an x (ISBN number validation). I want to take the number from a given input (bookNum), check the input, and feed any valid input into a new array (book). At the line
'bookNum.charAt[j]==book[i]'
I get the 'not a statement error'. What gives?
String[] book = new String [ISBN_NUM];
bookNum.replaceAll("-","");
if (bookNum.length()!=ISBN_NUM)
throw new ISBNException ("ISBN "+ bookNum + " must be 10 characters");
for (int i=0;i<bookNum.length();i++)
{
if (Character.isDigit(bookNum.charAt(i)))
bookNum.CharAt[j]==book[i];
j++;
if (book[9].isNotDigit()||
book[9]!="x" ||
book[9]!="X")
throw new ISBNException ("ISBN " + bookNum + " must contain all digits" +
"or 'X' in the last position");
== is java is used for equivalence comparison. If you want to assign it, use a single =.
The first issue here is that charAt is a function, and thus needs parenthesis even though you are accessing with an index like an array.
The other issue is that the line is a boolean expression, which just by itself does not mean anything. A lot of people are suggestion that you mean to make an assignment to that character, but just changing to a single equals causes other problems. The left side of an equals sign needs to be a variable, and the result of a function is not a variable.
Strings are immutable, so you can not simply change one of the characters in the string. Earlier in your code, you have a call to replaceAll(), that returns a new string with the alterations. As written, this altered string is being lost.
There are few odd problems here. For starters, did you mean for book to be an array of Strings, as opposed to just one string? You're trying (assuming CharAt was written properly and the assignment was proper) to assign a character to a string.
Second, instead of copying character by character, why not check the whole string, and copy the whole thing at the end if it is a proper ISBN? Depending on what you do with Exceptions (if you continue regardless), you could add a boolean as a flag that gets set if there is an error. At the end, if there is no error, then make book = to booknumber.replace(etc...)
bookNum.CharAt[j]==book[i];
Should be
bookNum.CharAt[j]=book[i];
You are using an equality boolean operator, not an assignment one.
Looks like you're using .charAt(i) wrong! Assuming that "bookNum" is a String, you should use:
bookNum.charAt(i)==book[i];
Instead. Note that this is a boolean expression, and not "=".
The line bookNum.CharAt[j]==book[i]; isn't a statement. It's a comparison. Perhaps you want bookNum.CharAt[j]=book[i]; (single = instead of ==).
Edit: That's not going to fix things, though, since you can't assign to bookNum.CharAt[j].