Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

It\'s a little surprising that our text has no examples of a Java Applet, consid

ID: 638294 • Letter: I

Question

It's a little surprising that our text has no examples of a Java Applet, considering how common they are in the world, in fact used to demo many things in this course (later chapters).  In this assignment, you'll need to figure out how to create a web page that loads a Java Applet which allows a user to drag a shape around with the mouse, as shown at this page:http://scidiv.bellevuecollege.edu/WPI/Applets/DrawShapes4.htm

Your assignment:  Create a .java file that works like my DrawShapes4 applet (see above).  Include an appropriate web page html file to display your applet.  And include the .class byte code so your page will actually work.  Zip all three of these files into one zip folder, and upload here.

Hints:  Start with my drawshapes3 java and html files, then modify to work with just one shape, notice that my example implements multiple interfaces,. neither of which will complete your assignment.  You need to listen to mouse motion to move the shape.

Explanation / Answer

A Tutorial Introduction to Java

A Tutorial Introduction Part 1: the Syntax

Hello World: The Application

At least since the first edition of Kernighan and Ritchie's The C Programming Language it's been customary to begin programming tutorials and classes with the "Hello World" program, a program that prints the string "Hello World" to the display. Being heavily influenced by Kernighan and Ritchie and not ones to defy tradition we begin similarly.

To make later life simpler make a directory (folder for Mac users) called "javahtml" and within that directory make another directory (folder) called "classes". You can call the javahtml directory whatever you want, but I'll refer to it by that name in this document. However the classes directory must be called classes.

The following is the Hello World Application as written in Java. Type it into a text file or copy it out of your web browser, and save it as a file named HelloWorld.java in the javahtml directory.

To compile this program make sure you're in the javahtml directory and type javac HelloWorld.java at the command prompt. Hello World is very close to the simplest program imaginable. Although it doesn't teach very much from a programming standpoint, it gives you a chance to learn the mechanics of writing and compiling code. If you're like me your first effort won't compile, especially if you typed it in from scratch rather than copying and pasting. Here are a few common mistakes:

Once your program has compiled successfully, the compiler places the executable output in a file called HelloWorld.class in the javahtml directory. You can then run the program by typing java HelloWorldat the command prompt. As you probably guessed the program responds by printing Hello World! on your screen.

Congratulations! You've just written your first Java program!

Examining Hello World

Hello World is very close to the simplest program imaginable. Nonetheless there's quite a lot going on in it. Let's investigate it, line by line.

For now the initial class statement may be thought of as defining the program name, in this case HelloWorld. The compiler actually got the name for the class file from the class HelloWorld statement in the source code, not from the name of the source code file. If there is more than one class in a file, then the Java compiler will store each one in a separate .class file. For reasons we'll see later it's advisable to give the source code file the same name as the main class in the file plus the .java extension.

The initial class statement is actually quite a bit more than that since this "program" can be called not just from the command line but also by other parts of the same or different programs. We'll see more in the section on classes and methods below.

The HelloWorld class contains one method, the main method. As in C the main method is where an application begins executing. The method is declared public meaning that the method can be called from anywhere. It is declared static meaning that all instances of this class share this one method. (If that last sentence was about as intelligible as Linear B, don't worry. We'll come back to it later.) It is declaredvoid which means, as in C, that this method does not return a value. Finally we pass any command line arguments to the method in an array of Strings called args. In this simple program there aren't any command line arguments though.

Finally when the main method is called it does exactly one thing: print "Hello World" to the standard output, generally a terminal monitor or console window of some sort. This is accomplished by theSystem.out.println method. To be more precise this is accomplished by calling the println method of the out class belonging to the System object; but for now we'll just treat this as one method.

One final note: unlike the printf function in C the System.out.println method does append a newline at the end of its output. There's no need to include a at the end of each string to break a line.

Exercises

Braces and Blocks

Let's investigate the Hello World program a little more closely. In Java a source code file is broken up into parts separated by opening and closing braces, i.e. the { and } characters. Everything between { and } is a block and exists more or less independently of everything outside of the braces.

Blocks are important both syntactically and logically. Without the braces the code wouldn''t compile. The compiler would have trouble figuring out where one method or class ended and the next one began. Similarly it would be very difficult for someone else reading your code to understand what was going on. For that matter it would be very difficult for you, yourself to understand what was going on. The braces are used to group related statements together. In the broadest sense everything between matching braces is executed as one statement (though depending not necessarily everything inside the braces is executed every time).

Blocks can be hierarchical. One block can contain one or more subsidiary blocks. In this case we have one outer block that defines the HelloWorld class. Within the HelloWorld block we have a method block called "main".

In this tutorial we help to identify different blocks with indentation. Every time we enter a new block we indent our source code by two spaces. When we leave a block we deindent by two spaces. This is a common convention in many programming languages. However it is not part of the language. The code would produce identical output if we didn't indent it. In fact I'm sure you'll find a few examples here where I haven't followed convention precisely. Indentation makes the code easier to read and understand, but it does not change its meaning.

Comments

Comments can appear anywhere in a source file. Comments are identical to those in C and C++. Everything between /* and */ is ignored by the compiler and everything on a line after two consecutive slashes is also thrown away. Therefore the following program is, as far as the compiler is concerned, identical to the first one:

Data and Variables

Methods are only half of a Java class. The other half is data. Consider the following generalization of the HelloWorld program:

Here, rather than saying hello to a rather generic world, we allow Java to say hello to a specific individual. We do this by creating a String variable called "name" and storing the value "Rusty" in it. (You may, of course, have replaced Rusty with your own name.) Then we print out "Hello ". Notice that we've switched here from System.out.println method to the similar System.out.print method.System.out.print is just like System.out.println except that it doesn't break the line after it's finished. Therefore when we reach the next line of code, the cursor is still located on the same line as the word "Hello" and we're ready to print out the name.

Command Line Arguments

Our Hello program still isn't very general. We can't change the name we say hello to without editing and recompiling the source code. This may be fine for the programmers, but what if the secretaries want their computers to say Hello to them? (I know. This is a little far-fetched but bear with me. I'm making a point.)

What we need is a way to change the name at runtime rather than at compile time. (Runtime is when we type java HelloRusty. Compile time is when we type javac HelloRusty.java). To do this we'll make use of command-line arguments. They allow us to type something like Java Hello Gloria and have the program respond with "Hello Gloria". Here's the code:

Compile this program in the javahtml directory as usual and then type java Hello Gloria.

This isn't very hard is it? In fact we've even gotten rid of the name variable from the HelloRusty program. We're using args[0] instead. args is what is known as an array. An array stores a series of values. The values can be Strings as in this example, numbers, objects or any other kind of Java data type.

args is a special array that holds the command line arguments. args[0] holds the first command line argument. args[1] holds the second command line argument, args[2] holds the third command line argument and so on.

At this point almost everyone reading this is probably saying "Whoa, that can't be right." However why you're saying depends on your background.

If you've never programmed before or if you've programmed only in Pascal or Fortran, you're probably wondering why the first element of the array is at position 0, the second at position 1, the third at position 2 instead of the clearly more sensible element 1 being the first element in the array, element 2 being the second and so on. All I can tell you is that this is a holdover from C where this convention almost made sense.

On the other hand if you're used to C you're probably upset because args[0] is the first command line argument instead of the command name. The problem is that in Java it's not always clear what the command name is. For instance in the above example is it java or Hello? On some systems where Java runs there may not even be a command line, the Mac for example.

Now you should experiment with this program a little. What happens if instead of typing java Hello Gloria you type java Hello Gloria and Beth? What if you leave out the name entirely, i.e. java Hello?

That was interesting wasn't it? You should have seen something very close to

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at Hello.main(C:javahtmlHello.java:7)

What happened was that since we didn't give Hello any command line arguments there wasn't anything in args[0]. Therefore Java kicked back this not too friendly error message about an "ArrayIndexOutOfBoundsException." That's a mouthful. We'll see one way to fix it in the next section.

All but the most trivial computer programs need to make decisions. They need to test some condition and operate differently based on that condition. This is quite common in real life. For instance you stick your hand out the window to test if it's raining. If it is raining then you take an umbrella with you. If it isn't raining then you don't.

All programming languages have some form of an if statement that allows you to test conditions. In the previous code we should have tested whether there actually were command line arguments before we tried to use them.

All arrays have lengths and we can access that length by referencing the variable arrayname.length. (Experienced Java programmers will note that this means that the array is an object which contains a public member variable called length.) We test the length of the args array as follows:

Compile and run this program and toss different inputs at it. You should note that there's no longer an ArrayIndexOutOfBoundsException if you don't give it any command line arguments at all.

What we did was wrap the System.out.println(args[0]) statement in a conditional test, if (args.length > 0) { }. The code inside the braces, System.out.println(args[0]), now gets executed if and only if the length of the args array is greater than zero. In Java numerical greater than and lesser than tests are done with the > and < characters respectively. We can test for a number being less than or equal to and greater than or equal to with <= and >= respectively.

Testing for equality is a little trickier. We would expect to test if two numbers were equal by using the = sign. However we've already used the = sign to set the value of a variable. Therefore we need a new symbol to test for equality. Java borrows C's double equals sign, ==, to test for equality.

It's not uncommon for even experienced programmers to write == when they mean = or vice versa. In fact this is a very common cause of errors in C programs. Fortunately in Java, you are not allowed to use == and = in the same places. Therefore the compiler can catch your mistake and make you fix it before you run the program.

All conditional statements in Java require boolean values, and that's what the ==, <, >, <=, and >= operators all return. A boolean is a value that is either true or false. Unlike in C booleans are not the same as ints, and ints and booleans cannot be cast back and forth. If you need to set a boolean variable in a Java program, you have to use the constants true and false. true is not 0 and false is not non-zero as in C. Boolean values are no more integers than are strings.

Experienced programmers may note that there was an alternative method to deal with the ArrayIndexOutOFBoundsException involving try and catch statements. We'll return to that soon.

Else

You may have noticed a minor cosmetic bug in the previous program. A cosmetic bug is one that doesn't crash the program or system, or produce incorrect results, but just looks a little annoying. Cosmetic bugs are acceptable in quick hacks you'll only use once but not in finished code.

The cosmetic bug here was that if we didn't include any command line arguments, although the program didn't crash, it still didn't say Hello. The problem was that we only used System.out.print and notSystem.out.println. There was never any end of line character. It was like we typed in what we wanted to say, but never hit the return key.

We could fix this by putting a System.out.println(""); line at the end of the main method, but then we'd have one too many end-of-lines if the user did type in a name. We could add an additional if statement like so:

This corrects the bug, but the code is hard to read and maintain. It's very easy to miss a possible case. For instance we might well have tested to see if args.length were less than zero and left out the more important case that args.length equals zero. What we need is an else statement that will catch any result other than the one we hope for, and luckily Java provides exactly that. Here's the right solution:

Now that Hello at least doesn't crash with an ArrayIndexOutOfBoundsException we're still not done. java Hello works and Java Hello Rusty works, but if we type java Hello Elliotte Rusty Harold, Java still only prints Hello Elliotte. Let's fix that.

We're not just limited to two cases though. We can combine an else and an if to make an else if and use this to test a whole range of mutually exclusive possibilities. For instance here's a version of the Hello program that handles up to four names on the command line:

You can see that this gets mighty complicated mighty quickly. Once again no experienced Java programmer would write code like this. One of the things that makes this solution so unwieldy is that I've used a different print statement for every single variable. However Java makes it very easy to print multiple items at once. Instead of including just one thing in the print method's arguments we put multiple items in there separated by + signs. These items can include variables like args[0] and constant strings like " and all the rest!". For example the last else block could have been written as

This syntax is simpler to read and write but would still be unwieldy once the number of command line arguments grew past ten or so. In the next section we'll see how to handle over two billion command line arguments in a much simpler fashion.

Exercises

Variables and Arithmetic Expressions

We'll begin this section by finding a more elegant way to handle multiple command line arguments of an undetermined number. Toward this end we introduce the concept of a loop. A loop is a section of code that is executed repeatedly until a stopping condition is met. A typical loop may look like:

This isn't working code but it does give you an idea of a very typical loop. We have a test condition (Is there more data?) and something we want to do with if the condition is met. (Read a Line of Data and Do Something with the Data.)

There are many different kinds of loops in Java including while, for, and do while loops. They differ primarily in the stopping conditions used.

For loops typically iterate a fixed number of times and then exit. While loops iterate continuously until a particular condition is met. You usually do not know in advance how many times a while loop will loop.

In this case we want to write a loop that will print each of the command line arguments in succession, starting with the first one. We don't know in advance how many arguments there will be, but we can easily find this out before the loop starts using the args.length. Therefore we will write this with a for loop. Here's the code:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote