Loirak Development Logo  

Java Programming for beginners in four hours

Loirak -> Programming -> Java

Loirak.com
About Us
Contact
Search
Games
Tank DirectX
Tank GBA
Skiing
Raycaster
vbChess
BMI Calculator
Programming
C/C++
Java
Gameboy
DirectX

 
 

The Four Hour Java Tutorial

Have you ever wanted to master a programming language? Well, you have chosen a language which is considered by most to be the future of programming. This tutorial will give you the basics that will enable you to build powerful programs and applets.

Java is a high-level programming language, or a 3rd generation language. It operates like this: you type in the source code, then a program called a "compiler" transforms it into Java bytecode. Bytecode makes Java architecture neutral, since the computer that runs your program needs an interpreter or a bytecode compiler.
Now to the pre-requisite. "Aller Anfang ist schwer!"

Java Developement Kit (JDK) 20+MB - this includes all of the standard objects and classes to make and run your programs. If you like running programs, download this! This file can be downloaded from the Sun Java Page (http://java.sun.com).

Now to programming, in only four hours to go!

Hour I. Hello Program, Orientation, and Input

Example I.

class Hello {
  public static void main (String[] args) {
    System.out.println("Welcome to the world of Java Programming.");
  } // method main
} // class Hello
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
} // end of class Echo
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.

Hour II. Data types and Loops

Java has several standard(primitive) data types, this hour will cover the two most common. Since String is actually an object, it will be covered in the fourth hour.

Example III.

import java.io.*; 

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

    BufferedReader stdin = new BufferedReader
      (new InputStreamReader(System.in));
    int num1, num2, sum; // declares three integers
    double dollars; // declares a number that can have decimals

    System.out.print ("How many candy bars do you want  : ");
    System.out.flush(); 

    // read a line, and then converts it to an integer
    num1 = Integer.parseInt( stdin.readLine());

    System.out.print ("How many suckers you do want  : ");
    System.out.flush(); 
    num2 = Integer.parseInt( stdin.readLine());

    sum = num1 + num2; // Adds the two numbers;
    dollars = (double) sum * .75;
    System.out.println("You owe : $" + dollars);
  } // method main
} 
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.


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.

Hour III. Applets

Now we are going to learn how to create Applets, to include in your web pages and amaze your friends.

Example V.

import java.applet.Applet; // Includes standard Applet classes
import java.awt.*; // Standard Graphics Routines 

public class Wow extends Applet {
  // Applets use paint instead of main
  public void paint (Graphics page) {
    page.drawString("Wow, this is an Applet!", 5, 10);
  } // method paint
} // class Wow
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)


Hour IV. Arrays, Objects, Classes and Methods

The manipulation of objects and arrays, complemented with the use of several classes and methods will define you as a true java programmer, so take good notes!

Example VI.

class Bank {
  public static void main (String[] args) { 
    // Creates an object with the class Bank_Account defined below
    Bank_Account account = new Bank_Account(150.00);
    System.out.println ("Balance: "+ account.current_Account());
    account.debit_Account(50.30);
    System.out.println ("New Balance : "+ account.current_Account());
  }
}

class Bank_Account {
  private double value_account; 
  public Bank_Account ( double initial_value) {
    value_account = initial_value;
  } // end constructor for object creation
  public void debit_Account ( double number) {
    value_account = value_account + number;         
  }
  public double current_Account () {
    return value_account;
  } 
}
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
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.
Now that you have completed the tutorial, you are ready to enter the world of programming, right? You have the basics, and where you go from here depends on how much ambition and hard work you are willing to spend on developing your skills.
  • Not satisfied with the basics, try this tutorial http://sunsite.unc.edu/javafaq/javatutorial.html
  • Visit Loirak Enterprises for more on programming, and source code. (http://www.loirak.com).
  • Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks, etc. Where those designations are missing, note that they are properties of their respective corporations

[C/C++] [Gameboy] [Java] [DirectX] [Games] [Contact] [Loirak HQ]
Viewing: Loirak -> Programming -> Java
© Copyright 1998-2014 Loirak. All rights reserved.
23 November 2014