introduction to java
This page gives a few helpful hints for those starting to learn Java.
- Links
- Documentation
- Primitives
- Operators
- Control Structures - while, if/else, for, return, break, continue
- Arrays and ArrayLists
- Making your Code Look Pretty - commenting, naming, indentation
- Stand-Alone Applications for People who know BlueJ
Links
Java is a complex language to learn and I can't cover all of the features here. Below is a handful of links which point to other places to get more information on the Java programming language.
- Sun's Java Webpage
- The Java Tutorial - Three complete books available online covering all the basics of Java
- Java 1.4.2 API Documentation
Documentation
The Java documentation is really good and should be your first port of call to find out how to use any of the built-in classes in Java. However, there are thousands of classes in Java which could make it difficult to find what you are looking for! Here's a list of common classes, sorted by package:
java.lang
- ArrayIndexOutOfBoundsException
- Boolean (boolean wrapper class)
- Byte (byte wrapper class)
- IllegalArgumentException
- Integer (int wrapper class)
- Math
- Object (superclass of all classes)
- String
- System (contains the System.out.println() method)
java.io
java.util
- ArrayList
- Collection (interface)
- HashMap
- HashSet
- Iterator (interface)
- LinkedList
- Random
java.awt
java.awt.event
- ActionEvent
- ActionListener (interface)
- MouseEvent
- MouseListener (interface)
- KeyEvent
- KeyListener (interface)
javax.swing
- JButton
- JCheckBox
- JComponent
- JFrame
- JLabel
- JMenu
- JMenuBar
- JMenuItem
- JOptionPane
- JPanel
- JRadioButton
- JTabbedPane
- JTable
Java Primitive Types
| Type | Description | Minimum | Maximum | Wrapper class |
|---|---|---|---|---|
byte | 8 bit signed integer | -128 | 127 | Byte |
short | 16 bit signed integer | -32768 | 32767 | Short |
int | 32 bit signed integer | -2147483648 | 2147483647 | Integer |
long | 64 bit signed integer | -9223372036854775808 | 9223372036854775807 | Long |
float | single-precision floating point | 1.4e-45 | 3.4028235e38 | Float |
double | double-precision floating point | 4.9e-324 | 1.7976931348623157e308 | Double |
char | 16 bit signed value (character) | 0 | 65535 | Character |
boolean | boolean value (true/false) | Boolean | ||
| Table 1. Properties of primitive types in Java. | ||||
Java Operators
Arithmetic Operators
Boolean Operators
Bitwise Operators
Operator Precedence
[] . ++ - parameters |
++ == + - ! ~ |
new type casts |
* / % |
+ - |
<< >> >>> |
< > >= <= instanceof |
== != |
& |
^ |
| |
&& |
|| |
?: (ternary if operator) |
= += -= *= /= %= >>= <<= >>>= &= |= ^= |
| Table 2. Java Operators ordered by precedence, with highest precedence at the top and lowest precedence at the bottom. |
|---|
Java Control Structures
Control structures is the name given to the things in Java that affect the flow of control of your program. They include for loops, if statements, while loops and so on. I will add a brief bit of information about each control structure as it is introduced on the module.
Java has three loop structures (while, for and do/while), two types of decision-making structures (if and switch), exception handling (try/catch/finally) and branching statements.
While loops
While loops are the simplest for of loops available in Java. A loop is a
block of code that (usually) executes more than once. In Java, a while loop
contains a condition which is checked before the loop is executed.
If the condition is true, the code in the block is executed,
otherwise the execution skips the while loop block and carries on.
The format of a while loop is:
while (condition) {
... // Code to execute if the condition is true
}
... // Code to execute when the condition becomes false
A simple example of a while loop is given below:
int counter = 0;
while (counter < 10) {
System.out.println("Counter is " + counter);
counter++;
}
This loop will execute 10 times before the condition (counter < 10) becomes
false:
Counter is 0 Counter is 1 Counter is 2 Counter is 3 Counter is 4 Counter is 5 Counter is 6 Counter is 7 Counter is 8 Counter is 9
Note that a while loop doesn't have to exccute at all - if the condition is
false to start with, the code in the block of the while loop
won't execute.
For loops
For loops are a convenient way of doing something a certain number of times. The syntax for a for loop is a little strange at first:
for (initialisation; termination condition; increment) {
... // Code to execute while the termination condition is false
}
The initialisation part is used to initialise the loop (usually by creating
a variable to count how many times we have looped). The termination condition
is checked just before the loop starts each iteration - if the condition is
true the code in the for loop block will execute. The increment
is used to modify the variable created in the initialisation part so that the
termination condition eventually becomes false.
Remember the while loop from earlier:
int counter = 0;
while (counter < 10) {
System.out.println("Counter is " + counter);
counter++;
}
This could be simplified by using a for loop:
for (int counter = 0; counter < 10; counter++) {
System.out.println("Counter is " + counter);
}
It should be possible to see where the various parts of the while loop translate into the for loop.
As with while loops, it is important to make sure that the termination
condition eventually becomes false. If not, then your code will
get locked into a perpetual loop! In the code above we can ensure this as
counter starts with a value less than 10 and is increased each
time the loop loops.
If statements
If statements are a convenient way of conditionally executing various blocks of code. They allow you to compare a boolean condition and the flow of control varies depending on the value of the condition.
The format of an if statement is:
if (condition) {
... // This code is executed if the condition is true
} else {
... // This code is executed if the condition is false
}
In the above example, either one thing or another could happen depending on
the value of the condition. In the simple example below, the value of a
variable, x, is compared. The output depends on the value
of x. You can try experimenting with different values of
x. What happens if x is 0? Or what about 5?
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is less than or equal to 5");
}
You are not restricted to a single condition though. Say we have a variable,
z, that could be 0, 1, 2 or 3. We want to do different things
depending on the value of z; if z is not 0, 1, 2 or
3 we want to print out an error message. Using the syntax above you might
well write something like this:
if (z == 0) {
System.out.println("z is 0");
} else {
if (z == 1) {
System.out.println("z is 1");
} else {
if (z == 2) {
System.out.println("z is 2");
} else {
if (z == 3) {
System.out.println("z is 3");
} else {
System.out.println("ERROR: z is not 0, 1, 2 or 3");
}
}
}
}
While this works fine, there's a simpler way of doing it using else if. Else
if allows you to have more than one condition to check. The important thing
to remember is that only one of the else if blocks will execute (unless the
condition isn't true for any of them). Here's the code to do
exactly the same thing as above but this time using else if:
if (z == 0) {
System.out.println("z is 0");
} else if (z == 1) {
System.out.println("z is 1");
} else if (z == 2) {
System.out.println("z is 2");
} else if (z == 3) {
System.out.println("z is 3");
} else {
System.out.println("ERROR: z is not 0, 1, 2 or 3");
}
Notice how much simpler it looks!
Another thing to point out is that you do not need to have the else block. In the example below, I have combined while loops and if statements to simulate a 24-hour clock with hours and minutes:
public class Clock {
int hours = 0;
int minutes = 0;
/**
* Constructor for a clock that allows you to set the time.
*
* @param hours the hours to set the Clock to.
* @param minutes the minutes to set the Clock to.
*/
public Clock(int hours, int minutes) {
this.hours = hours;
this.minutes = minutes;
}
/**
* This will start the Clock running forever and display the time every
* minute.
*/
public void startClock() {
while (true) { // this will loop forever (or until I quit the program!)
minutes++; // Next minute
// Check to see if we have got to the next hour
if (minutes > 59) {
hours++; // Next hour
minutes = 0;
}
// Check to see if we need to reset the hours to 0
if (hours > 23) {
hours = 0;
}
System.out.println("The time is: " + hours + ":" + minutes);
// Wait for a minute...
}
}
/**
* Main method
*/
public static void main(String[] args) {
// Create a new Clock and set the time to 10:00.
Clock clock = new Clock(10, 0);
// Start the Clock
clock.startClock();
}
}
Branching statements
Branching statements affect the flow of control in your program. They are used to break out of a loop, skip to the next iteration of a loop or to return a value. Branching statements should be used with care!
The most common branching statement is return. return is
essential for any method that has a return type where return is
used to return the value of the method. Indeed you must make sure that the
method returns something in this case!:
public int double (int num) {
return (2 * num);
}
return can also be used to terminate a method, for example if a
parameter is invalid:
/**
* Print out the square root of the given number if it is greater than 0
*/
public void sqrt(double num) {
if (num > 0) {
System.out.println("num must be greater than 0");
// Don't do anything else
return;
}
System.out.println("The square root of num is " + Math.sqrt(num));
}
To break out of a loop you can use the break statement. For
example, you might want to finish a loop early if you found the answer you
were looking for:
/**
* Look through the given array and find out if any element was true
*/
public boolean findTrue(boolean[] array) {
// Remember the result
boolean result = false;
for (int i = 0; i < array.length; i++) {
result = array[i];
// If the current element was true we don't need to look at any more
// of the array
if (result) {
break;
}
}
return result;
}
continue is used in a very similar way to break except
that rather than breaking out of the loop it just restarts the loop on the
next iteration
Arrays and ArrayLists
A common problem is getting confused with the difference between an array and an ArrayList.
To do
Making your Code Look Pretty
Nasty code is difficult to understand! For example, can you work out what this chunk of code does?:
class Div{static $1 $_;class $1{void _$(String $_){System.//
out.print($_);}$1(){_();}void _(){int _,$,_$,$$,__,ä=(1<<5),
å=100,ö=12,åö=ä*ö;å-=1<<4;while(åö>0){for($$=_$=_=__=$=(int)
å;_$>($$-(1<<2));_$(""+(char)(_$)),_$-=1<<1)for(_=$=__-9;_>(
$-6);_-=1<<1,_$(""+(char)(_$!=å?_:ä)));char S$=(char)(å+ö+1)
;_$("te"+S$+(char)(ö+(int)S$));åö--;}}}Div(){$_=new $1();}
public static void main(String []$){Div å=new Div();}}
(from http://www.gamedev.net/hosted/javaextreme/obfuscat.htm)
Which is why it is important to spend time making your code look pretty. It really is worth it, trust me! Here's a few pointers to help you along the way.
Comments
Comments are important. I know they are a pain in the backside to do, but they will help you in the long-run. In general you should make sure that your classes, attributes and methods are properly commented:
/**
* Simple class with some useful maths methods
*/
public class Utility {
// The value of pi
private double pi = 3.141593;
/**
* Return the square of a number
*
* @param num the number to square
* @return the square of num
*/
public int square(int num) {
return (num * num);
}
/**
* Calcuate the area of a circle with the given radius
*
* @param the radius of the circle
* @return the area of the circle
*/
public double circleArea(double radius) {
return (pi * square(radius));
}
}
Class/Attribute/Variable Names
Naming your classes and attributes is very important. Make sure that the names are meaningful and make sense in context. Calling an object of type Book fred for example makes no sense at all.
Indentation
Indentation is important if you want to write code that has more chance of working first time. A common mistake is to write too many or too few { } brackets or putting code in the wrong block - proper indentation can solve these problems!
To indent properly, remember that { } brackets always appear as a pair. They are used to delimit a block of code (e.g. a class or a method or the body of a for loop). Everything between a matching pair of { } brackets should be indented (4 spaces is a good idea) and the { } brackets should be aligned in the same column vertically.
Example of poor indenting:
public void countFalses(boolean[] array) {
int count = 0;
for (int i = 0; i < array.length, i++)
{ if (!array[i])
{
count++; } }
}
Same code, but properly indented:
public void countFalses(boolean[] array) {
int count = 0;
for (int i = 0; i < array.length, i++) {
if (!array[i]) {
count++;
}
}
}
Stand-alone Applications for People who know BlueJ
BlueJ is a good place to start when learning Java. It has the advantage of letting you experiment with objects in a kind of sandpit, allowing you to visualise object relations and interactions. However, it doesn't encourage you to write stand-alone applications that will run outside of BlueJ. To do that you need to either get dirty with your favourite text editor and a command-line compiler or use an integrated development environment (IDE) such as JCreator or Eclipse.
First off, an introduction to the main method.
The main method
The main method is a special method that indicates the entry
point of your program. When you run a Java application, it looks for the
main method in the specified class. Every Java application
must have a main method.
A main method looks like this:
public static void main (String[] args) {
... // Code
}
Compiling and running Java code from the command line
See http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html.
© 2000-06, Jonathan Stott.
06 Sep 2010 08:04:27
