Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Can someone explain why Java concatenates strings and integers in the following examples?
public class main {
public static void main(String[] args) {
System.out.println("test" + 5);
System.out.println(5 + "5");
}
}
And what is the difference from Python's implementation of the + operator.
In Python, this raises a TypeError:
"5" + 5
What makes you think + should behave in the same way for two different languages? In Java, when you have something like
System.out.println(5 + "5");
55
string concatenation is performed, as you can see. This is outlined by the Java language's specification (see JLS §15.18.1). By contrast, Python doesn't coerce the types like Java (hence the TypeError); in order for string concatenation to occur, both operands of + must be strings, which is why you need
>>> "5" + str(5)
'55'
This is outlined in Python's specification (see Python Language Reference §5.6). There is no universal rule that states + must behave in a specific manner across languages: if I wanted to, I could create a language in which + performs subtraction!
As #Wooble points out, Perl's + behaves in yet another way:
$ perl -e 'print 5 + "5"; print "\n"'
10
Simply put, in Java, the + operator is overloaded for Strings. Python obviously doesn't implement that override so you'll need to find out what the concatenation operator is for Python to make the latter case work.
You get a TypeError because "5" is of type string and 5 is of type int. Like someone said, its just how it was designed. Im guessing in part to prevent confusion. Do you want "5" + 5 to equal 10 or 55?
If you want 55 you can do this by converting the int to a string
'5' + str(5)
If you check docs
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.
So ,it's java specific
Basically in Python you have to do the following:
"5" + str(5)
Because, although operator + is overridden for pairs of strings in both Python and Java, in Python for a string and an integer there is no appropriate override, and integers are not implicitly casted to strings when needed. Hence you need to explicitly cast 5 to a string, in order to have strings on both sides ot the concatenation.
The compiler java converts 5 + "5" into a StringBuilder internally and uses .append(int) to "add" the integer to the String.
In java, if there is a string type in a + b, then + will do concatenation where as in python the + of two different types has not been defined by default. Thus, as suggested, in python, one needs to do str(Int) before concatenation.
Related
This question already has answers here:
String valueOf vs concatenation with empty string
(10 answers)
Is conversion to String using ("" + <int value>) bad practice?
(8 answers)
Closed 3 years ago.
I was just wondering, i've always used the first version but ran into instance of doing the second variation in our old codebase.
Is there any dangers related to second variation ?
Are they interchangeable ?
It feels strange to me to convert into String by doing just variable + "";
Thanks!
In Java the strings have the special operator + which is concatenation. If the operands of the concatenation are not strings their respective .toString method is called, and if it is the value is null the "null" string is concatenated. Most modern JITs or even compilers might decide to use a stringbuilder. So the only danger here is that you create extra objects which get discarded. Additionally, this code might be less readible or more confusing.
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 5 years ago.
Improve this question
class Pattern4 {
public static void main(String args[]) {
for(int i=1;i<=5;i++) {
for(int j=1;j<=5;j++) {
System.out.print((char)(i+64));
}
System.out.println();
}
}
}
In this program if I don't provide () to char keyword, I am getting a compile time error. So my question is why is it necessary to write (char) and then (i+64) and why not char(i+64)?
(i+64)
is an int, because it's the sum of an int and an int.
If you want to print it as an int, you don't have to do anything.
System.out.println(i + 64);
If you want to print it as a char, you have to convert it to one:
System.out.println((char)(i + 64));
That's simply the syntax Java uses for casting.
Because char(65) is method call syntax. You're not calling a method named char with 65 as a parameter, you're casting 65 to a char.
Remember that, unlike spoken languages, programming languages are carefully designed to avoid ambiguity of any kind. This is both for "user friendliness" (i.e. to make the code clearer) and from the practical necessity of writing compilers and creating correct software. Anything that would introduce ambiguity could also "break" compilers and cause subtle, difficult-to-track bugs.
(char)int is syntax to type cast. This syntax does not take any input and its as per language design (Its not a function but language syntax). This tells compiler to accept the type as char and not as int. Java is strongly typed language and it ensures type safety.
We need to tell compiler explicitly when we need to change type otherwise compiler will complain.
Hope this clarifies why this does not take input in parenthesis like:
abc(input);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Ok, so I have the following code. I know that making a new line in a char makes no sense but what I want to know is why it prints from 10-19 instead of 1-10 as normal. Can someone give me an answer?
public class Demo {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println('\n' + i);
}
}
}
The ASCII value for \n is 10. The + operator is being interpreted as an "add" operand between two numeric values, not as an "append" operation between two Strings. This is because you are using single quotes, not double quotes. Single quotes indicate a char.
A char can be treated as an actual number in Java. You can check all ASCII values on this chart.
JLS 4.10.1 - Subtyping Among Primitive Types pretty clearly displays that char is a subtype of int, if you're in to looking at the in-depth specifications. There's also JLS 5.1 - Kinds of Conversions for details on conversions.
Per Tom Blodget's comment below, it appears that Java actually uses UTF-16 for String literals, as detailed in the String documentation and JLS 3. This is likely an important fact to keep in mind, although I have used ASCII values successfully for many years and never encountered a bug or a problem of any kind.
String concatenation only applies when one of two operands of + is a String typed value. In this case, you have one char and one int, no String values. As such, you have integer addition. Java applies primitive widening conversion to convert the char value '\n' to an int value, 10. You can then see why it counts from 10 to 19.
As mentioned Java interprets '\n' as ASCII character, which correspond to a integer value of 10 (hex value 0x0A).
What you can do:
System.out.println('\n' + Integer.toString(i));
System.out.println("" + '\n' + i);
System.out.printf("\n %i", i));
System.out.printf("\n" + i));
But all ideas are connected to the same idea.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What is the purpose of having methods converting one value into another value of a different type. For example a method that converts a string of digits into an int and another method converting an int into a string of digits? What exactly would be the advantages to doing one over the other? Is it there is no advantage and the methods for conversion exist only to provide compatible values for the arguments of the constructors of different classes?
Simply, it's because those different types exhibit different behaviors:
String str = "42";
System.out.println(str + 1);
System.out.println(Integer.parseInt(str) + 1);
421
43
You need to have methods like Integer.parseInt() if you want to perform normal addition as opposed to string concatenation, for example.
A tangible example of this can come up when you read a number as input from a user; more often than not you will want to treat this number as a number (double, int, etc.) as opposed to a string.
The different forms serve different purposes beyond providing compatible values for methods and constructors.
For the int type, mathematical operations are most easily performed on this type (and similar primitive types). User input is usually given in the form of a String, so to perform a mathematical operation on user input, one must convert it into an int (or a double, long, float, byte, or short as appropriate).
For converting to a String: This is how numerical output is displayed. We may code System.out.println(myInt);, but behind the scenes, Java is converting the number to a String for display purposes.
Since you used the "Java" tag, I'll answer you regarding java.
It is because, Java was written this way . There are languages that do not need types (lisp for example) and you can read a string (from Std. In) and raise it to a power (for example) if it is a number. But Java needs types. The compiler wants to know it ahead.
One useful advantage of being able to convert numbers to string is that you are able to use very large numbers, storing them as strings, instead of integers. However you cannot work with strings when you use the regular operators (+,-,*,/).
Another advantage: when you have a TextField and you read user input, it is given as a string. So you need to get a number out of it to work with it.
This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 9 years ago.
I want to parse an operator say "+" from the string "+" which i entered as command-line argument at run-time and then add two integers say 'a' and 'b'.
So how can i perform the above task?
What nobody so far is telling you is that to recognize arithmetic expressions in general you need to use, or write, a parser. Have a look for the Shunting-yard algorithm, recursive descent expression parsing, etc.
If you are using Java 1.7, you can use a switch to test for each possible operator and then do the corresponding operation:
switch(operator){
case("+"): result = a + b; break;
case("-"): result = a - b; break;
}
For older versions of Java can be done using if statements.
if (string.equals("+")) {
System.out.println("The result is " + (a + b));
}