Skip to main content

Input and output in java

Input and Output (IO) are mainly used concepts in java real time applications to share objects from one place to another. Input represents data given to a program and output represents data displayed as a result of program. We are already familiar with the following two statements to display the output.

1
2
System.out.print();
System.out.println();

                Both of the statements are used to show the output on the screen. The difference between these two is that print() method keeps cursor in the same line after displaying the output and println() throws cursor to the next line after displaying the result.

Example to show the differences between print() and println() methods:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class Sysout{
      public static void main(String[] args){
             int a,b;
             a = 10;
             b = 15;
             c = a+b;
             System.out.print("result of a+b is ");
             System.out.println(c)
      }
}

          There are two output print statements in the above program. First print statement will print 'result of a+b is' and cursor will be in same line only. So, when next print statement will get executed that will print the value of c in same line only, means the complete output will print in same line only.
          When it will get executes the println() method , out put will print and cursor move to next line.

Accepting input from the keyboard:
          A Stream is required to accept data from the keyboard. Stream represents the data flow from one place to other place. It is like water-pipe where water flows. A Stream is always required if we want to move data from one place to other place.

          Basically there are two types of streams one is input stream and another one is output stream. Input streams which receive or read data coming from some other place. Output streams are those streams which send or write data from other place.
            • System.in : This represents Input Stream object, which by default represents standard input device, i.e.keyboard.
            • System.out : This represents Print Stream object, which by default represents standard output device, i.e. monitor.
            • System.err : This field also represents Print Stream object, which by default represents monitor.
          * Connect the keyboard to an input stream object. Here, we can use InputStreamReader that can read data from keyboard.

1
InputStreamReader reader = new InputStreamReader(System.in);
         
          In this statement, we are creating InputStreamReader object and connecting the keyboard (System.in) to it.

         
* Connecting InputStreamReader to BufferedReader, which is another input type of stream. We are using BufferedReader as it has got methods to read data properly, coming from the stream.
1
BufferedReader br = new BufferedReader(reader);

          Here, we are creating BufferedReader object and connecting the InputStreamReader object to it.

Note: In the above two statements will combine and write in a single statement as,
1
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

          Now, we can read the data coming from the keyboard using read() and readLine() methods available in BufferedRerader class.
Accepting single character from the Keyboard:
          Follow these steps in order to accept single character from the keyboard.
              •  Create a BufferedReader class object(br).
              •  read a single character from the keyboard using read() method.

1
char ch = br.read();
         
          The above read() method it get ASCII number of the character in Integer format. That integer value can't save into character type variable char variable.

1
char ch = (char)br.read();
         
To accept and display a character from the keyboard:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.io.*;

class Accept{
     public static void main(String[] args)throws IOException{
          /*create BufferedReader object to accept data from the keyboard*/
          BufferedReader br = new BufferedReader(new  InputStreamReader(System.in));
          //Ask for character to read it
          System.out.print("Enter a character: ");
          char ch = (char)br.read();

          //Display the character
          System.out.println("You entered: "+ch);
     }
}

Accepting a String from keyboard:
          For reading a String from keyboard there is a readLine() method in BufferedReader class.

1
String str = br.readLine();
         
          The below one is the example to read a String from the keyboard.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Import java.io.*;

public class Accept{
     public static void main(String[] args)throws IOException{
          /*Create BufferedReader object to accept data from keyboard*/
          BufferedReader br = new BufferedReader(new   InputStreamReader(System.in));

          //Ask for String and read it
          System.out.println("Enter a name: ");
          String name = br.readLine();
         
          //Display the String
          System.out.println("You entered: "+name);
     }
}

Accepting an Integer value from the keyboard:
          First we should accept the integer number from the keyboard as a String, using readLine().

1
String str = br.readLine();
         
          The number is in str in String format. That should be converted into int by using parseInt() method of Integer class.

1
int n = Integer.parseInt(str);

          The above two statements combined into a single statement.

1
int n = Integer.parseInt(br.readLine());
         
Here, is the example to read int value from the keyboard,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.io.*;

public class AcceptInt{
     public static void main(String[] args){
          /* Create BufferedReader object to read data from keyboard */
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          //Ask for integer and read it
          System.out.println("Enter an int value:");
          int num = Integer.parseInt(br.readLine());

          //display the int
          System.out.println("you entered:"+num);
     }
}

Reading input from Scanner:
          java.util.Scanner class will be helpful to read input from the keyboard or from a text file. When Scanner class loads input, that breakes into peaces called 'tokens'. These tokens can be retrieved from the Scanner object using the following methods.
            • next() - to read String
      • nextByte() - to read byte value
      • nextInt() - to read an Integer value
      • nextFloat() - to read float value
      • nextLong() - to read long value
      • nextDouble() - to read double value

          To read input from the keyboard we will use Scanner class as below

1
Scanner sc = new Scanner(System.in);

          If the user has given an integer value from the keyboard, it is stored into the Scanner object as a token. We can use the method sc.nextInt().
          Here is the program to read input from the keyboard.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.javatbrains.io;

import java.util.Scanner;

public class ScannerKeyboard {
     public static void main(String[] args) {
          System.out.println("Enter id name sal:");
          Scanner sc = new Scanner(System.in);

          int id = sc.nextInt();
          String name = sc.next();
          float sal = sc.nextFloat();

          System.out.println("Id =  " + id);
          System.out.println("Name = " + name);
          System.out.println("Salary = " + sal);
     }
}
OutPut:
     Enter id name sal:
          12 JavaTBrains 1234.23  //passing input
          Id =  12
          Name = JavaTBrains
          Salary = 1234.23

          Here is the example to read text file using Scanner class. You need to create one text file with some content and pass that file path into File. This will read each and every line in the file and will print in console also as of the file format.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package com.javatbrains.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerFile {
     public static void main(String[] args) throws FileNotFoundException {
          File file = new File("C:/<Your File Name>.txt");
          Scanner sc = new Scanner(file);

          int lineNumber = 1;
          while (sc.hasNextLine()) {
              String text = sc.nextLine();
              System.out.println(text);
              lineNumber++;
          }
     }
}

          If your passing input file is not present in the path, it will throws an exception called  FileNotFoundException.

Do you know?

Comments

Popular posts from this blog

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...