Reputation: 7193
So in this basic Java program,
public class HelloWorld{
public void testFunc(){
System.out.println("Class = "+this);
}
@Override
public String toString(){
return "TEST";
}
public static void main(String[] args){
int i = 5;
HelloWorld hw = new HelloWorld();
System.out.println("Hello, World");
hw.testFunc();
System.out.println(i);
}
}
the line System.out.println(i);
automatically converts the int
i
into a String
. I thought any function that requires a String type argument would automatically do this conversion in java (unlike in C). However, if I try this in Android
Toast.makeText(getApplicationContext(), i, Toast.LENGTH_SHORT).show();
where i
declared as an int
in the extended activity class, the app crashes upon launch. So how does this conversion work in Java?
Upvotes: 0
Views: 561
Reputation: 136072
System.out.println(int)
does convert int to char, it converts int to String using String.valueOf(int)
. Try explicit conversion System.println((char)i)
and you will see that it prints a different result, it will be U+0005 Unicode character
Upvotes: 2
Reputation: 4787
To understand Type Conversions in JAVA:Refer
Every expression written in the Java programming language has a type that can be deduced from the structure of the expression and the types of the literals, variables, and methods mentioned in the expression.
It is possible, however, to write an expression in a context where the type of the expression is not appropriate. In some cases, this leads to an error at compile time. This holds true with Android Toast Example.
In other cases, the context may be able to accept a type that is related to the type of the expression; as a convenience, rather than requiring the programmer to indicate a type conversion explicitly, the Java programming language performs an implicit conversion from the type of the expression to a type acceptable for its surrounding context. And this holds true for System.out.println(i) Example
Upvotes: 1
Reputation: 9741
Its not an implicit conversion. The pintln()
is overloaded by lots of datatypes:
public void println(int x) {
synchronized (this) {
print(x);
newLine();
}
}
And in your case makeText()
is not.
Upvotes: 5