Click here to Skip to main content
15,879,474 members
Articles / Programming Languages / Java / Java SE

Java Basics - Input and Output

Rate me:
Please Sign up or sign in to vote.
4.58/5 (21 votes)
5 Sep 20024 min read 609.4K   29   35
This tutorial provides any beginner with the basic skills required to start programming in Java.

Introduction

At the end of this tutorial, you should be able to create a basic Java program that requests input from a user, does something with the information and displays the results.

In this tutorial, we will be making a program that requests the user’s name, the year she/he was born and the current year. It will then display the user’s name and her/his age.

The basic structure of a Java program is as follows:

Java
class ClassName {
}

The class name must be the same as the file name, for example.
For our program, we will call it Tut1. We will call the file name Tut1.java so the structure will be:

Java
class Tut1{
}

Within a class, you will find methods. The structure of these is as follows:

Java
methodName( ){
}

You will notice that there are brackets after the method name. You can place variable names within these brackets which will receive the values passed to the method. I will talk more about this at a later stage.

The most common method that you will use is the ‘main’ method. The class that is actually executed must have this method in the class. However not every class must have a ‘main’ method. The structure of the main method is as follows:

Java
public static void main(String args[])
{
}

Note the capital ‘S’ for String. This is important or you will receive an error.

I believe that there are many different ways of outputting text. I will use one method which uses the standard java package.

Java
System.out.println("Welcome To My First Java Program ");

Again in this example, note the capital ‘S’ for System.
This code basically prints a line of text which is contained within the quotes. The line is terminated, like most lines in java, with a semi colon.

If we put all this code together, it will look like this:

Java
class Tut1 {
     public static void main(String args[])
     	{
          System.out.println("Welcome To My First Java Program");
     }	
}

This program will output the following on the screen:

Welcome To My First Java Program 

This is the most basic program you can make that provides any functionality.

Next we will extend this program to request data from the user via the keyboard.
To read input from the keyboard, we will use the standard java classes. We will need to use the IOException class which is in the java.io package.

To use this class, we must import the java.io package into this class. This is done by the following:

Java
import java.io.* ;

There are many other packages that you can import in a similar manner.

The first step is to create the InputStreamReader. The format is as follows:

Java
InputStreamReader varName = new InputStreamReader(System.in) ;

This will create the reader and assign it to the variable varName. You can change varName to whatever you want provided you follow the naming rules for a variable.
This code does the actual reading from the keyboard and converts it to Unicode characters. This is not very useful to us as we want the information in a string. This is where the BufferedReader comes in:

Java
BufferedReader varName = new BufferedReader(varName) ;

Again the rules with the variable names apply here. Also note that you cannot have the InputStreamReader and BufferedReader with the same name. I have only done this for demonstration purposes. Also the varName within the brackets in the BufferedReader must be the variable name or your InputStreamReader.
Here is an example of the actual code that we will use for our project:

Java
InputStreamReader istream = new InputStreamReader(System.in) ;

BufferedReader bufRead = new BufferedReader(istream) ;

Note the case of the characters and the semicolons.

For this example, we want to read a line in. You can do this by the following:

Java
String firstName = bufRead.readLine();

*Note the capital L.

To read from the keyboard, you must also create a try catch block:

Java
try {
}
catch (IOException err) {
}

To use a try catch block, you place the code for reading the values in, in the try section and in the catch block, you place any error messages, or what to do if there is an error.
Here is the code for our project:

Java
try {
     String firstName = bufRead.readLine();
}
catch (IOException err) {
     System.out.println("Error reading line");
}

This will try to read the input. It will then catch any IOException errors and print out a user friendly error if one occurs. In this case the error is "Error reading line".
Within the try block, we will also ask the user to enter in their first name or the user won't know what she/he is supposed to enter:

Java
try {
     System.out.println("Please Enter In Your First Name: ");
     string firstName = bufRead.readLine();
}
catch (IOException err) {
     System.out.println("Error reading line");
}

Let's now put what we have so far of our code together.

Java
import java.io.* ;
class Tut1 {
     public static void main(String args[])
     {
               InputStreamReader istream = new InputStreamReader(System.in) ;
               BufferedReader bufRead = new BufferedReader(istream) ;
               
               System.out.println("Welcome To My First Java Program");
          try {
               System.out.println("Please Enter In Your First Name: ");
               String firstName = bufRead.readLine();
          }
          catch (IOException err) {
               System.out.println("Error reading line");
          }
     }	
}

Congratulations! You have now made a fairly useless program. It asks for information and does nothing with it.

We will now expand on this base code.
We also want to ask for the user’s birth year and the current year:

Java
System.out.println("Please Enter In The Year You Were Born: ");
String bornYear = bufRead.readLine();

System.out.println("Please Enter In The Current Year: ");
String thisYear = bufRead.readLine();

From this information, we want to calculate the person’s age. But there is a problem - how do you take a string from another string. You can't, so we must change the string value into a numeric value. We will convert the string values into Integer values using the parseInt function:

Java
int bYear = Integer.parseInt(bornYear);
int tYear = Integer.parseInt(thisYear);

This code must go in a try catch block. You can then catch the conversion error:

Java
catch(NumberFormatException err) {
     System.out.println("Error Converting Number");
}

The next step is to calculate the age of the person and output all the data:

Java
int age = tYear – bYear ;
System.out.println("Hello " + firstName + ". You are " + age + " years old");

The last step is to combine all our code:

Java
import java.io.* ;

class Tut1 {
     public static void main(String args[])
     {
          InputStreamReader istream = new InputStreamReader(System.in) ;
          BufferedReader bufRead = new BufferedReader(istream) ;

          System.out.println("Welcome To My First Java Program");
	
          try {
               System.out.println("Please Enter In Your First Name: ");
               String firstName = bufRead.readLine();

               System.out.println("Please Enter In The Year You Were Born: ");
               String bornYear = bufRead.readLine();

               System.out.println("Please Enter In The Current Year: ");
               String thisYear = bufRead.readLine();

               int bYear = Integer.parseInt(bornYear);
               int tYear = Integer.parseInt(thisYear);

               int age = tYear – bYear ;
               System.out.println("Hello " + firstName + ". 
				You are " + age + " years old");
          }
          catch (IOException err) {
               System.out.println("Error reading line");
          }
          catch(NumberFormatException err) {
               System.out.println("Error Converting Number");
          }			
     }
}

Well, that’s your first basic Java program and the end of my first tutorial.
If you are interested in more tutorials by me, check out my site www.jcroucher.com.

History

  • 5th September, 2002: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
Australia Australia
www.jcroucher.com

Comments and Discussions

 
QuestionHow to Import other forms Pin
anuavi23-Apr-06 5:37
anuavi23-Apr-06 5:37 
Generalmultithreading Pin
Anonymous8-Nov-04 2:49
Anonymous8-Nov-04 2:49 
GeneralI was just thinking... Pin
Arun Reginald Zaheeruddin4-May-04 0:41
Arun Reginald Zaheeruddin4-May-04 0:41 
NewsRe: I was just thinking... Pin
JanaaMCA1-Apr-08 1:59
JanaaMCA1-Apr-08 1:59 
GeneralRe: I was just thinking... Pin
JanaaMCA1-Apr-08 2:00
JanaaMCA1-Apr-08 2:00 
GeneralIllegal Character Pin
nmq23-Feb-04 15:27
nmq23-Feb-04 15:27 
GeneralRe: Illegal Character Pin
Anonymous23-Jul-04 9:10
Anonymous23-Jul-04 9:10 
GeneralRe: Illegal Character Pin
pari_ra20-Sep-04 23:16
pari_ra20-Sep-04 23:16 
GeneralRe: Illegal Character Pin
JanaaMCA1-Apr-08 1:57
JanaaMCA1-Apr-08 1:57 
Remove The "/*age*/(tYear-bYear)" then compile ...
U may Success Sniff | :^)
Questionreadfloat() ? readdouble,long etc? Pin
Anonymous17-Oct-03 3:50
Anonymous17-Oct-03 3:50 
AnswerRe: readfloat() ? readdouble,long etc? Pin
John Croucher17-Oct-03 5:19
John Croucher17-Oct-03 5:19 
GeneralreadInt() Pin
traci25-Sep-03 17:10
traci25-Sep-03 17:10 
GeneralRe: readInt() Pin
John Croucher26-Sep-03 4:25
John Croucher26-Sep-03 4:25 
QuestionFollow Steps?? Pin
AYSHA SAEED18-Jan-03 4:58
AYSHA SAEED18-Jan-03 4:58 
AnswerRe: Follow Steps?? Pin
John Croucher18-Jan-03 22:01
John Croucher18-Jan-03 22:01 
GeneralExcellent Job Pin
Anonymous9-Sep-02 14:28
Anonymous9-Sep-02 14:28 
GeneralRe: Excellent Job Pin
Mark Kozel22-Nov-02 5:29
Mark Kozel22-Nov-02 5:29 
QuestionWhats Java? Pin
NormDroid7-Sep-02 0:06
professionalNormDroid7-Sep-02 0:06 
AnswerRe: Whats Java? Pin
Daniel Turini7-Sep-02 9:26
Daniel Turini7-Sep-02 9:26 
GeneralRe: Whats Java? Pin
John Croucher8-Sep-02 3:49
John Croucher8-Sep-02 3:49 
GeneralRe: Whats Java? Pin
NormDroid8-Sep-02 4:44
professionalNormDroid8-Sep-02 4:44 
GeneralRe: Whats Java? Pin
Jon Newman9-Sep-02 9:44
Jon Newman9-Sep-02 9:44 
GeneralRe: Whats Java? Pin
Doron Barak20-Oct-04 7:21
Doron Barak20-Oct-04 7:21 
GeneralMessage Closed Pin
4-Jan-16 11:48
kontorig4-Jan-16 11:48 
GeneralRe: Whats Java? Pin
tetonka4-Jan-16 11:51
tetonka4-Jan-16 11:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.