Input-Output, Array and Scanner class in Java


In this article, I will explain about the What is Array, types of Array i.e. Single dimensional arrays (1D), Multi-dimensional arrays (2D, 3D…arrays), How to provide input-output, What is InputStreamReader, What is BufferedReader, Scanner class in Java.

Array

Array is the concept used in Java for a collection of similar types of elements. Array is created by JVM dynamically. Everything i.e. variable, array, object etc. gets create on dynamic memory.

Array in java is index based. First element starts with 0.
Advantages:
  • Code optimization: We can sort or retrieve the data easily.
  • Random access: We can access any data of any index position.

Disadvantages:

Types of array

  • Single dimensional arrays (1D): It is used to represent a row or column of elements.
    Syntax: datatype arrayname[] = {value1, value2, value3};

    Java code for single dimensional array:
    public class SingleDimentionalArray {
        public static void main(String[] args) {
            String arr[] = new String[3];
            arr[0] = "ABC";
            arr[1] = "XYZ";
            arr[2] = "PQR";
            for(int i = 0 ; i<arr.length ;i++){
                System.out.println(arr[i]);
            }
        }
    }

    Output:
    ABC
    XYZ
    PQR
  • Multi-dimensional arrays (2D, 3D…arrays):
    Java code for multi-dimensional array:
    public class MultiDimensionalArray {
            public static void main(String[] args) {
                int add1[][] = new int[3][3];
                add1[0][0] = 1;
                add1[0][1] = 2;
                add1[0][2] = 3;
                add1[1][0] = 4;
                add1[1][1] = 5;
                add1[1][2] = 6;
                add1[2][0] = 7;
                add1[2][1] = 8;
                add1[2][2] = 9;

                for(int i=0; i<add1.length; i++){
                    for(int j=0; j<add1[i].length; j++){
                        System.out.print(add1[i][j]+" ");
                }
            System.out.println();
        }
        }
    }

    Output:
    1 2 3
    4 5 6
    7 8 9
    Length property is used to find out length of array.
    Syntax: arrayname.length
    Example: If we want to find length of add1 array of above example then code will be
    int length = add1.length;
    System.out.println(j);

    Output: 3

Input and output

  • In java, we have package 'java.io' which contains all classes of stream.
  • For giving input and displaying output, we need stream. Basically we can divide streams into two types i.e. input and output.
  • To give input by keyboard we use 'in' from 'system' class. System class is available in 'java.lang' package.
    1. System.in: This is used to represent InputStream object which takes input from keyboard.
    2. System.out: This is used to represent PrintStream object which displays normal messages to monitor.
    3. System.err: Represents PrintStream object used to display error messages.

To take input from keyboard we need to use 'InputStreamReader' which will read data from keyboard.

What is InputStreamReader?
  • It is a class of java.io package which extends from 'Reader' class. 'Reader' class is abstract class which extends from 'Object' class.
  • It reads bytes and converts them into characters as per the character encoding.
  • InputStreamReader can read text which is converted into ASCII value which is in integer form. So to read text in string format we need to use 'BufferedReader' class.
  • Then connect 'InputStreamReader' to 'BufferedReader' which have many methods to read data.

What is BufferedReader?
  • It is class of java.io package which extends from 'Reader' class.
  • It read the characters, arrays and lines from user.
    InputStreamReader obj = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(obj);
  • Now by using object of BufferedReader, we can use methods of BufferedReader i.e. Read() and readline().
    • Read() method
      It could not accept a character, so when using read method handle IOException.
      It can read only one character at a time.

    • Readline() method
      It is used to read complete word.
      It accept the string from keyboard.

  • Accept integer from keyboard
    If we want to accept integer value from keyboard then we need to use 'parseInt' method of integer class to convert string into integer.

    InputStreamReader obj = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(obj);
    String str = br.readline();
    Int n = Integer.parseInt(str);

  • Accept float value from keyboard
    We need to use parseFloat method of Float class to convert string into float.

    InputStreamReader obj = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(obj);
    String str = br.readline();
    float n = float.parsefloat(str);

  • Accept double value from keyboard
    We need to use parseDouble method of Double class to convert string into double.

    InputStreamReader obj = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(obj);
    String str = br.readline();
    double n = double.parseDouble(str);

  • Accept short value from keyboard
    We need to use parseShort method of Short class to convert string into short.
    InputStreamReader obj = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(obj);
    String str = br.readline();
    Short n = short.parseShort(str);

    Similar parse statements are applicable for long and Boolean data type.

Complete code to accept string from user and display it on console
public class InputStreamReaderProgram {
    public static void main(String[] args) throws IOException {
        InputStreamReader obj = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(obj);

        System.out.println("Enter name: ");
        String str = br.readLine();
        System.out.println(str);
    }
}


Scanner class

In java.util package we have scanner class which is used to receive input from keyboard or text file. Scanner class is a final class which extends from Object class.

Syntax: Scanner scan = new scanner(system.in)
'scan' is object of scanner class and now we can use methods of scanner class by using 'scan' object.
Scanner class has below methods
  • Scan.close(): It is used to close this scanner.
  • Scan.nextint(): It is used to accept integer values from user.
  • Scan.next(): It is used to accept string values from user.
  • Scan.next().charAt(0): It is used to access first letter of word.

Program to take string input from user
public class ScannerClassProgram {
    public static void main(String[] args) throws IOException {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter name: ");

        String s = scan.next();
        System.out.println("Entered name is: " +s);
    }
}
Output:
Enter name:
abc
Entered name is: abc

Program to take integer input from user
public class ScannerClassProgram {
    public static void main(String[] args) throws IOException {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter name: ");

        int i = scan.nextInt();
        System.out.println("Entered name is: " +i);
    }
}
Output:
Enter name:
23
Entered name is: 23


Related Articles

What is difference between an Interface and Abstract class in Java?

Are you looking for an article which explains the concepts of an Interface and Abstract class in simple language? Then your search ends here. Read this article, herein the detail about abstract class and an Interface is given. Also the important differences between an Interface and Abstract class is in Java is explained. This article highlights the important aspects regarding whether abstract class to be used or an Interface is to be used for given requirement of Enterprise application.

Directory Structure - XML Output

In this article, I have submitted a Java program. We will be able to get the dynamic XML file with treeview represents a folder and file structure of a given folder path using it. This Java program also show how to use a recursive function to read a directory structure and then save it to XML file. I commented properly for your better understanding how the program flow goes. The output XML file is well-formed

Java Based Voice Recognition System

This Java based Voice recognition system project gives a solution developed to communicate between different users using both voice and message. It is an application that provides a good user interface with all the facilities of a chat and voice application. This resource includes requirements, hard requirements and java code.

How to add two int values using Java programming language?

Are you looking for an article on how to add two int values using Java language? Your search will end here, here in we have given detailed information about coding for adding two int values is given. The article also explains about the various standards used in the given coding. The article also focus on use of such kind of coding in real applications.

More articles: Java

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: