Java for OO Programmers

From SwinBrain

This page is designed to teach you the basics of the Java language syntax. It assumes you already know some basic programming, and understand the principles of Object Oriented Programming.

Contents

Getting started

The Java Development Kit (JDK) is available for download from the Sun site, Java SE Downloads. There are a lot of different versions to choose from, the most recent (at the time of writing) is JDK 6. Once you have selected the version you will need to select the appropriate platform (Windows, Linux) for your system.

Which ever version you select, there are installation instructions available to guide you through the installation process and how to set the execution path. Also provided with this document is a troubleshooting guide for any problems that may arise during installation.


Because of it's simplicity this little application is always used to demonstrate the basics, no matter what language you are using. So here is HelloWorld:

  1. public class HelloWorld
  2. {
  3. public static void main(String[] args)
  4. {
  5. System.out.println("Hello World");
  6. }
  7. }

Although this code does not appear to be doing very much, there are some important points that you need to know. Line 1 creates a new class called HelloWorld. A block of code is always surrounded by braces, '{' and '}'. Line 3 which will become a lot clearer in due time, but for now you need to know that this is the entry point for an application. You must have this line of code in a class if you wish to run it. Line 5 prints the text "Hello World" to the screen.


If you choose not to use an Integrated Development Environment (IDE), like Eclipse to write your Java code and instead use a text editor that does not compile and run your applications automatically then you will need to know how to do this from the command line.

To compile and run the HelloWorld application, type the following:

javac HellowWorld.java
java HelloWorld

The first command compiles the .java file into a .class file with the same name using the java compiler (java compiler). Then you can run that file by issuing the second command which runs the .class file. Remember not to include the .class extension.

Packaging Java Classes

As you could imagine when you create a large scale application in Java, your solution will contain a large number items including classes, images etc. If you distribute your application it would become difficult to distribute all of these files seperatly. So instead you can create a Java Archive (JAR) file. JAR uses the same compression format that ZIP does so files are stored in one location and also compressed to allow for easy transportation.

Variables and Types in Java

Java supports many, many different types of variables. To declare and use a variable with a certain type, see the code below, and for a description of each one, see the table.

int myInt = 10;
String myString = "Hello!";
int myOtherInt = 20;
System.out.println(myString);
int sum = myInt * myOtherInt;
System.out.println("" + myOtherInt);
Category Description
Value Types Simple types Signed Integral: short, int, long, byte
Unicode characters: char
IEEE floating point: float, double
Boolean: boolean
Enum types: User defined types of the form: enum E {...}
Reference types Class types Ultimate base class of all other types: object
Unicode strings: String
User defined types of the form: class C {...}
Interface types User defined types of the form: interface I {...}
Array types Single and multi dimensional types, for example, int[] and int[][]
Category Bits Type Range / Precision
Signed integral 32 int -2,147,483,648...2,147,483,647
16 short -32,768...32,767
64 long -9,223,372,036,854,775,808...9,223,372,036,854,775,807
8 byte -128...127
Floating point 32 float 1.5*10^(-45) to 3.4*10^(38), 7-digit precision
64 double 5.0*10^(-324) to 1.7*10^(308), 15-digit precision
  • Local variables
    Local variables are simple, easy to declare variables. They are only usable in the current function or procedure, and are even limited to within a set of parenthesis.
public class MyClass
{
    public MyClass()
    {
        System.out.println(MyOtherMethod());
        System.out.println(MyMethod());
    }
 
    public String MyOtherMethod()
    {
        //This string can only be accessed from within MyOtherMethod(). Even MyClass cannot see it.
        String myString = "Hello world!";
    }
 
    public int MyMethod(int myInt)
    {
        //myInt is only accessible from within MyMethod(), and not MyOtherMethod().
 
        if (myInt = 1)
        {
            //This is only accessible from within the "then" section of this if statement, and does not exist outside it.
            int someInt = 20;
            return someInt + myInt;
        }
    }
}
  • Instance variables
    An instance variable is one that is associated with an instance of a class. It is created when an object of the classes type is made, and can vary for each instance of the object. The code below makes two objects of the same type, and changes one of their variables. It shows that they can both have different properties although they are the same type.
public class MyClass
{
    public int MyInstanceVar;
 
    public MyClass(int myInt)
    {
        MyInstanceVar = myInt;
    }
 
    public static void Main(String[] args)
    {
        myFirstObj = new MyClass(20);
        mySecondObj = new MyClass(10);
        System.out.println("Here are the values for both of the objects.");
        System.out.println("myFirstObj: " + myFirstObj.MyInstanceVar);
        System.out.println("mySecondObj: " + mySecondObj.MyInstanceVar);
        System.out.println("Notice how they are different.");
    }
}
  • Static variables
    A static variable is a variable which, like any other member of a class, is not duplicated upon instantiation. It is created before any instances of the class, and initialized with the default value for the variable's type. They can be reassigned, read from and used just as any other variable. See the example below, which uses and changes a static variable.
public class MyClass
{
    public static int MyStaticVar;
 
    public MyClass()
    {
        System.out.println("The class was made.");
    }
 
    public static void Main(String[] args)
    {
        MyStaticVar = 20;
        System.out.println("MyStaticVar: " + MyStaticVar);
        System.out.println("Now we'll change it again.");
        MyStaticVar = 10;
        System.out.println("MyStaticVar: " + MyStaticVar);
        System.out.println("Now we'll make a class.");
        myObj = new MyClass();
        System.out.println("Did the variable MyStaticVar change?");
        System.out.println("MyStaticVar: " + MyStaticVar);
    }
}
  • categorise using value/reference types

Java Methods

Declaring Methods

Declaring a method in Java is simple. They all have the following structure to them:
<access> <static> [return-type] [name](<parameters>) <throws [Exception]> { }
The access level is optional, by default it will be private though.
A method is also either static or not. For static methods, just write in place static and then the rest of the methods declaration.
The return type must be specified and is a type of object, write void if nothing is to be returned.
Next is the name of the method. This does not necessarily need to be unique, however the method's signature does, but more on that in a moment. Remember that Java is completely case sensitive and that does not exclude method names.
Next are the parameters, which have the following format:
(<type> [object type] [local name])
In Java all parameters are call by value. This means that a copy of the variable is created.
Then, you need to tell the type of the parameter. These can be any type of object, for instance: int, boolean, String, byte, or even a custom class. The code will not compile if one of these is incorrectly matched with a parameter.
The variable needs to be given a name, which is local to the method. The name does not need to be anything like that of the variable being passed as a parameter. Here is an example of the different types of parameters, and below it, the output of running this program.
Lastly, if the method throws an exception then this needs to be declared in the method signature. To do this just add throws Exception.

Method Signatures

Each method you have has a signature. The signature is a way of identifying a method, and it isn't just by method name. The number and types of parameters have to match as well. A method called
public static void MyMethod()
is not the same as a method called
public static void MyMethod(int myInt)
This allows us to 'overload' methods. We can, through overloading, choose which version of a method to call, depending on what we what to pass to it. An example of this is the System.out.println() method. It takes no parameters, or strings, ints.. in fact, almost anything.

Returning Data

Returning data from a method is exceedingly simple. All you need to do is change the word 'void' to the type of object being returned, and have a return line at the end of the method. Here is an example and below is the expected output.
public class Return
{
	public static void main(String[] args)
	{
		int number1 = 5;
		int number2 = 5;
		int result;
		
		result = Addition(number1, number2);
		System.out.println("" + result);
	}
	
	public static int Addition(int num1, int num2)
	{
		return num1 + num2;
	}
}
 10

Control Flow Statements

Branching

Branching allows you to execute a certain block of code depending on the condition that is evaluated at the beginning. There are two types of branching statements, they are the if/else and switch statements.

The if statement has the following form:

 if (condition) statement

If you want to execute multiple statements if the condition is true you can use a block statement:

 if (condition)
 {
   statement 1
   statement 2
   statement n
 }

Normally if the condition is false then you would want to execute a different statement, or block of statements:

 if (condition) statement 1
 else statement 2

You can combine multiple if statements together using:

 if (condition 1) statement 1
 else if (condition 2) statement 2
 else statement 3

The other branching statement available is the switch statement. The switch statement is useful when multiple selections need to made, instead of having multiple if/else statements. Switch statements are very useful when the user needs to select an option from a list:

int option = 3;
switch (option)
{
  case 1:
    System.out.println("Option 1 selected");
    break;
  case 2:
    System.out.println("Option 2 selected");
    break;
  case 3:
    System.out.println("Option 3 selected");
    break;
  default:
    System.out.println("Invalid option selected");
    break;
}

In the above example the option selected is 3, so the text "Option 3 selected" will be displayed. For each case label, the value next to it is checked and if it matches the value 3 then it executes the code following the case label. You must include the break statement after the code you want executed, this will exit the switch statement so no other statements are executed. The case labels can only be integers or enumerated constants.

Looping

There are two versions of the while loop. With the first version the expression is evaluated first before entering into the loop:

while (expression)
{
  //Code, only executed while expression is true
}

The second version, do/while loop, does one iteration of the loop then evaluates the expression:

do
{
  //Code, executed once and while expression is true
}
while (expression)

Determinate Loops

The for loop allows you to loop through a block of code a specified number of times. After each loop the counter is incremented. The following code prints the numbers 1 to 10 to the console:

for (int i = 1; i <= 10; i++)
{
  System.out.println(i);
}

The expression within the parentheses is split into three sections. The first section initialises the counter, this can be done outside the the parentheses. The second section is the condition which specifies how long the loop will last. The last section controls how much the counter will be incremented by, this can contain any valid integral equation.


Another variation of the for loop is the enhanced for loop, which was introduced with JDK 5.0. This loop allows you to loop through a collection of elements (like an array) without setting up counters to control the loop. In the following example an array of integers called numbers has been created containing the even numbers below 10. It gets each int from the array, one at a time and the executes the code in the block.

for (int n : numbers)
{
  System.out.println(n);
}

Control modification

Java supplies a few keywords that allow you to alter the current flow of execution. Two of them, break and continue, allow you to exit out of loops and the other allows you to return a variable from a method.


There are two variations of the break statement. The first is an unlabeled break statement:

 break;

This code can be used to exit out of a loop or switch statement.

The other is a labeled break statement. This allows you to exit out of multiple nested loops. You achieve this by placing a label above the nested loops you want to exit out of, followed by a colon:

 restart:

then when a condition arises and you want to exit all the loops:

 break restart;


Like the break statement the continue statement has a labeled and unlabeled version.

 continue;

The continue statement skips all the remaining lines of code in the loop and starts the next iteration of the loop. For example, in a for loop in the continue statement is executed then it will begin the loop again on the next iteration. The labeled version:

  restart:
  continue restart;

The labeled version jumps to the header of the loop with the matching label and continues execution from there.


When a method returns a value the return keyword must be used.

 return variable;

When the return keyword is executed it returns the variable to the calling object and this indicates the end of execution for the method.

Exception Handling

For the following section on exceptions definitions will be given on each part of creating, throwing and catching exceptions.

Methods throw exceptions when a situation arises that is not within the normal process of execution. If a method throws an exception it must be declared within the method header:

public void OpenFile(String filename) throws FileNotFoundException
{
  //Code
}

This is useful for anyone looking up the method signature in the API, because they can instantly see that they may need to catch an exception if they use this method.

Once an exception has been thrown it can be caught or you can leave it. If you leave it then the program will terminate and display the exception along with a stack trace in the console. To catch an exception you need to include the following try/catch block around the code that can throw an exception:

try
{
  //Code that may throw an exception
}
catch (FileNotFoundException ex)
{
  //Code to handle the exception
}

So if an exception is thrown within the try block then normal execution stops and the code within the catch block is then executed. If the code within the try block does not throw an exception then the catch block is skipped. You can have multiple catch blocks that catch and deal with different exceptions individually. All that needs to be done is to add additional catch blocks.

Because execution stops once an exception is thrown important code can sometimes be skipped. This can become a problem when you are writing to files and then an exception is thrown, so the file remains open and could become corrupted if not closed properly. This is where the finally clause is useful. The code within the finally clause is always executed even if an exception is not thrown. So the code that is needed to save and close files can be written once in the finally clause and is guaranteed to be executed.

try
{
  //Code that can throw an exception
}
catch (ExceptionType ex)
{
  //Code to handle the exception
}
finally
{
  //Code is always executed
}

Useful Classes

Class Description
System.out Standard output stream. Allows you to print to the console.
Scanner Allows you to read primtive and strings from the command line.
Stack Creates a last-in-first-out (LIFO) stack of objects.
Hash Map Creates a key/reference list of objects that can be referenced by their key.
Enum Enumerates a set of values.

Links

Download link for source code:
Links to other resources/further information