Object Oriented Programming (Mahlet and Mohammed)
Object Oriented Programming (Mahlet and Mohammed)
Mahlet Teklay
Mohammed Abrar
Mahlet Teklay
Mohammed Abrar
Information Technology
January 2024
i
Week Six : Practical ............................................................................................................................. 155
Week Six: Assessments ....................................................................................................................... 157
Week Seven: Session........................................................................................................................... 158
3.2. Instance Fields Constructors and Methods ......................................................................... 158
Week Seven: Practical ......................................................................................................................... 170
Week Seven: Assessments .................................................................................................................. 175
Reference ............................................................................................................................................ 176
Chapter Four: Object Oriented Programming Concepts ................................................................... 178
Week Nine: Session............................................................................................................................. 180
4.1. Inheritance........................................................................................................................... 180
4.2. Encapsulation ...................................................................................................................... 188
Week Nine: Practical ........................................................................................................................... 192
Week Nine : Assesment ...................................................................................................................... 193
Week Ten: Session .............................................................................................................................. 195
4.3. Polymorphism ..................................................................................................................... 195
Week Ten: Practical ............................................................................................................................ 212
Week Ten : Assesment ........................................................................................................................ 217
Reference ............................................................................................................................................ 219
Chapter Five: Exception Handling in Java .......................................................................................... 220
Week Eleven: Session ......................................................................................................................... 222
5.1. Exception Handling in Java ................................................................................................ 222
5.2. Java try and catch block ...................................................................................................... 226
5.3. Java finally block ................................................................................................................ 234
5.4. Why use java finally ........................................................................................................... 235
5.5. Difference between throw and throws in Java .................................................................... 236
5.6. Java Custom Exception ....................................................................................................... 239
Week Eleven: Practical ........................................................................................................................ 241
Week Eleven : Assesment ................................................................................................................... 244
Week Twelve: Session ......................................................................................................................... 245
5.7. Exception Hierarchy ........................................................................................................... 245
5.8. Types of Exception in Java ................................................................................................. 245
5.8.1. Checked exception .......................................................................................................... 247
5.8.2. Unchecked exception ...................................................................................................... 254
Week Twelve: Practical ....................................................................................................................... 261
ii
Week Twelve: Assesment ................................................................................................................... 263
Chapter Six: AWT, Swing and Java Applets ......................................................................................... 268
Week Thirteen: Session ...................................................................................................................... 270
6.1 Introduction ......................................................................................................................... 270
6.2 AWT ................................................................................................................................... 271
Week Thirteen : Practical .................................................................................................................... 304
Week Thirteen : Assesment ................................................................................................................ 308
Week 14: Session ............................................................................................................................... 310
6.3 Swing .................................................................................................................................. 310
Week Fourteen : Practical ................................................................................................................... 315
Week Fourteen : Assesment ............................................................................................................... 318
Week Fifteen: Session ........................................................................................................................ 322
6.4 Applet.................................................................................................................................. 322
Week Fifteen : Practical ...................................................................................................................... 337
Week Fifteen: Assessment ................................................................................................................. 340
Reference ............................................................................................................................................ 343
iii
iv
Course Profile
Department Information Technology
1
Detailed Course Outline
1.3. Overview of Java • Installation of Java IDE 5.1.1 PC, JDK, netbeans
Programs
Interpreting)
2.1. Variable types and • Variable declaration 5.1.2 PC, JDK, netbeans
identifiers
• Datatype defination
3
2.2. Number types, strings,
constants
2.3 Operators and operator • Operators in practice 5.1.1 PC, JDK, netbeans
4 precedence
• Type conversion and 5.1.2
2.4. Type Conversion/ Casting casting in java
5.1.3
5.1.2
2.5. Decision and Repetition • If statement PC, JDK, netbeans
5.1.3
5 Statements • Switch statement
• For loop
2
• While, Do while loop
7 3.4 Instance fields, Construction • Instantiating and using 5.1.3 PC, JDK, netbeans
and methods objects
5.1.2
• Passing and returning
5.1.3
objects
10 4.3. Polymorphism • OOP Principles: and Data 5.1.2 PC, JDK, netbeans
abstraction, and
4.4.Abstract classes and 5.2.1
Polymorphism
Interfaces
5.2.2
11 5.1 Exception Handling in Java • Methods to print 5.1.2 PC, JDK, netbeans
5.2.2
12 5.3 Types of Exceptions • Java Exception Handling 5.2.2 PC, JDK, netbeans
Example
5.4 Errors
3
• Java error handling
13 6.1 Abstract Window Toolkit • Creating Graphical User PC, JDK, netbeans
Interface (GUI) in Java.
(AWT) 5.2.1
like button, label,
Basic ideas 5.2.2
checkbox
General Layout of AWT
• JTextArea class
• JComboBox class
• JTable class
• Restrictions
4
Chapter One : Introduction to Object-Oriented Programming
Lesson Plan
1. Learning objectives
5. Practice contents/Activities/Safety
Active practice; on java input and output, writing (Editing), compiling, interprating.
5
Chapter One : Introduction to Object-Oriented Programming
6. Assessments
9. Review/Reflection
• Review the outcome of the practice, improvement measure and previous reflected
opinions.
6
Chapter One : Introduction to Object-Oriented Programming
There are basically two types of computer programming languages given below:
A. Machine Language
The instructions in binary form, which can be directly understood by the computer (CPU)
without translating them, is called a machine language or machine code. Machine language is
also known as the first generation of programming language. Machine language is the
fundamental language of the computer and the program instructions in this language are in the
binary form (that is 0's and 1's). This language is different for different computers. It is not easy
to learn the machine language.
The only advantage of machine language is that the program of machine language runs very
fast because no translation program is required for the CPU.
➔ Machine Dependent - the internal design of every computer is different from every
other type of computer, machine language also differs from one computer to another.
7
Chapter One : Introduction to Object-Oriented Programming
Hence, after becoming proficient in the machine language of one type of computer, if
a company decides to change to another type, then its programmer will have to learn a
new machine language and would have to rewrite all existing program.
B. Assembly Language
Assembly language is also known as the second generation of programming language. With
assembly language, a programmer writes instructions using symbolic instruction code instead
of binary codes. Symbolic codes are meaningful abbreviations such as SUB is used for
substation operation, MUL for multiply operation and so on. Therefore this language is also
called the low-level symbolic language. The set of program instructions written in assembly
language are also called mnemonic code. Assembly language provides facilities for controlling
the hardware.
Advantages:
➔ Easy to understand and use - due to the use of mnemonic instead of numeric op-
codes and symbolic names for data location instead of numeric addresses, it is much
easier to understand and use in contrast with machine language.
➔ Easier to locate and correct errors - the programmers need not to keep track of
storage location of the data and instruction, fewer errors are made while writing
programs in assembly language and those that are made, are easier to find and correct.
Disadvantages:
8
Chapter One : Introduction to Object-Oriented Programming
Hence like machine language programs, writing assembly language program is also time
consuming and difficult.
Advantages: There are several advantages of high level programming languages. The most
important advantages are:
➔ Easy to learn - the high level languages are very easy to learn than low level
languages.
➔ Easy to write program - in high level language, a new program can easily be written
in a very short time.
➔ Easy to detect and remove errors - the errors in a program can be easily detected
and removed.
➔ Built-in library functions - Each high level language provides a large number of
built-in functions or procedures that can be used to perform specific tasks during
designing of new programs.
9
Chapter One : Introduction to Object-Oriented Programming
➔ Low efficiency - a program written in high level languages has lower efficiency than
one written in a machine/assembly language to do the same job.
➔ Less flexibility - high level languages are less flexible than assembly languages
because they do not normally have instructions or mechanisms to control a computer's
CPU, memory and register.
The word “imperative” comes from the Latin “impero” meaning “I command”. The paradigm
consists of several statements, and after the execution of all of them, the result is stored. It’s
about writing a list of instructions to tell the computer what to do step by step.
10
Chapter One : Introduction to Object-Oriented Programming
In an imperative programming paradigm, the order of the steps is crucial, because a given step
will have different consequences depending on the current values of variables when the step is
executed.
It is one of the oldest programming paradigm. It features close relation to machine architecture.
It is based on Von Neumann architecture. It works by changing the program state through
assignment statements. It performs step by step task by changing state. The main focus is on
how to achieve the goal. The paradigm consist of several statements and after execution of all
the result is stored.
Advantage Disadvantage
Imperative programming is divided into three broad categories: Procedural, OOP and parallel
processing. These paradigms are as follows:
This paradigm emphasizes on procedure in terms of under lying machine model. There is no
difference in between procedural and imperative approach. It has the ability to reuse the code
and it was boon at that time when it was in use because of its reusability.
11
Chapter One : Introduction to Object-Oriented Programming
C++
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int i, fact = 1, num;
6. cout << "Enter any Number: ";
7. cin >> number;
8. for (i = 1; i <= num; i++) {
9. fact = fact * i;
10. }
11. cout << "Factorial of " << num << " is: " << fact << endl;
12. return 0;
13. }
The program is written as a collection of classes and object which are meant for communication.
The smallest and basic entity is object and all kind of computation is performed on the objects
only. More emphasis is on data rather procedure. It can handle almost all kind of real life
problems which are today in scenario.
Advantages:
• Data security
• Inheritance
• Code reusability
1. import java.io.*;
2. class GFG {
3. public static void main(String[] args)
4. {
5. System.out.println("GfG!");
6. Signup s1 = new Signup();
7. s1.create(22, "riya", "riya2@gmail.com", 'F', 89002);
8. }
9. }
10. class Signup {
11. int userid;
12. String name;
13. String emailid;
14. char sex;
15. long mob;
16. public void create(int userid, String name,
17. String emailid, char sex, long mob)
18. {
19. System.out.println("Welcome to GeeksforGeeks\nLets
create your account\n");
20. this.userid = 132;
21. this.name = "Radha";
22. this.emailid = "radha.89@gmail.com";
23. this.sex = 'F';
24. this.mob = 900558981;
25. System.out.println("your account has been created");
26. }
27. }
Parallel processing is the processing of program instructions by dividing them among multiple
processors. A parallel processing system posses many numbers of processor with the objective
of running a program in less time by dividing them. This approach seems to be like divide and
conquer. Examples are NESL (one of the oldest one) and C/C++ also supports because of some
library function.
13
Chapter One : Introduction to Object-Oriented Programming
It can be termed as abstract model of computation. It would solve logical problems like puzzles,
series etc. In logic programming we have a knowledge base which we know before and along
with the question and knowledge base which is given to machine, it produces result.
In normal programming languages, such concept of knowledge base is not available but while
using the concept of artificial intelligence, machine learning we have some models like
Perception model which is using the same mechanism. In logical programming the main
emphasize is on knowledge base and the problem. The execution of the program is very much
like proof of mathematical statement, e.g., Prolog sum of two number in prolog:
1. predicates
2. sumoftwonumber(integer, integer)
3. clauses
4. sum(0, 0).
5. sum(n, r):-
6. n1=n-1,
7. sum(n1, r1),
8. r=r1+n
The functional programming paradigms has its roots in mathematics and it is language
independent. The key principal of this paradigms is the execution of series of mathematical
functions. The central model for the abstraction is the function which are meant for some
specific computation and not the data structure. Data are loosely coupled to functions.The
function hide their implementation. Function can be replaced with their values without
14
Chapter One : Introduction to Object-Oriented Programming
changing the meaning of the program. Some of the languages like perl, javascript mostly uses
this paradigm.
This programming methodology is based on data and its movement. Program statements are
defined by data rather than hard-coding a series of steps. A database program is the heart of a
business information system and provides file creation, data entry, update, query and reporting
functions. There are several programming languages that are developed mostly for database
application. For example SQL. It is applied to streams of structured data, for filtering,
transforming, aggregating (such as computing statistics), or calling other programs. So it has
its own wide application.
Adding new data and function is not Adding new data and function is
easy. easy.
15
Chapter One : Introduction to Object-Oriented Programming
16
Chapter One : Introduction to Object-Oriented Programming
distinguishing feature of objects is that an object’s procedures provide access to and modify its
fields.
The main ideas behind Java’s Object-Oriented Programming, OOP concepts include object,
class, abstraction, encapsulation, inheritance and polymorphism.
i. Object
Any entity that has state and behavior is known as an object.
E.g, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory.
ii. Class
Collection of objects is called class. It is a logical entity. A class can also be defined as a
blueprint from which you can create an individual object. Class doesn't consume any space.
E.g.
class Book {
}
iii. Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Inheritance is a mechanism in which one object acquires all the states and behaviors of a parent
object. Inheritance uses a parent-child relationship (IS-A relationship).
iv. Polymorphism
Polymorphism is the ability of an object to take on many forms. Polymorphism in OOP occurs
when a superclass references a subclass object
17
Chapter One : Introduction to Object-Oriented Programming
v. Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing. In Java, we use abstract class and interface to
achieve abstraction. Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
vi. Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because
all the data members are private here. Encapsulation is a process of wrapping code and data
together into a single unit. It's just like a capsule that contains a mix of several medicines, and
is a technique that helps keep instance variables protected.
vii. Association
Association represents the relationship between the objects. Here, one object can be associated
with one object or many objects. There can be four types of association between the objects:
▪ One to One
▪ One to Many
▪ Many to Many
Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where
one object contains other objects as a part of its state. It represents the weak relationship
between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents
the is-a relationship. It is another way to reuse objects.
Composition
The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a strong
relationship between the containing object and the dependent object. It is the state where
containing objects do not have an independent existence. If you delete the parent object, all the
child objects will be deleted automatically.
18
Chapter One : Introduction to Object-Oriented Programming
Functional Programming
Functional programming is a programming paradigm where you have a style of building the
structure and elements of computer programs. Here you treat computation as an evaluation of
mathematical functions and you avoid changing-state and mutable data. Functional
programming consists only of PURE functions. So, what do you understand by Pure functions?
Pure functions are those which take an argument list as an input and whose output is a return
value. Now you may feel that all functions are pure as any function takes in values and returns
a value.
For example, if a function relies on the global variable or class member’s data, then it is not
pure. And in such cases, the return value of that function is not entirely dependent on the list
of arguments received as input and can also have side effects. So, what do you understand by
the term side effect? A side effect is a change in the state of an application that is observable
outside the called function other than its return value. For example: Modifying any external
variable or object property such as a global variable, or a variable in the parent function scope
chain.
Pure functions – As seen above, if the input is an array, the output will be a new array and the
input array will not be modified. So in case of pure functions, the output depends only on the
input. Here’s a function in the language Scala that takes values and returns their sum.
The add function caused no side-effects. It did not alter the input values provided, it used
another pure function, the + operator, and returned the sum of the values as the result of the
call. The add function is a pure function.
Recursion-A recursive function is a function that calls itself during its execution. This enables
the function to repeat itself several times, the result being outputted at the end of each iteration.
Below is an example of a recursive function.
19
Chapter One : Introduction to Object-Oriented Programming
The function Count() above uses recursion to count from any number between 1 and 9, to the
number 10. For example, Count(1) would return 2,3,4,5,6,7,8,9,10. Count(7) would return
8,9,10.
You will note that recursive functions are common in computer science because they allow you
to write efficient programs using a minimal amount of code. The downside is that they can
cause infinite loops and other unexpected results if not written properly. For example, in the
example above, the function is terminated if the number is 0 or less or greater than 9. If proper
cases are not included in the function to stop the execution, the recursion will repeat forever,
causing the program to crash, or worse yet, hang the entire computer system.
In this example, the mult method is referentially transparent because any call to it may be
replaced with the corresponding return value. This may be observed by replacing mult(3, 4)
with 12:
In the same way, add(2, 12) may be replaced with the corresponding return value, 14:
20
Chapter One : Introduction to Object-Oriented Programming
int x = 14;
• Variables are Immutable-In functional programming you cannot modify a variable after
it has been initialized. You can create new variables and this helps to maintain state
throughout the runtime of a program. Strings are immutable objects.
*name will have the value – Susie*uppd will have the value - SUSIE
Lisp is the second-oldest high-level programming language after Fortran but still in use. Lisp
is a functional programming language; that is, functions are first-class objects in Lisp. However,
it is not a pure-functional language such as Haskell, because operations in Lisp can have side-
effects. Lisp continues to be popular in the field of artificial intelligence down to the present
day.
21
Chapter One : Introduction to Object-Oriented Programming
I. Subjective Questions
22
Chapter One : Introduction to Object-Oriented Programming
Java is:
Object Oriented - In Java, everything is an Object. Java can be easily extended since
it is based on the Object model.
Simple - Java is designed to be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master.
Secure - With Java's secure feature it enables the development of virus-free, tamper-
free systems. Authentication techniques are based on public-key encryption.
23
Chapter One : Introduction to Object-Oriented Programming
Interpreted - Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.
High Performance - With the use of Just-In-Time compilers, Java enables high
performance.
• Java FX
All Java platforms consist of a Java Virtual Machine (VM) and an application programming
interface (API). The Java Virtual Machine is a program, for a particular hardware and software
platform, that runs Java technology applications. An API is a collection of software
components that you can use to create other software components or applications. Each Java
platform provides a virtual machine and an API, and this allows applications written for that
platform to run on any compatible system with all the advantages of the Java programming
language: platform-independence, power, stability, ease-of-development, and security.
1. Java SE
When most people think of the Java programming language, they think of the Java SE API.
Java SE's API provides the core functionality of the Java programming language. It defines
everything from the basic types and objects of the Java programming language to high-level
classes that are used for networking, security, database access, graphical user interface (GUI)
development, and XML parsing. In addition to the core API, the Java SE platform consists of
a virtual machine, development tools, deployment technologies, and other class libraries and
toolkits commonly used in Java technology applications.
24
Chapter One : Introduction to Object-Oriented Programming
2. Java EE
The Java EE platform is built on top of the Java SE platform. The Java EE platform provides
an API and runtime environment for developing and running large-scale, multi-tiered, scalable,
reliable, and secure network applications.
3. Java ME
The Java ME platform provides an API and a small-footprint virtual machine for running Java
programming language applications on small devices, like mobile phones. The API is a subset
of the Java SE API, along with special class libraries useful for small device application
development. Java ME applications are often clients of Java EE platform services.
4. Java FX
Java FX technology is a platform for creating rich internet applications written in JavaFX
ScriptTM. JavaFX Script is a statically-typed declarative language that is compiled to Java
technology bytecode, which can then be run on a Java VM. Applications written for the JavaFX
platform can include and link to Java programming language classes, and may be clients of
Java EE platform services.
Java Application is a Java program that runs on an underlying operating system with the
support of a virtual machine. It is also known as an application program. The graphical user
interface is not necessary to execute the java applications, it can be run with or without it.
An applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at the client side. An applet is embedded in an HTML page using the
APPLET or OBJECT tag and hosted on a web server. Applets are used to make the web site
more dynamic and entertaining
Figure 3: Java
25
Chapter One : Introduction to Object-Oriented Programming
▪ Stand-alone application
▪ Web applets
Applets are small programs developed for Internet applications. An applet located on a distant
computer (server) can be downloaded via Internet and executed on a local computer (client)
using a Java-capable browser.
26
Chapter One : Introduction to Object-Oriented Programming
A. Editing a Program
Any text editor may be used to edit a program by merely typing the program and making
corrections as needed. Popular Unix and Linux editors include vi and emacs. Macintosh editors
include SimpleText and BBEdit, and the WinEdit and NotePad editors are available for
windows.
As we have seen, a Java program consists of one or more class definitions. We will follow the
convention of placing each class definition in its own file. (Normally in Java a source file
should contain only one public class definition.) The files containing these classes' definitions
must be named ClassName.java where ClassName is the name of the public Java class
contained in the file.
NB: A file that defines a public class named ClassName must be saved in text file named
ClassName.java otherwise an error will result.
B. Compiling a Program
Recall that before you can run a Java source program you have to compile it into the Java
bytecode, the intermediate code understood by the Java Virtual Machine (JVM). Source code
for applets and applications must be compiled. To run a Java program, whether an applet or an
application, the JVM is then used to interpret and execute the bytecode.
J2SE (Java SE) comes in two parts, a runtime program, called the Java Runtime Environment
(JRE) and a development package, called the Software Development Kit (SDK). If you are just
going to run Java programs, you need only install the JRE on your computer. In order to run
Java applets, our browser, such as Internet Explorer and Netscape Navigator, must contain a
plug-in version of the JRE. On the other hand, if you are going to be developing Java programs,
you will need to install the SDK as well.
The Java SDK compiler is named javac. In some environments such as within Linux or at the
Windows command prompt HelloWorld.java would be compiled by typing the following
command at the system prompt: Javac HelloWorld.java
In order to run (or execute) a program on any computer, the program's executable code must
be loaded into the computer's main memory. For Java environments, this means that the
27
Chapter One : Introduction to Object-Oriented Programming
program's .class file must be loaded into the computer's memory, where it is then interpreted
by the Java Virtual Machine. To run a Java program on Linux systems or at the Windows
command prompt, type: Java HelloWorld
To run a Java applet, you need to use either a Web browser or the SDK's appletviewer, a
stripped-down Web browser for running applets. The Web browser (or appletviewer) uses an
HTML (HyperText Markup Language) document to locate the applet's bytecode files on the
Web (or directly on your computer's hard drive). The HTML file must contain an <applet> tag....
<html>
...
<applet code="HelloWorldApplet.class" width=200
height=200>
</applet>
....
</html>
Java combines both these approaches thus makes it a two-stage system. Java compiler
translates the source code into bytecode instructions Java interpreter generates the machine
code that can be directly executed by the machine that is running the java program.
Java compiler produces an intermediate code known as bytecode for a machine that does not
exist. This machine is known as Java Virtual Machine (JVM) & it exists only inside computer
memory. It is a simulated computer within the computer and does all major functions of the
real computer.
Just In Time compiler (JIT), part of the JVM, is responsible for compiling code as it is needed,
during execution.
28
Chapter One : Introduction to Object-Oriented Programming
Class Declaration: the first line class Sample declares a class, which is an object constructor.
Class is keyword and declares a new class definition and Sample is a java identifier that
specifies the name of the class to be defined.
Opening Brace “{“: Every class definition in java begins with an opening brace and ends with
a closing brace “}”.
The main line: the third line public static void main(String args[]) defines a method named as
main. Is the starting point for the interpreter to begin the execution of the program.
A java program can have any number of classes but only one of them must include the main
method to initiate the execution. Java applets will not use the main method at all.
The third line uses a number of keywords: public, static and void
▪ Public: is an access specifier that declares the main method as “unprotected” and
therefore making it accessible to all other classes.
▪ static: declares that this method as one that belongs to the entire class and not a part of
any objects of the class.
▪ Main must always be declared as static since the interpreter uses this method before
any objects are created.
▪ void : states that the main method does not return any value.
▪ All parameters to a method are declared inside a pair of parenthesis. Here, String args[ ]
declares a parameter named args, which contains array of objects of the class type
String.
29
Chapter One : Introduction to Object-Oriented Programming
System.out.println(“Hello world.”);
▪ The printlnmethod is a member of the out object, which is a static data member of
System class.
Optional
Package Statement
Optional
Import Statements
Optional
Interface Statements
comprises a set of comment lines giving the name of the program, the author and other details,
which the programmer would like to refer at a later stage. Java supports three types of
comments:
………………*/
Package Statement
Is the first statement in Java file and is optional.It declares a package name and informs the
compiler that the classes defined here belong to this package.
30
Chapter One : Introduction to Object-Oriented Programming
import statements
Next to package statements (but before any class definitions) a number of import statements
may exist. This is similar to #include statements in C or C++. Using import statements we can
have access to classes that are part of other named packages.
interface Statements
An interface is like a class but includes a group of method declarations. It is also an optional
section. It is used only when we wish to implement the multiple inheritance features in the
program
Class Definitions
A Java program may contain multiple class definitions. Classes are the primary and essential
elements of a Java program.These classes are used to map objects of real-world problems. The
number of classes depends on the complexity of the problem.
Since every Java stand-alone program requires a main method as its starting point, this class is
the essential part of a Java program. A simple Java program may contain only this part. The
main method creates objects of various classes and establishes communications between them.
On reaching the end of main, the program terminates and control passes back to the operating
system. A class in java is defined by a set of declaration statements and methods containing
executable statements.Most statements contain expressions, which describe the actions carried
out on data.Smallest individual units in a program are known as tokens.
Java I/O (Input and Output) is used to process the input and produce the output. Java uses the
concept of a stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
31
Chapter One : Introduction to Object-Oriented Programming
Let's see the code to print output and an error message to the console.
System.out.println("simple message");
System.err.println("error message");
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket. Let's understand the working of Java OutputStream and
InputStream by the figure given below.
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes. An output stream accepts output bytes and sends them to some sink.
32
Chapter One : Introduction to Object-Oriented Programming
Method Description
OutputStream Hierarchy
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
33
Chapter One : Introduction to Object-Oriented Programming
Method Description
1) public abstract int reads the next byte of data from the input stream. It
read()throws IOException returns -1 at the end of the file.
InputStream Hierarchy
Java FileOutputStream is an output stream used for writing data to a file. If you have to write
primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as
character-oriented data through FileOutputStream class. But, for character-oriented data, it is
preferred to use FileWriter than FileOutputStream.
34
Chapter One : Introduction to Object-Oriented Programming
Method Description
protected void finalize() It is used to clean up the connection with the file output
stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to
the file output stream.
void write(byte[] ary, It is used to write len bytes from the byte array starting at
int off, int len) offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output
stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the
stream.
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also read character-
stream data. But, for reading streams of characters, it is recommended to use FileReader class.
35
Chapter One : Introduction to Object-Oriented Programming
Method Description
int read() It is used to read the byte of data from the input stream.
int read(byte[] b, int off, int It is used to read up to len bytes of data from the input
len) stream.
long skip(long x) It is used to skip over and discards x bytes of data from
the input stream.
36
Chapter One : Introduction to Object-Oriented Programming
Figure 9: JVM
Disadvantages of Java
▪ Running bytecode through the interpreter is not as fast as running machine code, which is
specific to that platform.
▪ Java interpreter must be installed on the computer in order to run Java programs.
37
Chapter One : Introduction to Object-Oriented Programming
How To Install and Get Started with Java Programming(on Windows, Mac
OS and Ubuntu)
Compared with its rival Eclipse (http://www.elicpse.org) (both are open-source, so I don't
know what are they competing for?), NetBeans provides seamless support for Java
AWT/Swing, Java ME mobility pack, Java EE, and bundled with an excellent profiler for
performance tuning.
To use NetBeans for Java programming, you need to first install Java Development Kit
(JDK). See "JDK - How to Install".
Step 2: Download
To use NetBeans for Java programming, you need to first install JDK. Read "How to install
JDK on Mac".
To install NetBeans:
38
Chapter One : Introduction to Object-Oriented Programming
OS X". There are many "bundles" available. For beginners, choose "Java SE" (e.g.,
"netbeans-8.2-javase-macosx.dmg" 116MB).
To use NetBeans for Java programming, you need to first install JDK. Read "How to install
JDK on Ubuntu".
To install NetBeans:
2. Set the downloaded sh file to executable and run the sh file. Open a Terminal:
$ cd ~/Downloads
$ chmod a+x netbeans-7.x-ml-javase-linux.sh // Set
to executable for all (a+x)
$ ./netbeans-7.x-ml-javase-linux.sh // Run
To start NetBeans, run the script "netbeans" in the NetBeans' bin directory:
$ cd netbeans-bin-directory
$ ./netbeans
Launch NetBeans. If the "Start Page" appears, close it by clicking the "cross" button next to
the "Start Page" title.
39
Chapter One : Introduction to Object-Oriented Programming
For each Java application, you need to create a "project" to keep all the source files, classes
and relevant resources.
3. The "Name and Location" dialog pops up ⇒ Under "Project Name", enter
"FirstProject" ⇒ In "Project Location", select a suitable directory to save your
works ⇒ Uncheck "Use Dedicated Folder for Storing Libraries" ⇒ Uncheck
"Create Main class" ⇒ Finish.
1. Right-click on "FirstProject" ⇒ New ⇒ Java Class (OR choose the "File" menu
⇒ "New File..." ⇒ Categories: "Java", File Types: "Java Class" ⇒ "Next").
2. The "Name and Location" dialog pops up ⇒ In "Class Name", enter "Hello" ⇒
Delete the content in "Package" if it is not empty ⇒ "Finish".
3. The source file "Hello.java" appears in the editor panel. Enter the following codes:
There is no need to "compile" the source code in NetBeans explicitly, as NetBeans performs
the so-called incremental compilation (i.e., the source statement is compiled as and when it is
entered).
To run the program, right-click anywhere in the source (or from the "Run" menu) ⇒ Run File.
Observe the output on the output console.
Notes:
40
Chapter One : Introduction to Object-Oriented Programming
• You should create a NEW Java project for EACH of your Java application.
• Nonetheless, NetBeans allows you to keep more than one programs in a project,
which is handy for writing toy programs (such as your tutorial exercises). To run a
particular program, open and right-click on the source file ⇒ Run File.
NetBeans performs incremented compilation, as and when a source line is entered. It marked
a source line with syntax error with a RED CROSS. Point your cursor at the RED CROSS to
view the error message. You CANNOT RUN the program if there is any syntax error (marked
by a RED CROSS before the filename). Correct all the syntax errors; and RUN the program.
[TODO] Diagram
HINTS: In some cases, NetBeans shows a ORANGE LIGHT-BULB (for HINTS) next to the
ERROR RED-CROSS (Line 5 in the above diagram). You can click on the LIGHT-BULB to
get a list of HINTS to resolve this particular error, which may or may not work!
At a minimum, you SHOULD READ the "IDE Basics, Getting Started, Java Application",
which is accessible via NetBeans's "HELP" menu ⇒ Help Contents. This will save you many
agonizing hours trying to figure out how to do somethings later.
The NetBeans "Start Page" also provides many useful links to get you started.
The following program computes and prints the factorial of n (=1*2*3*...*n). The program,
however, has a logical error and produce a wrong answer for n=20 ("The Factorial of 20 is -
2102132736" - a negative number?!).
41
Chapter One : Introduction to Object-Oriented Programming
A breakpoint suspends program execution for you to examine the internal states of the program.
Before starting the debugger, you need to set at least one breakpoint to suspend the execution
inside the program. Set a breakpoint at main() method by clicking on the left-margin of the line
containing main(). A red circle or an inverted Triangle appears in the left-margin indicating a
breakpoint is set at that line.
Input statement is used to read input from key board in the run time or from files. Output is
used to display output in the screen. In Java everything is treated as a class and object.Java
class is a template or blue print that the object will follow. Class consists of properties and
actions, properties is variables and actions are method. Every class consists of variables and
methods.
In order to access class variables and methods we have to create an instance of this class is
called object. Object is a reference of a class.
IOSTREAMS
▪ System is a class where input and output is built in, in is an object for input
42
Chapter One : Introduction to Object-Oriented Programming
43
Chapter One : Introduction to Object-Oriented Programming
2. Write a Java program to print the sum, multiply, subtract, divide and remainder of any two
numbers.
3. Write a Java program that takes three numbers as input to calculate and print the average
of the numbers
7. Write a Java program to check whether Java is installed on your computer or not
8. Write a Java program and compute the sum of the digits of an integer
10. Write a Java program to count the letters, spaces, numbers and other characters of an input
string
11. Write a Java program to print the ascii value of a given character
12. Write a Java program that accepts an integer (n) and computes the value of n+nn+nnn
44
Chapter One : Introduction to Object-Oriented Programming
Reference
1. Java: A Beginner's Guide, Eighth Edition by Herbert Schildt
2. Java: How to Program, 9th Edition (Deitel)
3. https://www.javatpoint.com/
45
Chapter Two: Basics in Java Programming
Lesson Plan
1. Learning objectives
• Use literals
• Initialize variables
• Apply continue
2. Motivation
46
Chapter Two: Basics in Java Programming
5. Practice contents/Activities/Safety
Active practice; on java input and output, writing (Editing), compiling, interprating.
6. Assessments
9. Review/Reflection
• Review the outcome of the practice, improvement measure and previous reflected
opinions.
47
Chapter Two: Basics in Java Programming
They can have alphabets, digits, and the underscore and dollar sign characters.
Remember, you can’t start an identifier with a digit. Thus, 12x is invalid, for example.
In general, you cannot use the Java keywords as identifier names. Also, you should not use the
name of any standard method, such as println, as an identifier. Beyond these two restrictions,
good programming practice dictates that you use identifier names that reflect the meaning or
usage of the items being named.
2.1.2. Keywords
Sixty-one keywords are currently defined in the Java language. These keywords, combined
with the syntax of the operators and separators, form the definition of the Java language. In
general, keywords cannot be used as names for a variable, class, or method. The exceptions to
this rule are the context-sensitive keywords added by JDK 9 to support modules. Also,
beginning with JDK 9, an underscore by itself is considered a keyword in order to prevent its
use as the name of something in your program.
48
Chapter Two: Basics in Java Programming
The keywords const and goto are reserved but not used. In the early days of Java, several other
keywords were reserved for possible future use. However, the current specification for Java
defines only the keywords shown in Table 1-1.
In addition to the keywords, Java reserves four other names. Three have been part of Java since
the start: true, false, and null. These are values defined by Java. You may not use these words
for the names of variables, classes, and so on. Beginning with JDK 10, the word var has
been added as a context-sensitive, reserved type name.
2.1.3. Variable
Perhaps no other construct is as important to a programming language as the assignment of a
value to a variable. A variable is a named memory location that can be assigned a value. Further,
the value of a variable can be changed during the execution of a program. That is, the content
of a variable is changeable, not fixed. The following program creates two variables called
myVar1 and myVar2:
49
Chapter Two: Basics in Java Programming
/*
This demonstrates a variable.
Call this file Example2.java.
*/
class Example2 {
public static void main(String args[]) {
int myVar1; // this declares a variable.
int myVar2; // this declares another variable
myVar1 = 1024; // this assigns 1024 to myVar1.
System.out.println("myVar1 contains " + myVar1);
myVar2 = myVar1 / 2;
System.out.print("myVar2 contains myVar1 / 2: ");
System.out.println(myVar2);
}
When you run this program, you will see the following output:
This program introduces several new concepts. First, the statement int myVar1 declares a
variable called myVar1 of type integer. In Java, all variables must be declared before they are
used. Further, the type of values that the variable can hold must also be specified. This is called
the type of the variable. In this case, myVar1 can hold integer values. These are whole number
values. In Java, to declare a variable to be of type integer, precede its name with the keyword
int. Thus, the preceding statement declares a variable called myVar1 of type int.
Notice that this line uses the same format as the first line except that the name of the variable
is different.
In general, to declare a variable you will use a statement like this: type var-name;
Here, type specifies the type of variable being declared, and var-name is the name of the
variable. In addition to int, Java supports several other data types.
50
Chapter Two: Basics in Java Programming
The following line of code assigns myVar1 the value 1024: myVar1 = 1024; // this assigns
1024 to varl
In Java, the assignment operator is the single equal sign. It copies the value on its right side
into the variable on its left.
The next line of code outputs the value of myVar1 preceded by the string "myVar1 contains":
In this statement, the plus sign causes the value of myVar1 to be displayed after the string that
precedes it. This approach can be generalized. Using the + operator, you can chain together as
many items as you want within a single println( ) statement.
The next line of code assigns myVar2 the value of myVar1 divided by 2: myVar2 = myVar1 /
2;
This line divides the value in myVar1 by 2 and then stores that result in myVar2. Thus, after
the line executes, myVar2 will contain the value 512. The value of myVar1 will be unchanged.
System.out.println(myVar2);
Two new things are occurring here. First, the built-in method print( ) is used to display the
string "myVar2 contains myVarl / 2:". This string is not followed by a new line. This means
that when the next output is generated, it will start on the same line. The print( ) method is just
like println( ), except that it does not output a new line after each call. Second, in the call to
println( ), notice that myVar2 is used by itself. Both print( ) and println( ) can be used to output
values of any of Java’s built-in types.
One more point about declaring variables before we move on: It is possible to declare two or
more variables using the same declaration statement. Just separate their names by commas. For
example, myVarl and myVar2 could have been declared like this:
51
Chapter Two: Basics in Java Programming
to which it can be applied. Fortunately, Java supports a rich assortment of both data types and
operators, making it suitable for any type of programming.
Data types are especially important in Java because it is a strongly typed language. This means
that all operations are type-checked by the compiler for type compatibility. Illegal operations
will not be compiled. Thus, strong type checking helps prevent errors and enhances reliability.
To enable strong type checking, all variables, expressions, and values have a type. There is no
concept of a “type-less” variable, for example. Furthermore, the type of a value determines
what operations are allowed on it. An operation allowed on one type might not be allowed on
another.
Type Meaning
char Character
int Integer
52
Chapter Two: Basics in Java Programming
Type Meaning
Java strictly specifies a range and behavior for each primitive type, which all implementations
of the Java Virtual Machine must support. Because of Java’s portability requirement, Java is
uncompromising on this account. For example, an int is the same in all execution environments.
This allows programs to be fully portable. There is no need to rewrite code to fit a specific
platform. Although strictly specifying the range of the primitive types may cause a small loss
of performance in some environments, it is necessary in order to achieve portability.
Integers
Java defines four integer types: byte, short, int, and long, which are shown here:
As the table shows, all of the integer types are signed positive and negative values. Java does
not support unsigned (positive-only) integers. Many other computer languages support both
signed and unsigned integers. However, Java’s designers felt that unsigned integers were
unnecessary. Technically, the Java run-time system can use any size it wants to store a primitive
type. However, in all cases, types must act as specified.
The most commonly used integer type is int. Variables of type int are often employed to control
loops, to index arrays, and to perform general-purpose integer math.
53
Chapter Two: Basics in Java Programming
When you need an integer that has a range greater than int, use long. For example, here is a
program that computes the number of cubic inches contained in a cube that is one mile by one
mile, by one mile:
Clearly, the result could not have been held in an int variable.
The smallest integer type is byte. Variables of type byte are especially useful when working
with raw binary data that may not be directly compatible with Java’s other built-in types. The
short type creates a short integer. Variables of type short are appropriate when you don’t need
the larger range offered by int.
Floating-Point Types
The floating-point types can represent numbers that have fractional components. There are two kinds
of floating-point types, float and double, which represent single- and double-precision numbers,
respectively. Type float is 32 bits wide and type double is 64 bits wide.
Of the two, double is the most commonly used, and many of the math functions in Java’s class library
use double values. For example, the sqrt( ) method (which is defined by the standard Math class)
returns a double value that is the square root of its double argument. Here, sqrt( ) is used to compute
the length of the hypotenuse, given the lengths of the two opposing sides:
54
Chapter Two: Basics in Java Programming
/*
Use the Pythagorean theorem to find the length of the
hypotenuse given the lengths of the two opposing sides.
*/
class Hypot {
public static void main{String args[]) {
double x, y, z;
x = 3;
y = 4 ;
z= Math.sqrt(x*x + y*y); //Notice how sqrt() is
called. It is preceded by the name of the class of
which it is a member.
System.out.println("Hypotenuse is " + z) ;
}
}
Hypotenuse is 5.0
One other point about the preceding example: As mentioned, sqrt( ) is a member of the
standard Math class. Notice how sqrt( ) is called; it is preceded by the name Math. This is
similar to the way System.out precedes println( ). Although not all standard methods are
called by specifying their class name first, several are.
Characters
In Java, characters are not 8-bit quantities like they are in many other computer languages.
Instead, Java uses Unicode. Unicode defines a character set that can represent all of the
characters found in all human languages. In Java, char is an unsigned 16-bit type having a range
of o to 65,535. The standard 8-bit ASCII character set is a subset of Unicode and ranges from
0 to 127. Thus, the ASCII characters are still valid Java characters.
A character variable can be assigned a value by enclosing the character in single quotes. For
example, this assigns the variable ch the letter X:
char ch;
ch = ‘ X’;
55
Chapter Two: Basics in Java Programming
You can output a char value using a println( ) statement. For example, this line outputs the
value in ch:
Since char is an unsigned 16-bit type, it is possible to perform various arithmetic manipulations
on a char variable. For example, consider the following program:
ch contains X
ch is now Y
ch is now s
In the program, ch is first given the value X. Next, ch is incremented. This results in ch
containing Y, the next character in the ASCII (and Unicode) sequence. Next, ch is assigned the
value 90, which is the ASCII (and Unicode) value that corresponds to the letter Z. Since the
ASCII character set occupies the first 127 values in the Unicode character set, all the “old tricks”
that you may have used with characters in other languages will work in Java, too.
56
Chapter Two: Basics in Java Programming
A: Java was designed for worldwide use. Thus, it needs to use a character set that can represent
all the world’s languages. Unicode is the standard character set designed expressly for this
purpose. Of course, the use of Unicode is inefficient for languages such as English, German,
Spanish, or French, whose characters can be contained within 8 bits. But such is the price that
must be paid for global portability.
The boolean type represents true/false values. Java defines the values true and false using the
reserved words true and false. Thus, a variable or expression of type boolean will be one of
these two values. Here is a program that demonstrates the boolean type:
b is false
b is true
This is executed.
10 > 9 is true
57
Chapter Two: Basics in Java Programming
There are three interesting things to notice about this program. First, as you can see, when a
boolean value is output by println( ), "true" or "false" is displayed. Second,the value of a
boolean variable is sufficient, by itself, to control the if statement. There is no need to write an
if statement like this:
if(b = = true) .. .
Third, the outcome of a relational operator, such as <, is a boolean value. This is why the
expression 10 > 9 displays the value "true." Further, the extra set of parentheses around 10 > 9
is necessary because the + operator has a higher precedence than the >.
Literals
In Java, literals refer to fixed values that are represented in their human-readable form. For
example, the number 100 is a literal. Literals are also commonly called constants. For the most
part, literals, and their usage, are so intuitive that they have been used in one form or another
by all the preceding sample programs. Now the time has come to explain them formally.
Java literals can be of any of the primitive data types. The way each literal is represented
depends upon its type. As explained earlier, character constants are enclosed in single quotes.
For example, 'a' and' %' are both character constants.
Integer literals are specified as numbers without fractional components. For example, 10 and
-100 are integer literals. Floating-point literals require the use of the decimal point followed by
the number’s fractional component. For example, 11.123 is a floating-point literal. Java also
allows you to use scientific notation for floating-point numbers.
By default, integer literals are of type int. If you want to specify a long literal, append an l or
an L. For example, 12 is an int, but 12L is a long.
By default, floating-point literals are of type double. To specify a float literal, append an F or
f to the constant. For example, 10.19F is of type float.
Although integer literals create an int value by default, they can still be assigned to variables
of type char, byte, or short as long as the value being assigned can be represented by the target
type. An integer literal can always be assigned to a long variable.
You can embed one or more underscores into an integer or floating-point literal. Doing so can
make it easier to read values consisting of many digits. When the literal is compiled, the
underscores are simply discarded.
58
Chapter Two: Basics in Java Programming
Here is an example:
123_45_1234
This specifies the value 123,451,234. The use of underscores is particularly useful when
encoding things like part numbers, customer IDs, and status codes that are commonly thought
of as consisting of subgroups of digits.
Enclosing character constants in single quotes works for most printlng characters, but a few
characters, such as the carriage return, pose a special problem when a text editor is used. In
addition, certain other characters, such as the single and double quotes, have special meaning
in Java, so you cannot use them directly. For these reasons, Java provides special escape
sequences, sometimes referred to as backslash character constants, shown in Table 2-2. These
sequences are used in place of the characters that they represent.
\\ Backslash
\r Carriage return
\n New line
\f Form feed
\t Horizontal tab
\b Backspace
59
Chapter Two: Basics in Java Programming
ch ='\t';
ch = '\' ';
String Literals
Java supports one other type of literal: the string. A string is a set of characters enclosed by
double quotes. For example,
"this is a test"
is a string. You have seen examples of strings in many of the println( ) statements in the
preceding sample programs.
In addition to normal characters, a string literal can also contain one or more of the escape
sequences just described. For example, consider the following program. It uses the \n and \t
escape sequences.
First line
Second line
A B C
D E F
60
Chapter Two: Basics in Java Programming
Q: Is a string consisting of a single character the same as a character literal? For example, is
"k" the same as 'k'?
A: No. You must not confuse strings with characters. A character literal represents a single
letter of type char. A string containing only one letter is still a string. Although strings consist
of characters, they are not the same type.
Notice how the \n escape sequence is used to generate a new line. You don’t need to use
multiple println( ) statements to get multiline output. Just embed \n within a longer string at
the points where you want the new lines to occur.
Variables were introduced in Chapter 1. Here, we will take a closer look at them. As you
learned earlier, variables are declared using this form of statement,
type var-name;
where type is the data type of the variable, and var-name is its name. You can declare a variable
of any valid type, including the simple types just described, and every variable will have a type.
Thus, the capabilities of a variable are determined by its type. For example, a variable of type
boolean cannot be used to store floating-point values. Furthermore, the type of a variable
cannot change during its lifetime. An int variable cannot turn into a char variable, for example.
All variables in Java must be declared prior to their use. This is necessary because the compiler
must know what type of data a variable contains before it can properly compile any statement
that uses the variable. It also enables Java to perform strict type checking.
Initializing a Variable
In general, you must give a variable a value prior to using it. One way to give a variable a value
is through an assignment statement, as you have already seen. Another way is by giving it an
initial value when it is declared. To do this, follow the variable’s name with an equal sign and
the value being assigned. The general form of initialization is shown here:
Here, value is the value that is given to var when var is created. The value must be compatible
with the specified type. Here are some examples:
61
Chapter Two: Basics in Java Programming
When declaring two or more variables of the same type using a comma-separated list, you can
give one or more of those variables an initial value. For example:
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows variables
to be initialized dynamically, using any expression valid at the time the variable is declared.
For example, here is a short program that computes the volume of a cylinder given the radius
of its base and its height:
Here, three local variables—radius, height, and volume—are declared. The first two, radius
and height, are initialized by constants. However, volume is initialized dynamically to the
volume of the cylinder. The key point here is that the initialization expression can use any
element valid at the time of the initialization, including calls to methods, other variables, or
literals.
each time you start a new block, you are creating a new scope. A scope determines what objects
are visible to other parts of your program. It also determines the lifetime of those objects.
In general, every declaration in Java has a scope. As a result, Java defines a powerful, finely
grained concept of scope. Two of the most common scopes in Java are those defined by a class
and those defined by a method. A discussion of class scope (and variables declared within it)
is deferred until later in this book, when classes are described. For now, we will examine only
the scopes defined by or within a method.
The scope defined by a method begins with its opening curly brace. However, if that method
has parameters, they too are included within the method’s scope. A method’s scope ends with
its closing curly brace. This block of code is called the method body.
As a general rule, variables declared inside a scope are not visible (that is, accessible) to code
that is defined outside that scope. Thus, when you declare a variable within a scope, you are
localizing that variable and protecting it from unauthorized access and/or modification. Indeed,
the scope rules provide the foundation for encapsulation. A variable declared within a block is
called a local variable.
Scopes can be nested. For example, each time you create a block of code, you are creating a
new, nested scope. When this occurs, the outer scope encloses the inner scope. This means that
objects declared in the outer scope will be visible to code within the inner scope. However, the
reverse is not true. Objects declared within the inner scope will not be visible outside it.
63
Chapter Two: Basics in Java Programming
As the comments indicate, the variable x is declared at the start of main( )’s scope and is
accessible to all subsequent code within main( ). Within the if block, y is declared. Since a
block defines a scope, y is visible only to other code within its block. This is why outside of its
block, the line y = 100; is commented out. If you remove the leading comment symbol, a
compile-time error will occur, because y is not visible outside of its block. Within the if block,
x can be used because code within a block (that is, a nested scope) has access to variables
declared by an enclosing scope.
Within a block, variables can be declared at any point, but are valid only after they are declared.
Thus, if you define a variable at the start of a method, it is available to all of the code within
that method. Conversely, if you declare a variable at the end of a block, it is effectively useless,
because no code will have access to it.
Here is another important point to remember: variables are created when their scope is entered,
and destroyed when their scope is left. This means that a variable will not hold its value once
it has gone out of scope. Therefore, variables declared within a method will not hold their
values between calls to that method. Also, a variable declared within a block will lose its value
when the block is left. Thus, the lifetime of a variable is confined to its scope.
If a variable declaration includes an initializer, that variable will be reinitialized each time the
block in which it is declared is entered. For example, consider this program:
64
Chapter Two: Basics in Java Programming
y = 100;
System.out.println("y is now: " + y);
}
}
Y is: - 1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
As you can see, y is reinitialized to -l each time the inner for loop is entered. Even though it is
subsequently assigned the value 100, this value is lost.
There is one quirk to Java’s scope rules that may surprise you: although blocks can be nested,
no variable declared within an inner scope can have the same name as a variable declared by
an enclosing scope. For example, the following program, which tries to declare two separate
variables with the same name, will not compile.
65
Chapter Two: Basics in Java Programming
Secondly, declare and assign variables of the following different data types.
• Declare a variable named value_int of the data type int that is assigned the value 20
• Secondly, declare a variable named value_string of the data type string that is assigned the
value “Java”
• Third, create a variable named value_double of the data type double that is assigned the value
23.63
• Finally, print all variables in the console.
To create a new variable in Java,
66
Chapter Two: Basics in Java Programming
System.out.println(value_int);
System.out.println(value_string);
System.out.println(value_double);
Resulting in,
20
Java
23.63
First,
• Declare a variable named value of the data type int that is assigned the value 50
• Secondly, declare a variable named another_value of the data type double that is assigned the
value 30.2
Secondly,
• Convert the variable value from data type int to data type double. Save the new variable to a
new variable value_double
Finally,
• Add the variable value and another_value and assign the value to a new variable which is
assigned the name sum_value of type double.
• Print the result
67
Chapter Two: Basics in Java Programming
• We easily create variables by first specifying the data type, followed by the variable name and
the value we want to assign to the variable.
• We can convert an int to a double by creating a new variable of the data type double.
• Summing up is easy with the plus operator +
public class DeclareDatatype {
System.out.println(sum_value);
68
Chapter Two: Basics in Java Programming
Assessments
Theory
A. Instance Variable
B. Class Variable
C. Local Variable
11. A variable declared outside of a method is known as
public class TestMain {
String msg = "Hello World"; // msg variable name
public static void main(String[] args) {
70
Chapter Two: Basics in Java Programming
71
Chapter Two: Basics in Java Programming
1. Why does Java strictly specify the range and behavior of its primitive types?
2. What is Java’s character type, and how does it differ from the character type used by some other
programming languages?
3. A boolean value can have any value you like because any non-zero value is true. True or False?
One
Two
Three
using a single string, show the println( ) statement that produced it.
sum = sum + i;
6. Explain the difference between the prefix and postfix forms of the increment operator.
10. Write a program that finds all of the prime numbers between 2 and 100.
72
Chapter Two: Basics in Java Programming
• arithmetic,
• bitwise,
• relational, and
• Logical.
Java also defines some additional operators that handle certain special situations.
A. Arithmetic operators
Java defines the following arithmetic operators:
Operator Meaning
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
73
Chapter Two: Basics in Java Programming
The operators +,-,*, and / all work the same way in Java as they do in any other computer
language (or algebra, for that matter). These can be applied to any built-in numeric data type.
They can also be used on objects of type char.
Although the actions of arithmetic operators are well known to all readers, a few special
situations warrant some explanation. First, remember that when / is applied to an integer, any
remainder will be truncated; for example, 10/3 will equal 3 in integer division. You can obtain
the remainder of this division by using the modulus operator %. It yields the remainder of an
integer division. For example, 10 % 3 is 1. In Java, the % can be applied to both integer and
floating-point types. Thus, 10.0 % 3.0 is also 1.
As you can see, the % yields a remainder of 1 for both integer and floating-point operations.
74
Chapter Two: Basics in Java Programming
The increment operator adds 1 to its operand, and the decrement operator subtracts 1.
Therefore,
x = x + 1; is the same as x + +;
Both the increment and decrement operators can either precede (prefix) or follow (postfix) the
operand. For example,
In the foregoing example, there is no difference whether the increment is applied as a prefix or
a postfix. However, when an increment or decrement is used as part of a larger expression,
there is an important difference. When an increment or decrement operator precedes its operand,
Java will perform the corresponding operation prior to obtaining the operand’s value for use
by the rest of the expression. If the operator follows its operand, Java will obtain the operand’s
value before incrementing or decrementing it. Consider the following:
x = 10;
y = ++x;
x = 10;
y = x++;
then y will be set to 10. In both cases, x is still set to 11; the difference is when it happens.
There are significant advantages in being able to control when the increment or decrement
operation takes place.
75
Chapter Two: Basics in Java Programming
can be connected together. Since the relational operators produce true or false results, they
often work with the logical operators. For this reason they will be discussed together here.
Table 0-12: The relational operators Table 0-13: The logical operators
!= Not equal to 1 OR
In Java, all objects can be compared for equality or inequality using = = and !=. However, the
comparison operators, <, >, <=, or >=, can be applied only to those types that support an
ordering relationship. Therefore, all of the relational operators can be applied to all numeric
types and to type char. However, values of type boolean can only be compared for equality or
inequality, since the true and false values are not ordered. For example, true > false has no
meaning in Java.
For the logical operators, the operands must be of type boolean, and the result of a logical
operation is of type boolean. The logical operators, &, |,ꓥ, and !, support the basic logical
operations AND, OR, XOR, and NOT, according to the following truth table:
p q p&q pvq p ꓥq !P
76
Chapter Two: Basics in Java Programming
As the table shows, the outcome of an exclusive OR operation is true when exactly one and
only one operand is true.
Here is a program that demonstrates several of the relational and logical operators:
}
}
77
Chapter Two: Basics in Java Programming
I<j
i <= j
i!=j
b1 | b2 is true
b1 ꓥ b2 is true
The short-circuit AND operator is &&, and the short-circuit OR operator is ||. Their normal
counterparts are & and |. The only difference between the normal and short- circuit versions is
that the normal operands will always evaluate each operand, but short-circuit versions will
evaluate the second operand only when necessary.
Here is a program that demonstrates the short-circuit AND operator. The program determines
whether the value in d is a factor of n. It does this by performing a modulus operation. If the
remainder of n / d is zero, then d is a factor. However, since the modulus operation involves a
division, the short-circuit form of the AND is used to prevent a divide-by-zero error.
78
Chapter Two: Basics in Java Programming
if(d != 0 && (n % d) == 0)
System.out.println(d + " is a factor of "+ n) ;
d = 0; // now, set d to zero
// Since d is zero, the second operand is not
evaluated.
if (d != 0 && (n % d) == 0);//The short-circuit
operator prevents a division by zero.
System.out.println(d + " is a factor of " + n) ;
/* Now, try same thing without short-circuit operator.
This will cause a divide-by-zero error.
* /
if (d!=0 && (n%d)==0) // Now both expressions are
evaluated, allowing a division by zero to occur.
System.out.println(d+" is a factor of " + n) ;
}
}
To prevent a divide-by-zero, the if statement first checks to see if d is equal to zero. If it is, the
short-circuit AND stops at that point and does not perform the modulus division. Thus, in the
first test, d is 2 and the modulus operation is performed. The second test fails because d is set
to zero, and the modulus operation is skipped, avoiding a divide- by-zero error. Finally, the
normal AND operator is tried. This causes both operands to be evaluated, which leads to a run-
time error when the division by zero occurs.
One last point: The formal specification for Java refers to the short-circuit operators as the
conditional-or and the conditional-and operators, but the term “short-circuit” is commonly used.
var = expression;
Here, the type of var must be compatible with the type of expression.
The assignment operator does have one interesting attribute that you may not be familiar with:
it allows you to create a chain of assignments. For example, consider this fragment:
79
Chapter Two: Basics in Java Programming
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to 100 using a single statement. This works because
the = is an operator that yields the value of the right-hand expression. Thus, the value of z =
100 is 100, which is then assigned to y, which in turn is assigned to x. Using a “chain of
assignment” is an easy way to set a group of variables to a common value.
Shorthand assignments
Java provides special shorthand assignment operators that simplify the coding of certain
assignment statements. Let’s begin with an example. The assignment statement shown here
x = x + 10;
x + = 10;
Q: Since the short-circuit operators are, in some cases, more efficient than their normal
counterparts, why does Java still offer the normal AND and OR operators?
A: In some cases you will want both operands of an AND or OR operation to be evaluated
because of the side effects produced. Consider the following:
As the comments indicate, in the first if statement, i is incremented whether the if succeeds or
not. However, when the short-circuit operator is used, the variable i is not incremented when
the first operand is false. The lesson here is that if your code expects the right-hand operand of
an AND or OR operation to be evaluated, you must use Java’s non-short-circuit forms of these
operations.
The operator pair += tells the compiler to assign to x the value of x plus 10. Here is another
example. The statement
x = x - 100;
is the same as
x -= 100;
This shorthand will work for all the binary operators in Java (that is, those that require two
operands). The general form of the shorthand is
var op = expression;
Thus, the arithmetic and logical shorthand assignment operators are the following:
+= -= *= /=
%= &= |= ꓥ=
Because these operators combine an operation with an assignment, they are formally referred
to as compound assignment operators.
The compound assignment operators provide two benefits. First, they are more compact than
their “longhand” equivalents. Second, in some cases, they are more efficient. For these reasons,
you will often see the compound assignment operators used in professionally written Java
programs.
81
Chapter Two: Basics in Java Programming
int i;
float f;
i = 10;
f = i; // assign an int to a float
When compatible types are mixed in an assignment, the value of the right side is automatically
converted to the type of the left side. Thus, in the preceding fragment, the value in i is converted
into a float and then assigned to f. However, because of Java’s strict type checking, not all
types are compatible, and thus, not all type conversions are implicitly allowed. For example,
boolean and int are not compatible.
When one type of data is assigned to another type of variable, an automatic type conversion
will take place if
When these two conditions are met, a widening conversion takes place. For example, the int
type is always large enough to hold all valid byte values, and both int and byte are integer types,
so an automatic conversion from byte to int can be applied.
For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other. For example, the following program is perfectly valid since long
to double is a widening conversion that is automatically performed.
82
Chapter Two: Basics in Java Programming
)
}
There are no automatic conversions from the numeric types to char or boolean. Also, char and
boolean are not compatible with each other. However, an integer literal can be assigned to char.
Although the automatic type conversions are helpful, they will not fulfill all programming
needs because they apply only to widening conversions between compatible types. For all other
cases you must employ a cast. A cast is an instruction to the compiler to convert one type into
another. Thus, it requests an explicit type conversion. A cast has this general form:
(target-type) expression
Here, target-type specifies the desired type to convert the specified expression to. For example,
if you want to convert the type of the expression x/y to int, you can write
double x, y;
// . . *
(int) (x / y)
Here, even though x and y are of type double, the cast converts the outcome of the expression
to int. The parentheses surrounding x/y are necessary. Otherwise, the cast to int would apply
83
Chapter Two: Basics in Java Programming
only to the x and not to the outcome of the division. The cast is necessary here because there
is no automatic conversion from double to int.
When a cast involves a narrowing conversion, information might be lost. For example, when
casting a long into a short, information will be lost if the long’s value is greater than the range
of a short because its high-order bits are removed. When a floating-point value is cast to an
integer type, the fractional component will also be lost due to truncation. For example, if the
value 1.23 is assigned to an integer, the resulting value will simply be 1. The 0.23 is lost.
The following program demonstrates some type conversions that require casts:
84
Chapter Two: Basics in Java Programming
Integer outcome of x / y: 3
value of b: 100
Value of b: 1
ch: X
In the program, the cast of (x / y) to int results in the truncation of the fractional component,
and information is lost. Next, no loss of information occurs when b is assigned the value 100
because a byte can hold the value 100. However, when the attempt is made to assign b the
value 257, information loss occurs because 257 exceeds a byte’s maximum value. Finally, no
information is lost, but a cast is needed when assigning a byte value to a char.
85
Chapter Two: Basics in Java Programming
LogicalOpTable.java
In this project, you will create a program that displays the truth table for Java’s logical operators.
You must make the columns in the table line up. This project makes use of several features
covered in this chapter, including one of Java’s escape sequences and the logical operators. It
also illustrates the differences in the precedence between the arithmetic + operator and the
logical operators.
3. Each subsequent line in the table will use tabs to position the outcome of each operation
under its proper heading.
4. Here is the entire LogicalOpTable.java program listing. Enter it at this time.
class LogicalOpTable {
public static void main(String args[]} {
boolean p, q;
System.out.println("P\tQ\tAND\tOR\tXOR\tNOT");
p = true; q = true;
System.out.print(p + "\t" + q +"\t");
System.out.print ((p&q)+" \t" +(p|q) +"\t");
System.out.println((pꓥq) + "\t" + (!p));
p = true; q = false;
System.out.print(p + "\t" + q +"\t");
System.out.print ((p&q) +" \t"+ (p|q)+"\t");
System.out.println((pꓥq) + "\t" +(!p));
p = false; q =true;
System.out.print (p + " \t" + q +"\t");
System.out.print ((p&q) +" \t"+ (p|q)+"\t");
System.out.println((pꓥq) + "\t" + (!p));
p = false; q = false;
86
Chapter Two: Basics in Java Programming
Notice the parentheses surrounding the logical operations inside the println( ) statements. They
are necessary because of the precedence of Java’s operators. The + operator is higher than the
logical operators.
6. On your own, try modifying the program so that it uses and displays 1’s and 0’s, rather
than true and false. This may involve a bit more effort than you might at first think!
EXPRESSIONS
Operators, variables, and literals are constituents of expressions. You probably already know
the general form of an expression from your other programming experience, or from algebra.
However, a few aspects of expressions will be discussed now.
First, all char, byte, and short values are promoted to int. Then, if one operand is a long, the
whole expression is promoted to long. If one operand is a float operand, the entire expression
is promoted to float. If any of the operands is double, the result is double. It is important to
understand that type promotions apply only to the values operated upon when an expression is
evaluated. For example, if the value of a byte variable is promoted to int inside an expression,
87
Chapter Two: Basics in Java Programming
outside the expression, the variable is still a byte. Type promotion only affects the evaluation
of an expression.
Type promotion can, however, lead to somewhat unexpected results. For example, when an
arithmetic operation involves two byte values, the following sequence occurs: First, the byte
operands are promoted to int. Then the operation takes place, yielding an int result. Thus, the
outcome of an operation involving two byte values will be an int. This is not what you might
intuitively expect. Consider the following program:
// A promotion surprise!
class PromDemo {
public static void main(String args []) {
byte b; int i ;
b = 10;
i =b * b; // No cast needed because result is already
elevated to int
b = (byte)(b* b); // Cast is needed here to assign an
int to a byte!
System.out.println("i and b: " + i +" " + b);
}
Somewhat counter intuitively, no cast is needed when assigning b*b to i, because b is promoted
to int when the expression is evaluated. However, when you try to assign b * b to b, you do
need a cast—back to byte! Keep this in mind if you get unexpected type- incompatibility error
messages on expressions that would otherwise seem perfectly OK.
This same sort of situation also occurs when performing operations on chars. For example, in
the following fragment, the cast back to char is needed because of the promotion of chi and
ch2 to int within the expression:
Without the cast, the result of adding ch1 to ch2 would be int, which can’t be assigned to a
char.
Casts are not only useful when converting between types in an assignment. For example,
consider the following program. It uses a cast to double to obtain a fractional component from
an otherwise integer division.
88
Chapter Two: Basics in Java Programming
0/3: 0
0 / 3 with fractions: 0 .0
1/ 3: 0
1 / 3 with fractions: 0.3333333333333333
2/3: 0
2 / 3 with fractions: 0 .6666666666666666
3/3:1
3 / 3 with fractions: 1.0
4/3 :1
4 / 3 with fractions: 1.3333333333333333
An expression in Java may have tabs and spaces in it to make it more readable. For example,
the following two expressions are the same, but the second is easier to read:
x=10/y*(127/x);
x = 10 / y * (127/x);
89
Chapter Two: Basics in Java Programming
Parentheses increase the precedence of the operations contained within them, just like in
algebra. Use of redundant or additional parentheses will not cause errors or slow down the
execution of the expression. You are encouraged to use parentheses to make clear the exact
order of evaluation, both for yourself and for others who may have to figure out your program
later. For example, which of the following two expressions is easier to read?
x = y/3-34*temp+12 7;
90
Chapter Two: Basics in Java Programming
In this exercise we are going to declare five variables , accept their values from user and finally display
them for user
import java.util.Scanner;
91
Chapter Two: Basics in Java Programming
In this exersice we are going to add three numbers which have different data types then display the
result
import java.util.Scanner;
92
Chapter Two: Basics in Java Programming
float number2=input.nextFloat();
System.out.println(“Enter Float number”);
double number3=input.nextDouble();
System.out.println(“Enter Double number”);
Step2 : Add the three variable and Display the result
Result=number1+number2+number3;
System.out.println(“Result is is:”+result);
}
}
93
Chapter Two: Basics in Java Programming
a) $amount
b) 6tally
c) my*Name
d) salary
e) score
f) first Name
g) total#
h) cast
int y = 2;
94
Chapter Two: Basics in Java Programming
Before examining Java’s control statements, we will make a short digression that will allow
you to begin writing interactive programs. Up to this point, the sample programs in this book
have displayed information to the user, but they have not received information from the user.
Thus, you have been using console output, but not console (keyboard) input. The main reason
for this is that Java’s input capabilities rely on or make use of features not discussed until later
in this book. Also, most real-world Java applications will be graphical and window based, not
console based. For these reasons, not much use of console input is found in this book. However,
there is one type of console input that is relatively easy to use: reading a character from the
keyboard. Since several of the examples in this chapter will make use of this feature, it is
discussed here.
To read a character from the keyboard, we will use System.in.read( ). System.in is the
complement to System.out. It is the input object attached to the keyboard. The read( ) method
waits until the user presses a key and then returns the result. The character is returned as an
integer, so it must be cast into a char to assign it to a char variable. By default, console input is
line buffered. Here, the term buffer refers to a small portion of memory that is used to hold the
characters before they are read by your program. In this case, the buffer holds a complete line
of text. As a result, you must press ENTER before any character that you type will be sent to
your program. Here is a program that reads a character from the keyboard:
95
Chapter Two: Basics in Java Programming
char ch;
System.out.print("Press a key followed by ENTER: ");
ch = (char) System.in. read () ; // Read a character
from the keyboard.
System.out.println("Your key is: " + ch);
}
throws java.io.IOException {
Because System.in.read( ) is being used, the program must specify the throws
java.io.IOException clause. This line is necessary to handle input errors. It is part of Java’s
exception handling mechanism, which is discussed in another Chapter. For now, don’t worry
about its precise meaning.
The fact that System.in is line buffered is a source of annoyance at times. When you press
ENTER, a carriage return, line feed sequence is entered into the input stream. Furthermore,
these characters are left pending in the input buffer until you read them. Thus, for some
applications, you may need to remove them (by reading them) before the next input operation.
You will see an example of this later in this chapter.
If(condition) statement;
else statement;
where the targets of the if and else are single statements. The else clause is optional. The targets
of both the if and else can be blocks of statements. The general form of the if, using blocks of
statements, is
if(condition)
{
statement sequence
96
Chapter Two: Basics in Java Programming
}
Else
{
statement sequence
}
If the conditional expression is true, the target of the if will be executed; otherwise, if it exists,
the target of the else will be executed. At no time will both of them be executed. The conditional
expression controlling the if must produce a boolean result.
To demonstrate the if (and several other control statements), we will create and develop a
simple computerized guessing game that would be suitable for young children. In the first
version of the game, the program asks the player for a letter between A and Z. If the player
presses the correct letter on the keyboard, the program responds by printlng the message **
Right **. The program is shown here:
This program prompts the player and then reads a character from the keyboard. Using an if
statement, it then checks that character against the answer, which is K in this case. If K was
entered, the message is displayed. When you try this program, remember that the K must be
entered in uppercase.
Taking the guessing game further, the next version uses the else to print a message when the
wrong letter is picked.
97
Chapter Two: Basics in Java Programming
Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very common in
programming. The main thing to remember about nested ifs in Java is that an else statement always
refers to the nearest if statement that is within the same block as the else and not already associated with
an else. Here is an example:
if(i == 10) {
if (j < 20) a = b;
if(k > 100) c = d;
else a = c; // this else refers to if(k > 100)
}
else a = d; // this else refers to if(i == 10)
As the comments indicate, the final else is not associated with if(j < 20), because it is not in the same
block (even though it is the nearest if without an else). Rather, the final else is associated with if(i==
10). The inner else refers to if(k > 100), because it is the closest if within the same block.
You can use a nested if to add a further improvement to the guessing game. This addition provides the
player with feedback about a wrong guess.
98
Chapter Two: Basics in Java Programming
A common programming construct that is based upon the nested if is the if-else-if ladder. It
looks like this:
if{condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.
else
statement;
99
Chapter Two: Basics in Java Programming
The conditional expressions are evaluated from the top downward. As soon as a true condition
is found, the statement associated with it is executed, and the rest of the ladder is bypassed. If
none of the conditions are true, the final else statement will be executed. The final else often
acts as a default condition; that is, if all other conditional tests fail, the last else statement is
performed. If there is no final else and all other conditions are false, no action will take place.
X is one
X is two
X is three
X is four
100
Chapter Two: Basics in Java Programming
As you can see, the default else is executed only if none of the preceding if statements succeeds.
switch (expression) {
case constant1: statement sequence
break;
case constant2:
statement sequence
break;
case constants3:
statement sequence
break;
default:
statement sequence
}
For versions of Java prior to JDK 7, the expression controlling the switch must resolve to type
byte, short, int, char, or an enumeration. (Enumerations are described in Chapter 12.)
However, beginning with JDK 7, expression can also be of type String. This means that modern
versions of Java can use a string to control a switch. (This technique is demonstrated in Chapter
5, when String is described.) Frequently, the expression controlling a switch is simply a
variable rather than a larger expression.
Each value specified in the case statements must be a unique constant expression (such as a
literal value). Duplicate case values are not allowed. The type of each value must be compatible
with the type of expression.
101
Chapter Two: Basics in Java Programming
The default statement sequence is executed if no case constant matches the expression. The
default is optional; if it is not present, no action takes place if all matches fail. When a match
is found, the statements associated with that case are executed until the break is encountered
or, in the case of default or the last case, until the end of the switch is reached.
102
Chapter Two: Basics in Java Programming
i is zero
i is one
i is two
i is three
i is four
i is five or more
i is five or more
i is five or more
i is five or more
i is five or more
As you can see, each time through the loop, the statements associated with the case constant
that matches i are executed. All others are bypassed. When i is five or greater, no case
statements match, so the default statement is executed.
Technically, the break statement is optional, although most applications of the switch will use
it. When encountered within the statement sequence of a case, the break statement causes
program flow to exit from the entire switch statement and resume at the next statement outside
the switch. However, if a break statement does not end the statement sequence associated with
a case, then all the statements at and following the matching case will be executed until a break
(or the end of the switch) is encountered.
For example, study the following program carefully. Before looking at the output, can you
figure out what it will display on the screen?
case 2:
System.out.println("i is less than three
case 3:
System.out.println("i is less than four")
case 4:
System.out.println("i is less than five"}
}
System.out.println();
As this program illustrates, execution will continue into the next case if no break statement is
present.
104
Chapter Two: Basics in Java Programming
switch(i) {
case 1: case 2 :
case 3: System.out.println("i is 1, 2 or 3M); break;
case 4: System.out.println(" i is 4 11) ; break;
}
In this fragment, if i has the value 1, 2, or 3, the first println( ) statement executes. If it is 4, the
second println( ) statement executes. The “stacking” of cases, as shown in this example, is
common when several cases share common code.
It is possible to have a switch as part of the statement sequence of an outer switch. This is called
a nested switch. Even if the case constants of the inner and outer switch contain common values,
no conflicts will arise. For example, the following code fragment is perfectly acceptable:
switch(ch1) {
case 'A':
System.out.println("This A is part of outer switch.");
break;
switch(ch2) { case 'A':
System.out.println("This A is part of inner switch");
break;
case 'B' : // ...
} // end of inner switch
break case 'B': // ...
Help.java
This project builds a simple help system that displays the syntax for the Java control statements.
The program displays a menu containing the control statements and then waits for you to
choose one. After one is chosen, the syntax of the statement is displayed. In this first version
of the program, help is available for only the if and switch statements. The other control
statements are added in subsequent projects.
105
Chapter Two: Basics in Java Programming
Help on:
a. if
b. switch
Choose one:
To accomplish this, you will use the statement sequence shown here:
Notice how the default clause catches invalid choices. For example, if the user enters
106
Chapter Two: Basics in Java Programming
class Help {
public static void main(String args [) )
throws java.io.IOException {
char choice;
System.out.println( "Help on: " ) ;
System.out.println("1.if");
System.out.println("2.switch");
System.out.print("Choose one: " ) ;
choice = (char) System.in.read();
System.out.println("\n");
switch(choice) { case '1':
System.out.println("The if : \ n") ;
System.out.println("if (condition) statement; ") ;
System.out.println("else statement;")
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch (expression) { ") ;
System.out.println("case constant:");
System.out.println("statement sequence");
System.out.println("break; ") ;
System.out.println("// ..");
System.out.println("} ") ;
break;
default:
System.out.print("Selection not found.");
}
}
}
107
Chapter Two: Basics in Java Programming
Help on:
1. if
2. switch
Choose one: 1
The if:
if(condition) statement;
else statement;
The general form of the for loop for repeating a single statement is
Q: Under what conditions should I use an if-else-if ladder rather than a switch when coding a
multiway branch?
A: In general, use an if-else-if ladder when the conditions controlling the selection process do
not rely upon a single value. For example, consider the following if-else-if sequence:
statement sequence
108
Chapter Two: Basics in Java Programming
This sequence cannot be recoded into a switch because all three conditions involve different
variables and differing types. What variable would control the switch? Also, you will need to
use an if-else-if ladder when testing floating-point values or other objects that are not of types
valid for use in a switch expression.
The initialization is usually an assignment statement that sets the initial value of the loop
control variable, which acts as the counter that controls the loop.
The condition is a Boolean expression that determines whether or not the loop will repeat.
The iteration expression defines the amount by which the loop control variable will change
each time the loop is repeated.
Notice that these three major sections of the loop must be separated by semicolons. The for
loop will continue to execute as long as the condition tests true. Once the condition becomes
false, the loop will exit, and program execution will resume on the statement following the for.
The following program uses a for loop to print the square roots of the numbers between l and
99. It also displays the rounding error present for each square root.
Notice that the rounding error is computed by squaring the square root of each number. This
result is then subtracted from the original number, thus yielding the rounding error.
109
Chapter Two: Basics in Java Programming
The for loop can proceed in a positive or negative fashion, and it can change the loop control
variable by any amount. For example, the following program prints the numbers 100 to -95, in
decrements of 5:
An important point about for loops is that the conditional expression is always tested at the top
of the loop. This means that the code inside the loop may not be executed at all if the condition
is false to begin with. Here is an example:
This loop will never execute because its control variable, count, is greater than 5 when the loop
is first entered. This makes the conditional expression, count < 5, false from the outset; thus,
not even one iteration of the loop will occur.
The for is one of the most versatile statements in the Java language because it allows a wide range of
variations. For example, multiple loop control variables can be used.
i and j : 0 10
i and j : 1 9
i and j : 2 8
i and j : 3 7
i and j : 4 6
Here, commas separate the two initialization statements and the two iteration expressions.
When the loop begins, both i and j are initialized. Each time the loop repeats, i is incremented
and j is decremented. Multiple loop control variables are often convenient and can simplify
certain algorithms. You can have any number of initialization and iteration statements, but in
practice, more than two or three make the for loop unwieldy.
The condition controlling the loop can be any valid Boolean expression. It does not need to
involve the loop control variable. In the next example, the loop continues to execute until the
user types the letter S at the keyboard:
Missing pieces
Some interesting for loop variations are created by leaving pieces of the loop definition empty.
In Java, it is possible for any or all of the initialization, condition, or iteration portions of the
for loop to be blank. For example, consider the following program:
111
Chapter Two: Basics in Java Programming
class Empty {
public static void main(String args[j) {
int i;
for(i = 0; i < 10; ) { //The
iteration expression is missing.
System.out.println("Pass #" + i);
i++; // increment loop control var
}
}
}
Here, the iteration expression of the for is empty. Instead, the loop control variable i is
incremented inside the body of the loop. This means that each time the loop repeats, i is tested
to see whether it equals 10, but no further action takes place. Of course, since i is still
incremented within the body of the loop, the loop runs normally, displaying the following
output:
Pass #0
Pass #1
Pass #2
Pass #3
Pass #4
Pass #5
Pass #6
Pass #7
Pass #8
Pass #9
In the next example, the initialization portion is also moved out of the for:
112
Chapter Two: Basics in Java Programming
In this version, i is initialized before the loop begins, rather than as part of the for. Normally,
you will want to initialize the loop control variable inside the for. Placing the initialization
outside of the loop is generally done only when the initial value is derived through a complex
process that does not lend itself to containment inside the for statement.
You can create an infinite loop (a loop that never terminates) using the for by leaving the conditional
expression empty. For example, the following fragment shows the way many Java programmers create
an infinite loop:
This loop will run forever. Although there are some programming tasks, such as operating system
command processors, that require an infinite loop, most “infinite loops” are really just loops with special
termination requirements. Near the end of this chapter, you will see how to halt a loop of this type.
(Hint: It’s done using the break statement.)
In Java, the body associated with a for loop (or any other loop) can be empty. This is because a null
statement is syntactically valid. Body-less loops are often useful. For example, the following program
uses one to sum the numbers l through 5:
113
Chapter Two: Basics in Java Programming
Sum is 15
Notice that the summation process is handled entirely within the for statement, and no body is
needed. Pay special attention to the iteration expression:
sum += i++
Don’t be intimidated by statements like this. They are common in professionally written Java
programs and are easy to understand if you break them down into their parts. In other words,
this statement says, “Add to sum the value of sum plus i, then increment i.” Thus, it is the same
as this sequence of statements:
sum = sum + i;
i+ + ;
Often the variable that controls a for loop is needed only for the purposes of the loop and is not
used elsewhere. When this is the case, it is possible to declare the variable inside the
initialization portion of the for. For example, the following program computes both the
summation and the factorial of the numbers l through 5. It declares its loop control variable i
inside the for.
114
Chapter Two: Basics in Java Programming
When you declare a variable inside a for loop, there is one important point to remember: the
scope of that variable ends when the for statement does. (That is, the scope of the variable is
limited to the for loop.) Outside the for loop, the variable will cease to exist. Thus, in the
preceding example, i is not accessible outside the for loop. If you need to use the loop control
variable elsewhere in your program, you will not be able to declare it inside the for loop.
Before moving on, you might want to experiment with your own variations on the for loop. As
you will find, it is a fascinating loop.
There is another form of the for loop, called the enhanced for. The enhanced for provides a
streamlined way to cycle through the contents of a collection of objects, such as an array. The
enhanced for loop is discussed after arrays have been introduced.
while(condition) statement;
where statement may be a single statement or a block of statements, and condition defines the
condition that controls the loop. The condition may be any valid Boolean expression. The loop
repeats while the condition is true. When the condition becomes false, program control passes
to the line immediately following the loop.
115
Chapter Two: Basics in Java Programming
char ch;
// print the alphabet using a while loop
ch = 'a ';
while(ch <='z') {
System.out.print (ch)
ch++;
}
}
}
Here, ch is initialized to the letter a. Each time through the loop, ch is output and then
incremented. This process continues until ch is greater than z.
As with the for loop, the while checks the conditional expression at the top of the loop, which
means that the loop code may not execute at all. This eliminates the need for performing a
separate test before the loop. The following program illustrates this characteristic of the while
loop. It computes the integer powers of 2, from 0 to 9.
116
Chapter Two: Basics in Java Programming
2 to the 0 power is 1
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 12 8
Notice that the while loop executes only when e is greater than o. Thus, when e is zero, as it is
in the first iteration of the for loop, the while loop is skipped.
Q: Given the flexibility inherent in all of Java’s loops, what criteria should I use when selecting
a loop? That is, how do I choose the right loop for a specific job?
A: Use a for loop when performing a known number of iterations based on the value of a loop
control variable. Use the do-while when you need a loop that will always perform at least one
iteration. The while is best used when the loop will repeat until some condition becomes false.
do{
statements;
} while(condition);
Although the braces are not necessary when only one statement is present, they are often used
to improve readability of the do-while construct, thus preventing confusion with the while. The
do-while loop executes as long as the conditional expression is true.
117
Chapter Two: Basics in Java Programming
The following program loops until the user enters the letter q:
Using a do-while loop, we can further improve the guessing game program from earlier in this
chapter. This time, the program loops until you guess the letter.
118
Chapter Two: Basics in Java Programming
System.out.println("too low");
else
System.out.println("too high");
System.out.println("Try again!\n");
}
} while(answer != ch);
}
Try again I
Try again!
** Right **
Notice one other thing of interest in this program. There are two do-while loops in the program.
The first loops until the user guesses the letter. Its operation and meaning should be clear. The
second do-while loop, shown again here, warrants some explanation:
As explained earlier, console input is line buffered—you have to press ENTER before
characters are sent. Pressing ENTER causes a carriage return and a line feed (newline)
sequence to be generated. These characters are left pending in the input buffer. Also, if you
119
Chapter Two: Basics in Java Programming
typed more than one key before pressing ENTER, they too would still be in the input buffer.
This loop discards those characters by continuing to read input until the end of the line is
reached. If they were not discarded, then those characters would also be sent to the program as
guesses, which is not what is wanted. (To see the effect of this, you might try removing the
inner do-while loop.) In Chapter 10, after you have learned more about Java, some other,
higher-level ways of handling console input are described. However, the use of read( ) here
gives you insight into how the foundation of Java's I/O system operates. It also shows another
example of Java's loops in action.
Help2.java j
This project expands on the Java help system that was created. This version adds the syntax for
the for, while, and do-while loops. It also checks the user’s menu selection, looping until a
valid response is entered.
2. Change the first part of main( ) so that it uses a loop to display the choices, as shown here:
120
Chapter Two: Basics in Java Programming
Notice that a nested do-while loop is used to discard any unwanted characters remaining in the
input buffer. After making this change, the program will loop, displaying the menu until the
user enters a response that is between 1 and 5.
3. Expand the switch statement to include the for, while, and do-while loops, as shown
here:
switch(choice) {
case '1':
System.out.println("The if : \n") ;
System.out.println("if (condition) statement;") ;
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch: \n") ;
System.out.println("switch (expression) {") ;
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break; ") ;
System.out.println(" // ….");
System.out.println("}") ;
break;
case '3':
System.out.println("The for:\n");
System.out.print("for (init; condition; iteration") ;
System.out.println(" statement; ") ;
break;
case '4':
System.out.println("The while; \n") ;
System.out.println("while (condition) statement; '')
break;
case '5':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println("statement;") ;
121
Chapter Two: Basics in Java Programming
Notice that no default statement is present in this version of the switch. Since the menu loop
ensures that a valid response will be entered, it is no longer necessary to include a default
statement to handle an invalid choice.
/*
Try This 3-2
An improved Help system that uses a do-while to process
a menu selection.
*/
class Help2 {
public static void main(String args[])
throws java.io.IOException {
char choice, ignore;
do {
System.out.println("Help on:");
System.out.println("1- if") ;
System.out.println("2. switch");
System.out.println("3. for") ;
System.out.println("4. while");
System.out.println("5. do-while\n");
System.out.print ( "Choose one; ");
choice = (char) System.in.read();
do {
ignore = (char) System.in.read();
} while(ignore != '\n');
} while( choice < '1' | choice > '5');
System.out.print ( "\n");
switch(choice) {
case '1':
System.out.println("The if : \n") ;
122
Chapter Two: Basics in Java Programming
123
Chapter Two: Basics in Java Programming
statement is encountered inside a loop, the loop is terminated and program control resumes at
the next statement following the loop. Here is a simple example:
0 1 2 3 4 5 6 7 8 9 Loop complete.
As you can see, although the for loop is designed to run from 0 to num (which in this case is
100), the break statement causes it to terminate early, when i squared is greater than or equal
to num.
The break statement can be used with any of Java’s loops, including intentionally infinite loops.
For example, the following program simply reads input until the user types the letter q:
124
Chapter Two: Basics in Java Programming
When used inside a set of nested loops, the break statement will break out of only the
innermost loop. For example:
Loops complete.
As you can see, the break statement in the inner loop causes the termination of only that loop.
The outer loop is unaffected.
125
Chapter Two: Basics in Java Programming
Here are two other points to remember about break. First, more than one break statement may
appear in a loop. However, be careful. Too many break statements have the tendency to
destructure your code. Second, the break that terminates a switch statement affects only that
switch statement and not any enclosing loops.
Q: You say that the goto is unstructured and that the break with a label offers a better
alternative. But really, doesn’t breaking to a label, which might be many lines of code and
levels of nesting removed from the break, also destructure code?
A: The short answer is yes! However, in those cases in which a jarring change in program flow
is required, breaking to a label still retains some structure. A goto has none!
// Use continue.
class ContDemo {
public static void main(String argsf]) {
int i; // print even numbers between 0 and 100
for(i = 0; i< = 100; i + + } {
if((i%2)!=0) continue; // iterate
System.out.println(i);
}
}
}
Only even numbers are printed, because an odd one will cause the loop to iterate early,
bypassing the call to println( ).
In while and do-while loops, a continue statement will cause control to go directly to the
conditional expression and then continue the looping process. In the case of the for, the iteration
126
Chapter Two: Basics in Java Programming
expression of the loop is evaluated, then the conditional expression is executed, and then the
loop continues.
As with the break statement, continue may specify a label to describe which enclosing loop to
continue. Here is an example program that uses continue with a label:
As the output shows, when the continue executes, control passes to the outer loop,skipping the
remainder of the inner loop.
127
Chapter Two: Basics in Java Programming
Good uses of continue are rare. One reason is that Java provides a rich set of loop statements
that fit most applications. However, for those special circumstances in which early iteration is
needed, the continue statement provides a structured way to accomplish it.
NESTED LOOPS
As you have seen in some of the preceding examples, one loop can be nested inside of another.
Nested loops are used to solve a wide variety of programming problems and are an essential
part of programming. So, before leaving the topic of Java’s loop statements, let’s look at one
more nested loop example. The following program uses a nested for loop to find the factors of
the numbers from 2 to 100:
/*
Use nested loops to find factors of numbers between 2
and 100,
*/
class FindFac {
public static void main{String args []) {
for(int i=2; i <= 100; i++) {
System.out.print (" Factors of " + i + ,f: ") ;
for(int j = 2; j < i; j++)
if((i%j) == 0) System.out.print(j + " ") ;
System.out.println();
}
}
}
Factors of 2
Factors of 3
Factors of 4 2
Factors of 5
Factors of 6 23
Factors of 7
Factors of 8 24
128
Chapter Two: Basics in Java Programming
Factors of 9 3
Factors of 10 : 2 5
Factors of 12 : 2 3 4
Factors of 13 :
Factors of 14 : 2 7
Factors of 15 : 3 5
Factors of 16 : 2 4 8
Factors of 17 :
Factors of 18 : 2 3 6
Factors of 19:
Factors of 20 : 2 4 5
In the program, the outer loop runs i from 2 through 100. The inner loop successively tests all
numbers from 2 up to i, printlng those that evenly divide i. Extra challenge: The preceding
program can be made more efficient. Can you see how? (Hint: The number of iterations in the
inner loop can be reduced.)
129
Chapter Two: Basics in Java Programming
Helps.java I
This project puts the finishing touches on the Java help system that was created in the previous
projects. This version adds the syntax for break and continue. It also allows the user to request
the syntax for more than one statement. It does this by adding an outer loop that runs until the
user enters q as a menu selection.
2. Surround all of the program code with an infinite for loop. Break out of this loop, using
break, when a letter q is entered. Since this loop surrounds all of the program code, breaking
out of this loop causes the program to terminate.
do {
System.out.println("Help on:");
System.out.println("1. if") ;
System.out.println("2. switch");
System.out.println("3. for") ;
System.out.println("4. while");
System.out.println("5. do-while\n");
System.out.println( "Choose one; ");
choice = (char) System.in.read();
do {
ignore = (char) System.in.read();
} while(ignore != '\n');
} while( choice < '1' | choice > '5');
do {
System.out.println("Help on:");
System.out.println("1- if") ;
System.out.println("2. switch");
130
Chapter Two: Basics in Java Programming
System.out.println("3. for") ;
System.out.println("4. while");
System.out.println("5. do-while\n") ;
System.out.println("6. break");
System.out.println("7. continue \n");
System.out.print ( "Choose one (q to quit ");
choice = (char) System.in.read();
do {
ignore = (char) System.in.read();
} while(ignore != '\n');
} while( choice < '1' | choice > '7' & choice !);
Notice that this loop now includes the break and continue statements. It also accepts the letter
q as a valid choice.
4. Expand the switch statement to include the break and continue statements, as shown
here:
/*
Try This 3-3
The finished Java statement Help system that processes
multiple requests.
*/
class Help3 {
public static void main(String argstl) throws
java.io.IOException { char choice, ignore;
for{;;) {
do {
System.out.println("Help on:");
131
Chapter Two: Basics in Java Programming
System.out.println("1- if") ;
System.out.println("2. switch");
System.out.println("3. for") ;
System.out.println("4. while");
System.out.println("5. do-while\n") ;
System.out.println("6. break");
System.out.println("7. continue \n");
System.out.print("Choose one (q to quit) : ,r) ;
choice = (char) System.in.read();
do {
ignore = (char) System.in.read();
} while(ignore != '\n');
} while( choice < '1'|| choice >'7' & &choice!='q');
if(choice == 'q') break;
System.out.println("\n"} ;
switch(choice) {
case '1':
System.out.println("The if: \n") ;
System.out.println("if(condition) statement;");
System.out.println("else statement;"); break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}"); break;
case '3':
System.out.println("The for:\n");
System.out.println("for(init; condition; iteration)");
System.out.println(" statement;"); break;
case '4':
System.out.println("The while:\n");
132
Chapter Two: Basics in Java Programming
System.out.println("while(condition) statement;");
break;
case '5':
System.out. println( "The do-while: \n")
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);"); break;
case '6':
System.out.println("The break:\n");
System.out.println("break; or break label;"); break;
case '7':
System.out.println("The continue:\n");
System.out.println("continue; or continue label;");
break;
}
System.out.println();
}
}
Help on:
1, if
2. switch
3. for
4. while
5. do-while
6. break
7. continue
Help on:
1. if 2. switch 3 . for
133
Chapter Two: Basics in Java Programming
4. while
5. do-while
6, break
7, continue
Help on:
1. if
2. switch
3 . for
4. while
5. do-while 6 - break
7, continue
134
Chapter Two: Basics in Java Programming
1. Find out Errors in the following program and discuss ways for correction.
a) //Errors.java
2. Write a Java application program that asks the user to enter two numbers obtains the
numbers from the user and prints the sum, product, difference and quotient of the
numbers?
3. Write a Java application program that asks the user to enter two integers, obtains the
numbers from the user and displays the larger number followed by the words “is larger
than “ the smaller number in the screen. If the numbers are equal, print the message
“These numbers are equal.”
4. Write four different Java statements that each add 1 to integer variable x.
second+=1;
a) if(num>100 || num<0)
System.out.prinln(“Out of Range”);
135
Chapter Two: Basics in Java Programming
else
sum+=num;
y=1;
else
y=0;
6. Write a Java application program that reads the coefficients of a quadratic equation
(ax2+bx+c=0), generates and display the roots.
Note:
An appropriate message should be generated when the user types an invalid input to the
equation.
2. Write a Java application program that asks the user to enter an integer number from the
keyboard and computes the sum of the digits of the number.
136
Chapter Two: Basics in Java Programming
[ Hint: if the user types 4567as input , then the output will be 22 ]
1. Given a number, write a program using while loop to reverse the digits of the
number. [ Hint: Use Modulus Operator to extract the last digit and the integer
division by 10 to get the n-1 digit number from the n digit]
a)
$ $ $ $ $
$ $ $ $
$ $ $
$ $
b)
1 2
1 2 3
1 2 3 4
1 2 3 4 5
137
Chapter Two: Basics in Java Programming
Reference
1. Java: A Beginner's Guide, Eighth Edition by Herbert Schildt
2. Java: How to Program, 9th Edition (Deitel)
3. https://www.javatpoint.com/
138
Chapter Two: Basics in Java Programming
139
Chapter Three : Objects and Classes
Lesson Plan
1. Learning objectives
5. Practice contents/Activities/Safety
Active practice; on java input and output, writing (Editing), compiling, interprating.
140
Chapter Three : Objects and Classes
6. Assessments
9. Review/Reflection
• Review the outcome of the practice, improvement measure and previous reflected
opinions.
141
Chapter Three : Objects and Classes
◼ Classes are constructs that define objects of the same type. (Building plan of similar
objects). A class is a collection of fields (data) and methods (procedure or function) that
operate on that data.
Creating a Class
• Data items that differentiate one object of the class from another. e.g.
employee name, student number
Methods (behaviors):
type instance-variable1;
type instance-variable2;
// ...
142
Chapter Three : Objects and Classes
type instance-variableN;
type methodname1(parameter-list) {
// body of method
type methodname2(parameter-list) {
// body of method
// ...
type methodnameN(parameter-list) {
// body of method
For example:
Access modifiers define what classes can access this class. Valid access modifiers for class are:
• Public
• Abstract
• Final
The naming convention for the name of a class (ClassName) states that classes should begin
with a capital letter.
• The data, or variables, defined within a class are called instance variables.
143
Chapter Three : Objects and Classes
• Collectively, the methods and variables defined within a class are called members of
the class.
• In most classes, the instance variables are acted upon and accessed by the methods
defined for that class.
• Thus, it is the methods that determine how a class’ data can be used.
• Protected: available only to methods in the class, it’s children and other classes in the
same package.
A typical program uses various values and these values keep changing while the program is
running. For example, you create a program that is used to perform calculations; the values
entered by one user will obviously be different from the values entered by another user. This
also means that, when creating the program, you cannot know all possible values that will be
entered in your program. You should still be able to manage the values that the users will
eventually enter in your program
If you create a program used to perform calculations as introduced above, when a user enters a
new value that would be involved in the calculation, to manage that value, you can (temporarily)
144
Chapter Three : Objects and Classes
store it in the computer memory. Since the values entered in a reserved memory area change
regularly, they are called variables. Because neither you nor the compiler can predict all
possible values that would be used, there are safeguards you can use. First, you must ask the
compiler to reserve an area of memory for a value you intend to use. Asking the compiler to
reserve an area of memory is referred to as Declaring a Variable. Remember that when you
declare a variable, the compiler reserves an area of the compiler memory for you. Eventually,
you can put the desired but appropriate values in that memory space.
After declaring a variable, when you need the value stored in its memory area, you can ask the
compiler to retrieve it and hand it to you. To effectively handle this transaction, the compiler
would need two pieces of information from you: a name of your choice for the memory area
that will be reserved, and the type of value that will be stored in that area of memory. Based
on this, the formula to declare a variable is:
TypeOfValue VariableName
All variables must have a data type. You can use primitive types such as int, float, boolean, etc.
Or you can use reference types, such as strings, arrays, or objects.
Like any normal variable, to use a class in your program, you can first declare a variable for it.
To declare a variable of a class, you can use its name followed by a name for the variable. For
example, to declare a variable of the above House class, you could type the following:
class House {
House property;
The variables we have declared so far are called value variables. This is because such variables
of primitive types hold their value. You can use another type of variable. This time, when you
declare the variable, its name does not hold the value of the variable; it holds a reference to the
145
Chapter Three : Objects and Classes
address where the actual variable is stored in memory. This reference type is the kind used to
declare a variable for a class.
Variable Initialization
After declaring a variable, you can store a value in the memory reserved for it. When you have
just declared a variable, it may not hold a significant value. To know the value it has, you
should put an initial value into that memory space. Putting an initial value is referred to as
initializing the variable.
To initialize a variable, on the right side of its name, type the assignment operator, followed by
the value you want to put in the reserved memory. You cannot and should not put any type of
value in a variable.
To use a variable as reference, you must initialize it using an operator called new. Here is an
example:
class House {
}
public class Main {
public static void main(String[] args) {
House property = new House();
}
}
You can also first declare the variable. Then, on another line, you can allocate memory for it
using the new operator. Here is an example:
class House {
}
public class Main {
public static void main(String[] args) {
House property;
property = new House();
}
}
After declaring a variable and once it has a value, to display that value, you can provide the
name of the variable to the parentheses of the System.out.print() method.
146
Chapter Three : Objects and Classes
Data Input
In Java to do anything, you have to go through a class. To retrieve a value, you have to go
through different classes. When you type a value in a program, to retrieve it, you can use in
object of the System package:
System.in
After getting that value, you must first store it somewhere. One of the classes you can use is
called Scanner. Before using the Scanner class, you must import the java.util.Scanner
package into your program. This would be done by writing the following in the top section of
the file:
import java.util.Scanner;
To use the Scanner class to retrieve a value, use the following formula:
The only thing we need to mention at this time is that, after the Scanner class, you must give
a variable name. An example would be:
After declaring a Scanner class, its variable is ready to receive the value. The value depends
on a type. When getting a value, the Scanner class must be able to convert it to its appropriate
type. To support this, the Scanner class is equipped with a mechanism (actually called a
method) for each type of value. To retrieve a value, you will write the name of the Scanner
variable, followed by a period, followed by the mechanism as we will indicate, then assign it
to the variable whose value you want to retrieve. The formula will be:
VariableName = ScannerVariable.Mechanism();
To retrieve the value a variable of type int, apply nextInt() to the Scanner variable. Here
is an example:
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) {
147
Chapter Three : Objects and Classes
Days Passed: 42
Bytes
A byte is series of 8 bits. It is used to represent small numbers. To declare a variable that would
hold a natural number between -128 and 127, you can use the byte data type.
To retrieve the value of a byte variable, apply nextByte() to the Scanner variable. Here is an
example:
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
byte temperature;
System.out.print("Enter the temperature:
");
temperature = scnr.nextByte();
System.out.print("Temperature: ");
System.out.println(temperature);
}
}
148
Chapter Three : Objects and Classes
Temperature: 32
To initialize a byte variable, make sure you assign it a number in the appropriate range.
Here is an example:
Temperature: -28
The value assigned to a byte variable must in the correct range; otherwise you would receive
an error. For example, if you assign a value lower than -128 or higher than 127 to a byte variable,
the program would not work.
Data Output
To display a value, you can write it in the parentheses of System.out.print(). If the value is a
character, include it between single-quotes. Here is an example:
149
Chapter Three : Objects and Classes
James Harding
If the value is a (constant) number, simply type that number in the parentheses of
System.out.print() or System.out.println(). Here is an example:
248
If the value is stored in a variable, you can write the name of that variable in the parentheses of
System.out.print().
The section between the curly brackets, { and }, of a class is referred to as its body. In the body
of a class, you can create a list of the parts that make up the class. Each of these parts must be
a complete variable with a name and a data type. For example, here are the characteristics that
make up a house, declared as the parts of the above class and each declared as a variable:
150
Chapter Three : Objects and Classes
The variables declared in the body of a class are referred to as its member variables. In Java,
these member variables are called fields. The fields can be any data type. When creating a class,
it is your job to decide what your object is made of.
Initializing an Object
After declaring an instance of a class, you can access each of its members and assign it the
desired value. Here is an example:
Once a member variable has been initialized, you can use the period operator to access it and
retrieve its value:
151
Chapter Three : Objects and Classes
System.out.println("Properties Inventory"); ;
System.out.println("Property #: " +
property.propertyNumber);
System.out.println("Property Type: " +
property.propertyType);
System.out.println("Bedrooms: " +
property.Bedrooms);
System.out.println("Market Value: " +
property.MarketValue);
}
}
Properties Inventory
Property #: 283795
Bedrooms: 4
• Protected: available only to other methods in the class, it’s children, and other classes
in the same package.
Naming conventions for methods state that method name should begin with a lower case letter.
When you create a class, the fields are meant to describe it. For an example of a class named
House, such aspects as the number of bedrooms or its market value, are used to describe it.
152
Chapter Three : Objects and Classes
Besides the characteristics used to describe it, an object can also perform actions or assignments.
An action performed by a class is called a method. A method is simply a section of code that
takes care of a particular detail for the functionality of the class. To create a method, you specify
its name, which follows the rules we defined for variables. The name of a method is followed
by parentheses.
A method's job is to carry a specific assignment within a program. As such, it could provide a
value once the assignment has been carried. In some cases, a method must produce a result. If
it doesn't, then it is considered void. The type of value that a method can provide (or return) is
written on the left side of the method name. If the method doesn't produce a result, type void
to its left. The assignment that a method carries is included between an opening curly bracket
"{" and a closing curly bracket "}". Here is an example:
The main method provides the control of program flow. The Java interpreter executes the
application by invoking the main method. The default implementation of the main() method is
of type void. Another way to implement the main() method is to make it return an integer. The
rule is the same as for any method of type int. The main() method can return any type of integer
as long as it is a valid integer.
//Statements;
}
153
Chapter Three : Objects and Classes
• Public is an access specifier that declares the method unprotected and therefore making
it accessible to all other classes.
• Static is a keyword, which declares this method as one that belongs to the entire class
and not a part of any objects of the class.
For main, modifiers must be public static, return type must be void, and the parameter
represents an array of type String, String []. This parameter represents the command line
arguments when the program is executed. The most regularly used method of a Java program
is called main.
After creating a method, in its body delimited by its curly brackets, you can define the desired
behavior. For example, you can write the member variables in the parentheses of
System.out.print() or System.out.pr
In the same way, you can create as many methods as you want in a class.
154
Chapter Three : Objects and Classes
}//end of main
}//end of class that contains main
155
Chapter Three : Objects and Classes
156
Chapter Three : Objects and Classes
I. Subjective
4. Using two separate statements, show how to declare an object called counter of a
class
called MyCounter.
5. Show how a method called myMeth( ) is declared if it has a return type of double
and has two int parameters called a and b.
157
Chapter Three : Objects and Classes
Imagine you create a class. To access it in the main() method, you can declare its variable. A
variable you have declared of a class is also called an instance of the class. In the same way,
you can declare various instances of the same class as necessary:
class Book {
String Title;
String Author;
short YearPublished;
int NumberOfPages;
char CoverType;
}
public class Main {
public static void main(String[] args) {
Book written = new Book();
Book bought = new Book();
}
}
Each one of these instances gives you access to the members of the class but each instance
holds the particular values of the members of its instance. Consider the results of the following
program:
class Book {
String Title;
String Author;
short YearPublished;
int NumberOfPages;
char CoverType;
}
158
Chapter Three : Objects and Classes
159
Chapter Three : Objects and Classes
Book Characteristics
Year: 1996
Pages: 872
Cover: H
Book Characteristics
Year: 2004
Pages: 604
Cover: P
All of the member variables and methods of classes we have used so far are referred to as
instance members because, in order to access them, you must have an instance of a class
declared in another class in which you want to access them.
In your application, you can declare a class member and refer to it regardless of which instance
of an object you are using. Such a member variable is called static. To declare a member
variable of a class as static, type the static keyword on its left. Whenever you have a static
member, in order to refer to it, you must "qualify" it in the class in which you want to call it.
Qualifying a member means you must specify its class. Here is an example:
class Book {
static String Title;
static String Author;
int yearPublished;
int Pages;
char CoverType;
}
public class Main {
160
Chapter Three : Objects and Classes
Notice that when a member variable has been declared as static, you don't need an instance of
the class to access that member variable outside of the class. Based on this, if you declare all
members of a class as static, you don't need to declare a variable of their class in order to access
161
Chapter Three : Objects and Classes
them. In the following example, the Title and Author fields of the Book class are accessed from
the Exercise class without using an instance of the Book class:
class Book {
public static String Title;
public static String Author;
}
public class Main {
public static void main(String[] args) {
Book.Title = "Psychology and Human Evolution";
Book.Author = "Jeannot Lamm";
System.out.println("Book Characteristics");
System.out.println("Title: " + Book.Title);
System.out.println("Author: " + Book.Author);
Book.Title = "Java First Step";
Book.Author = "Alexandra Miles";
System.out.println("Book Characteristics");
System.out.println("Title: " + Book.Title);
System.out.println("Author: " + Book.Author);
}
}
Static Methods
Like a member variable, a method of a class can be defined as static. Consequently, this
particular method can access any member of the class regardless of the instance if there are
many instances of the class declared.
To define a method as static, type the static keyword to its left. Here is an example:
class Book {
static String Title;
static String Author;
static int Pages;
static double Price;
static void CreateBook() {
Title = "Psychology and Human Evolution";
162
Chapter Three : Objects and Classes
Book Characteristics
Pages: 472
Price: 24.95
163
Chapter Three : Objects and Classes
A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also
known as functions.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes
in which it is defined.
164
Chapter Three : Objects and Classes
Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by
its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with a
lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word
must be in uppercase except the first word.
Accessing a Method
After creating a method, you can access it outside of its class. You do this following the same
rules used to access a member variable, using the period operator. Unlike a member variable,
the name of a class must be followed by parentheses. Here is an example:
property.Display();
}
}
Every time an object is created using the new() keyword, at least one constructor is called. It
calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
• parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
Note: We can use access modifiers while declaring a constructor. It controls the object creation.
In other words, we can have private, protected, public or default constructor in Java.
• Parameterized constructor
166
Chapter Three : Objects and Classes
<class_name>(){}
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
167
Chapter Three : Objects and Classes
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
168
Chapter Three : Objects and Classes
169
Chapter Three : Objects and Classes
Activity on Constructors
It can be tedious to initialize all of the variables in a class each time an instance is created. Even
when you add convenience functions like setDim( )…
• But it would be simpler and more concise to initialize an object when it is first created.
Java supports a special type of method, called a constructor, that enables an object to initialize
itself when it is created. Constructors are special methods that are used to construct an instance
of a class.
A constructor initializes an object immediately upon creation. But object creation only doesn’t
call constructor rather it will be called when the object is instantiated.
Class name and constructor name should be the same. That is, it has the same name as the class
in which it resides and is syntactically similar to a method. Constructors have no return type
(not even void), this is because they return the instance of the class itself.
• They can be overloaded. Many constructors with the same name can be defined.
Types of Constructors
170
Chapter Three : Objects and Classes
It will be the default constructor which will be called, if there are no any parameterized
constructor. But if there is any parameterized constructor, then it will be the parameterized
constructor with the specified parameter(s) which will be called.
Default Constructor
When you do not write a constructor in a class, it implicitly has a constructor with no arguments
and an empty body. But we can also have a default constructor with no parameter(s) as follows:
class A
{
// Variable declaration and initialization
// Method definition
System.out.println(“Welcome”);}
class A{
public A(){
System.out.println(“Welcome”);
}}
Parameterized Constructors
class employee
{
private String Ename, empno;
private float salary;
171
Chapter Three : Objects and Classes
}
}
public class demoEmp
{
public static void main(String args[])
{
employee emp = new employee(“Au196/03”,
“Jhon Micheal”, 2563.54);
}
}
Example:
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;
}
} class BoxDemo7 {
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
172
Chapter Three : Objects and Classes
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Example :
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
173
Chapter Three : Objects and Classes
Activity: An OOP to find the area and perimeter of a rectangle by using constructor
class Rectangle{
//instance variables of Rectangle class
double height,width;
//Parametrized constructor
public Rectangle(double h,double w)
{
height=h;
width=w;
}
//methods of Rectangle class
public void Area()
{ System.out.println("Area of the rectangle is:
"+height*width);}
public void Perimeter()
{
System.out.println("Perimeter of the rectangle is:
"+2*height+2*width);
}
}//end of Rectangle class
public class UsingConstructor {
public static void main(String[] args) {
//object instantiating
Rectangle ob=new Rectangle(15.5,16.5);
ob.Area();
ob.Perimeter();
}//end of main
}//end of class UsingConstructor
174
Chapter Three : Objects and Classes
I. Subjective
175
Chapter Three : Objects and Classes
Reference
1. Java: A Beginner's Guide, Eighth Edition by Herbert Schildt
2. Java: How to Program, 9th Edition (Deitel)
3. https://www.javatpoint.com/
176
Chapter Three : Objects and Classes
177
Chapter Four: Object Oriented Programming Concepts
Lesson Plan
1. Learning objectives
5. Practice contents/Activities/Safety
Active practice; on java input and output, writing (Editing), compiling, interprating.
6. Assessments
178
Chapter Four: Object Oriented Programming Concepts
9. Review/Reflection
• Review the outcome of the practice, improvement measure and previous reflected
opinions.
179
Chapter Four: Object Oriented Programming Concepts
4.1. Inheritance
Inheritance is the process by which one object can acquire the properties of another object. This
is important because it supports the concept of hierarchical classification. If you think about it,
most knowledge is made manageable by hierarchical (i.e., top-down) classifications. For
example, a Red Delicious apple is part of the classification apple, which in turn is part of the
fruit class, which is under the larger class/food. That is, the food class possesses certain
qualities (edible, nutritious, etc.) which also, logically, apply to its subclass, fruit. In addition
to these qualities, the fruit class has specific characteristics (juicy, sweet, etc.) that distinguish
it from other food. The apple class defines those qualities specific to an apple (grows on trees,
not tropical, etc.). A Red Delicious apple would, in turn, inherit all the qualities of all preceding
classes, and would define only those qualities that make it unique.
Without the use of hierarchies, each object would have to explicitly define all of its
characteristics. Using inheritance, an object need only define those qualities that make it unique
within its class. It can inherit its general attributes from its parent. Thus, it is the inheritance
mechanism that makes it possible for one object to be a specific instance of a more general
case. There are various types of inheritance as demonstrated below.
180
Chapter Four: Object Oriented Programming Concepts
• Single Inherintence: Derivation a subclass from only one super class is called Single
Inherintence.
• Multiple Inheritance: Derivation of one class from two or more super classes is called
Multiple Inheritance. But java does not support Multiple Inheritance directly. It can be
implemented by using interface concept.
A subclass is defined as
181
Chapter Four: Object Oriented Programming Concepts
A very important fact to remember is that Java does not support multiple inheritance. This
means that a class cannot extend more than one class. Therefore following is illegal –
Often an instance variable of a class will be declared private to prevent its unauthorized use or
tampering. Inheriting a class does not overrule the private access restriction. Thus, even though
a subclass includes all of the members of its superclass, it cannot access those members of the
superclass that have been declared private.
In a hierarchy, it is possible for both superclasses and subclasses to have their own constructors.
This raises an important question: What constructor is responsible for building an object of the
subclass—the one in the superclass, the one in the subclass, or both? The answer is this: The
constructor for the superclass constructs the superclass portion of the object, and the
constructor for the subclass constructs the subclass part. This makes sense because the
superclass has no knowledge of or access to any element in a subclass. Thus, their construction
must be separate. The preceding examples have relied upon the default constructors created
automatically by Java, so this was not an issue. However, in practice, most classes will have
explicit constructors. Here you will see how to handle this situation.
The class which inherits the properties of other is known as subclass derivedclass, childclass
and the class whose properties are inherited is known as superclass baseclass, parentclass.
extends Keyword
extends is the keyword used to inherit the properties of a class. Below given is the syntax of
extends keyword.
class Super
{
.....
.....
}
class Sub extends Super
{
.....
.....
182
Chapter Four: Object Oriented Programming Concepts
Sample Code
Below given is an example demonstrating Java inheritance. In this example you can observe
two classes namely Calculation and My_Calculation. Using extends keyword the
My_Calculation inherits the methods addition and Subtraction of Calculation class.
class Calculation
{
int z;
public void addition(int x, int y)
{
z=x+y;
System.out.println("The sum of the given num bers:"+z);
}
public void Substraction(int x,int y)
{
z=x-y;
System .out.println("The difference between the given
num bers:"+z);
}
}
public class My_Calculation extends Calculation
{
public void m ultiplication(int x, int y)
{
z=x* y;
System .out.println("The product of the given num
bers:"+z);
}
public static void m ain(String args[])
{
int a=20, b=10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
183
Chapter Four: Object Oriented Programming Concepts
demo.Substraction(a, b);
demo.m ultiplication(a, b);
}
}
In the given program when an object to My_Calculation class is created, a copy of the contents
of the super class is made with in it. That is why, using the object of the subclass you can access
the members of a super class.
The Superclass reference variable can hold the subclass object, but using that variable you can
access only the members of the superclass, so to access the members of both classes it is
recommended to always create reference variable to the subclass.
If you consider the above program you can instantiate the class as given below as well. But
using the superclass reference variable ( cal in this case ) you cannot call the method
multiplication, which belongs to the subclass My_Calculation.
Note: A subclass inherits all the members fields, methods, andnestedclasses from its
superclass. Constructors are not members, so they are not inherited by subclasses, but the
constructor of the superclass can be invoked from the subclass.
The super keyword is similar to this keyword following are the scenarios where the super
keyword is used. It is used to differentiate the members of superclass from the members of
subclass, if they have same names. It is used to invoke the superclass constructor from subclass.
184
Chapter Four: Object Oriented Programming Concepts
If a class is inheriting the properties of another class. And if the members of the superclass
have the names same as the sub class, to differentiate these variables we use super keyword as
shown below.
super.variable
super.method();
Sample Code
This section provides you a program that demonstrates the usage of the super keyword.
In the given program you have two classes namely Sub_class and Super_class, both have a
method named display with different implementations, and a variable named num with
different values. We are invoking display method of both classes and printlng the value of the
variable num of both classes, here you can observe that we have used super key word to
differentiate the members of super class from sub class.
class Super_class
{
int num =20; //display method of superclass
public void display()
{
System .out.println("This is the display method of
superclass");
}
}
public class Sub_class extends Super_class
{
int num =10; //display method of sub class
public void display()
{
System .out.println("This is the display method of
subclass");
}
public void my_method()
{
//Instantiating subclass
185
Chapter Four: Object Oriented Programming Concepts
Compile and execute the above code using the following syntax.
javac Super_Demo
java Super
If a class is inheriting the properties of another class, the subclass automatically acquires the
default constructor of the super class. But if you want to call a parametrized constructor of the
super class, you need to use the super keyword as shown below.
186
Chapter Four: Object Oriented Programming Concepts
super(values);
Sample Code
The program given in this section demonstrates how to use the super keyword to invoke the
parametrized constructor of the superclass. This program contains a super class and a sub class,
where the super class contains a parametrized constructor which accepts a string value, and we
used the super keyword to invoke the parametrized constructor of the super class.
Copy and paste the below given program in a file with name Subclass.java
class Superclass
{
int age;
Superclass(int age)
{
this.age=age;
}
public void getAge()
{
System .out.println("The value of the variable nam ed
age in super class is: " +age);
}
}
public class Subclass extends Superclass
{
Subclass(int age)
{
super(age);
}
public static void m ain(String argd[])
{
Subclass s= new Subclass(24);
s.getAge();
}
}
187
Chapter Four: Object Oriented Programming Concepts
Compile and execute the above code using the following syntax.
javac Subclass
java Subclass
4.2. Encapsulation
Encapsulation is a programming mechanism that binds together code and the data it
manipulates, and that keeps both safe from outside interference and misuse. In an object-
oriented language, code and data can be bound together in such a way that a self-contained
black box is created. Within the box are all necessary data and code. When code and data are
linked together in this fashion, an object is created. In other words, an object is the device that
supports encapsulation.
Within an object, code, data, or both may be private to that object or public. Private code or
data is known to and accessible by only another part of the object. That is, private code or data
cannot be accessed by a piece of the program that exists outside the object. When code or data
is public, other parts of your program can access it even though it is defined within an object.
Typically, the public parts of an object are used to provide a controlled interface to the private
elements of the object. Java’s basic unit of encapsulation is the class.
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data variables and code acting on the
data methods together as as single unit. In encapsulation the variables of a class will be hidden
from other classes, and can be accessed only through the methods of their current class,
therefore it is also known as data hiding.
• Provide public setter and getter methods to modify and view the variables values.
Example:
188
Chapter Four: Object Oriented Programming Concepts
189
Chapter Four: Object Oriented Programming Concepts
The public setXXX and getXXX methods are the access points of the instance variables of the
EncapTest class. Normally, these methods are referred as getters and setters. Therefore any
class that wants to access the variables should access them through these getters and setters.
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. A class can change the
data type of a field and users of the class do not need to change any of their code.
190
Chapter Four: Object Oriented Programming Concepts
191
Chapter Four: Object Oriented Programming Concepts
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance. (File: TestInheritance2.java)
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
192
Chapter Four: Object Oriented Programming Concepts
4. If data members are private, what can we do to access them from the class object?
a) Private data members can never be accessed from outside the class
b) Create public member functions to access those data members
c) Create private member functions to access those data members
d) Create protected member functions to access those data members
5. If in multiple inheritance, class C inherits class B, and Class B inherits class A. In
which sequence are their destructors called if an object of class C was declared?
a) ~A() then ~B() then ~C()
b) ~C() then ~A() then ~B()
c) ~C() then ~B() then ~A()
d) ~B() then ~C() then ~A()
a) Polymorphism c) Inheritance
b) Overloading d) Abstraction
193
Chapter Four: Object Oriented Programming Concepts
1. Write a Java program to create a class called BankAccount with private instance variables
accountNumber and balance. Provide public getter and setter methods to access and modify
these variables.
2. Write a Java program to create a class called Employee with private instance variables
employee_id, employee_name, and employee_salary. Provide public getter and setter
methods to access and modify the id and name variables, but provide a getter method for
the salary variable that returns a formatted string.
194
Chapter Four: Object Oriented Programming Concepts
4.3. Polymorphism
4.3.1. Method overloading and overriding
Polymorphism (from Greek, meaning “many forms”) is the quality that allows one interface to
access a general class of actions. The specific action is determined by the exact nature of the
situation. A simple example of polymorphism is found in the steering wheel of an automobile.
The steering wheel (i.e., the interface) is the same no matter what type of actual steering
mechanism is used. That is, the steering wheel works the same whether your car has manual
steering, power steering, or rack-and- pinion steering. Therefore, once you know how to
operate the steering wheel, you can drive any type of car.
The same principle can also apply to programming. For example, consider a stack (which is a
first-in, last-out list). You might have a program that requires three different types of stacks.
One stack is used for integer values, one for floating-point values, and one for characters. In
this case, the algorithm that implements each stack is the same, even though the data being
stored differs. In a non-object-oriented language, you would be required to create three
different sets of stack routines, with each set using different names. However, because of
polymorphism, in Java you can create one general set of stack routines that works for all three
specific situations. This way, once you know how to use one stack, you can use them all.
More generally, the concept of polymorphism is often expressed by the phrase “one interface,
multiple methods.” This means that it is possible to design a generic interface to a group of
related activities. Polymorphism helps reduce complexity by allowing the same interface to be
used to specify a general class of action. It is the compiler’s job to select the specific action
(i.e., method) as it applies to each situation. You, the programmer, don’t need to do this
selection manually. You need only remember and utilize the general interface. Plays an
important role in allowing objects having different internal structures to share the same external
interface.
195
Chapter Four: Object Oriented Programming Concepts
Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs. So, we perform method overloading to
figure out the program quickly.
In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
196
Chapter Four: Object Oriented Programming Concepts
Output:
22
33
In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
Q) Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
197
Chapter Four: Object Oriented Programming Concepts
Output:
Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler
time error if you declare the same method having same parameters.
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:
class TestOverloading4{
public static void main(String[]
args){System.out.println("main with String[]");}
public static void main(String
args){System.out.println("main with String");}
public static void main(){System.out.println("main
without args");}
}
Output:
One type is promoted to another implicitly if no matching datatype is found. Let's understand
the concept by the figure given below:
As displayed in the diagram below, byte can be promoted to short, int, long, float or double.
The short datatype can be promoted to int,long,float or double. The char datatype can be
promoted to int,long,float or double and so on.
198
Chapter Four: Object Oriented Programming Concepts
class OverloadingCalculation1{
void sum(int a,long b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
OverloadingCalculation1 obj=new
OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be
promoted to long
obj.sum(20,20,20);
}
}
199
Chapter Four: Object Oriented Programming Concepts
Output:
40
60
If there are matching type arguments in the method, type promotion is not performed.
class OverloadingCalculation2
{
void sum(int a,int b)
{System.out.println("int arg method
invoked");}
void sum(long a,long b)
{System.out.println("long arg method
invoked");}
public static void main(String args[])
{
OverloadingCalculation2 obj=new
OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
Output:
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
class OverloadingCalculation3{
void sum(int a,long b){System.out.println("a method
invoked");}
void sum(long a,int b){System.out.println("b method
invoked");}
public static void main(String args[]){
200
Chapter Four: Object Oriented Programming Concepts
OverloadingCalculation3 obj=new
OverloadingCalculation3();
obj.sum(20,20);//now ambiguity
}
}
Output:
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
Let's understand the problem that we may face in the program if we don't use method overriding.
201
Chapter Four: Object Oriented Programming Concepts
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Output:
Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.
In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method are the same,
and there is IS-A relationship between the classes, so there is method overriding.
202
Chapter Four: Object Oriented Programming Concepts
Output:
Consider a scenario where Bank is a class that provides functionality to get the rate of interest.
However, the rate of interest varies according to banks. For example, SBI, ICICI and AXIS
banks could provide 8%, 7%, and 9% rate of interest.
203
Chapter Four: Object Oriented Programming Concepts
int getRateOfInterest()
{
return 0;
}
} //Creating child classes.
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest:
"+s.getRateOfInterest()); System.out.println("ICICI
204
Chapter Four: Object Oriented Programming Concepts
Output:
It is because the static method is bound with class whereas instance method is bound with an
object. Static belongs to the class area, and an instance belongs to the heap area.
No, because the main is a static method. Method Overloading in Java with examples
A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body). Before learning the Java
abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality
to the user. Another way, it shows only essential things to the user and hides the internal details,
for example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
205
Chapter Four: Object Oriented Programming Concepts
2. Interface (100%)
A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
Points to Remember:
• It cannot be instantiated.
• It can have final methods which will force the subclass not to change the body of the
method.
206
Chapter Four: Object Oriented Programming Concepts
A method which is declared as abstract and does not have implementation is known as an
abstract method.
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
OutPut
running safely
In this example, Shape is the abstract class, and its implementation is provided by the Rectangle
and Circle classes.
Mostly, we don't know about the implementation class (which is hidden to the end user), and
an object of the implementation class is provided by the factory method.
207
Chapter Four: Object Oriented Programming Concepts
A factory method is a method that returns the instance of the class. We will learn about the
factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class
will be invoked.
File: TestAbstraction1.java
Output
drawing circle
File: TestBank.java
AD
208
Chapter Four: Object Oriented Programming Concepts
Output
An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.
File: TestAbstraction2.java
209
Chapter Four: Object Oriented Programming Concepts
Output
bike is created
running safely..
gear changed
1. class Bike12{
2. abstract void run();
3. }
Output
Rule: If you are extending an abstract class that has an abstract method, you must either provide
the implementation of the method or make this class abstract.
210
Chapter Four: Object Oriented Programming Concepts
The abstract class can also be used to provide some implementation of the interface. In such
case, the end user may not be forced to override all the methods of the interface.
Note: If you are beginner to java, learn interface first and skip this example.
interface A{
void a();
void b();
void c();
void d();
}
abstract class B implements A{
public void c(){System.out.println("I am c");}
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
a.d();
}}
Output
I am a
I am b
I am c
I am d
211
Chapter Four: Object Oriented Programming Concepts
Write a Java program to create a class known as "BankAccount" with methods called deposit()
and withdraw(). Create a subclass called SavingsAccount that overrides the withdraw() method
to prevent withdrawals if the account balance falls below one hundred.
Sample Solution:
Java Code:
// BankAccount.java
// Parent class BankAccount
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double
balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient balance");
}
}
public double getBalance() {
return balance;
}
}
// SavingsAccount.java
// Child class SavingsAccount
212
Chapter Four: Object Oriented Programming Concepts
213
Chapter Four: Object Oriented Programming Concepts
System.out.println("Withdraw $600
from account BA1234:");
BA1234.withdraw(600);
System.out.println("New balance after
withdrawing $600: $" + BA1234.getBalance());
// Create a SavingsAccount object (A/c No.
"SA1234") with initial balance of $450
System.out.println("\nCreate a
SavingsAccount object (A/c No. SA1234) with initial
balance of $450:");
SavingsAccount SA1234 = new
SavingsAccount("SA1234",450);
// Withdraw $300 from SA1234
SA1234.withdraw(300);
System.out.println("Balance after trying to
withdraw $300: $" + SA1234.getBalance());
// Create a SavingsAccount object
(A/c No. "SA1000") with initial balance of $300
System.out.println("\nCreate a
SavingsAccount object (A/c No. SA1000) with initial
balance of $300:");
SavingsAccount SA1000 = new
SavingsAccount("SA1000",300);
// Withdraw $250 from SA1000 (balance falls
below $100)
System.out.println("Try to withdraw
$250 from SA1000!");
SA1000.withdraw(250);
System.out.println("Balance after trying to
withdraw $250: $" + SA1000.getBalance());
}
}
214
Chapter Four: Object Oriented Programming Concepts
Sample Output:
Create a Bank Account object (A/c No. BA1234) with initial balance of $500:
Create a SavingsAccount object (A/c No. SA1234) with initial balance of $450:
Create a SavingsAccount object (A/c No. SA1000) with initial balance of $300:
Explanation:
The BankAccount class has a constructor that takes account number and balance as arguments.
It also has methods to deposit and withdraw money, and to check the account balance. The
SavingsAccount class is a subclass of BankAccount and overrides the withdraw() method. It
checks if the account balance falls below one hundred before allowing a withdrawal. The
method prints an error message if the balance is below one hundred. If the balance is greater
than or equal to one hundred, the method calls the withdraw() method of the superclass to
withdraw.
In Main() method -
The main method begins by creating an instance of the BankAccount class with an account
number of "BA1234" and an initial balance of $500. It then deposits $1000 into the account
and displays the new balance. It then withdraws $600 from the account and displays the new
balance.
215
Chapter Four: Object Oriented Programming Concepts
Next, the method creates an instance of the SavingsAccount class with an account number of
"SA1234" and an initial balance of $450. It then attempts to withdraw $300 from the account
and displays the new balance. Since the balance remains above the minimum $150 balance
required for the account, the withdrawal is successful.
Finally, the method creates another instance of the SavingsAccount class with an account
number of "SA1000" and an initial balance of $300. It then attempts to withdraw $250 from
the account, which would bring the balance below the minimum balance required for the
account. The method displays the new balance after the attempted withdrawal, which should
still be $300 since the withdrawal was unsuccessful.
216
Chapter Four: Object Oriented Programming Concepts
b) Member functions having the same name and different signature inside main
function
c) Member functions having the same name in base and derived classes
a) Polymorphism
b) Encapsulation
c) Abstraction
d) Inheritance
a) Virtual Function
b) Inline function
c) Enclosing class
d) Nested class
in any language?
a) Function Overloading
b) Function Overriding
c) Operator Overloading
d) Operator Overriding
217
Chapter Four: Object Oriented Programming Concepts
1. Write a Java program to create a class known as Person with methods called getFirstName()
and getLastName(). Create a subclass called Employee that adds a new method named
getEmployeeId() and overrides the getLastName() method to include the employee's job
title.
2. Write a Java program to create a class Employee with a method called calculateSalary().
Create two subclasses Manager and Programmer. In each subclass, override the
calculateSalary() method to calculate and return the salary based on their specific roles.
218
Chapter Four: Object Oriented Programming Concepts
Reference
1. Java: A Beginner's Guide, Eighth Edition by Herbert Schildt
2. Java: How to Program, 9th Edition (Deitel)
3. https://www.javatpoint.com/
219
Chapter Five: Exception Handling in Java
Lesson Plan
1. Learning objectives
•
2. Motivation
5. Practice contents/Activities/Safety
Active practice; on java input and output, writing (Editing), compiling, interprating.
6. Assessments
7. Clean-up
9. Review/Reflection
• Review the outcome of the practice, improvement measure and previous reflected
opinions.
221
Chapter Five: Exception Handling in Java
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of
a program, i.e. at run time, that disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object. It contains information
about the exception, such as the name and description of the exception and the state of the
program when the exception occurred.
An Exception can be anything which interrupts the normal flow of the program. When an
exception occurs program processing gets terminated and doesn’t continue further. In such
cases we get a system generated error message. The good thing about exceptions is that they
can be handled.
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that
222
Chapter Five: Exception Handling in Java
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be
executed. If we perform exception handling, the rest of the statement will be executed.
That is why we use exception handling in Java.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions. Few examples –
• DivideByZero exception
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException
223
Chapter Five: Exception Handling in Java
• It also gives us the scope of organizing and differentiating between different error types
using a separate block of codes. This is done with the help of try-catch blocks.
If an exception is raised, which has not been handled by programmer then program execution
can get terminated and system prints a non user friendly error message.
For a beginner user the above message won’t be easy to understand. In order to let them know
that what went wrong we use exception handling in java program. We handle such conditions
and then prints a user friendly warning message to user, which lets them correct the error as
most of the time exception occurs due to bad data provided by user.
Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally.
It means, we can't use try block alone.
224
Chapter Five: Exception Handling in Java
catch The "catch" block is used to handle the exception. It must be preceded
by try block which means we can't use catch block alone. It can be
followed by finally block later.
finally The "finally" block is used to execute the important code of the program.
It is executed whether an exception is handled or not.
Let's see an example of Java Exception Handling where we using a try-catch statement to
handle the exception.
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
225
Chapter Five: Exception Handling in Java
226
Chapter Five: Exception Handling in Java
System.out.println(e);
}
System.out.println("rest of the code");
}
Output:
java.lang.ArithmeticException: / by zero
In this example, we also kept the code in a try block that will not throw an exception.
public class TryCatchExample3 {
227
Chapter Five: Exception Handling in Java
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will not
execute.
Let's see an example to resolve the exception in a catch block.
public class TryCatchExample6 {
System.out.println(i/(j+2));
}
}
}
Output:
25
228
Chapter Five: Exception Handling in Java
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw except
ion
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
Output:
java.lang.ArrayIndexOutOfBoundsException: 10
PrintWriter pw;
try {
pw = new PrintWriter("jtp.txt"); //may thro
w exception
pw.println("saved");
229
Chapter Five: Exception Handling in Java
}
// providing the checked exception handler
catch (FileNotFoundException e) {
System.out.println(e);
}
System.out.println("File saved successfully");
}
}
Output:
The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:
230
Chapter Five: Exception Handling in Java
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Example 1
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Excep
tion occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfB
ounds Exception occurs");
}
catch(Exception e)
231
Chapter Five: Exception Handling in Java
{
System.out.println("Parent Exception
occurs");
}
System.out.println("rest of the code");
}
}
Arithmetic Exception occurs
rest of the code
Example 2
try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Excep
tion occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfB
ounds Exception occurs");
}
catch(Exception e)
{
232
Chapter Five: Exception Handling in Java
System.out.println("Parent Exception
occurs");
}
System.out.println("rest of the code");
}
}
Output:
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
....
try
{
statement 1; statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
233
Chapter Five: Exception Handling in Java
{
}
....
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out
.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
235
Chapter Five: Exception Handling in Java
Output:5
4) Throw is used within the method. Throws is used with the method
signature.
236
Chapter Five: Exception Handling in Java
In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
237
Chapter Five: Exception Handling in Java
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
//method code
}
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exc
eption
}
void n()throws IOException{
m();
}
238
Chapter Five: Exception Handling in Java
void p(){
try{
n();
}catch(Exception e){System.out.println("exception ha
ndled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
5.6. Java Custom Exception
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
Let's see a simple example of java custom exception.
239
Chapter Five: Exception Handling in Java
System.out.println("welcome to vote");
}
240
Chapter Five: Exception Handling in Java
Example 1:
TryCatchExample1.java
Output:
Example 2:
TryCatchExample2.java
241
Chapter Five: Exception Handling in Java
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
As displayed in the above example, the rest of the code is executed, i.e., the rest of the
code statement is printed.
Example 3:
In this example, we also kept the code in a try block that will not throw an exception.
TryCatchExample3.java
242
Chapter Five: Exception Handling in Java
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will not
execute.
Example 4
Output:
java.lang.ArithmeticException: / by zero
243
Chapter Five: Exception Handling in Java
I. Practical
1. Write a Java program that throws an exception and catch it using a try-catch
block.
2. Write a Java program to create a method that takes an integer as a parameter and
throws an exception if the number is odd.
3. Write a Java program to create a method that reads a file and throws an exception
if the file is not found.
4. Write a Java program that reads a list of numbers from a file and throws an
exception if any of the numbers are positive.
5. Write a Java program that reads a file and throws an exception if the file is empty.
6. Write a Java program that reads a list of integers from the user and throws an
exception if any
244
Chapter Five: Exception Handling in Java
Exceptions are the unwanted errors or bugs or events that restrict the normal execution of a
program. Each time an exception occurs, program execution gets disrupted. An error message
is displayed on the screen.
245
Chapter Five: Exception Handling in Java
There are several reasons behind the occurrence of exceptions. These are some conditions
where an exception occurs:
The parent class of all the exception classes is the java.lang.Exception class. The Figure below
illustrates the different types of Java exceptions.
Exception class, it is a subclass of the built-in Throwable class. There is another subclass
which is derived from the Throwable class i.e. Error as illustrated in Figure 1. The error can
be defined as an abnormal condition that indicates something has gone wrong with the
execution of the program. These are not handled by Java programs.
There are some important methods available in the Throwable class which are as follows:
• public String getMessage() – Provides information about the exception that has
occurred through a message, which is initialized in the Throwable constructor.
246
Chapter Five: Exception Handling in Java
by a Throwable object.
• public void printStackTrace() – Used to display the output of toString() along with
the stack trace to System.err (error output stream).
1. Checked exception
2. Unchecked exception
To illustrate the concept of checked exception, let us consider the following code snippet:
import java.io.*;
class demo1 {
public static void main(String args[]) {
FileInputStream input1 = null;
/* FileInputStream(File filename) is a
constructor that will throw
* FileNotFoundException (a checked
exception)
*/
input1 = new FileInputStream("D:/file.txt");
int m;
System.out.print((char)m);
}
// The close() will close the file input
stream, and it will also throw a exception
input1.close();
}
}
Output:
throw keyword
It is clearly displayed in the output that the program throws exceptions during the compilation
process. There are two methods of resolving such issues. You can declare the exception with
the help of the throw keyword.
import java.io.*;
class demo1 {
public static void main(String args[]) throws
IOException {
FileInputStream input1 = null;
input1 = new FileInputStream("D:/file.txt");
int m;
while ((m = input1.read()) != -1) {
System.out.print((char)m);
}
input1.close();
}
}
248
Chapter Five: Exception Handling in Java
Output:
try-catch block
Apart from the above-mentioned method, there is another way to resolve exceptions. You can
manage them with the help of try-catch blocks.
import java.io.*;
class demo1 {
public static void main(String args[]) {
FileInputStream input1 = null;
try {
input1 = new
FileInputStream("D:/file.txt");
} catch(FileNotFoundException input2) {
system.out.println("The file does not " +
"exist at the location");
}
int m;
try {
while((m = input1.read()) != -1) {
System.out.print((char)m);
}
input1.close();
} catch(IOException input3) {
system.out.println("I/O error occurred: "+
input3);
}
}
}
249
Chapter Five: Exception Handling in Java
Output:
The code will run smoothly and the file will be displayed.
SQLException
This type of exception occurs while executing queries on a database related to the SQL syntax.
For example, consider the following code snippet:
Output:
IOException
This type of exception occurs while using file I/O stream operations. For example, consider the
following code snippet:
250
Chapter Five: Exception Handling in Java
import java.io.*;
public class sample_IOException {
private static String filepath =
"D:\User\guest\Desktop\File2.txt";
Output:
251
Chapter Five: Exception Handling in Java
ClassNotFoundException
This type of exception is thrown when the JVM is not able to find the required class. It may be
due to a command-line error, a classpath issue, or a missing .class file. For example, consider
the following code snippet:
Output:
InvocationTargetException
This type of exception wraps an exception thrown by an invoked method or a constructor. The
thrown exception can be accessed with the help of the getTargetException method. For
example, consider the following code snippet:
package main.samplejava;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Example {
@SuppressWarnings("unused")
252
Chapter Five: Exception Handling in Java
253
Chapter Five: Exception Handling in Java
System.out.format("Invocation of %s
failed because of: %s%n",
methodName,
cause.getMessage());
}
}
} catch (ClassNotFoundException |
InstantiationException | IllegalAccessException ex) {
System.err.println("The following exception
was thrown:");
ex.printStackTrace();
}
}
}
Output:
Invoking testMethod()
Invocation of testMethod failed because of: The string must contain at least one character!
Output:
To illustrate the concept of an unchecked exception, let us consider the following code snippet:
import java.util.Scanner;
public class Sample_RunTimeException {
public static void main(String[] args) {
254
Chapter Five: Exception Handling in Java
Output 1:
Output 2:
at exceptiondemo.sample_runtimedemo.main(Sample_RunTimeExceptionDemo.java:11)
255
Chapter Five: Exception Handling in Java
NullPointerException
This type of exception occurs when you try to access an object with the help of a reference
variable whose current value is null or empty. For example, consider the following code snippet:
Output:
ArrayIndexOutofBound
This type of exception occurs when you try to access an array with an invalid index value. The
value you are providing is either negative or beyond the length of the array.
256
Chapter Five: Exception Handling in Java
Output:
IllegalArgumentException
This type of exception occurs whenever an inappropriate or incorrect argument is passed to a
method. For example, if a method is defined with non-empty string as parameters. But you are
providing null input strings. Then, the IllegalArgumentException is thrown to indicate the user
that you cannot pass a null input string to the method.
import java.io.File;
public class Sample_IllegalArgumentException {
public static String createRelativePath(String par,
String f_name) {
if (par == null)
throw new IllegalArgumentException("You
cannot provide null parent path!");
if (f_name == null)
throw new IllegalArgumentException("Please
enter the complete filename!");
return par + File.separator + f_name;
}
public static void main(String[] args) {
// This command will be successfully executed.
system.out.println(IllegalArgumentExceptionExample.crea
teRelativePath("dir1", "file1"));
system.out.println();
257
Chapter Five: Exception Handling in Java
System.out.println(IllegalArgumentExceptionExample.crea
teRelativePath(null, "file1"));
}
}
Output:
IllegalStateException
This type of exception occurs when the state of the environment does not match the operation
being executed. For example, consider the following code snippet, which demonstrates this
type of exception:
/**
* This code will publish the current book.
* If the book is already published, it will throw an
IllegalStateException.
**/
public void pub() throws IllegalStateException {
Date pub_at = getPub_at();
if (pub_at == null) {
setPub_at(new Date());
Logging.log(String.format("Published '%s'
by %s.", getTitle(), getAuthor()));
} else {
throw new IllegalStateException(
String.format("Cannot publish '%s' by %s
(already published on %s).",
getTitle(), getAuthor(), pub_at));
}
}
Output:
258
Chapter Five: Exception Handling in Java
If a publication date already exists in the System. then it will produce an IllegalStateException
that indicates that the book cannot be published again.
NumberFormatException
This type of exception occurs when you pass a string to a method that cannot be converted to
a number. For example, consider the following code snippet:
Output:
ArithmeticException
This type of exception occurs when you perform an incorrect arithmetic operation. For example,
if you divide any number by zero, it will display such an exception. Let us consider the
following code snippet:
259
Chapter Five: Exception Handling in Java
Output:
Java defines several types of exceptions that relate to its various class libraries. Java also allows
users to define their own exceptions.
260
Chapter Five: Exception Handling in Java
Write a Java program to create a method that takes an integer as a parameter and throws an exception
if the number is odd.
Sample Solution:
Java Code:
int n = 18;
trynumber(n);
n = 7;
trynumber(n);
try {
checkEvenNumber(n);
} catch (IllegalArgumentException e) {
if (number % 2 != 0) {
261
Chapter Five: Exception Handling in Java
odd.");
Sample Output:
18 is even.
Error: 7 is odd.
Explanation:
• In the main method, an integer n is declared and assigned 18. The trynumber method is then
called with n as an argument.
• The trynumber method handles the exception. It contains a try-catch block. Inside the try block,
the method checkEvenNumber is called, passing n as an argument. If the number is even, the
message "[number] is even." is printed.
• If an exception occurs in the try block, it is caught by the catch block, which handles
IllegalArgumentException. In this case, the error message "Error: [exception message]" is
printed.
• After the first call to trynumber(n), the value of n is updated to 7, and the trynumber method is
called again. This time, since 7 is an odd number, an exception is thrown.
• The checkEvenNumber method checks if a given number is even or odd. If the number is odd,
it throws an IllegalArgumentException with the message "[number] is odd."
262
Chapter Five: Exception Handling in Java
b) catch
c) try
d) finally
b) To specify the code that is always executed, regardless of whether an exception occurs or not
d) To specify the code that is executed after the try block but before any catch block
c) The process of passing an exception from one method to its calling method
263
Chapter Five: Exception Handling in Java
A. ArrayIndexOutOfBoundsException
B. ClassCastException
C. IllegalArgumentException
D. NumberFormatException
E. None of the above.
7. Which of the following are checked exceptions? (Choose all that apply)
A. Exception
B. IllegalArgumentException
C. IOException
D. NullPointerException
E. NumberFormatException
F. StackOverflowError
A. Compiler Error
264
Chapter Five: Exception Handling in Java
9. Which of the following exceptions are thrown by the JVM? (Choose all that apply)
A. ArrayIndexOutOfBoundsException
B. ExceptionInInitializerError
C. java.io.IOException
D. NullPointerException
E. NumberFormatException
A. Starting up
B. Starting up Problem
C. Starting up Problem Shutting down
D. Starting up Shutting down
E. The code does not compile.
F. An uncaught exception is thrown
265
Chapter Five: Exception Handling in Java
Reference
1. Java: A Beginner's Guide, Eighth Edition by Herbert Schildt
2. Java: How to Program, 9th Edition (Deitel)
3. https://www.javatpoint.com/
266
Chapter Five: Exception Handling in Java
267
Chapter Six: AWT, Swing and Java Applets
Lesson Plan
1. Learning objectives
• Iintroduction to Swing
5. Practice contents/Activities/Safety
Active practice; on java input and output, writing (Editing), compiling, interprating.
6. Assessments
268
Chapter Six: AWT, Swing and Java Applets
7. Clean-up
9. Review/Reflection
• Review the outcome of the practice, improvement measure and previous reflected
opinions.
269
Chapter Six: AWT, Swing and Java Applets
6.1 Introduction
All of the programs in this book have been console-based. This means that they do not make
use of a graphical user interface (GUI). Although console-based programs are excellent for
teaching the basics of Java and for some types of programs, such as server- side code, most
real-world client applications will be GUI-based. At the time of this writing, the most widely
used Java GUI is Swing.
Swing defines a collection of classes and interfaces that support a rich set of visual components,
such as buttons, text fields, scroll panes, check boxes, trees, and tables, to name a few.
Collectively, these controls can be used to construct powerful, yet easy-to- use graphical
interfaces. Because of its widespread use, Swing is something with which all Java programmers
should be familiar. Therefore, this chapter provides an introduction to this important GUI
framework.
It is important to state at the outset that Swing is a very large topic that requires an entire book
of its own. It then introduces five commonly used Swing components: the label, push button,
text field, checkbox, and list.
Swing did not exist in the early days of Java. Rather, it was a response to deficiencies present
in Java’s original GUI subsystem: the Abstract Window Toolkit (AWT). The AWT defines a
basic set of components that support a usable, but limited, graphical interface. One reason for
the limited nature of the AWT is that it translates its various visual components into their
corresponding, platform-specific equivalents, or peers. This means that the look and feel of an
AWT component is defined by the platform, not by Java. Because the AWT components use
native code resources, they are referred to as heavyweight.
The use of native peers led to several problems. First, because of differences between operating
systems, a component might look, or even act, differently on different platforms. This potential
variability threatened the overarching philosophy of Java: write once, run anywhere. Second,
the look and feel of each component was fixed (because it is defined by the platform) and could
not be (easily) changed. Third, the use of heavyweight components caused some frustrating
restrictions. For example, a heavyweight component was always opaque.
270
Chapter Six: AWT, Swing and Java Applets
Not long after Java’s original release, it became apparent that the limitations and restrictions
present in the AWT were sufficiently serious that a better approach was needed. The solution
was Swing. Introduced in 1997, Swing was included as part of the Java Foundation Classes
(JFC). Swing was initially available for use with Java 1.1 as a separate library. However,
beginning with Java 1.2, Swing (and the rest of JFC) was fully integrated into Java.
Swing addresses the limitations associated with the AWT’s components through the use of two
key features: lightweight components and a. pluggable look and feel. Although they are largely
transparent to the programmer, these two features are at the foundation of Swing’s design
philosophy and the reason for much of its power and flexibility. Let’s look at each.
With very few exceptions, Swing components are lightweight. This means that a component is
written entirely in Java. They do not rely on platform-specific peers. Lightweight components
have some important advantages, including efficiency and flexibility. Furthermore, because
lightweight components do not translate into platform-specific peers, the look and feel of each
component is determined by Swing, not by the underlying operating system. This means that
each component can work in a consistent manner across all platforms.
Note that Swing does not replace the AWT. Rather, Swing builds upon the foundation provided
by aspects of the AWT. Thus, portions of the AWT are still a crucial part of Java. Although
knowledge of the AWT is not required by this chapter, you need a solid understanding of its
structure and features if you seek full Swing mastery.
6.2 AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavy weight i.e. its components are using the resources of
underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in simple and easy
steps.
271
Chapter Six: AWT, Swing and Java Applets
Java AWT calls the native platform calls the native platform (operating systems) subroutine
for creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have
different look and feel for the different platforms like Windows, MAC OS, and Unix. The
reason for this is the platforms have different view for their native components and AWT
directly calls the native subroutine that creates those components.
In simple words, an AWT application will look like a windows application in Windows OS
whereas it will look like a Mac application in the MAC OS.
All the elements like the button, text fields, scroll bars, etc. are called components. In Java
AWT, there are classes for each component as shown in above diagram. In order to place every
component in a particular position on a screen, we need to add them to a container.
272
Chapter Six: AWT, Swing and Java Applets
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can add a
container inside container.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window. We need to create an instance of Window class to
create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have
other components like button, text field, scrollbar etc. Frame is most widely used container
while developing an AWT application.
273
Chapter Six: AWT, Swing and Java Applets
Method Description
public void setSize(int width,int height) Sets the size (width and height) of the
component.
public void setLayout(LayoutManager Defines the layout manager for the component.
m)
274
Chapter Six: AWT, Swing and Java Applets
b.setBounds(30,100,80,30);
// adding button into frame
add(b);
// frame size 300 width and 300 height
setSize(300,300);
// setting the title of Frame
setTitle("This is our basic AWT example");
// no layout manager
setLayout(null);
// now frame will be visible, by default it is no
t visible
setVisible(true);
}
// main method
public static void main(String args[]) {
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above example
that sets the position of the awt button.
Output:
275
Chapter Six: AWT, Swing and Java Applets
276
Chapter Six: AWT, Swing and Java Applets
Output:
277
Chapter Six: AWT, Swing and Java Applets
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods.
For example:
• Button
o public void addActionListener(ActionListener a){}
• MenuItem
o public void addActionListener(ActionListener a){}
• TextField
278
Chapter Six: AWT, Swing and Java Applets
1. Within class
2. Other class
3. Anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
279
Chapter Six: AWT, Swing and Java Applets
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.
280
Chapter Six: AWT, Swing and Java Applets
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
281
Chapter Six: AWT, Swing and Java Applets
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
282
Chapter Six: AWT, Swing and Java Applets
To perform an action on a button being pressed and released, the ActionListener interface
needs to be implemented. The registered new listener can receive events from the button by
calling addActionListener method of the button. The Java application can use the button's
action command as a messaging protocol.
2. Button (String text) It constructs a new button with given string as its label.
1. void setText (String text) It sets the string message on the button
3. void setLabel (String label) It sets the label of button with the specified
string.
283
Chapter Six: AWT, Swing and Java Applets
11. protected String paramString() It returns the string which represents the
state of button.
12. protected void processActionEvent It process the action events on the button
(ActionEvent e) by dispatching them to a registered
ActionListener object.
15. void setActionCommand(String It sets the command name for the action
command) event given by the button.
Note: The Button class inherits methods from java.awt.Component and java.lang.Object
classes.
284
Chapter Six: AWT, Swing and Java Applets
ButtonExample.java
// importing necessary libraries
import java.awt.*;
import java.awt.event.*;
public class ButtonExample3 {
public static void main(String[] args) {
// create instance of frame with the label
Frame f = new Frame("Button Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
// create instance of button with label
Button b=new Button("Click Here");
// set the position for the button in frame
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
tf.setText("Welcome to Javatpoint.");
}
});
// adding button the frame
f.add(b);
// adding textfield the frame
f.add(tf);
// setting size, layout and visibility
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
285
Chapter Six: AWT, Swing and Java Applets
3. Label(String text, int It constructs a label with the specified string and the
alignement) specified alignment.
1. void setText(String text) It sets the texts for label with the specified text.
286
Chapter Six: AWT, Swing and Java Applets
2. void setAlignment(int alignment) It sets the alignment for label with the
specified alignment.
7. protected String paramString() It returns the string the state of the label.
Method inherited
The above methods are inherited by the following classes:
• java.awt.Component
• java.lang.Object
In the following example, we are creating the objects of TextField, Label and Button classes
and adding them to the Frame. Using the actionPerformed() method an event is generated over
the button. When we add the website in the text field and click on the button, we get the IP
address of website.
LabelExample2.java
import java.awt.*;
import java.awt.event.*;
// creating class which implements ActionListener interface
and inherits Frame class
public class LabelExample2 extends Frame implements ActionLi
stener{
// creating objects of TextField, Label and Button class
TextField tf;
287
Chapter Six: AWT, Swing and Java Applets
Label l;
Button b;
// constructor to instantiate the above objects
LabelExample2() {
tf = new TextField();
tf.setBounds(50, 50, 150, 20);
l = new Label();
l.setBounds(50, 100, 250, 20);
b = new Button("Find IP");
b.setBounds(50,150,60,30);
b.addActionListener(this);
add(b);
add(tf);
add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
// defining actionPerformed method to generate an event
public void actionPerformed(ActionEvent e) {
try {
String host = tf.getText();
String ip = java.net.InetAddress.getByName(host).get
HostAddress();
l.setText("IP of "+host+" is: "+ip);
}
catch (Exception ex) {
System.out.println(ex);
}
}
// main method
public static void main(String[] args) {
new LabelExample2();
}
}
288
Chapter Six: AWT, Swing and Java Applets
Output:
2. TextField(String text) It constructs a new text field initialized with the given
string text to be displayed.
289
Chapter Six: AWT, Swing and Java Applets
4. TextField(String text, int It constructs a new text field with the given text and
columns) given number of columns (width).
290
Chapter Six: AWT, Swing and Java Applets
11. Dimension getPreferredSize(int columns) It fetches the preferred size of the text
field with specified number of columns.
17. void setEchoChar(char c) It sets the echo character for text field.
Method Inherited
The AWT TextField class inherits the methods from below classes:
1. java.awt.TextComponent
2. java.awt.Component
3. java.lang.Object
291
Chapter Six: AWT, Swing and Java Applets
TextFieldExample2.java
// importing necessary libraries
import java.awt.*;
import java.awt.event.*;
// Our class extends Frame class and implements ActionListen
er interface
public class TextFieldExample2 extends Frame implements Acti
onListener {
// creating instances of TextField and Button class
TextField tf1, tf2, tf3;
Button b1, b2;
// instantiating using constructor
TextFieldExample2() {
// instantiating objects of text field and button
// setting position of components in frame
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);
tf2 = new TextField();
tf2.setBounds(50, 100, 150, 20);
tf3 = new TextField();
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);
292
Chapter Six: AWT, Swing and Java Applets
b1 = new Button("+");
b1.setBounds(50, 200, 50, 50);
b2 = new Button("-");
b2.setBounds(120,200,50,50);
// adding action listener
b1.addActionListener(this);
b2.addActionListener(this);
// adding components to frame
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
// setting size, layout and visibility of frame
setSize(300,300);
setLayout(null);
setVisible(true);
}
// defining the actionPerformed method to generate an ev
ent on buttons
public void actionPerformed(ActionEvent e) {
String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = 0;
if (e.getSource() == b1){
c = a + b;
}
else if (e.getSource() == b2){
c = a - b;
}
String result = String.valueOf(c);
tf3.setText(result);
}
// main method
public static void main(String[] args) {
293
Chapter Six: AWT, Swing and Java Applets
new TextFieldExample2();
}
}
Output:
294
Chapter Six: AWT, Swing and Java Applets
3. Checkbox(String label, boolean It constructs a checkbox with the given label and
state) sets the given state.
4. Checkbox(String label, boolean It constructs a checkbox with the given label, set
state, CheckboxGroup group) the given state in the specified checkbox group.
295
Chapter Six: AWT, Swing and Java Applets
15. void setLabel(String label) It sets the checkbox's label to the string
argument.
296
Chapter Six: AWT, Swing and Java Applets
297
Chapter Six: AWT, Swing and Java Applets
+ (e.getStateChange()==1?"checked":"unchecke
d"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
Output:
298
Chapter Six: AWT, Swing and Java Applets
• java.awt.Component
• java.lang.Object
2. void addItemListener(ItemListener It adds the item listener that receives item events
l) from the choice menu.
5. String getItem(int index) It gets the item (string) at the given index
position in the choice menu.
299
Chapter Six: AWT, Swing and Java Applets
12. void insert(String item, int index) Inserts the item into this choice at the specified
position.
13. protected String paramString() Returns a string representing the state of this
Choice menu.
15. protected void processItemEvent Processes item events occurring on this Choice
(ItemEvent e) menu by dispatching them to any registered
ItemListener objects.
16. void remove(int position) It removes an item from the choice menu at the
given index position.
17. void remove(String item) It removes the first occurrence of the item from
choice menu.
18. void removeAll() It removes all the items from the choice menu.
300
Chapter Six: AWT, Swing and Java Applets
20. void select(int pos) It changes / sets the selected item in the choice
menu to the item at given index position.
21. void select(String str) It changes / sets the selected item in the choice
menu to the item whose string value is equal to
string specified in the argument.
301
Chapter Six: AWT, Swing and Java Applets
// main method
public static void main(String args[])
{
302
Chapter Six: AWT, Swing and Java Applets
new ChoiceExample2();
}
}
Output:
303
Chapter Six: AWT, Swing and Java Applets
Activity: AWTCounter
Write an AWT GUI application (called AWTCounter) as shown in the Figure. Each time the
"Count" button is clicked, the counter value shall increase by 1.
1. a java.awt.Label "Counter";
2. a non-editable java.awt.TextField to display the counter value; and
3. a java.awt.Button "Count".
The components are placed inside the top-level AWT container java.awt.Frame, arranged in
FlowLayout.
305
Chapter Six: AWT, Swing and Java Applets
306
Chapter Six: AWT, Swing and Java Applets
You have to use control-c, or "close" the CMD shell, or hit the "terminate" button on Eclipse's
Console to terminate the program. This is because the program does not process the
WindowEvent fired by the "window-close" button.
TRY:
1. Modify the program (called AWTCounterDown) to count down, with an initial value of
88, as shown.
2. Modify the program (called AWTFactorial) to display n and factorial of n, as shown.
Clicking the "Next" button shall increase n by 1. n shall begin at 1.
307
Chapter Six: AWT, Swing and Java Applets
308
Chapter Six: AWT, Swing and Java Applets
d. destroy()
309
Chapter Six: AWT, Swing and Java Applets
6.3 Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java. Unlike AWT, Java Swing provides platform-independent and
lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
3) AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.
4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
310
Chapter Six: AWT, Swing and Java Applets
Method Description
311
Chapter Six: AWT, Swing and Java Applets
Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
File: FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButto
n
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
OutPut
312
Chapter Six: AWT, Swing and Java Applets
We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.
File: Simple.java
import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButto
n
b.setBounds(130,100,100, 40);
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
public static void main(String[] args) {
new Simple();
}
}
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets
the position of the button.
We can also inherit the JFrame class, so there is no need to create the instance of JFrame class
explicitly.
import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
313
Chapter Six: AWT, Swing and Java Applets
314
Chapter Six: AWT, Swing and Java Applets
Activity: SwingAdder
Write a Swing application called SwingAdder as shown. The "ADD" button adds the two integers
and display the result. The "CLEAR" button shall clear all the text fields.
Hints: Set the content-pane to 4x2 GridLayout. The components are added from left-to-right,
top-to-bottom.
315
Chapter Six: AWT, Swing and Java Applets
316
Chapter Six: AWT, Swing and Java Applets
setVisible(true);
}
317
Chapter Six: AWT, Swing and Java Applets
1. Modify the above exercise (called SwingArithmetics) to include buttons "+", "-", "*",
"/","%" (remainder) and "CLEAR" as shown.
318
Chapter Six: AWT, Swing and Java Applets
319
Chapter Six: AWT, Swing and Java Applets
12) Which of the following methods is used to set the size of a component?
A. setSize()
B. setPreferredSize()
C. setBounds()
D. setMinimumSize()
13) Which of the following methods is used to set the layout manager of a container?
A. setLayoutManager ()
B. setLayout()
C. setContainerLayout()
D. setComponentLayout()
14) Which of the following methods is used to get the selected item from a JComboBox?
A. getSelectedItem()
B. getSelectedIndex()
C. getItemAt()
D. setSelectedItem()
15) Which of the following methods is used to set the title of a JFrame?
A. setTitle()
B. setLabel()
C. setText()
D. setCaption()
320
Chapter Six: AWT, Swing and Java Applets
16) Which of the following methods is used to create a new JMenuBar object?
A. new JMenuBar()
B. createMenuBar()
C. makeMenuBar()
D. getMenuBar()
17) Which of the following methods is used to add a menu to a JMenuBar object?
A. addMenu()
B. createMenu()
C. makeMenu()
D. add()
18) Which of the following methods is used to create a new JMenuItem object?
A. new JMenuItem()
B. createMenuItem()
C. makeMenuItem()
D. getMenuItem()
19) Which of the following methods is used to add an ActionListener to a JButton object?
A. addAction()
B. addActionListener()
C. addListener()
D. addEventHandler()
20) Which of the following methods is used to display a JOptionPane dialog box?
A. showMessageDialog()
B. showInputDialog()
C. showOptionDialog()
D. showConfirmDialog()
321
Chapter Six: AWT, Swing and Java Applets
6.4 Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
Drawback of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
323
Chapter Six: AWT, Swing and Java Applets
2. public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that create an html file
and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
myapplet.html
324
Chapter Six: AWT, Swing and Java Applets
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.java. Now Html file is not required but
it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
c:\>javac First.java
c:\>appletviewer First.java
325
Chapter Six: AWT, Swing and Java Applets
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw
oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval
with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
326
Chapter Six: AWT, Swing and Java Applets
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
327
Chapter Six: AWT, Swing and Java Applets
picture = getImage(getDocumentBase(),"sonoo.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
In the above example, drawImage() method of Graphics class is used to display the image.
The 4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif");
}
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
try{Thread.sleep(100);}catch(Exception e){}
}
}
328
Chapter Six: AWT, Swing and Java Applets
In the above example, drawImage() method of Graphics class is used to display the image.
The 4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see
the simple example of event handling in applet that prints a message by click on the button.
329
Chapter Six: AWT, Swing and Java Applets
In the above example, we have created all the controls in init() method because it is invoked only once.
myapplet.html
<html>
<body>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</body>
</html>
Signed applets provide a way to verify that the applet is downloaded from a reliable source and
can be trusted to run with the permissions granted in the policy file.
In a Web browser, a Java plug-in provides a common framework and enables secure
deployment of applets in the browser using the JRE. While downloading an applet, the Java
plug-in enables the browser to install all the class files and then render the applet. A security
manager (SecurityManager implementation) will be automatically installed during startup
whenever an applet starts running in a Java-enabled Web browser. No downloaded applets are
allowed to access resources in the client host unless they are explicitly granted permission using
an entry in a Java security policy file.
330
Chapter Six: AWT, Swing and Java Applets
Example below is source code for an applet named WriteFileApplet that attempts to create and
to write to a file named AppletGenrtdFile in the local directory.
Example. WriteFileApplet.java
import java.awt.*;
import java.io.*;
import java.lang.*;
import java.applet.*;
public class WriteFileApplet extends Applet
String myFile = "/tmp/AppletGenrtdFile";
File f = new File(myFile);
DataOutputStream dos;
public void init() {
String osname = System.getProperty("os.name");
if (osname.indexof("Windows") != -1) {
myFile="C:" + file.separator + "AppletGenrtdFile";
}
}
public void paint(Graphics g) {
try {
dos = new DataOutputStream(new BufferedOutputStream
(new FileOutputStream(myFile),128));
dos.writeChars("This is an Applet generated file\n");
dos.flush();
g.drawString("Success: Writing file"
+ myFile, 10, 10);
}
catch (SecurityException se) {
g.drawString("Write Failed: Security exception:
" + se, 10, 10);
}
catch (IOException ioe) {
g.drawString("Write Failed:I/O exception" + ioe, 10, 10);
}
}
}
331
Chapter Six: AWT, Swing and Java Applets
To run the applet, you need to compile the source code using javac and then you may choose
to deploy this applet class along with an HTML page in a Web server. To do so, create an
HTML file (see Example below) called WriteFileApplet.html.
Example. WriteFileApplet.html
<html><head>
<title> Core Security Patterns Example: Applet
Security</title></head><body>
<h1> WriteFileApplet: Writing Files in the Client host </h1>
<hr>
<APPLET CODE = WriteFileApplet.class WIDTH=400 HEIGHT=40>
</APPLET>
<hr></body>
</html>
appletviewer
http://coresecuritypatterns.com/WriteFileApplet.html
When executing this applet, you should receive the SecurityException in the applet window.
This applet shouldn't be able to write the file, because it does not have a security policy with a
file permission to write in the user's home directory.
Now, let's use the following policy file WriteAppletPolicy, which grants a write permission.
To do so, create a policy file (see Example below) called WriteAppletPolicy.policy in the
working directory:
Example. WriteAppletPolicy.policy
grant {
permission java.io.FilePermission "<<ALL FILES>>","write";
};
To test the applet using an appletviewer, you may choose to use the -J-
Djava.security.policy=WriteAppletPolicy.policy option on the JVM command line, or you can
explicitly specify your policy file in the JVM security properties file in the
<JAVA_HOME>/jre/lib/security directory:
policy.url.3=file:/export/xyz/WriteAppletpolicy.policy
332
Chapter Six: AWT, Swing and Java Applets
Example below shows running the WriteFileApplet applet with the WriteAppletPolicy policy
file from the command-line interface.
appletviewer
-J-Djava.security.policy=WriteAppletPolicy.policy
http://coresecuritypatterns.com/WriteFileApplet.html
You should be able to run the WriteFileApplet applet successfully without a SecurityException,
and it should also be able to create and write the file AppletGenrtdFile in the client's local
directory. Now let's explore the concept of signed applets.
Signed Applets
The Java 2 platform introduced the notion of signed applets. Signing an applet ensures that an
applet's origin and its integrity are guaranteed by a certificate authority (CA) and that it can be
trusted to run with the permissions granted in the policy file. The J2SE bundle provides a set
of security tools that allows the end users and administrators to sign applets and applications,
and also to define local security policy. This is done by attaching a digital signature to the
applet that indicates who developed the applet and by specifying a local security policy in a
policy file mentioning the required access to local system resources.
The Java 2 platform requires an executable applet class to be packaged into a JAR file before
it is signed. The JAR file is signed using the private key of the applet creator. The signature is
verified using its public key by the client user of the JAR file. The public key certificate is sent
along with the JAR file to any client recipients who will use the applet. The client who receives
the certificate uses it to authenticate the signature on the JAR file. To sign the applet, we need
to obtain a certificate that is capable of code signing. For all production purposes, you must
always obtain a certificate from a CA such as VeriSign, Thawte, or some other CA.
The Java 2 platform introduced new key management tools to facilitate support for creating
signed applets:
• The keytool is used to create pairs of public and private keys, to import and display
certificate chains, to export certificates, and to generate X.509 v1 self-signed
certificates.
• The jarsigner tool is used to sign JAR files and also to verify the authenticity of the
signature(s) of signed JAR files.
333
Chapter Six: AWT, Swing and Java Applets
• The policytool is used to create and modify the security policy configuration files.
Let's take a look at the procedure involved in creating a signed applet using our previous
WriteFileApplet applet example. The following steps are involved on the originating host
environment responsible for developing and deploying the signed applet:
1. Compile the Applet source code to an executable class. Use the javac command to
compile the WritefileApplet.java class. The output from the javac command is the
WriteFileApplet.class.
2. javac WriteFileApplet.java
3. Package the compiled class into a JAR file. Use the jar utility with the cvf option to
create a new JAR file with verbose mode (v), and specify the archive file name (f).
5. Generate key pairs. Using the keytool utility, create the key pair and self-signed
certificate (for testing purposes only). The JAR file is signed with the creator's private
key and the signature is verified by the communicating peer of the JAR file with the
public key in the pair.
7. -keypass mykeypass
8. -storepass mystorepass
This keytool -genkey command generates a key pair that is identified by the alias signapplet.
Subsequent keytool commands are required to use this alias and the key password (-keypass
mykeypass) to access the private key in the generated pair. The generated key pair is stored in
a keystore database called mykeystore (-keystore mykeystore) in the current directory and is
accessed with the mystorepass password (-storepass mystorepass). The command also prompts
the signer to input information about the certificate, such as name, organization, location, and
so forth.
9. Sign the JAR file. Using the jarsigner utility (see Example 3-14), sign the JAR file and
verify the signature on the JAR files.
334
Chapter Six: AWT, Swing and Java Applets
WriteFileApplet.jar signapplet
The -storepass mystorepass and -keystore mykeystore options specify the keystore database
and password where the private key for signing the JAR file is stored. The -keypass mykeypass
option is the password to the private key, SignedWriteFileApplet.jar is the name of the signed
JAR file, and signapplet is the alias to the private key. jarsigner extracts the certificate from
the keystore and attaches it to the generated signature of the signed JAR file.
1. Export the public key certificate. The public key certificate will be sent with the JAR
file to the end user who will use it to authenticate the signed applet. To have trusted
interactions, the end user must have a copy of those public keys in its keystore. This is
accomplished by exporting the public key certificate from the originating JAR signer
keystore as a binary certificate file and then importing it into the client's keystore as a
trusted certificate. Using the keytool, export the certificate from mykeystore to a file
named mycertificate.cer as follows:
3. -storepass mystorepass
5. Deploy the JAR and certificate files. They should be deployed to a distribution
directory on a Web server. Additionally, create a Web page embedding the applet and
the JAR. As shown in Example 3-15, the applet tag must use the following syntax.
In addition to the previous steps, the following steps are involved in the client's environment:
1. Import certificate as a trusted certificate. To download and execute the signed applet,
you must import the trusted public key certificate (provided by the issuer) into a
keystore database. The Java runtime will use this client-side keystore to store its trusted
335
Chapter Six: AWT, Swing and Java Applets
certificates and to authenticate the signed applet. Using the Keytool utility, import the
trusted certificate provided by the issuer (see Example 3-16).
1. Create the policy file. Create a policy file client.policy, which grants the applet to have
permission for creating and writing to the file "AppletGenrtdFile" in the client's local
directory (see Example 3-17).
2. Run and test the applet using appletviewer. The appletviewer tool runs the HTML
document specified in the URL, which displays the applet in its own window. To run
the applet using the client policy file, enter the following at the command line (see
Example 3-18).
http://coresecuritypatterns.com/SignedWriteFileApplet.html
336
Chapter Six: AWT, Swing and Java Applets
NOTE: Most browsers today do not support Java applets anymore. Keep this section for
nostalgia.
An Java applet is a graphics program run inside a browser. Write a Java applet (called
AWTAccumulatorApplet) which contains:
import java.applet.Applet;
import java.awt.*; // Using AWT's containers and
components
import java.awt.event.*; // Using AWT's event classes and
listener interfaces
337
Chapter Six: AWT, Swing and Java Applets
Applet uses init() to create the GUI, while standalone GUI application uses the constructor
(invoked in main()).
338
Chapter Six: AWT, Swing and Java Applets
follows:
<html>
<head>
<title>An AWT Applet</title>
</head>
<body>
<p>A simple applet which accumulates the number entered
into
a TextField and displays the accumulated sum on the
status bar</p>
<applet code="AWTAccumulatorApplet.class" width="300"
height="60">
</applet>
</body>
</html>
339
Chapter Six: AWT, Swing and Java Applets
A. Javascript
B. Css
C. HTML
D. SQL
A. JCM
B. JDM
C. JVM
D. Java class
4. Which method is automatically called after the browser calls the init method?
A. start
B. stop
C. destroy
D. paint
340
Chapter Six: AWT, Swing and Java Applets
5. Which method is only called when the browser shuts down normally?
A. start
B. stop
C. destroy
D. paint
6. Which of these operators can be used to get run time information about an object?
A. getInfo
B. Info
C. instanceof
D. getinfoof
A. TRUE
B. FALSE
C. Can be true or false
D. Can not say
A. display()
B. Print()
C. drawString()
D. transient()
341
Chapter Six: AWT, Swing and Java Applets
{
g.drawString(""A Simple Applet"", 20, 20);
}
}
A. A Simple Applet
B. A Simple Applet 20 20
C. Compilation Error
D. Runtime Error
342
Chapter Six: AWT, Swing and Java Applets
Reference
343
This textbook was developed by TVTI faculties through KOICA
project “Capacity Development for TVET Leaders and
Trainers in Ethiopia”