Java 4 Hour
Java 4 Hour
To compile and run this program, you need to have installed JDK and added a line to your path statement referring to the directory of where it was install + \bin. (e.g. path %path%;c:\jdk\bin;)
type this file into notepad or something save it as Hello.java(class name + .java) drop to a command prompt type javac Hello.java (e.g. "javac C:\work\Hello.java") type java Hello (e.g. "java C:\work\Hello") then watch the magic
You have now written and completed your first Java program. Looking back to the above program, you should notice the following. First, Java is case-sensitive. The commands have to be written like they are above. Java also denotes the end of statement with a semi-colon like C & Pascal. Brackets signify either to "{" begin a group of statements, or "}" end a group of statements. The // designates a comment. Anything after two slashes the compiler ignores. Now we're ready to read input from the keyboard. Pay attention to the comments, they help explain the programs. Example II.
import java.io.*; //include Java's standard Input and Output routines class Echo { public static void main (String[] args) throws IOException { // Defines the standard input stream BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); String message; // Creates a varible called message for input System.out.print ("Enter the message : "); System.out.flush(); // empties buffer, before you input text message = stdin.readLine(); System.out.print("You "); System.out.println("entered : " + message); } // method main
Company Confidential
Company Confidential
You have just learned the standard way of getting text. First you create a reader, and then you input the text with readLine() , and finally you use the print command to output it. Notice the difference in the print commands : println prints, then goes to the next line, while print does not. The throws IOException in main lets Java know what to do with errors, when it encounters them.
Using (double) to convert the integer sum to a double, we can multiply by .75 to calculate the amount of money. This method of conversion using parentheses is called casting. Java has several types of loops, the most useful being the for & while loops, which are both demonstrated in this next example. The standard if-then-else, will also be a very handy programming tool.
Company Confidential
Company Confidential
Example IV.
import java.io.*; class Loopit { public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); int count, max, num; num = 0; // Assign initial value of count while (num != -1) { System.out.print ("Enter a number to factorialize (-1 to quit): "); System.out.flush(); num = Integer.parseInt (stdin.readLine()); max = 1; // Assign to 1, so factorial isn't zero every time if (num == -1) { System.out.println("Okay, quiting..."); } else { // Since they're not quitting we better factorialize for (count = 1; count<=num; count++) { max = count * max; } System.out.println (num+"! (factorial) is : "+ max); } } } // method main }
The first loop above is called a while loop, the syntax being : while (condition) { dosomething; } The program runs what is in the brackets until the condition becomes false. For instance, the above program runs until the user enters negative one. Hence, "!=" mean not equal to. Next is if, then and else. The syntax being : if (condition) { dosomething; } else { dosomethingdifferent; } The above program compares (==) the number entered to negative one. If they are equal it tells the user the program is quitting, otherwise it factorializes the number using the for loop. The syntax for a for loop is : for (initialization; condition; increment) { dosomething; } In example four, the initialization, count = 1, assigns count to one. The increment, count++, adds one to the variable count until the condition, count<=num, becomes false. In other words, count is assigned one, two, three, ... num, with the inside of the loop being processed after each increment. Notice again that count++ increments by one; however, count+=2 would increment count by a factor of two. This is also true for count-- and count-=2. The former decreases by a factor of one, the latter by a factor of two.
Company Confidential
Company Confidential
The page.drawString statement is like the print command. Note that it also accepts the coordinates for the text. In the above example, the text is placed five pixels right and ten down from the top left corner of the Applet. To actually use this Applet :
compile it like a normal program with javac create the following HTML file
<HTML> <HEAD> <TITLE>The Wow Applet!</TITLE> <BODY> <APPLET CODE="Wow.class" WIDTH="150" HEIGHT="50"> </APPLET> <HR> Was that easy or what? </BODY> </HTML>
load the HTML file with a web browser then watch the magic
Applets is a topic that could easily be the subject matter of an entire book, to learn more visit : Sun's Java Tutor (http://java.sun.com/docs/books/tutorial)
Company Confidential
Company Confidential
The above program has several methods and two classes. Look at the creation and usage of the object account. Its value is changed by the method debit_Account. Using objects can simplify programs by allowing user defined types. The syntax for class creation is self explanatory; however, the syntax for method declaration is a bit more complex. Using the example : public void debit_Account ( double number)
public is the access level, which defines what can access the method. public allows other classes to access the method; however, private would only allow the method to be accessed inside class Bank_Account void is the return type. void is used when a particular method does not need to return a value; however, in example six, the current_Account method returns a double debit_Account is the name of the method ( double number) is known as the arguments for the method. This allows the value of the "bank account" to be passed into the method for processing
Company Confidential
Company Confidential
Now that we understand classes and methods (if not, read it again), we'll move on to something a lot simpler Arrays. Example VII.
class Arrays { public static void main (String[] args) { int[] list = new int[5]; // creates Array of 5 integers for (int index=0; index < 5; index++) { list[index] = index * 2; // Assign values to Array } for (int index=4; index > -1; index--) { System.out.println(list[index]); } } // method main }
Java uses [ and ] to signify an array. In the above program an array of 5 integers is created. The number five is the number of elements in the array; however Java starts array indexing at ZERO, therefore the last index of the above array is four (5-1). Arrays can also be used for objects, as well as the primitive data types. For example, the String[] args you see along with the main method is simply an array of String objects. This array of objects stores the command line parameters you type when you run your program. For example, if you typed : java Someclassname new the value stored in args[0] would be "new". Make sure args[0] exists before you access it, or else you will get an array out of bounds exception.
Company Confidential