0% found this document useful (0 votes)
14 views305 pages

Building Java Programs

Uploaded by

robelassefa708
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)
14 views305 pages

Building Java Programs

Uploaded by

robelassefa708
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/ 305

Building Java Programs

Chapter 1
Lecture 1-1: Introduction; Basic Java Programs

reading: 1.1 - 1.3

Copyright 2013 by Pearson Education


Programming
 program: A set of instructions
to be carried out by a computer.

 program execution: The act of


carrying out the instructions
contained in a program.

 programming language: A systematic set of rules used


to describe computations in a format that is editable by
humans.

2
Copyright 2013 by Pearson Education
Why Java?
 Relatively simple

 Object-oriented

 Pre-written software

 Platform independent (Mac, Windows…)

 Widely used
 #1 in popularity ie
http://www.tiobe.com/index.php/content/paperinfo/tpci/index
.html

3
Copyright 2013 by Pearson Education
Compiling/running a program
1. Write it.
code or source code: The set of instructions in a
program.
2. Compile it.
• compile: Translate a program from one language to
another.
byte code: The Java compiler converts your code into a
format named byte code that runs on many computer
types.
3. Run (execute) it. output
source code byte code
output: The messages printed to the user by a program.
compile run

4
Copyright 2013 by Pearson Education
What is JDK? Why We need JDK
 The Java Development Kit (JDK) is a software development
environment used for developing Java applications and applets.
 It includes the Java Runtime Environment (JRE), an interpreter/loader
(java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc) and other tools needed in Java development.

5
Copyright 2013 by Pearson Education
A Java program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println();
System.out.println("This program produces");
System.out.println("four lines of output");
}
}

 Its output:
Hello, world!

This program produces


four lines of output

6
Copyright 2013 by Pearson Education
Structure of a Java program
class: a program
public class name {
public static void main(String[] args) {
statement;
statement; method: a named group
... of statements
statement;
}
} statement: a command to be executed

 Every executable Java program consists of a class,


 that contains a method named main,
 that contains the statements (commands) to be executed.

7
Copyright 2013 by Pearson Education
System.out.println
 A statement that prints a line of output on the console.
 pronounced "print-linn"
 sometimes called a "println statement" for short

 Two ways to use System.out.println :

•System.out.println("text");
Prints the given message as output.

•System.out.println();
Prints a blank line of output.

8
Copyright 2013 by Pearson Education
Names and identifiers
 You must give your program a name.

public class GangstaRap {

 Naming convention: capitalize each word (e.g. MyClassName)


 Your program's file must match exactly (GangstaRap.java)
 includes capitalization (Java is "case-sensitive")

 identifier: A name given to an item in your program.


 must start with a letter or _ or $
 subsequent characters can be any of those or a number
 legal: _myName TheCure ANSWER_IS_42 $bling$
 illegal: me+u 49ers side-swipe Ph.D's

9
Copyright 2013 by Pearson Education
Keywords
 keyword: An identifier that you cannot use because it
already has a reserved meaning in Java.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized

 i.e., You may not use char or while for the name of a class.

10
Copyright 2013 by Pearson Education
Syntax
 syntax: The set of legal structures and commands that can
be used in a particular language.
 Every basic Java statement ends with a semicolon ;
 The contents of a class or method occur between { and }

 syntax error (compiler error): A problem in the


structure of a program that causes the compiler to fail.
Examples:
 Missing semicolon
 Too many or too few { } braces
 Illegal identifier for class name
 Class and file names do not match
 ...
11
Copyright 2013 by Pearson Education
Syntax error example
1 public class Hello {
2 pooblic static void main(String[] args) {
3 System.owt.println("Hello, world!")_
4 }
5 }

 Compiler output:
Hello.java:2: <identifier> expected
pooblic static void main(String[] args) {
^
Hello.java:3: ';' expected
}
^
2 errors

 The compiler shows the line number where it found the error.
 The error messages can be tough to understand!

12
Copyright 2013 by Pearson Education
string: A sequence of characters to be printed.
Starts and ends with a " quote " character.

Strings  The quotes do not appear in the output.


Examples:
"hello"
"This is a string. It's very long!"

Restrictions:
May not span multiple lines.

"This is not
a legal String."
May not contain a " character.
"This is not a "legal" String either."

13
Copyright 2013 by Pearson Education
escape sequence: A special sequence of characters used to
represent certain special characters in a string.

Escape \t tab character


sequences
\n new line character
\" quotation mark character
\\ backslash character

 Example:
System.out.println("\\hello\nhow\tare \"you\"?\\\\");
Output:
\hello
how are "you"?\\

14
Copyright 2013 by Pearson Education
Questions
 What is the output of the following println statements?

System.out.println("\ta\tb\tc");
System.out.println("\\\\");
System.out.println("'");
System.out.println("\"\"\"");
System.out.println("C:\nin\the downward spiral");

 Write a println statement to produce this output:


/ \ // \\ /// \\\

15
Copyright 2013 by Pearson Education
Answers
 Output of each println statement:
a b c
\\
'
"""
C:
in he downward spiral

 println statement to produce the line of output:


System.out.println("/ \\ // \\\\ /// \\\\\\");

16
Copyright 2013 by Pearson Education
Questions
 What println statements will generate this output?
This program prints a
quote from the Gettysburg Address.

"Four score and seven years ago,


our 'fore fathers' brought forth on
this continent a new nation."

 What println statements will generate this output?


A "quoted" String is
'much' better if you learn
the rules of "escape sequences."

Also, "" represents an empty String.


Don't forget: use \" instead of " !
'' is not the same as "

17
Copyright 2013 by Pearson Education
Answers
 println statements to generate the output:
System.out.println("This program prints a");
System.out.println("quote from the Gettysburg Address.");
System.out.println();
System.out.println("\"Four score and seven years ago,");
System.out.println("our 'fore fathers' brought forth on");
System.out.println("this continent a new nation.\"");

 println statements to generate the output:


System.out.println("A \"quoted\" String is");
System.out.println("'much' better if you learn");
System.out.println("the rules of \"escape sequences.\"");
System.out.println();
System.out.println("Also, \"\" represents an empty String.");
System.out.println("Don't forget: use \\\" instead of \" !");
System.out.println("'' is not the same as \"");

18
Copyright 2013 by Pearson Education
EEEg3142
Object Oriented Programming

Department of CSIT, Software


Engineering
AASTU
October, 2017
Chapter 2
Introduction to Java Elements

2
Outline
 Introduction
 Sample Java Program
 Java Identifiers
 Java Keywords
 Number types, strings, constants
 Operators
 Type Conversion/Casting
 I/O, Conditional statements and loops
 Arrays

3
Definition and History of java
 Java is an object-oriented programming language.
 Java was developed by James Gosling and his team at
Sun Microsystems in California. Sun formally announced
Java at an industry conference in May 1995.
 In 1991 Sun funded an internal corporate research project
code-named Green. The language was based on C and
C++ and was originally intended for writing programs that
control consumer appliances such as toasters,
microwave ovens, and others.
 The language was first called Oak, named after the oak
tree outside of Gosling’s office, but the name was already
taken, so the team renamed it Java.
4
Java Application and Java Applet
 Java can be used to program two types of programs:
Applets and applications.
 Applets: are programs called that run within a Web
browser. That is, you need a Web browser to execute
Java applets.
 Applets allow more dynamic and
dissemination of information on the Internet
flexible
 Java Application: is a complete stand-alone program
that does not require a Web browser.
 A Java application is analogous to a program we write
in other programming languages.

5
Basics of a Typical Java Environment
 Java programs normally undergo five phases
 Edit
 Programmer writes program (and stores program on disk)
 Compile
 Compiler creates bytecodes from program
 Load
 Class loader stores bytecodes in memory
 Verify
 Verifier ensures bytecodes do not violate security requirements
 Execute
 Interpreter translates bytecodes into machine language

6
Basics of a Typical Java Environment(cont’d)

7
Basics of a Typical Java Environment(cont’d)

8
Basics of a Typical Java Environment(cont’d)

Java source
code

Java
Java bytecode
compiler

Bytecode
interpreter

Machine
code

9
Basics of a Typical Java Environment(cont’d)

 Phase 1: Creating a Program


 consists of editing a file with an editor program (editor).
 You type a Java program (source code) using the editor, make
any necessary corrections and save the program.
 A file name ending with the .java extension indicates that the file
contains Java source code

 Phase 2: Compiling a Java Program into Bytecodes


 Use the command javac (the Java compiler) to
compile a
program.
 E.g.: To compile a program called Welcome.java, you
would type javac Welcome.java in the command window
of your system

10
Basics of a Typical Java Environment(cont’d)
 If the program compiles, the compiler produces a .class file called
Welcome.class that contains the compiled version of the program.
 The Java compiler translates Java source code into bytecodes that
represent the tasks to execute in the execution phase (Phase 5).
 Byte codes are executed by the Java Virtual Machine (JVM).
 Virtual machine (VM) is a software application that simulates a
computer, but hides the under-lying operating system and hardware
from the programs that interact with the VM.
 Java’s bytecodes are portable. Unlike machine language, which is
dependent on specific computer hardware, bytecodes are platform-
independent instructions. That is why Java is guaranteed to be
Write Once, Run Anywhere.
 The JVM is invoked by the java command.
 For example, to execute a Java application called Welcome, you
would type the command java Welcome in a command window to
invoke the JVM, which would then initiate the steps necessary to
execute the application. This begins Phase 3. 11
Basics of a Typical Java Environment(cont’d)

 Phase 3: loading: placing the program in memory before


executing it.
 The class loader takes the .class files containing the program’s
bytecodes and transfers them to primary memory.
 The .class files can be loaded from a disk on your system or over
a network (e.g., your local college or company network, or the
Internet).

 Phase 4: Bytecode Verification


 bytecode verifier examines their bytecodes to ensure that they
are valid and do not violate Java’s security restrictions.
 Java enforces strong security, to make sure that Java programs
arriving over the network do not damage your files or your
system (as computer viruses and worms might).

12
Basics of a Typical Java Environment(cont’d)

 Phase 5: Execution
 The JVM executes the program’s bytecodes, thus performing the
actions specified by the program.
 In early Java versions, the JVM would interpret and execute one
bytecode at a time; Java programs execute slowly.
 Today’s JVMs typically execute bytecodes using a combination of
interpretation and so-called just-in-time (JIT) compilation.
 The JVM analyzes the bytecodes as they are interpreted, searching
for hot spots— parts of the bytecodes that execute frequently.

 Integrated development environment (IDE)


combines these steps into a single task.
 A graphical user interface is available for editing,
compiling,
linking, and running the application.
 Example: NetBeans, Eclipse, Jbuilder, …
13
Java Features
 Java is:
 Object Oriented
 Simple
 Architectural-neutral: Java compiler generates an architecture-
neutral object file format which makes the compiled code to be
executable on many processors
 Platform independent
 Portable
 Java promise: “Write once, run everywhere”.
 Secure
 Robust: measures how well the program runs under various
conditions.
 Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime
checking through mechanisms like exception handling.
14
Java Features(cont’d)
 Multithreaded:
 With Java's multithreaded feature it is possible to write programs
that can do many tasks simultaneously.
 Java differs from other programming languages in that it is both
compiled and interpreted language.
 High Performance: With the use of Just-In-Time compilers,
Java enables high performance.

15
Syntax & Semantics
 The syntax rules of a language define how we can put
together symbols, reserved words, and identifiers to
make a valid program
 The semantics of a program statement define what
that statement means (its purpose or role in a
program)
 A program that is syntactically correct is
necessarily logically (semantically) correct
not
 A program will always do what we tell it to do,
not what we meant to tell it to do

16
Errors
 A program can have three types of errors

 The compiler will find syntax errors and other basic


problems (compile-time errors)
 If compile-time errors exist, an executable version
of the
program is not created

 A problem can occur during program execution, such


as trying to divide by zero, which causes a program to
terminate abnormally (run-time errors)

 A program may run, but produce incorrect results,


perhaps using an incorrect formula (logical errors)
17
Java Program Structure
 In the Java programming language:
 A program is made up of one or more classes
 A class contains one or more methods
 A method contains program statements

 A Java application always contains a method called


main

18
Java Program Structure(cont’d)

// comments about the class


public class MyProgram
{
class header

class
body

Comments can be placed


anywhere

19
Java Program Structure(cont’d)

// comments about the class


public class MyProgram
{
// comments about the
method
public static void main
(String[] args)
method method
{ body header

20
First Java Program
 A simple code that would print the words Hello World.
public class MyFirstJavaProgram {
public static void main(String[ ] args)
{ System.out.println("Hello
World");
}
}

21
Basic Syntax
 About Java programs, it is very important to keep in
mind the following points.
 Case Sensitivity, E.g. Hello is different from hello
 Class Names - For all class names the first letter shall be in
Upper Case. If several words are used to form a name of the
class, each inner word's first letter should be in Upper Case.
 Example class MyFirstJavaClass
 Method Names - All method names shall start with a lower
case letter. If several words are used to form the name of the
method, then each inner word's first letter should be in Upper
Case. Example public void myMethodName()
 Program File Name - Name of the program file should
exactly match the class name. Example : Assume
'MyFirstJavaProgram' is the class name. Then the file should be
saved as 'MyFirstJavaProgram.java'.
 Public static void main(String[] args)- Java program processing
22
starts from the main()
Java Keywords
 The following list shows the reserved words in Java.
These reserved words may not be used as constant
or variable or any other identifier names.

23
Java Identifiers
 Names used for classes, variables and methods are
called identifiers.
 All identifiers should begin with a letter (A to Z or a to z),
currency character
($) or an underscore (_).
 After the first character identifiers can have any combination of
letters, digit, $, and _.
 A key word cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, 1_value
 Examples of illegal identifiers: 123abc, -salary

24
Comments in Java
 E.g.
public static void main(String []args){
// This is an example of single line comment
/* This is also an example of
multline comment. */
System.out.println("Hello World");
}
}

25
Variable
 A variable is a name for a location in memory
 You must declare all variables before they can be used.
The basic form of a variable declaration is:
 data type variable [ = value][, variable [= value] ...] ;
data variable
type name

int total;
 E.g. int a, b, c; // Declares three ints, a, b, and c.
 int a = 10, b = 10; // Example of initialization
 byte B = 22; // initializes a byte type variable B.
 double pi = 3.14159; // declares and assigns a value of PI.
 char a = 'a'; // the char variable a iis initialized with value ‘a’

26
Java Variable Types(cont’d)
 There are two data types available in Java:
 Primitive Data Types
 Reference/Object Data Types

Data Size Range


Type
byte 1 byte Integers in the range of -128 to +128
short 2 bytes Integers in the range of -32,768 to +32,767
int 4 bytes Integers in the range of -2,147,483,648 to
+2,147,483,647
long 8 bytes Integers in the range of -9,223,372,036,854,775,808
to +9,223,372,036,854,775,807
float 4 bytes Floating-point numbers in the range of ±3.4x10-38 to
±3.4x1038 with 7 digits of accuracy
double 8 bytes Floating-point numbers in the range of ±1.7x10-308 to
±1.7x10308 with 15 digits of accuracy

27
Constants
 A constant is an identifier that is similar to a variable
except that it holds the same value during its entire
existence
 Example:
 byte a = 68;
 char a = 'A'

 In Java, we use the final modifier to declare a


constant final int MIN_HEIGHT = 69;

28
The println Method
 We can invoke the println method to print
a
character string
 The System.out object represents a destination
(the monitor screen) to which we can send output

System.out.println ("Whatever you are, be a good


one.");
object method
information provided to the
name
method (parameters)

29
The print Method
 The System.out object provides another service
as well

 The print method is similar to the println


method, except that it does not advance to the next
line

 Therefore anything printed after a print


statement will appear on the same line

30
Escape Sequence(cont’d)
 What if we wanted to print a the quote character?
 The following line would confuse the compiler
because it would interpret the second quote as the
end of the string
System.out.println ("I said "Hello" to you.");

 An escape sequence is a series of characters that


represents a special character
 An escape sequence begins with a backslash
character (\)
System.out.println ("I said \"Hello\" to you.");

31
Escape Sequence

32
EscapeExample.java
public class EscapeExample{
public static void main( String args[] )
{ System.out.println("Hello World");
System.out.println("two\nlines");
System.out.println("\"This is in quotes\"");
}
}
Output:
Hello World
two
lines
“This
is in
quot 33
String
 A string of characters can be represented as a string literal by
putting double quotes around the text:
 Examples:
"This is a string literal."
"123 Main Street"
 There are close to 50 methods defined in the String class. We
will introduce some of them here:
 substring
 E.g. String text;
text = "Espresso";
System.out.print(t
ext.substring(2,
7));
 Output: press
 Length
 Example
 text1 = "";
//empty string
 text2 = "Hello";
 text3 = "Java"; 34
String(cont’d)
 Indexof()
 To locate the index position of a substring within another string, we
use the indexOf() method
 Example
 text = "I Love Java and Java loves me.";
 text.indexOf("J") =7
 text.indexOf("love") =21
 text.indexOf("ove") =3

 String concatenation
 We can create a new string from two strings by concatenating the
two strings. We use the plus symbol (+) for string concatenation
 string text1 = "Jon";
 string text2 = "Java";
 text1 + text2--------- "JonJava"
 text1 + " " + text2--------- "Jon Java"
 "How are you, " + text1 + "?"-------------- "How are you, Jon?"
35
StringExample.java
public class StringExample{
public static void main(String[] args) {
String text1="Espresslo", text2 = "Hello“;
String text3 = "I Love Java and Java loves
me."; System.out.println(text1.substring(2,7));
System.out.println(text2.length());
System.out.println(text3.indexOf("I"));
System.out.println(text1+" "+text2);
}
}
Output:?

36
Simple Type Conversion/Casting
 A value in any of the built-in types we have seen so
far can be converted (type-cast) to any of the other
types.
 For example: (int) 3.14 // converts 3.14 to an
int 3
 (double) 2 // converts 2 to a double to
give 2.0
 (string) 122 // converts 122 to a string
whose code=122
 Integer division always results in an integer
outcome.
 Division of integer by integer will not round off to the next
integer
37
 E.g.: 9/2 gives 4 not 4.5
Java Basic Operators
 Java provides a rich set of operators to manipulate
variables. We can divide all the Java operators into
the following groups:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators

38
Arithmetic Operator

39
Example
public class Test{
public static void main(String args[]){
int a =10;
int b =20;
int c =25;
int d =25;
System.out.println("a + b = "+(a +
b));
System.out.println("a - b = "+(a - b));
System.out.println("a * b = "+(a * b));
System.out.println("b / a = "+(b / a));
System.out.println("b % a = "+(b % a));
System.out.println("c % a = "+(c % a));
System.out.println("a++ = "+(a++)); 40
Example(cont’d)
System.out.println(“a-- = "+(a--));
// Check the difference in d++ and ++d
System.out.println("d++ = "+(d++));
System.out.println("++d = "+(++d));
}
}
 This would produce the
following result:
 a + b =30
 a - b =-10
 a * b =200
 b / a =2
 b % a =0
 c % a =5
 a++=10
 b--=11
 d++=25
 ++d =27 41
The Relational Operator

42
Example
public class Test{
public static void main(String args[]){
int a =10;
int b =20;
System.out.println("a == b = "+(a ==
b));
System.out.println("a != b = "+(a !=
b));
}
}

 This would produce the


following result:
 a == b =false
 a != b =true
43
The Logical Operators

44
Example
public class Test{
public static void main(String args[]){
boolean a =true;
boolean b =false;
System.out.println("a && b = "+(a&&b));
System.out.println("a || b = "+(a||b));
System.out.println("!(a && b) = "+!(a && b));
}
}

 This would produce the


following result:
 a && b =false
 a || b =true
45

The Assignment Operator

46
Basic Classes
1. System: one of the core classes
 System.out.println( "Welcome to Java!" );
 System.out.print(“…”);
 System.exit(0);

47
Basic Classes(cont’d)
2. Scanner:
 The java.util.Scanner: for accepting input from console
 Methods: nextInt(), nextDouble(), nextLine(), next(), …
 Eg:- Scanner s=new Scanner (System.in);
int x=s.nextInt();
3. JOptionPane
 The JOptionPane provides dialog boxes for both input
and output.

48
Basic Classes(cont’d)
Eg:
 int x =JOptionPane.showInputDialog( "Enter first integer" );
 JOptionPane.showMessageDialog( null, “result" + sum,
“Title", PLAIN_MESSAGE);
 The following statement must be before the class
program’s
header(tells the compiler where to find the JOptionPane class)
import javax.swing.JOptionPane;

49
Example 1
import java.util.Scanner; // so that I can use Scanner
public class Age{
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How old are you? "); // prompt
int age = console.nextInt();
System.out.println("You'll be 30 in " + (30 - age)
+ " years.");
} }
Output:
How old are you? 18
You’ll be 30 in 12 years

50
Example 2
import java.util.*;
public class HelloName{
public static void main(String args[])
{ Scanner input= new
Scanner(System.in);
System.out.print("What is your name? ");
String name = input.nextLine();
System.out.println("Hello there " + name +
", nice to meet you!");
}
}
Output:
Hello there Leta, nice to meet you! 51
Example3
import java.util.Scanner; // program uses class Scanner
// Addition program that displays the sum of two numbers.
public class AdditionExample{
// main method begins execution of Java application
public static void main( String args[] ){
Scanner input = new Scanner( System.in );
int number1; // first number to add
int number2; // second number to add
int sum; // sum of number1 and number2
System.out.print( "Enter first integer: " ); // prompt
number1 = input.nextInt(); // read first number from user
System.out.print( "Enter second integer: " ); // prompt
number2 = input.nextInt(); // read second number from user
sum = number1 + number2; // add numbers
System.out.println( "Sum is “ + sum );
} // end method main
} // end class Addition

52
Example 4
import javax.swing.JOptionPane;
String firstNumber, secondNumber;
int number1,number2,sum;
firstNumber =JOptionPane.showInputDialog( "Enter
first integer" );
secondNumber = JOptionPane.showInputDialog( "Enter second
integer" );
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
sum = number1 + number2;

JOptionPane.showMessageDialog( null,
"The sum is " + sum,
"Results", JOptionPane.PLAIN_MESSAGE );
System.exit( 0 );
53
Basic Classes(cont’d)
4. Math-Class
 The java.lang.Math contains methods
class
performing basic numeric for
elementary exponential, logarithm,
operations square root,
such as
and trigonometric functions the
 Eg: Math.ceil(x)
 Math.floor(x)
 Math.PI;
 Math.sin(x);
 Math.pow(x,y), Math.round(x)
 Math.max(x,y) ,Math.toDegrees(x);
 Math.random(): a random floating point number between
0
and 1. generates a double value in the range [0,1)
54
Basic Classes(cont’d)
 Random is a class used to generate random numbers
between the given lists/ranges.
 Example:
import java.util.Random;
import java.util.Scanner;
public class RandomExample {
public static void main(String[] args) {
double x []=new double[20];
Random r=new Random();
int sum=0;
Scanner s=new Scanner(System.in);
for(int i=0;i<5;i++)
{x[i]=r.nextInt(100);
System.out.println(x[i])
;
} 55
Conditional Statements
 Two types:
 If statements
 Switch statements

 Syntax of if statements
if(expression){
//Statements will execute if the expression is true
}

56
Example
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if
statement");
}
}

Output
This is if statement

57
if…else statement
 An if statement can be followed by an optional else
statement, which executes when the expression is
false.
if(expression){
//Executes when the expression is true
}else{
//Executes when the expression is false
}

58
Example 1
public class Test2 {
public static void main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("This is if
statement");
}else{
System.out.print("This is else
statement");
}
}
}
Output:
This is else statement 59
Example2
public class Test3 {
public static void main(String args[]){
int x = 30;
if( x == 10 )
{ System.out.print("Value of X is
10");
}else if( x == 20 )
{ System.out.print("Value of X is
20");
}else if( x == 30 )
{ System.out.print("Value of X is
30");
}else{
System.out.print("This is else
statement"); 60
Switch
Handles multiple conditions efficiently.
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}

61
Example
public class SwitchTest {
public static void main(String args[]){
char grade = 'C';
switch(grade){
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
System.out.println("Well done");
break;
case 'C' :
System.out.println("You
passed");
break;
case 'D' :
System.out.println("You Failed");
case 'F' :
System.out.println("Better try
again");
break;
default : 62
Loop
 There may be a situation when we need to execute a
block of code several number of times, and is often
referred to as a loop.
 You can use one of the following three loops:
 while Loop
 for Loop
 do...while Loop

63
Example
 Displaying all squares of numbers 1 to 10
public static void main(String args[])
{ int i=1;
while(i<=10)
{ System.out.println(i*i
); i++;
}
}

64
Exercise
Write a program to:
1. Check whether a number is even or not…using if &
Scanner
2. Display sum of the first 100 integer numbers using
for loop.

65
Arrays
stores a fixed-size sequential collection of elements
of the same type.
Sysntax:
Data type arrayname[]=new dataType[size];

int x[]=new int[20];


Example-
import java.util.*;
public class ArrayExample{
public static void main(String[] args) {
int x []=new int[20];//array declaration
int sum=0; 66
Scanner s=new Scanner(System.in);
System.out.println("enter the numbers");
for(int i=0;i<5;i++)
{ x[i]=s.nextInt();
sum =sum+x[i];
}
System.out.println("result="+sum);
}}

67
Exercise: Array
1. Write a java program that accepts 5 integers and display
1. the smallest
2. only evens
3. Count only integers>50
2. Insert N-integers from the keyboard and calculate the sum
and
average
3. Generate 5 random numbers between 10 and 20 and find
the smallest
4. Generate 5 random numbers between 1 and 50 and find
the largest two
5. Insert a string using Scanner and count the number of ‘a’ in
the string
6. Check if the inserted string is palindrome or not
68
Object Oriented Programming

Computer Engineering
Department AASTU
November, 2021
Chapter 3
Classes and Objects

2
Objectives
In this chapter you will learn:
 What classes, objects, methods and instance variables are.
 How to declare a class and use it to create an object.
 How to declare methods in a class to implement the class’s
behaviors.
 How to declare instance variables in a class to implement the
class’s attributes.
 How to call an object’s method to make that method perform
its task.
 How to use a constructor to ensure that an object’s data is
initialized when the object is created.

3
Content
 Classes and Objects
 Access Control (private, protected, public)
 Attributes and methods
 Constructors

4
Classes and Objects
 Object-oriented programming (OOP)
programming using objects.
involves
 The two most important concepts in object-
oriented programming are the class and the object.
 Object
 is an entity, both tangible and intangible, in the real world that
can be distinctly identified. E.g. Student, Room, Account
 An object is comprised of data and operations
manipulate
that these data.
 E.g.1 For a Student object
 Data(property/attribute): name, gender, birth date, home
address, phone number, age, …
 And operations for assigning and changing these data values.

5
Classes and Objects(cont’d)
 E.g. 2 dog,
 data - name, breed, color, …
 behavior(operation) - barking, wagging, running.

 Class
 A class is a template or blue print that defines what an object’s
data fields and methods will be.
 For the computer to be able to create an object, we must
provide a definition, called a class.
 A class is a kind of mold or template that dictates what objects
can and cannot do.
 An object is called an instance of a class.
 Once a class is defined, we can create as many instances of
the class as a program requires. Creating an instance is
referred to as instantiation.

6
Example: Class and object

7
Declaring Class
 Class Declaration syntax
class ClassName {
// declare instance variables
type var1;
type var2;
// ...
type varN;
// declare methods
type method1(parameters) {
// body of method
}
type method2(parameters) {
// body of method
}
// ...
type methodN(parameters) {
// body of method
}
} 8
Creating Objects
 A class provides the blue print for objects; you create an
object from a class.
 Syntax:
 ClassName objectname; //object declaration
 objectname=new ClassName (parameters); // object creation
Or
ClassName objectname=new ClassName
(parameters);
 E.g. If we have the following class definition for customer:
class Customer{
//variables
public void printCust(){
//method definition
}
}
we can create “cust” objcte as follows: 9
Accessing data members
 To access data members, and methods of the class,
we use dot(.) operator.
 Objectname.data member//to access the data member of
the class
 Objectname.method // to access the method of the
class
 E.g. cust.printCust();

10
Example 1
public class GradeBook {
public void displayMessage() {
System.out.println (“Welcome to the Grade Book!”);
}
}
 A second class GradeBookTest uses and
executes the method declared in Gradebook class

11
Cont’d
public class GradeBookTest{
public static void main (String args[] ) {
GradeBook myGradeBook = new GradeBook();
myGradeBook.displayMessage();
}
}

12
Example 2: defining a class
for circle object
public class Circle {
Double pi=3.14;
Double rad;
Double area(){
return (pi*rad*rad)
;
}
Double circumf (){
return
(2*pi*rad);
}
} 13
Cont’d
public class TestCircle {
public static void main(String args[]){
Circle c1=new Circle();
c1.rad=3.0;
System.out.println (“area of the circle is:”+c1.area());
System.out.println (“circumference of the circle
is:”+c1.circumf ());
}
}

14
Access control
 Java provides a number of access modifiers to set
access levels for classes, variables, methods, and
constructors.
 The access modifiers are: private, protected,
public and default
 Access to class members (in class C in package P)
 public: accessible anywhere C is accessible
 protected: accessible in P and to any of C’s subclasses
 private: only accessible within class C
 If you don't use any modifier: only accessible in P (the default)

15
Access control(cont’d)

16
Example
// public vs private access.
class MyClass {
private int alpha; // private access
public int beta; // public access
public int gamma; // public access
//Methods to access alpha. It is
OK for a member of a class to
//access a private member of the same
class. void setAlpha(int a) {
alpha = a;
}
int getAlpha() {
return alpha;
}

17
Example(cont’d)
class AccessDemo {
public static void main(String args[]) {
MyClass ob = new MyClass();
//Access to alpha is allowed only through its accessor
//method.
ob.setAlpha(-99);
System.out.println("ob.alpha is " + ob.getAlpha());
// You cannot access alpha like this:
// ob.alpha = 10; // Wrong! alpha is private!
// These are OK because beta and gamma are
public.
ob.beta = 88;
ob.gamma = 99;
System.out.println("ob.beta is " + ob.beta);
System.out.println("ob.gamma is " +
ob.gamma);

} 18
Exercise
 Based on the following sample code and information, identify the
correct statements from a-d
ClassA{
int a;
public int b;
private int c;
protected int d;
….
}
 ClassA & ClassB are defined under package1, Class C is defined
under
Package2 and ClassD, which is sub class of ClassB, is defined under Package3
 (a) ClassB{ClassA ca = new ClassA; ca.a; }
 (b) ClassC{ClassA cb = new ClassA; cb.b;}
 (c) ClassD{ClassA cc = new ClassA; cc.c ;}
 (d) ClassD{ClassA cd = new ClassA; cd.d }
19
Local, instance and class
(static) variables
 Local variables:
 Variables defined inside methods, constructors or blocks are
called local variables.
 The variable will be declared and initialized within the method
and the variable will be destroyed when the method has
completed.
 Local variables are visible only within the declared method,
constructor or block.
 There is no default value for local variables so local variables
should be declared and an initial value should be assigned
before the first use.
 E.g. in the next slide age is a local variable. This is defined
inside pupAge() method and its scope is limited to this method
only.

20
Example: Local Variables
public class TestLocal{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.pr
intln("Puppy
age is : " +
age);
}
public static void main(String args[]){
TestLocal test = new TestLocal();
test.pupAge();
}
}
Output
21
Example(cont’d)
 Following example uses age without initializing it, so it
would give an error at the time of compilation.
public class
Test{ public void
pupAge(){
int age;
age = age + 7;
System.out.println("P
uppy age is : " +
age);
}
public static void
main(String args[]){
Test test = new Test();
test.pupAge(); 22
Instance Variables
 Are variables within a class but outside any method.
 Instance variables are created when an object
created
is with the use of the keyword 'new' and
destroyed when the object is destroyed.
 Instance variables can be declared in class
level
before or after use.
 Instance variables can be accessed directly by
calling the variable name inside the class.
However within static methods and different class
should be called using the fully qualified name.
 E. g. ObjectName.variable

23
Instance Variables(cont’d)
 Access modifiers can be given for instance variables.
 Instance variables have default values. For numbers
the default value is 0, for Booleans it is false and for
object references it is null.
 Values can be assigned during the declaration or
within the constructor.

24
Example1
public class Employee{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class
only. private double salary;
// The name variable is assigned a value.
public void setName(String empName){
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal){
salary = empSal;
}
// This method prints the employee details.
public void printEmp(){
System.out.println("name :"+
name ); System.out.println("salary :" +
25
salary);
Example1(cont’d)
public static void main(String args[])
{ Employee empOne = new
Employee(); Employee empTwo =
new Employee();
empOne.setName("John");
empTwo.setName("Max");
empOne.setSalary(1000);
empTwo.setSalary(2000);
empOne.printEmp();
empTwo.printEmp();
}
}
Output:
name : John
salary :1000.0
name : Max 26
Example2
public class Bank {
int balance;
void setbalance(int bal){
balance=bal;
}
int deposite( int dep)
{ balance=balance +
dep; return balance;
}
int withdraw(int withd)
{ balance=balance -
withd; return balance;
}
}
27
Example2(cont’d)
public class Runbank {
public static void main(String arg[]){
Bank cust1= new
Bank();
cust1.setbalance(1000);
System.out.println("customer 1 balance after withdrawal
"+ cust1.withdraw(300));
System.out.println(" Customer 1 balance after depositing
"+ cust1.deposite(3000));
Bank cust2= new Bank();
cust2.setbalance(5000);
System.out.println(" customer 2 balance after withdrawal
"+ cust2.withdraw(500));
System.out.print(" customer 2 balance after depositing

"+
cust2.deposite(3000)); 28
Example 3: Predict output
public class Foo
{ private boolean
x;
public static void main(String[] args)
{ Foo foo = new Foo();
System.out.println(foo.x);
}
}

29
Class/static variables
 Class variables also known as static variables are
declared with the static keyword in a class, but outside
a method, constructor or a block.
 Every object has its own copy of all the instance
variables of the class. But, there would only be one
copy of each class variable per class, regardless of
how many objects are created from it.
 Static variables are rarely used other than
declared as constants. Constant variables being
change from their initial value. never
 Static variables are created when the program starts and
destroyed when the program stops.
 Default values are same as instance variables.
30
Example1
public class Employee2{
// salary variable is a private static variable
private static double salary;

// DEPARTMENT is a constant
public static String DEPARTMENT = "Development ";

public static void main(String args[]){


salary = 1000;
System.out.println(DEPARTMENT + "average salary:" +
salary);
}
}

31
Example 2
public class Employee3 {
// this instance variable is visible for any child class.
public String name;
public static double initialsalary;
// The name variable is assigned in the constructor.
public Employee3 (String empName){
name = empName;
}
// The salary variable is assigned a
value. public void setSalary(double
empSal){
initialsalary = empSal;
}
// This method prints the employee details.
public void printEmp(){
System.out.println("name : " + name );
System.out.println("initial salary :" +
initialsalary);
} 32
Example2(cont’d)
public class EmployeeTest{
public static void main(String args[]){
Employee3 empOne = new
Employee3(“Ahmed"); empOne.setSalary(1000);
empOne.printEmp();
Employee3 emptwo = new Employee3(“Kedir");
/* here the initial salary for the second employee
emptwo.setSalary(xxx) is not set hence it uses the one
that is set by the first object since only one copy of the
initial salary exist */
emptwo.printEmp();
}
}

33
Example 3: Predict output
class Counter{
int count=0;// what if it is static int count=0;
public void printCounter()
{ count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
c1.printCounter();
Counter c2=new Counter();
c2.printCounter();
Counter c3=new Counter();
c3.printCounter();
}
}

34
Methods
 Method describe behavior of an object.
 A method is a collection of statements that are
group together to perform an operation.
 Java methods are like C/C++ functions. General
case:
[modifier] returnType methodName ( arg1, arg2, … argN)
{
methodBody
}

 Example:

35
Instance and Static Methods
 Methods are defined in a class, invoked using the class object.
 Normally a class member must be accessed only in conjunction with an
object of its class. There will be times when you will want to define a class
member that will be used independently of any object of that class.
 It is possible to create a member that can be used by itself, without
reference to a specific instance. To create such a member, precede its
declaration with the keyword static.
 When a member is declared static, it can be accessed before
any
objects of its class are created, and without reference to any object.
 The most common example of a static member is main( ). main( ) is
declared as static because it must be called before any objects exist.

36
Instance and Static Methods(cont’d)
Class methods Instance Methods
Static methods are declared by using static instance methods are declared without static
keyword. keyword
All objects share the single copy of static All objects have their own copy of instance
method. method.
Static method does not depend on the single Instance method depends on the object for
object because it belongs to a class which it is available.
Static method can be invoked without creating Instance method cannot be invoked without
an object, by using class name. creating an object.
ClassName.method( ); ObjectName.method( );

Static methods cannot call non-static methods. Non-static methods can call static methods
Static methods cannot access non-static Non-static methods can access static variables
variables.
Static methods cannot refer to this or super. Instance methods can refer to this and super

37
Example
 Suppose that the class Foo is defined in (a). Let f be an instance of Foo.
Which of the statements in (b) are correct?
 (a)
public class Foo {
int i;
static String s;
void imethod() {
}
static void
smethod() {
}
}
(b)
System.out.println(f.i);
System.out.println(f.s);
f.imethod();
f.smethod();
System.out.println(Foo.i);
System.out.println(Foo.s);
38
Foo.imethod();
Example 2
public class EmployeeStatic{
private String firstName;
private String lastName;
private static int count = 0; // number of objects in memory
public EmployeeStatic( String first, String last ) {
firstName = first;
lastName = last;
count++;
System.out.println
( "Employee
constructor:" +
firstName +
lastName
+";count= " +
count );
} 39
Example 2(cont’d)
public String getLastName(){
return lastName;
} // end method getLastName
public static int getCount()
{
return count;
}
}

40
Example 2(cont’d)
public class EmployeeStaticTest{
public static void main( String args[] ) {
// show that count is 0 before creating Employees
System.out.println( "Employees before instantiation: " +
EmployeeStatic.getCount());
// create two Employees; count should be 2
EmployeeStatic e1 = new EmployeeStatic( "Susan",
"Baker" ); EmployeeStatic e2 = new EmployeeStatic( "Bob",
"Blue" );

// show that count is 2 after creating two Employees


System.out.println( "\nEmployees after instantiation: " );
System.out.println( "via e1.getCount():" +e1.getCount() );
System.out.println( "via e2.getCount():" + e2.getCount());
System.out.println( "via Employee.getCount():"+
EmployeeStatic.getCount());

41
Example 2(cont’d)
// get names of Employees
System.out.println( "Employee 1: "+ e1.getFirstName()+ " " +
e1.getLastName());
System.out.println( "Employee 2: "+ e2.getFirstName()+ " "
+ e2.getLastName());
} // end main
} // end class EmployeeStaticTest

42
Declaring a method with a
parameter
 A method can require one or more parameters that
represent additional information it needs to perform
its task.
 A method call supplies values—called arguments—for
each of the method’s parameters.
 For example, to make a deposit into a bank account,
a deposit method specifies a parameter that
represents the deposit amount.

43
Example
public class GradeBook2{
public void displayMessage(String courseName){
System.out.print( "Welcome to the grade book for"+ courseName );
}
}
import java.util.*;
public class GradeBookTest2 {
public static void main( String args[] ){
Scanner input = new Scanner( System.in );
GradeBook2 myGradeBook = new GradeBook2();
System.out.print( "enter the course name” );
String nameOfCourse = input.nextLine();
myGradeBook.displayMessage( nameOfCourse )
;
}} 44
Constructors
 Constructor in java is a special type of method that
is used to create or construct instances of the class.
 Called when keyword new is followed by the class
name and parentheses
 Their name is the same as the class name
 It looks like a method, however it is not a method.
Methods have return type but constructors don’t have
any return type(even void).
 Format: public ClassName(para){…}
 A constructor with no parameters is referred to as
a
no-arg constructor. 45
Default Constructor
 A class may be declared without constructors.
 In this case, a no-arg constructor with an empty body
is implicitly declared in the class. This constructor,
called a default constructor, is provided
automatically only if no constructors are explicitly
declared in the class.
 Format: public ClassName(){…}

46
Constructor Example

public class EmployeeConstructor{


// this instance variable is visible for any child
class. public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public EmployeeConstructor (String empName){
name = empName;
}
// The salary variable is assigned a
value. public void setSalary(double
empSal){
salary = empSal;
}
47
Constructor example(cont’d)
// This method prints the employee details.
public void printEmp()
{ System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]){
EmployeeConstructor empOne = new
EmployeeConstructor(“Leta");
empOne.setSalary(1000);
empOne.printEmp();
}
}

48
Example 2
class Account {
// Data Members
private double balance;
//Constructor
public Account(double startingBalance) {
balance = startingBalance;
}
//Adds the passed amount to the balance
public void depos(double amt) {
balance = balance + amt;
}
//Returns the current balance of this account
public double getCurrentBalance( ) {
return balance;
}
}
49
Example2(cont’d)
import java.util.Scanner;
public class AccountTest{
public static void main(String args[])
{ Scanner in = new
Scanner(System.in); Double bal, amt;
Account acct = new Account(200);
System.out.println("Please enter amount of deposit");
amt= in.nextDouble();
acct.depost (amt);
System.out.println("The current balance is: " +
acct.getCurrentBalance());

}
}

50
Exercise
 Which of the following constructors are invalid?
1. public int ClassA(int one) {
...
}
2. public ClassB(int one, int two) {
...
}
3. void ClassC( ) {
...
}

51
Multiple constructors
 A class can have multiple constructors, as long as
their signature (the parameters they take) are not the
same.
 You can define as many constructors as you need.

52
Example
public class CircleConstructor {
public double r; //instance variable
// Constructors
public CircleConstructor(double radius)
{ r = radius;
}
public CircleConstructor()
{ r=1.0;
}
//Methods to return
area public double
area() {
return 3.14 * r * r;
}
} 53
Example(cont’d)
public class CircleConstructorTest{
public static void main(String args[]){
CircleConstructor circleA = new CircleConstructor(20.0);
CircleConstructor circleB = new
CircleConstructor(10.0); CircleConstructor circleC =
new CircleConstructor();
Double ca = circleA.area();
System.out.println(ca);
Double cb = circleB.area();
System.out.println(cb);
Double cc = circleC.area();
System.out.println(cc);
}
}

54
Accessors and mutators
 A class’s private fields can be manipulated only by
methods of that class.
 Classes often provide public methods to allow clients
of the class to set (i.e., assign values to) or get (i.e.,
obtain the values of) private instance variables.
 Set methods are also commonly called mutator
methods, because they typically change a value. Get
methods are also commonly called accessor
methods or query methods

55
Example
class Person{
private String fname;
private String mname;
private String lname;
private String addr;
public Person(String

firstname, String
middlename, String

lastname,
String address){// constructor
fname=firstname;
mname=middlename;
lname=lastname;
addr=address;
}
public String getFname(){ // accessor for fname
return fname;
} 56
Example(cont’d)
public String getLname(){ // acccessor for Lname
return lname;
}
public String getAddress(){ // accessor for Address
return addr;
}
public void setAddress(String address){ //mutator for
address
addr=address;
}
public void setLname(String lastname){ //mutator for Last name
lname=lastname;
}
}

57
Example(cont’d)
public class PersonExample{
public static void main(String args[]){
Person dani=new Person("Daniel","Abebe", “Kebede", “Adama");
System .out.println(dani.getFname()+" "+dani.getMname()+"
"+dani.getLname()+ " "+dani.getAddress() );
dani.setAddress("Addis Ababa"); //to change Adama to Addis
Ababa
though address is private
dani.setLname(“Kebede");//to change last name from
Kebede to Leta although private
System .out.println(dani.getFname()+" "+dani.getMname()+"
"+dani.getLname()+ " "+dani.getAddress() );
}
}

58
Box Example
// Use this to resolve name-space
collisions.
class Box
{ double
width; double
height;
double depth;
// This is the
constructor
for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth; 59
Box Example(cont’d)
class BoxDemo{
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first
box vol =
mybox1.volume();
System.out.println("Vol
ume is " + vol);
// get volume of second
box vol =
mybox2.volume();
System.out.println("Volum 60
The this Keyword
 is used to refer always current object/current instance
of a class
(I) Instance Variable Hiding
 It is illegal in Java to declare two local variables with the same
name inside the same or enclosing scopes.
 when a local variable has the same name as an instance
variable, the local variable hides the instance variable.
 The this keyword can be used to refer current class instance
variable. If there is ambiguity between the instance variables
and parameters, this keyword resolves the problem of
ambiguity.

61
Example
// Use this to resolve name-space collisions.
class Box
{ double
width; double
height;
double depth;
// This is the
constructor
for Box.
Box(double width, double height, double depth)
{ this.width = width;
this.height = height;
this.depth = depth;
}
// compute and return volume
double volume() {
return width * height * depth;
} 62
Example(cont’d)
class BoxDemo{
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first
box vol =
mybox1.volume();
System.out.println("Vol
ume is " + vol);
// get volume of second
box vol =
mybox2.volume();
System.out.println("Volum 63
The this Keyword(cont’d)
 (II) to invoke current class method

64
The this Keyword(cont’d)
 (III) To call another overloaded Constructor
 “this” keyword can be used inside the constructor to
call another overloaded constructor in the same Class.
 Example
class JBT {
JBT() {
this("JBT");
System.out.
println("Insi
de
Constructor
without
parameter");
}
JBT(String str)
{
System.out.pri
ntln("Inside
Constructor 65
Example: predict output
public class Officer{
public Officer(){
this("Second");
System.out.println("I am First");
}
public Officer(String name){
System.out.println("Officer
name is " + name);
}
public Officer(int salary){
this();
System.out.println("Officer
salary is Rs." + salary);
}
public static void main(String
args[]){ 66
Exercise
 Define a class product with members(name, price, qty &
calcCost(),calcTax())
 Input values
 Using constructor
 Using input from keyboard(Scanner/JOptionPane)
 What if for N-products

 Define four static methods of


simple calculator(Arithemetic)
 Input values
 Using constructor
 Using input from keyboard(Scanner/JOptionPane)

67
3.6 Packages
• Packages in Java are a way of grouping similar types of
classes / interfaces together.(acts as a container for group
of related classes).
• It is a great way to achieve reusability.
• We can simply import a class providing the required
functionality from an existing package and use it in our
program.
• it avoids name conflicts and controls access of class, interface and
enumeration etc
• It is easier to locate the related classes
• The concept of package can be considered as means to achieve data
encapsulation.
• consists of a lot of classes but only few needs to be exposed as most
of them are required internally. Thus, we can hide the classes and
prevent programs or other packages from accessing classes which
are meant for internal usage only.68
Cont…
 The Packages are categorized as :

 Built-in packages ( standard packages which come as a


part of Java Runtime Environment )
 These packages consists of a large number of classes which are a
part of Java API
 Accessing classes in a package: Eg:-
1 ) import java.util.Random; // import the Random class from util
package

2 ) import java.util.*; // import all the class from util package

 User-defined packages ( packages defined by


programmers to bundle group of related classes )
 Java is a friendly language and permits to create our own packages and use in
programming.
 We know packages avoid name collision problems.

 Creating packages are indispensable in project development where number


of developers are involved doing different modules and tasks.
69
Built-in packages
 Examples:
Package Name Description
Contains language support classes ( for
e.g classes which defines primitive
java.lang
data types, math operations, etc.) .
This package is automatically
imported.
Contains classes for supporting input /
java.io
output operations.
Contains utility classes which
implement data structures like Linked
java.util
List, Hash Table, Dictionary, etc and
support for Date / Time operations.

java.applet Contains classes for creating Applets.


Contains classes for implementing the
java.awt components of graphical user interface
( like buttons, menus, etc. ).
Contains classes for supporting
java.net
networking operations.
70
User defined packages
 Creating a package in java is quite easy.
 Simply include a package command followed by
name of the package as the first statement in java
source file.
 package RelationEg;

 However, because of new editors we can simply


create using GUI wizard
 R->click on ur project
 New java-package
 Then you can create many-related classes in it

71
package REL1;
public class Comp1 {
public int getMax(int x, int y)
{ if ( x > y ) {
return x;
}
else {
return y;
}
}
}

72
package packageeg;
import REL1.Comp1;
public class EgComp {
public static void main(String args[]) {
int val1 = 7, val2 = 9;
Comp1 comp = new Comp1();
int max = comp.getMax(val1, val2); // get the max value
System.out.println("Maximum value is " + max);
}
}

73
Questions
 Can we make a class private? If no which specific
access modifiers can be used with class.
 If we define class with protected access modifier can
we create public method?
 Double vs. double
 Is an array an object or a primitive type value?

74
SWEG2031

Object Oriented Programming


COMPUTER ENGINEERING
AASTU
December, 2021
Chapter 4
Inheritance

2
Objectives
 To encapsulate data fields to make classes easy to
maintain
 To discuss the basic concept of inheritance
 To introduce the notions of abstract methods,
abstract
classes, and interfaces.
 To introduce issues that arise with subclasses
protected
- visibility, use of the super() constructor
 To discuss the notion of multiple inheritance
and Java’s approach to it

3
Content
 Inheritance
 Method overloading and overriding
 Abstract classes and Interfaces

4
Fundamental OOP Concepts
 Encapsulation is one of the fundamental OOP concepts.
The other two are inheritance and polymorphism.
 Encapsulation is combining data and behavior in one
package and hiding the implementation details. It is the
technique of making the fields in a class private and
providing access to the fields via public methods.
 Encapsulation is also referred to as data hiding.
 Benefit: the ability to modify our implemented code
without breaking the code of others who use our code.

5
OOP Concepts(cont’d)
 In OO systems, the class is the basic unit of encapsulation.
 For example, you can create a Circle object and find the area
of the circle without knowing how the area is computed.
 Benefits of Encapsulation
 A class can have total control over what is stored in its fields.
 The users of a class do not know how the class stores its data.
 The fields of a class can be made read-only or write-only.

6
Encapsulation(Example)
public class EncapTest{
private String name;
private String
idNum; private int
age;
public int getAge(){
return age;
}
publicString getName(){
return name;
}
publicString getIdNum(){
return idNum;
}

7
Example(cont’d)
publicvoid setAge(int newAge){
age = newAge;
}
publicvoid setName(String newName){
name = newName;
}
public void setIdNum(String newId){
idNum = newId;
}
}

8
Example(cont’d)
public class RunEncap{
public static void main(String args[]){
EncapTest encap =new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : "+ encap.getName()+"
Age : "+ encap.getAge());
}
}

 Output
Name: James Age:20

9
Inheritance
 Inheritance can be defined as the process where one object
acquires the properties of another.
 It allows you to derive new classes from existing classes.
 Allows reusing software.
 E.g.
 Suppose you want to design the classes to model geometric objects
such as circles and rectangles.
 Geometric objects have many common properties and behaviors: can
be drawn in a certain color, filled or unfilled. Thus a general class
GeometricObject can be used to model all geometric objects.

 To avoid redundancy and make the system easy


to comprehend and easy to maintain use inheritance.

10
Inheritance(cont’d)

The GeometricObject class is the superclass for Circle and Rectangle

11
Inheritance(cont’d)
 One of the main uses of inheritance is to model
hierarchical
structures that exist in the world.
 Example: Consider people at AASTU. Broadly speaking, they fall
into two categories: employees and students.
 There are some features that both employees and students have in
common - whether a person is an employee or a student, he or she
has a name, address, date of birth, etc.
 There are also some features that are unique to each kind of person
e.g. an employee has a pay rate, but a student does not; a
student has a GPA, but an employee does not, etc.

12
Inheritance(cont’d)

We can represent this hierarchical structure this


way

13
Inheritance(cont’d)
 With this structure, the classes Employee and Student inherit all
the features of the class Person.
 In addition, each of the classes Employee and Student can have
features of its own not shared with the other classes.
 To inherit a class, you simply incorporate the definition of one
class into another by using the extends keyword.
 For example, we could declare classes Person, Employee, and
Student as follows:
class Person {
...
}
class Employee extends Person {
...
}
class Student extends Person {
...
} 14
Inheritance(cont’d)
 public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
 Now, based on the above example, in Object Oriented terms the
following are true:
 Animal is the superclass of Mammal class.
 Animal is the superclass of Reptile class.
 Mammal and Reptile are subclasses of Animal class.
 Dog is the subclass of both Mammal and Animal classes
 A subclass and its superclass must have the is-a relationship
 Now, if we consider the IS-A relationship, we can say:
 Mammal IS-A Animal
 Reptile IS-A Animal
 Dog IS-A Mammal
 Hence : Dog IS-A Animal as well 15
Inheritance(cont’d)
 Basic terminology: If a class B inherits from a class A:
 We say that B extends A or B is a subclass of A - So we say
Employee extends Person, or Employee is a subclass of Person.
 We say that A is the base class of B or the superclass of B - So we
say Person is the base class of Employee, or the superclass of
Employee.
 A key aspect of inheritance is that a subclass inherits all the
features of its base class except for the private properties of
the superclass.
 A subclass is not a subset of its super-class. In fact, a subclass
usually contains more information and methods than its
superclass.

16
Inheritance(cont’d)
 Consider the following example of a class hierarchy for
bank accounts.

 Observe the following:


 The classes SavingsAccount and CheckingAccount
inherit the features of BankAccount
 a) Since a BankAccount has an owner and a balance, so
does a SavingsAccount or a CheckingAccount.
 b) Since a BankAccount has methods deposit(),
reportBalance(), and getAccountNumber(), so does a SavingsAccount
or a CheckingAccount.

17
Inheritance(cont’d)
 Savings account adds features that an ordinary BankAccount
does not have - e.g. payInterest() and setInterestRate().
 CheckingAccount overrides the withdraw() method of
BankAccount.
 a) In the special case where the checking account balance is
insufficient for the withdrawal, but the customer has a savings
account with enough money in it, the withdrawal is made from
savings instead.
 b) In all other cases, the inherited behavior is used by invoking
super.withdraw(amount).

18
Inheritance(cont’d)
 In designing a class hierarchy, methods should be placed at
the appropriate level. For example, in the BankAccount
Example:
 deposit(), reportBalance(), and getAccountNumber() are defined in
the base class BankAccount, and so are inherited by the two
subclasses.
 If they were defined in the subclasses, we would have to repeat
the code twice - extra work and an invitation to inconsistency.
 On the other hand, payInterest() and setInterestRate() are defined
in SavingsAccount, because they are not relevant for
CheckingAccounts.
 withdraw() is defined in BankAccount and overridden in
CheckingAccount. Why is this better than simply defining separate
versions in CheckingAccount and SavingsAcccount?

19
Types of Inheritance
 On the basis of class, there can be three types of inheritance in
java: single, multilevel and hierarchical.
 In java programming, multiple and hybrid
inheritance is supported through interface only.

20
Types of Inheritance(cont’d)

21
Types of Inheritance(cont’d)

22
Example: Single
// A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void
showij()
{
System.
out.printl
n("i and
j: " + i +
" " + j);
}
}
// Create a subclass by extending class
A. class B extends A {
int k;
void showk() 23
Example(cont’d)
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new
A(); B subOb = new
B();
// The superclass
may be used by
itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb:
"); superOb.showij();
System.out.println();

24
Example(cont’d)
/* The subclass has access to all public members
of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb:
"); subOb.showij();
subOb.showk();
System.out.println();
System.out.println("
Sum of i, j and k in
subOb:");
subOb.sum();
}
}

25
Example(cont’d)
The output from this program is shown here:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24

26
Exercise
 If you have identified the following three classes: Taxi,
Truck, & Automobile, how do you design the classes
using inheritance concept?

27
Method overloading
 Methods of the same name can be declared in the same class,
as long as they have different sets of parameters. This is called
method overloading.
 Method overloading is commonly used to create several
methods with the same name that perform the same or similar
tasks, but on different types or different numbers of arguments.
 Method calls cannot be distinguished by return type if they have
the same number and type of parameters.
 E.g. If we define method: public int square(int no);
It is not allowed to define another method like this:
public double square(int no);

28
Example
public class MethodOverload{
// test overloaded square methods
public void testOverloadedMethods(){
System.out.printf( "Square of integer 7 is " +square( 7 ) );
System.out.printf( "Square of double 7.5 is" + square( 7.5 ) );
}
public int square( int intValue ){
System.out.printf( "Called square with int argument:" +intValue );
return intValue * intValue;
}
public double square( double doubleValue )
{ System.out.printf( "\nCalled square with double
argument:"
+doubleValue );
return doubleValue * doubleValue;
}
}

29
Example(cont’d)
public class
MethodOverloadTest{ public static
void main( String args[] ){
MethodOverload methodOverload = new MethodOverload();
methodOverload.testOverloadedMethods();
}
}

30
Method overriding
 Overriding means to provide a new implementation for
a
method in the subclass.
 To override a method, the method must be defined in the
subclass using the same signature and the same return type
 Benefit of overriding is ability to define a behavior that's
specific to the subclass type which means a subclass can
implement a parent class method based on its requirement.

31
Example1
class Animal{
public void move(){
System.out.println("Animals can move");
}
}

class Dog extends


Animal{ public void
move(){
System.out.println("Dogs
can walk and run");
}
}

32
Example1(cont’d)
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
}
}

Program Output
Animals can move
Dogs can walk and run
33
Example 2
class Animal2{
public void move(){
System.out.println("Animals can move");
}
}
class Dog2 extends
Animal2{ public void
move(){
System.out.println("Dogs
can walk and run");
}

public void bark()


{ System.out.println("Dogs can
bark"); 34
Example2(cont’d)
public class TestDog2{
public static void main(String args[]){
Animal2 a =new Animal2();// Animal reference and object
Animal2 b =new Dog2();// Animal reference but Dog
object a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
b.bark();
}
}
 Program output:
TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
^
This program will throw a compile time error since b's reference
type Animal doesn't have a method by the name of bark 35
Rules for method overriding
 The argument list should be exactly the same as that of
overridden method.
the
 The return type should be the same
 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 overriding method in the subclass cannot be
either private or protected.
 Instance methods can be overridden only if they are inherited by
the
subclass.
 A method declared static cannot be overridden.
 A subclass within the same package as the instance's superclass can
override any superclass method that is not declared private
 A subclass in a different package can only override methods
declared public or protected. 36
The super keyword
 It can be used in two ways:
 (I) To call a superclass constructor.
 Each subclass constructor must implicitly or explicitly call
its superclass constructor
 Syntax: super(), or super(parameters);
 statement super() or super(arguments) must appear in the first
line of the subclass; this is the only way to explicitly invoke a
superclass constructor.
 Note: Unlike properties and methods, the constructors of a
superclass are not inherited in the subclass. They can only be
invoked from the constructors of the subclasses, using the
keyword super

37
The super keyword(cont’d)
If a class is designed to be extended, it is better to provide a no-arg
constructor to avoid programming errors.
Example:
class Fruit{
public Fruit(String name) {
System.out.println("Fruit's constructor is invoked");
}
}
public class Apple extends Fruit {
}
Since Apple is a subclass of Fruit, Apple’s default constructor automatically
invokes Fruit’s no-arg constructor. However, Fruit does not have a no-arg
constructor, because Fruit has an explicit constructor defined. Therefore,
the program cannot be compiled.
38
The super keyword(cont’d)
 (II) To call a superclass method, when invoking a superclass version
of an overridden method.
 Syntax: super.method(parameters);

39
The super keyword(cont’d)
 Example
class Animal3{
public void move(){
System.out.println("Animals can move");
}
}
class Dog3 extends Animal3{
public void move(){
super.move();// invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog3{
public static void main(String args[]){
Animal3 b =new Dog3();// Animal reference but Dog object
b.move();//Runs the method in Dog class
}
}
 program Output
Animals can move
40
Dogs can walk and run
Exercise 1
What will be an output of the following program?
public class Test{
public static void main(String[] args) {
A a = new A(3);
}
}
class A extends B {
public A(int t) {
System.out.println("A's constructor is
invoked");
}
}
class B {
public B() {
System.out.println("B's constructor is
invoked");
}
}
Output: B's constructor is invoked
A's constructor is invoked 41
Exercise 2
1. Identify error in the following program
class A {
public A(int x) {
System.out.println(“A’s Constructor”);
}
}
class B extends A {
public B() {
System.out.println(“B’s Constructor”);
}
}
public class C {
public static void main(String[] args) {
B b = new B();
}
}
Error:
Can’t find constructor A()
42
Exercise 3
class Room{ class Test{
int l,w; public static void main(String [] args){
Room(int x, int y){ BedRoom room1=new BedRoom(14,12,10);
l=x; System.out.println("Area1="+room1.area());
w=y;
} System.out.println("Volume1="+room1.volum
int area(){ e());
return (l*w); } }
}
}
class BedRoom extends Room{ Output
int h;
Areaa1=168
BedRoom(int x, int y, int z){
super(x,y); Volume1=1680
h=z;
}
int volume()
{ return(l*h*
w);
}
}
43
Abstract Class
 When we define a superclass, we often do not need
to create any instances of the superclass. An abstract
class is one that cannot be instantiated.
 An abstract class must include the keyword abstract
in its definition.
 An abstract class has an incomplete definition
because the class includes the abstract method that
does not have a method body.
 E.g abstract class AbstractClass{
}

44
An abstract method
 An abstract method is a method with the keyword
abstract, and it ends with a semicolon instead of a
method body. E.g abstract abMethod();
 If you want a class to contain a particular method but you
want the actual implementation of that method to be
determined by child classes, you can declare the method
in the parent class as abstract.
 An abstract method consists of a method signature, but no
method body.
 A class is abstract if the class contains an abstract
method or does not provide an implementation of an
inherited abstract method.

45
Example
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract
classes void callmetoo() {
System.out.println("This is a concrete method.");
}
}

class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}

46
Example(cont’d)
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
Output
B’s
implementation of
callme
This is concrete
method

47
Which of the following class definition is valid?
public class abstract
Ck{ String s;
abstract void name(){
this.s
=s;
return s;
}

public abstract class Ck{


abstract String name(String s);
}

public class Ck{


abstract void name(String s);
}

48
Interfaces
 Using interface, you can specify what a class must do,
but not how it does it.
 Once an interface has been defined, one or more
classes can implement that interface.
 An interface is not a class. A class describes the
attributes and behaviors of an object. An interface
contains behaviors that a class implements.
 An interface is similar to a class in the following ways:
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the
name of the interface matching the name of the file.
 The bytecode of an interface appears in a .class file.

49
Interfaces(cont’d)
 interface is different from a class in several ways:
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields
that can appear in an interface must be declared as static.
 An interface is not extended by a class; it is implemented by
a class.

50
Defining an Interface
 general form of an interface:
access interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations
}
 access is either public or not used(default)
 Variables can be declared inside of interface declarations. They
are implicitly final and static, meaning they cannot be changed
by the implementing class.
 example of an interface definition:
interface Callback {
void callback(int param);
}
51
Implementing Interfaces
 To implement an interface, include the implements
clause in a class definition, and then create the
methods defined by the interface.
 The general form:
access class classname [extends superclass]
[implements interface [,interface...]] {
// class-body
}

 If a class implements more than one interface,


the interfaces are separated with a comma.

52
Example
interface AnimalInterface{
public void eat();//abstract methods
public void travel();//abstract methods
}

// class implementing the Animal Interface


public class MammalInt implements
AnimalInterface{ public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
}
53
Example(cont’d
public class InterfaceDemo{
public static void main(String args[])
{ MammalInt m = new
MammalInt(); m.eat();
m.travel();
}
}

Output: Mammal eats


Mammal travels

54
Inheritance versus Interface
 They are similar because they are both used to model
an IS-A relationship.
 We use the Java interface to share common behavior
(defined by its abstract methods) among the instances
of unrelated classes.
 We use inheritance, on the other hand, to share
common code (including both data members and
methods) among the instances of related classes.
 Use the Java interface to share common behavior.
Use the inheritance to share common code

55
Abstract class Vs. Interface
Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can have static methods, main Interface can't have static methods,
method and constructor. main method or constructor.

5) Abstract class can provide Interface can't provide the implementation of


the implementation of interface. abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

56
Multiple Inheritance
 Multiple inheritance - a class can inherit properties of more
than
one parent class.
 Why java doesn’t support multiple inheritance?
 To avoid ambiguity

 Multiple inheritance is supported in interface.

57
Example
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{
public static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}

58
Example: Multiple inheritance
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

59
Questions
 How we prevent classes from being extended?
 Why java doesn’t “support” multiple inheritance? If
multiple inheritance is required how do we
implement?
 What is dynamic binding?

60
Object Oriented Programming

Computer Engineering Department


AASTU
November, 2021
Chapter 5
Polymorphism

2
Polymorphism
 Polymorphism is Greek word meaning “many
a forms”.
 Polymorphism enables us to “program in the general”
rather than “program in the specific.”
 Example: Suppose we create a program that
simulates the movement of several types of animals
for a biological study.
 Classes Fish, Frog and Bird represent the three types of
animals under investigation.
 Imagine that each of these classes extends superclass
Animal, which contains a method move and maintains an
animal’s current location as x-y coordinates.

3
Polymorphism(cont’d)
 To simulate the animals’ movements, the program sends each
object the same message once per second.
 However, each specific type of Animal responds to a move
message in a unique way
 a Fish might swim three feet, a Frog might jump five feet and a
Bird might fly ten feet.
 The program issues the same message (i.e., move ) to each
animal object generically, but each object knows how to
modify its x-y coordinates appropriately for its specific type
of movement.

 The same message (in this case, move ) sent to a


variety of objects has “many forms” of results—
hence the term polymorphism.

4
Polymorphism(cont’d)
 E.g. 2 One person present in different behaviors:
 Suppose if you are in class room that time you behave like a
student, when you are in market at that time you behave like a
customer, when you at your home at that time you behave like
a son or daughter.

 The most common use of polymorphism in OOP occurs


when a parent class reference is used to refer to a child
class object.
 The following two output statements will produce different
results, depending on whether p is a Dog or a Cat:
Pet p;
p = new Dog( );
System.out.println(p.speak( ));
p = new Cat( ); 5
Example
class Pet {
private String name;
public String getName( ) {
return name;
}
public void
setName(String petName)
{
name = petName;
}
public String speak( ) {
return "I'm your
cuddly little pet.";
}
}
class Cat extends Pet
{ public String speak( )
{ 6
Example(cont’d)
class Dog extends Pet
{ public String fetch( )
{
return "Yes, master.
Fetch I will.";
}
}
==================
=============
public class RunPetDog{
public static void main(String args[]){
Pet p;
p = new Dog( );
System.out.println(p.speak( ));
p = new Cat( );
System.out.println(p.speak( )); 7
}
Example(cont’d)
 Output
I’m Your cuddly little pet
Don’t give me orders
I speak only when I want

8
Object Oriented Programming

Computer Engineering Department


AASTU
November, 2021
Chapter 6
Exception Handling

2
Objectives
 To get an of exceptions and exception
overview handling
 To explore the advantages of using
handling
exception
 To declare exceptions in a method header
 To throw exceptions in a method
 To write a try-catch block to handle exceptions
 To explain how an exception is propagated
 To use the finally clause in a try-catch block

3
Introduction
 An exception is an object that represents an error or a condition
that prevents execution from proceeding normally.
 An exception can occur for many different reasons:
 A user has entered invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications
or the JVM has run out of memory.
 Handling an exception allows a program to continue executing as
if no problem had been encountered.
 How can you handle the exception so that the program
can continue to run or else terminate gracefully?
 Java exception handling is managed via five keywords:
try, catch, throw, throws, and finally.

4
Example: Divide by Zero without Exception
Handling
import java.util.Scanner;
public class DivideByZeroNoExceptionHandling {
public static int quotient(int numerator,int denominator ){
return numerator / denominator;
}// end method quotient
public static void main( String args[] ){
Scanner scanner =new Scanner( System.in ); // scanner for input
System.out.print("Please enter an integer numerator: ");
int numerator = scanner.nextInt();
System.out.print("Please enter an integer denominator: ");
int denominator = scanner.nextInt();
int result = quotient( numerator, denominator );
System.out.print( numerator + " / " + denominator + " = " +
result );
}
}

Output
Please enter an integer numerator: 100
Please enter an integer denominator: 0
Exception in thread "main"
java.lang.ArithmeticException: / by zero
5
Introduction(cont’d)
 try
 Contain program statements that you want to monitor for exceptions
 catch
 The exception is caught by the catch block.
 The code in the catch block is executed to handle the exception
 throw
 The execution of a throw statement is called throwing an exception
 The throw statement is analogous to a method call, but instead of calling a
method, it calls a catch block.
 throws
 To declare an exception in a method, use the throws keyword
 finally
 Holds code that absolutely must be executed before a method returns
 A finally block of code always executes, whether or not an exception has
occurred.

6
Exception handling overview
 This is the general form of an exception-handling
block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
/
/ 7
Exception Types

8
Exception Types(cont’d)
 The exception classes can be classified into three major types:
system errors, exceptions, and runtime exceptions.
 System errors are thrown by the JVM and represented in the
Error class.
 rarely occur.

Class Possible Reason for Exception


LinkageError A class has some dependency on another class,
but the latter class has changed incompatibly
after the compilation of the former class.

VirtualMachineError The JVM is broken or has run out of


the resources it needs in order to continue
operating.

9
Exception Types(cont’d)
 Exceptions are represented in the Exception class,
which describes errors caused by your program and by
external circumstances.

Class Possible Reason for Exception


ClassNotFoundException Attempt to use a class that does not exist.
IOException Related to input/output operations, such as
invalid input, reading past
the end of a file, and opening a nonexistent
file.

10
Exception Types(cont’d)
Runtime exceptions are represented in the RuntimeException
class, which describes programming errors, such as bad casting,
accessing an out-of-bounds array, and numeric errors.
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.
ClassNotFoundException Class not found.
InstantiationException Attempt to create an object of an abstract class or interface.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.

11
Catching Exceptions(Example)
A method catches an exception using a combination of the try and catch keywords

import java.util.Scanner;
public class QuotientWithException {
public static void main(String[] args)
{ Scanner input = new
Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
try {
if (number2 == 0)
throw new
ArithmeticException("Divis
or cannot be zero");
System.out.println(number1
+ " / " + number2 + " is " +
(number1 / number2));
}
12
catch (ArithmeticException ex)
Example 2
public class CircleWithException {
private double radius;
// Construct a circle with a specified radius
public CircleWithException(double newRadius)
{
setRadius(newRadius);
}
/** Return radius */
public double getRadius() {
return radius;
}

13
Example 2(cont’d)
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException{
if (newRadius >= 0)
radius = newRadius;
else
throw new
IllegalArgumentExc
eption("Radius
cannot be
negative");
}

/** Return the area of this


circle */ public double findArea() {
return radius * radius *
3.14159;
14
Example 2(cont’d)
public class TestCircleWithException
{ public static void main(String[] args)
{
try{
CircleWithException c1 = new CircleWithException(5);
CircleWithException c2 = new CircleWithException(-5);
CircleWithException c3 = new CircleWithException(0);

}
catch(IllegalArgumentException ex){
System.out.println(ex);
}
}
}
Output:
java.lang. IllegalArgumentException :
15
Radius cannot be negative
The throws Keyword
 If a method is capable of causing an exception that it
does not handle, it must specify this behavior so that
callers of the method can guard themselves against
that exception.
 You do this by including a throws clause in the
method’s declaration.
 This is the general form of a method declaration that
includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}

16
Example
class ThrowsDemo {
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Output:
inside throwOne 17
The finally Keyword
 The finally keyword is used to create a block of code
that follows a try block.
 A finally block of code always executes, whether
or not an exception has occurred.

18
Example
public class ExcepTest{
public static void main(String args[]){
int a[]=new int[2];
try{
System.out.println("Access
element three :"+ a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :"+ e);
}
finally{ a
[0]=6;
System.out.println("First element value: "+a[0]);
System.out.println("The finally statement is executed");
}
}
}
This would produce the following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException:3
19
First finally
The element value:6 is executed
statement
Object Oriented Programming

Computer Engineering Department


AASTU
November, 2021
Chapter Seven
Introduction to GUI in Java

2
Objectives
 In this chapter you will learn:
 The design principles of graphical user interfaces (GUIs).
 To create and manipulate buttons, labels, lists, text fields and
panels.
 To use layout managers to arrange GUI components
 To understand the packages containing GUI
components,
event-handlingGUIs
 Tobuild classes
andandhandle
interfaces.
events by user
generated interactions with GUIs
 To handle mouse events and keyboard events.

3
Introduction
 A graphical user interface (GUI) presents a user-
friendly
mechanism for interacting with an application.
 A GUI gives an application a distinctive “look” and “feel”.
 There are different sets of visual components
and containers for user interface design in JAVA:
 AWT (Abstract Window Toolkit) - in package java.awt and
 Swing - in package javax.swing
 JavaFx(not covered within this course)

 When Java was introduced, the GUI classes were bundled


in a library known as the Abstract Windows Toolkit (AWT).

4
AWT vs. Swing
 AWT is fine for developing simple graphical user interfaces, but
not for developing comprehensive GUI projects.
 Besides, AWT is prone to platform-specific bugs.
 The AWT user-interface components were replaced by a more
robust, versatile, and flexible library known as Swing
components.
 Swing components depend less on the target platform and
use less of the native GUI resource. Swing components are
painted directly on canvases using Java code.
 For this reason, Swing components that don’t rely on native GUI
are referred to as lightweight components, and AWT
components are referred to as heavyweight components.

5
AWT vs. Swing (cont’d)
 AWT features include:
 A rich set of user interface components.
 A robust event-handling model.
 Graphics and imaging tools, including shape, color, and font classes.

 Swing features include:


 All the features of AWT.
 100% Pure Java certified versions of the existing
AWT component set (Button, Scrollbar, Label, etc.).
 A rich set of higher-level components (such as tree view, list
box, and tabbed panes).
 Pure Java design, no reliance on peers.
 Pluggable Look and Feel.

6
Java GUI API
 The GUI API contains classes that can be classified into
three groups:
 component classes,
 container classes, and
 helper classes.

 The component classes, such as JButton, JLabel,


and
JTextField, are for creating the user interface.
 The container classes, such as JFrame, JPanel, and
JApplet, are used to contain other components.
 The helper classes, such as Graphics, Color,
Font, FontMetrics, and Dimension, are used to
support GUI components.

7
Java GUI API (cont’d)

8
Frames
 To create a user interface, you need to create either a
frame or an applet to hold the user-interface
components.
 A top-level window (that is, a window that is not
contained inside another window) is called a frame in
Java.
 To create a frame, use the JFrame class
 A Frame has:
 a title bar (containing an icon, a and the
title, minimize/maximize(restore-down)/close
buttons),
 an optional menu bar and
 the content display area.
9
Frame
Example 1
import javax.swing.JFrame;
public class MyFrame {
public static void
main(String[] args) {
// Create a frame
JFrame frame =
new
JFrame("MyFrame"
);
frame.setSize(400,
300); // Set the
frame size
// Center a frame
frame.setLocationRelativeTo(null); //or .setLocation(300,200)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Display the frame
} 10
Frame (cont’d)

JFrame is a top-level container to hold GUI components

11
Frame (cont’d)
 Adding Components to a Frame
 Example 1: Adding button
import javax.swing.JFrame;
import javax.swing.JButton;
public class FrameWithButton {
public static void main(String[]
args) {
JFrame frame = new
JFrame("MyFrame");
// Add a button into the frame
JButton jbtOK = new JButton("OK");
frame.add(jbtOK);
frame.setSize(400, 300);
frame.setLocation(360,360);
frame.setDefaultCloseOperation(JF
rame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
12
Frame (cont’d)
 Example 2: Adding Lablel
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FrameWithLabel {
public static void
main(String[] args) {
JFrame frame = new
JFrame("MyFrame");
// Add a lable into the
frame
JLabel jLblName = new JLabel(“First Name");
frame.add(jLblName);
frame.setSize(400, 300);
frame.setLocation(360,360);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
13
}
Layout Managers
 Java’s layout managers provide a level of abstraction that
automatically maps your user interface on all window
systems.
 The Java GUI components are placed in containers, where
they are arranged by the container’s layout manager.
 Layout managers are set in containers using the
setLayout(aLayoutManager) method.
 This section introduces three basic layout
managers:
FlowLayout, GridLayout, and BorderLayout.

14
FlowLayout
 Flowlayout
 Is the simplest layout manager.
 The components are arranged in the container from left to right in the
order in which they were added. When one row is filled, a new row is
started.
 You can specify the way the components are aligned by using one of
three constants:
 FlowLayout.RIGHT,
 FlowLayout.CENTER, or
 FlowLayout.LEFT.
 You can also specify the gap between components in pixels.

15
FlowLayout (cont’d)
Example
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.FlowLayout;
public class ShowFlowLayout{
public static void main(String args[]){
JFrame frame = new JFrame();
//Set FlowLayout, aligned left with
horizontal gap 10
//and vertical gap 20 between
components
FlowLayout x = new FlowLayout(FlowLayout.LEFT, 10, 20);
frame.setLayout(x);
//Add labels and text fields to the frame
JLabel jlblFN = new JLabel("First Name");
JTextField jtxtFN = new JTextField(8);
JLabel jlblMI = new JLabel("MI");
JTextField jtxtMI = new JTextField(1);
JLabel jlblLN = new JLabel("Last Name");
JTextField jtxtLN = new JTextField(8);
16
FlowLayout (cont’d)
frame.add(jlblFN);
frame.add(jtxtFN);
frame.add(jlblMI);
frame.add(jtxtMI);
frame.add(jlblLN);
frame.add(jtxtLN);

frame.setTitle("ShowFlowLayout");
frame.setSize(220, 150);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

17
FlowLayout (cont’d)
EXAMPLE
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.FlowLayout;

public class ShowFlowLayout


extends JFrame{
public ShowFlowLayout() {
// Set FlowLayout, aligned
left with horizontal gap 10
// and vertical gap 20 between components
setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20) );
// Add labels and text fields to the frame
add(new JLabel("First Name"));
add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(1));
add(new JLabel("Last Name"));
add(new JTextField(8));
} 18
FlowLayout (cont’d)
/** Main method */
public static void main(String[] args) {
ShowFlowLayout frame = new
ShowFlowLayout();
frame.setTitle("ShowFlowLayout");
frame.setSize(200, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output

19
GridLayout
 Arranges components in a grid (matrix) formation.
 The components are placed in the grid from left to
right, starting with the first row, then the second, and
so on, in the order in which they are added.
 If both the number of rows and the number of columns
are nonzero, the number of rows is the dominating
parameter.
 All components are given equal size in the container
of GridLayout.

20
GridLayout (cont’d)
EXAMPLE
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.GridLayout;

public class ShowGridLayout


extends JFrame {
public ShowGridLayout() {
// Set GridLayout, 3 rows, 2
columns, and gaps 5
between
// components horizontally and vertically
setLayout(new GridLayout(3, 2, 5, 5));

// Add labels and text fields to the frame


add(new JLabel("First Name"));
add(new JTextField(8));
add(new JLabel("MI"));
add(new JTextField(8));
add(new JLabel("Last Name")); 21
GridLayout (cont’d)
/** Main method */
public static void main(String[] args)
{ ShowGridLayout frame = new
ShowGridLayout();
frame.setTitle("ShowGridLayout");
frame.setSize(200, 125);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Output

22
BorderLayout
 Divides a container into five areas: East, South,
West,
North, and Center.
 Components are added to a BorderLayout using
by add(Component, index), where index is a
constant
 BorderLayout.EAST,
 BorderLayout.SOUTH,
 BorderLayout.WEST,
 BorderLayout.NORTH, or
 BorderLayout.CENTER.

23
BorderLayout
 EXAMPLE
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class ShowBorderLayout extends JFrame {
public ShowBorderLayout() {
// Set BorderLayout with horizontal gap 5 and
vertical gap 10
setLayout( new BorderLayout(5, 10));

// Add buttons to the frame


add(new JButton("East"), BorderLayout.EAST);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("North"), BorderLayout.NORTH);
add(new JButton("Center"), BorderLayout.CENTER);
}

24
BorderLayout (cont’d)
/** Main method */
public static void main(String[] args) {
ShowBorderLayout frame = new ShowBorderLayout();
frame.setTitle("ShowBorderLayout");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE);
frame.setVisible(true);
}
}
Output

25
Panels
 With Java GUI programming, you can divide a window
into panels. Panels act as subcontainers to group
user-interface components.
 You add the buttons in one panel, then add the panel
into the frame.
 You can use new JPanel() to create a panel with
default
a FlowLayout manager or
Panel(LayoutManager) to create a new panel
specified layout manager. with
the

26
Panels (cont’d)
 Example 1
import javax.swing.*; import
java.awt.GridLayout;
import
java.awt.BorderLayout;
public class SimplePanelExample extends JFrame {
public SimplePanelExample() {
// Create panel p1 to hold label and text field; and
set GridLayout
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 2));
//Add label and text field to the panel
p1.add(new JLabel("First Name"));
p1.add(new JTextField(8));
// Create panel p2 to hold p1 and some other component
JPanel p2 = new JPanel(new BorderLayout());
p2.add(p1, BorderLayout.NORTH);
p2.add (new JButton("Button in Panel 2"),
BorderLayout.SOUTH); 27
Panels (cont’d)
/** Main method */
public static void main(String[] args) {
SimplePanelExample frame = new SimplePanelExample();
frame.setTitle("Panel With Components");
frame.setSize(350, 100);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS
E);
frame.setVisible(true);
}
}

Output:

28
Panels (cont’d)
 Example 2
import java.awt.GridLayout;
import javax.swing.*;
import
java.awt.BorderLayout;

public class TestPanels


extends JFrame {
public TestPanels() {
// Create panel p1 for
the buttons and set
GridLayout

JPanel p1 = new JPanel();

p1.setLayout(new GridLayout(4, 3));


//Add buttons to the panel
for (int i = 1; i <= 9; i++) {
p1.add(new JButton("" + i));
}
29
Panels (cont’d)
p1.add(new JButton("" + 0));
p1.add(new JButton("Start"));
p1.add(new JButton("Stop"));

// Create panel p2 to hold a text field and p1


JPanel p2 = new JPanel(new BorderLayout());
p2.add (new JTextField("Time to be displayed here"),
BorderLayout.NORTH);
p2.add(p1, BorderLayout.CENTER);

// add contents into the frame


add(p2, BorderLayout.EAST);
add(new JButton("Food to be placed here"),
BorderLayout.CENTER);
}

30
Panels (cont’d)
/** Main method */
public static void main(String[] args) {
TestPanels frame = new TestPanels();
frame.setTitle("The Front View of a Microwave Oven");
frame.setSize(400, 250);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

 Output

31
The Font Class
 You can create a font using the java.awt.Font class and set
fonts for the components using the setFont method in the
Component class.
 The constructor for Font is:
 Font(String name, int style, int size);
 You can choose a font name from SansSerif, Serif,
Monospaced, Dialog, or DialogInput,
 Choose style from Font.PLAIN (0), Font.BOLD (1),
a (2), and Font.BOLD Font.ITALIC (3), and
Font.ITALIC
specify a font size of any positive integer.

32
Font (cont’d)
 Example:
Font font1 = new Font("SansSerif", Font.BOLD, 16);
Font font2 = new Font("Serif", Font.BOLD + Font.ITALIC, 12);
JButton jbtOK = new JButton("OK");
jbtOK.setFont(font1);

33
The Color Class
 You can set colors for GUI components by using
the
java.awt.Color class.
 Colors are made of red, green, and blue components, each
represented by an int value that describes its intensity,
ranging from 0 (darkest shade) to 255 (lightest shade).
 You can create a color using the following constructor:
 public Color(int r, int g, int b);
 Example:
 Color color = new Color(128, 100, 100);
 You can use the setBackground(Color c) and
setForeground(Color c) methods to set a component’s
background and foreground colors.
34
The Color Class (cont’d)
 Example
 JButton jbtOK = new JButton("OK");
 jbtOK.setBackground(color);
 jbtOK.setForeground(new Color(100, 1, 1));
 Alternatively, you can use one of the 13 standard
colors
(BLACK,
LIGHT_GRAY, BLUE,MAGENTA,
CYAN, DARK_GRAY,
ORANGE, GRAY,
PINK, RED,
GREEN,
WHITE, and YELLOW) defined as constants in
java.awt.Color.
 The following code, for instance, sets the foreground
color of a button to red:
 jbtOK.setForeground(Color.RED);

35
The Color Class (cont’d)
 Example
import java.awt.GridLayout;
import java.awt.Color;
import javax.swing.*;
public class ColorExample extends JFrame{
public ColorExample(){
JFrame jf = new JFrame("Color Frame");
setLayout(new GridLayout(1,2));
Color color = new Color(128, 100, 100);
JButton bcleft = new JButton("Left Button");
JButton bcright = new JButton("Right Button");
bcleft.setBackground(color);
bcright.setForeground(new Color(250,0, 0));
//bc2.setForeground(Color.RED);
add(bcleft);
add(bcright);
}
36
The Color Class (cont’d)
public static void main(String[] args)
{ ColorExample ce = new
ColorExample(); ce.setSize(300,150);
ce.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ce.setLocationRelativeTo(null);
ce.setVisible(true);
}
}

37
Image Icons
import javax.swing.*;
import java.awt.GridLayout;
public class ImageExample extends JFrame
{ public ImageExample() {
ImageIcon homeIcon = new ImageIcon("src/home.gif");
ImageIcon birdIcon = new ImageIcon("src/bird.gif");
ImageIcon mailIcon = new ImageIcon("src/mail.gif");
setLayout(new GridLayout(1, 3, 5, 5));
add(new JLabel(homeIcon));
add(new JButton(birdIcon));
add(new JLabel(mailIcon));

38
Image Icons (cont’d)

/** Main method */


public static void main(String[] args)
{ ImageExample frame = new
ImageExample();
frame.setTitle("TestImageIcon");
frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

39
Event Handling
 Event and Event Source
 When you run a Java GUI program, the program interacts with
the user, and the events drive its execution.
 An event can be defined as a signal to the program that
something has happened.
 Events are triggered either by external user actions, such as
mouse movements, button clicks, and keystrokes, or by
internal program activities, such as a timer.
 The program can choose to respond to or ignore an event.
 The component that creates an event and fires it is called the
source object or source component.
 For example, a button is the source object for a button-clicking
action event.
 The root class of the event classes is java.util.EventObject.

40
Event Handling (cont’d)

An event is an object of the EventObject class.

The following Table lists external user actions, source objects, and
event types fired
41
Event Handling (cont’d)
 Listeners, Registrations, and Handling Events
 Java uses a delegation-based model for event handling:
 a source object fires an event, and an object
interested in the event handles it. The latter object is called a
listener.
 For an object to be a listener for an event on a source object,
two things are needed:
 The listener object must be an instance of the corresponding
event-listener interface to ensure that the listener has the correct
method for processing the event. The following table lists event
types, the corresponding listener interfaces, and the methods
defined in the listener interfaces.
 The listener object must be registered by the source object.
Registration methods depend on the event type. For ActionEvent,
the method is addActionListener.

42
Example 1
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class HandleEvent extends JFrame{


public HandleEvent() {
// Create two buttons
JButton jbtOK = new JButton("OK");
JButton jbtCancel = new
JButton("Cancel");

// Create a panel to hold buttons


JPanel panel = new JPanel();
panel.add(jbtOK);
panel.add(jbtCancel);

add(panel); // Add panel to the


frame
43
Example 1(cont’d)
// Register listeners
OKListenerClass listener1 = new OKListenerClass();
CancelListenerClass listener2 = new CancelListenerClass();
jbtOK.addActionListener(listener1);
jbtCancel.addActionListener(listener2);
}

public static void main(String[] args)


{ JFrame frame = new
HandleEvent();
frame.setTitle("Handle Event");
frame.setSize(200, 150);
frame.setLocation(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

44
Example 1(cont’d)
class OKListenerClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.out.println("OK button clicked");
}
}

class CancelListenerClass implements ActionListener {


public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Cancel
button clicked");
}
}

45
Example 2
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class TestEvent


extends JFrame {
private JButton clickme = new JButton("ClickMe");
private JButton tests = new JButton("Test");
public TestEvent(){
setLayout(new GridLayout(2, 0, 5, 5));
add(clickme);
add(tests);
TestListenerClass t= new TestListenerClass();
clickme.addActionListener(t);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200,200);
setVisible(true);
}//constructor 46
Example 2(cont’d)
public static void main(String[] args)
{ JFrame frame = new
TestEvent();
frame.setTitle("Handle Event");
frame.setSize(200, 150);
frame.setLocation(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
} //end of main
class TestListenerClass implements ActionListener{
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clickme) {
tests.setText("Clickme button clicked");
} //end of if
} //action performed
} //end of TestListenerClass
} // end of TestEvent class
47
Example 2 Modified
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class MyGUI extends JFrame


implements ActionListener
{ private JButton clickme = new
JButton("ClickMe"); private JButton tests = new
JButton("Test"); public MyGUI() {
// Add clickme to the GUI and
assign it a listener setLayout(new GridLayout(2,
0, 5, 5)); add(clickme);
add(tests);
clickme.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200,200);
setVisible(true);
}
48
Example 2 modified (cont’d)
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clickme) {
tests.setText("Clickme button clicked");
}
} // actionPerformed()

public static void main(String args[]) {


MyGUI gui = new MyGUI();
}
} // MyGUI class

49
Example 3: Add two numbers
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AddNo
extends JFrame {
private JTextField firstno = new JTextField(4);
private JLabel plus = new JLabel("+");
private JTextField secondno = new
JTextField(4);
private JButton equal = new JButton("=");
private JTextField result = new JTextField(4);
private JButton jbclear = new JButton("Clear");
public AddNo() {
setLayout(new
FlowLayout(FlowLayout.CENTER, 5, 5));
add(firstno);
add(plus);
50
Example 3(cont’d)
add(secondno);
add(equal);
add(result);
add(jbclear);

AddListenerClass addlistener = new AddListenerClass();


equal.addActionListener(addlistener);
jbclear.addActionListener(addlistener);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,100);
setLocationRelativeTo(null);
setVisible(true);
}

51
Example 3(cont’d)
public static void main(String args[]) {
AddNo gui = new AddNo();
}
class AddListenerClass implements
ActionListener{

public void actionPerformed(ActionEvent e)


{ if(e.getSource()==equal){
int fno,sno,sum;
try{
fno =
Integer.valueOf(firstno.getText()).intValue(); sno =

Integer.valueOf(secondno.getText()).intValue();
}
catch(NumberFormatException ex)
{ JOptionPane.showMessageDialog(null, "Please Enter
Only Number" );
return;
52
}
Example 3(cont’d)
sum = fno + sno;
result.setText(""+sum);
}
else{
firstno.setText("");
secondno.setText("");
result.setText("");
}
} // actionPerformed()
}
}

53
Example 4
import javax.swing.*; // Packages used
import java.awt.*;
import java.awt.event.*;
public class Converter extends JFrame implements ActionListener{
private JLabel prompt = new JLabel("Distance in miles: ");
private JTextField input = new JTextField(6); private
JTextArea display = new JTextArea(10,20); private
JButton convert = new JButton("Convert!"); public
Converter() {
setLayout(new FlowLayout());
add(prompt);
add(input);
add(convert);
add(display);
display.setLineWrap(true);
display.setEditable(false);
ConverterHandler ch = new ConverterHandler();
convert.addActionListener(ch);
} // Converter()
54
Example 4(cont’d)
public static void main(String args[]) {
Converter f = new Converter();
f.setSize(400, 300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.E
XIT_ON_CLOSE);
} // main()
class ConverterHandler implements
ActionListener{
public void
actionPerformed( ActionEvent e )
{
//CHECK TO ACCEPT ONLY
NUMBERS
double miles;
try{
miles =

Double.value
55
Of(input.get
Example 4(cont’d)

display.setText("");
double km = miles/0.62;
display.append(miles + " miles equals " + km + " kilometers\n");

} // actionPerformed()
}//ConvertHandler
}//Converter

56
Exercise
 Write a java program to create the following GUI.
1

2

57
Exercise
3

58

You might also like