Java Tutorial for Beginners

 

Java Language Basics

A Java program consists of one or more classes. Classes can be defined by you, or they can be predefined classes, either from the standard Java libraries, or from third-party Java libraries.

Classes consist of a class header and a class body. The body, enclosed in braces {}, can contain data declarations and methods.

Methods could be described as named groups of actions. Each method in a class consists of a method header, followed by a list of actions that make up the method. We've already had a brief look at class and method headers. We'll look a bit more closely at actions shortly.

The data declarations define variables and constants that will be used by the program. For those not familiar with programming terms, you can think of a variable as being a place where you can store a piece of data. All variables must be declared - in other words, you must give them names, and specify what type of data will be stored in them. Constants are similar to variables, except that they are given a value when they are declared, and that value never changes. You may, for example, define a variable to store the value of the mathematical constant Pi.

Data declarations can also be included inside a method. If data is declared within a method, it can only be used by that method. However, if data is declared within the class, but not within a method, that data can be used by any method within the class. Variables declared outside methods are known as class variables. They are also known as properties of the class, since they store information belonging to the class. In fact, the rule is that variables can only be used within the same block in which they are declared. A block, as I mentioned earlier, is a bunch of Java statements surrounded by braces {}.

Data declarations give a name, a data type and optionally a value for each item of data that the program needs.

Data names are given by you, the programmer. They are usually made up of letters, numbers and underscores. They cannot contain spaces.

Java defines 8 primitive data types. More complex types of data can be used in Java, but must be defined by a class. The primitive data types are:

Description

Type

Details

Integer data types

(No decimal places allowed)

long

Long integers occupy 8 bytes, and are capable of storing signed numbers 18-19 digits in length.

 

int

These occupy 4 bytes, and store signed numbers 8-9 digits in length.

 

short

Short integers occupy 2 bytes, and store numbers in the range –32768 to +32767.

 

byte

Byte variables occupy 1 byte and store numbers in the range –128 to +127

Floating point data types

float

Float variables occupy 4 bytes. They can be used to store numbers with fractional parts.

 

However, since the fractional part is stored as a binary fraction, and binary fractions do not always convert exactly to decimal fractions, there may be some rounding errors This makes them unsuitable for storing currency values for accounting functions.

 

Float variables store 6 to 7 significant digits with a range of approximately ±3.4E+38

 

double

This is a double precision floating point variable occupying 8 bytes. As with Float, it is stored as a binary fractions. Doubles have 15 significant digits and can store numbers in the range of approximately ±1.8E+308

Character data

char

This stores a single Unicode character occupying two bytes. Unlike C, character variables in Java cannot be used for arithmetic. They can, however, be converted to and from the integer data types to obtain a numeric Unicode value. Unicode is a 2-byte extension of the Ascii character set catering for multi-language characters.

Boolean data types

boolean

This is used to store a boolean value of true or false, and can be used in Java statements to make program decisions. It occupies 4 bytes. Unlike C, the boolean data type is not compatible with the numeric data types, and cannot be converted to or from them.

 

Additionally, there is a pseudo data type called String. Although String is actually a class, in many ways it behaves like an ordinary data type. It is used to store and manipulate character strings.

To be able to write a Java program, we now need to know how to code data declarations, and also how to code the actions that make up a method.

Let’s look at another sample program. This one calculates the average of all the numbers between 1 and 4. Not terribly useful, but it serves to illustrate a few points.

public class Averages
{

public static void main(String[] args)
{
float total, average;
total=1+2+3+4;
average=total/4;
System.out.println(“The average of the numbers 1 to 4 is:”);
System.out.println(average);
}

}

Notes:

  1. The line 

float total, average;  

is a data declaration. First of all, a data declaration must specify the data type of the variable. In this case, the data type is float. Secondly, a data declaration must give a name to the variable. If we have several data items of the same type, we can simply provide a list of names of all all items of this type, separated by commas. So here we have two floating point numbers that we will call total and average. Finally, the data declaration must be terminated with a semi-colon.

  1. The lines 

        total=1+2+3+4;
        average=
total/4; 

are actions. This particular type of action is called an assignment, since it assigns a value to a variable. This assignment consists of literals and arithmetic operators. A literal is an actual supplied value – in the first of these lines we have supplied the values 1,2,3 and 4. An arithmetic operator causes arithmetic to be carried out on the supplied values. In this case, we are using the plus sign (+). We can also use others, such as – for subtraction, * for multiplication and / for division. 

So the first of these lines carries out the sum 1+2+3+4, and places the answer in the variable total, which now contains 10. The second line takes the value held in total, divides it by 4, and places the answer in the variable average, which will then contain 2.5. Note that actions must also be terminated by semi-colons. 

  1. The lines: 

      System.out.println(“The average of the numbers 1 to 4 is:”);
      System.out.println(average); 

are also actions, but a different kind. This type of action is a method call. It invokes another method – in other words, it goes away and carries out all the actions that make up that method, then comes back again. Methods can be called from the current class, or from a different class. If they belong to another class, the name of the method must be prefixed by either the name of the class, or the name of an object created from that class. (We’ll talk more about creating objects a bit later.) Here we are calling a method called println that belongs to the class System.out. System.out is one of the standard Java library classes, and the println method displays the message supplied inside the brackets on the screen. The first of these lines tells it to print the literal character string The average of the numbers 1 to 4 is: . Note that string literals must be enclosed in double quotes. Single character literals, by the way, should be enclosed in single quotes. The second line tells it to print the contents of the variable average. 

Try typing in this program and running it. Then see if you can write a new program of your own that will display the result of multiplying together all the numbers between 2 and 7.

Using Methods from the Java libraries

The Java libraries are what makes Java so powerful. There are library classes for almost every conceivable programming task, from creating interactive Web pages down to mathematical and scientific functions. Here we’ll look at a program that makes use of a few methods from library classes. As yet, we haven’t learnt how to create an object from a class. We learn that in the next chapter. But some classes have methods that can be used, even when no object has been created from the class. These are called static methods. Let’s have a look at a simple program that illustrates this.

This program calculates simple monthly interest on a loan rounded to the nearest dollar, given the amount of the loan and the annual interest rate.

public class interest
{

public static void main(String[] args)
{
double loan, rate, mthlyInt;
loan=Double.parseDouble(args[0]); // First argument is the loan
rate=Double.parseDouble(args[1]); // Second argument is the rate
mthlyInt=
Math.round(loan*rate/1200);
System.out.println(“Interest is “+mthlyInt);
}

}

Notes:

  1. The line 

float total, average;  

is a data declaration. First of all, a data declaration must specify the data type of the variable. In this case, the data type is float. Secondly, a data declaration must give a name to the variable. If we have several data items of the same type, we can simply provide a list of names of all all items of this type, separated by commas. So here we have two floating point numbers that we will call total and average. Finally, the data declaration must be terminated with a semi-colon.

  1. The lines 

      total=1+2+3+4;
      average=
total/4; 

are actions. This particular type of action is called an assignment, since it assigns a value to a variable. This assignment consists of literals and arithmetic operators. A literal is an actual supplied value – in the first of these lines we have supplied the values 1,2,3 and 4. An arithmetic operator causes arithmetic to be carried out on the supplied values. In this case, we are using the plus sign (+). We can also use others, such as – for subtraction, * for multiplication and / for division. 

So the first of these lines carries out the sum 1+2+3+4, and places the answer in the variable total, which now contains 10. The second line takes the value held in total, divides it by 4, and places the answer in the variable average, which will then contain 2.5. Note that actions must also be terminated by semi-colons. 

  1. The lines: 

      System.out.println(“The average of the numbers 1 to 4 is:”);
      System.out.println(average); 

are also actions, but a different kind. This type of action is a method call. It invokes another method – in other words, it goes away and carries out all the actions that make up that method, then comes back again. Methods can be called from the current class, or from a different class. If they belong to another class, the name of the method must be prefixed by either the name of the class, or the name of an object created from that class. (We’ll talk more about creating objects a bit later.) Here we are calling a method called println that belongs to the class System.out. System.out is one of the standard Java library classes, and the println method displays the message supplied inside the brackets on the screen. The first of these lines tells it to print the literal character string The average of the numbers 1 to 4 is: . Note that string literals must be enclosed in double quotes. Single character literals, by the way, should be enclosed in single quotes. The second line tells it to print the contents of the variable average. 

Try typing in this program and running it. Then see if you can write a new program of your own that will display the result of multiplying together all the numbers between 2 and 7. 

Using Methods from the Java libraries

The Java libraries are what makes Java so powerful. There are library classes for almost every conceivable programming task, from creating interactive Web pages down to mathematical and scientific functions. Here we’ll look at a program that makes use of a few methods from library classes. As yet, we haven’t learnt how to create an object from a class. We learn that in the next chapter. But some classes have methods that can be used, even when no object has been created from the class. These are called static methods. Let’s have a look at a simple program that illustrates this.

This program calculates simple monthly interest on a loan rounded to the nearest dollar, given the amount of the loan and the annual interest rate.

public class interest
{

public static void main(String[] args)
{
double loan, rate, mthlyInt;
loan=Double.parseDouble(args[0]); // First argument is the loan
rate=Double.parseDouble(args[1]); // Second argument is the rate
mthlyInt=
Math.round(loan*rate/1200);
System.out.println(“Interest is “+mthlyInt);
}

}

The program allows the user to enter the loan amount and the annual interest rate as arguments in the command line. Later, we’ll look at other, and better, ways of allowing the user to enter data into the program. But command line arguments are easy to deal with in Java, so we’ll use these in the next few examples. The program then calculates and displays the monthly interest.

Let’s look at the main method line by line:

double loan, rate,mthlyInt;
This declares three variables needed by the program.

loan=Double.parseDouble(args[0]);
rate=Double.parseDouble(args[1]);
The command line arguments are received by the program in the array of strings named args that are defined in the method header of the method main. The first of these, the loan amount, will be found in args[0], and the second, the interest rate, in args[1]. Elements in an array are always numbered starting from 0. To convert these strings to binary numbers compatible with the primitive data type double, we use a method from one of the library classes, Double. The method parseDouble checks that a string contains a valid number, and, if so, converts it to data type double. So the variables loan and rate now contain the amount of the loan and the annual interest rate.

 

mthlyInt=Math.round((loan*rate)/1200);
This uses the formula (loan*rate)/1200 to calculate the monthly interest. It then uses the round method of the Math class to round it to the nearest dollar.

 

System.out.println(“Interest is “+mthlyInt);
This diplays the text “Interest is” followed by the contents of the variable mthlyInt. 

When running the program, the loan amount and the interest rate must be entered as command line arguments. To do this in Eclipse, after typing in and saving the program, choose Open Run Dialog from the Run menu. Click on the Arguments tab, and enter the arguments as shown below. Then click Run to run the program.

 

To enter command line arguments when running the Java program from the command prompt, simply type the arguments after the program name, as shown below: 

java interest 1500 8 

Documentation on the various library classes and the methods available in each can be found on the Java website at http://java.sun.com/javase/6/docs/api/. There are many hundreds of Java classes. This short tutorial will look at using just a very few of them. To become an expert Java programmer, you will need to learn to work with the Java documentation. You’ll get some practice at doing that in some of the later examples.

Making Program Decisions

As with most programming languages, the flow of Java programs can be controlled with conditional statements, loops or switches. There is no GOTO in the Java language.z 

Conditional statements are coded according to one of the following:
if (condition) statement; 

or 

if (condition) statement;
else              statement; 

or 

if (condition) {block of statements) 

or 

if (condition) {block of statements}
else {block of statements} 

The condition can be used to select either a single statement or a block of statements.
condition is any valid boolean expression. Boolean expressions are a way of expressing the criteria for a program decision. Most conditions are expressed by comparing one thing to another. For example, we can compare a variable containing the type of customer to the literal value ‘Dealer’. If they are equal, we want to give the customer discount. Assume that the customer type is stored in a variable named CustType and the discount is stored in a variable named discount. 

if (CustType==”Dealer”)
       discount= (AmtDue * 0.1);
else
       discount = 0;
Note the double equal sign used in the condition. Java uses a double equal sign for comparisons. A single equals sign is used for assignments. 

if (FinalMark < 50) Result = “Fail”;
else Result = “Pass);
uses the value of the variable FinalMark to decide on the value to be placed in the variable Result. 

You can compare a variable to a literal, to another variable, to an arithmetic expression, or to the value returned by a method. You can also use a variable of data type boolean to make a decision, since these variable contain a value of either true or false. 

You can also join two or more conditions together using boolean operators. && represents ‘and’, || represents ‘or’, and ! represents ‘not’. The following code checks that there is enough stock available and the customer has not exceeded his credit limit, in order to decide between calling methods to either create an invoice, or reject the invoice. 

if ((SaleQty <= StockQty) && (SaleValue <= CreditAvail))
{
  StockQty = StockQty - SaleQty;
  CreditAvail = CreditAvail - SaleValue;
  Invoice.Write();
}
else Invoice.Reject(); 

This is probably a good time to include a summary of all the operators that can be used in coding statements in a Java program. See the table below. 

Comments

Comments in Java programs can take three forms:

 

 

//

Indicates that the rest of the line should be treated as a comment.

 

/*

Indicates the beginning of a comment block which may span more than one line.

 

*/

Indicates the end of a comment block begun with either /* or /**

 

/**

Indicates the beginning of a comment block which can be used to form part of the program documentation. The utility javadoc can be used to build program documentation from these comment lines.

 

Operators

There are many different operators available in Java. These are classified below.

 

Arithmetic

+

Addition. Note: the + sign can also be used for string concatenation.

 

-

Subtraction

 

*

Multiplication

 

/

Division. If both of the operands are integer, integer division with truncation is carried out; otherwise, the answer will contain fractional parts.

 

%

Modulus. This will give the remainder portion of an integer division carried out on the two operands e.g. 15 % 6 would give the answer 3.

 

Note that there is no exponential (to the power of) operator. A method of the Math class can be used to achieve this, as detailed in Chapter 4.

Increment and Decrement

var++

Where var indicates a variable name, var++ will increment the contents of the variable by 1. This will be done after the variable has been used in the expression, so that after the following statements:

int n = 5;

int x;

x=3*n++

n would contain 6, since it has been incremented, and x would contain 15, since it is calculated using the value of n before incrementation.

 

var--

This works in the same way as var++, except that the contents of var would be decremented by 1.

 

++var

This increments the contents of var before var is evaluated for the expression, so that after the following statements:

int n = 5;

int x;

x=3*++n

n would have the value of 6, and x would have the value of 18, since the incremented value is used in evaluating the expression.

 

--var

This works in the same way as ++var, except that var is decremented by one.

Relational and Boolean

==

This tests for equality. The double equals sign avoids confusion with the single equals sign used for assignments.

 

!=

Not equal to

 

> 

Greater than

 

< 

Less than

 

>=

Greater than or equal to

 

<=

Less than or equal to

 

!

Not

 

&&

And

 

||

Or

Bit manipulation

&

Logical And

 

|

Logical Or

 

^

Exclusive Or

 

~

Not

 

>> 

Bit shift right, extending sign bit

 

<< 

Bit shift left

 

>>> 

Bit shift right, extending with zeros

Condition

?

This is used within an assignment to choose between two possible values. Its usage is as illustrated in the following example:

SalesTaxPercent=(TaxDue=='Y')? 20:0;

The condition TaxDue==’Y’ is used to decide whether to place the value 20 or the value 0 into SalesTaxPercent.

Shortcut

Programs often need to use the current value of a variable in calculating its new value, for example

x=x+10

This can be shortened to

x=+=10

in Java. This produces the same result as the first example.

 

This shortcut can be used with most of the arithmetic and bit manipulation operators, so that the following are valid:

+=; -=; *=; /=; %=; &=; |=; ^=; <<=; >>=; >>>=

Order of evaluation

Java assignments can become extremely long and complicated, often using several operators in a single statement. It is therefore important to understand the order of evaluation.

 

The table below lists the different levels in the order of evaluation to which each operator belongs. Those at a higher level will always be carried out before those at a lower level.

 

 

Method calls

 

Brackets, !, ~, ++, --, Unary plus and minus (ie sign associated with a number), cast

 

*, /, %

 

+,-

 

<<,>>,>>>

 

<, <=, >, >=

 

==,!=

 

&

 

^

 

|

 

&&

 

||

 

?

 

=,+= and other equivalent shortcuts

 

 

Brackets may always be used to control the order of evaluation.

 

Making Program Decisions

The main advantage of computers is that they can carry out repetitive tasks very quickly. To do this, we need to be able to repeat an action or group of actions many times. There are several ways of doing this in Java.

The for .. loop is generally used when a statement or block of statements needs to be executed a fixed number of times.

The syntax is:
for (InitiationStatement; Condition; IncrementationStatement)
statement;
or
for (InitiationStatement; Condition; IncrementationStatement)
{block}

The initiation statement is usually used to set a counter to an initial value; often 0. The condition is checked before each cycle of the loop; when the condition becomes false, the loop terminates.

The incrementation statement is used to increment the counter after each cycle of the loop. A simple increment (eg i++) can be used to increment the counter by 1, or any assignment expression can be used to increment it by some other value.

The following example prints the square of all the numbers between 1 and 10.

public class Squares
{

public static void main(String[] args)
{
for (int i=1; i<11;i++)
System.out.println(+ i + " squared is " + i*i);
}

}

/* Note: The + operator is used in the println method to concatenate the items to be printed. Since a string is expected here, and the first item to be printed is an integer, the concatenation operator precedes it to convert it to a string. */

The variable i is used as a counter to step through all the values between 1 and 10.

Try typing this program in and running it. Then try modifying it to print the squares of all the numbers between 20 and 30.

Additional Tip: The break statement can be used within a Java loop to break out of the loop prematurely. It will cause execution to continue with the next statement after the loop.

The while loop is used to repeat a statement or group of statements while a condition remains true. The condition is tested before any of the statements are executed, so that if the condition is false at the outset, the loop will not be executed at all.

Example:
while (MoreEntries)
Entry.Process;

The do....while loop is similar to the previous type of loop, except that the condition is checked after processing the statement or block of statements, so that it will always be executed at least once, even if the condition is false at the outset

The following program illustrates the use of the do....while loop. It also illustrates using the boolean data type, and the use of the break command.

Sample Program: Check for Prime Numbers

/* ******************************************
* This program will take a number *
* from the command line, and check *
* to see whether it is a prime number *
* **************************************************/

public class prime
{

public static void main(String[] args)
{
int NumIn, Counter;
double NumRoot;
NumIn = Integer.parseInt(args[0]);

/* ******************************************
* Factors between 2 and the square *
* root of the number entered will be *
* searched for *
* ******************************************/
NumRoot=Math.sqrt(NumIn);
Counter=2;
boolean Factorised=false;
String Result;

do
{

if (Counter > NumRoot) // Factors cannot be greater
break; // than the square root
if(NumIn % Counter == 0) // If dividing by the counter gives
Factorised=true; // remainder 0, a factor was found
Counter ++;
}
while (! Factorised);

if (Factorised)
System.out.println(+ NumIn + " is not a prime number");
else
System.out.println(+ NumIn + " is a prime number");
}
}

When running this program, enter the number to be checked as an argument. The program will tell you whether it is a prime number.

Using the switch statement

The switch is used to select alternate program paths depending on the value of a variable. In some cases, this is easier than using a lot of if statments to check the contents of the same variable.

The general syntax is:

switch(variablename)
{
case value:
statement …..;
break;
case value:
statement …..;
break;
etc
default:
statement …..;
break;
}

The contents of variablename are tested against each of the case values listed. If a match is found, the statements between the matching case and the next break are executed.

A case with its relevant statements would be coded for each value which is of interest to the program. Optionally, a default can be included. The statements listed under the default will be executed if there are no matches.

Sample program using switch:

// *****************************************************
// * This program will carry out a calculation *
// * entered on the command line. The calculation *
// * should be entered as a number, followed by a *
// * space, followed by an operand, followed by a *
// * space and a number. Valid operands are +,-,x *
// * and /. *
// *****************************************************
public class calc
{

public static void main(String[] args)
{
double Num1, Num2, Ans=0;
char Op;
Num1=Integer.parseInt(args[0]); //First argument is a number
Op=args[1].charAt(0); //First character of second
//argument is the operand
Num2=Integer.parseInt(args[2]); //Third argument is a number

// *********************************************************
// Decide on the correct calculation depending on *
// the operand entered *
// **********************************************************

switch(Op)
{

case '+':
Ans=Num1+Num2;
break;
case '-':
Ans=Num1-Num2;
break;
case 'x':
Ans=Num1*Num2;
break;
case '/':
Ans=Num1/Num2;
break;
default:
System.out.println ("Can't do that - I'm only a cheap calculator");
break;
}
System.out.println("Answer is " + Ans);
}
}

Notes:

The following lines may need some extra explanation:

Num1=Integer.parseInt(args[0]);

We have already used the parseDouble method of the Double class in a previous example. The Integer class is similar to Double, except that it contains methods useful when dealing with data type int (Whole numbers) 

Op=args[1].charAt(0);

The String class defines several methods useful when dealing with strings. Because args[1] is defined as an object of class String, we can use the methods of the String class to work with it. The charAt method retrieves a single character at a given ppoint in the string. charAt(0) retrieves the first character. Check out the Java documentation for the String class to see other useful string handling methods. Go to http://java.sun.com/javase/6/docs/api/, then choose java.lang to see the core Java language documentation. From there, choose the String class.