Programming in Java Tutorial, by ARTHUR CRUMMER
/* This is file SAMPLECODE.html, an intro using some Java programming
examples. This may be useful for someone already
experienced in some other high level language.
BUGFIXES: 05-16-99: Fixed capitalization problem with "internalValue"
in class "FirstClass".
It's designed as a sequence of little test programs. You are invited to cut
Java code from this file and run/modify/experiment with these sample programs.
All programs will be in the form of Applications:
Java programs come in two types:
* Applications (which are stand-alone programs that can run on any system
apart from the existence of WWWW browsers) and
* Applets (which can have a browser presentation in some graphic form and
be executed by clicking on something in a web browsers)
Instructions for compiling and running these applications on a UNIX system:
1) make sure there is a javac compiler available on your system (you may have
to add to your .cshrc file a line similar to this: setenv PATH
"/usr/local/java/bin:$PATH", where the string in quotes would be provided
by your system administrator, according to where the javac compiler was
instalkled))
2) type in the program
3) compile it by typing javac
4) re-edit until the compiler gives no error messages
5) run the program by typing: java
Arthur Crummer, 12/15/97
/*
We start with a simple "HelloWorld" program.
Type it in and save it as "HelloWorld.java"
( The file name must correspond to the name of the class containing
"main" as you'll see below.)
*/
public class HelloWorld {
public static void main (String[] args){
System.out.println("Hello world!");
}
}
/*
The first two lines are required for EVERY JAVA program.
Thus, we have created a form for all future programs.
FIRST LINE SAYS:
We are defining something whose name will be "HelloWorld"
It is a class.
It is a public class (meaning it can be used by anyone).
SECOND LINE:
We are defining something whose name will be "main"
It is a method (because of the parenthesis).
Its return value type is void ( meaning it has no return value).
It accepts an argument whose type is an array of Strings.
(This will be explained later; arrays are indicated by the bracket pair [].)
The name of the array is "args".
The method "main" is associated with the class rather than objects
(because of the keyword "static").
Every standalone Java executable program requires a method named main()
This is where the java interpreter begins running the program.
A method is sometimes called a function.
THIRD LINE:
This is the entire actual program: System.out.println("Hello world!");
It causes the string in quotes to be printed to the output device,
which is by default the monitor.
The semicolon is required; the compiler sees it as terminator of the
instruction. One or more instructions can be grouped together in a "block"
and treated as ONE instruction by surrounding that sequence of instructions
by a pair of braces: "{" and "}"
The 4th LINE:
This is the closure of the block in which main() is declared
The 5th LINE:
This is the closure of the block in which HelloWorld is declared
========================================================
*/
//===================================================
// This is located in file ForLoop.java:
public class ForLoop {
public static void main (String[] args){
for (int i =0; i<10; i++)
System.out.println(i + " squared is:" + i*i);
}
}
/*
.... The ForLoop example illustrates the use of a "for loop"
*/
//===================================================
// This is located in file WhileLoop.java:
public class WhileLoop {
public static void main (String[] args){
int i =0;
while ( i<10)
{
System.out.println(i + " squared is:" + i*i);
i++;
}
}
}
//
//===================================================
//===================================================
// The following is in file "ForLoop2.java" compiled separately
// with Forloop2.class residing in directory accessible to main()
public class ForLoop2 {
void runMe(int HowManyTimes){
for (int i = 0; i < HowManyTimes; i++)
System.out.println(i + " squared is:" + i*i);
}
}
/*
Objects of this class do not contain any data.
All they can do is respond to a request to "runMe"
a certain mumber of times. There is no "main()".
The next class is executable (has a main() method),
in which a ForLoop2 object is constructed and asked to "runMe"
*/
public class TestForLoop2 {
public static void main (String[] args){
if (args.length == 0) System.out.println("No Argument found");
else {
ForLoop2 Loop = new ForLoop2 () ;
Loop.runMe( Integer.parseInt ( args[0]) ) ;
System.out.println("Thats all folks!");
}
}
}
//
//===================================================
/* These files are located in files FirstClass.java and TestFirstClass.java
Typically classes are defined in separate files.
One file, containing a main(...) method, is the application program
which uses objects of the types defined in the class definitions.
In this example, we have one file containing the class definition:
of FirstClass and another which uses objects of that class, namely
TestFirstClass below. */
// the following is found in file "FirstClass" compiled separately
public class FirstClass {
private int internalValue ; //declaration is not known to outside
public FirstClass (){ //"public" ->declaration is known to outside
internalValue = 0; // this is the so-called "default constructor"
// namely the one that takes no arguments
// notice that constructor methods have NO RETURN TYPE
}
public FirstClass (int value){
internalValue = value;
}
public //declaration is known to outside
void displayInternalValue(){
System.out.println("Internal value is: " + internalValue);
}
} // end of class definition
/*
By defining this class, we have created a form or template or shape.
This is now a new TYPE which can be used for declaring actual variables
which "fit the mold". Such variables are called objects.
Each instantiation of this class, "FirstClass", contains an internal
state variable and a function which can display the value of its
internal state variable.
*/
public class TestFirstClass {
public static void main (String[] args){
System.out.println("This program instantiates 3 object and gives you info...") ;
FirstClass MyObj1 = new FirstClass() ;
// This declares an Object and assigns to it
// the address of new storage allocated to store
// a FirstClass object, whose
// internal value is NOT yet initialized, however
FirstClass MyObj2 = new FirstClass(100) ;
// MyObj2 now hold the address of a FirstClass object
// whose internal value is initialized to 100.
System.out.println("An objects uninitialized internal value...") ;
// Next we'll request the object to display its internal value,
// (which is uninitalized)
MyObj1.displayInternalValue();
System.out.println("Another objects initialized internal value...") ;
MyObj2.displayInternalValue();
// Notice how the notation works:
// we use the ObjectName, then ".",
// then the name of the function (service) requested
// Some prefer to say that we sent a message to the object
// and the object responded.
FirstClass TempObj ;// a new variable, uninitialized.
// as usual, this variable is capable of holding
// the address of an object of type FirstClass;
// however, this one does not yet hold such an address
TempObj = MyObj2 ; // now it does !
System.out.println("Temporary obj will display its internal value.") ;
TempObj.displayInternalValue();
System.out.println(".......Th..Th..Thats all folks");
}
}
//===================================================
//
//===================================================
// Heres a simple program to give you an idea of Unicode numeric
// representation of characters
public class CharTest {
public static void main (String[] args){
for (int i =32; i<127; i++)
System.out.println(i + " char:" + (char)i );
System.out.println("backSp char:" + (int)'\b' );
System.out.println(" tab char:" + (int)'\t' );
System.out.println("newln char:" + (int)'\n' );
System.out.println(" CR char:" + (int)'\r' );
System.out.println(" \" char:" + (int)'\"' );
System.out.println(" \' char:" + (int)'\'' );
System.out.println("null char:" + (int)'\0' );
}
}
//===================================================
//
//===================================================
//===================================================
/***********
An array groups together information of the "same Type" in a sequential data
structure. Arrays in Java are not primitive data, they are reference variable
just like all other objects.
You declare a variable to be an array of some type by specifying
the type followed by the bracket pair [] like shown below:
********/
class ArrayExample {
public static void main (String[] args){
int [] arrayOfIntegers ;
// arrayOfIntegers is now a variable capable of
// holding a reference to such an array of integers,
// but it currently holds no such address because its not initialized.
arrayOfIntegers = new int[100] ;
// now arrayOfIntegers hold a specific address where begins storage for
// 100 integers, but no values have been stored there yet.
// arrayOfIntegers is a reference variable.
// the actual storage spaces are numbered 0 to 99,
// and they are named arrayOfIntegers[0],arrayOfIntegers[1],......
// up to arrayOfIntegers[99]
int ProductSoFar = 1 ; // this is just to make a fun example
int i = 0 ; // an index to count from 0 to 19
while ( i < 20) {
arrayOfIntegers[i] = ProductSoFar ;
i++ ;
ProductSoFar *= i ;
}
for (i = 0 ; i< 20; i++)
System.out.println("The array value at " + i +" is:" + arrayOfIntegers[i] );
}
}
/******************
If you run the above array example, you will discover something horrifying!
This illustrates problems (when you actually run it) that can be encountered
due to the finiteness of storage locations. Im sure you already know that
care must be exercised in choosing the type variables in which we store
info. The above program's output highlights the situation.
*******************/
//
//===================================================
//===================================================
// This is located in file count.java:
/*
In this demonstration, we use the "import" keyword to make available to our
program some classes that we need.
You can group together a collection of files and call it a PACKAGE. Other
classes may be defined so as to allow use of the classes declared in the files
of a given package. This is done by use of the keyword "import", as
illustrated below with the package java.io
The classes grouped together can be ones you the programmer has
defined or they can be ones provided by vendors.
In this example we are importing classes needed to do input and output (I/O).
In general, I/O activities are not under the complete control of the program
because data may be coming in from an external source such as a file or
keyboard; therefore the format of the incoming data stream may sometimes not
conform to what is expected.
Being more error prone, I/O activities normally should have a way of handling
exceptions graciously. We will not address these issues at the moment, but
will postpone them until after we are strong on the basics.
*/
import java.io.*
// import all classes defined in this "java.io" package
class Count {
public static void main(String[] args)
throws java.io.IOException
{
int count = 0;
while (System.in.read() != -1)
count++;
System.out.println("Input has " + count + " chars.");
}
}
//===================================================
//
//===================================================
// This is located in file count2.java:
public class Count2 {
public static void main(String[] args)
throws java.io.IOException
{
System.out.println("Enter some chars,Ill count them (on UNIX, End with ^D):");
int count = 0;
System.out.println("Ill echo chars back to the screen (counting chars):");
System.out.println("and Ill show you what the chars unicode values are.");
System.out.println("Type, ending with (on UNIX, End with ^D):");
count = 0;
int valueTyped = 0;
while (valueTyped != -1)
{ valueTyped = System.in.read() ;
count++;
System.out.println(": you entered:" + valueTyped + " = "
+ (char)valueTyped ) ;
}
System.out.println("Input has " + count + " chars.");
}
//===================================================
This document is
copyright 1995-97 by Arthur Crummer.