How does System.out.printIn () accept integers?

So, I started learning java a few days ago and got a question. For the following 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 implicit assignment of an integer to a string is not allowed, why does the expression above work? Can anyone give a detailed explanation? I also wonder when we can use this implicit thing, and when we cannot.

+8
source share
5 answers

There are so many overloaded PrintStream System.out methods:

 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) 
+10
source

The reason you can call println with an integer is because the method is overloaded. Basically, there are several methods called println, and one of them takes an integer.

Take a look here: PrintStream

+15
source

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

+3
source

Check out the API on PrintStream ( System.out - 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 put quotation marks there ( String s = "123"; ) or use Integer.toString ( String s = Integer.toString(123); ) or String.valueOf ( String s = String.valueOf(123); ).

+3
source

Im assuming you don't have println not printin, java has a println function for each data type, so you can call println on booleans, ints, strings, ect and choose the right function. Of course, you cannot assign an integer to a string variable, because these are different types.

+1
source

All Articles