Java By Example
An introduction to the Java programming language and the basic concepts of object oriented programming.
Contents
Lesson 1 - Introduction to JavaLesson 2 - Hello World
Lesson 3 - Basic Java Syntax
Lesson 4 - Basic Objects
Lesson 5 - More Java Syntax
Lesson 6 - Exception Handling
Lesson 7 - Advanced Objects
Lesson 8 - Java Beans
Lesson 1 - Introduction to Java
This lesson will introduce you to the Java programming language, and equip you with the knowledge needed to compile and run your first Java program.
1.1 What is Java?
- A free programming language from Sun Microsystems Inc.
- It is platform independent (Write Once Run Everywhere).
- A platform for application development.
- An object oriented programming language.
- Has an easy syntax. (Not as complex as C++)
- Has automatic garbage collection (Makes it hard to cause memory leaks.)
- Is a typesafe language.
- Has built-in multithreading support.
- Has built-in error handling.
- Is designed for TCP/IP networking (internet).
- Comes with a huge class library.
- Is dynamically linked at run-time.
- Supports development of standalone, client-server or browser-enabled applications.
1.2 Java Terms
Java Virtual Machine (JVM)
Essentially a software microprocessor that works as an abstraction over the hardware microprocessor. The JVM is what makes the Java platform independent, as it is available for all major platforms, and it interfaces uniformly to the Java application on all these platforms.
Class files
Compiled Java files that can be executed by the Java VM. A class file contains the instructions, a.k.a. byte-code that the JVM translates into corresponding native CPU instructions.
Classpath
Tells the JVM where to look for class files. Analogous to the DOS/WIN PATH that tells DOS/WIN where to look for executable files. The classpath may point to directories or Zip/Jar files.
Jar files
Essentially the same as a ZIP file. The JVM can look for class files directly in Jar or Zip files, provided they are listed in the classpath. Makes it easier to group, maintain and distribute Java class files.
1.3 Java Development Tools
Command line tools
- SUN JDK - Java Development Kit from Sun Microsystems themselves.
- IBM JDK - Equivalent from IBM but with IBM’s own VM.
Some Integrated Development Environments (IDE’s)
- Eclipse, www.eclipse.org
- IntelliJ IDEA, www.intellij.com
- Borland JBuilder, www.borland.com
We shall in this tutorial use the SUN JDK 1.4 that you can download free-of-charge from java.sun.com
1.4 SUN JDK
Installation
Download and install it from java.sun.com/j2se. Afterwards you will need to add the JDK bin directory to your standard path. I suggest that you modify your environment variables like this:
SET PATH=%JAVA_HOME%\bin;%PATH%
SET CLASSPATH=.;%JAVA_HOME%\lib\tools.jar
Important JDK files
- java.exe The JavaTM Virtual Machine (JVM).
- javac.exe Compiler for the JavaTM programming language.
- javadoc.exe API documentation generator.
- appletviewer.exe Run and debug applets without a web browser.
- jar.exe Manage Java Archive (JAR) files.
1.5 Java Resources on the Internet
The Java Tutorial
A very good place to start if you are new to the Java programming language. Also covers more advanced topics for the experienced developer. Get it here.
Java 2 SDK Documentation
Complete online documentation to the Java platform. Get it here.
Cafe au Lait Java FAQ's
Very good online Java resource from Metalab. Get it here.
Thinking in Java 3rd edition by Bruce Eckel.
Very good book that introduces you to Java and object oriented programming techniques. C++ programmers should definitely read appendix B: Comparing C++ and Java. You can download the book here.
Lesson 2 - Hello World
This lesson will show you how to write a simple Java program, how to compile it, and how to execute it.
2.1 Example I
The following file HelloWorld.java is one of the simplest Java programs that you can possibly write.
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
You may enter the program in any text editor, just make sure to save it as HelloWorld.java, because Java requires the filename to be identical to the class name including the case since Java is a fully case sensitive language. While we are at it; Java will also only allow you to define one public class per compilation unit (file).
Now compile and run the program using the SUN JDK from the command line like this:
javac HelloWorld.java | (Compiles the program as HelloWorld.class) |
java HelloWorld | (Executes HelloWorld.class) |
2.2 Example II
Let us try and extend the example a bit by adding a method to the HelloWorld class. This method, which we will call printMessage, simply prints the string passed to it through the parameter msg as shown in the code example below.
public void printMessage(String msg) {
System.out.println(msg);
}
public static void main(String[] args) {
HelloWorld helloWorldInstance = new HelloWorld();
helloWorldInstance.printMessage("Hello world!");
}
}
Note that we have not at all changed the functionality of the program, it still prints “Hello World!” on the screen. We have just changed the way to do it. In the first line of the main method, we define an object helloWorldInstance of type HelloWorld and assign a new instance of the HelloWorld class to it. In the second line we call the method printMessage on the newly allocated HelloWorld object, and as you can see we do not care about cleaning up any memory. This is taken care of by the garbage collector in the Java Virtual machine.
Lesson 3 - Basic Java Syntax
This lesson will introduce you to the basics of the Java syntax, which is actually very similar to the C++ syntax.
3.1 Java Keywords
The following words are reserved by the Java language as keywords and cannot be used as identifiers.
abstract | assert | boolean | break | byte |
case | catch | char | class | const |
continue | default | do | double | else |
extends | final | finally | float | for |
goto | if | implements | import | instanceof |
int | interface | long | native | new |
package | private | protected | public | return |
short | static | super | switch | synchronized |
this | throw | throws | transient | try |
void | volatile | while |
The keywords const and goto are reserved as keywords, even though they are not currently used in Java. This may allow a Java compiler to produce better error messages if these C++ keywords incorrectly appear in Java programs.
3.2 Primitive Types
The following list shows the predefined data types and their value range in the Java language, and they are all named by their reserved keyword.
boolean | true or false |
byte | 8-bit, from -128 to 127 |
short | 16-bit, from -32768 to 32767 |
int | 32-bit, from -231 to 231-1 |
long | 64-bit, from -263 to 263-1 |
char | 16-bit, from 0 to 65535 |
float | 32-bit, IEEE 754 floating point number. |
double | 64-bit, IEEE 754 floating point number. |
void | has no value. |
Did you wonder why the char data type is 16-bit and not 8-bit? In Java the char data type represents Unicode characters and not just ASCII characters. Finally you should also notice that Java does not have an unsigned identifier like C/C++ has.
3.3 Operators
The following 37 tokens are the Java operators, and almost all of them work with primitives only. The exceptions are ‘=‘, ‘==‘ and ‘!=‘, which work with all objects. The String class is a special case in the sense that it also supports ‘+‘ and ‘+=‘. Note, Operator overloading is not possible in Java!
= | Assignment. | & | Bitwise AND |
> | Greater than. | | | Bitwise OR |
< | Less than. | ^ | Bitwise XOR |
! | Logical NOT | % | Modulus |
~ | Bitwise NOT | << | Bitwise left-shift. |
? : | Ternary if-else | >> | Bitwise right-shift. |
== | Equivalent to. | >>> | Bitwise unsigned right-shift. |
<= | Less than or equal to. | += | Addition then assignment. |
>= | Greater than or equal to. | -= | Subtraction then assignment. |
!= | Not equivalent to. | *= | Multiplication then assignment. |
&& | Logical AND. | /= | Division then assignment. |
|| | Logical OR. | &= | Bitwise AND then assignment. |
++ | Auto increment. | |= | Bitwise OR then assignment. |
-- | Auto decrement. | ^= | Bitwise XOR then assignment. |
+ | Addition. | %= | Modulus then assignment. |
- | Subtraction and unary minus. | <<= | left-shift then assignment. |
* | Multiplication. | >>= | right-shift then assignment. |
/ | Division. | >>>= | U. right-shift then assignment. |
3.4 Execution Control
Java uses all of C‘s execution control statements, if-else, while, do-while, for, and switch. Below are some snippets of sample Java code that demostrates each control structure.
// do something
} else {
// do something else
}
for (int i=0; i<10; i++) {
// do something.
}
// 0 or more iterations.
}
// 1 or more iterations.
} while (a < b);
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': System.out.println("vowel");
break;
case 'y':
case 'w': System.out.println("Sometimes a vowel");
break;
default : System.out.println("consonant");
}
}
Lesson 4 - Basic Objects
This lesson will show you how to work with objects in Java, the very essence of Java and any other OO language for that matter.
4.1 The Class Definition
An object is an instance in the memory of a Java class that is defined by the reserved word class. The two examples below defines two empty classes Shape and Line where Line is derived from Shape, i.e. it inherits the properties of Shape. Shape is again derived from the class Object, although this is not very obvious. But Java enforces a singly-rooted class hierarchy, i.e. all classes are ultimately inherited from a single base class, simply called Object in Java.
public class Shape {
}
public class Line extends Shape {
}
4.2 Access Specifiers
Class attributes, methods and constructors can all be prefixed with one of three access specifiers; public, protected and private, with the following effects:
- public: Member is part of the class interface and is thus visible to everyone.
- protected: Member is only visible to the owning class and derived classes.
- private: Member is only visible to the owning class.
An access specifier may also be omitted to make the element package private
, which is the default access. Such elements are only visible to classes within the same package.
package dk.fastrup.demo;
public class Foo {
int w; // Visible to classes in the package dk.fastrup.demo
private int x; // Visible only to Foo itself.
protected int y; // Visible to Foo and any subclass.
public int z; // Visible to everyone.
void methodA() { ... } // Visible to classes in the package dk.fastrup.demo
private void methodB() { ... } // Visible only to Foo itself.
protected void methodC() { ... } // Visible to Foo and any subclass.
public void methodD() { ... } // Visible to everyone.
}