Java - A Step-by-Step Guide for Absolute Beginners
Java - A Step-by-Step Guide for Absolute Beginners
***
A Step-by-Step Guide for Absolute
Beginners
Daniel Bell
Please note the information contained within this document is for educational and entertainment
purposes only. No warranties of any kind are expressed or implied. Readers acknowledge that the
author is not engaging in the rendering of legal, financial, medical or professional advice. Please
consult a licensed professional before attempting any techniques outlined in this book.
By reading this document, the reader agrees that under no circumstances is the author responsible for
any losses, direct or indirect, which are incurred as a result of the use of the information contained
within this document, including, but not limited to, errors, omissions, or inaccuracies.
Java: A Step-by-Step Guide For Absolute Beginners
Copyright © 2019 by Daniel Bell.2nd Edition
All rights reserved. No part of this book may be used or reproduced in any manner whatsoever without
written permission except in the case of brief quotations em- bodied in critical articles or reviews.
Under no circumstances will any legal responsibility or blame be held against the publisher for any
reparation, damages, or monetary loss due to the information herein, either directly or indirectly.
Publisher: Amazon KDP & Guzzler Media LLC
http://www.guzzlermedia.com
Contact: contact@guzzlermedia.com
Book and Cover design by Angela W.T.
ISBN:
Imprint: Independently published
First Edition: April 2019
CONTENTS
INTRODUCTION
1-GETTING STARTED WITH JAVA
What is Java?
Java Environment
First Java Program
2-JAVA CLASSES AND OBJECTS
Constructors
Creating Objects
Accessing Variables and Methods
3-VARIABLES IN JAVA
Variable Declaration
Variable Initialization
Variable Types
4-JAVA DATA TYPES
Primitive Data Types
Non-Primitive Data Types
Type Casting and Type Conversion
5-ARRAYS IN JAVA
Single Dimensional Arrays
Multi-Dimensional Arrays
6-OPERATORS IN JAVA
Unary Operator
Arithmetic Operators
Logical Operators
Comparison Operators
7-DECISION MAKING STATEMENTS
if statement
if…else statement
if...else if...else Statement
Nested if
switch statement
8-JAVA LOOPS
for Loop
while Loop
do…while Loop
break Statement
continue Statement
9-JAVA METHODS
Creating Methods
Calling Methods
The void Keyword
Call by Value
Abstract Methods
Method Overloading
Command-Line Arguments
The this Keyword
Variable Arguments
Method Overriding
Recursive Functions in Java
10-INHERITANCE IN JAVA
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Invoking Superclass Constructor
The instance of Keyword
11-ABSTRACTION IN JAVA
12-ENCAPSULATION
13-INTERFACES
14-PACKAGES
Import Keyword
15-JAVA APPLETS
Applets’ Lifecycle
Displaying Images
Applet Animations
Events on Applets
Applet Parameters
16-JAVA INPUT/ OUTPUT
Byte Streams
Character Streams
Standard Streams
Reading and Writing Files
File Navigation
Listing Directories
17-EXCEPTION HANDLING
Catching Exceptions
Multiple Catch Blocks
Throw/Throws Keywords
Finally Statement
Try-with-resources
User-defined Exceptions
18-JAVA AWT
Handling Events
AWT Button
AWT Label
AWT TextField
AWT TextArea
AWT Checkbox
AWT CheckboxGroup
AWT Menu and MenuItem
KeyListener Interface
CONCLUSION
ABOUT THE AUTHOR
ACKNOWLEDGMENTS
Introduction
Java is a great programming language that can be used for the development
of both standalone and distributed applications. These types of applications
are on high demand today for both small and large enterprises. Java comes
with a feature known as apples which are web pages that can be embedded
on web browsers. This means that Java can help you add some functionality
to your web applications. You can now tell why Java is a popular
programming language with a high demand worldwide. It also has many
other features which you can take advantage of when developing your
application. For instance, Java is an object-oriented programming language.
If you are familiar with any other object-oriented programming language, it
will be easy for you to learn Java. Java has a simple syntax easy to grasp,
even by beginners.
It is easy to get started with writing and running Java programs. You only
need to have the Java compiler installed on your computer and a text editor
where you will write your code. With these, you can write your Java
programs and get instant results. For the case of the text editor, a basic text
editor like Notepad is okay although there are more advanced text editors
for Java-like NetBeans and Eclipse. Once you compile your Java code, you
get the Java byte-code which is platform independent, meaning you can
execute it on a machine running any type of operating system. This book is
an excellent guide for you to learn everything about Java. The author takes
you from the initial steps of getting started with Java to develop your own
Java application. Enjoy reading!
1-Getting Started with
Java
What is Java?
Java is both a platform and a programming language. As a platform, we
have the Java runtime environment (JRE) which is a software environment
on which programs can run. As a language, Java is a high-level, robust and
object-oriented programming language. The language was developed by
Suns Microsystems in 1995.
Since Java is an object-oriented programming language, it treats everything
as an object. The object model nature of the language also makes it easy for
us to extend it. Java programs go through two steps to generate results. The
first step is compilation after which the Java bytecode is generated. The
Java bytecode is platform independent, meaning that it can be run on any
machine. After the compilation, the bytecode is passed through the
execution step to generate the results.
Java is known to be an easy language. If you are familiar with the concepts
of object-oriented programming, then it will be easy for you to understand
Java. Java comes with a secure feature that allows developers to create
temper-free and virus-free systems. The public-key encryption is used as a
technique for securing the systems.
Java Environment
To write and running your Java programs, you must have the Java compiler
and a text editor such as Notepad in Windows. To get the Java compiler,
you must install the Java Development (JDK) on your computer. Once this
is installed, your computer will have the Java compiler.
Now you have the Java compiler, you must have a text editor in which you
will write your programs. You can use either a basic text editor or an
advanced text editor. Examples of advanced text editors you can use for
Java programming include NetBeans and Eclipse. You can download the
JDK from the following
URL:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-
downloads-2133151.html
Once the download is complete, just double click the setup file and the
installation process will begin. You will be taken through a sequence of
simple on-screen instructions for the installation to be done. Installation
alone is not enough as you have to do something for the Java installation
directories to be known. You have to set the path environment variable.
This way, you will be able to invoke the Java compiler from the terminal of
your operating system. In most cases, the installation of JDK is done in the
c:\Program Files\java\jdk directory. On windows, you can set the path
environment variable by right clicking “My Computer” then choosing
“Properties”. Next, open the “Advanced” tab then choose “Environment
variables”. Add the “c:\Program Files\java\jdk\bin” path. Linux users
are advised to read the documentation of their shells.
Once you have saved the above code, open the terminal of your operating
system and navigate to the directory where you have saved the file.
Run the following command on the terminal:
javac Hello.java
The above command should generate the Hello.class file. This is the file
with the Java byte code, which is platform-independent. You can confirm
this by checking the same directory for this file. What we have done is that
we have invoked the Java compiler (Jayac) on the file to compile the Java
code contained in the file.
Now that the code has compiled with no error, we can execute it. Just run
the following command on the same terminal:
java Hello
The above command should return results on the terminal as shown below:
The above output shows that the code returned Hello World as the output.
Consider the following line which I have extracted from the code:
What we are doing in the above line is that we are creating a class named
Hello. The H in the class name has been written in uppercase; hence we
must write the class that way anytime we are referring to it. Java is a case
sensitive language. The public is an access modifier, declaring the class as
public, meaning it can be accessed from the rest of the classes contained
within the same package. The opening curly brace { marks the beginning of
the body of the class and to close it, we must use the closing curly brace }.
Consider the following section extracted from the code:
/* my first java program
* the code will print 'Hello World'
*/
The above is a comment. Note that we have enclosed them within /* and */.
This is the way we denote block comments in Java. Comments can also be a
single line, and such are denoted using two forward slashes //. Here is an
example:
The above is referred to as the main method. No Java program can run or
execute without the main method. Here is another line extracted from the
code:
System.out.println("Hello World");
We have called a method named println to help us print the text we pass to
it on the display. You have also noticed that we have used two closing curly
braces }}. The first one closes the main method while the second one closes
the class.
2-Java Classes and
Objects
void eating() {
}
void barking() {
}
void sleeping() {
}
}
In the above example, we have defined a class named Dog. Three variables
have been defined inside this class, which are the name, breed, and color.
These are the properties of the Dog class. We have also defined 3 methods
for the class. These are eating(), barking() and sleeping(). We can define
many methods inside a class.
Constructors
Creating Objects
A c c e s s i n g Va r i a b l e s a n d M e t h o d s
In classes, one of the best ways for us to access instance variables and
methods is by creating objects. An instance variable can be accessed by
following the sequence of steps given below:
Va r i a b l e D e c l a r a t i o n
int a, x, p;
float pi;
double p;
char c;
The int, float, double and char are the data types, specifying the value each
variable can or should hold. To declare several variables in one line,
separate them using a comma (,) as in the first example. A variable
declaration should end with a semicolon (;).
Va r i a b l e I n i t i a l i z a t i o n
a =10.12768781;
c= ‘s’;
float pi=3.14f;
double p=15.23d;
char c= ‘s’;
Va r i a b l e Ty p e s
1. Local Variables
2. Static Variables
3. Instance Variables
L o c a l Va r i a b l e s
These are variables declared within a method body. They can only be
accessed from within that method.
I n s t a n c e Va r i a b l e s
These are the variables that have been defined without the use of a STATIC
keyword. These variables are specific to an object.
S t a t i c Va r i a b l e s
These are variables initialized once and at the beginning of program
execution. You should initialize them before instance variables.
The following example shows the different Java variables:
class VariablesExample {
int p = 1; //an instance variable
static int q = 5; //a static variable
void methodExample() {
int r = 10; //a local variable
}
}
The variable integer q is a static variable since it has been defined with the
static keyword. The variable int r has been declared within the
methodExample method, making it a local variable. It can only be accessed
from within that method.
4 - J a v a D a t a Ty p e s
In Java, a data type can be primitive or non-primitive.
These are the pre-defined data types that are already provided by Java. They
are 8 in number including byte, short, long, char, int, float, Boolean and
double data types.
Let us now discuss the various primitive data types in Java:
B o o l e a n
This data type stores only two values, which are true and false. It is used in
simple statements that track only true/false conditions. It specifies only
one bit of information, but we cannot define its size precisely.
B y t e
This has a default value of 0, and its minimum value is -128 (-2^7). It helps
in saving space in large arrays as it is 4 times smaller than integers.
S h o r t
It has a default value of 0 and values lying with the range of -32,768 to
32,767. It can also be used for saving on space just like the byte data type.
I n t
This also has a default value of 0 and values ranging between -
2,147,483,648 and 2,147,483,647. It has a minimum value of -
2,147,483,648 and a maximum value of 2,147,483,647.
L o n g
This data type also has a default value of 0 with its values ranging between
-9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. Its minimum
value is - 9,223,372,036,854,775,808 while its maximum value is
9,223,372,036,854,775,807. It is the best data type to use when you want to
have a long range of values than the o0nes provided by the int data type.
F l o a t
This data type has an unlimited range of values. It can help you save on
space compared to the use of a double. Avoid using this data type for
precise values like currency. Its default value is 0.0F.
D o u b l e
This data type has a default value of 0.0d and it comes with an unlimited
range of values. It used to represent values with the decimal part just like
the float data type. Avoid using it for precision values like currency.
C h a r
This data type is used for storing characters.
We have defined three integer variables p,q, and r. The values for p and q
have been initialized, while the value for r is the addition of the previous
two variables. We have then invoked the println function to print the value
of r. It should print 32, the result of the addition of 10 and 22. This is shown
below:
32
double p;
int q=6;
p-q;
Typecasting is when a variable of larger capacity is assigned some other
variable of a smaller capacity.
Example:
p =6;
int q;
q= (int) p;
The (int) is known as the type cast operator. If it is not specified you get an
error. Typecasting example:
<elementDataType>[] <arrayName>;
Another syntax:
<elementDataType> <arrayName>[];
Example:
int arrayExample[];
int []arrayExample;
arrayExample[0]=20;
The line states that the element 1 should be stored at index 0 of the array.
An array can also be declared and initialized simultaneously:
Example:
}
}
The array will print the elements contained at different indices as shown
below:
The program will return the value stored at index [0][0] and index [1][1] as
shown below:
6-Operators in Java
Operators are symbols used to perform operations. For example, the +
symbol is used for arithmetic operations. Java supports different operators:
Unary Operator
Arithmetic Operators
Logical Operators
These operators are used together with binary values. They help in the
evaluation of conditions in loops and conditional statements. They include
||, &&, !. Suppose we have two Boolean variable a1 and a2, the following
conditions apply:
• a1&&a2 will return true if both a1 and a2 are true, otherwise, false.
• a1||a2 will return false if both a1 and a2 are false, otherwise true.
• !a1 will return the opposite of a1.
Example:
public class JavaLogicalOperator {
public static void main(String args[]) {
boolean p = true;
boolean q = false;
The value of variable p has been set to true while that of variable q has
been set to a false. In the first case, we are using && operator, hence true
and false return a false. In the second case, we are using the || operator,
hence true or false give a true. In the last case, we are negating the result of
the && operation.
Comparison Operators
Java supports 6 types of comparison operators, ==, !=, <, >, >=, <=:
• == will return true if both left and right sides are equal.
• != will return true if the left and right sides of the operator are not
equal.
• > returns true if the left side is greater than the right side.
• < returns true if the left side is less than the right side.
• >= returns true if the left side is greater than/equal to the right.
• <= returns true if the left side is less than the right side.
Example:
if( p != q ){
System.out.println("p and q aren’t equal");
}
else{
System.out.println("p and q are equal");
}
if( p > q ){
System.out.println("p is greater than q");
}
else{
System.out.println("p isn’t greater than q");
}
if( p >= q ){
System.out.println("p is equal to or greater than q");
}
else{
System.out.println("p is less than q");
}
if( p < q ){
System.out.println("p is less than q");
}
else{
System.out.println("p isn’t less than q");
}
if( p <= q){
System.out.println("p is equal to or less than q");
}
else{
System.out.println("p is greater than q");
}
}
}
if statement
if(A_boolean_expression) {
// Statement(s) to be run if true
}
The statements within the body of the expression will run if the condition is
true, otherwise, no result from the program.
Example:
if( x < 10 ) {
System.out.print("The value of x is below 10");
}
}
}
if…else statement
This statement combines an “if” with “else”, with the latter specifying the
statement(s) to run if the expression is false. Syntax:
if(A_boolean_expression) {
// Statement(S) to run if expression is true
}else {
// Statement(s) to run if expression is false
}
Example:
public class JavaIfElseStatement {
public static void main(String args[]) {
int marks = 30;
The first statement will be printed, the marks are below 50. This is
because the Boolean expression will be true. If it is false, the other
statement will be printed.
Example:
if( x < 5 ) {
System.out.print("The value of x is below 5");
}else {
System.out.print("The value of x is above 5");
}
}
}
if(A_boolean_expression a) {
// Statement(s)
}else if(A_boolean_expression b) {
// Statement(s)
}else if(A_boolean_expression c) {
// Statement(s)
}else {
// Statement(s)
}
Example:
if( x == 10 ) {
System.out.print("value of x is 10");
}else if( x == 15 ) {
System.out.print("value of x is 15");
}else if( x == 20 ) {
System.out.print("value of x is 20");
}else {
System.out.print("None of the above");
}
}
}
The value of variable x was initialized to 15, hence the test condition for 15
tested to a true. The statement below was executed to give us the above
result.
Here is another example:
if(marks<40){
System.out.println("You fail");
}
else if(marks>=40 && marks<50){
System.out.println("You scored D grade");
}
else if(marks>=50 && marks<60){
System.out.println("You scored C grade");
}
else if(marks>=60 && marks<70){
System.out.println("You scored B grade");
}
else if(marks>=70){
System.out.println("You scored A grade");
}
}
}
The value of variable marks is 64, hence it lies between 60 and 70. The else
if the condition for that will test to a true hence the statement within its
body will be executed.
Nested if
The if…else statements can be nested, meaning that one may use an if
inside another if or an if…else inside another if…else.
The nesting the syntax is shown below:
if(A_boolean_expression a) {
// Statament(s)
if(A_boolean_expression b) {
// Statament(s)
}
}
Example:
public class NestingExample {
if(age>=18){
if(weight>55){
System.out.println("You can donate blood.");
}
}
}
}
If the first condition becomes true, the second condition will test. This is
true in our case; hence the println statement was executed. If any of the
conditions is false, then the println statement will not be executed. This
means that for the println statement to be executed, all the conditions must
test to a true.
switch statement
This statement allows us to test a certain variable for equality against some
values list. Every value is referred to as a case.
The following syntax is used:
switch(an_expression) {
case value:
// Statement(s)
break; //optional
case value:
// Statement(s)
break; //optional
default : //Optional
// Statement(s)
}
The switch will end once it has reached the break statement. The flow will
then jump to the next line. However, note that there is not an obligation to
add a break to every case. A default case may add to the end of the switch,
and this will run if none of the cases is true.
Example:
switch(your_grade) {
case 'A':
System.out.println("That is Excellent!");
break;
case 'B':
System.out.println("That is Good!");
break;
case 'C':
System.out.println("That is Fair!");
break;
case 'D':
System.out.println("That is Poor!");
case 'F':
System.out.println("You Failed!");
break;
default:
System.out.println("Unknown grade");
}
System.out.println("You scored " + your_grade);
}
}
The case for grade A tested to a true, hence the source of the above output.
The last println statement will execute in all cases regardless of the value of
the grade.
8-Java Loops
Java loops help us do some tasks repeatedly. Loops execute the statements
in a sequential manner. The first one is run first, followed by second, etc.
Let us discuss the various types of loops supported in Java:
for Loop
The loop is run provided condition tests to true. The execution will stop
immediately the condition becomes false. Syntax:
The initialization defines the initial value of the loop condition. The
loop_condition specifies the condition that must always be true for loop to
run. The loop_increment/decrement defines the amount by which the
initialization value will be incremented or decremented after any iteration.
Example:
public class ForLoopExample {
public static void main(String args[]){
for(int p=0; p<10; p++){
System.out.println("The value of p now is: "+p);
}
}
}
The output shows that the loop returns the values of variable p from 0 to 9.
When the loop increments the 9 to get 10, it will find that it is violating the
loop condition, p<10, hence the execution will stop immediately.
while Loop
while(A_boolean_expression) {
// Statement(s)
}
Example:
public class JavaWhileLoopExample {
while( p < 12 ) {
System.out.print("The value of p is: " + p );
p++;
System.out.print("\n");
}
}
}
The program prints p’s value from 5 to 11. The variable’s initial value is 5.
The test condition checks whether this value is less than 12, which is true.
This means the loop will run. When it reached 11, it will check and find the
value of p is 12. The execution of the loop then stops immediately since
continuing to execute it will violate the loop condition.
do…while Loop
This is closely related to the while loop. In the while loop condition,
execution is done before loop body execution. This is the opposite in do…
while loop as the body is executed first before the condition. In while loop,
the loop body may never be executed, but in do…while loop, the loop body
must be executed for at least once.
Syntax:
do
{
Statement or statements;
} while(loop_condition);
Example:
public class JavaDoWhileLoop {
do {
System.out.print("The value of p is: " + p );
p++;
System.out.print("\n");
}while( p < 12 );
}
}
The code will print the value of p from 5 to 11 just as in the previous loop.
This is because the condition is true, 5 is less than 12. Suppose we set loop
condition as false, for example, initialize the value of p to 20 as shown
below:
do {
System.out.print("The value of p is: " + p );
p++;
System.out.print("\n");
}while( p < 12 );
}
}
After running the above program, you will get the following output:
This means that the while condition is false. This is because the Java
compiler first runs through the program for the initial value of p which is
20. That value is printed. Once it moves to loop condition, it violates the
condition, p<20, hence loop execution stops immediately.
There are two statements that are used for controlling how Java loops are
executed. They are called continue and break statements. They work by
changing the normal way of executing a loop.
Let us discuss them.
break Statement
This statement causes the execution of a loop to a halt, and control jumps to
the statement that comes next after the loop. It also stops a case in a switch
statement.
Syntax:
your-jump-statement;
break;
Example:
public class BreakStatementExample {
public static void main(String[] args) {
for(int p=0;p<=10;p++){
if(p==6){
break;
}
System.out.println("The value of p is:" +p);
}
}
}
The increment is done from 0 to 5, and once it notices that the value of p is
6, it will halt immediately as it will violate the above condition. For the case
of nested loops, the break can be added to the inner loop and it will break it.
This will cause the inner loop to break once the specified condition is met.
Example:
continue Statement
This statement makes the loop jump to next iteration immediately. It helps
the loop to continue after a jump. Note that in the previous case, the loop
halted immediately. This statement can help it resume execution in the next
iteration after the jump.
Example:
your_jump-statement;
continue;
Example:
All values between 10 and 20 have been printed except 15. The continue
statement may also be used with an inner loop. In such a case, it will only
continue your inner loop.
Example:
public class JavaContinueStatament2 {
public static void main(String[] args) {
for(int p=1;p<=3;p++){
for(int q=1;q<=3;q++){
if(p==2&&q==2){
continue;
}
System.out.println(p+" "+q);
}
}
}
}
Creating Methods
return min;
}
In the above example, we have defined a method named
minimumFunction. This function takes two arguments of an integer data
type. The method should compare two integer values you pass to it and
return the minimum one. Thus, we can define a method in Java.
Calling Methods
After defining a method, you can only use it by calling it. Note that
depending on the definition of the method, it may or may not return a value.
Once a program has called a method, the control of the program is shifted to
the called method. The control will only be returned to the program under
two conditions:
return min;
}
}
We have used the minimumFunction that checks and returns the minimum
of two numbers. In the above example, we have passed to it the values 10
and 13. It returned 10 since it is the minimum one.
This is the keyword we used to define a method that should not return a
value. Let us show this using an example:
As you have noticed, we have not used the return keyword within the body
of the method.
C a l l b y Va l u e
The method call is a way of invoking java functions. Java supports call-by-
value. There is no call-by-reference in Java. When calling by-value, the
original value isn’t changed.
Example:
}
}
When calling by-reference, the original value will change if changes are
made to call method. If an object is passed in place of primitive value, the
original value changes.
Example:
}
}
The value has changed from 10 to 60, after adding 50. This is shown in the
output given below:
Abstract Methods
You may declare a method and then need its implementation to be done in
child classes. The class can be marked as abstract in the parent class. Add
abstract keyword before the method name. Abstract methods don’t have a
method body. You only add a semicolon (;) at its end.
Example:
public abstract class Worker {
private String workerName;
private String workerAddress;
private int workerNumber;
Note that an abstract method must only be declared in the abstract class.
The getPay() method above is abstract. We can have a class inheriting from
the Worker class then implement the getPay() method in it:
Method Overloading
This occurs when we have two or more methods with one name but
different parameters. The difference in parameters can be in terms of
number or type.
Consider the example given below:
// for integer
public static int minimumFunction(int p, int q) {
int min;
if (p > q)
min = q;
else
min = p;
return min;
}
// for double
public static double minimumFunction(double p, double q) {
double min;
if (p > q)
min = q;
else
min = p;
return min;
}
}
Command-Line Arguments
We referred to the above as the main() method and no Java program can be
executed without this method. It can also be written as follows:
The [] denotes an array and we can pass arguments to it. Note that these
arguments will begin from index 0.
Consider the example given below :
public class CommandLineArguments {
Run the code from the command line. After compiling the code, pass the
arguments to the terminal as showed below:
The this Keyword
The this keyword is used in Java to refer to the object of the current class,
within a constructor or instance method. The keyword can be used for
referencing the members of a class such as variables, methods, and
constructors. It helps in differentiation between local variables and instance
variables when they have similar names within a method or constructor.
The following example shows how this keyword can be used:
class Person {
int age;
Person(int age) {
this.age = age;
}
}
Let us show how we can use this keyword to access the various members of
a class:
This_Class() {
System.out.println("Demonstrating the use of this keyword in Java");
}
This_Class(int x) {
// Invoke the default constructor
this();
Va r i a b l e A r g u m e n t s
type_Name... parameter_Name
Method Overriding
A subclass can override a method defined in the parent class if it was not
declared with the final keyword. Overriding means overriding functionality
of the existing method.
Example:
class Mammal {
public void run() {
System.out.println("Mammals can run");
}
}
}
}
Here, mb is a Mammal type, but it can use the method defined in Cow
class.
Another Example:
We will take a bank example. Different banks offer different interest rates
on loans:
class LendingInstitution{
int getInterestRate(){
return 0;
}
}
}
}
}
}
class LendingInstitution3 extends LendingInstitution{
int getInterestRate(){
return 14;
}
}
class Mammals {
public void run() {
System.out.println("Mammals can run");
}
}
returntype method(){
//code to run
method();//call same method
}
Example:
If you run the above code, it will keep on printing the Hello there text. The
method helloMethod() will call itself infinite times because we have not
specified the number of times that the method should call itself. The
implementation for a method to call itself finite times may be implemented
in this way:
Note that the Fibonacci of a number is the sum of two of its previous
numbers. In the above example, we have done the recursion for 18 times.
10-Inheritance in Java
In inheritance, an object gains the behaviors and properties of another
object. The object gaining the behaviors and the properties becomes the
child, while the object from which they are inherited is the parent. They
can also be referred to as subclass and superclass, respectively. Inheritance
makes information manageable in a hierarchical order. The methods that
had been defined in the superclass can be reused in the subclass without
defining them again.
To Inherit from a parent class, we use the extends keyword. Inheritance is
done using the syntax given below:
class Child-class-name extends Parent-class-name
{
// fields and methods
}
The extends keyword is an indication that we are creating some new class
from the existing class.
Example:
class Employee{
float employee_salary=60000;
}
public class Developer extends Employee{
int commision=20000;
public static void main(String args[]){
Developer d=new Developer();
System.out.println("developer salary is:"+d.employee_salary);
System.out.println("Commision for Developer is:"+d.commision);
}
}
We first created a class named Employee. This forms the parent class for an
example. We have then created the class named Developer which extends
the Employee class. The Developer class becomes the child class. We have
created an instance/object of the Developer class and given it the name d.
By using this instance; we could access a variable that was defined in the
parent class.
There are different types of inheritance in Java. Let us discuss them:
Single Inheritance
Here, a single class inherits from another class. The Worker and DBA
classes given previously are an example of this.
Example:
class Mammal{
void run(){
System.out.println("Running...");
}
}
class Cow extends Mammal{
void moow(){System.out.println("Moowing...");}
}
public class JavaInheritance{
public static void main(String args[]){
Cow cw=new Cow();
cw.moow();
cw.run();
}
}
In the above example, the run() method has been defined in the Mammal
class while the moow() method has been defined in Cow class which
extends the Mammal class. In the JavaInheritance class, we have created
an instance of Cow class and named it cw. We have then used this instance
to access the two methods that have been defined in two different classes.
Multilevel Inheritance
This type of inheritance occurs when class B inherits from class A, while
class C inherits from class B.
Here is an example:
class Mammal{
void run(){
System.out.println("Running...");
}
}
class Cow extends Mammal{
void moow(){
System.out.println("Moowing...");
}
}
class BabyCow extends Cow{
void eat(){
System.out.println("Eating...");}
}
public class JavaInheritanceTest2{
public static void main(String args[]){
BabyCow bc=new BabyCow();
bc.moow();
bc.eat();
bc.run();
}
}
The run() method has been defined in the Mammal class. The moow()
method is defined in the Cow class which extends the Mammal class. The
eat() method has been defined in the BabyCow class which extends the
Cow class. In the InheritanceTest2 class, we have created an instance of
BabyCow class named bc. This instance has then been used to access
various properties or methods. We can use the instance of BabyCow class to
access methods defined in the Cow and Mammal classes. The methods in
various classes can be seen as their properties.
Hierarchical Inheritance
class Mammal{
void run(){
System.out.println("Running...");
}
}
class Cow extends Mammal{
void moow(){
System.out.println("Moowing...");
}
}
class Goat extends Mammal{
void meew(){
System.out.println("Meewing...");
}
}
public class JavaInheritanceTest{
public static void main(String args[]){
Goat gt=new Goat();
gt.meew();
gt.run();
//gt.moow(); will give an Error
}
}
That is the closest way by where we can get to the multiple inheritance
feature in Java. For the class, we keyword “extends”, but this cannot be
used for an interface. Instead, we use keyword implements. By this way, we
can inherit the features of an interface. Inheritance helps in the reuse of
existing properties and methods.
class MySuperclass {
int x;
MySuperclass(int x) {
this.x = x;
}
interface Mammal{}
class Cow implements Mammal{}
The class Worker is like other Java classes except for the use of the abstract
keyword. Attempt to instantiate it:
The Worker class cannot be instantiated, but Wage class can be instantiated
and then we can use its instance to access all fields and methods of Worker
class.
Example:
To run the above codes, you must create files in different files compile and
execute the last class.
Then, you will get the results. This is showed below:
12-Encapsulation
Encapsulation is a feature of object-oriented programming that helps in
grouping data and methods together. The data are the variables while
methods are the codes that let us act on the data. With encapsulation, class
variables can be hidden from other classes and the access to them may only
be possible via methods of the class. Encapsulation works as a Data
Hiding. It’s achieved by setting class variables as private. The “setter” and
“getter” methods for the variables should be set as public and be used to
change the value of the variables.
Example:
The variable name was marked as private in Workers class. The methods
setWorkerName() and getWorkerName() were set as public in Workers
class. We have instantiated Students class in TestWorkers class, then we
have used this instance to access its variable and methods.
Another example:
Any class that needs of accessing private variables must use public
methods: the setters and getters.
We access using methode given below:
interface <interfaceName>{
//constant fields
// abstract methods
}
An interface is an implicit abstract; hence we don’t add abstract keyword
when declaring it. The methods are implicitly abstract; hence we don’t use
abstract keyword when declaring them. They are implicitly public.
Example:
interface Mammal {
public void run();
public void eat();
}
interface Mammal {
public void run();
public void eat();
}
We defined Toyotas interface. The others, Harrier and Prado are extending
the Toyotas interface. The interface Prado has four methods, but two of
these have been inherited from Toyotas interface. You may inherit from
several interfaces by use of (,) to separate them.
Example:
interface ObjectInterface{
void drawObject();
static int cubeObject(int ab){return ab*ab*ab;}
}
class Cuboid implements ObjectInterface{
public void drawObject(){
System.out.println("drawing cuboid");
}
}
public class InterfaceTest{
public static void main(String args[]){
ObjectInterface ob=new Cuboid();
ob.drawObject();
System.out.println(ObjectInterface.cubeObject(3));
}
}
A nested interface is the one we can add inside another interface. Example:
interface Message{
void printMessage();
interface ShortMessage{
void message();
}
}
The ShortMessage interface has been defined inside the Message interface,
making it a nested interface.
14-Packages
Packages are essentials for grouping related interfaces and classes together.
The grouping is determined by functionality. With packages, we can group
classes and find the ones we need easily to avoid conflicts. It is
recommended that you create a package and then use it to group related
classes, interfaces, etc. With packages, it’s easy to access variables and
methods defined in classes and interfaces in the same package.
A Java package can be user-defined or built-in. Examples of built-in Java
packages include lang, awt, java, javax, net, io, swing, util, sql, and
others. To use these packages, use the import statement to be made
available in your class. To create packages, use package keyword then
package name.
Example:
package firstpackage;
public class MyPackage{
public static void main(String args[]){
System.out.println("My first package");
}
}
package animal;
interface Mammals {
public void run();
public void eat();
}
package animal;
interface Mammals {
public void run();
public void eat();
}
Import Keyword
You can access packages outside a certain package. Using the import
keyword is one of the possibilities to do it. To access a class in the same
package, it unnecessary for a package to be used. After importing class
using the packagename.classname syntax, only methods in imported class
will be accessible.
Example:
package hellopackage;
public class HelloClass{
public void messsage(){
System.out.println("Hello there!");
}
}
package studentspackage;
class HelloStudentsClass{
public static void main(String args[]){
HelloClass hello = new HelloClass();
hello.message();
}
}
class HelloStudentsClass{
public static void main(String args[]){
HelloClass hello = new HelloClass();
hello.message();
}
}
A name for package and class is useful to avoid an error. With this
methode, we do not need to use the import keyword since the name will
direct us to the package and class, and then the method will be accessible
from there.
Example:
package hellopackage;
public class HelloClass{
public void messsage(){
System.out.println("Hello there!");
}
}
To use the message() method in a class in another package, we can do it as
follows:
package studentspacks;
class HelloStudentsClass{
public static void main(String args[]){
hellopackage.HelloClass hello = new hellopackage.HelloClass();
hello.message();
}
}
package armory;
interface guns {
public void pistol();
package armory;
public class ceska implements guns {
public void bullets() {
System.out.println("Ceska has bullets");
}
public void pistol() {
System.out.println("It has 5 bullets");
}
public int owner() {
return 0;
}
public static void main(String args[]) {
ceska cs = new ceska();
cs.bullets();
}
}
15-Java Applets
Applets are Java programs that run on web browsers. An applet may act as
a fully functional app since it comes with a full Java API. The applet class
extends java.applet.Applet. Applets don’t have the main method, hence
they don’t invoke main(). They are instead embedded on HTML pages.
After an HTML page with an applet is opened, its code is downloaded to
the local machine. The JVM (Java Virtual Machine) is mandatory for you to
view applets.
Applets are processed on the client side; hence they give users a quick
response compared to other apps. Applets offer good security.
Applets’ Lifecycle
Applets go through these steps:
1. Initialization- the init() method initializes applets.
2. Starting- the start() method starts applets.
3. Painting- done after calling paint() method.
4. Stopping- we invoke stop() method to stop an applet.
5. Destroying- the applet is destroyed by invoking destroy()
method.
Applets are viewed by HTML.
Example:
Create a new file in text editor with name FirstApplet.java. and add this
code to it:
import java.awt.Graphics;
import java.applet.Applet;
public class FirstApplet extends Applet{
Create new file in editor named mycode.html. Add this code to it:
<html>
<body>
<applet code="FirstApplet.class" width="320" height="320">
</applet>
</body>
</html>
First, we have Java code in which we added code regarding what our applet
should do. The class is named MyApplet. Consider this:
We are drawing the “Our First Applet! Text at points 150, 150 of the applet
window. Note the two libraries added via import statement: Graphics and
Applet libraries. The paint() method is defined in Graphics library. If we
don’t import it, an error will be generated since Java compiler won’t
understand what we mean. We have HTML code in file mycode.html. In
this, we created a window on which to draw text.
Note how we have linked HTML code and Java code:
javac FirstApplet.java
This will generate FirstApplet.class file. We can use the appletviewer for
our applet viewing. Run this command on the console:
appletviewer mycode.html
A window should popup with the text OurFirstApplet!. That is the Applet.
Change the point where the text is drawn by altering the coordinates. It will
change the location on the window.
Try this and see the shapes generated:
Create file MyPaint.java with this code:
import java.applet.Applet;
import java.awt.*;
public class Mypaint extends Applet
{
public void paint(Graphics gc){
gc.drawOval(130, 40, 60, 50);
gc.drawLine(200,160,240,240);
gc.drawLine(240,240, 280,160);
}
}
import java.applet.Applet;
import java.awt.*;
public class OurPaintClass extends Applet
{
public void paint(Graphics g){
}
}
<HTML>
<TITLE>Hello World</TITLE>
<HEAD>Our Hello Applet</HEAD>
<Applet code="OurPaintClass.class" width=500 height=500>
</Applet>
</html>
import java.awt.*;
import java.applet.*;
public class ImageDisplay extends Applet {
Image img;
The drawImage() method displays the image. Its 4th parameter is an object
for ImageObserver. Save the code in a file named ImageDisplay.java. Add
this code to a file named imagedisplay.html:
<html>
<body>
<applet code="ImageDisplay.class" width="350" height="350">
</applet>
</body>
</html>
Compile Java class via command javac ImageDisplay.java, then invoke the
imagedisplay.html file via appletviewer. If you specified a correct image in
the same directory with these files, it will be shown on the window.
Applet Animations
Image img;
try{
Thread.sleep(100);
}
catch(Exception ex){
}
}
}
}
The method drawImage() helps us display an image. Create new file named
animation.html. and add this code:
<html>
<body>
<applet code="AnimationExample.class" width="350" height="300">
</applet>
</body>
</html>
Compile the .java class then run the .html file. Ensure the correct image is
specified in the .java class and keep it in the same directory as the files. It
will move after running the code.
Events on Applets
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class AppletEventExample extends Applet implements ActionListener{
Button btn;
TextField txt;
btn=new Button("Click");
btn.setBounds(80,150,60,50);
add(btn);
add(txt);
btn.addActionListener(this);
setLayout(null);
}
btn.addActionListener(this);
The command adds action listener event to our button, the button will wait
or listen to be clicked. After the click, the action specified in the
actionPerformed() method will be performed.
Create new file myapplet.html then add this:
<html>
<body>
<applet code="AppletEventExample.class" width="350" height="350">
</applet>
</body>
</html>
import java.awt.Graphics;
import java.applet.Applet;
<html>
<body>
<applet code="AppletParameters.class" width="350" height="350">
<param name="message" value="Applet Parameters">
</applet>
</body>
</html>
In the above HTML code, the value for param name should much the value
of the argument passed to getParameter() method in Java class.
Now, compile your Java code via javac AppletParametersExample.java
command. The AppletParametersExample.class file will be generated.
Invoke the html code via appletviewer appletcode.html.
You should then get the window given below:
This text was specified in the value attribute of param name in HTML
code.
16-Java Input/ Output
The java.io package comes with many classes we can use to perform
input/output tasks. The input/output concept in Java is implemented by the
use of streams. The stream is provided with the java.io package and it
supports different types of data including localized variables, object,
primitives, etc.
A stream is simply a sequence of data. There are two types of Streams:
• InPutStream – used for reading data from the source.
• OutPutStream –used for writing data to the destination.
Byte Streams
Java streams are made up of bytes. The Java byte streams perform
input/output operations of 8-bit bytes. There are several classes that are
related to the byte streams, but the common ones are FileInputStream and
FileOutputStream. Let us use an example which demonstrates how we can
use these two classes:
import java.io.*;
public class CopyingFiles {
try {
inp = new FileInputStream("colleagues.txt");
outp = new FileOutputStream("output.txt");
int ch;
while ((ch = inp.read()) != -1) {
outp.write(ch);
}
}finally {
if (inp != null) {
inp.close();
}
if (outp != null) {
outp.close();
}
}
}
}
The code will read the contents of the file colleagues.txt and copy them into
a new file named output.txt. Note that the latter will be created
automatically, and the contents copied into it.
Character Streams
Character Streams are used for performing input and output operations of
16-bit Unicode. There are many classes that are associated with character
streams. The most popular are the FileReader and FileWriter. Internally,
the FileReader uses the FileInputStream while FileWriter uses
FileOutputStream, but the major difference between them is that the
FileReader reads two bytes each time while FileWriter writes two bytes
each time. Let us use these two classes to rewrite our previous example:
import java.io.*;
public class CopyingFiles {
try {
inp = new FileReader("colleagues.txt");
outp = new FileWriter("output.txt");
int ch;
while ((ch = inp.read()) != -1) {
outp.write(ch);
}
}finally {
if (inp != null) {
inp.close();
}
if (outp != null) {
outp.close();
}
}
}
}
When you compile and run the code, it will copy the contents of the file
colleagues.txt into a new file named output.txt.
Standard Streams
In each programming language, a way is provided through which a user can
enter input through the keyboard and the input will be displayed on the
computer screen. We have three standard streams we can use for this
purpose:
• Standard Input − used for feeding data to the user's program with
the keyboard and used as the standard input stream. It is represented using
System.in.
• Standard Output − used to output data produced by the user's
program with the computer screen and used as the standard output stream. It
is represented using System.out.
• Standard Error − used to output error data generated by the user's
program with the computer screen and used as the standard error stream. It
is represented using System.err.
Consider the example given below:
import java.io.*;
public class ReadFromConsole {
try {
inp = new InputStreamReader(System.in);
System.out.println("Enter 'q' to quit.");
char ch;
do {
ch = (char) inp.read();
System.out.print(ch);
} while(ch != 'q');
}finally {
if (inp != null) {
inp.close();
}
}
}
}
Compile the code from the command line and execute it. When prompted,
type the letter ‘q’ then hit the enter key. See what happens.
You notice that once you press the letter ‘q’ and hit the enter key, the
program will quit.
You can run the code again and keep on pressing other letters and even
numbers on the keyboard. Keep on pressing the enter key after every
character you type. The program will only exit when you press the letter
‘q’.
This is showed below:
Reading and Writing Files
In the above example, the constructor takes the name of a file as a string for
creation of an input stream object for reading the file. Consider the next
example given below:
The constructor given above takes the name of a file as the string then
creates an input stream object for writing the file.
The second constructor can be used as shown below:
File f = new File("F:/java/names");
OutputStream f = new FileOutputStream(f);
The constructor given above takes a file object for creating an output stream
object for writing to a file. We have first called the File() method to create a
file object. The following example shows how to use these:
import java.io.*;
public class FileStreamExample {
try {
byte bWrite [] = {3,11,23,34,52};
OutputStream os = new FileOutputStream("myfile.txt");
for(int p = 0; p < bWrite.length ; p++) {
os.write( bWrite[p] ); // to write the bytes
}
os.close();
Compile and run the code. It will generate a file named myfile.txt and it will
write the specified numbers into that file. Note that the numbers will be
written using a binary format. The output you get on the screen will also be
in a binary format.
File Navigation
There are several classes in Java that can help us understand the concept of
navigation.
F i l e C l a s s
This Java class represents both files and the directory pathnames in a
hastily manner. It is the class we use for creating files and directories file
deletion, file searching, etc. We use the file object to represent the real
file/directory on the disk. The following example shows how we can create
a File object and use it:
import java.io.File;
// to print
System.out.println(" is executable: "+ bool);
}
} catch (Exception ex) {
// in case an I/O error occurs
ex.printStackTrace();
}
}
}
The code will get the directory of the files and tell you whether or not the
files are executable.
F i l e R e a d e r C l a s s
This is a Java class that inherits the InputStreamReader class. We use it for
reading character streams. The class also comes with many constructors we
can use for the creation of the objects we want. Here are the constructors
provided with this class:
• FileReader(File file)- this is a constructor for creating a new reader
when it is given the file from which it is to read.
• FileReader(FileDescriptor fd)- a constructor for creating a new
FileReader when it has been provided with the FileDescriptor from which
it should read.
• FileReader(String fileName)- this is a constructor for creating a
new FileReader when provided with the file from which to read.
The following example shows how to use this class:
import java.io.*;
public class FileReadExample {
for(char c : ch)
System.out.print(c); // print the characters
fr.close();
}
}
The code will give the output given below upon execution:
F i l e Wr i t e r C l a s s
This is a Java class that inherits the OutputStreamWriter class. We use this
class when we need to write streams of characters. The class comes with
many constructors that can be used for the creation of objects. They
include:
• FileWriter(File file)- this is a constructor for creating a FileWriter
object when given the File object.
• FileWriter(File file, boolean append)- this is a constructor for
creating a FileWriter object when given the File object having a Boolean
that shows whether or not the given data should be appended.
• FileWriter(FileDescriptor fd)- this is a constructor for creating a
FileWriter object that is associated with the file descriptor that is given.
• FileWriter(String fileName)- this constructor will create a
FileWriter object when given the file name.
• FileWriter(String fileName, boolean append)- this constructor will
create a FileWriter object when given the file name with a Boolean that
shows whether or not the written data should be appended.
Here is an example showing how to use this Java class:
import java.io.*;
public class FileReadExample {
for(char c : ch)
System.out.print(c); // print the characters
fr.close();
}
}
Listing Directories
To see all the directories and the files in a particular directory, you can use
the list() method provided by the File object. This is showed using the
following example:
import java.io.File;
public class ReadDirectory {
try {
// creating a new file object
f = new File("/tmp");
import java.io.File;
import java.io.FileReader;
Both the read() and write() methods have thrown the IOException, but the
Java compiler could handle this together with the FileNotFound exception.
An unchecked exception is a kind of exception that occurs during the
program execution time. Such exceptions are also referred to as runtime
exceptions. Examples of such exceptions are programming bugs like
improper use of APIs and logic errors. A good example of that is when you
try to access an array element that is out of bounds as showed below:
Catching Exceptions
To catch exceptions in Java, we combine the try and catch keywords. The
code that is more likely to generate an error is surrounded using the
try/catch block. The code placed within the try/catch block is referred to as
the protected code. Here is the syntax for using this statement:
try {
// the protected code
} catch (ExceptionName ex1) {
// the Catch block
}
After the occurrence of the exception, it will be handled by the catch block
you have created. Anytime you create a try block, it must be followed by
either the catch or the finally block. If the exception that has occurred has
been defined in the catch block, it will be passed to the catch block in the
same way that an argument is passed to a method.
Here is an example:
import java.io.*;
In the above example, we have defined an array with 3 elements but we are
trying to access its 4th element. The code will return the following result
upon execution:
We can create a try block followed by many catch blocks. This should be
done following the syntax given below:
try {
// the protected code
} catch (ExceptionType1 ex1) {
// A Catch block
} catch (ExceptionType2 ex2) {
// A Catch block
} catch (ExceptionType3 ex3) {
// A Catch block
}
In the above syntax, we have created three catch blocks and a single try
block. However, it is possible to use any number of catch blocks for a single
try block. When an exception has occurred within the protected code, it will
be thrown to the first catch block. If the exception’s data type matches the
ExceptionType1, then it will be caught there. If this doesn’t occur, the
exception will be thrown to the second catch block. This will continue for
all the catch blocks in the code. If the exception is not caught, the method
will halt the execution.
The following is an example of a code that shows how to use multiple catch
statements:
try {
f = new FileInputStream(file_Name);
x = (byte) f.read();
} catch (IOException io) {
io.printStackTrace();
return -1;
} catch (FileNotFoundException ex) // Not valid! {
ex.printStackTrace();
return -1;
}
Throw/Throws Keywords
import java.io.*;
public class ExceptionTest {
In the above example, we have the method save() which has declared that it
is throws a RemoteException. It is possible for one method to declare that
it will throw many exceptions, in which you should use commas (,) to
separate the exceptions.
Consider the following example that shows how to implement this:
import java.io.*;
public class ExceptionTest {
Finally Statement
The finally block comes after the try or catch block. This block will always
be executed, regardless of whether or not the exception occurred. The final
statement provides you with a good way of running your cleanup-type
statements you need to be executed regardless of what happens inside your
protected code. It should be added at the end of the catch blocks as showed
in the following syntax:
try {
//The protected code
} catch (ExceptionType1 ex1) {
// A Catch block
} catch (ExceptionType2 ex2) {
// A Catch block
} catch (ExceptionType3 ex3) {
// A Catch block
}finally {
// The finally block to always execute.
}
Note that java does not allow you to use a catch clause without the try
clause. You don’t have to add the finally clause to your try/catch block.
And, you cannot use the try clause without either the catch clause or the
finally clause.
Try-with-resources
After using resources like connections, streams, and others, we have to
close them explicitly by using the finally clause. Let us show how you can
open a file using the FileReader class and close the file by using the finally
clause:
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
Let us show how to use this statement to read data from a file:
import java.io.FileReader;
import java.io.IOException;
User-defined Exceptions
Java allows you to create your own exceptions. However, any exception
that you create should be a child of Throwable. Anytime you need to create
a checked exception to be automatically enforced by the Handle or set the
rule, you should extend the Exception class.
To create our own user-defined exceptions, we use the following syntax:
The above syntax shows that you are only required to extend the Exception
class which is predefined so as to create your own exception. These are
referred to as checked exceptions. Let us show how to create one in Java:
import java.io.*;
Now that we have defined the above exception, let us demonstrate how we
can use it by writing an example:
import java.io.*;
Let us show how we can invoke the save() and withdraw() methods of the
AccountCheck class:
try {
System.out.println("\nWithdrawing $200...");
c.withdraw(200.00);
System.out.println("\nWithdrawing $1100...");
c.withdraw(1100.00);
} catch (InadequateFundsException ex) {
System.out.println("Sorry, your account is short $" + ex.getDeposit());
ex.printStackTrace();
}
}
}
Compile all the classes and run them. The exception should be raised at last
as you will have withdrawn more from the account than what you have.
1 8 - J a v a AW T
AWT stands for Abstract Window kit is an API that we use to develop
window-based or GUI applications in Java. The components of Java AWT
are platform-independent, meaning that these components are displayed
based on the operating system. This API is heavyweight, meaning that its
components use the resources of the operating system.
The java.awt package comes with many classes for the AWT api like
TextField, Label, RadioButton, CheckBox, TextArea, Choice, List. Let us
discuss some of its important components:
• Container- this is an AWT component capable of holding other
components like textfields, labels, buttons, textareas, etc. it is extended by
classes such as Frame, Panel, and Dialog.
• Window- this is a container with no menu bars and borders. To create
a window, use a dialog, a frame or another window.
• Panel- this is a container with no menu bars and title bar. You can
add other components like textfields and buttons to it.
• Frame- this is a container with a title bar and it may have menu bars.
You can add other components like textfields and buttons to it.
This class comes with differents methods, with the most important ones
including the following:
• public void add(Component c)- this method adds a component to the
component.
• public void setSize(int width, int height)- this method sets the
measurements of the component, both the width and the height.
• public void setLayout(LayoutManager m)- this method defines the
layout manager of the component.
• public void setVisible(boolean status)- this is the method we use to
change the visibility of a component. It has a default setting of false.
We need to create an awt example. We need a frame for this. There are two
ways through which we can create this:
• By extending the Frame class (inheritance).
• By creating an object of the Frame class (association).
Let us create our first example by inheriting the Frame class. We will add a
button to the frame:
import java.awt.*;
public class MyGui extends Frame {
MyGui() {
Button btn=new Button("click Here");
btn.setBounds(30,100,80,30);// set the button position
add(btn);//add the button to the frame
setSize(300,300);// set frame size, 300 width, 300 height
setLayout(null);//no layout manager
setVisible(true);//make the frame visible, by default it is not visible
}
public static void main(String args[]) {
MyGui mg=new MyGui();
}
}
import java.awt.*;
public class MyGui2 {
MyGui2() {
Frame fr=new Frame();
Button btn=new Button("click Here");
btn.setBounds(30,50,80,30);
fr.add(btn);
fr.setSize(300,300);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[]) {
MyGui2 mg=new MyGui2();
}
}
The code should return the following graphical user interface:
Handling Events
Now we have registered the component with the listener, we can add the
event handling code. Consider the example given below:
import java.awt.*;
import java.awt.event.*;
class MyEvent extends Frame implements ActionListener{
TextField txtf;
MyEvent(){
//add the components then set their size, layout and visibility
add(btn);
add(txtf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent event){
txtf.setText("This is a message");
}
public static void main(String args[]){
new MyEvent();
}
}
Once you execute the code, you will get the following interface:
The interface consists of a textfield and a button. Click the button and see
what will happen. You will get the following:
When you click the button, some text is added to the textfield. The reason is
that we added the code to add that text to the textfield on a click of the
button. Let us see how we can handle events by an outer class:
Here is our first class, MyEvent2.java:
import java.awt.*;
import java.awt.event.*;
class MyEvent2 extends Frame{
TextField txtf;
MyEvent2(){
//create the components
txtf=new TextField();
txtf.setBounds(60,50,170,20);
Button btn=new Button("click Here");
btn.setBounds(100,120,80,30);
//register with listener
OuterClass oc=new OuterClass(this);
btn.addActionListener(oc);//passing an instance of outer class
//add the components then set the size, layout and visibility
add(btn);
add(txtf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new MyEvent2();
}
}
import java.awt.event.*;
public class OuterClass implements ActionListener{
MyEvent2 mev;
OuterClass(MyEvent2 mev){
this.mev=mev;
}
public void actionPerformed(ActionEvent ev){
mev.txtf.setText("This is a message");
}
public static void main(String args[]){
new MyEvent2();
}
}
Compile the first class, then compile and execute the second class. It will
run as our previous example.
We can also handle events by using an anonymous class. Let us show this
using an example:
import java.awt.*;
import java.awt.event.*;
class MyEvent3 extends Frame{
TextField txtf;
MyEvent3(){
txtf=new TextField();
txtf.setBounds(60,50,170,20);
Button btn=new Button("click Here");
btn.setBounds(50,120,80,30);
btn.addActionListener(new ActionListener(){
public void actionPerformed(){
txtf.setText("This is a message");
}
});
add(btn);
add(txtf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new MyEvent3();
}
}
AWT Button
We use the Button class to create a button with a label and this can be
implemented on any platform. Action can also be added so that the button
does something when clicked. The following shows how to use this class to
create a button:
import java.awt.*;
public class MyButton {
public static void main(String[] args) {
Frame fr=new Frame("My Button");
Button btn=new Button("Click Here");
btn.setBounds(50,100,80,30);
fr.add(btn);
fr.setSize(400,400);
fr.setLayout(null);
fr.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
public class MyButton {
public static void main(String[] args) {
Frame fr=new Frame("My Button");
final TextField txtf=new TextField();
txtf.setBounds(50,50, 150,20);
Button btn=new Button("Click Here");
btn.setBounds(50,100,60,30);
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
txtf.setText("This is a message");
}
});
fr.add(btn);
fr.add(txtf);
fr.setSize(400,400);
fr.setLayout(null);
fr.setVisible(true);
}
}
Run the code and click the button. The text will be shown in the text field.
AWT Label
The label object provides us with a way of adding text to the container. We
use it to display one line of text which is read-only. An application can edit
this text but the user may not change it directly. The following example
shows how to create a label in Java:
import java.awt.*;
class MyLabel {
public static void main(String args[]){
Frame fr= new Frame("My Label");
Label lab1,lab2;
lab1=new Label("Label 1");
lab1.setBounds(50,100, 100,30);
lab2=new Label("Label 2");
lab2.setBounds(50,150, 100,30);
fr.add(lab1);
fr.add(lab2);
fr.setSize(400,400);
fr.setLayout(null);
fr.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
public class MyLabel2 extends Frame implements ActionListener{
TextField txtf;
Label lab;
Button btn;
MyLabel2(){
txtf=new TextField();
txtf.setBounds(50,50, 150,20);
lab=new Label();
lab.setBounds(50,100, 250,20);
btn=new Button("Find IP");
btn.setBounds(50,150,60,30);
btn.addActionListener(this);
add(btn);
add(txtf);
add(lab);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent ev) {
try{
String host=txtf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
lab.setText("IP of host is "+ip);
}catch(Exception ex)
{
System.out.println(ex);
}
}
public static void main(String[] args) {
new MyLabel2();
}
}
Run the code then click the button. You should get both the name and the IP
address of the current host, which is the host from which you are running
the code:
AWT TextField
This is a component that allows a single line of text with the text being
editable. It is inherited from the TextComponent class.
It can be created as shown below:
import java.awt.*;
class MyTextField {
public static void main(String args[]){
Frame fr= new Frame("My TextField");
TextField txtf1, txtf2;
txtf1=new TextField("Welcome to Java Programming");
txtf1.setBounds(50,100, 200,30);
txtf2=new TextField("Java is a great coding Language");
txtf2.setBounds(50,150, 200,30);
fr.add(txtf1);
fr.add(txtf2);
fr.setSize(400,400);
fr.setLayout(null);
fr.setVisible(true);
}
}
We have created two text fields with some text on them. Try and you will
find that the text on the text fields can be edited. It is possible for us to add
an action listener to a textfield.
Let us demonstrate this using an example:
import java.awt.*;
import java.awt.event.*;
public class MyTextField2 extends Frame implements ActionListener{
TextField txtf1,txtf2,txtf3;
Button btn1,btn2;
MyTextField2(){
txtf1=new TextField();
txtf1.setBounds(50,50,150,20);
txtf2=new TextField();
txtf2.setBounds(50,100,150,20);
txtf3=new TextField();
txtf3.setBounds(50,150,150,20);
txtf3.setEditable(false);
btn1=new Button("*");
btn1.setBounds(50,200,50,50);
btn2=new Button("+");
btn2.setBounds(120,200,50,50);
btn1.addActionListener(this);
btn2.addActionListener(this);
add(txtf1);
add(txtf2);
add(txtf3);
add(btn1);
add(btn2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent ev) {
String s1=txtf1.getText();
String s2=txtf2.getText();
int x=Integer.parseInt(s1);
int y=Integer.parseInt(s2);
int z=0;
if(ev.getSource()==btn1){
z=x*y;
}else if(ev.getSource()==btn2){
z=x+y;
}
String result=String.valueOf(z);
txtf3.setText(result);
}
public static void main(String[] args) {
new MyTextField2();
}
}
AWT TextArea
This is a multi-line text field used for displaying text. With this, the user
may edit the text. It is inherited from the TextComponent class.
It can be created as showed below:
import java.awt.*;
public class MyTextArea
{
MyTextArea(){
Frame fr= new Frame();
TextArea ar=new TextArea("Welcome to Java programming");
ar.setBounds(10,30, 300,300);
fr.add(ar);
fr.setSize(400,400);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
new MyTextArea();
}
}
The code will return the result given below after execution:
Run the code and enter some text in the text area. After that, click the
Count Words button and see what happens. You will get:
We have successfully added an action listener to the button.
AWT Checkbox
import java.awt.*;
public class MyCheckbox
{
MyCheckbox(){
Frame fr= new Frame("My Checkbox");
Checkbox cb1 = new Checkbox("Yes");
cb1.setBounds(100,100, 50,50);
Checkbox cb2 = new Checkbox("No", true);
cb2.setBounds(100,150, 50,50);
fr.add(cb1);
fr.add(cb2);
fr.setSize(450,450);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
new MyCheckbox();
}
}
{
MyCheckbox2(){
Frame fr= new Frame("My CheckBox");
final Label lab = new Label();
lab.setAlignment(Label.CENTER);
lab.setSize(400,100);
Checkbox cb1 = new Checkbox("yes");
cb1.setBounds(100,100, 50,50);
Checkbox cb2 = new Checkbox("No");
cb2.setBounds(100,150, 50,50);
fr.add(cb1);
fr.add(cb2);
fr.add(lab);
cb1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
lab.setText("Yes Checkbox: "
+ (ev.getStateChange()==1?"checked":"unchecked"));
}
});
cb2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
lab.setText("No Checkbox: "
+ (ev.getStateChange()==1?"checked":"unchecked"));
}
});
fr.setSize(400,400);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
new MyCheckbox2();
}
}
Run the code and you will get an interface with Yes and No checkboxes.
Try to check and uncheck the different textboxes and see the text you will
get on the label:
AWT CheckboxGroup
import java.awt.*;
public class MyCheckboxGroup
{
MyCheckboxGroup (){
Frame fr= new Frame("My CheckboxGroup");
CheckboxGroup cg = new CheckboxGroup();
Checkbox cb1 = new Checkbox("yes", cg, false);
cb1.setBounds(100,100, 50,50);
Checkbox cb2 = new Checkbox("No", cg, true);
cb2.setBounds(100,150, 50,50);
fr.add(cb1);
fr.add(cb2);
fr.setSize(400,400);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
new MyCheckboxGroup();
}
}
You will realize that only one checkbox can be checked per time. We can
also add an ItemListener to the CheckboxGroup. The following example
shows this:
import java.awt.*;
import java.awt.event.*;
public class MyCheckbox2
import java.awt.*;
import java.awt.event.*;
public class MyCheckboxGroup2
{
MyCheckboxGroup2() {
Frame fr= new Frame("My CheckboxGroup");
final Label lab = new Label();
lab.setAlignment(Label.CENTER);
lab.setSize(400,100);
CheckboxGroup cg = new CheckboxGroup();
Checkbox cb1 = new Checkbox("yes", cg, false);
cb1.setBounds(100,100, 50,50);
Checkbox cb2 = new Checkbox("No", cg, false);
cb2.setBounds(100,150, 50,50);
fr.add(cb1);
fr.add(cb2);
fr.add(lab);
fr.setSize(400,400);
fr.setLayout(null);
fr.setVisible(true);
cb1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
lab.setText("Yes checkbox: Checked");
}
});
cb2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
lab.setText("No checkbox: Checked");
}
});
}
public static void main(String args[])
{
new MyCheckboxGroup2();
}
}
Run the code and click any of the checkboxes. You will see some text on
the label.
The text will change when you click another checkbox:
These are used for adding menus and menu items to the menu. This can be
explained best by creating an example:
import java.awt.*;
class MyMenu
{
MyMenu(){
Frame fr= new Frame("My Menu and MenuItem");
MenuBar mnb=new MenuBar();
Menu mn=new Menu("File");
Menu smn=new Menu("Save");
MenuItem i1=new MenuItem("New");
MenuItem i2=new MenuItem("Copy");
MenuItem i3=new MenuItem("Cut");
MenuItem i4=new MenuItem("Save");
MenuItem i5=new MenuItem("Save As");
mn.add(i1);
mn.add(i2);
mn.add(i3);
smn.add(i4);
smn.add(i5);
mn.add(smn);
mnb.add(mn);
fr.setMenuBar(mnb);
fr.setSize(400,400);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
new MyMenu();
}
}
Run the code and you will get a window. Click the File menu at the top left
corner of the window. You will see several menu items under it. Click the
Save option and see the submenus added to it:
KeyListener Interface
The KeyListener will be notified after you have changed the state of the
key. The notification is done against the KeyEvent. You can find the
KeyListener listener in java.awt.event package.
The KeyListener interface has three important methods which include:
• public abstract void keyPressed(KeyEvent ev);
• public abstract void keyReleased(KeyEvent ev);
• public abstract void keyTyped(KeyEvent ev);
import java.awt.*;
import java.awt.event.*;
public class MyKeyListener extends Frame implements KeyListener{
Label lab;
TextArea area;
MyKeyListener(){
lab=new Label();
lab.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(lab);
add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent ev) {
lab.setText("Key Pressed!");
}
public void keyReleased(KeyEvent ev) {
lab.setText("Key Released!");
}
public void keyTyped(KeyEvent ev) {
lab.setText("Key Typed!");
}
Execute the code and try to type something with the textarea provided for
you. You will see the text on the label change based on your action on the
keyboard.
Conclusion
This marks the end of this book. Java is a coding language. It is popular for
being one of the wide programming languages. A lot can be achieved with
Java. It is good for the development of desktop applications, commonly
referred to as standalone applications. It has applets, which can be
added/embedded on web pages. It is easy to learn Java, especially with a
background in object-oriented programming. Java supports features of
object-oriented programming. Examples include polymorphism, classes,
inheritance, encapsulation, etc. To code in Java, you need the Java compiler.
This tells you Java is compiled, not interpreted. The compiler is installed
automatically after installing JDK (Java Development Kit).
The JDK is open-source software, so get it for free and install it on your
computer. A text editor is needed, which is where you will write your Java
code. Examples include NetBeans, Notepad, Eclipse, etc. With those, you
can write your Java codes and run them from the console/terminal of your
OS. You invoke the java compiler (javac) to compile the code and generate
a .class file, then execute the .class file. The .class file has byte-code, which
is platform-independent, it can be run on any platform, example, Unix,
Windows, Mac OS, Solaris, etc.
ABOUT THE AUTHOR
Daniel Bell was born in the Bronx, New York. When he was nine, he
moved with his father Guy Bell to Nice in France. He received his Ph.D.
degree in computer science from the University of Nice (France) in 2012.
Daniel is conducting research in data management, with an emphasis on
topics related to Big Data and data sharing, such as probabilistic data, data
pricing, parallel data processing, data security. He spends his free time
writing books on computer programming and data science, to help the
absolute beginners in computer programming to code easily. He lives in
Chatillon, near Paris.
Acknowledgments