Getting started
To get started with java, one must download and install a version of Sun's JDK (Java Development Kit).
The newest release at the time of writting this article is JDK 6 downloadable from
http://java.sun.com/javase/downloads/index.jsp.
I will be using JDK 5(update 8)
but will in most cases will provide code that works on JDK 1.4 compilers as well.
I will also test some of the code on a 1.6 compiler.
The Java Development Kit
This is the tool that java programmers work with.
The chief components of the JDK are the following programming tools
javac - The compiler, which converts java source code(.java files) into Java bytecode(.class files).
java - This executes the java class files. It launches the Java application.
appletviewer - runs and debugs applets without the need of a web browser.
jar - The Java archiver, which packages related class libraries (and other files) into a single JAR file.
This is the executable for java programs.
javadoc - This tool generates documentation using comments in the source code.
jdb - The debugger
The JDK includes the (JRE) Java Runtime Environment. This consists of a Java Virtual Machine and the class libraries that will be present in the production environment including additional libraries useful to developers.
Setting the class path.
After successfully downloading and installing the JDK you need to set the class path.
By default the packages of the JDK standard API are accessible without needing to set the path.
Only the path for user-defined packages and libraries must be set either in the command-line or in the Manifest associated with the Jar file containing the classes(The second approach will
be revisited when we get to jar files).
How to set the class path depends on the operating system you are using.
You can get information on how to set class path for your OS version here
http://java.sun.com/j2se/1.5.0/docs/...classpath.html
The following article is a comprehensive discussion on the class path.
http://mindprod.com/jgloss/classpath.html
We will also revist the set up later when we have seen some of the JDK tools in action.
You will want to use an interface program like TextPad, JCreator, notepad++, etc for writting your code.
It is important to choose a tool you understand well. There are also IDEs like Netbeans(Available on the Sun site), however, you will want to use these only after you are fully conversant with the basic features of the language first.
Compiling Java code.
As mentioned earlier the javac tool is the one you use to compile Java classes. You invoke it by typing javac FileName.java on the prompt. If you are using a program like TextPad you simply click the compile java button and the tool is invoked. If the code does not have any errors, javac produces a class file called FileName.class for the above example. If the code has errors, they will be shown on the command prompt.
It is not neccessary to have a public class definition in a file. In this scenario, the file’s name should be different from the names of classes and interfaces which should not be public. In other words, files with no public classes can have a name that does not match any of the classes in the file.
This is because at most one public class definition is allowed per file.
The name of this class should match the file name. If there are more than one public class definitions, the compiler will accept the class with the file’s name and give an error at the line where the other class is defined. A blank file compiles without error (is a valid java source file).
javac error messages
Compilation errors are very important to a programmer. If the compiler outputs an error message during compilation, the class file is not produced. Compilation errors include a line number where the error has occured.
This should be very helpfull if your interface program has line numbers (a good interface program should have them and you should have them always enabled). When asking for help (eg in java forum always include the error message).
The next part will cover java basics and will contain java programs. So be sure you can compile and run java programs on your machine.
Java Basics
The approach in these articles is to get to program writting as soon as possible and then expand on the salient features of programming later on. One can easily understand those features if one has had some experience with writting programs.
Language structure
The Java programming language is a high level object-oriented language which is class-based and has support for concurrency. It is also strongly typed i.e it distinguishes between compile-time errors
(that can and must be detected at compile time), and run time errors (exceptions) that occur at run time.
The language is case sensitive and free-form(statements can reside anywhere on a line, cross over lines or any number of blank spaces are allowed between tokens)
Statements are terminated by a semi-colon ( ; ). A java file consisting only of semi-colons is a valid java source file.
For a java application to run, the class being run must contain the main method with the following signature:
Expand|Select|Wrap|Line Numbers
- public static void main(String[] args)
Expand|Select|Wrap|Line Numbers
- public static void main(String ... args)
Key words
As of jdk 1.5, the following is the set of java keywords.
{abstract, continue, for, new, switch, assert, default, if,
package, synchronized, boolean, do, goto, private, this, break,
double, implements, protected, throw, byte, else, import, public,
throws, case, enum, instanceof, return, transient, catch, extends,
int, short, try, char, final, interface, static, void, class,
finally, long, strictfp, volatile, const, float, native, super, while}
const and goto are reserved, even though they are not currently
used. We will look at the other keywords later on.
Primitive types
Java has the following eight primitive types:
boolean, byte, short, char, int, long, float and double.
You should have a table of their
minimum, maximum and initial values with you.
Literals have their size checked at compile time.
Expand|Select|Wrap|Line Numbers
- byte b = 128; //will not compile (Maximum value of byte is 127) but
- byte c = 127; //will compile
Literals
For now I will say a literal is a value of a primitive type (source code representation) or null or the String type(This will be examined in the later).
Literals are not keywords. i.e null, true, false etc are not keywords.
Unicode
It is wise to learn a bit of unicode if you want to become a serious programmer.
For now I will say that unicode characters can appear anywhere in java code. They are prefixed by \u and are four characters long. e.g "a" is represented by \u0061. You can substitute "a" with "\u0061"
in your code and it will still compile. Thus the following are equivalent:
Expand|Select|Wrap|Line Numbers
- boolean b = true;
- boole\u0061n b = true;
Separators
The following nine ASCII characters are the separators (punctuators):
( ) { } [ ] ; , .
Operators
The complete set of operators is:
= > < ! ~ ? :
== <= >= != && || ++ --
+ - * / & | ^ % << >> >>>
+= -= *= /= &= |= ^= %= <<= >>= >>>=
Arithmetic operators - *, /, %, +, - can be applied to numeric types only (at least int) except + which can also be applied to String literals.
Extended assignment operators and ++, -- operators perform implicit type casting.
Expand|Select|Wrap|Line Numbers
- byte a = 12;
- a = a + 1;
Expand|Select|Wrap|Line Numbers
- byte a = 12;
- a++;
Note that
Expand|Select|Wrap|Line Numbers
- byte b = 127;
- b++;
- System.out.println(b);
The operators && and || are short circuit logical operators. If the value of the first operand is sufficient for determining the value of the whole expression, the right hand side is not evaluated.
Expand|Select|Wrap|Line Numbers
- boolean s = true;
- boolean t = true;
- if((t = false) && (s = false) ) {
- ;
- }
- System.out.println(t);
- System.out.println(s);
Expand|Select|Wrap|Line Numbers
- false
- true
You should experiment with the rest of the operators especially the shift operators to understand their functions.
You should also be aware of the associativity of each operator.
eg
Expand|Select|Wrap|Line Numbers
- System.out.println( 1 + 2 + "3" ); // Prints 33
- System.out.println( "1" + 2 + 3 ); // Prints 123
We will look at the instanceof operator after we've covered inheritance.
Identifiers
Identifiers are the names you give to your variables. A java identifier must begin with a letter, dollar sign ($) or underscore (_). Subsequent characters may be letters, $, _ or digits.An identifier cannot have a name of a Java keyword, or be a literal.
Embedded keywords or literals are allowed
Java types.
Every variable and every expression has a type that is known at compile time(strongly typed).
There are two broad types in Java: Primitive types and reference types.
Type : PrimitiveType, ReferenceType
PrimitiveType : NumericType, boolean
ReferenceType : Class, Array, Interface
NumericType : IntegralType, FloatingPointType
IntegralType : int, long, char, byte, short
FloatingPointType : float, double
That's all I'll cover now for primitive types. Up next is the Class type.
The Java Class
What is a class?
A class defines a new reference type and how that type is implemented.
The best way to look at a class for now is that it is a template for making objects. A class is therefore different from an object. An object is like the implementation of a class. You can define one class and create many different objects using that same class. Classes are created at compile time and objects are created at runtime in memory. A class specifies both the properties and actions that an object can perform. The properties are specified as fields while the actions are specified as methods. Designing classes is very important during program development. If you design your classes and the relationships between your classes well, you'll find it very easy to solve real worl problems with Java. Class relationships are specified through inheritance and composition. These two are very important and should be mastered.
Encapsulation
A simple definition of encapsulation is combining elements to create a new entity. The idea is to hide certain information so that there is a separation of concerns. Code is grouped together into modules such that no code exists outside of a module. Java supports encapsulation directly in that every line of code that you write has to be in some class. No code exists outside a class. This has several consequences which will become obvious along the way. One consequence is that no object can be created if the code does not have a class.
Next we'll discover that no class exists outside a package.
Java packages
Packages are a way of organizing files into different directories according to their functionality, usability and categories that they belong to. This has the advantages of ease of maintenance, organization and (as an extra) allow us to reuse the same class name in a different package. Think of a package as a folder containing classes. If you type the following in your text editor and save it as PackageTest.java
Expand|Select|Wrap|Line Numbers
- package test;
- class PackageTest {
- public static void main(String[] args) {
- System.out.println("Tested");
- }
- }
was not found. If however, you create a folder called test and put the file in this folder and compile and run it you get "Tested" printed to the console. The JVM requires the fully-qualified class name to load the class so you needed to use java test.PackageTest to run it. Alternatively, you can specify the location of the .class using the classpath variable.
To use a package's classes, import them in your code using import statements. Package declaration comes before import statements. Many packages have already been created for you to import and use in your code.
You should always try to take advantage of the classes in the java api here . The compiler automatically imports the java.lang package for you.
Class structure
A class declaration starts with a modifier which can be any of
public, protected, private, abstract, static, strictfp, final.
To get us started we'll look at the public and protected modifiers first.
Java classes are encapsulated into packages. Classes in one package can only access public classes in another package. Protected classes are accessible only within the package that they have been defined. If you do not include a modifier, protected access is assumed. The class is put inside the default package which is automatically created for you.
You should always put your classes in a package. Here is the rest of the structure of a Java class:
Modifier(s) class ClassName {
members(methods, fields, nested classes and interfaces)
constructors
static initializers
}
Each of these three componets are optional.
static keyword.
If a variable (including method) is defined as static inside a class, that variable belongs to that class but is not part of instances (objects) of that class(Memory is not allocated for the static variables when the object is created).
Therefore the static variable can be accessed without creating an object of that class.
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- static int members;
- public static void main(String[] args) {
- System.out.println(members); //or Church.members
- }
- }
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- static int members;
- public static void main(String[] args) {
- System.out.println(Church.members);
- }
- }
Only static variables are accessible inside a static context.
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- static int members;
- int pastors;//pastors is not static
- public static void main(String[] args) {//main is a static context(modified by keyword static)
- System.out.println(Church.members);
- System.out.println(Church.pastors);//! will not compile
- }
- }
The static initializers are always resolved first before the program runs
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- static int members;
- public static void main(String[] args) {
- System.out.println(Church.members);
- System.out.println(Church.pastors);
- }
- static int pastors = 5;
- }
The Math class contains a lot of static methods which you can reuse. It is in the java.lang package so you do not need to import anything to be able to use it.
Expand|Select|Wrap|Line Numbers
- package tests;
- class EasyMath {
- public static void main(String[] args) {
- System.out.println(Math.PI); //static constant
- System.out.println(Math.pow(2, 6)); //static mothod
- }
- }
Creating objects.
So far we have not been creating any objects. Objects are created at runtime from classes that were created at compile time. The new keyword is used to create objects.
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- static int pastors;
- public static void main(String[] args) {
- //System.out.println(Church.pastors);
- Church c = new Church();
- }
- }
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- int pastors;
- public static void main(String[] args) {
- Church c = new Church();
- System.out.println(c.pastors);
- }
- }
to the screen. Notice that pastors is no longer accessible through class name but only from dereferencing the object c.
We can add more variables of different data types to the field area and each would become part of any object created
from that class.
Methods
Methods have a return type and a signature. A signature consists of the method name, the number of arguments and the order of the arguments. A method can return at most one value. You cannot have two methods with the same signature in the same class.
Notice therefore that
Expand|Select|Wrap|Line Numbers
- void a (int x, double y)
Expand|Select|Wrap|Line Numbers
- void a (double x, int y)
We have already had a look at class methods which are static methods. Remember they can only access static variables.
Instance methods (non-static) execute in the context of a particular object. They operate on the current object's instance variables and can refer to the object itself using the 'this' keyword.
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- int pastors;
- public static void main(String[] args) {
- Church c = new Church();
- c.setPastors(10);
- c.printPastors();
- }
- public void setPastors(int p) { //returns nothing takes one int
- pastors = p;
- // or this.pastors = p;
- }
- public int getPastors() { //returns int takes nothing
- return pastors;
- }
- public void printPastors() { //returns nothing takes nothing
- System.out.println(pastors);
- }
- }
Constructors
The other part of a class is a constructor. Note that unlike C++ there are no destructors in java. A constructor is used in the creation of an object. When you create a new instance of a class using the new keyword, a constructor for that class is called.
Constructors are used to initialize the instance variables (fields) of an object. They are similar to methods, but with some important differences. Constructors do not have a return type (the value is always this object). They must have the same name as the class they are in. Every class has at least one constructor. If you don't define a constructor for a class, (like we did in the examples above) a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (we'll examine this in the next lesson on inheritance) and initializes all instance variables to default values (zero for numeric types, null for object references, and false for booleans). Note that the default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created. So
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- public static void main(String[] args) {
- Church c = new Church();//calls default no-arg constructor automatically created by compiler
- }
- }
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- public Church(long a) {
- }
- public static void main(String[] args) {
- Church c = new Church();//calls default no-arg constructor automatically created by compiler
- }
- }
creation of the no-arg constructor. You can define as many constructors as you feel are necessary as long as they have different signatures.
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- int pastors;
- public Church() {// initializes pastors to 0
- pastors = 0;
- }
- public Church(int pastors) {// initializes pastors to the given value
- this.pastors = pastors;
- }
- public static void main(String[] args) {
- Church c1 = new Church();
- c1.printChurch();
- Church c2 = new Church(10);
- c2.printChurch();
- }
- public void printChurch() {
- System.out.println("Church with :" + getPastors() + " Pastors");
- }
- public int getPastors() {
- return pastors;
- }
- }
Expand|Select|Wrap|Line Numbers
- public Church(int pastors) {// initializes pastors to the given value
- this.pastors = pastors;
- }
You should use the constructor to initialize variables only.
A constructor can call another constructor in the same class (or in a different class. This will be examine in the next class on inheritance).
To do this you use the 'this' keyword. This must be the first line of the constructor.
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- int pastors;
- int members;
- public Church() {
- pastors = 0;
- members = 0;
- }
- public Church(int pastors) {
- this(); // calls the default constructor so members is also initialized to 0.
- this.pastors = pastors;
- }
- public Church(int pastors, int members) {
- this(pastors); // calls the one-arg constructor so pastors has been initialized.
- this.members = members;
- }
- }
The final keyword
Use the modifier to denote that a variable is assigned a value at most once. The compiler will not allow you to assign a value to a final variable twice.
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- final int pastors;
- public Church() {
- pastors = 0;
- }
- public Church(int pastors) {
- this.pastors = pastors;
- this.pastors = 2; //! will not compile
- }
- }
If you declare a final variable as a member variable of a class without initializing it, then that final variable must be initialized in every constructor of that class otherwise the compiler will give an error.
Expand|Select|Wrap|Line Numbers
- package religion;
- class Church {
- final int pastors;
- public Church(int pastors) {
- this.pastors = pastors;
- }
- public Church() { //! will not compile (variable pastors might not have been initialized)
- }
- }