How To Take Input From User In java

In this tutorial, I am going to show you how to take input from user in java using two different ways. You can follow any method according to your convenience. To understand how we get input from user in java we first must know of the following two things :

System.out
– Java uses System.out to refer to standard output device.
System.in – Java uses System.in to refer to standard input device.

By default output device is monitor and input device is keyboard. To perform console output, we simply use println method to display a primitive value or a string to the console. Console input is not directly supported in Java, but we can use the Scanner class to create an object to read input from System.in or we can use BufferedReader from java.io package.

How To Take Input From User In Java Using Scanner Class

Taking Input Using Scanner Class : Scanner input = new Scanner( System.in )

The above line : Scanner input = new Scanner( System.in ) creates a scanner object and assigns its reference to the variable input.

Note : Don’t worry if you find it hard to understand what these things mean and what they are doing. Once we come to the topic classes and objects then you’ll understand everything.

Various methods which can be invoked to take various types of input.

     Method                Description    
   nextByte( )  reads an integer of type byte
   nextShort( )  reads an integer of type short
   nextInt( )  reads an integer of type int
   nextLong( )  reads an integer of type long
   nextFloat( )  reads a number of type float
   nextDouble( )   reads a number of double type
   next( )  reads a string that ends with a white space character
   nextLine( )  reads a line of text ( ends when Enter key is pressed )

Now lets do a simple program that takes input of type int, double and string. All other input can be taken in the same manner.


  // How to take input from user in java using Scanner class
  // How to get input from user in java using Scanner class
  // Taking input of type int, double and string
  import java.util.Scanner;
  public class TakeInput
  {
         public static void main(String[] args)
  { 
     int number;
     double decNumber;
     String text;
 
     Scanner input = new Scanner(System.in);
     System.out.print("Enter an integer number : ");
     number = input.nextInt();
     System.out.print("Enter a decimal number : ");
     decNumber = input.nextDouble();
     System.out.print("Enter a line of text : ");
     text = input.nextLine();
 
     System.out.println("Ingeger Number : " + number);
     System.out.println("Decimal Number : " + decNumber);
     System.out.println("Text : " + text);
         }
  }

Now in the very first line I have imported Scanner class which is in java.util package. ( import java.util.Scanner )

How To Take Input From User In Java Using BufferedReader Class

Now let me show you another method to take input from the user.

BufferedReader input = new
                  BufferedReader( new InputStreamReader ( System.in ))


  // How to take input from user in java using BufferedReader class
  // How to get input from user in java using BufferedReader class
  // Taking input of type int, double and string
  import java.io.*;
  public class TakeInput
  {
         public static void main(String[] args)throws IOException
  {   
     int number;
     double decNumber;
     String text;
 
     BufferedReader input=new
      BufferedReader(new InputStreamReader(System.in));
 
     System.out.print("Enter an integer number : ");
     number = Integer.parseInt(input.readLine());
     System.out.print("Enter a decimal number : ");
     decNumber = Double.parseDouble(input.readLine());
     System.out.print("Enter a line of text : ");
     text = input.readLine();
     
     System.out.println("Ingeger Number : " + number);
     System.out.println("Decimal Number : " + decNumber);
     System.out.println("Text : " + text);
         }
  }


The code import java.io.*; imports all classes from java.io package. In the above programs I have used System.out.print( ) and System.out.println( ).

System.out.println( )
– prints the text in it and moves the cursor to the next line.
System.out.print( ) – prints the text in it but do not move the cursor to the next line.

Note : Java is a case sensitive language so be careful while coding.

Java Naming Conventions

package conventions;
class JavaNamingConventions
{
  static final double PI_VALUE = 3.14;
  
  static int circleRadius = 10;

  public static void circleArea()
  {
    System.out.println("Circle Area: " + (PI_VALUE * circleRadius * circleRadius));
  }

  public static void main(String args[])
  {
    // method circleArea() is of static type so we do not need to create an object
    circleArea();
  }
}

static : If a variable or method is of static in nature then we can access it directly without creating an object.
In above java program we used variables, methods, constants, class etc. If you notice then class name is written with first letter as capital of each word. Similarly different naming conventions is followed for constants, variables and methods.
Using naming conventions makes the program more easier to read and understand for you and the other programmer as well.
Before we start with java naming conventions you must know about the camel case as we would we using this term while discussing naming conventions.

CamelCase : CamelCase is a naming convention in which a name is formed of multiple words that are joined together as single word with first letter of each of multiple word as Capital letter. CamelCase may start with a capital or especially in programming languages as lowercase letter.

For example : Love java programming can be written as : LoveJavaProgramming or loveJavaProgramming

Java Naming Conventions For Classes

Classes always start with a capital letter and are CamelCase. Class name should be a noun.
  • class Circle
  • class VehicleSpecification
  • class JavaNamingConventions

Java Naming Conventions For Variables And Methods

Variables and Methods always start with a lowercase letter and are camelCase too. Method name should be a verb.
  • double area = 10.5;
  • int circleRadius = 10;
  • circleRadius( );
  • rectanglePerimeter( );

Java Naming Conventions For Constants

final instance variables can never change and therefore are constant. Constants are always in capital letter, with any breaks between words represented by an underscore.
  • final String TOPIC = “Java Naming Conventions “;
  • final double PI_VALUE = 3.14;
  • final String MY_GIRLFRIEND_NAME = ” Anything which you would like “;

Java Naming Conventions For Packages

Package names are written in all lowercase so as to avoid conflict with the name of classes and interfaces.
  • package integer;
  • package integer.number;

Java Naming Conventions For Interfaces

Interface name is capitalized as class name.
  • interface Sorting
  • interface RectangleProperties
  • interface SortingAndSearching

    You can read naming conventions as mentioned by Oracle : Java Code Conventions

How System.out.println() Works In Java

Meaning of System.out.println()

System : System is a class which is in java.lang package


  java.lang.Object
       java.lang.System

  • The above code means that System class which is in java.lang package extends Object class which is also in java.lang package or System is a subclass of Object class.
  • The Object is the root of the class hierarchy. Every class has Object as its super class. All objects, including array implements the methods of this class.
  • The System class is not imported because it is in the java.lang package. All the classes in the java.lang package are implicitly imported in every Java program.

What Is out In System.out.println()

 out : static reference variable defined in System class of reference type PrintStream


  public final class System
  {
     public static final PrintStream out = null;
     //...
  }

println() : non static method defined in PrintStream class.


  public class PrintStream
  {
    public void println()
    {
      //...
    }
  }

PrintStream class belongs to java.io package.


  java.lang.Object
     java.io.OutputStream
         java.io.FilterOutputStream
              java.io.PrintStream

  • The above code shows that PrintStream extends FilterOutputStream. FilterOutputStream extends OutputStream which extends Object Class.

What System.out.println() Does ?

System.out.println() terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator and is not necessarily a single newline character (‘\n’). There are various other methods which are defined in PrintStream class. Some of them are shown here :

  public class PrintStream{
  public void println()
  {
    // Terminates the current line by writing line separator string
  }

  public void println(long x)
  {
      //Prints a long and then terminate the line.
      // This method behaves as though it invokes print(long) and then println()
  }

  public void println(Object x)
  {
     // Prints an Object and then terminate the line.
     // It calls at first String.valueOf(x) to get the printed object's string value 
     // Then behaves as though it invokes print(String) and then println()
  }
  // And other methods
}

 How ‘out’ in System.out.println() instantiated

Now the question arises how, when and where ‘out’ reference variable is instantiated. 
 
  • JVM ( Java Virtual Machine ) invokes initializeSystemClass() method to complete the initialization of the System class.
  • initializeSystemClass()  method is in System class.
  • initializeSystemClass() then calls setOut0() that actually sets the ‘out’ reference variable.
  • The function setOut0() is a native function. We can find its implementation in System.c

  public final class System
  {
    public static final PrintStream out=null;
    private static void initializeSystemClass()
    {
      setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
    }
  }

System class also contains setOut() method which can be used to reassign the “standard” output stream i.e the ‘out’ reference variable.


  public final class System
  {
    public static final PrintStream out=null;
    public static void setOut(PrintStream out) 
    {
      setOut0(out);
    }
    private static void initializeSystemClass()
    {
      setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
    }
  }

 How we invoke println() method with the help of System.out

  • We know that println() is a method in PrintStream class and ‘out’ reference variable of type PrintStream in System class.
  • System is in java.lang package and PrintStream in java.io package.
  • java.lang is implicitly imported by every java program. But not java.io package.
So the question arises how System class invokes the println() method in PrintStream class. The answer is pretty simple : System.java imports java.io package.

  package java.lang;
  import java.io.*;
  // imports other packages as well
  public final class System 
  {
    public static final PrintStream out=null;
    //...
  }

 How System.out.println() Actually Works ?

So on the basis of the above we come to the following conclusion :


  package java.lang;
  import java.io.*;
  // imports other packages as well
  public final class System
  {
    public static final PrintStream out=null;
    public static void setOut(PrintStream out) 
    {
      setOut0(out);
    }
    private static void initializeSystemClass()
    {
      setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
    }
  }


  package java.io;
  public class PrintStream{
  public void println()
  {
    // Terminates the current line by writing line separator string
  }

  public void (long x)
  {
      //Prints a long and then terminate the line.
      // This method behaves as though it invokes print(long) and then println()
  }

  public void println(Object x)
  {
     // Prints an Object and then terminate the line.
     // It calls at first String.valueOf(x) to get the printed object's string value 
     // Then behaves as though it invokes print(String) and then println()
  }
  // And other methods
}

System.out.println() Example


// A java program that demonstrates the use of System.out.println()
 class SystemDemo
 {
    public static void main(String args[])
    {
      int number=10;
      System.out.print("Hello "); // prints 'Hello' but does not go to next line
      System.out.println("Reader"); // prints 'Reader' and goes to next line
      System.out.println("How are you : "); 
      System.out.println("Number assigned value : " + number); 
    } 
 }

Output :

Hello Reader
How are you :
Number assigned value : 10

Best Way To Learn Java Programming

This site is for those who are completely new to java programming or you can say java programming for dummies. I am not an expert in java programming but yes I can try to explain the very basics of java. Please do not depend on this site to completely learn java programming as here I am going to teach you core java which is the basic of java and there are various levels of java which is not included here. Java is very vast and the more you explore on internet from books the more you will learn.  I am trying to give you the best way to learn java. Hope this article be a little helpful to you in your journey to learn java.

HOW TO LEARN JAVA PROGRAMMING

 
Learning java programming language is not a daunting task ( very difficult to do or deal with ). In fact no programming language is difficult to learn all you need is a little bit of focus and determination. Its all about psychology. If you think that a thing is difficult to achieve then it is for you but in reality it is very easy. My purpose of telling you all these things is to encourage you and boost confidence in you. If you have heard from somewhere that learning programming language is difficult then forget it. Its said by those who are not hard working and determinant. Just have confidence in yourself that you can learn and believe me you won’t even realize that you have learned. One more thing which I would like to tell you is this if you find a topic or a program difficult please do not simply ask from someone to explain. First try to understand by reading it twice or thrice or even more. Try different books and sites and even then you do not understand then you can seek help from others. Same thing is with the programs. If you are trying to program something and you are not able to do it then don’t instantly jump to the solutions from books or on sites. Try it as many times as you can i.e give it a fair try and then if you fail to do so then you can see the solution for help. By doing this yes you will take a little more time to learn but hey there is no hurry right. There is a very famous dialogue ” There is no hurry to greatness “. I don’t remember where I have heard it but it’s true. Don’t be in a hurry to learn. The more time you spend learning programming and writing programs or codes the more you will learn.

And Hey one more thing when you have learned programming, try teaching it to others. The reason is very simple you go through all you learned and the question posed by the people whom you teach may be significant i.e they may ask something which you don’t know or which you have not thought of when you were reading that topic. This would certainly help in enhancing your programming skills and you may even understand the topic better than before.

You don’t need to be an expert to teach. I am also not an expert. You just need to be a guy who loves learning and sharing. Enjoy Learning..

Best Books To Learn Java Programming

‘Head First Java’ by Kathy Sierra

This Book Is very interactive and focus on concepts. You can see lots of pictures here and the book is written in a comic way. Its a great book to learn java as well as have fun while learning java programming.

‘Introduction To Java Programming’ by Y. Daniel Ling

This book is written in the conventional way and covers everything which you need to learn in java. The topics are divided quite well chapter wise and on completion of the book you will definitely be confident in java programming language.

From Quora User : The following two books are recommend by Will Goring

‘Thinking in Java’ by Bruce Eckel

This is a great introduction/tutorial on the language that should take you from not knowing Java to being a proficient developer in it.

‘Effective Java’ by Josh Bloch

Once you’ve learned the language, read this as a great guide to best practices and understanding why they are best practices.

For general Java programming, that’s it; those two books should cover everything you need to know. Beyond that, look into either general programming books or more domain specific titles as your interest takes you.

Beyond Curiosity