Click here to Skip to main content
Click here to Skip to main content

Java Basics - Input and Output

By , 5 Sep 2002
Rate this:
Please Sign up or sign in to vote.

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:

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:

class Tut1{
}

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

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:

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.

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:

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:

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:

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:

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:

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:

String firstName = bufRead.readLine();

*Note the capital L.

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

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:

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:

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.

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:

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:

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:

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:

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

The last step is to combine all our code:

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

About the Author

John Croucher
Web Developer
Australia Australia
_______________________________________
Web: www.jcroucher.com
Sonork: 100.472
ICQ: 25902350
MSN: jcroucher@yahoo.com
Yahoo: jcroucher@yahoo.com
----------KnOwLeDgE iS pOwEr-----------

Comments and Discussions

 
QuestionHow to Import other forms Pinmemberanuavi23-Apr-06 5:37 
Generalmultithreading PinsussAnonymous8-Nov-04 2:49 
GeneralI was just thinking... PinmemberAaron Reginald4-May-04 0:41 
NewsRe: I was just thinking... PinmemberJanaaMCA1-Apr-08 1:59 
GeneralRe: I was just thinking... PinmemberJanaaMCA1-Apr-08 2:00 
GeneralIllegal Character Pinmembernmq23-Feb-04 15:27 
GeneralRe: Illegal Character PinsussAnonymous23-Jul-04 9:10 
GeneralRe: Illegal Character Pinmemberpari_ra20-Sep-04 23:16 
GeneralRe: Illegal Character PinmemberJanaaMCA1-Apr-08 1:57 
Remove The "/*age*/(tYear-bYear)" then compile ...
U may Success Sniff | :^)
Questionreadfloat() ? readdouble,long etc? PinsussAnonymous17-Oct-03 3:50 
AnswerRe: readfloat() ? readdouble,long etc? PinmemberJohn Croucher17-Oct-03 5:19 
GeneralreadInt() PinsussTraci25-Sep-03 17:10 
GeneralRe: readInt() PinmemberJohn Croucher26-Sep-03 4:25 
QuestionFollow Steps?? PinmemberAYSHA SAEED18-Jan-03 4:58 
AnswerRe: Follow Steps?? PinmemberJohn Croucher18-Jan-03 22:01 
GeneralExcellent Job PinsussAnonymous9-Sep-02 14:28 
GeneralRe: Excellent Job PinmemberMark Kozel22-Nov-02 5:29 
QuestionWhats Java? Pinmembernorm .net7-Sep-02 0:06 
AnswerRe: Whats Java? PinmemberDaniel Turini7-Sep-02 9:26 
GeneralRe: Whats Java? Pinmemberduke8-Sep-02 3:49 
GeneralRe: Whats Java? PinmemberNorm Almond8-Sep-02 4:44 
GeneralRe: Whats Java? PinmemberJonny Newman9-Sep-02 9:44 
GeneralRe: Whats Java? PinmemberDoron Barak20-Oct-04 7:21 
GeneralRe: Whats Java? PinmemberJanaaMCA1-Apr-08 1:54 
GeneralRe: Whats Java? Pinmembernorm .net1-Apr-08 3:20 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 6 Sep 2002
Article Copyright 2002 by John Croucher
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid