Important alert: (current site time 9/1/2014 3:12:17 AM EDT)
 

article

Java Basics - Input and Output

Email
Submitted on: 9/6/2002 9:13:01 AM
By: John Croucher  
Level: Beginner
User Rating: By 11 Users
Compatibility: Java (JDK 1.1), Java (JDK 1.2)
Views: 11310
author picture
 
     This tutorial provides any beginner with the basic skills required to start programming in Java.

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				

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 they were born and the current year. It will then display the user’s name and their 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 make the file name called 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 in method in the class. However not every class must have a ‘main’ method. The structure of the main method is as followed:

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 ended, 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 on 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 what ever you want providing you follow the naming rules for a variable.
This code does the actual reading from the keyboard and converts them 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 can not 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.

The 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 wont know what they are 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”);
}



Lets 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.
Check out my site for more tutorials and code.


Other 2 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

9/8/2002 1:55:21 PMVille Berndtsson

To get input from user, check out:
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=3123&lngWId= 2
Maybe
easier for beginners! With that class you can get input from user by simply calling the different sub-programs in that class e.g. To get a string from user just refer to ::: String stringName = Read.STR();


(If this comment was disrespectful, please report it.)

 
8/21/2003 10:06:32 PMlost_forwords

Well done :)
Coming from VB trying to learn Java. Your tutorial was very helpfull.
*****
(If this comment was disrespectful, please report it.)

 
1/17/2005 1:25:49 AM

thanks man! i just need this in our exercise! happy programming!!!
(If this comment was disrespectful, please report it.)

 
8/13/2006 1:45:10 AMdubs

NOw hoe about zipping the tutorial for those to download so they can read without going throug hthe trouble of copying, open a doc program, paste, save, close, then come back. Make it easy for people
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.