Writing Console Output in Java
Writing Console Output in Java refers to writing the output of a Java program to the console or any particular file.
The methods used for streaming output are defined in the PrintStream class. The methods used for writing console output are print(), println() and write().
Methods of Writing Console Output in Java-print() and println()
Both print() and println() methods are used to direct the output to the console. These methods are defined in the PrintStream class and are widely used. Both these methods are used with the help of the System.out stream.
The basic differences between print() and println() methods are as follows:
- print() method displays the string in the same line whereas println() method outputs a newline character after its execution.
- print() method is used for directing output to console only whereas println() method is used for directing output to not only console but other sources also.
Now, let us understand it in a better way with the help of some examples.
Example of print() method:
// Sample program to display numbers from 1-10 using print method class printEg < public static void main(String args[]) < int a; for (a=1 ; a> >
Example of println() method:
Let us take the same example above and use println() method in place of print() method.
// Sample program to display numbers from 1-10 using println method class printlnEg < public static void main(String args[]) < int a; for (a=1 ; a> >
Observe the difference in the output.
Both these functions work best for output of strings as well. Let us have a look at another example.
Displaying strings using print() and println() methods
It is very easy to display strings using print() and println() methods. For displaying any particular string, the string to be displayed on screen is written within the double quotation marks (i.e. “ “).
For example: System.out.println(“Hello!! How are you?”);
In addition, if you want to display the value of any particular variable used in the program, then you have to append the variable name along with the string with a plus (+) symbol.
Example for displaying any string output:
// Sample program to display sum of numbers from 1-10 class Eg1 < public static void main(String args[]) < int a, total = 0; for (a=1 ; aSystem.out.println("Sum of first 10 numbers is: " + total); > >
The write() method
Alternatively, you can make use of the write() method for directing the output of your program to the console. The easiest syntax of the write() method is:
Where b is an integer of low order eight bits.
Let us have a look at a simple example.
You wonder: “Can I pay someone to do my Java homework for me? – You are not alone, coding experts from AssignmentCore will help with your Java assignments online.
Primary Sidebar
- Java Features and Advantages
- Java OOP Concepts
- Java Structure of a Program
- Java Understanding JDK, JRE and JVM
- Java Platform Independence
- Java Data Types
- Java Variables and Constants
- Java Operators and Expressions
- Java Object and Class
- Java Accessing Class Members
- Java Constructors
- Java Garbage Collection
- Java Method Overloading
- Java Access Modifiers
- Java Super Keyword in Inheritance
- Java Multilevel Hierarchy
- Java Method Overriding
- Java Dynamic Method Dispatch
- Java Abstract Classes
- Java Final Keyword
- Using JOptionPane Class in Java for User Dialogs
- Java I/O Streams
- Java Reading Console Input
- Writing Console Output in Java
- Java Predefined Streams
- Java Hashtable
- Handling String in Java- using String class
- Java Append Method
I/O from the Command Line
A program is often run from the command line and interacts with the user in the command line environment. The Java platform supports this kind of interaction in two ways: through the Standard Streams and through the Console.
Standard Streams
Standard Streams are a feature of many operating systems. By default, they read input from the keyboard and write output to the display. They also support I/O on files and between programs, but that feature is controlled by the command line interpreter, not the program.
The Java platform supports three Standard Streams: Standard Input, accessed through System.in ; Standard Output, accessed through System.out ; and Standard Error, accessed through System.err . These objects are defined automatically and do not need to be opened. Standard Output and Standard Error are both for output; having error output separately allows the user to divert regular output to a file and still be able to read error messages. For more information, refer to the documentation for your command line interpreter.
You might expect the Standard Streams to be character streams, but, for historical reasons, they are byte streams. System.out and System.err are defined as PrintStream objects. Although it is technically a byte stream, PrintStream utilizes an internal character stream object to emulate many of the features of character streams.
By contrast, System.in is a byte stream with no character stream features. To use Standard Input as a character stream, wrap System.in in InputStreamReader .
InputStreamReader cin = new InputStreamReader(System.in);
The Console
A more advanced alternative to the Standard Streams is the Console. This is a single, predefined object of type Console that has most of the features provided by the Standard Streams, and others besides. The Console is particularly useful for secure password entry. The Console object also provides input and output streams that are true character streams, through its reader and writer methods.
Before a program can use the Console, it must attempt to retrieve the Console object by invoking System.console() . If the Console object is available, this method returns it. If System.console returns NULL , then Console operations are not permitted, either because the OS doesn’t support them or because the program was launched in a noninteractive environment.
The Console object supports secure password entry through its readPassword method. This method helps secure password entry in two ways. First, it suppresses echoing, so the password is not visible on the user’s screen. Second, readPassword returns a character array, not a String , so the password can be overwritten, removing it from memory as soon as it is no longer needed.
The Password example is a prototype program for changing a user’s password. It demonstrates several Console methods.
import java.io.Console; import java.util.Arrays; import java.io.IOException; public class Password < public static void main (String args[]) throws IOException < Console c = System.console(); if (c == null) < System.err.println("No console."); System.exit(1); >String login = c.readLine("Enter your login: "); char [] oldPassword = c.readPassword("Enter your old password: "); if (verify(login, oldPassword)) < boolean noMatch; do < char [] newPassword1 = c.readPassword("Enter your new password: "); char [] newPassword2 = c.readPassword("Enter new password again: "); noMatch = ! Arrays.equals(newPassword1, newPassword2); if (noMatch) < c.format("Passwords don't match. Try again.%n"); >else < change(login, newPassword1); c.format("Password for %s changed.%n", login); >Arrays.fill(newPassword1, ' '); Arrays.fill(newPassword2, ' '); > while (noMatch); > Arrays.fill(oldPassword, ' '); > // Dummy change method. static boolean verify(String login, char[] password) < // This method always returns // true in this example. // Modify this method to verify // password according to your rules. return true; >// Dummy change method. static void change(String login, char[] password) < // Modify this method to change // password according to your rules. >>
The Password class follows these steps:
- Attempt to retrieve the Console object. If the object is not available, abort.
- Invoke Console.readLine to prompt for and read the user’s login name.
- Invoke Console.readPassword to prompt for and read the user’s existing password.
- Invoke verify to confirm that the user is authorized to change the password. (In this example, verify is a dummy method that always returns true .)
- Repeat the following steps until the user enters the same password twice:
- Invoke Console.readPassword twice to prompt for and read a new password.
- If the user entered the same password both times, invoke change to change it. (Again, change is a dummy method.)
- Overwrite both passwords with blanks.
Java windows console output
Наиболее простой способ взаимодействия с пользователем представляет консоль: мы можем выводить на консоль некоторую информацию или, наоборот, считывать с консоли некоторые данные. Для взаимодействия с консолью в 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", где разделителем является точка. В данном случае все зависит от текущей языковой локализации системы. В моем случае русскоязычная локализация, соответственно вводить необходимо числа, где разделителем является запятая. То же самое касается многих других локализаций, например, немецкой, французской и т.д., где применяется запятая.