Advanced Programming
Advanced Programming
History
The Java programming Language evolved from a language named Oak. Oak was developed in
the early nineties at Sun Microsystems as a platform-independent language aimed at allowing
entertainment appliances such as video game consoles and VCRs to communicate. Oak was first
slated to appear in television set-top boxes designed to provide video-on-demand services. Just
as the deals with the set-top box manufacturers were falling through, the World Wide Web was
coming to life. As Oak’s developers began to re cognize this trend, their focus shifted to the
Internet and WebRunner, an Oak-enabled browser, was born. Oak’s name was changed to Java
and WebRunner became the HotJava web browser. The excitement of the Internet attracted
software vendors such that Java development tools from many vendors quickly became
available. That same excitement has provided the impetus for a multitude of software developers
to discover Java and its many wonderful features. (The GNU General Public License (GNU
GPL or simply GPL) is a widely used free software license)
JAVA Principles
There were five primary goals in the creation of the Java language:
1. It should be "simple, object oriented and familiar".
2. It should be "robust and secure".
3. It should be "architecture neutral and portable".
4. It should execute with "high performance".
5. It should be "interpreted, threaded, and dynamic".
JAVA
Java is a programming language used to develop software applications as well as applets that run
on web pages. Originally developed by James Gosling at Sun Microsystems and released in
1995 as a core component of Sun Microsystems' Java platform. The language derives much of its
syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java
applications are typically compiled to bytecode (class file) that can run on any Java Virtual
Machine (JVM) regardless of computer architecture. Java is general-purpose, concurrent, class-
based, and object-oriented, and is specifically designed to have as few implementation
dependencies as possible. It is intended to let application developers "write once, run anywhere".
The original and reference implementation Java compilers, virtual machines, and class libraries
were developed by Sun from 1995. As of May 2007, in compliance with the specifications of the
Java Community Process, Sun relicensed most of their Java technologies under the GNU General
Public License. Others have also developed alternative implementations of these Sun
technologies, such as the GNU Compiler for Java and GNU Classpath.
1
ADVANCED PROGRAMMING
With Java, you can define your own reusable data structures called objects as well as define their
attributes (properties) and things they can do (methods). You can also create relationships
between various objects and data structures.
Java is a web language AND a software development language
With Java, you can create applets - small programs that run on web pages, as well as stand-alone
software applications.
What makes Java's platform independence possible is the way operating systems interpret Java.
Java source code will remain the same irregardless of what operating system you are writing a
Java program for. Essentially, Java source code is not converted into machine language, but
rather into a special form of instruction known as Java byte code. Java byte code is then
interpreted by the Java run-time environment. The Java run-time environment is a Java
interpreter which is also known as the Java virtual machine. The Java run-time environment
interprets Java byte code and instructs the operating system what to do. This allows for Java's
platform independence, since Java source code will be interpreted the same way on all operating
systems by the Java run-time environment.
Importance of java
Interact with the user
Interact with the user. For example, you can ask the user for their name and print a custom
message with it such as "Hello Roger!"
Create graphical programs
With Java, you can create graphical programs which can include various graphical components
including buttons, textboxes, menus, checkboxes, and more. For example, you can create a
simple text editing program such as Window's Notepad.
Create applets
An applet is a program that runs within another program. With Java, you can create applets that
will run inside web pages. For example, you can create an applet that will get input from the user
and store the data in a database.
Read from and write to files
You can read from and write to files. For example, you can store data that is input by the user in
a text file and retrieve that data when the user accesses the program again.
Communicate with databases
2
ADVANCED PROGRAMMING
Read data stored in a database or write new data to a database. For example, you can store a
users name and e-mail address in a database, and allow them to retrieve this information and
view it or change it, and the change will be reflected in the database.
A text editor
In the examples, we'll use Notepad, a simple editor included with the Windows platforms. You
can easily adapt these instructions if you use a different text editor.
These two items are all you'll need to write your first application.
Save the code in a file with the name HelloWorldApp.java. To do this in Notepad, first choose
the File > Save As menu item. Then, in the Save As dialog box:
3
ADVANCED PROGRAMMING
1. Using the Save in combo box, specify the folder (directory) where you'll save your file.
In this example, the directory is java on the C drive.
2. In the File name text field, type "HelloWorldApp.java", including the quotation marks.
3. From the Save as type combo box, choose Text Documents (*.txt).
4. In the Encoding combo box, leave the encoding as ANSI.
When you're finished, the dialog box should look like this.
A shell window.
The prompt shows your current directory. When you bring up the prompt, your current directory
is usually your home directory for Windows XP (as shown in the preceding figure).
To compile your source file, change your current directory to the directory where your file is
located. For example, if your source directory is java on the C drive, type the following
command at the prompt and press Enter:
4
ADVANCED PROGRAMMING
cd C:\java
Now the prompt should change to C:\java>.
Note: To change to a directory on a different drive, you must type an extra command: the name
of the drive. For example, to change to the java directory on the D drive, you must enter D:, as
shown in the following figure.
5
ADVANCED PROGRAMMING
6
ADVANCED PROGRAMMING
A class declaration
A class is a grouping of related variables and functions (methods) that is used to achieve
something. All the source code for a Java program will be placed within the class definition.
Syntax for declaring a class:
class nameOfClass
{
Code that will run the program goes here
}
NOTE: Class names should be descriptive and reflect the central purpose of a program.
Example:
class PrintText
{
}
In the above example a class named PrintText is declared.
A main() method
A method is a grouping of code that executes when it is called. The main() method is what
makes a Java program work. When you insert the main() method into a Java program, it has to be
used with a few special keywords, and has to contain a certain parameter.
Example:
class PrintText
{
public static void main(String[] args)
{
The above example does not do anything, but only contains the fundamental elements needed to
create a Java program.
Printing text
To print text in a Java program, you can use either the System.out.print() method to print a
single line of text or the System.out.println() method to print a single line of text followed by a
line break.
Syntax:
System.out.print("textToPrint");
System.out.println("textToPrint");
Example:
class PrintText
{
public static void main(String[] args)
{
System.out.println("Here is some text");
System.out.print("Here is some more text");
7
ADVANCED PROGRAMMING
The above code uses the System.out.println() method to print out one line of text followed by a
line break, and then the System.out.print() method to print out another line of text.
NOTE: Every line of code in a Java program must end with a semicolon. If you don't end a line
of code with a semicolon, an error will be generated!
}
NOTE: Single line comments can span only a single line.
VARIABLES.
A variable is a container which holds information in a computer's memory. The value of a
variable can change all throughout a program.
Declaring variables
In Java, different variables store different types of data. The type of data that is stored by a
variable is signified with a data type.
A variable is declared with the data type of the data it will store.
Syntax:
dataType varName;
Example:
char aCharacter;
int aNumber;
In this example, two variables are declared. The first variable is used to store a single character
and is therefore of data type char. The second variable is used to store a whole number and is
therefore of data type int. You can assign a value to a variable at the same time that it is declared.
This process is known as initialization.
Example of initializing a variable:
char aCharacter = 'a';
int aNumber = 10;
In the above example a character variable named aCharacter is initialized with the value 'a' and a
numeric variable is initialized with the value 10.
9
ADVANCED PROGRAMMING
int aNumber
aNumber = 10;
In the above example a character variable named aCharacter is declared. On the next line this
variable is assigned the value 'a' and a numeric variable named aNumber is declared and on the
next line it is assigned the value 10.
NOTE: A variable must be declared with a data type. If you do not specify a data type for a
variable, an error will be generated. The data type of a variable should be used only once with
the variable name - during declaration. After a variable has been declared or initialized, you can
refer to it by its name without the data type.
NAMING VARIABLES
When naming variables, several rules should be considered. These rules will make variable
declaration easier, as well as clear up possible errors in code.
Make sure that the variable name is descriptive
If you do not give a variable a descriptive name, it will be hard to understand what the variable
refers to. For example, if you wanted to create a variable which would hold a value describing
the amount of chairs in a room, then the better choice for the variable name would be numChairs
because it is more descriptive.
Make sure the variable name is of appropriate length
Make sure the variable name is long enough to be descriptive, but not too long.
Do not use spaces in variable names.
Java does not allow spaces in variable names, doing so will generate an error!
Do not use special symbols in variable names such as !@#%^&*
As is the rules with spaces, special symbols are not allowed in variable names, and using special
symbols in variable names will generate an error. There is however one special symbol that can
be used in variable names, and that symbol is the undersocre ( _ ) symbol. Variable names can
only contain letters, numbers and the underscore ( _ ) symbol.
Variable names can not start with an integer
While integers can be used in variable names, it cannot be the first character in a variables name.
Variable names can only start with a letter or the underscore ( _ ) symbol.
Distinguish between uppercase and lowercase
Java is a case sensitive language which means that the variables varOne, VarOne, and VARONE
are three separate variables!
PRINTING VARIABLES
Variables are printed by including the variable name in a System.out.print() or
System.out.println() method. When printing the value of a variable, the variable name should
NOT be included in double quotes.
Example:
10
ADVANCED PROGRAMMING
class PrintText
{
public static void main(String[] args)
{
//declare some variables
byte aByte = -10;
int aNumber = 10;
char aChar = 'b';
boolean isBoolean = true;
}
}
The if statement
The if statement tests if a certain condition is true or false and acts upon it accordingly.
Syntax:
if(condition)
{
Perform this action;
}
If the condition in the parenthesis is true, then the code following the condition will be executed,
otherwise it will not.
Example:
class TestCondition
{
public static void main(String[] args)
{
//declare a numeric variable
int aNumber = 5;
//check if aNumber equals 5 and if it is
//print a message accordingly
if (aNumber == 5)
{
System.out.print("aNumber is equal to 5");
}
}
}
NOTE: Use two equal signs (==) in the condition when comparing values. One equal sign (=) is
used to assign values, while two equal signs (==) are used to compare values.
else
{
Perform this action if the above condition is false;
}
12
ADVANCED PROGRAMMING
If the condition in the if statement is false, then the action dictated by the else statement will be
performed.
Example 1:
class TestCondition
{
public static void main(String[] args)
{
//declare a numeric variable
int aNumber = 5;
//check if aNumber equals 5 and if it is
//print a message accordingly
if (aNumber == 5)
{
System.out.print("aNumber is equal to 5");
}
//otherwise print
//a different message
else
{
System.out.println("aNumber equals a
number other than 5");
}
}
}
Example 2:
class TestCondition
{
public static void main(String[] args){
//declare a numeric variable
int aNumber = 10;
//check if aNumber equals 5 and if it is
//print a message accordingly
if (aNumber == 5)
{
System.out.print("aNumber is equal to 5");
}
//otherwise print
//a different message
else
{
System.out.println("aNumber equals a
number other than 5");
}
}
}
13
ADVANCED PROGRAMMING
Example:
class TestCondition
{
public static void main(String[] args)
{
//declare a numeric variable
int aNumber = 7;
Example:
class TestCondition
{
public static void main(String[] args)
{
//declare a numeric variable
int aNumber = 5;
//check if aNumber equals 9 and if it is
//print a message accordingly
if (aNumber == 9)
{
System.out.print("aNumber is equal to 9");
}
//check if aNumber equals 7 and if it is
//print a message accordingly
else if (aNumber == 7)
{
System.out.print("aNumber is equal to 7");
}
//check if aNumber equals 3 and if it is
//print a message accordingly
else if (aNumber == 3)
{
System.out.print("aNumber is equal to 3");
}
//check if aNumber equals 15 and if it is
//print a message accordingly
else if (aNumber == 15)
15
ADVANCED PROGRAMMING
{
System.out.print("aNumber is equal to 15");
//otherwise print
//a different message
else
{
System.out.print("aNumber is not equal to 9, 7, 3, or 15. aNumber is equal to "
+ aNumber);
}
}
}
NOTE: When using if, else if, and else statements - if the action dictated by these statements
contains more than one line of code, it should be surrounded by curly braces, otherwise the curly
braces are optional. Although, curly braces may not always be used with conditional statements.
Doing so is good convention.
Example:
class TestCondition
{
public static void main(String[] args)
{
//declare a numeric variable
int aNumber = 5;
int anotherNumber = 7;
if (aNumber == 9)
{
System.out.println("aNumber is equal to 9");
System.out.print("anotherNumber is equal to 7");
}
else if (aNumber == 7) System.out.print("aNumber is
equal to 7");
else if (aNumber == 3)
{
System.out.println("aNumber is equal to 3");
System.out.print("anotherNumber is equal to 7");
}
else if (X == 15)
{
System.out.println("aNumber is equal to 15");
System.out.print("anotherNumber is equal to 7");
}
else System.out.print("aNumber is not equal to 9, 7, 3, or 15, it is equal to 5");
}
16
ADVANCED PROGRAMMING
In the above example, some of the conditional statements dictate actions with one line of code -
not sorrounded by curly braces, and some conditional statements dictate actions with more than
one line of code - sorrounded by curly braces.
default:
perform this action if none of the values match;
}
Example:
class TestCondition
{
public static void main(String[] args)
{
//declare a numeric variable
int aNumber = 7;
Example:
class TestCondition
{
public static void main(String[] args)
{
//declare a numeric variable
int aNumber = 1;
int anotherNumber = 7;
Other operators
Other than the ternary operator, there are other operators used when working with conditional
logic as well as variables:
JAVA LOOPS
Loops are specifically designed by a programmer to perform repetitive tasks with one set of code
so as to save time. If you have to write a program which performs a repetitive task such as
printing 1 to 100. Coding 100 lines to do this would be hard. There is no easier way to code
repetitive tasks than implementing loops. Some of the loops used in java are as follows:
Example:
class ForLoopExample
{
public static void main(String[] args)
{
for(int a = 1; a < 11; a++)
{
System.out.println(a);
19
ADVANCED PROGRAMMING
}
}
}
The for loop has three parts:
Variable declaration
The variable declaration is the first part of the loop which initializes the variable at the beginning
of the loop to some value. This value is the starting point of the loop.
Condition
The condition is the second part of the loop, and it is the part that decides whether the loop will
continue running or not. While the condition in the loop is true, it will continue running. Once
the condition becomes false, the loop will stop running.
Increment statement
The increment statement is the third part of the loop. It is the part of the loop that changes the
value of the variable created in the variable declaration part of the loop. The increment statement
is the part of the loop which will eventually stop the loop from running.
Based on the above explanation of each part of the for loop, consider the example from earlier in
the lesson and take it apart to see what each part does. Remember, that this loop prints to the
screen the numbers 1 - 10.
class ForLoopExample
{
public static void main(String[] args)
{
for(int a = 1; a < 11; a++)
{
System.out.println(a);
}
}
}
int a = 1
This is the variable declaration part of the loop. A variable named a is declared with a value of 1.
a < 11
This is the condition of the loop. It states that as long as the variable a is less than 11, the loop
should keep running.
a++
This is the increment statement part of the loop. It states that for every iteration of the loop, the
value of the variable a should increase by 1. Recall that initially a is 1.
Example:
class WhileLoopExample
{
public static void main(String[] args)
{
int num = 0;
while(num < 25)
{
num = num + 5;
System.out.println(num);
}
}
}
In the above code, a variable named num is initialized with the value of 0. The condition in the
while loop is that while num is less than 25, 5 should be added to num. Once the value of num
is greater than 25, the loop will stop executing.
Example:
class DoWhileLoopExample
{
public static void main(String[] args)
{
int num = 0;
do
{
num = num + 5;
System.out.println(num);
}
}
}
}
The above example initializes the variable num with the value of 50, and states that as long as
num is greater than 10, add five to num. Based on the variable declaration and the increment
statement, num will always be greater than 10 in this loop, and thus, it is an endless loop.
The above example initializes the variable num with the value of 50, and states that as long as
num is greater than 40, add 5 to num. Based on the variable declaration and the increment
statement, num will always be greater than 40 in this loop, and thus, it is an endless loop.
Example:
class BreakOutOfLoop
{
public static void main(String[] args)
{
for(int a = 1; a < 10; a++)
{
System.out.println(a);
if(a == 5)
{
break;
}
}
}
}
In the above example, the FOR loop is set to iterate 9 times and print the current value of the
variable a during each iteration. The IF statement within the loop states that when the variable a
is equal to 5, it should break out of the loop.
Continuing a loop
While you can break out of a loop completely with the break keyword, there is another keyword
used when working with loops - the continue keyword. Using the continue keyword in a loop
will stop the loop at some point and continue with the next iteration of the loop from the
beginning of it.
Example:
class ContinueLoop
{
public static void main(String[] args)
{
for(int a = 1; a < 10; a++)
{
if(a == 5)
{
23
ADVANCED PROGRAMMING
continue;
}
System.out.println(a);
}
System.out.print("You have exited the loop");
}
}
In the above example, the for loop is set to iterate 9 times and print the current value of the
variable a during each iteration. The if statement within the loop states that when the variable a
is equal to 5, stop the loop and continue with the next iteration of the loop from the beginning of
it. For this reason, all the numbers except the number 5 are printed.
Interface
An interface is a collection of methods that have no implementation - they are created, but have
no functionality. For one to define their functionality you do that individually in different classes.
An interface is an abstract, and a programmer defines how its elements (methods) work
according to their needs.
Importing packages
For a programmer to be able to use classes and interfaces located in a package, you have to
import the package they are in. If you try to use a class or an interface without importing the
package, your program will generate an error. Packages are imported using the import keyword.
24
ADVANCED PROGRAMMING
Importing individual classes – in this you will be able to use just those classes you have
specified. Eg.
//imports the BufferedReader class from java.io package
import java.io.BufferedReader;
Importing individual interfaces – the programmer will be able to use only those interfaces
specified. E.g.
//imports the ActionListener interface from java.awt.event package
import java.awt.event.ActionListener;
class ProgramWithPackages
{
public static void main(String[] args)
{
System.out.println("This program imports some packages");
}
}
NOTE:
The import statement should be the first thing in your code, even before the class declaration
done.
Java interfaces
An interface is a collection of methods that have no implementation - they are just created, but
have no functionality. What's the purpose of such methods? For you to define their functionality
individually in different classes. An interface is abstract, and you define how it's elements
(methods) work according to your needs.
Declaring an interface
While Java provides interfaces for you to use, you can also create your own interfaces. An
interface is declared with the interface keyword.
Syntax:
interface nameOfInterface
25
ADVANCED PROGRAMMING
{
//methods for interface here;
}
You can add methods to an interface the same way you would add methods to a class, except that
the methods in an interface have no implementation.
Just like regular Java programs, interfaces should be declared in separate files, the name of the
file an interface is declared in should have the same name as the interface (including the same
capitalization), and should have a .java extension. For example, the code for the interface from
above should be in a separate file named DataManager.java
Using an interface
To use an interface, a programmer will use the implements keyword with the name of the
interface in the class declaration line in the code. You specify that a class implements the
interface and you define in that class what the methods from the interface will do.
Syntax:
class nameOfClass implements nameOfInterface
{
}
Example:
class Sample implements DataManager
{
}
From the above example the Sample class can now use the methods declared in the DataManager
interface and define their functionality.
NOTE:
Remember always to import the package that contains the interface you are implementing as in
the example below.
import java.awt.event.*;
class FrameWithEvents implements WindowListener
{
}
class GetUserInput
{
}
User input classes
To get user input, we use the BufferedReader and InputStreamReader classes.
The BufferedReader class - buffers the user's input to make it work more efficiently.
The InputStreamReader class - reads the user's input.
Java exceptions
Exceptions are used to handle situations where something unexpected might happen, such as
attempting to divide by zero, a file you're trying to access is not found etc.
NOTE:
The base class of all the exception classes is the class Exception and it is located in the java.lang
package.
28
ADVANCED PROGRAMMING
Syntax:
try
{
code to execute if exception doesn't occur;
}
catch(anExceptionThatMayOccur)
{
code to execute if exception does occur;
}
Example:
try
{
name = reader.readLine();
System.out.println("Your name is " + name);
}
//watch for an input/output exception
catch(IOException ioe)
{
System.out.println("An unexpected error has occured");
}
Syntax:
try
{
code to execute if exception doesn't occur;
}
catch(anExceptionThatMayOccur)
{
code to execute if exception does occur;
}
finally
{
code to execute whether exception occurs or not;
}
Example:
try
{
name = reader.readLine();
System.out.println("Your name is " + name);
}
//watch for an input/output exception
catch(IOException ioe)
{
System.out.println("An unexpected error has occured");
29
ADVANCED PROGRAMMING
}
finally
{
//print this whether an exception occurs or not
System.out.println("Thanks for stopping by!);
}
Creating a frame
In Java, a frame is a standard graphical window. It has the minimize, maximize, and close
buttons in its top right corner and can be moved and resized by default. Frames are created using
the Frame class.
class Aframe
{
public static void main(String[] args)
{
Frame aFrame = new Frame();
aFrame.setSize(200, 200);
aFrame.setVisible(true);
}
}
Both sets of code from above produce the same frame:
NOTE: Initially, a frame is not visible. You have to set the visiblity using the setVisible()
method.
GUI components
There are various graphical components you can add to frames including labels, buttons,
textboxes, and text areas. Each component is created through a class and each of these classes
has methods to work with the component.
In the example below you will find usage of a few different classes used to create graphical
components as well as the usage of some of their methods.
The layout of the frame is set to FlowLayout which means that the components in the frame will
appear from left to right in the order in which they are added .
import java.awt.*;
class FrameWithComponents
{
public static void main(String[] args)
{
Frame AFrame = new Frame("Frame with components");
Label lblOne = new Label("This is a label");
Button btn1 = new Button("This is a button");
TextField tf1 = new TextField();
TextArea ta1 = new TextArea(12, 40);
tf1.setText("This is a textbox");
ta1.append("Number of columns in this textarea: " + ta1.getColumns());
//the add() method of the Frame class is
//used to add components to the frame
AFrame.add(lblOne);
31
ADVANCED PROGRAMMING
AFrame.add(btn1);
AFrame.add(tf1);
AFrame.add(ta1);
AFrame.setSize(450, 300);
AFrame.setLayout(new FlowLayout());
AFrame.setVisible(true);
}
}
output:
Setting a layout
You can set a frame to use a layout using the setLayout() method of the Frame class.
Example:
Frame AFrame = new Frame("Frame with components");
AFrame.setSize(450, 300);
//set the layout of the frame to FlowLayout
AFrame.setLayout(new FlowLayout());
AFrame.setVisible(true);
FlowLayout(int alignment) – this is used to Creates a FlowLayout with the specified alignment.
The Possible values include FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT,
FlowLayout.LEADING, FlowLayout.TRAILING.
import java.awt.*;
class FrameWithGridLayout
{
public static void main(String[] args)
{
Frame AFrame = new Frame("Frame with components");
Label lblOne = new Label("This is a label");
Button btn1 = new Button("This is a button");
TextField tf1 = new TextField();
TextArea ta1 = new TextArea(12, 40);
tf1.setText("This is a textbox");
ta1.append("Number of columns in this textarea: " + ta1.getColumns());
AFrame.add(lblOne);
AFrame.add(btn1);
AFrame.add(tf1);
AFrame.add(ta1);
AFrame.setSize(480, 300);
//set the layout of the frame to GridLayout
//specify the layout to have 2 rows and 2 columns
AFrame.setLayout(new GridLayout(2, 2));
AFrame.setVisible(true);
}
}
Output:
34
ADVANCED PROGRAMMING
NOTE: All the classes you will need to display graphics (as well as frames) are located in the
java.awt package.
Add a canvas to a frame just like you would any other component:
Drawing lines
To draw lines, the drawLine() method of the Graphics class is used. This method takes four
numeric attributes - the first two indicating the x/y starting point of the line, the last two
indicating the x/y ending point of the line.
Example:
public void paint(Graphics g)
{
//draw a line starting at point 10,10 and ending at point 50,50.
g.drawLine(10, 10, 50, 50);
}
Drawing rectangles
To draw rectangles, the drawRect() method is used. This method takes four numeric attributes -
the first two indicating the x/y starting point of the rectangle, the last two indicating the width
and height of the rectangle.
Example:
public void paint(Graphics g)
{
35
ADVANCED PROGRAMMING
Filling a rectangle
By default a rectangle will have no color on the inside (it will just look like a box). You can use
the fillRect() method to fill a rectangle. The fillRect() method has four numeric attributes
indicating the x/y starting position to begin filling and the height and width. Set these values the
same as you did for the drawRect() method to properly fill the rectangle.
Example:
public void paint(Graphics g)
{
//draw a rectangle starting at 100,100 width a width and height of 80
g.drawRect(100, 100, 80, 80);
g.fillRect(100, 100, 80, 80);
}
The rectangle is filled, but we didn't set a color for it! To do this, we will use the setColor()
method.
g.setColor(Color.orange);
Drawing ovals
To draw ovals, the drawOval() method is used. This method takes four numeric attributes - the
first two indicating the x/y starting point of the oval, the last two indicating the width and height
of the oval. Fill an oval with the fillOval() method which also takes four numeric attributes
indicating the starting position to begin filling and the height and width. Set these values the
same as you did for the drawOval() method to properly fill the oval.
Example:
public void paint(Graphics g)
{
g.setColor(Color.gray);
//draw an oval starting at 20,20 with a width and height of 100 and fill it
g.drawOval(20,20, 100, 100);
g.fillOval(20,20, 100, 100);
}
Displaying images
To display images, the Image class is used together with the Toolkit class. Use these classes to
get the image to display. Use the drawImage() method to display the image.
Example:
public void paint(Graphics g)
{
Image img1 = Toolkit.getDefaultToolkit().getImage("sky.jpg");
//four attributes: the image, x/y position, an image observer
g.drawImage(img1, 10, 10, this);
}
public GraphicsProgram()
{
setSize(200, 200);
setBackground(Color.white);
}
public static void main(String[] argS)
{
//GraphicsProgram class is now a type of canvas
//since it extends the Canvas class
//lets instantiate it
Output:
37
ADVANCED PROGRAMMING
Java applets
An applet is a Java program that runs on a webpage. Applets function like regular Java programs
but with a few security restrictions (such as applets can't read or write files on your computer).
Building an applet
The first four methods discussed above are actually run by a web browser automatically. You
can define the functionality of these methods in your applet code to specify what happens during
each stage of an applet's existence.
The applet below uses these methods to print to a textarea what is currently happening.
38
ADVANCED PROGRAMMING
If the applet doesn't load, try viewing this page in a different web browser.
NOTE: You should always refer to the compiled program file (the one with the .class extension)
in an <applet> tag when placing an applet on a webpage. Not the .java source code file!
Viewing an applet
You can view an applet by viewing the webpage on to which the applet is placed in a web
browser or you can use the Java appletviewer command line tool. In the command prompt type
appletviewer and the name of the page where the applet is located.
Example:
appletviewer appletpage.html
The appletviewer will display just the applet, not the entire webpage.
Java audio
Java provides the ability to play audio in applications and applets.
To be able to play audio in a program or applet, you first have to use the AudioClip interface and
instantiate an AudioClip object with it. The AudioClip interface is located in the java.applet
package.
Example:
AudioClip aClip;
In the above example, an audio file named sound.wav is loaded as the audio file to be played.
Methods of the AudioClip interface
Once the audio file is uploaded, you can use the methods of the AudioClip interface to work with
it.
}
setLayout(new FlowLayout());
setSize(220, 150);
setVisible(true);
}
public static void main(String[] args)
{
AudioFrame AF = new AudioFrame();
}
public void actionPerformed(ActionEvent e)
{
//the action event handler tracks which button
//is pressed and performs an action accordingly
if (e.getSource() == play)
{
bach.play();
}
if (e.getSource() == loop)
{
bach.loop();
}
if (e.getSource() == stop)
{ bach.stop();
}
}
}
Output:
Java arrays
Arrays are a very important concept in Java as well as many other programming languages. An
array is a special type of variable which can store a list of values.
41
ADVANCED PROGRAMMING
With Arrays, it is much simpler. An array gives you the ability to group together related
variables into one set. Arrays are special variables which hold lists of information. Therefore,
instead of the code above you can declare a 'Cars' array:
String[] Cars = new String[3];
Cars[0] = "Toyota Camry";
Cars[1] = "Honda Accord";
Cars[2] = "Mitsubishi Galant";
Declaring arrays
Arrays are declared with a data type, an array name, and square brackets [] specifying an array.
Syntax:
datatype arrayName[];
OR
datatype[] arrayName;
Example:
int evenNumbers[]; which can also be declared as
int[] evenNumbers;
The above example declares an array named evenNumbers of data type int. Whether you place
the square brackets after the array name or after the data type makes no difference.
After an array is declared, an array object has to be assigned to it using the new keyword as well
as the length of the array - specified in the square brackets. The length of the array denotes how
many elements an array can hold.
Syntax:
arrayName = new datatype[numElementsInArray];
Example:
evenNumbers = new int[10];
The above example declares an array named evenNumbers of data type int which has a length of
10, therefore it can store 10 elements.
Example:
evenNumbers[3] = 20;
The above example will assign the value 20 to the 4th element in the evenNumbers array.
NOTE: Array indexes begin at 0, so the first element of an array is at index 0, the fifth element
of an array is at index 4, and so on.
As an alternative to declaring an array and then assigning values to its elements, you can do both
tasks on one line.
Syntax:
dataType[] arrayName = {value, value, value, value, etc.};
42
ADVANCED PROGRAMMING
Example:
String[] Cars = {"Camry", "Accord", "Galant"};
The above example declares an array named Cars of data type String which stores three
elements.
In the above example, the third element of the Cars arrays is printed by referring to the Cars
array and the index number 2 in brackets.
Example:
class ModifyArrayElements
{
public static void main(String[] args)
{
int oddNumbers[] = new int[4];
oddNumbers[0] = 1;
oddNumbers[1] = 3;
oddNumbers[2] = 5;
oddNumbers[3] = 7;
Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from one
array into another:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
The two Object arguments specify the array to copy from and the array to copy to. The three
int arguments specify the starting position in the source array, the starting position in the
destination array, and the number of array elements to copy.
44
ADVANCED PROGRAMMING
The following program, ArrayCopyDemo, declares an array of char elements, spelling the word
"decaffeinated". It uses arraycopy to copy a subsequence of array components into a second
array:
class ArrayCopyDemo
{
public static void main(String[] args)
{
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
The output from this program is:
caffein
Example
public class CopyArray
{
public static void main(String[] args)
{
int array1[]= {2,3,4,5,8,9};
int array2[] = new int[6];
System.out.println("array:");
System.out.print("[");
for (int i=0; i<array1.length; i++)
{
System.out.print(" "+array1[i]);
}
System.out.print("]");
System.out.println("\narray1:");
System.out.print("[");
for(int j=0; j<array1.length; j++)
{
array2[j] = array1[j];
System.out.print(" "+ array2[j]);
}
System.out.print("]");
}
}
{
value[0] = 4;
value[1] = 5;
value[2] = 6;
}
Output:
num[0] = 4
num[1] = 5
num[2] = 6
(The values in the array have been changed.
Notice that nothing was "returned".)
Example: Fill an array with 10 integer values. Pass the array to a method that will add up the
values and return the sum.
(In this example, no original data in the array was altered. The array information was simply
used to find the sum.)
import java.io.*;
import BreezyGUI.*;
return (total);
}
Java strings
A string is a grouping of text. You can store this group of a text in a variable that would then be
known as a String variable. You can print strings, and you can also use various functions to
perform operations on strings such as returning the string's length.
Declaring a string
46
ADVANCED PROGRAMMING
Syntax:
String nameOfString = "stringValue";
String nameOfString = new String("stringValue");
Example:
String aString = "This is a string";
String aString = new String("This is a string");
Whether you declare a string as a variable or with the new keyword, it becomes an instance of
the String class. A class is a special type of variable.
Printing a string
Use the System.out.print or System.out.println methods to print a string.
Example:
String myString = "I like pineapple";
//print a string variable
System.out.println(myString); //print a non-variable string
//just put some text in double quotes and it's done
System.out.println("Green is a great color");
Concatenation
Concatenation is the process by which two or more strings are joined together. This is achieved
with the use of the + operator. You can use concatenation to join two or more strings into one or
print two or more strings together.
Example:
String aString = "Here is some text. ";
String anotherString = "Here is some more text.";
//declare a third string and
//combine into it the first two strings
String combinedString = aString + anotherString;
System.out.println(combinedString);
//print two strings together
System.out.println("Notepad is a " + "simple text editor.");
String functions
The String class has various functions (methods) you can use to work with text.
charAt(int index) - Returns a character from a string at a specified index.
equals() - Compares two strings and returns true if they are the same.
length() - Returns the length of a string.
toUpperCase() - Converts all letters in a string to upper case.
Example:
String aString = "Here is some text";
String anotherString = "Here is some more text";
//extract the third character
//from the aString string and print it
System.out.println(aString.charAt(2));
//compare the two strings aString and anotherString
47
ADVANCED PROGRAMMING
Java, being an object-oriented language, supports the creation of these advanced data types
(objects). Objects consist of a set of variables (representing information about the object) and
functions (representing what the object can do and things you can do with the object).
Creating a class
A class is a blueprint for an object. An object is a representation of a real world thing. An object
can represent a car, a table, a book or any other real world concept. Before an object can be
implemented, however, a blueprint has to be designed for it, and that blueprint is the class of an
object. A class is a blueprint for an object stating the various properties (variables) of the object
as well as what it can do (methods).
Syntax for creating a class:
class className
{
}
A class is created with the class keyword, followed by a single space, the name of the class to be
created, an opening curly brace, and a closing curly brace. All the specifics and logistics of the
class go in between these curly braces.
Example of a class:
class Book
{
}
The above code creates a class named Book.
Classes can be declared with certain keywords called access modifiers which dictate the level of
access on a class.
48
ADVANCED PROGRAMMING
}
protected
The keyword protected when placed in front of a class name specifies that a class can only be
accessed within the same package.
Example:
protected class Aclass
{
private
The keyword private when placed in front of a class name specifies that a class can be accessed
only within itself. It cannot be subclassed (extended) or instantiated.
Example:
private class Aclass
{
The above code uses the Book class and creates two member variables for it. The first is title - a
string variable which will store the title of the book. The second is numPages - a numeric
variable which will store the number of pages in the book.
Variables can be declared with certain keywords called access modifiers which dictate the level
of access on a variable.
protected
The keyword protected when placed in front of a variable specifies that the variable can be
accessed by the class it is defined in, a subclass of the class it is defined in, or from classes
within the same package.
49
ADVANCED PROGRAMMING
private
The keyword private when placed in front of a variable specifies that the variable can be
accessed only by the class it is declared in.
Example:
private int aNumber;
Example:
class Book
{
String title;
int numPages;
//this is a mutator method
public void setNumPages(int numOfPages)
{
numPages = numOfPages;
}
//this is an accessor method
public int getNumPages()
{
return numPages;
}
//this is a mutator method
public void setTitle(String theTitle)
{
title = theTitle;
}
//this is an accessor method
public String getTitle()
{
return title;
}
}
This method is used to return the number of pages in the book, this is done through the use of the
keyword return followed by the variable numPages - the variable that stores the value of how
many pages there are in the book.
setTitle(String theTitle)
This method is used to set the title of the book; this is done through its parameter theTitle. The
method sets the variable title to whatever value you supply to it through its parameter theTitle.
getTitle()
This method is used to return the title of the book; this is done through the use of the keyword
return followed by the variable title - the variable that stores the title of the book.
Methods can be declared with certain keywords called access modifiers which dictate the level of
access on a method.
Example:
public void printNumber()
{
}
protected
The keyword protected when placed in front of a method specifies that the method can be
accessed by the class it is defined in, a subclass of the class it is defined in, or from classes
within the same package.
Example:
protected void printNumber()
{
}
private
The keyword private when placed in front of a method specifies that the method can be accessed
only by the class it is declared in.
Example:
private void printNumber()
{
}
Another keyword used with methods is the void keyword. The void keyword is used to specify
that a method will not return a value. To specify that a method does return a value, instead of the
void keyword, the appropriate keyword corresponding to the data type that the method will
return should be used. For example, a method that will return an integer should have the keyword
int in front of it.
Generally, mutator methods do not return a value, and accessor methods do return a value.
The example from above contains two methods that do not return a value and two methods that
do return a value. Ie.
class Book
{
51
ADVANCED PROGRAMMING
String title;
int numPages;
//does not return a value
//use the keyword void
public void setNumPages(int numOfPages)
{
numPages = numOfPages;
}
//returns an int value
//use the keyword int
public int getNumPages()
{
return numPages;
}
Instantiating a class
You can create objects of a class based on how you designed your class. The process of creating
an object is called instantiation.
Syntax:
nameOfClass nameOfObject = new nameOfClass();
Example:
Book YellowPages = new Book();
The above example creates an object named YellowPages which is an instance of the Book class.
NOTE: A class constructor should be declared within the class that it is a constructor for.
52
ADVANCED PROGRAMMING
Syntax:
name_Of_Class_To_Create_A_Constructor_For([parameters])
{
Example:
class Book
{
String title;
int numPages;
public Book(int numPages)
{
this.numPages = numPages;
}
}
In the above example, the Book class contains a constructor with one parameter. The value given
to this parameter will be how many pages the book has.
Did you notice a new keyword in the above example? The keyword this is a special keyword
used when creating classes. The purpose of it is to refer to the current class.
Now we can instantiate a new Book object and automatically set how many pages it has based on
the class constructor.
Book object with 340 pages:
Book YellowPages = new Book(340);
Just as with the variables of a class, you can use the methods of a class with an object by
referring to them by name together with the object name.
Syntax:
objectName.methodName([parameters])
Example:
class Aclass
{
public static void main(String[] args)
{
Book ABook = new Book();
//set the number of pages in the book to 300
ABook.setNumPages(300);
//set the title of the book to "Read Me"
ABook.setTitle("Read Me");
System.out.println("Book title: " + ABook.getTitle());
System.out.println("Number of pages in the book: " + ABook.getNumPages());
}
}
NOTE: Because getTitle() and getNumPages() are used to return values, you can use them as
values themselves. This is why they are used inside of the System.out.println() statements.
Inheritance
Inheritance is the process by which a class gets the properties and methods of another class. The
idea behind inheritance is that it is not absolutely necessary to always build a class from scratch.
Instead, you can take an existing class, add a few new features to it, and have a new class based
on the already existing class. Inheritance is achieved through the use of the extends keyword.
Recall the Book class with all its variables and methods from above.
class Book
{
Sting title;
int numPages;
public void setNumPages(int numOfPages)
{
numPages = numOfPages;
}
public int getNumPages()
{
return numPages;
}
public void setTitle(String theTitle)
{
title = theTitle;
}
public String getTitle()
{
return title;
}
}
54
ADVANCED PROGRAMMING
This class is designed for objects which represent books, but what if you wanted to have a class
whose objects represent soft cover books only? This is where inheritance comes into the picture.
Instead of creating a whole new class for soft cover books, we will create a class for soft cover
books which extends the Book class.
NOTE: All classes in Java inherits from the class Object whether this is explicitly declared or
not. The Object class is the base class in Java.
Polymorphism
Polymorphism (meaning many forms) means that an instance of a class is also an instance of its
superclass. For example, if you create an instance of the SoftCoverBook class, it is automatically
an instance of the Book class because the SoftCoverBook class is a subclass of the Book class.
Furthermore, since all classes in Java inherit from the Object class, every instance of the
SoftCoverBook class as well as the Book class are automatically instances of the Object class.
Encapsulation
Encapsulation basically means data hiding. Through the use of encapsulation, you can declare
class variables as private so that objects of the class (as well as other classes) cannot access them
directly. You can then declare public methods within the same class that access these variables,
and then objects of the class (as well as other classes) can access the private class variables by
proxy through these public methods.
Example:
class Book
{
//declare a private class variable
private String title;
//declare a public method to set the title of the book
public void setTitle(String theTitle)
{
title = theTitle;
}
//declare a public method to get the title of the book
public String getTitle()
{
return title;
}
}
class Aclass
{
public static void main(String[] args)
{
//declare a new instance of the Book class
Book ABook = new Book();
ABook.setTitle("Greatest book ever");
//try to access the private variable title directly
//it will not work and an error will be generated
System.out.println(ABook.title);
}
}
Output:
AClass.java:12: title has private access in Book System.out.println(ABook.title); ^ 1 error
As you can see, an error is generated when trying to access a private variable directly. But if we
try to access it through a public method, it will work.
Handling events
There are several types of events that can happen in a Java program:
Window events - Occur when something happens with the program window such as maximizing
the window, minimizing the window, or closing the window.
Action events - Occur when something happens with a component such as the clicking of a
button
Focus events - Occur when a component gains or loses focus
Mouse events - Occur when something happens with the mouse such as moving the mouse or
clicking the mouse
56
ADVANCED PROGRAMMING
Key events - Occur when something happens with the keyboard such as a key is pressed or a key
is released.
Each event type has it's own interface that you need to implement in a program to handle those
events. These interfaces are located in the java.awt.event package.
Window events - WindowListener interface
Action events - ActionListener interface
Focus events - FocusListener interface
Mouse events - MouseListener, MouseMotionListener interfaces
Key events - KeyListener interface
Each interface has it's own methods to use to execute some code when certain events occur. For
example, the KeyListener interface has a keyPressed method that can be used to execute some
code when a key is pressed.
import java.awt.*;
import java.awt.event.*;
class FrameWithEvents implements WindowListener
{
}
Now we need to use the methods of the WindowListener interface to specify what happens
during window events.
//Window event methods
public void windowClosing(WindowEvent e)
{
System.out.println("The frame is closing.....");
}
public void windowClosed(WindowEvent e)
{
}
public void windowDeactivated(WindowEvent e)
{
}
............. .....................
NOTE: When you implement an interface, you have to define all of it's methods in your
program.
Example
57
ADVANCED PROGRAMMING
aFrame.addWindowListener(this);
import java.awt.*;
import java.awt.event.*;
class frame implements WindowListener
{
public frame()
{
Frame aFrame = new Frame();
aFrame.setSize(500, 500);
aFrame.addWindowListener(this);
aFrame.setVisible(true);
}
59