Chapter 1: Preview of Java Fundamentals:

To run a program compiled in Net Beans in Dos environment - if the project folder where the program resides is called JavaApplication1 then after compiling this project in Net Beans, a file called JavaApplication1.jar would be created. To run in Dos, use the following command, for example:

C:\CSc2310\JavaApplication1\dist\ java -jar JavaApplication1.jar

To run in Net Beans, press F5 or click the Run menu.

There are several different ways in writing a Java program and saving it as a file:

1.  As a single class in one file with the name of the file and the class name being the same.

2.  As a single file with one public class and one or several private classes with the name of the file being the same as the public class.

3.  As several files with each consisting of one or more classes. However, each file must consist of at least one public class whose name will be the same as the file name. Also, one of these files will consist of the main program which is identified by having the main function - main().

4.  By creating packages, each package made up of one or more of related classes and the main program can be one class in the package. But the file consisting the main program must be named for the class that consist the function - main().

The program on page 5 gives an example of a program consisting of two classes within a package.

Packages:

The “package” in Java provides a means to write and group related classes. To write a package:

1.  Use the keyword package followed by a name chosen by the programmer.

2.  Follow this line of code with an import line. Need to import functions/classes from other packages the Java library – could use import java.io.*; to include most of the common functions or any others that you may need. A few other more commonly used packages are java.util, java.lang, java.swing, etc.

3.  Next line – the class in the format of public class any_name {…}

4.  Input the required code inside of the curly brace.

5.  Note: give the package a different named from the class inside of the package.

Classes:

An object in Java is an instance of a class. A class is a data type similar to int or double and by using the class name, we can create a class variable. A class definition includes a number of options – Figure 1-2. We use the new key word to create a class object.

Data Fields:

These are either variables of constants. They can contain modifiers such as public, private or protected and no access modifiers. Figure 1-3 on page 7. These are effective only if the class is declared as public. Writing a method includes the access modifier followed by optionally the use modifier, the return type, the name of the function and a parameter list enclosed in parentheses. NOTE: In java 1.5 and later, if a parameter list consist of the same data type, then the declaration can list the data type followed by 3 ellipses and then a name, example:

public static int max (int … numbers)

this means that there can be any amount of integers given as parameters, and they all would be in the form of an array with the name of the array being numbers.

Furthermore, when writing the code of this function, we could use the enhanced for loop to process the array:

for(int num : numbers)

{

}

Each time the loop iterates, num will start with the first value, then the second value, then the third value, etc. until all of the values in numbers would have been exhausted. Note: there is no need to initialize the loop by a counter, nor increasing the counter, nor stopping the loop at some value – all of these are done implicitly.

All members of a class that are declared as public can be accessed outside of the class by an object of the class followed by the dot operator and the name of the member, example:

SimpleSphere ball = new SimpleSphere();

double volley_ball = ball.getVolume();

And members (data or method) that are declared static can be accessed using the class name followed by the dot operator and then the data or method name – example:

SimpleSphere.DEFAULT_RADIUS;

Language Basics:

1.  Comments - //single line, /*multiple lines*/ & /** generate automatic documentation using javadoc */

2.  Identifiers & key words – a series of letters, digits, underscores and dollar signs, but it must begin with a letter or underscore only.

Variables:

A variable can have any name except a key word.

Primitive Data Type:

Note: The primitive data types are not objects and so cannot be used “as is” as a substitute for an object. To use a variable of primitive data type as an object, it must be first converted to an object, and only thereafter can be used as an object, example:

Int x = 5;

Integer intObj = new Integer(x); //converting the variable x to an object

OR

Integer intObject = 100;

The java 1.5 compiler (or later version) automatically converts 100 to an object – intObject. It will also automatically reconvert an object to an integer. The same procedure can be used with the other primitive data type to convert them to objects.

References:

Only addresses used for the reference data types.

Literal Constants:

These are variables whose values can change. Example at one time x = 5 and at another time x = 6 in the same program. Also scientific notations can be used to initialize variables such as:

double y = 1.2e-2 which is the same as double y = 0.012

We can do this for characters, Boolean or any of the data types.

Named Constants:

This is when a variable is made into a constant example:

final double pi = 3.15;

Note: if we declare this inside of the function in which it is used, we don’t have to use the key word public nor static. Otherwise, we may have to use these keywords. Also once a name has been used to create a “Named Constant”, it cannot be reused for something else in the program. A few other named constants are - \n, \t, etc.

Assignments & Expressions:

Arrays:

Declaring an array requires that you indicate the data type, the size and must use the new key word example:

double d[] = new double[10]; or double[] d = new double[10];

In this declaration, we could have declared a final value and initialize it to the value of 10, then provide the final value as the size of the array. To find the size of an array, we use name of the array followed by the dot operator then the key word length - as in this case d.length which will return 10.

A multi-dimensional array is similar to a single dimension array except that the declaration requires two sets of brackets example:

int numbers[][] = new int[5][5];

Vectors in Java:

An alternative to using an array is the Vector class. A Vector encapsulates the functionality of an array with the added benefit of automatic expansion. Vectors are useful when you don’t want to worry about storage reallocation – you can just keep adding things to a Vector and it will “grow” as needed.

Vectors cannot be accessed in the same manner as arrays – they can only be accessed with methods to add objects, retrieve objects, find objects, and remove objects. You can store any type of object in a Vector. You can keep track of how many items are in the Vector through the size() method. You can also access the amount of total storage allocated to the Vector through the capacity() method. Primitive data types must by converted to objects with type wrappers – the Integer, Double, Boolean, Float, Long, and Character classes. References can be added directly to a Vector, however.

Constructors:

Vector() // default capacity is 10; capacity is doubled when full

Vector( int initialCapacity ) // capacity is initialCapacity; capacity is doubled when full

Vector( int initialCapacity, int capacityIncrement ) // capacity increased by fixed amount

Methods( public final ):

void add( Object obj ) // insert obj at the end

void add( int index, Object obj ) // insert obj at the specified index

int capacity() // returns the Vector’s capacity

boolean contains( Object obj ) // true if the Vector contains obj

Object get( int index ) // returns the object reference at the given index

int indexOf( Object obj ) // returns the index if found, otherwise returns –1

boolean isEmpty() // returns true if the Vector is empty, otherwise false

void remove( Object obj ) // removes an object by reference

void remove( int index ) // removes an object by position

void removeAllElements() // remove all elements from the Vector

int size() // returns the number of elements in the Vector

A simple example of a vector program

import java.util.*;

import javax.swing.JOptionPane;

import java.lang.String;

public class testVec

{

public static void main(String[] args)

{

String output;

Vector vect = new Vector( 5, 5 ); // Initial capacity is 5

// Will grow by 5 elements when full.

output = "Vector size is " + vect.size() +

"\nVector capacity is " + vect.capacity() + "\n";

output += "Vector Contents:\n";

vect.add( 0, 45 ); // Inserts 45 at index 0. Note 45 is a regular int & all of the

//following are objects

vect.add( new Long( 900000000 ) ); // Inserts at index 1.

vect.add( new Double( 5.75 ) ); // Inserts at index 2.

vect.add( "Homer Simpson" ); // Inserts at index 3.

vect.add( new Character( '*' ) ); // Inserts at index 4.

vect.add( new Boolean( false ) ); // Inserts at index 5.

for( int i = 0; i < vect.size(); i++ )

{

output += vect.get( i ) + "\n";

}

output += "Vector size is now " + vect.size() +

"\nVector capacity is now " + vect.capacity();

JOptionPane.showMessageDialog( null, output,

"Vector Example", JOptionPane.PLAIN_MESSAGE );

}

}

Output:

Vector size is 0.

Vector capacity is 5

Vector contents

45

900000000

5.75

Homer Simpson

*

false

Vector size is now 6

Vector capacity is now 10

Selection statements:

If Statements:

If-else-statements:

Conditional-operator:

Nested If Statements:

Cascaded if Statements:

Switch Statements:

Iteration Statements:

The While Loop:

The For Loop:

The Do Loop:

Useful Java Classes:

The Java Application Programming Interface (JAPI or API) provides a number of classes that are useful for programming – one of the most useful is the Object class. Many classes have a single inheritance from the object class allowing methods from the object class to be reused “as is” or even be redefined to suit the particular class. Some of the methods from the Object class are equals(), finalize(), hashCode() and toString().

The String Classes:

There are three string classes in Java; String, StringBuffer and StringTokenizer.

The String class:

The StringBuffer class:

This class provides the same functionalities as the string class as well as a few others. The idea is a string is non-mutable (cannot change) and to make the string mutable, we use the StringBuffer.

The StringTokenizer class:

Allow us to separate a string into individual tokens. By default, this class uses the space, carriage return, tab, form feed and new line characters to separate tokens. However, the user can provide their own separator to separate the tokens.

Java Exceptions:

Java provides the try-catch block to find errors. When a statement in the try block throws an exception, the remainder of the statements in the try block are ignored and execution goes into the catch block. A try block can have several catch blocks attached to it and each of the catch blocks can catch different exception. There are a number of built in exceptions such as the ArithmeticException, NullPointerException, InterruptedException (to handle Java Thread.sleep() function) , NumberFormatException, ArrayIndexOutOfBoundsException, FileNotFoundException and others.

The exceptions are grouped into two groups: Checked and Unchecked (runtime exception).

Checked Exceptions: These are exceptions that occur from the subclasses of the java.lang.Exception class. These exceptions must be handled by the programmer – example of these are InterruptedException when using the Tread.sleep(), or the FileNotFoundException when trying to open a file.

Unchecked Exceptions: These types are considered to be less serious and could be catered for by the programmer. However, if not catered for, they may not affect the performance of the program immensely. And recovery of execution is easier.

Input and Output text:

Input from the keyboard and output to the screen consist of a stream- the class of the input stream is the InputStream and the class of the output stream is the PrintStream.

These classes are found in the java.lang.System class.

Input:

Prior to Java 1.5, we used the following code to read from the key board and store the line into an object of type BufferedReader:

BufferedReader stdin = new BufferedRedader(new InputAtreamReader(System.in));

String nextLine = stdin.readLine();

Note: everything read into nextLine is read in as a string – the programmer will have to extract these into tokens and convert each token into the primitive data types – int, float, etc.