10

So I started learning java several days ago and got a question. For the next expression:

String foo=123;

is not allowed. However, in System.out.printIn(), we can use something like:

int x=5;
System.out.println(x);

Since implicitly assigning a integer to a string is not allowed, why the expression above works? Anyone can give a detailed explanation? I'm also wondering when can we use this kind of implicit thing and when we cannot.

0

5 Answers 5

14

The reason you can call println with an integer is because the method is overloaded. Basically there are more than one method called println and one of them accept an integer.

Take a look here: PrintStream

1
  • Why JDK 1.4.2 as reference? We are already in JDK 7 and 8 is soon to be released. Perhaps a reference to JDK 6 or 7 would be better. Commented May 24, 2012 at 22:33
12

There are so many overloaded methods of the PrintStream System.out:

println(boolean x)
println(char x)
println(int x)
println(long x)
println(float x)
println(double x)
println(char x[])
println(String x)
println(Object x)
2
  • What is (Object x)? A template of any kinds of objects?
    – OneZero
    Commented May 24, 2012 at 22:33
  • 1
    @user1229490 It will use the Object.toString() method of whatever you pass to it.
    – Jivings
    Commented May 24, 2012 at 22:34
3

The static member out of the class System is a PrintStream which has a method with the signature println(int).

3

Look at the API for PrintStream (System.out is a PrintStream). It has methods println(), println(boolean), println(char), println(char[]), println(double), println(float), println(int), println(long), println(Object) and println(String). This is called method overloading (scroll down to find the section on method overloading).

If you want to create a String from an integer literal, you can either put quotes around it (String s = "123";) or use Integer.toString (String s = Integer.toString(123);) or String.valueOf (String s = String.valueOf(123);).

1

Im assuming you mean't println not printin , java has a println function for each datatype, so you can call println on booleans, ints, strings, ect and it will select the right function. of course you cannot assign an integer to a string variable because they are different types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.