Here's part of "The Secret Guide to Computers," copyright by Russ Walter, 29th edition. For newer info, read the 33rd edition at www.SecretFun.com.

Java

Java resembles JavaScript (and JScript) but includes extra commands, so you can create a greater variety of programs. Those extra commands make Java a complete programming language (like QBASIC and Visual BASIC).

Java is fairly easy to learn: it’s just slightly harder than QBASIC, Visual BASIC, JavaScript, and JScript. Java’s a simplified version of C (which is much harder and explained in the next chapter).

 

Fundamentals

There are several versions of Java. Microsoft’s version is called Visual J++. I’ll explain how to use Visual J++ 6.0, which you can buy individually or as part of Visual Studio 6. (Other versions of Java are similar.)

Copy Java to the hard disk

Here’s how to copy Visual J++ 6.0 (professional edition) to the hard disk.

Make sure your computer contains Windows 98 (not 95) and Internet Explorer 5 (not 4).

Turn on the computer without any floppy or CD-ROM disks in the drives, so the computer runs Windows 98 and the computer’s bottom left corner says Start. Put the Visual J++ disk into the CD-ROM drive. The computer will say “Visual J++”. Press ENTER. Click “I accept the agreement”. Press ENTER.

Type the 10-digit CD key number (printed on the orange sticker at the back of the CD-ROM disk’s square case). Press TAB. Type your name. Press TAB. Type the name of your company (if any). Press ENTER three times.

You’ll see a product ID. Copy it onto a sheet of paper. Press ENTER three times.

The computer will reboot itself.

The computer will say “Install MSDN”. Put the MSDN Library’s Disc 1 into the CD-ROM drive. Click “Next”. Press ENTER.

You’ll see an MSDN product ID. Copy it onto a sheet of paper. Press ENTER three times. The computer will copy the MSDN Library to the hard disk. Press ENTER three times.

Remove the check mark from the “Register Now” box (by clicking it). Press ENTER.

Start Java

To start using Visual J++ (version 6.0), do this:

Remove any CD-ROM disk. Click “Start” then “Programs” then “Microsoft Visual J++ 6.0” then “Microsoft Visual J++ 6.0” again.

Start a new program

Click “Applications” then “Console Applications”.

Double-click in the Name box. Invent a name for your program (such as “joe”); type the name and press ENTER.

Press ENTER again. Double-click “Class1.java” (which is at the screen’s right side).

You see a big white box. In that box is a prototype Java program. That program does nothing useful, but you can edit it to do whatever you wish!


In that program, the important lines look like this:

public class Class1

{

    public static void main (String[] args)

    {

    }

}

The other lines are green. The computer ignores the green lines — and you should too! — since they’re just comments.

If you find the green lines too distracting, erase them as follows:

Point in the left margin, to the left of the first green line, so the mouse pointer is an arrow (not a vertical line). Click (to highlight that line), or drag down (to highlight that line and several lines below it). Press the DELETE key to delete the highlighted lines.

Let’s program the computer to say:

make your nose

touch your toes

To do that, edit the prototype program by inserting these extra lines:

public class Class1

{

    public static void main (String[] args)

    {

        System.out.println("make your nose"); x

        System.out.println("touch your toes");

        while (true);                         x

    }

}

Here’s how to insert those extra lines:

Click to the right of the second “{“, press ENTER, type the first extra line, press ENTER, type the second extra line, press ENTER, and type the third extra line. Notice you must type a semicolon at the end of each line.

The computer indents the lines automatically. (If you ever want the computer to indent differently, do this before typing a line’s first word or symbol: press the TAB key to indent; press the BACKSPACE key to unindent.)

Here’s what those extra lines mean:

The first extra line makes the computer system send out a printed line saying “make your nose” and makes the computer press ENTER afterwards. (If you omit the “ln”, the computer will not press ENTER afterwards.)

The second extra line makes the computer print “touch your toes” and press ENTER afterwards.

The third extra line makes the computer pause awhile, so you can read what the computer printed. That line is needed in Visual J++ 6.0 but not in most other Java versions.

When you finish inserting those extra lines, congratulations! You’ve written a Java program!

Run the program

To run the program, press the F5 key. The computer will say —

make your nose

touch your toes

then pause for you to admire what it said. When you finish admiring the computer’s work, do this: while holding down the Ctrl key, tap the C key.


Switch programs

While the program you wrote is on the screen, you can edit it. After editing it, run it (by pressing the F5 key).

When you finish playing with that program, here’s how to create a totally different program instead:

If the program is still on the screen, look at the X at the screen’s top right corner; instead of clicking that X, click the X that’s immediately below it, so the program lines you typed disappear.

Click the New Project button (which is near the screen’s top left corner, below the word “File”). Then do the “Start a new program” routine that I explained in this page’s left column.

Here’s how to view an old program you created earlier:

Go into Visual J++. If a different program is on the screen, get it off the screen (by clicking the X that’s below the top right corner’s X). Click the Open Project button (which is near the screen’s top left corner and shows an opening manila folder). You’ll see a list of Java program folders, double-click the program folder you want to use. You’ll see a green icon and a blue icon for your program; double-click the blue icon. At the screen’s right edge, you’ll see the blue icon again; double-click it again. Then double-click “Class1.java”.

Erase files

If you type and run a program named “joe”, the computer generates a folder called “joe”, which is in the Visual Studio Projects folder, which is in the My Documents folder.

The “joe” folder contains four files, called “joe.vjp”, “joe.sln”, “joe.suo”, and “joe.exe”.

To erase them all, do this:

Get the icon for the “joe” folder onto the screen (by clicking the Open Project button). Click that “joe” folder icon. Press the DELETE key (to move the folder to the Recycle Bin) or press SHIFT with DELETE (to erase the folder). Press ENTER.

 

 

 

 

 

 

 

 

 

 

 

 

 

Math

The computer can do math. For example, this line makes the computer do 4+2:

        System.out.println(4+2);

If you put that line into your program and run the program, the computer will print this answer on your screen:

6

If you bought 750 apples and buy 12 more, how many apples do you have altogether? This line prints the answer:

        System.out.println(750+12+" apples");

That line makes the computer do 750+12 (which is 762) and add the word “ apples” (which includes a blank space), so the computer will print:

762 apples

This line makes the computer put the answer into a complete sentence:

        System.out.println("You have "+(750+12)+" apples!");

The computer will print “You have ” and add 762 and add
“ apples!”, so altogether the computer will print:

You have 762 apples!

Like most other languages (such as BASIC and JavaScript), Java lets you use the symbols +, -, *, /, parentheses, decimal points, and e notation.

Integers versus double precision

Java handles two types of numbers well.

One type of number is called an integer (or int). An int contains no decimal point and no e. For example, -27 and 30000 are ints.

The other type of number that Java handles well is called a double-precision number (or a double). A double contains a decimal point or an e. For example, -27.0 and 3e4 are doubles. You can abbreviate: instead of writing “-27.0”, you can write “-27.”, and instead of writing “0.37” you can write “.37”.

Largest and tiniest numbers

The largest permissible int is about 2 billion. More precisely:

the largest int is  2147483647

the lowest int is -2147483648

If you try to feed the computer an int that’s too large or too low, the computer won’t complain. Instead, the computer will typically print a wrong answer!

The largest permissible double is about 1.7e308. More precisely, it’s 1.7976931348623158e308. If you feed the computer a math problem whose answer is bigger than that, the computer will give up and typically say the answer is:

Infinity

The tiniest double that the computer handles well is about 2.2e-308. More precisely, it’s 2.2250738585072014e-308. If you feed the computer a math problem whose answer is tinier than that, the computer will either handle the rightmost digits inaccurately or give up, saying the answer is 0.0.

Tricky arithmetic

If you combine ints, the answer is an int. For example, 2+3 is this int: 5.

11/4 is this int: 2. (11/4 is not 2.75.)

If you combine doubles, the answer is a double. If you combine an int with a double, the answer is a double.

How much is 2000 times 2000000? Theoretically, the answer should be this int: 4000000000. But since 4000000000 is too large to be an int, the computer will print a wrong answer. To make the computer multiply 2000 by 2000000 correctly, ask for 2000.0*2000000.0, like this:

    System.out.println(2000.0*2000000.0);

That program makes the computer get the correct answer, 4000000000.0, which the computer will write in e notation, so you see this answer:

4.0E9


Long decimals

If an answer is a decimal that contains many digits,
the computer will typically print the first 16 significant digits accurately and the 17th digit approximately. The computer won’t bother printing later digits.

For example, suppose you ask the computer to print 10.0 divided by 9.0, like this:

    System.out.println(10.0/9.0);

The computer will print:

1.1111111111111112

Notice that the 17th digit, the 2, is slightly wrong: it should be 1.

Division by 0.0

If you try to divide 1.0 by 0.0, the computer will say the answer is:

Infinity

If you try to divide 0.0 by 0.0, the computer will say the answer is —

NaN

which means “Not a Number”.

Advanced math

The computer can do advanced math. For example, it can compute square roots. This line makes the computer print the square root of 9:

        System.out.println(Math.sqrt(9.0));

The computer will print:

3.0

Say Math.sqrt(9.0) rather than Math.sqrt(9), because the number you find the square root of should be double-precision, not an integer. If you make the mistake of saying Math.sqrt(9), the computer will print the correct answer but slowly.

Besides sqrt, you can use other advanced math functions, but you must say “Math.” at the beginning of each. Here’s a list of those advanced-math functions:

To handle exponents, you can use sqrt (square root), exp (exponential power of e), and log (logarithm base e). You can also use pow: for example, pow(3.0,2.0) is 3.0 raised to the 2.0 power.

For trigonometry, you can use sin (sine), cos (cosine), tan (tangent), asin (arcsin), acos (arccosine), and atan (arctangent). You can also use atan2: for example, atan2(y,x) is the arctangent of y divided by x.

For absolute value, use abs. For example, abs(-2.3) is 2.3.

To round, use floor (which rounds down) or ceil (which stands for “ceiling” and rounds up). For example, floor(26.319) is 26.0, and ceil(26.319) is 27.0.

 

Variables

Like BASIC and JavaScript, Java lets you use variables. For example, you can say:

    n=3;

A variable’s name can be short (such as n) or long (such as town_population_in_1999). It can be as long as you wish! The name can contain letters, digits, and underscores, but not blank spaces. The name must begin with a letter or underscore, not a digit.

Before using a variable, say what type of number the variable stands for. For example, if n and town_population_in_1999 will stand for numbers that are ints and mortgage_rate will stand for a double, begin your program by saying:

public class Class1

{

    public static void main (String[] args)

    {

        int n, town_population_in_1999;

        double mortgage_rate;

If n is an integer that starts at 3, you can say —

    int n;

    n=3;

but you can combine those two lines into this single line:

    int n=3;

Here’s how to say “n is an integer that starts at 3, and population_in_1999 is an integer that starts at 27000”:

    int n=3, population_in_1999=27000;

Increase

Like JavaScript, Java uses the symbol ++ to mean “increase”. For example, ++n means “increase n”.

These lines create n, increase it, then print it:

        int n=3;

        ++n;

        System.out.println(n);

The n starts at 3 and increases to 4, so the computer prints 4.

Saying ++n gives the same answer as n=n+1, but the computer handles ++n faster.

The symbol ++ increases the number by 1, even if the number is a decimal. For example, if x is 17.4 and you say ++x, the x will become 18.4.

Decrease

The opposite of ++ is --. The symbol -- means “decrease”. For example, --n means “decrease n”. Saying --n gives the same answer as n=n-1 but faster.

Strange short cuts

If you use the following short cuts, your programs will be briefer and run faster.

Instead of saying n=n+2, say n+=2, which means “n’s increase is 2”. Similarly, instead of saying n=n*3, say n*=3, which means “n’s multiplier is 3”.

Instead of saying ++n and then giving another command, say ++n in the middle of the other command. For example, instead of saying —

    ++n;

    j=7*n;

say:

    j=7*++n;

That’s pronounced: “j is 7 times an increased n”. So if n was 2, saying j=7*++n makes n become 3 and j become 21.

Notice that when you say j=7*++n, the computer increases n before computing j. If you say j=7*n++ instead, the computer increases n after computing j; so j=7*n++ has the same effect as saying:

    j=7*n;

    ++n;


Arrays

Like BASIC and JavaScript, Java lets you create arrays. For example, if you want x to be a list of 3 double-precision numbers, begin your program by saying:

        double[] x=new double[3];

That says x will be a list of 3 double-precision numbers, called x[0], x[1], and x[2]. Like JavaScript, Java starts counting at 0.

Here’s a complete Java program using that array:

public class Class1

{

    public static void main (String[] args)

    {

        double[] x=new double[3];          x

        x[0]=10.6;                         x

        x[1]=3.2;                          x

        x[2]=1.1;                          x

        System.out.println(x[0]+x[1]+x[2]);

        while (true);

    }

}

The computer will print the sum, 14.9.

Notice that if you say double[] x=new double[3], you can refer to x[0], x[1], and x[2], but not x[3]. If you accidentally refer to x[3], the computer will gripe about “ArrayIndexOutOfBoundsException”.

If you want x to be a table having 2 rows and 3 columns of double-precision numbers, begin your program by saying:

        double[][] x=new double[2][3];

Since Java always starts counting at 0 (not 1), the number in the table’s top left corner is called x[0][0].

Character variables

A variable can stand for a character.

For example, suppose you’re in school, take a test, and get an A on it. To proclaim your grade, write a program containing this line:

    grade='A';

Here’s the complete program:

public class Class1

    {

    public static void main (String[] args)

    {

        char grade;               The grade is a character.

        grade='A';                The grade is ‘A’.

        System.out.println(grade); Print the character that’s the grade.

        while (true);

    }

}

The computer will print:

A

In that program, you can combine these two lines —

        char grade;               The grade is a character.

        grade='A';                The grade is ‘A’.

to form this single line:

        char grade='A';           The grade is this character: ‘A’.

String variables

A variable can stand for a whole String of characters:

public class Class1

    {

    public static void main (String[] args)

    {

        String x;                        

        x="he";                          

        System.out.println("fat"+x+"red");

        while (true);

    }

}

The first shaded line says there’s a String of characters, called x. The second shaded line says x is this String of characters: “he”. The third shaded line makes the computer print “fat” then x (which is “he”) then “red”, so the computer will print:

fathered

Java requires you to capitalize the first letter of String: say String, not string.

In that program, you can combine these two lines —

        String x;

        x="he";

to form this single line:

        String x="he";


Input

Like BASIC and JavaScript, Java lets you input; but Java makes it harder.


String input

This program lets you input a String:

import java.io.*;

public class Class1

    {

    public static void main (String[] args) throws IOException

    {

        InputStreamReader is=new InputStreamReader(System.in);

        BufferedReader br=new BufferedReader(is);             x

        System.out.print("What is your name? ");

        String s=br.readLine();

        System.out.println ("I like the name "+s+" very much");

        while (true);

    }

}

To handle input well, you must prepare the computer for input:

Begin your program by saying “import java.io.*”.

Say “throws IOException” at the end of the “public static void main” line.

Begin the program’s main part by inserting lines about InputStreamReader and BufferedReader.

Type all that carefully! Beware of capitals and spaces! After you’ve typed all that junk, the rest of the program is easy:

The System.out.print line makes the computer ask “What is your name? ”.

The next line makes the String s be whatever the human types; the computer reads the Line the human inputs.

The System.out.println makes the computer say “I like the name ” then s then “ very much”.

For example, if the human’s name is “Dr. Hector von Snotblower, Jr., M.D.”, the program makes the conversation go like this:

What is your name? Dr. Hector von Snotblower, Jr., M.D.

I like the name Dr. Hector von Snotblower, Jr., M.D. very much

Integer input

The program above lets you input a String. To input an integer instead, do this trick: input a String, then convert the String to an integer by saying “Integer.parseInt”. For example, this program asks the human’s age, then predicts how old the human will be 10 years from now:

import java.io.*;

public class Class1

    {

    public static void main (String[] args) throws IOException

    {

        InputStreamReader is=new InputStreamReader(System.in);

        BufferedReader br=new BufferedReader(is);

        System.out.print("How old are you? ");

        int age=Integer.parseInt(br.readLine());

        System.out.println ("Ten years from now, you'll be "+(age+10));

        while (true);

    }

}

Here’s how the program works:

The System.out.print line makes the computer ask “How old are you? ”.

The next line makes the integer age be the string the human types, converted to an integer.

The System.out.println makes the computer say “Ten years from now, you’ll be ” then age+10.

Here’s a sample run:

How old are you? 27

Ten years from now, you'll be 37

Double-precision input

In the program above, age is an integer. If you want age to be double-precision instead, change the shaded line to this —

        double age=Utils.parseDblList(br.readLine())[0];

and insert one more line at the top of the program:

import com.ms.wfc.util.*;

That works in Visual J++ 6.0, but other Java versions use different commands.


Logic

Java lets you say “if”, “while”, “for”, and create comments. Here are examples.…

If

If a person’s age is less than 18, let’s make the computer say “You are still a minor.” Here’s the fundamental line:

        if (age<18) System.out.println("You are still a minor.");

Notice you must put parentheses after the word “if”.

If a person’s age is less than 18, let’s make the computer say “You are still a minor.” and also say “Ah, the joys of youth!” and “I wish I could be as young as you!” Here’s how to say all that:

        if (age<18)

        {

            System.out.println("You are still a minor.");

            System.out.println("Ah, the joys of youth!");

            System.out.println("I wish I could be as young as you!");

        }

Since that “if” line is above the “{”, the “if” line is a structure line, similar to a “public class” line, and does not end in a semicolon.

Here’s how to put that structure into a complete program, assuming age is an integer:

import java.io.*;

public class Class1

    {

    public static void main (String[] args) throws IOException

    {

        InputStreamReader is=new InputStreamReader(System.in);

        BufferedReader br=new BufferedReader(is);

        System.out.print("How old are you? ");

        int age=Integer.parseInt(br.readLine());

        if (age<18)

        {

            System.out.println("You are still a minor.");

            System.out.println("Ah, the joys of youth!");

            System.out.println("I wish I could be as young as you!");

        }

        else

        {

            System.out.println("You are an adult.");

            System.out.println("Now we can have some adult fun!");

        }

        System.out.println("Glad to have met you.");

        while (true);

    }

}

If the person’s age is less than 18, the computer will print “You are still a minor.” and “Ah, the joys of youth!” and “I wish I could be as young as you!” If the person’s age is not less than 18, the computer will print “You are an adult.” and “Now we can have some adult fun!” Regardless of the person’s age, the computer will end the conversation by saying “Glad to have met you.”

The “if” statement uses this notation:

Notation                                            Meaning

if (age<18)                  if age is less than 18

if (age<=18)                 if age is less than or equal to 18

if (age==18)                 if age is equal to 18

if (age!=18)                 if age is not equal to 18

if (age<18 && weight>200)    if age<18 and weight>200

if (age<18 || weight>200)    if age<18 or weight>200

Notice that in the “if” statement, you should use double symbols: you should say “==” instead of “=”, say “&&” instead of “&”, and say “||” instead of “|”. If you accidentally say “=” instead of “==”, the computer will gripe. If you accidentally say “&” instead of “&&” or say “|” instead of “||”, the computer will still get the right answers but too slowly.


Strings The symbols <, <=, ==, and != let you compare numbers or characters but not Strings. If you try to use them to compare Strings, you’ll get wrong answers.

For example, suppose x and y are strings, and you want to test whether they’re equal. Do not say “if (x==y)”. Instead, say:

        if (x.equals(y))

Make sure you put the period after x and put parentheses around y.

An alternative is to say:

        if (x.equalsIgnoreCase(y))

That makes the computer compare x with y and ignore capitalization. It makes the computer consider x to be “equal” to y if the only difference is “which letters in the string are capitalized”.

To test whether x’s string comes before y’s in the dictionary, do not say “if (x<y)”. Instead, say:

        if (x.compareTo(y)<0)


While

Let’s make the computer print the word “love” repeatedly, like this:

love love love love love love love love love etc.

love love love love love love love love love etc.

love love love love love love love love love etc.

etc.

This program does it:

public class Class1

{

    public static void main (String[] args)

    {

        while (true) System.out.print("love ");

    }

}

In that program, the “while (true)” means: do repeatedly. The computer will do System.out.print(“love ”) repeatedly, looping forever — or until you abort the program by pressing Ctrl with C.

Let’s make the computer start at 20 and keep counting, so the computer will print:

20

21

22

23

24

25

26

27

28

29

30

31

32

etc.

This program does it:

Program                                                       Meaning

public class Class1

{

    public static void main (String[] args)

    {

        int i=20;                 Start the integer i at 20.

        while (true)               Repeat indented lines forever:

        {

            System.out.println(i);        print i then press ENTER

            ++i;                        increase i

        }

}

It prints faster than you can read.

To pause the printing, press the PAUSE key.

To resume the printing, press the ENTER key.

To abort the program, press ENTER, then press Ctrl with C.

In that program, if you say “while (i<30)” instead of “while (true)”, the computer will do the loop only while i remains less than 30; the computer will print just:

20

21

22

23

24

25

26

27

28

29

To make that list stay on the screen, so you can read it, make the computer pause by saying “while (true)” at the end of that program, so your program looks like this:

Program                                                      Meaning

public class Class1

{

    public static void main (String[] args)

    {

        int i=20;                Start the integer i at 20.

        while (i<30)             Repeat indented lines while i<30:

        {

            System.out.println(i);      print i

            ++i;                      increase i

        }

        while (true);           Pause, so human can read screen.

    }

}

Instead of saying “while (i<30)”, you can say “while (i<=29)”.

For

Here’s a more natural way to get that output of numbers from 20 to 29:

public class Class1

{

    public static void main (String[] args)

    {

        for (int i=20; i<=29; ++i) System.out.println(i);

        while (true);

    }

}

In that program, the “for (int i=20; i<=29; ++i)” means “Do repeatedly. Start the integer i at 20, and keep repeating as long as i<=29. At the end of each repetition, do ++i.”

In that “for” statement, if you change the ++i to i+=3, the computer will increase i by 3 instead of by 1, so the computer will print:

20

23

26

29

The “for” statement is quite flexible. You can even say “for (int i=20; i<100; i*=2)”, which makes i start at 20 and keep doubling, so the computer prints:

20

40

80

Like “if” and “while”, the “for” statement can sit atop a group of indented lines that are in braces.

Comments

To put a comment in your program, begin the comment with the symbol //. The computer ignores everything that’s to the right of //. Here’s an example:

// This program is fishy

// It was written by a sick sailor swimming in the sun

public class Class1

{

    public static void main (String[] args)

    {

        System.out.println("Our funny God");  // religious

        System.out.println(invented cod");    // wet joke

        while (true);

    }

}

The computer ignores all the comments, which are to the right of //.

While you type the program, the computer makes each // and each comment turn green. Then the computer ignores everything that’s turned green, so the computer prints just:

Our funny God

invented cod