0% found this document useful (0 votes)
2 views268 pages

Introduction to Java Programming 2020

This document provides an introduction to Java programming, covering its features, strengths, and common programming practices. It includes details on Java installation, program structure, data types, operators, and control flow statements, along with examples and lab activities. The document also discusses common programming errors and emphasizes good programming practices for better code readability and maintenance.

Uploaded by

Richmond Yuoni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views268 pages

Introduction to Java Programming 2020

This document provides an introduction to Java programming, covering its features, strengths, and common programming practices. It includes details on Java installation, program structure, data types, operators, and control flow statements, along with examples and lab activities. The document also discusses common programming errors and emphasizes good programming practices for better code readability and maintenance.

Uploaded by

Richmond Yuoni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 268

INTRODUCTION TO JAVA

PROGRAMMING

SESSION 1
SESSION OUTLINE
• What Java is: Features & Strengths
• Common Programming Errors
• Good Programming Practice
• Java comments
• Java Installation & Configuration
– Using Windows Environment
– Using NetBeans IDE
• Java Program Structure with examples
• Lab Work
Historical Account
• Sun Microsystems in 1991 funded an internal
corporate research project code-named
Green, which resulted in a C++-based
language
• Its creator, James Gosling, called Oak after an
oak tree outside his window at Sun.
• The name was later changed to Java
Features/Strengths
• Java is a high-level programming language
– It implements most of the concepts of objects-
oriented systems e. g. software reuse.
– It is platform-independent
– It is more portable. It will run on any PC that
implements the Java virtual machine.
• Java has “class libraries
• Java can be implemented by Integrated
Development Environments.
Java & C++
• It has built-in graphical interface support
• Its syntax (structure) is similar to C++, but
simpler than C++ in most areas
• Java Software Development Kit (SDK) is open
source. Java SDK is software for compiling and
running Java programs.
• Java has many of the features of C++.
• It is slower than its ‘rival’ C++ because of extra
level of processing.
• It uses no pointers
Java Platforms
• There are three main platforms.
• Java Standard Edition: used for developing
desktop applications;
• Java Enterprise Edition: used to produce
software for businesses and enterprises
• Java Micro Edition: used for smart devices such
as mobile phones, smartphones, personal digital
assistants (PDAs).
Types of Java Programs
• Java Applications
– Must have the resource files stored locally
– Run directly on a device
– Contain a "main()" method and compiled using the
"javac",
• Java Applets
– Run by a browser and no "main()" method
– They are contained within a website document: HTML
– They are stored on the server of a website
– They are unable to run standalone.
• Midlets Run on mobile phones and managed by device
software.
• Servlets are designed to run inside web servers
Common Programming Error
• Forgetting one of the delimiters. A syntax error
occurs when the compiler encounters code that
violates Java’s language rules
• Java is case sensitive. Not using the proper
uppercase and lowercase letters for an identifier

• A public class must be placed in a file that has the


same name as the class (in terms of both spelling
and capitalization) plus the .java extension;
Common Programming Error
• Omitting the semicolon at the end of a
statement is a syntax error.
Good Programming Practice
• Every program should begin with a comment
that explains the purpose of the program
• Use blank lines and space characters to
enhance program readability.
• By convention, always begin a class name’s
identifier with a capital letter and start each
subsequent word in the identifier with a
capital letter.
Good Programming Practice
• Whenever you type an opening left brace, {, in
your program, immediately type the closing
right brace, },
• Indent the entire body of each class
declaration one “level” of indentation
between the left brace.
• Following the closing right brace (}) of a
method body or class declaration with an end-
of-line comment
Use Comments
• A comment is a piece of information usually
text that provides explanations for people
who will read the program.
• Comments as tools in programming are part
of a program documentation

Types
• Java has three types of comments. Namely:

– //: This is the most commonly used comments


– /*. . . . .*/ This is a type of comment that starts with
‘/*’ and ends with */
– Special comments /** and ends with ‘*/’.It can spread
over more than one line.(Thus two or more lines).
– The third type of comment is used by a tool called
javadoc for automatic generation of documentation.
Java Installation
• Download and install (Consider 32-bit & 64-
bit)
• Configure JDK on Windows platform
• Set Environment variable
– Take note of the directory
– Add Path as new variable name
– Add directory as variable value
Creating a Program
• Create source file using text editor
• Save the file to the directory
• Compile the source file into class file using
javac
• If error occurs Do Editing
• Run the program using java
Programming is about Diligence
SESSION OUTLINE
• Working with JAVA & NetBeans IDE
– Downloading
– Installation
• Java Syntax
• Program Structure
• Java Program Structure with examples
• Program Control Structures
• Lab Work
Java IDE Installation
• NetBeans IDE can also be used for your
programming activities.
• A Java and NetBeansIDE is open-source and
free which can be downloaded from
https://www.netbeans.org/index.html.
• Java and Eclipse IDE: Eclipse is also a Java IDE
developed by the eclipse open-source
community and can be downloaded from
https://www.eclipse.org/
Program Structure
Program Creation
• The steps you will follow to write and run your
programs are:
1. Write the source code in Java
2. Compile the source code
3. Correct Errors if any
4. Run the program
Program String statement
• // This program displays Hello World
class HelloBigJava
{
public static void main (String [] args)
{
System.out.println("HelloWorld!");
}
}
Program String statement
• A compiler converts the Java program into an
intermediate language representation called
Bytecode which is platform independent.
JAVA SYNTAX
• A normal text editor can be used to write Java
programs.
• Java code is case sensitive
• Data Types: type of data the variables can
have in that particular language.
• Data type is the manner in which a sequence
of bits represents data in a computer.
Data Types available in java are:
• Primary Data Type: The eight data types of
Java are byte, short, int, long, float, double,
char and Boolean
• Non-Primitive Data Types string, array
• The Java programming language is statically-
typed, which means that all variables must
first be declared before they can be used.
• short: It has a minimum value of -32,768 and a
maximum value of 32,767 (inclusive).
• int: It has a minimum value of -2,147,483,648
and a maximum value of 2,147,483,647
(inclusive). used For integer values
• long: It has a minimum value of -
9,223,372,036,854,775,808 and a maximum
value of 9,223,372,036,854,775,807
• float: Use for decimal values
• double: Its range of values is extremely large.
Used for decimal values.
Java Variables
• Variables are the identifier of the memory
location, used to save data temporary for later
use.
• Rules of declaring variables in Java
• Variable name can consist of Capital letters A-Z,
lowercase letters a-z, digits 0-9, and two special
characters such as underscore and dollar Sign.
• The first character must be a letter.
• Blank spaces cannot be used in variable names.
• Java keywords cannot be used as variable names.
• Variable names are case sensitive.
Variable Definition in Java
Syntax:
type variable name;
type variable name, variable name, variable name;
• Example:
/* variable definition and initialization */
int width, height=5;
char letter='C';
float age, area;
double d;
Initialization
• /* actual initialization */
width = 10;
age = 26.5;
Illustrating Declaration and
Initialisation

public static void main(String[] args) {


int a, b, sum;
a = 10;
b=6;
sum = a + b;
System.out.println ("The Sum of the two
numbers is: " + sum);
Example
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello Student");
}
}
public class Hello
• This creates a class called Hello.
• All class names required to start with a capital
letter.
• The word public means that it is accessible by
any other classes.
{…}: The 2 curly brackets are used to group all the
commands together so it is known that the
commands belong to that class.
• public static void main (String [] args)
– The word public means that it is accessible by any
other classes.
– The word static means that it is unique.
– The word void means this main method has no return
value.
• main is a method where the program starts.
• main: The main starting point for execution in
every Java program.
• String: A bunch of text; a row of characters,
one after another.
System.out.println();
• System is a final class name and cannot be
instantiated. Therefore all its memebers (fields and
methods) will be static, it is a utility class.
• System class provides standard input, standard output,
and error output streams.
• out: The place where a text-based program displays its
text.
• out is static member in System class which is instance
of java.io.PrintStream

• println: Display text on your computer screen.


System.out.println();
• println method displays text on the screen
with newline.
• There are multiple println methods with
different arguments (overloading). Every
println makes a call to print method and adds
a newline.
• print calls write()
System.out.println();
System class
NewDay

Programming is about Diligence


Session Outline
• Operations on data
• Program Control flow statements
– If ….else
– Switch case
• Looping using for statement
– For
– While, do………..while
• Lab Activities
Operations on data
• Arithmetic operators
• Increment and decrement operators
• Comparison operators
• Logical operators
• Assignment operators
• Operator precedence
Arithmetic operators
Comparison operators
Operators and Expressions
Expression

• Can be translated into Java expression as:


(3 + 4 * x) / 5 – 10 * (y - 5) * (a + b + c) / x + 9 *
(4 / x + (9 + x) / y)
Operators and Expressions
• As in regular algebraic notation, multiplication
and division have a higher precedence than
addition and subtraction.
• Write programs to print to a standard output
the results of following mathematical
expressions:
• 2x + 5y – 7
• (X2y2- 9x2)/( x2y – 3x2) [Where the values of x and
y are 2 and 3 respectively]
Problem Analysis

1. 2x + 5y – 7

2. (X2y2- 9x2)/( x2y – 3x2)

3. (z2y2- 9x2)/( z2y5 – 3x2)

[Where the values of x , y and z are 2, 3 and 4.5


respectively]
Solution

class ExpCal1{
public static void main(String[] args)
{
int x= 2, int y= 3 , int results;
results= 2*x + 5*y -7;
System.out.println("The output of the program
is:"+ results);
}
}
Problem Analysis

class OperatorPrecedence {
Lab Activity 1
1. Write a program to find difference between
two numbers
2. Write a program to find the product of two
numbers
Identify Errors and Fix Them

public class Addition


{
public static void main(String [] args)
{
int num1, num2, sum;

sum = num1 + num2

System.out.println("The sum of the two numbers is :" + sum){


}

}
import java.util.Scanner;
public class Addition
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int num1, num2, sum;

System.out.print("Enter first integer ");//prompt user for a number

num1 = input.nextInt();

System.out.print("Enter second integer ");

num2 = input.nextInt();

sum = num1 + num2;

System.out.println("The sum of the two numbers is :" + sum);


}

}
APPLICATIONS
1. Write a program to find the smallest of two
numbers.

2. Write a program to check whether two


numbers are equal or not.
Lab Activity
QUESTION
A vat rate of seventeen and half percent (17.5%)
is charged on any transaction at PomaaKrom
Rural Bank. Write a program to calculate the
vat that will be paid on GH¢6000.00.
Solution
class VatRate
{
public static void main(String[] args)
{
double Vrate, amount, Trate;
Vrate = 0.17;
amount = 50000.00;
Trate = rate * amount;

System.out.println("The total Vat Rate for GHC 50000 is:" + Trate);

}
};
Logical Operators
Logical Operators
• Logical operators are symbols that are used to
combine expressions containing relational
operators.
• This circumstance will arise when you want to
perform a statement block on a combined
condition,
• like x > 7 and y < 14.
• Then you code this using an AND operator.
The AND operator is represented as &&.
Logical Operators
Logical Operators
• Example:
((x > 7) && (x < 14))
(salary >=4000 && salary <=5000)
Decision Making statements
• if -else statement
• Java else if is a like doing another if condition for a true or false value.
Syntax:
if(condition)
{
//execute your code
}
else if(condition n)
{
//execute your code
}
else
{
//execute your code
}
Application
public class Compare {

public static void main(String args[]) {


int a = 30, b = 30;

if (b > a) {
System.out.println("b is greater");
}
else if(a > b){
System.out.println("a is greater");
}
else {
System.out.println("Both are equal");
}
}
}
Java switch Statements
• Java switch statement is used when you have multiple possibilities for the if
statement.
• Syntax:
switch(variable)
{
case 1:
//execute your code
break;

case n:
//execute your code
break;

default:
//execute your code
break;
}
Example:
public class Sample {

public static void main(String args[]) {


int a = 5;

switch (a) {
case 1:
System.out.println("You chose One");
break;

case 2:
System.out.println("You chose Two");
break;

case 3:
System.out.println("You chose Three");
break;
Switch statement
case 4:
System.out.println("You chose Four");
break;

case 5:
System.out.println("You chose Five");
break;

default:
System.out.println("Invalid Choice. Enter a no between 1 and 5");
break;
}
}
}
END
Looping statements
• For loop
• While loop
• Do-while loop
Looping using ‘for’ statement
for (initial statement; termination condition;
increment instruction)
statement ;
• For multiple statements the statements are put
inside brackets.
for (initial statement; termination condition;
increment instruction)
{
statement 1;
statement 2;
}
Lab Application
// This program uses for loop to print numbers 1 through 10
to standard output
class PrintNum
{
public static void main(String[] args)
{
int i;
for(i=1; i<11; i++)
{
System.out.println(“The numbers are: " + i);
}
}
}
Error identification and Correction

int j, sum;
sum = 0;
for (j=1;j<=10;j++) ;
sum += j ;
Java while loop

• Java while loops statement allows to repeatedly run


the same block of code, until a condition is met.
Syntax:
While (condition)
{
statement(s);
Incrementation;
}
Application
public class Sample {
public static void main(String args[]) {
/* local variable Initialization */
int n = 1, times = 5;
/* while loops execution */
while (n <= times) {
System.out.println("Java while loops:" + n);
n++;
}
}
}
Java do…..while loop
• Java do…while loop is very similar to the java
while loop, but it always executes the code block
at least once and further more as long as the
condition remains true.
• Syntax:
do
{
statement(s);
}
while( condition );
Example
public class Sample {

public static void main(String args[]) {


int n = 1, times = 0;

/* do-while loops execution */


do {
System.out.println("Java do while loops:" + n);
n++;
} while (n <= times);
}
}
Lab Activity
• Using the if…….else statement, write a program to accept the age of the
user and to display on the screen a message indicating the age status of
the user. The program should display result using the examples below:

Enter your age:


When the age is not up to 100 years it should display the
message:
You are pretty young!
When the age is 100 years it should display the message:
You are old
When the person is older than 100 years it should display
the message:
You are really old.
Lab Activity

QUESTION
A student must pass both Mid-Sem and
examination to pass a course. The pass marks
for each is 50%. Write a program to input the
two marks and determine whether or not the
student passed.
Lab Activities
1. Write a program to print all the prime
numbers between 20 and 40.
2. Write a program to determine the maximum
value of two numbers
NewDay
SESSION OUTLINE
• Arrays
• Types of array
– One dimensional array
– Multidimensional array
• Declaring Array
• Applications
• Lab Activity
Array
• A data structure that can store a fixed size of
sequential collection of elements of same data
type
• Syntax:
– datatype[] identifier;
or
– datatype identifier[];
Example:
int[] refVar;
Illustration of array in Memory
Array Declaration
• To use array, the following are required:
• Declare a variable to be used as the array name
E.g. string [] mySelf;
char[] grade;
short[] refVar;
first part: string [].
• A bit different from creating a regular variable,
notice square brackets.
• That means that we want to create an string
array, and not a single variable.
Lab Activity
• Declare two integer arrays
• Declare two double arrays
• Declare three char arrays
• Declare one long arrays
• Arrays can be initialized at declaration time:
• int age[5]={22,25,30,32,35};
Initialize an Array in Java
• Using the initializer list. Thus, declare,
construct and initialise the array all in one
statement.
int age[5]={22,25,30,32,35};

• Using new operator to declare and construct


in one statement
Initialize an Array in Java
• By using new operator array can be initialized.

• int[] age = new int[5]; //5 is the size of array.


• After that initialise the values
class ArrayEg1{
public static void main ( String[] args ) {
int age[ ]={22,25,30,32,35};
System.out.println("stuff[0] has " + stuff[0] );
System.out.println("stuff[1] has " + stuff[1] );
System.out.println("stuff[2] has " + stuff[2] );
System.out.println("stuff[3] has " + stuff[3] );
System.out.println("stuff[4] has " + stuff[4] );
}
}
class ArrayEg1{
public static void main ( String[] args ) {
int[] stuff = new int[5];
stuff[0] = 23;
stuff[1] = 38;
stuff[2] = 7*2;
stuff[3] = 100;
System.out.println("stuff[0] has " + stuff[0] );
System.out.println("stuff[1] has " + stuff[1] );
System.out.println("stuff[2] has " + stuff[2] );
System.out.println("stuff[3] has " + stuff[3] );
System.out.println("stuff[4] has " + stuff[4] );
}
}
class ArrayEg1{
public static void main ( String[] args ) {
int[] stuff = new int[5];

stuff[0] = 23;
stuff[1] = 38;
stuff[2] = 7*2;

System.out.println("stuff[0] has " + stuff[0] );


System.out.println("stuff[1] has " + stuff[1] );
System.out.println("stuff[2] has " + stuff[2] );
System.out.println("stuff[3] has " + stuff[3] );
System.out.println("stuff[4] has " + stuff[4] );
}
}
Initializing each element separately in
loop
public class Sample {

public static void main(String args[]) {


int[] newArray = new int[5];

// Initializing elements of array separately


for (int n = 0; n < newArray.length; n++) {
newArray[n] = n; // Accessing the elements
}
}
}
Write the output of this program
public class Samples {
public static void main(String[] args) {
int[] newArray = new int[5];
for (int n = 0; n < newArray.length; n++) {
newArray[n] = n;
}
System.out.println(newArray[4]);
}}
Accessing Array Elements in Java
public class Sample {

public static void main(String args[]) {


int[] newArray = new int[5];

// Initializing elements of array seperately


for (int n = 0; n < newArray.length; n++) {
newArray[n] = n;
}
System.out.println(newArray[2]/2); // Assigning 2nd
element of array value
}}
Application
Public class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println(“Count is: " + item);
}
}
}
Two-Dimensional Arrays
• Data come in a two dimensional form.
• Example: Spreadsheet.
• A collection of cells laid out in a 2D grid, like
graph paper.
• Each cell can hold a value (as with a 1D array).
However, now two indexes are needed to specify
a cell. Headings are not part of the array
Two Dimensional Array
Headings are not part of the array
How it is represented in Memory
Two- Dimensional Implementation
public class ArrayEg1 {

public static void main(String[] args) {


int[][] twoDArray;
twoDArray = new int[4][4];
// initialize elements
twoDArray[0][0] = 100;
twoDArray[1][0] = 200;
twoDArray[2][0] = 300;
twoDArray[3][0] = 400;
// display values
System.out.println("Element at index 0: "+ twoDArray[0][0]);
System.out.println("Element at index 1: "+ twoDArray[1][0]);
System.out.println("Element at index 2: "+ twoDArray[1][0]);
}

}
GradeTable
• The grade for student 0 week 1 is 42
• The grade for student 3 week 4 is 93
• The grade for student 6 week 2 is 78
• A compact notation for specifying a cell uses the
row and column indexes like this:
gradeTable[ row ][ col ]
• As with one dimensional arrays, indices start at
zero. For example:
gradeTable[ 0 ][ 1 ] is 42
Lab Activity
Write the values that will be output by the
following:
• gradeTable[ 3 ][ 4 ]
• gradeTable[ 6 ][ 2 ]
• gradeTable[ 5 ][ 2 ]
• gradeTable[ 2 ][ 3 ]
• int value = (gradeTable[ 6 ][ 2 ] + 2) / 2 ;
• gradeTable[ 3 ][ 4 ]++ ;
Lab Assignment
Declare and initialize an array for this table
Lab Assignment 2
• Write a program to display the following
values from the table:
• 100
• 43
• 73
Using Initializer list

double[][] sales = {
{8.2, 2.5, 5.4},
{81.2, 92.5, 45.4},
{20.2, 22.5, 85.4},
};
2D String Implementation
class ArrayString {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. ", "Miss "},
{"Afriyie", "Patricia", "Agnes"}
};
System.out.println(names[0][0] + names[1][0]);
System.out.println(names[0][2] + names[1][1]);
System.out.println(names[0][3] + names[1][2]);
}
}
Arrays Implementation Using LOOPS
• for loop
Lab Exercise
Write a program to print out the unit of Toothpaste
sold on Thursday, Monday and Friday.
2D Array
class SalesTable{
public static void main(String[] args) {
int[][]examTable={
{60,76,62,52,67},
{64,53,84,55,48},
{90,46,76,100,73}
};
//int examTable,sum;
int sum=examTable[2][1] + examTable[2][2] +
examTable[2][3]+examTable[2][4];
System.out.println("The total score for Zuleha is:" + sum);
System.out.println("ICT for Alima is:" + examTable[0][1]);
System.out.println("Social Studies for Alima is:" +
examTable[0][3]);
}}
2D Array
int [][]SalesTable = {
{40, 10, 120, 70, 67},
{46, 53, 84, 18, 48},
{90, 46, 76, 100, 73},
{78, 79, 48, 50, 45},
{81, 59, 84, 92, 66} };
for(int i = 0; i <=4; i++){
for(int j = 0; j <=4; j++){
if (i==4)
if (j!=1)
System.out.println("sales = " + SalesTable[i][j]);
}
}
NEXT LESSON
Quiz on Reading Assignment
Attempt all questions
Duration: 5 Minutes
1. Name two java classes that can be used in an
interactive program
2. What is the function of the next() method
3. What method is used to convert the text
enters by a user to the appropriate primitive
type?
[ 5 Marks]
SESSION OUTLINE

• Interactive programs using:


• Scanner class
• Objects
• Scanner objects
– Scanner methods
• JOptionPane class
Scanner class
• Java has a class called Scanner
• Used to get input from the user.
• Importing the Scanner class
• import java.util.Scanner;
• Note that it is only the Scanner which is started with a
capital letter.
• If we are using other classes in the java.util package.
• Import the entire package by writing the import
statement like this:
• import java.util.*;
Declaring and creating a Scanner
object
• Before we can use the Scanner class, declare a
Scanner variable and create an instance of the
Scanner class.
• Create the Scanner object in the class variable.
• Syntax:
Scanner <name> = new Scanner(System.in);
Example:
Scanner sc = new Scanner(System.in);
Scanner Methods
• Once we construct the Scanner,
• We call various methods on it to read the
input from the user.
Implementation of Scanner Class
import java.util.Scanner;
Scanner input=new Scanner (System.in);
double BMI, weight, height;
System.out.print("Please enter weight in pounds");
weight=input.nextDouble();
weight=1 * 0.45359237;
System.out.print("Please enter height in inches");
height=input.nextDouble();
height=1 * 0.0254;
BMI = weight/(height*height);
System.out.println("The Body Mass Index is: "+ BMI);
JOptionPane Class
• The JOptionPane class is used to display dialog
boxes.
• Use the parse methods of the primitive data
type wrapper classes to convert the text
entered by the user to the appropriate
primitive type.
• Import the JOptionPane class as:
– import javax.swing.JOptionPane;
JOptionPane Class
import javax.swing.JOptionPane;
String input1 = JOptionPane.showInputDialog("Enter your
first integer value and click OK");
// String to integer
int value1 = Integer.parseInt(input1);
String input2 = JOptionPane.showInputDialog("Enter your
second integer value and click OK");
int value2 = Integer.parseInt(input2);
int sum = value1 + value2;
String output = ("The sum of the two values is :" + (value1
+value2));
JOptionPane.showMessageDialog(null, output);
}
}
SESSION OUTLINE
• Object-Oriented programming [OOP]
Concepts
• classes
• Methods
– Overloading methods
– Method overriding
• Interfaces
• Inheritance
• Polymorphism
Objected Oriented Programming
• A type of programming in which a problem is
divided into a number of entities/units called
object.
• The data and methods are built around the
objects.
• Object is an instance of a class
• Examples of Objects: Table, computer, pen etc.
Class
• A collection of objects of similar type
• A class represents a group of objects of the
same kind.
• The smallest unit of java program
• For example, class of animals represent: cow,
dog, cat, tiger, cock, dove, etc.
• More examples ?
Structure of Classes
• A class--the basic building block of an object-
oriented language
• Classes generally contain the following parts
– Class definition
– Creating instance and class variables
– Method definitions: a set of action taken in
response to a request
Object
• An identifiable entity with some
characteristics and behaviour
• Objects are characterized by the following
features
• State: colour, shape, size
• Behaviour/function: play, sing, think
• Identity: ID
• A class is defined by the keyword class
followed by the name of the class.
• By default, classes inherit from the Object
class.
• Object class is the superclass of all classes in
the Java class hierarchy
Illustration of Classes
public class MyPoint {
public int x = 0;
public int y = 0;
void displayPoint( ) {
System.out.println("Printing the coordinates");
System.out.println(x + " " + y );
}
public static void main (String args[ ]) {
MyPoint point = new MyPoint( );
point.displayPoint( );
}
}
Variables

1. Instance variables
2. Class variables
3. Local variables
Instance Variables
• Variables declared outside the method definitions are
called instance variables.
• Generally they are defined immediately after the first line
of the class definition.
• An instance variable represents data for which each
instance has it's own copy
class MyPoint {
int x;
int y;
// method 1
// method 2
}
Class variable
• The static keyword is used to declare a class
variable.
class MyPoint {
int x;
int y;
static int quadrant=1;
// method 1
// method 2
}
Local Variables
• Variables defined within the methods are called local
variables. Their scope is limited to within the method in which
they are defined.
class MyPoint {
int x, y;
static int quadrant;
public void displayPoint( ) {
int temp;
int j;
}
}
The variables temp and j are local variables.
They are valid only within the method displayPoint( ).
Methods
• A set of actions taken by a receiving object in
response to a request/message
• Methods are defined as follows
– Return type
– Name of the method
– A list of parameters
– Body of the method.
• void displayPoint( ) {
// body of the method
}
Methods
• The method describes the mechanisms that
actually perform its tasks.
• The method hides from its user the complex
tasks that it performs.
• A method is a mechanism that knows how
objects of a certain type carry out a particular
task.
• It tells us about the behaviour of objects.
Methods
• In Java, we begin by creating a class to house a
method,
• just as a car’s engineering drawings house the
design of an accelerator pedal.
• In a class, you provide one or more methods that
are designed to perform the class’s tasks.
• For example, a class that represents a bank
account might contain
– one method to deposit money to an account
– another method to withdraw money from an account
– a third to inquire what the current balance is.
Method calling in a Program
public class Javamethods {
void corona(){
System.out.print("This is a deadly disease,");
System.out.println("observe all the safety
protocols.");
}
void exams(){
System.out.println("Exams are starting on Monday,
the 27th of July.");
System.out.println("The first paper is Java
Programming.");
int bankacct(){
int deposit=500,withdrawal=150, accbalance;
accbalance=deposit-withdrawal;
System.out.println(" Your Account Balance is " +
accbalance);
return accbalance;
}
public static void main(String[] args) {
Javamethods methods = new Javamethods();
methods.corona();
methods.exams();
methods.bankacct();
}
Defining a Class
import java.util.Date;
class Date{
public static void main(String args[]) {
Date today = new Date(); //instantiate object
System.out.println(today);
}
}
Detail
• The first line in the Date application listing above
begins a class definition block.
• A class--is a template that describes the data and
behaviour associated with instances of that class.
When you instantiate a class you create an object
that will look and feel like other instances of the
same class.
• The data associated with a class or object are
called variables; the behaviour associated with
class or object are called methods.
Methods implementation 2

public class Animal {


public void sleep(){ // method
System.out.println("Sleeping");
}
public void eat(){
System.out.println("Eating");
}
public static void main (String [] args){
Animal d = new Animal();
d.sleep(); // call method sleep
}
}
Methods
• A collection of activities that performs a task.
• A method is a behavior or a task.
– For example, an object that represents a car might
have methods such as start, stop, drive, or speed.
• A class can contain many methods. It is in
methods where the logics are written, data is
manipulated and all the actions are executed.
Method Implementation
public class Animal {
public void sleep(){ // method
System.out.println("Sleeping");
}
public void eat(){
System.out.println("Eating");
}
public static void main (String [] args){
Animal d = new Animal();
Animal k = new Animal();
d.sleep(); // call method sleep
k.eat();
}
}
Lab Activity
i. Write a method named bark and call the
method to print “woo…….wo”
ii. Create another method called compute and
call the method to print the sum of two
numbers.
Solution
public class Animal {
public void sleep(){ // method
System.out.println("Sleeping"); }
public void eat(){
System.out.println("Eating"); }
static int compute() {
int sum, a=6, b=26;
sum = a+b;
System.out.println("compute a and b =" + sum);
return a+b;}
public static void main (String [] args){
Animal d = new Animal();
Animal k = new Animal();
d.sleep(); // call method sleep
k.eat();
Animal maths = new Animal();
maths.compute();
}}
Method overloading
• You can have same name for more than one
method.
• The numbers of arguments or the types of
arguments are to be different for creating two
or more methods with the same name.
• The return types of the methods can be
different as long as the method signature is
different.
Method Overloading
class OverloadMethod {
static float add(int x, int y) {
return x+y;
}
static float add(float t1, float t2) {
return t1+t2;
}
static float add(String s1, String s2) {
float sum;
sum = Integer.parseInt(s1)+Integer.parseInt(s2);
return sum;
}
Method overloading

public static void main(String args[]) {


int x=10, y=20;
float m=5.5f, n=10.5f;
String s1="25", s2="35”;

System.out.println(add(x,y));
System.out.println(add(m,n));
System.out.println(add(s1,s2));
}
}
Concept of Inheritance of OOP
• The process where one class acquires the
properties (methods and fields) of another.
• The class which inherits the properties of
other is known as subclass (derived class)
• The class whose properties are inherited is
known as superclass (base class, parent class).
General Syntax
• extends Keyword
• extends is the keyword used to inherit the properties of a
class.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Concept of Inheritance
• Deriving a new class from the existing class
Public class Cat extends Animal {
Public void meow(){ //method
System.out.println(“The cat said meow”);
}
}
The cat class inherits is derived from the Animal
class. The Animal class is called superclass
The cat class is called subclass or derived class
Concept of Inheritance
class Calculation{
int z;
public void addition(int x, int y){
z = x+y;
System.out.println("The sum of the given numbers:"+z);
}
public void Substraction(int x, int y){
z = x-y;
System.out.println("The difference between the given
numbers:"+z);
}
}
Concept of Inheritance
class My_Calculation extends Calculation{
public void multiplication(int x, int y){
z = x*y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]){
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
demo.multiplication(a, b);
}}
Method Overriding
• Overriding means to supersede the
functionality of an existing method.
• If a class inherits a method from its superclass,
then there is a chance to override the method
provided that it is not marked final.
• Overriding helps to define a behavior that is
specific to the subclass type.
• Thus, a subclass can implement a parent class
method based on its requirement.
Rules about method overriding
• The argument list should be exactly the same as that of
the overridden method.
• The return type should be the same or a subtype of the
return type declared in the original overridden method
in the superclass.
• The access level cannot be more restrictive than the
overridden method's access level. For example: If the
superclass method is declared public then the
overridding method in the sub class cannot be either
private or protected.
• A method declared final cannot be overridden.
• A method declared static cannot be overridden .
Method overriding
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
} }
Method Overriding
class Lecturer{
Void showMessage(){
System.out.println(“I am in lecturer class”);
}
void display(){
System.out.println(“Inside lecturer’s display() ”)
}
Class Student extends Lecturer{
void display(){
System.out.println(“Inside student’s display()”);
{
Public static void main(String [] args){
Student object = new Student();
Object.display();
}
}
Lab Exercise
Write programs to illustrate how the following
are implemented in Java
1. Method
2. Inheritance
3. Method Overloading
4. Method Overriding
Inheritance
SESSION OUTLINE
• Java as Object Oriented Programming Language
• Multiple Inheritance
• Packages
• Access modifiers
• Applet and Graphics
– Applet program
• HTML
• Lab Applications
Multiple Inheritance
• Java does not support multiple inheritance
• we cannot inherit from more than one class at
the same time.
• Two classes:
class a
class b
Inheritance concept:
• Example: class a, b // not possible in Java
• But possible in Java rival?
class a, b
{
……………..
……………
} // not possible in Java. Illegal
Multiple Inheritance Cont’d
• Want to inherit the class child from mother and
father classes.
• That is subclass child from two super classes:
• Class mother, Class father
class Child extends Father, Mother
{
// body of class child
}
• Syntax error
• Use the concept of interface
Interface
• An interface is a collection of methods.
• Interfaces serve to implement multiple
inheritance
• Implementing classes implement the
methods.
Interface Declaration
• Syntax:
• Interface interface –name
• The interface is created using the keyword
interface
• Interface can be declared public
• An interface can extend any number of
interfaces
Programming implementing the concept of interface
class Salary{
void showSalary(){
System.out.println("Salary:10000");
}
// Interface defined
interface Commission {
void showComm(); // only method declared
}
class Income extends Salary implements Commission {
public void showComm(){
System.out.println("Commission:1000");
}}
void showIncome(){ // method defined
showSalary(); // method of salary class called
showComm(); // method of commission class called
}
Interface Implementation Cont’d
public static void main (String [] args)
{
Income obj = new Income(); // objected created
obj.showIncome(); // method called using object
System.out.println("Total income includes ");
}
}
interface Birth {
default void run(){
System.out.println("I am sitting, mum ");
System.out.println("I am running, kid !!");
}
}

interface Crawl {
default void run(){
System.out.println("I am crawling, daddy ");
}
}
class Parent implements Birth, Crawl {
public static void main(String[] args) {
Parent self = new Parent();
self.run();
}
Interface Implementation

public void run() {


Birth.super.run();
Crawl.super.run();
}
}
Polymorphism
• Polymorphism is the ability of an object to
take on many forms.
• This concept permits a single variable to make
reference to objects from different classes
with a common base.
• The most common use of polymorphism in
OOP occurs when a parent class reference is
used to refer to a child class object.
Packages
• A package is a collection of related classes and
interfaces that provides access protection and
name space management.
• You can think of package as different folders
on your computer.
• You may keep word documents in one folder
and images in another folder.
• Java language programs automatically import
all classes in the java.lang package.
Advantages of Packages
• The concept of packages help in organising
and grouping classes and interfaces according
to purpose and functionality.
• Packages give us the following advantages:
• Help to group similar classes, avoid conflict in
naming classes,
• Protect classes, methods and variables and
restrict the access amongst the classes.
Creating a Package
• To create a package, you choose a name for the
package and put a package statement with that
name at the top of every source file that contains
the types (classes, interfaces, enumerations, and
annotation types) that you want to include in the
package.
• There can be only one package statement in each
source file, and it applies to all types in the file.
E.g. package pack.subpack;
• To import classes from a package, import
command is used.
Packages in Java
• java.lang - contains language support classes
such as String, Math, Thread
• java.io - classes for input , output functions
are bundled in this package
• Java.net: Contains classes which are used for
networking. For communication between
interconnected computers.
PACKAGES
• java.applet: Provides the classes necessary to create an applet
and the classes an applet uses to communicate with its applet
context.
• java.awt: Contains all of the classes for creating user interfaces
and for painting graphics and images. E.g.: Button, TextArea,
Window
• java.awt.color: Provides classes for color spaces.
• java.sql: Provides classes for implementing database
connectivity.
• The classes in this package are used for connecting to the
database and performing operations on the database
Packages
• java.util
• Contains the collections framework, legacy
collection classes, date and time facilities, and
miscellaneous utility classes (a string, a
random-number generator, and a bit array).
Access Modifiers
• These are used for controlling the accessibility
of the members of a class
• They broaden or restrict the accessibility of
the members to other classes.
• Default: the members are accessible to classes
in which they are defined
• The subclasses in the same package
• Other classes
ACCESS MODIFIERS
Protected: subclasses, other classes in the same
package
Private: the classes in which they are defined
Public: other classes in another packages,
subclasses in another packages, classes in the
same packages
APPLET
Applet
• An applet is a java program designed to be run
by a Java-enabled web browser or an applet
viewer
• The applet is written in java and compiled like
any other Java application
• The web browser is an application contains
the main method
• Applet does not have a main() method and
therefore cannot be started as an application
Applets
• Java programs written to run on World Wide
Web (WWW) are called applets.
• An applet is a Java program that can be
embedded in a web page. Java applications
are run by using a Java interpreter.
• Applets are run on any browser that supports
Java.
• In order to run an applet it must be included
in a web page, using HTML tags.
• All applets are subclasses of the Applet class
in the java.applet package.
• Applets do not have main() method.
• An applet displays information on the
screen by using the paint method. This
method is available in java.awt.Component
class.
• The browser creates an instance of Graphics
class and passes to the method paint().
Graphics
• Graphics class provides a method
drawString to display text.
• It also requires a position to be specified as
arguments.
END
HTML BASIC STRUCTURE
<html>
<body>
<Head>
</Head>
<Title>
</Title>
</body>
</html>
• An applet is called from an Html script file
• The java applet is included in a web page
using the <Applet> tag which has the syntax:
<Applet code = applet filename
width = pixel width
height= pixel height>
</Applet>
Java Applet Implementation

import java.applet.Applet;
import java.awt.Graphics;
public class AppletProgram extends Applet
{
public void paint(Graphics g)
{
g.drawString("Big Java", 25,25);
}
}
HTML SCRIPT

<html>
<body>
<Applet code = "AppletProgram" width = 150
height = 100>

</Applet>

</body>

</html>
Applet Programming
// Applet programming
import java.applet.Applet;
import java.awt.Graphics;

public class JavaApp extends Applet


{
public void paint(Graphics g)
{

g.drawString("Hello Welcome to my applet programming Page", 25,25);

g.drawString("Java Programmer can used Java to create two types of java programs", 27,37);

g.drawString("An applet is a java program run by a Java-enabled web browser or an applet viewer", 20,50);
}

}
HTML Code to Run Applet
<html>
<body>
<Applet code = "JavaApp.class" width = 250
height = 200>

</Applet>

</body>

</html>
Drawing Lines Using Applet
import java.applet.*;
import java.awt.*;
public class DrawingLines extends Applet {
int width, height;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void paint( Graphics g ) {
g.setColor( Color.green );
for ( int i = 0; i < 10; ++i ) {
g.drawLine( width, height, i * width / 10, 0 );
}
}
}
HTML FILE TO RUN APPLET
<html>
<body>
<Applet code = "DrawingLines.class" width =
250 height = 200>

</Applet>

</body>

</html>
Lab Exercise
Write an applet to draw 15 lines on a yellow
background
Applet Implementation
// Drawing red Lines applet
import java.applet.*;
import java.awt.*;
public class DrawingRedLines extends Applet {
int width, height;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void paint( Graphics g ) {
g.setColor( Color.red );
for ( int i = 0; i < 10; ++i ) {
g.drawLine( width, height, i * width / 10, 0 );
}
}
}
// Draw red lines
<html>
<body>
<Applet code = "DrawingRedLines.class" width = 250 height = 200>

</Applet>

</body>

</html>
Applet Application 1
//This program produces applet
import java.awt.*;
import java.applet.Applet;

public class MyAppletTest extends Applet


{
public void paint(Graphics g)
{

g.drawString("Welcome to my Page", 500,500);


}

}
HTML Script
<html>
<head>
<title> My Page</title>
</head>
<body>
<h2>This page shows use of Applet</h2>
<p><applet code =“MyAppletTest.class" width= 300 height =
100>
</applet>
<hr>
</body>
</html>
Applet application 2
// Lifecycle of an applet
import java.applet.Applet;
public class LifeCycle extends Applet{

public void init(){


System.out.println("init() method is called. This is the first milestone.");
}
public void start(){
System.out.println("stop() method is called. This is the second milestone.");
}
public void stop(){
System.out.println("stop() method is called. This is the third milestone.");
}
public void distroy(){
System.out.println("distroy () method is called. This is the last milestone.");
}
}
HTML SCRIPT
<HTML>
<Body>
<Applet code = "LifeCycle.class" width =
600 height = 300>
</Applet>
</Body>
</HTML>
APPLET 3
// The applet without comments
import java.applet.*;
import java.awt.*;
public class HelloWorldWar extends Applet {
public void init() {
}
public void stop() {
}
public void paint(Graphics g) {
g.drawString("Hey hey hey",20,20);
g.drawString("Hellooow WorldWar",20,40);
}
}
Running the Applet

<HTML>
<Body>
<Applet code = "HelloWorldWar.class"
width = 600 height = 300>
</Applet>
</Body>
</HTML>
Applet Application 3
// The applet using Java
import java.applet.*;
import java.awt.*;
public class TestApplet extends Applet {
public void paint(Graphics g) {
g.drawString(“Welcome to my Page",10,10);
}
}
HTML to run the applet

<HTML>
<head>
<title> My page </title>
</head>
<Body>
<h2> This page shows the use of applet </h2>
<Applet code = " TestApplet.class" width = 600
height = 300>
</Applet>
</Body>
</HTML>
HTML and APPLET
<html>
<head>
<title>The Java Applet</title>
</head>
<body>
<H1>Welcome to the JAVA Applet!</H1>
<applet width=300 height=300
code="DrawingLines.class">
</applet>
</body>
</html>
• public class DrawingLines extends Applet {

• int width, height;
• public void init() {
• width = getSize().width;
• height = getSize().height;
• setBackground( Color.black );
• }

• public void paint( Graphics g ) {
• g.setColor( Color.green );
• for ( int i = 0; i < 10; ++i ) {
• g.drawLine( width, height, i * width / 10, 0 );
• }
• }
• }
<html>
<head>
<title>The Java Applet</title>
</head>
<body>
<H1>Welcome to the JAVA Applet!</H1>
<applet width=300 height=300
code="DrawingLines.class"> </applet>
Sorry, your browser isn’t able to run Java applets.
</body>
</html>
Graphics
• Graphics class provides a method drawString
to display text.
• It also requires a position to be specified as
arguments.
END
import java.applet.*;
import java.awt.*;
public class DrawingLines extends Applet {
int width, height;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.blue );
}
}
Drawing Lines
public class DrawingLines extends Applet {
int width, height;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void paint( Graphics g ) {
g.setColor( Color.red );
for ( int i = 0; i < 10; ++i ) {
g.drawLine( width, height, i * width / 10, 0 );
} }
}
• The HelloWorld applet shown next is a Java class that displays the string "Hello World".
• Following is the source code for the HelloWorld applet:

import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
public class HelloWorld extends JApplet { //Called when
this applet is loaded into the browser.
public void init() { //Execute a job on the event-
dispatching thread; creating this applet's GUI. try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JLabel lbl = new JLabel("Hello World");
add(lbl);
} });
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
} }}
//Here's the source code for an applet:
import java.applet.*;
import java.awt.*;
public class DrawingLines extends Applet {
int width, height;
public void init() {
width = getSize().width;
height = getSize().height;
setBackground( Color.black );
}
public void paint( Graphics g ) {
g.setColor( Color.green );
for ( int i = 0; i < 10; ++i ) {
g.drawLine( width, height, i * width / 10, 0 );
} }
SESSION OUTLINE
• Java Foundation Classes
• Creating Graphical User Interface
• Application of Graphical User Interface
Java Foundation Classes (JFC)
• A group of features to help people build
graphical user interfaces (GUIs).
• A GUI is an interface between a user and a
computer that makes use of input devices
other than the keyboard, and presentation
techniques other than alphanumeric
• The JFC is defined as containing the following
features:
Java Abstract Windowing Toolkit
• java.awt: Contains all of the classes for
creating user interfaces and for painting
graphics and images. E.g.: Button, TextArea,
Window
How to Display Components
• Containers are the objects that are displayed
directly on the screen. Example: JFrame
• Controls must be added to a container if you
want to see them.
• The container, JFrame will be the main
window of most of the swing applications.
The GUI Builder's windows
Components
• The IDE's GUI Builder solves the core problem
of Java GUI creation by streamlining the
workflow of creating graphical interfaces,
freeing developers from the complexities of
Swing layout managers.
• Design Area
• Palette
• Properties Window
• Navigator
Design Area.
• This is the GUI Builder's primary window for
creating and editing Java GUI forms.
• The toolbar's Source button enables you to
view a class's source code,
• The Design button allows you to view a
graphical view of the GUI components,
• The History button allows you to access the
local history of changes of the file.
• The additional toolbar buttons provide
convenient access to common commands
Palette Window
• A customizable list of available components
containing tabs for JFC/Swing, AWT, and
JavaBeans components, as well as layout
managers.
• In addition, you can create, remove, and
rearrange the categories displayed in the
Palette using the customizer.
Java Palette Tools
• The palette contains a number of useful tools for
designing GUI
• Swing Containers: Panel, Frame, Toolbar, etc.
• Swing Controls: Button, Checkbox, Text Field, Text
Area, etc
• Swing Menus: Menu bar, Popup Menu, Menu,
etc.
• Swing Windows: Dialog box, File Chooser, Color
Chooser, etc
• AWT: A Label, Text Field, List, Text Area, etc.
Properties Window
• Displays the properties of the component
currently selected in the GUI Builder,
Navigator window, Projects window, or Files
window.
Navigator
• Provides a representation of all the
components, both visual and non-visual, in
your application as a tree hierarchy.
• The Navigator also provides visual feedback
about what component in the tree is currently
being edited in the GUI Builder as well as
allows you to organize components in the
available panels.
Free Design
• In the IDE's GUI Builder, you can build your
forms by simply putting components where
you want them as though you were using
absolute positioning.
• The GUI Builder figures out which layout
attributes are required and then generates the
code for you automatically.
• You need not concern yourself with insets,
anchors, fills, and so forth.
Automatic Component Positioning
(Snapping)
• The GUI Builder provides visual feedback that
assists in positioning components as you add
components to a form,
• The GUI Builder provides helpful inline hints
and other visual feedback regarding where
components should be placed on your form,
• Automatically snapping components into
position along guidelines.
• Visual Feedback
Visual Feedback
• The GUI Builder provides visual feedback
regarding component anchoring/fixing and
chaining relationships.
• These indicators enable you to quickly identify
the various positioning relationships and
component
• This speeds the GUI design process, enabling
you to quickly create visual interfaces that
work.
Creation of Some Components
• Text Field/ JText Field: An area of the screen
where one can enter a line of text or for
editing a single line of text.
• Codes to create TextFields
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
BUTTON (OK)
A labelled button
Code to create buttons:
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();

• Close a window
Exit = new javax.swing.JButton();
Application of GUI
import java.awt.*;
public class GUI extends Frame {
public GUI (String s){
super(s);
setBackground(Color.yellow);
setLayout(new FlowLayout());
Button pushButton = new Button("press me");
add(pushButton);
}
public static void main(String[] args) {
GUI screen = new GUI ("Example 1");
screen.setSize(500, 100);
screen.setVisible(true);
} }
EVENT
• An Event is an action which occurs when a GUI
component changes its state.
• Examples:
• When a button is pressed
• When an item is selected in a list, event is generated.
• Events are handled through interfaces
public class GUI extends Frame implements
ActionListener {
ActionListener Interface
• The interface ActionListener is contained in
the package java.awt.event.
• Therefore we should import java.awt.event
into the application as
import java.awt.event;
• This interface contains a method:
• public void actionPerformed(ActionEvent
event) {
Implementation

JButton okButton = new JButton("Open a Frame");


okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("A Frame shown to the user.");
frame.setVisible(true);
}
}
);
import java.awt.*;
import java.awt.event.*;
public class GUI extends Frame implements ActionListener {
public GUI (String s){
super(s);
setBackground(Color.red);
setLayout(new FlowLayout());
// addWindowListener(this);
Button pushButton = new Button("press me");
add(pushButton);
pushButton.addActionListener(this);}
public void windowClosed(WindowEvent event){}
public void windowDeiconifed(WindowEvent event){}
public void windowIconified(WindowEvent event){}
public void windowActivated(WindowEvent event){}
public void windowDeactivated(WindowEvent event){}
public void windowOpened(WindowEvent event){}

public void windowClosing(WindowEvent event ){


System.exit(0);
}
public void actionPerformed(ActionEvent event) {
final char BELL = '\u0007';
if(event.getActionCommand().equals("press me"))
System.out.print(BELL);
}
public static void main(String[] args) {
GUI screen = new GUI ("Example 2");
screen.setSize(500, 100);
screen.setVisible(true);
}
}
BUILDING GUI
1. Create the project
2. Deselect the main class
3. Build the front end interface
4. Create the Jframe container
5. Adding Actions
Creating Project
• Choose File > New Project.
• Select the Java node
• Choose Java Application.
• Click Next
• Enter the name of the project in the Project Name field
• Specify the project location.
• Leave the Use Dedicated Folder for Storing Libraries
checkbox unselected.
• Deselect checkbox of Create Main Class field.
• Click Finish.
Developing the User Interface
• Developing the UI of our Java (ContactEditor)
application.
• We use the IDE's Palette to add the various
GUI components that we need to our form.
• The IDE's Free Design paradigm helps to
control the size and position of the
components within the containers.
• All you need to do is drag and drop the
components you need to the GUI form
Create the Jframe container
1. Right click the project node
2. Choose New
3. Choose other
4. Choose New file dialog box
5. Choose Swing GUI form category choose Jframe
form file type
6. Next
7. Enter NumberAdditionUI (as the class name)
8. Enter my.numberaddition as package name
9. Click Finish
Adding Components
• With a JFrame as our form's container
• The next step is to add a couple of JPanels
which will enable us to group the components
of our UI using titled borders
Adding Jpanel Components to Form
• In the Palette window,
1. Click the Panel component from the Swing
Containers category
2. Move the cursor to the upper left corner of the
form in the GUI Builder.
3. Click in the form to place the JPanel in this
location
4. The JPanel component appears in the
ContactEditorUI form
Resize the JPanel
1. Select the Jpanel
2. Click and hold the resize handle on the right
3. Drag to the desire edge.
4. Release the resize handle to resize the
component.
5. Repeat the process to add as many Jpanel as
required
Add title borders to JPanels
1. Select the top JPanel in the GUI Builder.
2. In the Properties window, click the ellipsis button
(...) next to the Border property.
3. In the JPanel Border editor that appears, select the
Titled Border node in the Available Borders pane.
4. In the Properties pane enter Name for the Title
property.
5. Click the ellipsis (...) next to the Font property
6. Click OK to exit the dialogs.
7. Repeat steps 2 through 5 for the second Jpanel
8. Enter E-mail for the Title property.
Adding JLabel to Form
• In the Palette window, select the Label
component.
• Move the cursor over the Name JPanel we
added earlier.
• Click to place the label.
• The JLabel is added
Add JTextField to form
• In the Palette window,
• select the Text Field component from the
Swing Controls category.
• Move the cursor immediately to the right of
the First Name: Jlabel added.
• Click to position the JTextField.
Resize a JTextField
• Select the JTextField added to the right of
the Last Name: JLabel.
• Drag the JTextField's right edge resize handle
• Ensure alignment between the text field and
right edge of the Jpanel
• Release the mouse button
• The JTextField's right edge snaps into
alignment with the JPanel's recommended
edge margin
Adding a combo box
• Select the Combo Box
• the JComboBox's baseline is aligned with the
baseline of the text in the JLabel
• Ensure good spacing between components
• Click to position the combo box.
• Resize the combo box
• Save the file Ctrl + S
Lab Activity 1
• Design the interface below
Discussion of Lab Activity 2
• float num1, num2, result;
• // We have to parse the text to a type float.
• num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
• // Now we can perform the addition.
• result = num1+num2;
Session Outline
• Threading basics: what threads are
• Threads usefulness
• How to get started writing programs that use
them.
• Threads applications in programs
• Operating systems support the concept of processes
• Independently running programs that are isolated from
each other to some degree.
• Every Java program uses threads
• Every Java program has at least one thread -- the main
thread.
• When a Java program starts, the JVM creates the main
thread and calls the program's main() method within that
thread.

• Threading is a facility to allow multiple activities to coexist


within a single process.
Thread
• A thread is a kind of stripped down process - it
is just one `active hand' in a program
• Threads remember what they have done
separately
• They share the information about what
resources a program is using, and what state
the program is in.
• A thread is only a CPU assignment. Several
threads can contribute to a single task.
Multithreading
• The distribution of threads among various
processors
• A program in execution is called a process.
• A process is created and terminated, and it
allows some or all of the states of process
transition; such as New, Ready, Running,
Waiting and Exit.
Thread
• Thread is single sequence stream which allows
a program to split itself into two or more
simultaneously.
• A thread is contained inside a process and
different threads in the same process share
some resources.
Why use threads?
• Some of the reasons for using threads are that
they can help to:
1. Make the UI more responsive
2. Take advantage of multiprocessor systems
3. Simplify modeling
4. Perform asynchronous or background
processing
More Responsive UI
• Event-driven UI tools, AWT and Swing, have an
event thread that processes UI events such as
keystrokes and mouse clicks.
• AWT and Swing programs attach event
listeners to UI objects.
• These listeners are notified when a specific
event occurs, such as a button being clicked.
Event listeners are called from within the AWT
event thread.
Responsive UI
• If an event listener were to perform a lengthy
task, such as checking spelling in a large
document, the event thread would be busy
running the spelling checker, and thus would
not be able to process additional UI events
until the event listener completed.
• This would make the program appear to
freeze, which is upsetting to the user.
Responsive UI
• To avoid stalling the UI, the event listener
should hand off long tasks to another thread
so that the AWT thread can continue
processing UI events (including requests to
cancel the long-running task being performed)
while the task is in progress.
Take advantage of multiprocessor
systems
• Modern operating systems take advantage of
multiple processors and schedule threads to execute
on any available processor.
• The basic unit of scheduling is generally the thread;
• if a program has only one active thread, it can only
run on one processor at a time.
• If a program has multiple active threads, then
multiple threads may be scheduled at once.
• Multiple threads improve program throughput and
performance.
Advantages of using Threads
• Increase the responsiveness of GUI
applications
• Take advantage of multiprocessor systems
• Simplify program logic when there are
multiple independent entities
• Perform blocking I/O without blocking the
entire program
Life Cycle of a Thread
• Thread has six states:
– New
– Runnable
– Blocked
– Waiting
– Timed Waiting
– Terminated
Life Cycle of a Thread
• A thread is said to be in one of several thread
states.
• A new thread begins its life cycle in the new
state. It remains in this state until the program
starts the thread, which places it in the
runnable state.
• In the runnable state is considered to be
executing its task
Thread Life cycle
• Sometimes a runnable thread transitions to
the waiting state while it waits for another
thread to perform a task.
• A waiting thread transitions back to the
runnable state only when another thread
notifies the waiting thread to continue
executing.
• Timed waiting and waiting threads cannot use
a processor, even if one is available.
Thread Life Cycle
• Another way to place a thread in the timed
waiting state is to put a runnable thread to
sleep.
• A sleeping thread remains in the timed
waiting state for a designated period of time
(called a sleep interval), after which it returns
to the runnable state.
• Threads sleep when they momentarily do not
have work to perform.
Thread Life cycle
• A runnable thread enters the terminated state
when it successfully completes its task
• Otherwise terminates perhaps due to an error.
Diagrammatic Illustration of States of a
Thread
• Thread state
Creating thread
• Create a class that implements the standard
runnable interface
• Create a class that extends the standard
thread class
Implementing Runnable Interface

• // java multithreading using a class that implements the standard


runnable interface

import java.lang.*;
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
Lab Activity
public class SleepMessage {
public static void main(String args[])
throws InterruptedException {
String importantInfo[] = {
"The student sleeps in the class",
"Does he eat too much heavy food?",
"Majority of students eat little food before lectures",
"So you also eat little too" };
for (int i = 0;
i < importantInfo.length; i++) {
//Pause for 4 seconds
Thread.sleep(4000);
//Print a message
System.out.println(importantInfo[i]);
} }
}
public class TwoThreads {
public static class Thread1 extends Thread {
public void run() {
System.out.println("A");
System.out.println("B");
}}
public static class Thread2 extends Thread {
public void run() {
System.out.println("1");
System.out.println("2");
}}
public static void main(String[] args) {
new Thread1().start();
Threads and Java language
• Create a thread by instantiating an object of
type Thread (or a subclass) and send it
the start() message.
• A program can send the start() message to any
object that implements the Runnable interface.
Threads and Java language
• The definition of each thread's behavior is
contained in its run() method.
• A run method is equivalent to main() in a
traditional program: a thread will continue
running until run() returns, at which point the
thread dies or terminated.
Output
• We have no idea in what order the lines will
execute, except that "1" will be printed before "2"
and "A" before "B." The output could be any one
of the following:
• 12AB
• 1A2B
• 1AB2
• A12B
• A1B2
• AB12
Two threads to do work
• One for timing and one to do actual work.
• The main thread calculates prime numbers
• It creates and starts a timer thread
• Which will sleep for ten seconds, and then
set a flag that the main thread will check.
• After ten seconds, the main thread will stop.
Two threads to do work
// CalculatePrimes -- calculate as many primes as we can in ten seconds
public class CalculatePrimes extends Thread {
public static final int MAX_PRIMES = 1000000;
public static final int TEN_SECONDS = 10000;
public volatile boolean finished = false;
public void run() {
int[] primes = new int[MAX_PRIMES];
int count = 0;
for (int i=2; count<MAX_PRIMES; i++) {
// Check to see if the timer has expired
if (finished) {
break; }
boolean prime = true;
for (int j=0; j<count; j++) {
if (i % primes[j] == 0) {
prime = false;
break;
}}
if (prime) {
primes[count++] = i;
System.out.println("Found prime: " + i);
} }}
public static void main(String[] args) {
CalculatePrimes calculator = new CalculatePrimes();
calculator.start();
try {
Thread.sleep(TEN_SECONDS);
}
catch (InterruptedException e) {
// fall through
}
calculator.finished = true;
}}
End
• The definition of each thread's behavior is
contained in its run() method.
• A run method is equivalent to main() in a
traditional program: a thread will continue
running until run() returns, at which point the
thread dies or terminated.

You might also like