- How can System.out.printIn() accept integers?
- 5 Answers 5
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Java system out println integers
- Вывод на консоль
- Ввод с консоли
- System.out.println() in Java explained with examples
- Example 1: Displaying Strings using System.out.println()
- Example 2: Displaying the variable values using println() method
- Overloading of println() method
- Difference between print() and println() methods
- Top Related Articles:
- About the Author
How can System.out.printIn() accept integers?
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.
5 Answers 5
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.
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.
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)
The static member out of the class System is a PrintStream which has a method with the signature println(int) .
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); ).
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.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Java system out println integers
Наиболее простой способ взаимодействия с пользователем представляет консоль: мы можем выводить на консоль некоторую информацию или, наоборот, считывать с консоли некоторые данные. Для взаимодействия с консолью в Java применяется класс System , а его функциональность собственно обеспечивает консольный ввод и вывод.
Вывод на консоль
Для создания потока вывода в класс System определен объект out . В этом объекте определен метод println , который позволяет вывести на консоль некоторое значение с последующим переводом курсора консоли на следующую строку. Например:
В метод println передается любое значение, как правило, строка, которое надо вывести на консоль. И в данном случае мы получим следующий вывод:
При необходимости можно и не переводить курсор на следующую строку. В этом случае можно использовать метод System.out.print() , который аналогичен println за тем исключением, что не осуществляет перевода на следующую строку.
Консольный вывод данной программы:
Но с помощью метода System.out.print также можно осуществить перевод каретки на следующую строку. Для этого надо использовать escape-последовательность \n:
System.out.print("Hello world \n");
Нередко необходимо подставлять в строку какие-нибудь данные. Например, у нас есть два числа, и мы хотим вывести их значения на экран. В этом случае мы можем, например, написать так:
public class Program < public static void main(String[] args) < int x=5; int y=6; System.out.println("x=" + x + "; y console">x=5; y=6Но в Java есть также функция для форматированного вывода, унаследованная от языка С: System.out.printf() . С ее помощью мы можем переписать предыдущий пример следующим образом:
int x=5; int y=6; System.out.printf("x=%d; y=%d \n", x, y);В данном случае символы %d обозначают спецификатор, вместо которого подставляет один из аргументов. Спецификаторов и соответствующих им аргументов может быть множество. В данном случае у нас только два аргумента, поэтому вместо первого %d подставляет значение переменной x, а вместо второго - значение переменной y. Сама буква d означает, что данный спецификатор будет использоваться для вывода целочисленных значений.
Кроме спецификатора %d мы можем использовать еще ряд спецификаторов для других типов данных:
- %x : для вывода шестнадцатеричных чисел
- %f : для вывода чисел с плавающей точкой
- %e : для вывода чисел в экспоненциальной форме, например, 1.3e+01
- %c : для вывода одиночного символа
- %s : для вывода строковых значений
При выводе чисел с плавающей точкой мы можем указать количество знаков после запятой, для этого используем спецификатор на %.2f , где .2 указывает, что после запятой будет два знака. В итоге мы получим следующий вывод:
Name: Tom Age: 30 Height: 1,70
Ввод с консоли
Для получения ввода с консоли в классе System определен объект in . Однако непосредственно через объект System.in не очень удобно работать, поэтому, как правило, используют класс Scanner , который, в свою очередь использует System.in . Например, напишем маленькую программу, которая осуществляет ввод чисел:
import java.util.Scanner; public class Program < public static void main(String[] args) < Scanner in = new Scanner(System.in); System.out.print("Input a number: "); int num = in.nextInt(); System.out.printf("Your number: %d \n", num); in.close(); >>
Так как класс Scanner находится в пакете java.util , то мы вначале его импортируем с помощью инструкции import java.util.Scanner .
Для создания самого объекта Scanner в его конструктор передается объект System.in . После этого мы можем получать вводимые значения. Например, в данном случае вначале выводим приглашение к вводу и затем получаем вводимое число в переменную num.
Чтобы получить введенное число, используется метод in.nextInt(); , который возвращает введенное с клавиатуры целочисленное значение.
Input a number: 5 Your number: 5
Класс Scanner имеет еще ряд методов, которые позволяют получить введенные пользователем значения:
- next() : считывает введенную строку до первого пробела
- nextLine() : считывает всю введенную строку
- nextInt() : считывает введенное число int
- nextDouble() : считывает введенное число double
- nextBoolean() : считывает значение boolean
- nextByte() : считывает введенное число byte
- nextFloat() : считывает введенное число float
- nextShort() : считывает введенное число short
То есть для ввода значений каждого примитивного типа в классе Scanner определен свой метод.
Например, создадим программу для ввода информации о человеке:
import java.util.Scanner; public class Program < public static void main(String[] args) < Scanner in = new Scanner(System.in); System.out.print("Input name: "); String name = in.nextLine(); System.out.print("Input age: "); int age = in.nextInt(); System.out.print("Input height: "); float height = in.nextFloat(); System.out.printf("Name: %s Age: %d Height: %.2f \n", name, age, height); in.close(); >>
Здесь последовательно вводятся данные типов String, int, float и потом все введенные данные вместе выводятся на консоль. Пример работы программы:
Input name: Tom Input age: 34 Input height: 1,7 Name: Tom Age: 34 Height: 1,70
Обратите внимание, что для ввода значения типа float (то же самое относится к типу double) применяется число "1,7", где разделителем является запятая, а не "1.7", где разделителем является точка. В данном случае все зависит от текущей языковой локализации системы. В моем случае русскоязычная локализация, соответственно вводить необходимо числа, где разделителем является запятая. То же самое касается многих других локализаций, например, немецкой, французской и т.д., где применяется запятая.
System.out.println() in Java explained with examples
In java, we use System.out.println() statement to display a message, string or data on the screen. It displays the argument that we pass to it.
Let’s understand each part of this statement:
- System: It is a final class defined in the java.lang package.
- out: It is an instance of PrintStream type and its access specifiers are public and final
- println(): It is a method of PrintStream class.
As we know that we need to create the object of a class to invoke its method. Here instead of creating the object of the PrintStream class we use System.out, it internally creates the object of PrintStream class so we can use the statement System.out.println() to invoke println() method.
Example 1: Displaying Strings using System.out.println()
Here we are displaying three Strings using System.out.println() statements.
Output: Since we are using println() method, the strings are displayed in new lines, if there is a need to display the strings in a single line, use print() method instead.
Example 2: Displaying the variable values using println() method
In the above example, we simply passed the strings that we wanted to be displayed as output. However, we can do so much more with the println() method. We can pass the variable name in this method and it can read and display the value of the passed variable as output.
The product of 10 and 20 is: 200
Overloading of println() method
We learned in Overloading in Java that we can have more than one methods with the same name but different signatures.
The println() method belongs to the PrintStream class and this class has total 10 overloaded variants of println() method. The overloaded methods are invoked based on the arguments passed by the user.
Some of the overloaded methods are as follows. If user passes int to the println() method, it invokes the overloaded method with int parameter and if the passed parameter is of String type, it invokes String variant and so on.
System.out.println() System.out.println(int) System.out.println(double) System.out.println(boolean) System.out.println(String) System.out.println(char)
Difference between print() and println() methods
System.out.print(): This method displays the result on the screen and the cursor remains at the end of the the printed line. The next printing starts in the same line where the cursor is at. This method will only work when there is at least one parameter passed to it else it will throw an error.
System.out.println(): Like print() method, this method also displays the result on the screen based on the parameter passed to it. However unlike print() method, in this method the cursor jumps to the next line after displaying the result, which means the next printing starts in the new line. This method doesn’t throw an error if no parameters are passed in it.
Let’s take an example to see this in action.
print() statements: This is just a String println() statements: This is just a String
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.