How to Take Input From User in Java

Whether you are writing console programs or solving problems in Java, one of the common needs is to take input from the user. For console programs, you need to have access to the command line. Java has a utility class named Scanner which is capable of getting typed input from user. This class can directly convert user input to basic types such as int, float and String.

The following example program demonstrates the use of java.util.Scanner for getting user input from command line. It asks for user's name and age and then prints it back. Note the automatic conversion of age to the int variable. This is what makes Scanner so useful.

import java.util.Scanner;

/** This example program demonstrates how to get user input from commandline in Java */
public class UserInput {
    public static void main(String[] args) {
        UserInput ui = new UserInput();
        ui.getInputAndPrint();
    }

    /** Takes a number of inputs from user and then prints it back */
    private void getInputAndPrint() {
        Scanner scn = new Scanner(System.in);
        System.out.print("Please enter your name: ");
        String name = scn.nextLine();
        System.out.print("Please enter your age: ");
        int age = scn.nextInt();
        System.out.println("Hello "+name+"! "+ "You are "+age+" years old.");
    }
}

Please note that the scanner methods throw InputMismatchException exception if it doesn't receive the expected input. For example, if you try to enter alphabets when you called nextInt() method.

Scanner has methods such as nextInt, nextFloat, nextByte, nextDouble, nextBigDecimal, etc. to directly read typed data from command line. To read a line of String, use nextLine method. Scanner also has a generic next method to process an input which can be defined using a regular expression. If the input doesn't match the regular expression, InputMismatchException is thrown.

The following code demonstrates the use of restricting the user input to a regular expression pattern,

private void get4DigitNumber() {
        Scanner scn = new Scanner(System.in);
        String s = "";
        Pattern p = Pattern.compile("\\d\\d\\d\\d");//get 4 digit number 
        System.out.print("Please enter a 4 digit number: ");
        try {
             s = scn.next(p);
             System.out.println("4digit number is: "+s);
         }catch(InputMismatchException ex) {
             System.out.println("Error! Doesn't match the pattern");
         }
        
}

5 Must Watch Videos for Java Programmers

One of the ways to improve your Java programming skills and knowledge is to listen to tech talks given by Java experts. I have found immense value in listening to these talks. Following selected videos on Java language cover efficient use of the Java language, tricky areas in Java core libraries, future of Java including a very interesting Q&A by father of Java, James Gosling, new features in Java 8 and upcoming features in Java 9.

Here are the 5 must watch videos for Java programmers,

1. Effective Java - Still Effective After All These Years by Joshua Bloch (70 minutes)

In this video tech talk, Joshua Bloch takes us through a select set of Java best practices taken from his highly popular book, Effective Java (second edition). This talk is intellectually simulating and even if you are an advanced Java developer, you will learn a lot.

Note that this lecture doesn't go through all the items in the Effective Java book. However he focuses on a number of key items in the areas of Generics, Enum Types, Varargs, Concurrency and Serialization. In addition, Bloch also shares an interesting set of strange behaviors in Java libraries. The slides of this talk is available here (76 slides).

 

2. James Gosling on Apple, Google, Oracle and the Future of Java

In this 80 minute Q&A session made in 2010, James Gosling (creator of Java language) talks about the future of Java and its eco-system. It is a very interesting talk and he covers a lot of topics/questions such as,

  • What is the future of Java? Where are things headed?
  • Multi-core - what is the right thing to do with Java?
  • Do generics complicate Java?
  • What is your second favorite language? (Gosling thinks for a bit to reply. He hates C with a passion and objective-C refuels his hate! His second favorite language is Scala)
  • Hardware implementations of JVM byte code
  • How well does Java scale down?
  • Have you been following guava and Google's contribution to libraries?
  • Have you looked into Dalvik?
  • Was Sun preparing to sue Google over Android?
  • Forking Java. Will it happen?
  • How did the Java mobile world get so fragmented?
  • Java deprecation of Apple?
  • Scala comparison to Java
  • What happened to Java ME?
  • His take on social networking?
  • What is the motivation behind creation of Java?

 

3. Google I/O 2011: Java Puzzlers - Scraping the Bottom of the Barrel by Joshua Bloch and Jeremy Manson

This is a Java tech talk on traps, pitfalls and corner cases in Java programming language. Joshua Bloch is the designer of Java's collections framework and he takes us on a ride to the puzzling world of Java quirks. If you are looking for more Java puzzlers, check out his book, Java Puzzlers: Traps, Pitfalls, and Corner Cases.

Java puzzlers tech talk is from Google I/O and contains the following tips,

  • Use new BigDecimal(String), not new BigDecimal(double)
  • Don’t assume that Map.Entry objects in entrySet iteration are stable. new HashSet<EntryType>(map.entrySet()) idiom fails for EnumMap, IdentityHashMap
  • Beware of catastrophic backtracking when writing regular expressions
  • Generics and arrays don’t mix–don’t ignore compiler warnings!
  • Never use raw types in new code–they lose all generic type information
  • Always use uppercase L for long literals; never use 0 to pad int literal

 

4. New Features in Java SE 8: A Developer's Guide by Simon Ritter

Java 8 brings substantial changes to the Java platform and every programmer should adopt the new features for writing concise code. In this video, Simon Ritter provides an overview of new features available in Java 8. The topics covered include,

  • Lambda expressions
  • Extension methods
  • Generalized target-type inference
  • Access to parameter names at runtime
  • Concurrency updates
  • Bulk operations in Collections
  • Removal of permanent generation

If you are an experienced Java developer and is looking for a good Java 8 book, check out Java SE8 for the Really Impatient: A Short Course on the Basics (Java Series).

 

5. Java modularity: life after Java 9 - Paul Bakker and Sander Mak

Java platform is still undergoing rapid changes and the next big release of Java is Java 9. The biggest change is the modularization of the JDK under project Jigsaw. Take a look the the Java modularity tech talk by Paul Bakker and Sander Mak. This video will give you an idea of what you need to learn in Java in 2016 and beyond.

How to Find Method Execution Time in Java

Performance is an important technical feature to focus on when you write Java programs. One of the easiest ways to measure performance is to check the time taken by each method. Java provides a utility class System which is capable of returning the number of milliseconds elapsed since 1st January 1970. Using this we can measure the value before the method call and after the method call. The difference will give us the time taken by the method.

Following Java program shows how we can measure method execution time,


/**
 * Java program to measure method execution time
 */
public class MethodExecutionTime {
    public static void main(String[] args) {
        MethodExecutionTime me = new MethodExecutionTime();
        long startTime = System.currentTimeMillis();
        float v = me.callSlowMethod();
        long endTime = System.currentTimeMillis();
        System.out.println("Seconds take for execution is:"+(endTime-startTime)/1000);
    }
    /* Simulates a time consuming method */
    private float callSlowMethod() {
        float j=0;
        for(long i=0;i<5000000000L;i++) {
            j = i*i;
        }
        return j;
    }
}

6 Must Read Books for Java Programmers

Java books enable programmers to learn the language and the best practices followed by seasoned programmers. It gives you the confidence that you understand the language and use it correctly in your programming projects.

There are a large number of Java books available in the market. In this post, I will give an overview of the top 6 Java books every advanced Java programmer must read. Not all books mentioned are strictly on Java language, but they are super relevant for Java programmers.

Please note that most of these books (except the last one) are based on Java 6 or 7. Java 8 introduces a number of advanced concepts impacting how programs are structured. Using functional programming introduced in Java 8, it is possible to write concise code. However much of the best practices given in these books are still valid in Java 8.

If you are a new Java programmer, you should first read the Java official tutorial before reading these books. This tutorial always covers the latest version of the Java language (as of writing this post, it is Java 8).  Before digging into these books, you should also take a look at object oriented programming concepts.

Here are my top 6 must read books for Java programmers. You should read these books in the order given below,

 

1. Core Java Volume I - Fundamentals by (9th Edition) by Cay S. Horstmann and Gary Cornell

Core Java Volume 1 by Cay S. Horstmann and Gary Cornell is a comprehensive book on Java language fundamentals. This book is over 1000 pages long and covers everything from basics of the Java language, classes and objects, event handling and swing library, generics, collections and multi-threading. Core Java book covers each topic in depth and uses Eclipse IDE as the development environment.

The book I have reviewed is the 9th Edition which covers Java 7 platform. A new 10th edition is under development (at the time of writing this blog post) and it would cover Java 8 platform. You should buy the latest edition available for purchase.

Core Java Volume I is a an excellent reference for the Java language and every Java programmer should have it in their library.

 

2. Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides(Gang of Four)

Design Patterns: Elements of Reusable Object-Oriented Software is a catalogue of software designs that are suitable for an object oriented programming environment. Whenever you come across a complex software design problem in Java, you should take a look at these design patterns and decide whether one of them is appropriate for your solution.

Popularly known as Gang of Four book, Design Patterns contains over 23 common software patterns that will enable programmers to create flexible and reusable software. Each pattern is carefully explained with purpose of the design pattern, the motivation, applicability of the pattern, structure, objects participating in the pattern, implementation, sample code, known uses and related patterns. Code samples are in C++ language.

However please note that if you are novice programmer, you may get confused about some of these patterns. That is ok and over years you will begin to understand importance of each pattern and you will need to keep coming back to these patterns. This is another must have book for any programmer working on object oriented languages.

 

3. Effective Java (2nd Edition) by Joshua Bloch

Effective Java by Joshua Bloch is one of the best books ever produced on the Java language. Joshua Bloch worked on the core Java platform and was responsible for design of Java Collections framework. In this book, he provides a set of rules (78 in total!) for building high quality Java programs.

Each of the coding tips in Effective Java is thoroughly explained and is backed with plenty of code samples. This book will also help you in understanding how design decisions are made in core Java libraries. If you can afford only one book, this is the book to buy!

 

4. Refactoring: Improving the Design of Existing Code by Martin Fowler, Kent Beck and John Brant

Refactoring: Improving the Design of Existing Code by Martin Fowler et al. is an influential book in the world of software design. In this seminal work, Fowler shows us how we can improve the internal structure of a program without changing its external behavior.

The book contains a catalogue of software improvement strategies and all the examples are given in Java. Each entry is well explained with the problem, solution, refactoring mechanism and Java code examples with UML. Fowler also explains the critical role played by test cases in software refactoring.

I think frequent refactoring of code is what distinguishes great programmers from good programmers.

 

5. Core Java, Volume II--Advanced Features (9th Edition) by Cay S. Horstmann and Gary Cornell

Core Java, Volume II gives a thorough coverage of advanced Java programming topics with a focus on its rich code libraries. This volume contains topics such as streams and regular expressions, XML processing, networking, database programming, advanced swing, advanced AWT, security, JavaBeans, distributed objects etc. This is an essential read for anyone who wants to venture into the world of enterprise Java.

 

6. Java SE8 for the Really Impatient: A Short Course on the Basics (Java Series) by Cay S. Horstmann

All the books mentioned above is based on Java platform 7 or below. The latest Java 8 platform introduces a number of new programming features such as lambdas for functional programming. Java SE8 for the Really Impatient is a quick look at features in Java 8.  Written by Cay S. Horstmann (author of Core Java series), this is concise book (around 200 pages) on new features of Java 8.

This book is intended for Java programmers familiar with Java 7 or 6 and assumes knowledge of the language. It provides an in-depth coverage of Java 8 features such as lambda expressions, streams API, new date/time libraries, JavaFX and more.

Date Manipulation Techniques in Java

Manipulating dates is a common requirement in Java programs. Usually you want to add or subtract a fixed number of days, months or years to a given date. In Java, this can be easily achieved using the java.util.Calendar class. Calendar class can also work with java.util.Date.

The following program shows how date manipulation can be done in Java using the Calendar class. Please note that the following examples uses the system time zone,

import java.util.Calendar;
import java.util.Date;

/**
 * This program demonstrates various date manipulation techniques in Java 
 */
public class DateManipulator {
    public static void main(String[] args) {
        DateManipulator dm = new DateManipulator();
        Date curDate = new Date();
        System.out.println("Current date is "+curDate);
        
        Date after5Days = dm.addDays(curDate,5);
        System.out.println("Date after 5 days is "+after5Days);
        
        Date before5Days = dm.addDays(curDate,-5);
        System.out.println("Date before 5 days is "+before5Days);
        
        Date after5Months = dm.addMonths(curDate,5);
        System.out.println("Date after 5 months is "+after5Months);
        
        Date after5Years = dm.addYears(curDate,5);
        System.out.println("Date after 5 years is "+after5Years);
    }
    
	// Add days to a date in Java
    public Date addDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days);
        return cal.getTime();
    }
    
	// Add months to a date in Java
    public Date addMonths(Date date, int months) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, months);
        return cal.getTime();
    }
    
	// Add years to a date in Java
    public Date addYears(Date date, int years) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.YEAR, years);
        return cal.getTime();
    }
}

 

There are a number of third party libraries which provides these data manipulation methods and much more. For advanced date processing in Java, please use Apache Commons Lang library or Joda-Time.

If you are using Java 8, use the classes in java.time for date manipulation. The following code demonstrates date manipulation in Java 8 using java.time classes,

import java.time.LocalDate;
/**
 * This program demonstrates various date manipulation techniques in Java 8 using java.time.LocalDate
 */
public class DateManipulator8 {
    // This program works only in Java8
    public static void main(String[] args) {
        DateManipulator dm = new DateManipulator();
        LocalDate curDate = LocalDate.now();
        System.out.println("Current date is "+curDate);
       
        System.out.println("Date after 5 days is "+curDate.plusDays(5));
        System.out.println("Date before 5 days is "+curDate.plusDays(5));
        System.out.println("Date after 5 months is "+curDate.plusMonths(5));
        System.out.println("Date after 5 years is "+curDate.plusYears(5));
    }
}