Purpose: In this lab, you will attempt to enter and run your first Java programs. Hopefully, this well begin to get you accustomed to Java's syntax, compiler, and interpreter.
Many people begin working in a new programming language by writing
a short program that prints the words "Hello World".
Here's one such program, written in Java.
import rebelsky.io.SimpleOutput;
/**
* A simple Java program that illustrates textual output.
*
* @author Samuel A. Rebelsky
* @version 1.0 of January 1998
*/
public class HelloWorld
{
/**
* Print the string "Hello world." to standard output.
*/
public static void main(String[] args)
{
// The object we're using to print output
SimpleOutput out;
// Set up output
out = new SimpleOutput();
// And print
out.println("Hello world");
// That's it
System.exit(0);
} // main
} // HelloWorld
Let's deconstruct this program.
import Statement
import rebelsky.io.SimpleOutput;
This tells the Java compiler that we'll be using aSimpleOutputobject which is in the libraryrebelsky.io. As you might guess, this is a library that I've created.
Introduction
/** * A simple Java program that illustrates textual output. * * @author Samuel A. Rebelsky * @version 1.0 of January 1998 */
This is a comment about the program. Java supports a variety of commenting styles. This is a javadoc comment. It begins with a slash and two stars and ends with a star and a slash. Every class should have a javadoc comment which consists of a few-sentence summary of the intent of the class, a blank line, and the author and version (as above).
Class Header
public class HelloWorld
This is the beginning of the real code. We're defining a class (more or less, a combination of functions and templates for objects) namedHelloWorldthat can be used anywhere (public).
Begin Class Definition
{
This brace begins the definition (code) for the class. You'll see a corresponding closing brace later.
Method Summary
/** * Print the string "Hello world." to standard output. */
Another javadoc comment. Each method (function) you create should have a javadoc comment.
Method Header
public static void main(String[] args)
This is the start of a method (function) definition. In particular, we're
defining a method called main. Every Java program
must have one main function that begins just like this. For now,
we won't worry about why it looks like this, it just does. When
you execute a Java program, execution begins at the start of your
main method.
Begin Method Definition
{
This open brace begins the definition of main. You'll see
another one later.
Comment
// The object we're using to print output
This is another comment. You can begin a comment with two slashes. The comment then ends at the end of the line. I'd recommend making it a point to comment add a note as to the purpose of every variable.
Variable Declaration
SimpleOutput out;
This is a variable declaration. It says thatoutrefers to an object of typeSimpleOutput.
Object Creation and Assignment
// Set up output
out = new SimpleOutput();
Initially, variables have no values. This line (and associated comment) tells Java to create a newSimpleOutputobject and associate it with the variable we've just declared. The defaultSimpleOutputobject writes to the screen. Eventually, you'll learn how to write to files.
Output
// And print
out.println("Hello world");
This says to print the string "Hello World". More precisely, this says to call theprintlnmethod of theoutobject we've just created, and to pass it the string "Hello World". Note that the ordering here is similar to that we'd use if we were talking to someone, as in "Sam, write 'Hello World' on the board."
Cleanup
// That's it
System.exit(0);
This tells the program to end, and notes that the program finished
without errors (0 means "without errors"; other numbers mean "with some
error"). This isn't strictly necessary. However, while you don't need
to include a System.exit statement, I strongly recommend
that you do.
End Method Definition
} // main
This matches the brace that opened the body of main. The
comment isn't strictly necessary, but it makes it easier to read the
proram. I'd recommend making it a point to comment every end brace to
indicate what you are ending.
End Class Definition
} // HelloWorld
This matches the brace that opened the definition of HelloWorld.
Again, the comment isn't strictly necessary, but it makes the program more
readable.
Now, you're ready to create and run your first Java program. Copy the
code from above and save the program as
HelloWorld.java. You can cut and paste to copy the program,
or you can retype it by hand (at this point, I'd recommend retyping).
Next, you should compile it, following the procedure given in the basic Java instructions. If you've mistyped something, you may see an error. Let me know, and we'll fix the error together.
Finally, you can run it, again following the procedure given in the basic Java instructions.
Once you've gotten the program to run, try changing the message that it prints and recompiling.
We've seen how to print output and a sketch of the overall structure of a simple Java program. Now, let's move on to one that also reads input.
import rebelsky.io.SimpleInput;
import rebelsky.io.SimpleOutput;
/**
* A simple Java program that illustrates textual input and output.
*
* @author Samuel A. Rebelsky
* @version 1.0 of January 1998
*/
public class Welcome
{
/**
* Prompt for the user's name and print a greeting.
*/
public static void main(String[] args)
{
// The object we're using to read input.
SimpleInput in;
// The object we're using to print output.
SimpleOutput out;
// The user's name.
String name;
// Set up input and output.
in = new SimpleInput();
out = new SimpleOutput();
// Prompt for the name.
out.print("What is your name? ");
// Get the name.
name = in.readLine();
// Print a friendly message.
out.println("Hello " + name + ", welcome to the joy of Java.");
// That's it
System.exit(0);
} // main
} // Welcome
Again, we'll look at it, line by line (or at least chunk by chunk).
import Statements
import rebelsky.io.SimpleInput; import rebelsky.io.SimpleOutput;
Here, we indicate that we're using two differt library objects, both
from the rebelsky.io library. The first does simple
input; the second does simple output.
Introductory Material
/**
* A simple Java program that illustrates textual input and output.
*
* @author Samuel A. Rebelsky
* @version 1.0 of January 1998
*/
public class Welcome
{
Again, we have a javadoc comment that describes the program and
lists author and version. Then, we have a class header, indicating
that the class name is Welcome. Finally, we have an
open brace that begins the class.
Introduce main
/**
* Prompt for the user's name and print a greeting.
*/
public static void main(String[] args)
{
For simple programs, we always need this main() method.
We begin with a javadoc comment describing the purpose of the method.
Then we have the method header, which gives the name and some related
information (for now, assume "that's just how they do it"; we'll look
at detail later). Finally, we have an open brace to begin the definition.
Variables
// The object we're using to read input.
SimpleInput in;
// The object we're using to print output.
SimpleOutput out;
// The user's name.
String name;
This time, we have three variables. One will be used for reading input, one for writing output, and one to store the user's name (since we're reading the user's name, we need to store it somewhere). Note that I was able to use the typeStringwithoutimporting it. This is because strings are built into Java.
Initialization
// Set up input and output.
in = new SimpleInput();
out = new SimpleOutput();
Prompt
// Prompt for the name.
out.print("What is your name? ");
Note thatSimpleOutputpermits you to use bothprintln(which includes a carriage return) and
Input
// Get the name.
name = in.readLine();
SimpleInputprovides a number of methods for reading values. The simplest isreadLine, which reads and returns one line of text.
Output // Print a friendly message. out.println("Hello " + name + ", welcome to the joy of Java.");
Again, we print with println. Note that we can concatenate
(join) strings by using a plus sign. If you're not sure what this code
will do, try running the program.
Cleanup
// That's it
System.exit(0);
} // main
} // Welcome
You're now ready to create and run thisJava program. Copy the
code from above and save the program as
Welcome.java. You can cut and paste to copy the program,
or you can retype it by hand (at this point, I'd recommend retyping).
Compile and run the code to make sure that it works. Check with me if you get error messages.
Next, rename the program (to anything you'd like) and extend it to ask for an use two pieces of information (e.g., name and major). Note that you will have to rename your class to correspond to the name of the file.
It is likely that you will make some small errors. This is fine. Just let me know and we'll work on fixing them.
As our last exercise, let's work on some programs that read and write numbers (integers, in this case). Our basic program will prompt for a number and print the square of that number.
import rebelsky.io.SimpleInput;
import rebelsky.io.SimpleOutput;
/**
* A simple Java program that illustrates numeric input and output.
*
* @author Samuel A. Rebelsky
* @version 1.0 of January 1998
*/
public class Square
{
/**
* Prompt for a number and print the square of the number.
*/
public static void main(String[] args)
{
// The object we're using to read input.
SimpleInput in;
// The object we're using to print output.
SimpleOutput out;
// The value entered.
int val;
// Set up input and output.
in = new SimpleInput();
out = new SimpleOutput();
// Prompt for the value.
out.print("Please enter a value and I will square it: ");
// Get the name.
val = in.readInt();
// Print a friendly message.
out.println(val + " squared is " + val*val);
// That's it
System.exit(0);
} // main
} // Welcome
This time, we'll only look at the "new" lines (the ones that differ significantly from those in previous programs).
Integer Variables
int val;
You declare integer variables by writing the keyword int
(short for integer) and the name of the variable.
Integer Output
val = in.readInt();
SimpleInputalso supports areadIntmethod that reads an integer. You may want to test what happens if we enter something other than an integer.
Output and Computation
out.println(val + " squared is " + val*val);
This line illustrates one of the oddities of Java (or comes close to illustrating one of those oddities). The meaning of some symbols is context-dependent. Usually, we think of the plus sign as being used to add two numbers. However, it can also be used to join strings. In this case, it is being used for the latter purpose. Note also that Java can automatically convert integers to strings.
Again, try copying, compiling, and running it. You may want to see what happens if you enter something other than an integer, a very large integer, or a very small integer.
Next, try writing a program that does some useful computation. You might want to convert celsius to farenheit (or vice versa), you might want to compute some interesting function; you might want to do something completely different. It's up to you.
Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
Source text last modified Tue Jan 20 08:41:17 1998.
This page generated on Tue Jan 20 08:44:32 1998 by SiteWeaver.
Contact our webmaster at rebelsky@math.grin.edu