Upload
vumien
View
224
Download
0
Embed Size (px)
Citation preview
1
1. OBJECT ORIENTED PRGRAMMING (OOP)
Procedure Oriented Approach
High level languages provide easy approach to the users in developing their logic to solve any
problem with the help of a computer. These languages are machines independent because one
can develop and understand program logic without having much knowledge about computer’s
architecture. Conventional programming using high-level languages such as BASIC, COBOL,
FORTRAN and C are commonly known as Procedure Oriented Programming (POP). The
procedure oriented approach allows the users to develop their logic by applying a number of
functions to enable program productivity.
A sample flow diagram shows the procedure programming approach:
In procedure oriented programming system, many instructions are written to carry out any task.
These instructions are grouped together to form functions. In order to develop logical approach
you concentrate on functions.
However, least concentration is focused on the data items rather than the functions. When you
deal with a program containing many functions, the important data items are applied globally to be
Main Program
Function - A Function - B Function - C
Function - D Function - E
Function - F Function - G Function - H
2
used by all functions, whereas, a function may contain its own local data to deal with logical
situations. The figure below shows the system:
In this system the global data are loosely attached to the functions. They can keep floating
throughout the program. In order to make any change in the function you may need to reschedule
the associated data values. This may affect the normal sequencing of the programming logic.
Hence, in Procedure Oriented Programming system, the emphasis is on functions rather
than Data Items.
Drawbacks of Procedure Oriented Programming (POP)
As data values are global to all the functions, you may require to make necessary changes
in the function due to any change in the data values.
It is not suitable to solve complex problems in real situation.
Characteristics of Procedure Oriented Programming
Emphasis is on functions (logical steps)
Functions share global data.
Data values can keep floating from one function to another.
Uses top down approach of programming.
Object Oriented Programming System
Introduction
Object Oriented Programming (OOP) is an approach to standardize the program by creating
partitioned memory area for both data and functions. It has been developed to increase the
programmer’s productivity and also to overcome the traditional approach of programming.
Procedure Oriented Programming basically consists of a list of instructions for the computer to
follow and organizing them into groups, known as functions. We normally use a flow chart to
organize these actions and represent the flow of control from one action to another. In Procedure
Oriented Programming most of the functions share global data and data move openly around the
system from function to function.
In contrast to these, OOP does not allow data to flow freely from function to function and
procedure to procedure. In this system, the complete problem is decomposed into a number of
entities called objects. These objects are created and maintained along with a set of related
data. The data are used and maintained in such a way that they cannot be changed or edited
from other functions or objects. The data of an object can be accessed only by the functions
3
Object - A
Object - B Object - C
Data
Function
Data Data
Function Function
associated with that object. However, function of an object can access the function of other
object.
The different object oriented programming languages are C++, Java, Small talk, Simula-67, Eiffel
etc. Thus,
An Object Oriented Programming (OOP) is a modular approach, which allows the data to
be applied within stipulated program area. It also provides the reusability feature to
develop productive logic, which means to give more emphasis on data.
Features of Object Oriented Programming (OOP)
It gives stress on the data items rather than functions.
It makes the complete program/problem simpler by dividing it into a number of objects.
The objects can be used as a bridge to have data flow from one function to another.
You can easily modify the data without any change in the function.
4
Basic Elements of OOP (Principles of OOP)
Different people interpret the concept of object-oriented programming differently. Hence, it
becomes necessary to understand some elements of OOP. They are as follows:
Objects
Classes
Data Abstraction
Encapsulation
Data Hiding
Inheritance
Polymorphism
Dynamic Binding
Object
In Object Oriented Programming (OOP) languages like small talk, C++ and Java, attempts are
made to break a problem into some component, called Objects. They are the basic elements of
Object Oriented system and they are also known as the entities of the OOP. The set of related
objects may exchange data and information and they may interact with each other. Thus,
Object is a unique entity, which contains data and functions (characteristics and behavior)
together in an Object Oriented Programming (OOP) Language.
Let us consider the real world objects, which are visible before us. Any object in the real world can
possess the following characteristics:
It is visible.
It can be defined and described easily.
It can be put into thought and action.
5
1
2
3
4
5
6
7
You can observe that anything fulfilling above mentioned criteria has unique identity, definite
shape (State) or characteristics and behaviors. For example consider and object table:
It has the following characteristics:
It is four legs.
It has a plan top.
and the behaviors are:
It is used to keep glasses etc.
It is used to keep books etc.
Similarly, you can consider potato, as an object, which possesses characteristics such as it, is
brown in color, it is spherical in shape and or the behavior, it is used as a vegetable.
In payroll system, object may be an employee where characteristics are name, designation, basic
pay and behavior as calculating gross pay, calculating provident fund, printing pay slip etc.
Similarly you can imagine many more objects having some characteristics as well as related
behavior.
Classes
You just have learnt that an object contains states and behavior. The combination is also termed
as Data &Methods (Functions). The behavior (Method) is used to manipulate state(data). A class
is basically a user defined data type. Any variable declared of that type is considered an object of
that class. Each object belonging to a class contains entire set of data and functions included in
the class.
Rainbow (Class)
6
Example: If rainbow is the class which contains different colors like VIBGYOR. Then the colours
represent the different objects of the class Rainbow.
Similarly, we can consider a class named flower where rose, lotus and marigold are members of
the class flower. A class is used defined data type, which behaves as built in type.
If flower is defined as a class, then the statement:
Flower rose= new flower ();
Will create an object rose belonging to the class flower. Thus,
Class is a set of different objects. Each object of a class possesses same attributes and
behavior defined within the same class. As an object is a product of a class, hence class
is also termed as Object factory.
Encapsulation
In Object Oriented Programming (OOP), data cannot move freely from function to function. They
are kept in the corresponding classes in such a way that they will not be accessible to the outside
world except by using them through the related functions.
Data encapsulation is the most important feature of a class. The functions used in a class can
only access the data items. These functions provide interface between data items of the objects
and the calling program.
Such insulation of data, which cannot be accessed directly outside class premises although they
are available in the same program, is known as Data Hiding.
7
Thus,
The system of wrapping data and function into a single unit (called class) is known as
Encapsulation.
Data Abstraction
Let us consider a car. In order to drive it, you are only aware of some essential features of the
car. You can apply brake to stop the car, press accelerator to speed up the car and press clutch
to change the gears.
Do you ever think what changes are taking place in the machinery part of the engine? The
answer is simply No.
Hence, for driving a car you only use the essential features without knowing in details the internal
mechanism of the system. This act of driving a car is termed as abstraction.
Abstraction refers to the act of representing essential features without including
background details.
Abstraction is the absolute property of a class. The class encapsulates the data items and the
functions to promote abstraction. The data members are accessed only through the related
functions. As a class uses the property of abstraction, it is also called as abstract data type.
Object:
Employee
Attributes:
Name
Designation
Basic Pay
Methods:
Gross
PF
NET
GROSS
PF
NET
E
M
P
L
O
Y
E
E Methods
8
Inheritance
This term is derived from biology. The literal meaning of inheritance is acquired characteristics.
You would have studied in biology that the characteristics are transferred to the children from their
parents. Similarly an object of a class acquires some properties from the objects of another class.
Hence, Inheritance is the process by which objects of one class can link and share some
common properties of objects from another class.
Inheritance supports the concept of hierarchical classifications. For example the figure circle is a
part of the class two-dimensional, which is in turn a part of the class Mensuration. You can see the
hierarchical classifications in the given figure. Here, each derived class shares common
characteristics with the class from where it is derived.
Reusability is the process of adding some additional features to a class without modifying its
contents. This process can easily be attained if a class inherits another class which means the
new class contains some features of the existing class.
Circle
Attributes:
………………
………………
………………
………………
………………
Gr
Rectangle
Attributes:
………………
…….
………………
……….
Graph (Bar)
Cube
Attributes:
………………
………………
………………
………………
………………
Cylinder
Attributes:
………………
………………
………………
…….
Two Dimensional
Attributes:
……………………
……………
……………………
……………..
Three
Dimensional
Attributes:
……………………
……………………
……………………
…..
Mensuration
Attributes:
Area Volume
9
Polymorphism
This term is also derived from biology. The literal meaning is “available in many forms”. It is
important concept of OOP. Any operation exhibits different behavior and instances. The behavior
depends upon the type of data used in the operation. Suppose you have developed a function to
perform the addition then it will find the sum of two numbers passed to the function. In case the
passed arguments are strings the function will produce the concatenated(joined) string.
Hence, Polymorphism is the process of using a function for more than one purpose. It
allows the use of different internal structure of the object by keeping the same external
interface.
Dynamic Binding
Dynamic binding is the link established between function call and function signatures. While
writing a program, a function is invoked in the main function through function name. Do you ever
think, how this link is maintained in the physical memory when converted to machine level?
Compiler generates coded address of the function signature and applies at the function call
position in the caller program. The control gets transferred to the address available at function call
position, at the time of execution. This process is called Dynamic Binding.
Statistics
Graph
Pie Object
Graph (Pie)
Gr
Bar Object
Graph (Bar)
Histogram
Object
Graph
(Histogram)
10
Hence, dynamic binding is the process to link the function call with function signature at run-time
i.e., during execution of a program.
In the figure shown above, compiler generates machines code address of the function calculate ()
say (1000101), which in turn is replaced in the caller program at call position. On executing the
caller program control gets transferred to the required address to invoke the calculate () function
Benefits of Object Oriented Programming (OOP)
There are many benefits of OOP to the programmers as well as users. Some benefits of OOP are
listed below:
You can extend the use of existing class through inheritance.
Using the concept data hiding can generate secured program.
Multiple instances of an object can be generated to co-exist without any interference.
You can create different modules in your project through objects.
It is highly beneficial to solve complex problems.
It is easy to modify and maintain software complexity.
Address of the
Function
(1000101)
Data
FUNCTION
Calculate
Caller Program
………………………..
……………………….
Call (1000101)
(Call Position)
Link to the
address
Calculate()
11
Exercises
Multiple choice questions
I Tick ( √ ) the correct answer:
1. In OOP, the stress is given on :
(a) procedure (b) methods
(c) class (d) object
2. A ____________ has a unique identify though it may occur differently with same
characteristics and methods.
(a) object (b) class
(c) abstraction (d) encapsulation
3. A _____________ is an object maker.
(a) class (b) object
(c) program (d) method
4. The process of combining data and functions that are applied on data together as a single
entity is called :
(a) Inheritance (b) encapsulation
(c) classification (d) attributes
5. The process by which an object acquires the properties of another object is called:
(a) polymorphism (b) inheritance
(c) abstraction (d) object
6. In procedural programming, the stress is given on:
(a) class (b) function
(c) procedure (d) object
7. A ______________ is a set of objects that have the common structure and common
behavior:
(a) abstraction (b) encapsulation
(c) class (d) function
8. Which of the following is not an object oriented programming language:
(a) C++ (b) Simula
(c ) BASIC (d) Java
12
9. An object is identified by its:
(a) characteristics (b) state
(c) class (d) attributes
II. Write short answers:
1. What is OOP? Name two OOP languages.
2. Name any two OOP’s principles.
3. What are the features of OOP?
4. What are the elements of OOP?
5. What do you mean by abstraction?
6. Define the following with an example each.
(a) An object (b) A class
(c) Inheritance (d) Polymorphism
7. What do you understand by:
(a) Encapsulation (b) Data Hiding
13
2. HISTORY AND DEVELOPMENT OF JAVA
Java is an object oriented programming language developed primarily by James Gosling and
colleagues at Sun Micro Systems. This language was initially called Oak (named after the Oak
trees outside Gosling’s office).
In 1991, the Sun Micro systems (Broomfield, Colorado, USA) developed a complete language as
a part of research work to develop software for consumer electronics. It was developed as a full-
fledged programming language in which one can accomplish the same sort of tasks and solve the
similar problems like other programming languages such as BASIC, C++ etc. The platform
independence is one of the most significant advantages that JAVA has over other languages. It is
the capability of moving easily from one computer system to another.
Java, being an object oriented programming language encapsulation many features of C++.
Originally, JAVA was designed to execute applets, download while web browsing. But gradually,
the language has been gaining wide acceptance as a programming language, very often replacing
C or C++.
Basic features of Java
Java possesses the following features:
Java is an object oriented programming language.
Java programs are both compiled and interpreted.
It can access data from a local system as well as from net.
Java programming is written within a class. The variables and functions are declared and
defined with the class.
Java programs can create Applets (the programs which run on Web- browsers) and
applications are general programs like any other programming languages.
Java doesn’t require any preprocessor (#) or inclusion of header files for creating a Java
application program.
Java is a case sensitive language. It distinguishes the upper case and lower case letters.
14
Compiler and Interpreter
All high level languages need to be converted into machine code (binary code) so that the
computer understands the program after taking the required inputs. It processes the program and
then shows the desired result if the program is error free, otherwise the errors are to be corrected
to execute the program successfully.
The conversion of high-level language (source code) to machine level language (binary code) can
be done in two possible ways. It can be done either by using a Compiler or an interpreter.
The software, by which the conversion of the high level instructions is performed line by line to
machine level language, is known as an Interpreter. If an error is found on any line, further
execution stops till it is corrected. This process of error correction is much easier but the program
takes longer time to execute successfully.
Application Program System Program Object Code
However, if all the instructions are converted to machine level language at once and all the errors
are listed together, then the software is known as compiler. This process is much faster but
sometimes it becomes difficult to debug (correct) all the errors together in a program.
Byte Code& JVM
Java is a high level language (HLL) and the program written in HLL is compiled and then
converted to an intermediate language called Byte Code. This code is independent of the machine
on which the programs run. This makes a Java program highly portable as its Bytes code can
easily be transferred from one system to another.
Source Code
Compiler/
Interpreter
Machine Code
Java
Source
Code
Java
Compiler
Byte Code Java
Interpreter
Windows
Unix
System
OS-2
System
JVM
15
When this byte code is to be run on any system, an interpreter, known as Java Virtual Machine
(JVM) is needed which translates the byte code to machine code.
Java machine code varies for different platforms like windows, Unix, OS-2 etc. Hence, Java
Interpreter converts byte code to the machine code for concerning platform.
JVM acts as a virtual processor, which processes the byte code to machine code instructions for
various platforms. That is why it is called Java Virtual Machine.
Thus, the Java program uses compiler as well as interpreter both.
Exercises
Multiple choice questions:
I Tick ( √ ) the correct answer:
1. A program of Java that can be developed and executed by the users, is known as:
(a) Application (b) Applet
(c) Object (d) none
2. Who develop Java?
(a) James Gosling (b) Robert James
(c) Bjarne Stroustrup (d) none
3. Java Virtual Machine (JVM) is an:
(a) Interpreter (b) Compiler
(c) Machine (d) Byte code
4. Java is case sensitive. What is most appropriate with respect to this context?
(a) Upper and lower case letters are distinguished.
(b) Upper and lower case letters are ignored.
(c) Only lower case letters are distinguished.
(d) None.
16
II Write short answers:
1. What are the features of Java?
2. Define the terms:
(a) Source code (b) Machine code (c) Byte code
3. Distinguish between:
(a) Compiler and Interpreter
17
3. Starting Java Programming with Netbeans
Learning Objectives
After studying this lesson the students will be able to:
1. create a project
2. create a new form
3. appreciate the concept and importance of a Graphical User
Interface and Integrated Development Environment
4. understand the need and use of components like Button, Text
Field, Labels, Password Field, Text Area and Radio Buttons.
5. add components to the form and change the properties of the
components
6. attach code with components of the form
In our day to day life, we have to give information innumerable
times like fill up bank deposit slips to deposit money or type in
username and password to sign in to our mail account and many
more. Forms are means to accept data (input) from us and respond
as soon as we perform an action like clicking on a button or
submitting the form. Have you ever wondered how they are created
and wanted to create them yourselves? Well, our journey is a quest
in this direction. This chapter deals with teaching the basic process
of designing forms in Netbeans and using them to perform simple
manipulations using Java.
18
Introduction
Observe the given Figure carefully. We all may have come across some of the following but have
we ever given a thought about what these are? Let us try and analyze their utility. The Gmail
window displayed helps one to log in to user in the input area. The Gmail window displayed helps
one to log in to their mail account and view their inbox based on the username and password
entered by the user.
From the above discussion we infer that all these are means of entering data. The data entered
may be sent to some external agent for processing or simply stored somewhere. Such means of
collecting data are known as forms. Forms are used to accept data (input) from users and respond
to actions like clicking on a button. In the above figure, the enclosed area is used to accept input
and clicking on the button results in some output.
Now that we understand what a form is, let us start with a little fun and try to create our very own
form. Since this will be our first application so we will do something very simple. We will create a
form with a single button and on the click of this button, we will simply exit from the application.
We will use Netbeans to create this form, so first start Netbeans.
Since all development in the Netbeans takes place within projects, we first need to create a new
project within which we will store codes and other related files. The project will act as a storage
place for all the forms and codes created by us.
Integrated Development Environment (IDE)
NetBeans is an integrated development environment (IDE) for developing primarily with Java, but
also with other languages, in particular PHP, C/C++, and HTML5. It is also an application platform
framework for Java desktop applications and others.
19
Creating a new Project
To create a new application project called "Introduction":
1. Choose File > New Project. Alternately, click the New Project icon in the toolbar.
2. From the Categories pane select Java and in the Projects pane, choose Java Application.
Click Next.
3. Enter a name (in this case Introduction) in the Project Name field and specify the project
location by clicking on the Browse button. By default the project is saved in the NetBeansProjects
folder in My Documents and so this is the default Project location displayed in this field.
4. Ensure that the Set as Main Project checkbox is selected and clear the Create Main Class field.
5. Click Finish.
20
Netbeans creates the SW-Construction folder on your system in the designated location. This
folder will contain all of the associated files of the project.
Now the project is created and the following window pops up:
21
As you can see a class Main is automatically generated. You are now ready to Compile the Main
class. Click on Main file. Then Select Build -> Compile. Alternatively just Press F9. YOU are now
ready to Run (Execute) the program. Select Run -> Run File -> Run “Main..java” Alternatively just
Press Shift + F6.
You should get an absolutely nothing in the Output window; close it.
Therefore inside the main method put the following sentence:
System.out.println(“Hello Java World”);
Compile and run again.
Hopefully a sentence is printed out in the Output window.
CONGRATULATIONS YOUR FIRST NETBEANS-PROGRAM IS RUNNING
The next step is to create a form. To proceed with building our form, we need to create a container
within which we will place the other required components of the form like a button. For all our
applications we will choose the JFrame Form as the container to place other components.
To create a JFrame Form container:
1. In the Projects window, right-click the introduction node and choose New > JFrame
2. Enter Form Example 1 as the Class Name. This will be the name of your form.
3. Enter Book as the package. This should be the name given while creating the Project.
4. Click Finish.
We are now ready to create a file for your first GUI-program. Click on your folder for Java files cc, then: Select File -> New File -> Swing GUI Forms -> JFrame Form
22
Netbeans creates The Form Example1 form within the application and opens the form in the
Builder. Now we are ready to add components to our form. We want to add a button so follow the
given steps to add a JButton to the form:
1. In the Palette window, select the JButton component from the Swing Controls category
(displayed in above Figure).
2. Move the cursor over the Form. When the guidelines appear (as displayed in above Figure)
indicating that the JButton is positioned in the desired location, click to place the button.
The JButton is added to the form as displayed in above Figure. Note that as soon as the button is
added on the form, a corresponding node representing the component is added to the Inspector
window.
23
Attaching Code to a Form Component
After placing the button, the next step is to write a code to exit from the application on the click of
this button. To do the same, double click on the button to attach a code with the event i.e. click of
the button. Double clicking on the component opens up the source window and places the cursor
on the point where code is to be added. Note that certain code is pre generated and cannot be
changed. In the Source window add the single code line as shown in below Figure.
Know More
When we click the Source button, the application's Java source code in
the Editor is displayed with sections of code that are automatically
generated by the Netbeans Builder indicated by gray/blue areas, called
Guarded Blocks. Guarded blocks are protected areas that are not editable
in Source view. Note that we can only edit code appearing in the white
areas of the Editor when in Source view.
24
Executing a File
Now that the code for the first application is ready let us test our first application. To execute the
application simply select Run>Run File or press Shift+F6 as shown in the below Figure.
Executing a File
On executing the first example, the below figure will appear. Click on the button and observe the
result.
Simple Button Application
As soon as we click on the button, the application ends and we return back to the Netbeans
design window. So what did we learn? We learnt that the one line of code System.exit(0) causes
the application to terminate successfully.
25
Quick Recap - Steps for developing a Simple application
Step 1: Create a new Project
Step 2: Add a JFrame form
Step 3: Add the desired component from the Palette window using drag and drop feature
Step 4: Associate code with the component by double clicking the component.
Step 5: Add the source code.
Step 6: Test the form by pressing Shift+F6.
Exercises
1. What is Integrated Development Environment?
2. Explain briefly the following parts of Netbeans IDE
(a) Palette Pane
(b) Title Bar
(c) Inspector Pane
(d) Projects Pane
3. Fill in the blanks:
(a) _______________ Key is used to execute a file in Netbeans.
(b) _______________ contains all the components that can be added to the form.
(c) The ______________ window displays the files that are created in your application.
(d) ____________ provides Java developers the environment and tools they need to
develop and run Java programs.
(e) An application terminate with ________________ statement.
(f) ________________ Pane displays all the components of your currently opened form as
a tree hierarchy.
4. Design a form. Insert a button with the code to end the execution. Set the text Property of
the button as QUIT.
26
4. Netbeans – Integrated Development Environment
In Netbeans, the JFrame Form window contains a form named NewJFrame, which is where the
program’s Graphical User Interface (GUI) will be displayed. A GUI is the visual portion of the
program (i.e. buttons, labels etc). This is where the user enters data (known as Input) to the
program and where the program displays its result (known as Output) for the user to read.
Drawing or Placing a controls on the JFrame
In the Palette window, select the particular component from the Swing Controls category by
clicking and drag it to the JFrame area.
27
The above JFrame looks good but it would have looked great if the button had shown the text
STOP instead of jButton1. The text STOP on the button would have easily explained to the user
that clicking the button will stop the application run. So now let us try and achieve this. Each
component of our application including the form has certain attributes associated with it. The
Properties Window displays the names and values of the attributes (properties) of the currently
selected component. We can edit the values of most properties in the Properties window.
Using the text property of a button to change the display text
We want to change the text displayed on the button. There are four ways of doing the same in the
design view:
Select the button component by clicking on it. In the Properties window highlight the text
property and type STOP in the textbox adjacent to it as displayed in the above Figure.
Alternatively select the object. Left click on the button to highlight the display text. Type
STOP and press Enter.
Select the object > Press F2 - to make the display text editable. Type in the new text and
press Enter.
28
Right click on the button component and select Edit Text from the Drop down menu to make the
display text editable. Type in the new text and press Enter. Using the Properties window, it is also
possible to change the Font and Foreground property of the button as displayed in the below
Figure.
It is important to familiarize ourselves with the Netbeans Interface as it allows us to communicate
with the different parts of Netbeans easily and makes our task easier. As experienced above,
Netbeans is a GUI. A GUI is an acronym for the term Graphical User Interface. It is known as a
GUI as it allows us to interact with the various components through visual elements including
pictures, graphical icons, symbols and visual indicators. For example to add a button we simply
have to drag the button icon from the Swing Controls tab in the Palette. Similarly as we are writing
code, small visual indicators appear informing us about the errors in the code. The Netbeans GUI
29
Builder's various windows include four main components as displayed in the below Figure. These
components are explained below:
1. Design Area. The GUI Builder's primary window for creating and editing Java GUI forms. The
toolbar's Source and Design toggle buttons enable us to view the source code or a graphical view
of its GUI components. The additional toolbar buttons provide convenient access to common
commands, such as aligning components, setting component auto-resizing behaviour,and
previewing forms.
2. Inspector. Provides a graphic representation of all the components, both visual and non-visual,
in our application as a tree hierarchy. The Inspector also provides visual feedback about what
component in the tree is currently being edited in the GUI Builder as well as allows us to organize
components in the available panels.
3. Palette. Contains a customizable list of available components containing tabs for JFC/Swing,
AWT, and JavaBeans components, as well as layout managers. In addition, we can create,
remove, and rearrange the categories displayed in the Palette using the customizer.
4. Properties Window. Displays the properties of the component currently selected in the GUI
Builder, Inspector window, Projects window, or Files window.
30
The GUI Builder makes it possible to build professional-looking GUIs without an intimate
understanding of layout managers. We can lay out our forms by simply placing components where
we want them. Another interesting feature of Netbeans is that it provides comprehensive facilities
for software development. It is very helpful as it maximizes the programmer productivity by
providing tightly-knit components with similar user interfaces. This kind of an environment where
all the tools required for developing an application are available in a single place is known as an
Integrated Development Environment or simply IDE. Using an Integrated Development
Environment (IDE) for developing applications saves our time by managing windows, settings, and
data. In addition, an IDE can store repetitive tasks through macros and abbreviations. Drag-and-
drop features make creating graphical user interface (GUI) components or accessing databases
easy, and highlighted code and debugging features alert us to errors in our code.
Displaying a Message in a Dialog Box
Now, that we are comfortable with the creation process, let us experiment further and try to
display a message on the click of the button. Follow the same process to create a fresh form with
a simple button as shown in the below Figure. Modify the properties of the button as desired and
change the text property to "Wish Me".
Button with Modified Properties
31
Know More
Switch to the source window and add the single line code as shown in the below Figure.
JOptionPane.showMessageDialog(null,"Wishing you a GREAT DAY");
Above Figure Code to Display a Message on the Click of a Button. Now execute the file by
pressing Shift+F6. Click on the button to see the message. The execution is shown in the below
Figure which display a Message in a dialog Box on the Click of a Button.
Displaying a Message in a Dialog Box on the click of a Button
In graphical user interfaces, a dialog box is a special window, used in user interfaces to
display information to the user, or to get a response if needed. They are so-called because
they form a dialog between the computer and the user - either informing the user of
something, or requesting input from the user, or both. It provides controls that allows the
programmer to specify how to carry out an action.
32
Note: To use JOptionPane.showMessageDialog(), we have to add import javax.swing.JOptionPane; at the beginning of the code window.
In this example we learnt that the showMessageDialog method can be used to display a specified
message in a Dialog box. Till now we have learnt how to use:
The Design Window to create a Form and add components to it.
The Palette to add Swing Controls on the form.
The Inspector window to view the hierarchical relation among the different components.
The Properties Window to change the attributes of a selected component
So before proceeding further, let us take a minute to further familiarize ourselves with these
different parts of the Netbeans Builder interface. It is important to familiarize ourselves with the
Netbeans Interface as it allows us to communicate with the different parts of Netbeans easily and
makes our task easier.
Adding More Components to a Form
Great, now that we are comfortable with the interface, let us get back to the programming journey.
In the last example we had displayed a message on the click of a button. Now what next? All the
previous examples had only one component. Let us now delve further and try adding more than
one component to our form. Adding more components means that we will have multiple code
lines. So, first let us try and add more of similar components i.e. more buttons. So we will design a
application with 3 separate buttons and display a different message on the click of all the three
buttons.
Think what should be the first step?
Right, the first step is to add a new form and then we will add three buttons on the newly created
form. Drag and drop three buttons from the Swing Controls tab to complete the form design as
shown in the below Figure. Don't forget to change the properties and use the resize handle to
make the form appear exactly as shown in the below Figure.
A Form with three button
33
We are going to use the commands we have already learnt in our previous examples to:
Display the message "Good Morning" on the click of the Morning button
Display the message "Good Evening" on the click of the Evening button
End the application on the click of the STOP button.
JOptionPane.showMessageDialog(null,"GOODMORNING");
JOptionPane.showMessageDialog(null,"GOODEVENING");
System.exit(0);
34
Using a Text Field Component to Display Messages
The above code introduces us to a new method called setText(). This method is used to change
the display text of a component (label, text field or button) during run time. The syntax of this
method is given below:
35
Syntax:
component.setText("text")
The "text" is the display text to be shown for the mentioned component.
Do you remember how we can change the display text of a component during design time? Look
at the below Figure which displays a list of a few editable properties of a Text Field component.
Using a Text Field Component to Accept Input
36
Observe the above Figure carefully. What is new for us in this form? First we have used a new
component - a label and second is the difference between the two text fields. A label is a
component which is used to display simple text or as a label for another component. Can you spot
what is the difference between the two text fields? One of them has a white background while the
other has the same background colour as the form. The difference in the background colour tells
us that one of the text field is editable while the other is not. In simple words editable means that
the user can change the text displayed in the text field at run time. The text field at the top has to
accept the name of the user and the text field at the bottom has to display the greeting. So which
one should be editable?
After completing the designing of the form, now we are ready to add the code. Remember that we
had to use the getText() method in our code. Again double click on the three separate buttons one
by one to attach relevant code to each one of them.
Observe the coding given in below Figure and try to figure out what's happening. The code
teaches us another useful method - getText(). This is used to return the text contained in the
referred text component. It is generally used to retrieve the value typed by the user in a textbox or
label. The syntax for this method is given below:
Syntax:
jtextField1.getText()
This command is used to retrieve the value of the text Field named jtextField1.
Let us now understand the code. We want to display the message in the second text field along
with the name of the user which has been entered in the first text field.
jTextField1.getText()
retrieves the name entered by the user in the first text field using getText().
"Good Morning" + jTextField1.getText()
The message "Good Morning" is concatenated with the name retrieved from
the first text field using the + symbol.
37
jTextField2.setText("Good Morning" + jTextField1.getText())
The display text of the second text field is set to the concatenated message
using setText().
The below Figure displays an alternative method of concatenating the message and the contents
of the text field.
This alternate uses the concat() method to add the two strings together. The syntax of this method
is
Syntax:
string1.concat(string2)
This will result in adding the string2 at the end of the string1. For example:
"sham".concat("poo") returns shampoo
and
"to".concat("get").concat("her") returns together
38
Finally, our code is ready for execution. Below Figure displays the output when the user enters the
name and clicks on the Morning button.
Handling the Radio Button Component
By now we have completely familiarized ourselves with the working of text field, buttons, labels
and message box. Let us now delve further and try to explore the utility of other components. Let
us first try and modify the above example a bit. Supposing instead of displaying a message, we
need to display the title of the user (Mr. or Ms.) along with the name input in the textbox. How to
go about it? The simple answer would be to accept the title in a separate textbox and then
concatenate it with the name. But do you think it is the right approach? Using the textbox for
accepting the title will cause ambiguity thereby making the code complex as we will have to cater
to the different inputs. Different users will have different ways of entering the title. Some might
write MR. or some might write Mr. or some might write MR (without the dot). Then how do we
avoid this ambiguity? A simple solution is to use a radio button component to accept the gender
input. Radio buttons are groups of buttons in which, by convention, only one button at a time can
be selected. First design the form with the following components:
one editable text field to accept the name
a group of 2 radio buttons to accept the gender
one non-editable text field to display the name along with the title
appropriate labels to direct the user
As a first step drag a text field from the Swing Control tab of the Palette. Next drag and place two
radio buttons as shown in the following figure. Remember that out of several radio buttons
39
belonging to a group, only one can be selected. Therefore, the next step is to associate the two
radio buttons to each other. This is achieved by linking both the radio buttons with a ButtonGroup.
For each group of radio buttons, we need to create a ButtonGroup instance and add each radio
button to it. It is necessary to associate all the radio buttons in a group to one ButtonGroup. The
ButtonGroup takes care of unselecting the previously selected button when the user selects
another button in the group. So drag a Button Group component from the Swing Controls tab and
drop it anywhere on the form. This is an invisible component which is just used to associate
several radio buttons. Now to associate them to same button group, select the first radio button
and edit the buttonGroup property of this radio button using the Properties Window as shown in
the below Figure. Repeat the same procedure for the second radio button of this group to
associate them to same button group. Select the same Button Group from the drop down menu in
the buttonGroup property for the second radio button.
Now execute the program and see the output. One sample output is shown in the below Figure
40
Using the Text Area Component
The text field allows the user to enter a single line of text only. If we want to accept multiline input
or want to display multiline output, then what do we do? The Text Area component is a solution for
this problem. This component allows us to accept multiline input from the user or display multiple
lines of information. This component automatically adds vertical or horizontal scroll bars as and
when required during run time. Utilizing the concept of Text Area, let us design an application
which accepts names of two people and displays a short message about Friendship or Colleagues
depending upon which button is clicked.
Design the form shown in below Figure. One new component - the Text Area has been added
while the rest of the components are familiar.
! We should generally initialize a group of radio buttons so that one is selected.
However, there is no compulsion regarding this rule - a group of radio buttons can
have no initial selection. Once the user has made a selection, exactly one button is
selected from then on.
41
Now observe the below Figures (a), (b) and (c) carefully. These figures show the sample output of
the code given in above Figure. Try to point out the difference in the output pattern.
Figure (a) Figure (b)
Figure (c)
The main difference in the three sample output windows is about the way the text has been
displayed. In the first sample, the text is displayed without any wrapping and so only part of the
message is visible. To see the remaining part of the message, the user will have to use the
42
scrollbars. In the second sample, the text is displayed using line wrap without any word wrap. Due
to this words are broken although the entire message is visible.
In the third sample, the text is displayed using both line wrap and word wrap which ensures that
no words are broken and also all the lines are neatly wrapped. Let us first understand the exact
meaning of line wrap and word wrap and then we will learn how to change these properties. In text
display, line wrap is the feature of continuing on a new line when a line is full, such that each line
fits in the viewable window, allowing text to be read from top to bottom without any horizontal
scrolling.
On the other hand, Word wrap is a feature which allows text to be carried over to the next line so
that it will stay within a set of defined margins without breaking the words. These properties can
be set at design time using the Properties Window as shown in below Figure.
Know More
The '\n' is a non printable character that is used to cause explicit line breaks. It can be used
with any of the methods which are used to display text like setText() and showMessageDialog
43
Handling a Password Field Component
Now the question arises that what should be done if we want that the text input by the user should
not be displayed as characters but as special characters (so that it is not readable by anyone)?
The answer is simple. Use the Password Field instead of the normal text field. This component
allows confidential input like passwords which are single line. Let us design a simple application
which displays a simple message when the user inputs a user name and password. Below Figure
displays the sample run of the application. Remember that no checking is being done, rather a
simple message is to be displayed on the click of the LOGIN button and the application should be
terminated on the click of the CANCEL button.
44
Now before proceeding to the next chapter let us quickly recap the relation between a Project,
Form and Components. Remember each project can have multiple forms and this fact is clear
from the Projects window as shown in the below Figure.
Further each form can have one or more elements - some of which may be visible and some
invisible. The visible components are all shown under the Frame Component and the non-visible
components are part of other components. The relation of these components is clear from the
Inspector window as shown in the below Figure.
As we have learnt above, each application is treated as a Project in Netbeans and it can have one
or more forms. Each form can have one or more components and this relation between a Project,
form and components is depicted in the below Figure.
45
Summary
Forms are used to accept data (input) and submit data to an external agent for processing.
A project in Netbeans acts as a storage place for all the forms and codes created in one
application.
A JFrame Form acts as a container to place other components like the button, text field and
text area.
The Palette Window contains a customizable list of available components containing tabs
for JFC/Swing, AWT, and JavaBeans components, as well as layout managers.
The Swing Controls can be differentiated from other components as they are preceded with
a 'j' like jButton and jTextField.
The Source tab is used to view the Java source code.
The Design tab is used to design the form.
The Properties Window is used to display and edit the attributes of the currently selected
component.
To execute a single file of an application press Shift +F6 or select Run>Run File.
GUI is an acronym for Graphical User Interface which is an interface that allows us to
interact with the various components through visual elements including pictures, graphical
icons, symbols and visual indicators. The Netbeans IDE consists of The Design Area, the
Inspector Window, the Palette and the Properties Window.
IDE is an acronym for Integrated Development Environment which is a work environment
that integrates all tools necessary for Application Development and makes them available
as part of one environment.
46
A Desktop application creates a template that provides basic application infrastructure
such as a menu bar, persisting of window state, and status bar. With this template, you can
also generate code to create a GUI interface for a database table.
The various swing components learnt include a button, text field, label, text .area, radio
button, password field.
All radio buttons working together must be associated with a single ButtonGroup. The
ButtonGroup is an invisible component.
The general syntax of executing any method is:
object.method(arguments)
For example:
jTextField1.setText("Welcome")
In this example jTextField1 is the object, setText() the method and "Welcome" is
the argument supplied.
The concat() method or the string concatenation symbol(+) may be used to .add two strings
together.
A brief summary of all the methods learnt in this chapter is given in the table below:
47
Exercises
Multiple Choice Questions
I Tick ( √ ) correct choice:
1. The Form is designed in the
a) Inspector window
b) Design window
c) Palette window
d) Properties window
2. The Swing Controls components are contained in the
a) Design window
b) Inspector window
c) Properties window
d) Palette window
3. The most suitable component to accept multiline text is:
a) Text Field
b) Password Field
c) Text Area
d) All of the above
4. What will be the output of the following command?
Learning.concat("Java")
a) Learning Java
b) LearningJava
c) JavaLearning
d) Java Learning
e) Will result in an error
5. What will be the output of the following command?
"Learning".concat("Java")
a) Learning Java
b) LearningJava
c) JavaLearning
d) Java Learning
II Answer the following questions :
1. Explain the following terms:
a) IDE
b) Inspector Window
c) Form
48
2. Differentiate between:
a) Text field and Text area components
b) Text field and Password field components
c) Design and Source tabs
Lab Exercises
a) Design a GUI desktop application in java to accept the name and favourite sport in two text
fields and display an appropriate message including the name and favourite sport in a dialog box
using the concat() method. The application must have an exit button to end the application and
appropriate labels.
b) Design a GUI desktop application in java to accept age category using radio buttons and
display an appropriate age based message in a text area on selection of a radio button. The
application must have an exit button to end the application and appropriate labels.
c) Design a GUI desktop application in java to accept weight in Kilograms in a text field and
convert it into grams and milligrams on the click of two separate buttons. Display the result in a
second text field. The application must have an exit button to end the application and appropriate
labels.
d) Design a GUI desktop application in java to accept temperature in Celsius in a text field and
display temperature in Fahrenheit in another text field on the click of a button. The application
must have an exit button to end the application and appropriate labels.
49
5. Data Manipulation
Introduction Compiler contains a phase called storage assignment phase. This phase allocates memory for
different variables used in your program. It also creates the structure to store the data efficiently in
the location. Hence, the compiler must know the type of data you are likely to supply for storage to
ensure optimum utilization of memory space. This is the reason why data types are required in
Java programming.
Keywords
Keywords or reserve words are those words, which are predefined with the system. These words
cannot be applied as a variable name in any program. Java also has reserved words. Some of the
reserve words/Key words are listed below for your reference:
case switch Else break static
Do const throws float Default
Try int double void char
For while New import goto
Long if Byte package boolean
Catch short Public Class private
Comment Statement in Java Programming
Sometimes it becomes difficult for a user to understand the logic applied in a program particularly
when any other person has developed it. In such cases, the programmer keeps mentioning the
purpose and action being taken in different steps. This can be made possible only by applying
comment statement in the program.
There are two ways to give comment in Java programming. However, users are expected to give
comment wherever necessary while writing Java programming
1. Single Line Comment (// Comments to be written in single line)
2. Multi Line Comment (/* comments to be written*/)
50
Single Line Comment
This comment symbol is applied to explain the purpose of a logic step in short i.e, within a line. An
example is given below
class first
{
public static void main (String args[])
{
// This is my first program
int a=7,b=9,c;
c=a+b; // Find the sum of two numbers
System.out.println(“Sum of two numbers=”+c);
}
}
Multi Line Comment
Multi Line comment statement can be used when the programmer wants to explain the logical
steps in details i.e, by including multiple lines as shown below:
class first
{
public static void main (String args[])
{
/* This is my first program
It is developed on 20 / 02/ 2014.
The program is to show multi line comment statement. */
int a=7,b=9,c;
c=a+b; // Find the sum of two numbers
System.out.println(“Sum of two numbers=”+c);
}
}
51
TOKEN
Token
Each individual character used in Java statement is known as Token.
Types of Tokens
The various types of tokens available in Java are :
Literals
Identifiers
Assignments
Punctuators
Operators
1. Literals (Constants)
These are the constants used in Java program. While writing a program you can use some
contents, which remain fixed (i.e. do not change) throughout the execution of the program.
Such contents are called Literals or constants.
Java uses the literals classified in the following ways :
= a + C 5 ;
I D E N T I F I E R
A S S I G N M E N T
I D E N T I F I E R
O P E R A T O R
L I T E R A L
P U N C T U A T O R
String Literals Real Literals
Integer Literals
Null Literals
Character
Literals
Boolean Literals
LITERAL
S
52
Integer Literals : The number which are represented without decimal point are
called Integer Literals. These are the whole numbers having positive or negative
values. E.g. 14, 345, 8, 534 etc.
Real Literals : These are also called floating-point constants. They represent
numbers with decimals points. E.g. 24.6, 0.075 etc.
Character Literals : The constants, which are alphanumeric in nature, are called
character Literals. All alphabets upper or lowercase, digits, special characters can
be termed as Character Literals. E.g. ‘A’, ‘d’, ‘3’, ‘*’ etc.
A Character Literals represents a single character enclosed within a single quotes.
String Literals : String is a set of alphanumeric characters. A group of characters
enclosed within a pair of opening and closing double quotes is known as String
Literals.
E.g. “ABHISHEK KUMAR JHA”, “Year 2014”, “10% per annum” etc.
2. Identifiers (Variables)
Identifiers are also called variables in Java programming. A variable is a named memory
location, which contains a value. The value of a variable can be change during the
execution of the program. A variable can be treated by any combination of letters without
spaces. We can declare more than one variables of the same type in a statement.
Syntax : <data type> <space> <variable name>
int m;
float p,q,r;
BEFORE OPERATION AFTER OPERATION
int m = 5; m
Data 5 is stored in the location
named m
int m = m * m; m
The value of variable m changes in the
memory after executing this statement
5 25
53
Rules of naming a variable :
A variable may have any number of characters.
It may contain alphabets, digits and underscore.
The underscore can be applied in between the characters to increase the length of a
variable name.
Variable names should be meaning which easily depict the logic.
Reasons for a variable to be invalid
A variable name should not start with a digit or special character.
A variable name should not include a space in between the characters.
A digit should not be applied in between the characters of a variable name.
Data Types in Java
In Java programming we have to deal with various types of data, hence it becomes
necessary for a programmer to select an appropriate data type according to the data taken
in a program. The data and its types are given below:
54
Primitive Types
The data types, which are independent of any other type, are known as Primitive data types.
These types are also called Basic Data Types. E.g. byte, int, long, float, double etc.
Primitive data types are pre-defined or built-in data types because the system developers
of Java programming define them. You can declare a variable of type int, which will follow
the characteristics mentioned in this type.
e.g. int x;
It means variable x follows the characteristics of int type. Hence variable x contains only
integer value.
Integer Type
A variable declared integer type contains a whole number. The number may be negative or positive number without decimal point. There are two types of declarations under this heading.
int : Applied for short integer number.
long : Applied for large integer number.
A programmer has to select an appropriate data type according to the need in this program.
Data Data Types Bit size Format
Integer int 32 bits int a; a=15;
Long Integer Long 64 bits long b; b=45678;
Floating Type
If you declare a variable to be floating type then you can store a fractional number in it. i.e.
A number with decimal point. You can use two different types to represent fractional data
values.
float : It represents a fractional number with small range.
double : It represent s a fractional number with wide range values.
55
A programmer decides the types according to the need in his program. Refer the table
shown below:
Data Data Types Bit size Format
Small range of decimal
values
Float 32 bits float m; m=34.45;
Wide range of decimal
values
Double 64 bits double n;
n=0.00056435869;
Character Type
A character type variable contains a single character. There are 256 characters available
with computer. These characters are termed as ASCII Characters. Each ASCII character is
assigned a specific numeric value called ASCII code. The ASCII codes of the characters
range from 0 to 255.
ASCII codes of the characters are as follows :
A – Z : 65 – 90
A – z : 97 – 122 (Respectively)
0 – 9 : 48 – 57
The character types in Java are as follows :
Non numeric Character Type Bit size Format
Single character (An
alphabet or a special
character)
Char
16 bits(2 bytes) char p; p= ‘A’
char x; x= ‘*’;
More than one character/a
word/a sentence.
String More than 16 bits
A=“ABHISHEK”
string a;
56
Boolean Type
It is special type in which a variable contains a constant as True or False. You can use
Boolean type variable to set True or False in order to ensure whether a logical condition is
satisfied or not.
e.g. Boolean flag = false; or Boolean flag = true;
Special Notes : 1. A character is enclosed in single quotes ( ‘ ’).
2. Strings are enclosed in double quotes ( “ ”).
3. A Boolean type assumes one of the values true or false
without quotes.
Punctuators Punctuators are the punctuation signs used as special characters in Java. Some punctuators are - ;,? etc. Separators The special characters are used in Java to separate the characters or variable. E.g. (,), {,},
[,] etc.
Operators
The operators are the symbols used to perform arithmetical or logical operations in Java
programming.
e.g. +, -, *, /, %, &&, ||, !, <, >, == etc.
Mixed Expression
An expression, which includes different types of variables or values to yield a result, is
known as Mixed expression :
e.g. int a; float b; double d;
double x=a+b*d;
In the given example the expression a+b*d contains different types of variables as int, float
and double. Such expression is called Mixed expression.
57
Type Conversion
In a mixed expression the result can be obtained in any one form of its data types. Hence, it
is needed to convert the various data types into a single type. Such conversion in termed
as Type Conversion. In Java the type conversion can be done in two different ways which
are as show below :
Implicit type conversion
In mixed expression, the data type of the result gets converted automatically into its higher
type without intervention of the user. This system of type conversion is known as Implicit
type conversion.
Hierarchy of Data types
Hierarchy
The type of hierarchy shown above indicates the increasing order of data types. If two data of
different types are operated then result automatically gets converted to their higher type.
e.g. int a; long b; long c;
c = a + b;
int long
+
long
Byte
char
short
int
long
float
double
58
You must have noticed that two values int and long type in the expression shown above will
result in long type value. Hence, you must declare variable c as long type.
char c; int i; float f; double d;
d = c + i + f + / d
float double
int
char double
double
double
The result obtained in the illustration shown above is of double type. Hence, the resulting
variable d must be a double type.
Explicit Type conversion
Explicit type conversion is another way of type conversion in which the data type gets
converted to another type depending upon the user choice. This means the user forces the
system to get back into the desired data type.
When the data type gets converted to another type after User intervention, the type
conversion is known as explicit type conversion.
e.g. int a, b;
float x = (float) (a+b);
In the example given above, the outcome of the expression a+b has to be int implicitly. But,
(float) provided by the User before the expression a+b will cause the result forcibly converted
to float type. Hence, this type of conversion is also called as forced conversion or type casting.
Type casting is also applicable to convert the type from higher type to lower type.
e.g. double x,y;
int c=(int) (x+y);
The expression shown above will result in double type implicitly, but due to implication of type
casting the result is forced to get converted into a lower type int.
59
Java Packages for Mathematical calculation
A package is a collection of classes. Every package has a name and any one of them may be
included in a program by the import keyword. i.e. : import java.lang.*; and for the mathematical
functions we can include : import java.lang.Math;
Some of the functions are mentioned below :
Function Description Return Data type Format
sqrt(a)
Returns the square root
of a positive number
Double Math.sqrt(a);
min(a,b) Returns the smaller
between a & b.
int/long/float/double Math.min(a,b);
max(a,b) Returns the greater
between a & b.
int/long/float/double Math.max(a,b);
pow(a,b) Returns the value ab Double Math.pow(a,b);
abs(a) Returns the absolute
value (magnitude) of
any numeric.
int/long/float/double Math.abs(a);
round(a) Returns the rounded
value upto the nearest
integer.
Int Math.round(a);
floor(a) Returns the rounded
value down to the
nearest integer.
Double Math.floor(a);
sin(a)/cos(a)/tan(a) Returns the sin/cos/tan
of an angle a
(Expressed in radian).
Double Math.sin(a);
Math.cos(a);
Math.tan(a);
exp(a) Returns an exponent
value i.e. ea
Double Math.exp(a);
60
Primitive Data Types with their sizes and the ranges at a glance :
Data Type Size Range Description
Byte 8 bits ( 1 byte ) -123 to + 127 Bit wise operations
Char 16 bits ( 2 bytes ) To represent a character
Short 16 bits ( 2 bytes ) -32768 to + 32767 To represent short integers
Int 32 bits ( 4 bytes ) -231 to 231 – 1 To represent integers
Long 64 bits ( 8 bytes) -263 to 263 -1 To represent long integers
Float 32 bits ( 4 bytes ) -3.4 E + 38 to 3.4 E+ 38 To represent values up to 6
significant digits
Double 64 bits ( 8 bytes ) -1.7E + 308 to 1.7 E+308 To represent double value up to 15
significant digits
OPERATORS AND EXPRESSIONS IN JAVA
Operators
In computer programming you often need to perform some arithmetical or logical operations. In
such circumstances, you need operators to perform these tasks. Thus, an operator is basically a
symbol or token, which performs arithmetical or logical operations and gives meaningful result.
The values, which are involved in the operation, are termed as operand.
Types of operators
Basically there are three types of operators in Java, which are as follows:
Operands
a + b * c
Operators Expression
Operators
Arithmetical Relational Logical
61
Arithmetical Operators
The operators, which are applied to perform arithmetical calculations in a program, are known as
arithmetical operators. Some basic calculations like addition, subtraction, multiplication, division,
modulus are often needed during programming. You can apply the arithmetic operators like +, -, *,
/ and % respectively to carryout these calculations.
Differentiate between arithmetical expression and arithmetical statement:
Arithmetical Expression Arithmetical Statement
An arithmetical expression may contain
variables, constant and arithmetical
operators together to produce a meaningful
result.
x + y, m - 15, b * b - 4 * a * c etc.
If an arithmetical expression is assigned to
a variable then it is known as an
arithmetical statement.
Syntax :
Variable=Arithmetical Expression.
z=x+y, c=m-15, b = b * b - 4 * a * c
Expressions in Java
When you write a program in Java, it is necessary to represent the arithmetical expressions into
Java expressions. Few examples are given below to illustrate how a mathematical expressions
are written in Java.
Mathematical Expression Java Expression
Abc a * b * c
ab + bc + cd a * b + b * c + c * d
a2 + b2 a * a + b * b
2 ( l + b ) 2 * ( l + b )
pr t/ 100 p * r * t / 100
⅓ ab + ½ cd ⅓ * a * b + ½ * c * d
Arithmetical Operators
Unary Operator Binary Operator Ternary
Operator
62
Unary Operator
An arithmetical operator, which is applied with a single operand is known as Unary Operator. E.g.
+, -, ++, -- etc.
Unary (+) operator
This operator is applied before the operand. It is just applied as a pointer to a variable, which
results in the same value of a variable. E.g.
If a=8, then + a will result in 8.
If a= - 10, then + a will result in -10
Unary (-) Operator
This operator is used in the same way as Unary plus (+). It is applied before the operand. Unary
minus ( - ) reverts the sign of an operand e.g.
If a=4, then - a will result in - 4.
If a= 0, then - a will result in 0,
If a= - 3.6, then - a will result in 3.6,
Unary increment and decrement operators
Unary Increment Operator (++) increases the value of an operand by one. Unary decrement
Operator (--) decreases the value of an operand by one.
Example :
1. x = x + 1
By applying increment operator it can be written as x++ or ++x
2. p = p – 1
By applying decrement operator it can be written as p-- or –p
Unary Increment/Decrement
Operator
Prefix Postfix
63
Prefix When increment or decrement operators are applied before the operant, it is known as prefix operators. This operator works on the principle ‘CHANGE BEFORE ACTION’. It means the value of the variable changes before the operation takes place. Example of Prefix increment : p = 5;
p = ++p * 4;
p ++p (p increases by 1)
Before operation
After operation
p will result in 24
++p * 4
Example of Prefix decrement :
d = 11; t = 4 + (--d); d - - d (d decreases by 1)
Before operation
t
After operation
t will result in 14
Applied in Calculation
Postfix
This unary operator is used after an operant whose value is to be increased or decrement by 1. This works on the principle ‘CHANGE AFTER THE ACTION’. This means that the operant will be affected after performing the operation.
5
24
6
6 * 4 = 24
11
14
10
4 + 10 =
14
64
Example of Postfix increment :
p = 5;
p = p++ * 4;
p Value of p during operation
Initial Value
Final Value
p++ * 4=5*4=20
p
Stores result in p
Example of Postfix decrement :
p = 5;
p = p-- * 4;
p Value of p during operation
Initial Value
p- - * 4=5*4=20
m
Thus, m will result in 20 Stores result in m
Note : Both Prefix and Postfix increment operators increase the value of an operand by 1,
before the action and after the action respectively. Prefix and Postfix decrement
operators and vice-versa.
5
20
20
5 * 4
5
20
5 * 4
65
Solved example
Example 1 : If p=5; then find d=++p + 5;
Ans : d=++p + 5
= 6 + 5
=11
Example 2 : If a=48; then find a =a++ + ++a;
Ans : a = a++ + ++a
= 48 + 49 + 1
= 97 + 1
= 98
Example 3 : If c=2; then find d=++c + c++ + 4
Ans : d = ++c + c++ + 4
= 3 + 3 + 4
= 10
Example 4 : If m = 12; then find n = m++ * 5 + --m;
Ans : n = m++ * 5 + --m
= 12 * 5 + (13-1)
= 60 + 12
= 72
Example 5 : If y = 14 then find z = (++y * (y++ + 5))
Ans : z = (++y * (y++ + 5))
= (15 * (15 + 5))
= (15 * (20))
= (15 * 20)
= 300
Binary Arithmetic Operators
An arithmetic operator, which deals with two operands, is known as Binary Arithmetic
Operator.E.g. +, -, *, / and % etc.
66
A table is given below to illustrate Binary Arithmetic Operators :
Operators Symbols Format Description Results :
if a=22; b=5;
Addition + a + b Returns the
sum
27
Subtraction - a – b Returns the
difference
17
Multiplication * a * b Returns the
product
110
Division / a / b Returns the
integral part
4
Modulus/Remainder % a % b Returns the
remainder
2
Relational Operators
These operators are used to show the relationship among the operands. Relational operators
compare the values of the variables and results in terms of ‘True’ or ‘False’ (i.e. 0 or 1).
The different types of relational operators are as follows :
Symbol Meaning Format Result Returns : if
a=10; b=6;
< Less than a < b False 0
> Greater than a > b True 1
<= Less than or equal to a <= b False 0
>= Greater than or equal
to
a >= b True 1
= = Equal to a = = b False 0
!= Not equal to a != b True 1
67
Logical Operators
Java uses logical operators AND (&&), OR ( | | ) or NOT ( ! ). These operators yield 1 or 0 depending upon the outcome of different expressions. The different types of logical operators along with their format are as shown below :
Logical Operators Symbol Format
AND && ( a > b ) && (a > c )
OR || ( a = = b ) || ( a = = b )
NOT ! ! ( a = = b )
Precedence of logical operators is NOT (!), AND (&&) and OR ( || ) i.e. if a statement contains all
the three logical operators then NOT operator will perform first.
If (( a > b ) && ( b > c) || ( b > a ) ! ( c > b ))
2 3 1 - is order of the operations
Logical OR ( || )
This operator is used to combine two conditional expressions. It will result in true if either of two
conditions (expressions) is true otherwise false.
e.g. 5 > 4 || 8 > 12 : Result in true because 5 > 4 is true.
3 > 7 || 5 <= 4 : Result in false because both the expression is false.
2 < 0 || 12 : It will result in true because second expression is true.
Logical AND ( && )
The AND operator results in true if both the expressions (comprising its operands) are true.
e.g. 5 > 3 && 3 < 5 : Result in true because both the expressions are true.
6 = = 6 && 3 > 0 : Result in true as both the expressions are true.
5 != 5 && 4 = = 4 : Result in false as first expression is false.
68
Logical NOT ( ! )
Logical NOT operator is applied when you want to revert the outcome of an expression. It is a
unary operator because it uses a single operand.
e.g. ! ( 8 > 3 ) : False, because 8 > 3 is true.
! ( 5 < 7 ) : False, as 5 < 7 is true.
! ( 3 < 0 ) : True, as 3 < 0 is false.
Note : Relational operators have higher precedence over logical operators AND and OR.
Hence, while using AND and OR operators you need not enclose the operands
within parenthesis. NOT (!) operator has the highest precedence, so it is required to
enclose the operand under parenthesis.
Indicate whether the following statements result in True or False :
(i) 7 > 4 || 0 (ii) 3 > 0 || 0 <=14 (iii) 5 + 3 > 7 && 7 > = 4 + 3
(iv) 3 = = 4 && 5 = = 5 (v) ! (5 < 3)
Ans : (i) False (ii) True (iii) True (iv) False (v) True
Ternary Operators (Conditional Operator)
Ternary operators deals with three operands. It is also called conditional operator because the
value assigned to a variable depends upon a logical expression.
Syntax :
variable = (test expression) ? Expression 1 : Expression 2;
The variable contains the result of expression1 if the test condition is true, otherwise expression2.
e.g. a=5; b=3;
max = ( a > b ) ? a : b;
Hence, the value 5 is stored in max as a>b is true.
min = (b > a) ? a : b;
69
Nested Conditional Operator
You can use conditional operator (ternary operator) in nested form as shown below :
Program snippet to find maximum among three numbers:
max = ( a > b ) ? (a > c)?a:b : (b > c)? b:c;
Test condition Expression 1 Expression 2
The test condition a>b is false. Hence, it will operate expression 2. In expression 2, the test
condition b>c is true which enables value 12 to be stored in max. Hence, max=12.
Give the output, if the following statements are executed :
1. int c=(3<4)?3*4:3+4;
Ans : c=12
2. int a=14, b=4;
Ans : x = true
3. int x=90;
Ans : c= ‘Z’
4. int a=18; int b=12;
Ans : t=false
5. c=(val + 550 < 1700)?200?400;
if (a) val=1000
(b) val=1500
Ans : (a) c=200
(b) 400
70
Exercises
Multiple choice questions:
I. Tick (√ ) the correct answer :
1. The statement n++ is equivalent to :
(a) ++n (b) n=n+1
(c) n+1 (d) none
2. What will be output of a & b the following, if int a,b; a=10; b=++a?
(a) 10,10 (b) 10,11
(c) 11,10 (d) 11,11
3. What will be the output of a++; int a=-1?
(a) 1 (b) -1
(c) 0 (d) none
4. If int a=43; int b=5; int c=0; What value is stored in c when c=a%b?
(a) 9.6 (b) 9
(c) 0 (d) none
5. What is the result of the following in Java statement: When int m=8; m*=8;
System.out.printIn(“The output=”+m)?
(a) 8 (b) 64
(c) 64 (d) 88
6. double c; int x,y,z; x=5; y=10; z=11; c=x*y+z/2; the value stored in c is :
(a) 55.0 (b) 55.5
(c) 55 (d) none
7. int m, p; m=5; p=0; p=++m + --m; the output will be :
(a) 11 (b) 10
(c) 9 (d) 12
8. int a=7; int p=0; p=++a + --a; the output of p will be :
(a) 13 (b) 14
(c) 15 (d) -15
9. If a=0, b=1; then the output of logical OR will be :
(a) 0 (b) 1
(c) both 0 & 1 (d) none
71
II. Write the Java expressions for the following :
1. p=a2+bc 2. m = (a2 – b2)/ab
3. s = ut + ½ at2 4. f = uv/(u+v)
5. y = 2(lb + bh + lh) 6. a2 +b2
7. z = x3 + y3 – xy/z
III. Write short answers :
1. What is an operator? What are the three main types of operators? Name them.
2. Distinguish between Operator and Expression.
3. Explain the following with an example each :
(a) Arithmetic operator (b) Relational operator
(c) Logical operator (d) Ternary operator
4. Distinguish between :
(a) Unary & Binary arithmetic operator
(b) Increment & Decrement operator
(c) Prefix & Postfix operator
(d) Postfix & Prefix increment
(e) Postfix & Prefix decrement
5. What will be the output, if x=5?
(a) 5 * ++x (b) 5 * x++
6. If m = 5, n = 2; what will be the output of m and n after execution?
(a) m-- = n; (b) n = m + m/n;
7. What will be the output when:
(a) val=500 (b) 5 * x++
int val, sum, n=500;
sum=n + val > 1750? 400:200;
System.out.println(sum);
8. int a = 0, b = 30, c = 40;
A=--b + c++ + b;
System.out.println(“a=” +a);
72
IV. Multiple choice questions
Tick ( √ )the correct answer :
1. A constant which gives the exact representation of data is called
(a) Variable (b) Literal
(c) Identifier (d) Character
2. A word used in a high level language which has a special meaning attached to it is called
(a) Class (b) Identifier
(c) Keyword (d) Literal
3. A character literal is assigned to a :
(a) Char variable (b) Char type literal
(c) String variable (d) String Literal
4. A character literal is enclosed in :
(a) ‘ ’ (b) “ ”
(c) : : (d) { }
5. A set of characters is assigned to :
(a)String variable (b) Static variable
(c) Boolean variable (d) None
6. The ASCII codes of upper case alphabets ranges from :
(a) 65 – 90 (b) 60 – 85
(c) 65 – 91 (d) 97 – 122
7. Which of the following is false to find square of a number?
(a) Math.pow(a,2) (b) a*a
(c) Math.sqrt(a,2) (d) None
8. What type of value is returned by sqrt function?
(a) int (b) float
(c) double (d) All
73
9. Which of the following syntax is true to find the square root of a number?
(a) sqrt(a) (b) Math.sqrt(a)
(c) Squareroot(a) (d) None
10. Boolean Data is used to test a particular condition .i.e. true or false. Which of the following
is correct representation?
(a) boolean m=true (b) boolean m=‘true’
(c) boolean m= “true” (d) None
V. Answer the following questions:
1. Define variable.
2. What do you mean by constant? Explain with an example.
3. State two kind of data types.
4. What do you understand by Token? Name different types of tokens.
5. What are the rules to assign a variable in a Java programming?
6. What are the different ways to give comment in Java programming?
7. What do you understand by Java reserved words? Name at least five Java reserved words
which are commonly used in Java programming.
8. Distinguish between :
(a) Integer and floating constant
(b) Character and String constant
(c) String and Boolean constant
9. Write down the Data type of the following :
(a) Integer (b) Long Integer
(c) A fractional number (d) A special character
8. What is a package? Give an example.
9. What do you understand by Boolean type data? Explain with an example.
10. What do you understand by primitive and non-primitive data type? Give two examples of
each.
11. Define the following with an example each:
(a)Literals (b) Identifiers
12. Write down the syntax for the following functions in Java programming.
(a) To find minimum between two numbers.
(b) To find absolute value of a number.
(c ) To find the exponent of a number.
(d) To find the square root of a number.
74
6. Control Structure—Branching
When you issue command to execute your program in any programming language, the control
reaches straightway to the first line of the program. After executing the first line it moves to the
next line and so on. The control keeps executing the lines sequentially one after other unless it
has reached the end of the program. After executing the last line of the program control gets
terminated (i.e. passes back to the system). The flow of control from one statement to other
sequentially is termed as flow of control or sequential flow of control. This process of control flow
takes place by default.
Decision Making in Java
Conditional Flow of Control : Sometimes, during execution of a program user may need to transfer
the control to a specified location in the program by skipping some lines. This can be done by
conditional flow of control. You can perform this task by applying the control statements like if,
switch-case, loops etc.
Bi-directional Flow of Control
If a statement is referred as bi-directional branching statement i.e., it checks a given condition and
transfers the control to execute either of the two blocks of statements. This statement while
programming can be used in the following ways :
1. if
2. if – else
3. Nested if – else – if
75
if – Statement
You can use if statement to check a specified condition. If performs a course of action if the
condition is true. Otherwise, the action is ignored.
Syntax :
if (condition)
{
Statement 1 Yes
Statement 2
}
No
If the given condition is true the statements ( statement 1 and statement 2 ) are executed. If the
condition is false the control ignores the statements and passes to the next line of the program.
Note : You need not apply curly brackets if a single statement is to be performed for true
condition.
e.g.,
(a) if (n<10) System.out.println(“Single digit number”);
(b) if (n<10) c++;
If (n > 10 && n <= 100)
System.out.println(“Double digit number”);
Refer the example (a) shown above, the control checks whether the value of n is below 10 or not.
If yes it prints “Single digit number”.
In the example (b) shown above the value of c will increase by 1 if the condition n < 10 is true
otherwise the control ignores counting and is transferred to the next if statement. If this statement
is true it prints “Double digit number”.
(c) if (n > 10 && n <= 100)
{ c++;
System.out.println(“Double digit number”); }
In this example the complete block of the statements is executed if the condition is true otherwise
ignored.
Is
Condition
satisfied
? Statement 1
Statement 2
76
Example Program : Write a a program in Java to find the simple interest by using assignment
statement. If the simple interest is above Rs.100 then display the interest otherwise not.
// To find the interest by using assignment statement & use of if statement.
public class interest
{
public static void main(string args[ ])
{
int p,r,t,si; si=0;
p=2000; r=10; t=3;
si=(p*r*t)/100;
if ( si>100 )
System.out.println(“The Simple Interest =” +si);
}
}
2. if – else
You can use if – else statement in a logical situation when either of the two actions are to be
performed depending upon certain condition. If the condition is true it performs one set of
statements otherwise performs another set of statements.
Syntax :
if (condition)
Statement(s) 1
else Yes
Statement(s) 2
No
e.g.
if ( a > b )
max = a;
else
max = b;
In the example shown above the values of a and b are compared together. If the condition is true
then the value of a is assigned to max otherwise, max receives the value of b.
Is
satisfied
?
Statement (s) 1
Statement (s) 2
77
4. Nested if – else – if
When an if statement is placed within another if, it is known as nested if statement. It can be done
by using if – else – if structure.
Syntax :
if (condition 1) { if (condition 2) Statement 1 else Statement 2 } else { if (condition 3) Statement 3 else Statement 4 }
Explanation : In the syntax shown above, first of all condition 1 is checked, if it is true then it
further checks condition 2 and performs action statement 1 or statement 2 accordingly.
In case condition 1 is false, the control enters else part and further checks condition 3. Statement
3 and statement 4 are executed according to the result of condition 3.
e.g.
Structure of nested if – else
if ( a > b )
{
if (a > c)
max=a;
else
max=b;
}
else
{
if ( b>c)
max=b;
else
max=c;
}
System.out.println(“Maximum = ” +max);
78
The above mentioned program segment finds the maximum of 3 numbers a, b and c by applying
nested if-else structure. Can you guess what happens, when the following statements will be
executed ?
max=(a>b)?(a>c)? a:c:(b>c)? b:c;
System.out.println(max);
It will also find the maximum of three numbers. This could be made possible by using nested
ternary operators.
Example Program : WAP in Java to accept the number of days and display it after converting into
number of years, number of months and number of days.
Code window for the above prgram
79
Execute the Jframe, On click of JButton1
Switch Case Statement
Switch case statement is a multiple branching statement. In this system the control jumps to
perform a particular action out of a number of actions depending upon a switch value. A switch
statement is associated with a number of blocks. Each block is defined under a specific case. The
control gets transferred to a particular case, which matches with the given switch value. Each
case ends with a break statement, which can be used as a case terminator. Break statement
passes the control out of the switch block.
You can use a special case called default case which is automatically followed if no case matches
with the given switch value.
It has the following structure :
Switch (n) { case 1 : statement break; case 2 : statement break; case 3 statement break; default: statement }
Where n is the variable, which accepts the control transfer value within the program. If the value of
n is 2 then the control jumps to case 2 and performs the statement. On applying break, it
terminates the block. Similarly other cases are followed for other switch values.
80
Consider the following program snippet:
If (i==1)
System.out.println(“Good Morning”);
If (i==2)
System.out.println(“Good Afternoon”);
If (i==3)
System.out.println(“Good Evening”);
If (i<=0 && i>3)
System.out.println(“Good Night”);
The program snipped shown above prints a specific message for a given value of variable i. A
number of if statements can be sorted out just by applying a single switch case statement as
shown below :
Switch(i)
{
case 1 : System.out.println(“Good Morning”);
break;
case 2 : System.out.println(“Good Afternoon”);
break;
case 3 : System.out.println(“Good Evening”);
break;
default : System.out.println(“Good Nine”);
}
Note: 1.You need not use break to terminate the last case.
2. Switch statement can take decision only based on integer or character type values.
Example using switch case by applying character type value.
switch (ch)
{
case ‘+’ : c=a+b;
break;
case ‘-’ : c=a-b;
break;
case ‘*’ : c=a*b;
break;
case ‘/’ : c=a/b;
}
81
Differences between if-else and switch-case :
S.No. If – else Switch case
1. It results in a Boolean type value i.e. true
or false
It results in integer type value i.e. 1,2,3
etc.
2. Does not apply break Applies break at the end of each case.
3. For true/false condition either of two
blocks are operand.
Specific case is operated for a given
switch value.
4. No default operation. A default case is applied if no case is
available for a given switch value.
Testing and Debugging
In general, testing is the process of making sure that the program performs the intended task and
debugging is the process of locating and eliminating program errors. Testing and debugging are
vital steps in developing computer programs. They are also time consuming steps. In fact, the
time spent in testing and debugging often equals or exceeds the time spent in the program. If a
program runs successfully with the test data and produces correct result, it is normally released
for use.
Testing and debugging are two different tasks. You should not get confused with each other. The
differences between these processes are given below :
Testing Debugging
Testing is a process in which a program
is validated.
Debugging is a process in which the
errors in the program are removed.
It is a positive activity that seeks to
demonstrate that the program is correct.
It is a negative activity in a sense that it is
centered around elimination of known
errors or bugs.
Testing is complete when all desired
verifications against specifications have
been performed.
Debugging is finished when there are no
errors and the program is ready for
execution.
82
Types of Errors
There are three types of errors that occur in a computer program. i.e.
1. Syntax Error
These errors result when the rules or the grammar of the programming language are not
followed. Such programming errors typically involve incorrect punctuation, incorrect word
sequence, undefined terms or misuse of terms.
Example : The Java statement c=(a+b/2) has a syntax error because every Java statement
should terminate with a semi colon(;) so the correct form is
c = (a + b / 2 );
All syntax errors must be found and corrected. Otherwise, the program will not be execute.
2. Logical Error
A logical error, is an error in planning the program’s logic. The computer actually does not
know that an error has been made. It follows the program instructions and executes the
results, but the output may not be correct. The problem is that the logic being followed does
not produce the desired results.
Example : In a Java programming, the instruction is given as :
for (a=1; a<=10; a=a+2)
System.out..println(a);
The output of the program is all odd numbers between 1 – 10
But, the user wants to print all even numbers between 1 - 10
Thus, it should be :
for(a=2; a<=10; a=a+2) to give the desired result.
3. Run time Error
Even after errors are removed and the program is complied, it does not means that the
program will produce the results. They may be some other mistakes other than syntax error
and logical error which come in the way of execution, known as Run time errors. These
errors may occur due to dividing a number by zero or to find out the square root of a
negative number etc,
Example: The expression a = ( b + c ) / d;
If the value of d=0, then the result will come to an infinite, which is a run time error.
83
Application 1. Program to Create a Calculator.
Add 4 labels, 3 text fields, 4 buttons to your application by dragging them from the palette. Drag
them one by one, See the below screenshot and rename them and place them in the similar way
as I’ve placed.
After placing them click on Addition button and write the below code:
double fnum, snum, tot;
fnum = Double.parseDouble(jTextField1.getText());
snum = Double.parseDouble(jTextField2.getText());
tot = fnum+snum;
jTextField3.setText(Double.toString(tot));
84
Now go to the Subtraction button and the above code but just replace the addition
operator by subtracting operator, the code will look like this after you replace
double fnum, snum, tot;
fnum = Double.parseDouble(jTextField1.getText());
snum = Double.parseDouble(jTextField2.getText());
tot = fnum-snum;
jTextField3.setText(Double.toString(tot));
Now go to the Multiplication button and replace the operator by a astrict, it refers to
multiplication operator which will allow you to multiply the numbers
double fnum, snum, tot;
fnum = Double.parseDouble(jTextField1.getText());
snum = Double.parseDouble(jTextField2.getText());
tot = fnum*snum;
jTextField3.setText(Double.toString(tot));
Now go to the Division button and replace the operator by a slash, that operator is used
for dividing in computers, after replacing the code will be looking like this
double fnum, snum, tot;
fnum = Double.parseDouble(jTextField1.getText());
snum = Double.parseDouble(jTextField2.getText());
tot = fnum/snum;
jTextField3.setText(Double.toString(tot));
After adding the code in all the buttons your code will look similar to the code which I’ve shown in
the below Figure.
85
Application 2.
Program to do long division and display quotient and remainder.
1. Design a Jframe with following controls and set the necessary properties.
2. Write the following code in the code window.
int divisor,dividend;
int quotient,remainder;
divisor=Integer.parseInt(jTextField1.getText());
dividend=Integer.parseInt(jTextField2.getText());
quotient=(int)(dividend/divisor);
remainder=dividend-(int)(dividend/divisor)*divisor;
jTextField3.setText("The quotient is" + Integer.toString(quotient)); jTextField4.setText("The
remainder is" + Integer.toString(remainder));
86
3. Execute the Jframe, On click of JButton1the quotient and remainder will be displayed in the
respective textboxes.
87
Exercise Multiple choice questions:
I Tick ( √ ) the correct answer :
1. In a switch case, when the value of the switch does not satisfy then the execution transfers
to :
(a) A break statement (b) a default statement
(c) a loop (d) none
2. A compound statement in a Java programming is enclosed in :
(a) Parenthesis (b) Braces
(c) Square brackets (d) All of them
3. If condition is essentially formed by using :
(a) Arithmetic operators (b) Relational operators
(c) Logical operators (d) Ternary operators
4. If((a!=b)&&(a= =c)), then which of the statement is true :
(a) b is the smallest no. (b) b is the greatest no.
(c) a is the smallest no. (d) both a & b
5. {if (a!=b)
c=a;
else
c=b;}
can be written as :
(a) c=(b!=a)?a:b; (b) c=(a!=b)?a:b;
(c) c=(a!=b)?b:a; (d) both a & b
6. If((a>b)&&(b>c)&&(c>d)) means :
(a) d is the greatest no. (b) d is the smallest no.
(c) a is the smallest no. (d) all of the above
7. Two arithmetic expressions can be compared with if statement, using :
(a) Arithmetic operator (b) Null operator
(c) Logical operator (d) Ternary operator
88
8. Which of the following is a selective statement?
(a) if (b) goto
(c) for (d) none
9. A Java program executes but doesn’t give the desired output. It is due to the :
(a) Logical error in the program
(b) Syntax error in the program
(c) Runtime error in the program
(d) none
II Write short answers:
1. Differentiate between if and switch statement.
2. Explain with the help of an example, the purpose of default in a switch statement.
3. Write down the syntax with reference to Java Programming :
(a) If – else statement
(b) Switch case
4. Distinguish between :
(a) Testing and Debugging
(b) Syntax error and Logical error
5. What are the different types of errors that take place during the execution of a program ?
6. What is a compound statement ? Give an example.
7. What do understand by Run time error. Give an example.
III Java Programming :
1. Write a program in Java to find the sum, difference and the product of two numbers when
a=50, b=25;
2. Write a program in Java to find the quotient and the remainder of two numbers when a=57,
b=25;
3. Write a program in Java to find the area and perimeter of a square when the side of square
is 15.
4. Write a program in Java to calculate the Simple Interest and the Amount, when :
p=Rs. 4000; r=10%; t=3 years.
5. Write a program in Java to convert 104⁰F into Celsius. (Hint : C/5=(F-32)/9).
6. Write a program in Java to calculate the gross salary & net salary of an employee when
salary=Rs.12000; DA=40% of Salary; HRA=15% of Salary; PF=10% of the Salary.
Gross Salary=(Salary+Da+HRA)
Net Salary =Gross Salary – PF
7. A shopkeeper buys a tape recorder for Rs.550 and sells it for Rs.625. Write a program in
Java to calculate the actual profit and profit percent.
8. Write a program in Java to calculate the hypotenuse of a Right Angled Triangle when
perpendicular=20 cm and base=15cm.(Hint : h2=p2+b2 and use Math.sqrt();)
89
Use of if – else
9. Write a program in Java to accept a number and check whether it is positive number or a
negative number.
10. Write a program in Java to accept marks obtained in 5 different subjects and hence find the
sum and the average. If the average is 40% or more then display “Promotion granted”
otherwise “Promotion not granted”.
11. Write a program in Java o accept three angles of a triangle and check whether the triangle
is possible or not. If possible then check whether it is an acute angled, a right angled or an
obtuse angled triangle and display the message accordingly.
12. Write a program in Java to accept the cost price and selling price of an article and calculate
either profit percent or loss percent.
13. Write a program in Java to accept the age of a voter. If the age of a voter is 18 years or
more then he/she is eligible to vote otherwise not.
14. Jharkhand State Electricity Board (JSEB) charges for electricity from their consumers
according to the units consumed (per month) as per given tariff:
Units Consumed Charges
Upto 100 units Rs.1.35/ unit
>100 units and upto 200
units
Rs. 1.50/ unit
>200 units Rs.1.80 / unit
WAP in Java to calculate the monthly Electricity Bill.
90
7.Control Structure - Looping
Introduction
In the previous chapter, we have discussed different statements and functions using sequential
type of flow, i.e. the program will get executed step by step and after completion of the task it
would stop. The control does not repeat to execute the statements again.
Now, we will discuss the programs using conditional repetitive type of flow, i.e. after completion of
the stated task, it would check whether a given condition becomes true or false. Depending upon
the result, it would either repeat or stop the execution.
A looping structure contains the following parts
Control Variable : A variable, which starts with an initial value and determines the duration
of the repetitive is known as Control Variable or initial value.
Body of the loop : A set of statements, which are executed within the loop simultaneously.
Test Condition : Each loop conditions a test condition. Whether the loop has to be
repeated or terminated, depends upon the test condition. The control enters the body of the
loop for execution till the test condition is true, otherwise it terminates.
Step Value : The step value in a looping structure determines the increment or decrement
(i.e. updating) of the control variable unless the test condition is false. Based upon the
nature of iterations the loops are of two types which are as shown below:
Fixed Iterations
In this type of looping structure, the statements are repeated for a fixed number of times. The
control terminates after repeating the statement for given number of times.
for Loop
We can perform any conditional repetitive type of flow very easily with the help of for loop. A for
statement is used for a fixed number of iterations.
91
The syntax of for statement is :
for(initial value; final value; step value)
{
………;
Task
……..;
}
The for loop will be executed for all values from initial value to the final value, with the increment /
decrement of the step value.
Suppose, we want to print all natural numbers from 1 to 10, then the program could be written as
illustrated below :
Example Program : Write a program in Java to print all natural numbers from 1 to 10.
public class natural
{
public static void main(string args[ ])
{
int a;
for (a=1; a<=10; a++)
System.out.print(a);
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Consider the following statement used in the program shown above :
92
The order of execution of loop is as follows:
(i) First of all variable a is initialized to 1.
(ii) The control checks the condition, if it is true then it enters into the body of the loop and
executes the statements.
(iii) After performing the loop body it returns back to increase the value of a by 1. Further it re-
enters the block for execution.
(iv) The steps are repeated from (ii) and finally control exits the loop as soon as the test
condition is false.
If we want to display the output on a line, then the program could be written as :
// To print all natural nos. 1 to 10
public class natural
{
public static void main(string args[ ])
{
int a;
for (a=1; a<=10; a++)
System.out.println(a);
}
}
Output :
1 2 3 4 5 6 7 8 9 10
Different ways of using for loop
Omitting expressions
A for loop can run effectively after omitting some of the parameters.
for(; a<=10; a++)
{
body of the loop
}
In the above statement, it does not require the initialization of the variable. Hence, the loop starts
with a garbage initial value and operates the loop body unless the test condition is false.
Note : You must apply semi-column (;) even the initialization within the for statement is ignored.
Including more expression in for loop
You can apply other initialization and expressions within a for statement other than required
parameters.
e.g.
93
for (a=1; x=1; a=10; x++; a++)
{
System.out.println(a);
s+=x;
}
In the above example shown above, the variables a and x get initialized with 1. Now, control
enters the body of the loop. The value of a is printed and x is added to s. The process gets
repeated by increasing x and a by one simultaneously unless the test condition is false.
Null loop or bodyless loop
A for statements, which doesn’t include any statement as body of the loop is called null loop or
empty loop.
e.g. for(a=1; a<=10;a++)
A semi-colon ( ; ) placed after closing braces in a for loop indicates that the loop does not execute
any statement under it or body of the loop is not available. It can also be represented as shown
below:
e.g.
for(a=1; a<=10; a++)
{
}
The purpose of using such looping structure is simply to create delay during execution. The
variable a will start with 1 and keep on changing by 1 unless it exceed 10.
Endless loop or infinite loop
You can also design a structure with the help of a for loop which will never end. Such loop is
called Infinite loop or endless loop.
e.g.
for(m=1; m<=10;)
{
body of the loop
}
In the looping structure shown above, increment / decrement expression is missing. Hence, the
value of m will always remain 1. As a result the test condition will never be false and loop will
operate infinite times.
94
Nested Loop
Nested loop means loop within loop. In some cases, it is required to construct such loops. It can
be applied when the internal loop repeats for a given number of times for each iteration of external
loop. Nested loops may be designed using while,
Do – while or for statement.
It is simply like a cycle within another cycle in such a way that for each rotation of external cycle,
the internal cycle makes a number of rotations. The system can be understood easily with the help
of a clock.
You can observe in the clock shown below that the hour hand moves one step ahead for each 60
strokes of the minute hand.
The structure of the nested loop is shown below :
// starting of loop 1
{
………;
………;
// starting of loop 2
{
……..;
……..;
// starting of loop 3
{
……..;
……..;
}
// end of loop 3
}
// end of loop 2
}
// end of loop 1
In the nested loop structure shown above, you must have noticed that the end of internal loop
block is marked before the end of external loop block.
Nested for loop
When you apply a for loop within another for loop, the structure is termed as nested for loop. You
can understand the function of nested for loop as shown below:
95
for(initial value; test condition; step value)
{
………………………..;
………………………..;
for (initial value; test condition; step value)
{
……………………;
……………………;
} INNER LOOP
} OUTER LOOP
An example is illustrated below:
Example Program: Write a program in Java to display the given pattern:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
// An example of nested loop
public class pattern
{
public static void main(string args[ ])
{
int a;
f (a=1; a<=5; a++)
{
for (b=`1; b<=a; b++)
{
System.out.print(a);
System.out.println();
}
}
}
Note : The step value gets updated accordingly:
a++ : to increase the value by 1
a - - : to decrease the value by 1
a=a+2 : to increase the value by 2
a=a-2 : to decrease the value by 2
96
Loops with Varying Iterations
While Loop
This is also one of the ways to generate loop in a program. In general, this loop can be applied to
a program where numbers of iterations are not fixed. The syntax of while statements is given
below:
while(condition)
{
………………………;
Statements to execute
………………………;
}
While loop is a condition controlled loop. The loop will continue executing till the test condition is
true. The control terminates when the test condition is false.
Example Program : Write a program in Java to display a message on the screen 10 times by
using while statement.
// Use of while statement
public class Message
{
public static void main(String args[ ])
{
int i; i=1;
while (i<=10)
{
System.out.println(“ We are learning Java Programming”);
i++;
}
Refer the program shown above. Variable i starts with initial value 1. As the given condition is true
the control executes the loop block and resumes back to test the condition again. The process is
repeated unless the test condition results in false.
97
Different ways of using while loop
Infinite while loop
In a while loop if user does not provide increment / decrement expression it becomes infinite loop.
i=1;
while(i<=10)
{
s=s+i;
}
The looping structure shown in the above example starts with initial value of i with 1. It keeps
repeating the expression available within the body of the loop without increasing / decreasing the
control variable. Hence, the test condition always remains true and loop repeats infinitely.
Delay loop by using while
A while loop can also be used to create a delay loop. This can be done to pause the control as
needed by the user during programming. The body of the loop does not contain meaningful
operation to perform.
i=1;
while(i<=10)
do – while loop
do-while loop is used in a program where number of iterations is not fixed. In this system, the
control enters the loop without checking any condition, executes the given steps and then checks
the condition for further continuation of the loop.
Thus, this type of the loop executes the tasks at atleast once. If the condition is not satisfied, then
the control exits from the loop.
e.g.
do
{
……………………..;
Task to do
……………………..;
} while(condition);
98
Example Program: Write a program in Java to find the factorial of 10.
Factorial of 10 (10!=10*9*8 ………*1)
// to find the factorial of 10 using do-while statement
public class factorial
{
public static void main(String args[ ])
{
int i,f; i=1; f=1;
do
{
f=f*i;
i++;
}
while (i<=10);
System.out.println(“The Factorial of 10 =”+f);
}
}
User controlled loop
Sometimes in a program you use a loop, which makes iterations based on the needs of the users.
Such looping structure is termed as user controlled loop.
e.g.
int i=4,j=1;
char m= ‘Y’;
while(m== ‘Y’)
{
c=i*j;
System.out.println(c);
j++;
System.out.println(“Want to continue…(Y/N)”);
m=(char)(in.read());
}
The loop shown above will keep repeating and generating multiplication table of 4 unless the
value of m is entered as ‘N’.
99
The difference between while loop and do-while loop
While loop Do-while loop
The while loop will not execute at all if the
condition is not satisfied.
The do-while loop will continue atleast
once.
The while loop checks the condition first
and then execution begins, (Hence it is
entry controlled loop).
The do-while checks the condition after
executing the loop once. (Hence it is exit
control loop).
Note : Break and continue statements can also be used in for and do-while loops in the relevant
Java programming.
Some of the illustrated Programs based on Iteration through Loops
Example Program : WAP in Java to find the sum of all natural numbers from 1 to 10.
// To find the sum of natural nos. 1 – 10.
public class natural
{
public static void main(String args[ ])
{
int a,s;s=0;
for(a=1;a<=10;a++)
s=s+a;
System.out.println(“The sum of 1 to 10 =”+s);
}
}
Example Program : WAP in Java to find the sum of any ten natural numbers.
// To find the sum of any ten natural numbers
Import java.io.*;
public class sum
{
public static void main(String args[ ])throws IOException
{
s=s+Math.pow(x,a)/f;
}
System.out.println(“The sum of 1+x2/1!+x3/2! ….. +x10/9!= ”+s);
}
100
Exercises
Multiple choice questions
I Tick ( √ ) the correct answer :
1. When the statements are executed sequentially in a program, the construct is known as :
(a) Iteration (b) Sequence
(c) Selection (d) None
2. Which of the following statements is to be executed with fixed iteration ?
(a) for (b) while
(c) do – while (d) if – else
3. Which of the following loop executes at least one time in a program ?
(a) do-while (b) while
(c) for (d) nested loop
4. To execute a loop 10 times, which of the following statement satisfies ?
(a) for(i=6;i<=26;i=i+2) (b) for(i=3;i<=30;i=i+3)
(c) for(i=0;i<10;i++) (d) all of the above
5. Which of the following loop checks the condition first and then execution begins?
(a) do – while (b) do
(c) while loop (d) for
6. In a nested loop, which loop closes at last ?
(a) Innermost loop (b) outermost loop
(c) inner & outer together (d) none
7. How many times the loop, for (i=1; i++) will execute, if there is no statement to terminate
the loop ?
(a) 1 (b) 0
(c) infinite (d) none
8. Which of the following statement allows repetitive execution of the statement ?
(a) Do – while (b) while
(c) for (d) all of the above
9. A loop statement is given as :
While (flag)
{
Statements
}
The loop statement will be executed and repeated until the value of flag becomes :
(a) 0 (b) 1
(c) true (d) false
101
II Write short answers:
1. What do you understand by a loop? What is significance?
2. What are the different ways to generate a loop?
3. Write down the general format of:
(a) for loop (b) do – while (c) while loop
4. Distinguish between:
(a) Step loop and nested loop (b) while and do-while loop
5. Explain the term loop with an example.
6. State one difference and one similarity between while and do-while loop.
III Java Programming
1. Write a program in Java to display all odd numbers from 1 to 100.
2. Write a program in Java to display all even numbers from 1 to 100.
3. Write a program in Java to display:
1,4,9,16,………………….,900.
4. Write a program in Java to find the sum of:
(a) All odd numbers from 1 to 100.
(b) All even numbers from 1 to 100.
5. Write a program in Java to find the sum of the given series:
(a) 1+1/2+1/3+ ………………………….+ 1/20.
(b) ½+1/4+1/6+ ……………………….. + 1/20.
6. Write a program in Java to display the first ten numbers of the given series:
2,5,10,17……………………
7. Write a program in Java to find the factorial of 10.
Factorial of 10! = 10 * 9 * 8 …………………..* 1
8. Write a program in Java to display the first six numbers of the given series:
1,12,123,1234, ………………..
9. Write a program in Java to accept two numbers and find the L.C.M of the numbers. (Hint :
LCM=Product of two numbers / HCF )
10. Write a program in Java to find the sum of the given series:
(a) S=a2+a2/2+a2/3……………………. + a2/10; where a=2.
(b) S=1-2+3-4+5………………………. – 20.
11. Write a program in Java to display the following pattern :
(a) 5 5 5 5 5 (b) 2 2
4 4 4 4 4 4 4 4 4
3 3 3 3 3 6 6 6 6 6 6
2 2 2 2 2 8 8 8 8 8 8 8 8
1 1 1 1 1
(c)1 (d) 5 4 3 2 1
1 2 5 4 3 2
1 2 3 5 4 3
1 2 3 4 5 4
5
102
12. Write a program in Java to find the gross salary of 100 employees of a company
accordingly, taking Basic salary as an input.
HRA = 20% of Basic
DA = 25% OF Basic
CTA = 10% of Basic
Gross Salary = Basic + HRA + DA + CTA
The program also displays the number of employees getting Gross Salary as Rs.25000/-
or more.
13. Write a program in Java to accept the monthly sales of 40Salesman of an Advertising
Company and calculate the commission of each according to the following table :
Apart from this, each Salesman gets travelling allowance of Rs.1500/-. Display the total
income Salesman along with the Sale.
14. Write a program to input the accident records of 75 drivers and to print the number of
drivers below 20 years of age, those between 20 and 30 years of age and those above 30
years of age. Also print the percentage of female drivers who have met with an accident.
15. In an election, out of 1249 voters in a booth, only 861voter used their franchise correctly. If
five candidates are contesting, write a program in Java to find :
(i) The number of invalid and valid votes and
(ii) The percentage of the valid votes received by each candidate.
16. Computech company has 96 employees who are divided into 4 grades as per their basic
pay as the following:
GRADE I BASIC
DA
H.R.
Rs.10,000pm or more
40% of Basic
30% of Basic
GRADE II BASIC
D.A.
H.R.
Rs.5,000pm or more but less than Rs.10,000.
40% of Basic
25% of Basic
GRADE III BASIC
D.A.
H.R.
Less than Rs.5,000 but more than Rs.2,000pm
30% of Basic
20% of Basic
GRADE IV BASIC
D.A.
H.R.
Rs.2,000 pm or less
30% of Basic
15% of Basic
If the salary, which is the total of Basic, DA and HR is above Rs. 50,000 per annum then
income tax at the rate of 30% of the annual salary exceeding Rs.50,000 is deducted on
monthly basis at source. Taking name of the employee and the basic (monthly) pay as
inputs a pay slip for each employee is to be printed. Write a program in Java to perform the
job.
103
8. Radio Button and Check Box
Radio buttons are usually used to select just one item from a list, rather than the multiple items available with check boxes. Let's see how they work.
Drag and drop a panel onto your form. Then locate the Radio Button control in the NetBeans palette. Drag a Radio button onto your new palette. It should look like this:
The default text for the first radio button is jRadioButton1. We'll use our radio buttons to allow a user to select a payment method. So change the text of your radio button to Credit Card. (The text can be changed in the same way as you did for check boxes. Again, we'll leave the variable name on the default of jRadioButton1.)
Add two more radio buttons to the panel. Change the text to Debit Card, and PayPal:
104
There is, however, a problem with the radio buttons you've just added. To see what the problem is, run your program again. Now select one of the radio buttons. Try selecting another radio button and you'll find that you can indeed select more than one at the same time:
With our radio buttons, though, we only want the user to select one payment option. To solve the problem, Java lets you to create something called a ButtonGroup. As its name suggest, this allows you to group buttons under one name. You can then add radio buttons to the group. Once you've added buttons to the group, only one option is available for selection.
Add a Button Group to the panel (Fig:1) and set the button group property of each button to the Button Group1 (Fig:2).
Fig:1 Fig:2
105
Run your form again, and try to select more than one radio button. You should find that you can only select one in the group.
To get at which radio button was selected, again there's an isSelected method we can use.
Add a normal button to your form. When we click this button we'll display a message box stating which radio button was clicked.
Change the text property to Payment Option.
Now double click your new button to create a code stub. Add the following:
Note: To use JOptionPane.showMessageDialog(), we have to add import javax.swing.JOptionPane; at the beginning of the code window.
All we're doing here is checking which radio button is selected. Run your program again, and select an item from your radio button. Then click your button. You should see something like the following:
106
Check Box Check boxes are similar to radio buttons but their selection model is different. Each Check box
component works independently of each other and so the user can select any number of check
boxes from an interface. A group of radio buttons, on the other hand, can have only one button
selected. A Check box can be added from the Swing Control menu as shown in the below Figure.
107
Now let us try and develop a Sports Charges application to learn manipulation of check boxes. Design a form as shown in the below Figure. The aim of the application is to calculate the total charges payable by the user based on the sports selected. Note that all the text fields are disabled because they are just displaying the results and are not accepting any input from the user. The input is being taken in the form of selection of check boxes. On the selection of a particular sport check box, its charges are displayed in the adjacent text field and on the click of the Calculate Charges button, the charges for all the selected sports are added and displayed in the text field.
Code for the Sports charges application: private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: double amount=0; if (jCheckBox1.isSelected()) { amount=amount+2500; //cricket jTextField1.setText("2500"); } if (jCheckBox2.isSelected()) { amount=amount+1500; jTextField2.setText("1500"); }
108
if (jCheckBox3.isSelected()) { amount=amount+2000; jTextField3.setText("2000"); } if (jCheckBox4.isSelected()) { amount=amount+3500; jTextField4.setText("1000"); } jTextField5.setText(Double.toString(amount)); }
Q1: Design an application for Theatre Booking system. And answers the following questions:
A. When the user select different seat type, then its price should be displayed in the Label.
B. If the user enters an invalid no of seats i.e. less than I, then an error message should be
displayed in the dialog box.
C. When the user click at the Book Seats button , then total amount (calculated as no. of
seats x price per seat) should be displayed along with payment method, next to the push
button.
Price per seat depend upon the seat type :
Stall 625/-
Circle 750/-
Upper Circle 850/-
Box 1000/-
109
Ans:
(a) if(jRadioButton1.isSelected()==true)jLabel2.setText(“625”);
if(jRadioButton2.isSelected()==true) jLabel2.setText(“750”);
if(jRadioButton3.isSelected()==true) jLabel2.setText(“850”);
if(jRadioButton4.isSelected()==true) jLabel2.setText(“1000”);
(b) int s=Integer.parseInt(jTextField1.getText());
if(s<1)
JOptionPAne.showMessageDialog(null,”Error”);
(c) int s=Integer.parseInt(jTextField1.getText());
int p=Integer.parseInt(jLabel2.getText());
int tp=s*p;
if(jRadioButton5.isSelected()==true)
jLabel5.setText(“Cash Payment of “ +tp);
if(jRadioButton6.isSelected()==true)
jLabel5.setText(“Visa Payment of “ +tp);
if(jRadioButton7.isSelected()==true)
jLabel5.setText(“American Exress Payment of “+tp);
if(jRadioButton8.isSelected()==true)
jLabel5.setText(“Master Card Payment of “ +tp);
Q2 : Design the following application and answer the questions that follow :
(a) Write the code for the Clear button to clear all the textfields and checkbox. Set the default
choice in the radio button as Fixed Deposit.
(b) Write the code for the calculate button to calculate compound interest and amount and
display the values in the txtInterest and txtAmount depending on principal, rate and time.
Rate is calculated based on the time according to the following table:
110
Account Time Rate
Fixed Deposit <= 1 10%
>1 and <=5 12%
>5 15%
Recurring Deposit <= 2 11%
>2 and <=7 12%
>7 15%
An additional rate of 2% is given to the senior citizens i.e. if the chkSR checkbox is checked .
Ans:
(a) jTextField1.setText(“”);
jTextField2.setText(“”);
jTextField3.setText(“”); jRadioButton1.setSelected(true); jCheckBox1.setSelected(false);
(b) int p= Integer.parseInt(jTextField1.getText());
int t= Integer.parseInt(jTextField2.getText());
if(jRadioButton1.isSelected() )
{
if(t<=2) r=11;
else if(t>2 && t<=7) r=12;
else
r=15;
} else
{
if(t<=1) r=10;
else if(t>1 && t<=5) r=12;
else
r=15;
}
float ci= p*Math.pow((1+(r/100)),t);
float amt= p+ci;
txtInterest.setText(“”+ci);
txtAmount.setText(“”+amt);
111
Q 3: Consider the following application and answers the following questions:
The grading criteria for the two streams is given below :
Stream Percentage Grade
Medical >=80
60-80
<60
A
B
Non-Medical >=75
50-75
<50
A
B
A. Write code for Calculate Percentage button to calculate the Percentage
after finding the total marks of I term and II term . Also ensure that NCC
cadet gets an increment of 3% in their percentages.
B. Write code for Calculate grade button to calculate the grade depending
upon on the stream selected according to the given criteria.
Ans:
(a) float f= Integer.parseInt(jTextField1.getText());
float s= Integer.parseInt(jTextField2.getText());
float tot = f+s;
float p= tot/2;
if(jCheckBox1.isSelected()) p=p+3;
jLabelp.setText(“”+p);
( b) String g;
if(jRadioButton1.isSelected())
{
if(p>=80)
g=”A”;
112
else if(p>=60 &p<80)
g=”B”;
else
g=”C”;
}
else
{
if(p>=75)
g=”A”;
else if(p>=50 &p<75)
g=”B”;
else
g=”C”;
}
jLabelp.setText(“”+p);
jLabelg.setText(“”+g);
Q 4: Mr. Kumar works in a construction company. To calculate total wages he has developed the
following GUI in NetBeans.
Male and female workers are respectively paid Rs. 150/- per day and Rs. 170/- per day. Skilled workers are paid extra at the rate of Rs. 100/- day. Male and female workers from rural areas are paid 10% less per day.
a. When Calculate Wage button is clicked, the total wages is calculated as per the given
criteria and displayed in total wage text box.
b. When Clear button is clicked, all the text boxes should be cleared and radio button, check
box should be deselected.
c. Close the application when Quit button is pressed.
113
Ans:
(a) int w=0;
int d =Integer.parseInt(jTextField2.setText());
if(jRadioButton1.isSelected()) w=150; else
w=170;
if(jCheckBox1.isSelected())
w=w+100;
if(jRadioButton3.isSelected())
w=w-(w*10)/100;
int cw=d*w;
jLabel6.setText(“”+cw);
(b) jTextField1.setText(“”);
jTextField2.setText(“”); jRadioButton1.setSelected(false); jRadioButton2.setSelected(false); jRadioButton3.setSelected(false); jRadioButton4.setSelected(false); jCheckBox.setSelected(flase);
(c) System.exit(0);
Q 5: Mr. JigneshDesai an owner of Alpha Chemicals PVT ltd has asked his programmer Sweta to
develop the following GUI application in Netbeans:
114
Service Charges Rates are as follows :
Class of
City
Rate of Service
Charges
i 10% of sales price
ii 15% of sales price
iii 20% of sales price
Write java code for the following:
a. To calculate service charges depending on the selection of radio button. This code will
execute after click on the calculate service charges?
b. To calculate net price when Calculate Net price button will be clicked.
c. When exit button will be clicked application should be automatically closed.
Ans:
(a) float q=Float.parseFloat(jTextField2.getText());
float p=Float.parseFloat(jTextField3.getText());
float sp=q*p; jLabelsp.setText(“”+sp);
float sc;
if(jRadioButton1.isSelected()) sc=(10*sp)/100; else if(jRadioButton2.isSelected()) sc=(15*sp)/100;
else sc=(20*sp)/100;
jLabelsc.setText(“”+sc);
(b) float sp=Float.parseFloat(jLabelsp.getText());
float sc=Float.parseFloat(jLabelsc.getText()); float
np=sp+sc;
jLabelnp.setText(“”+np);
(c) System.exit(0);
Q6. Assume the following interface built using Netbeans used for bill calculation of a ice-
cream parlor. The parlor offers three verities of ice-cream - vanilla, strawberry, chocolate.
Vanilla ice- cream costs Rs. 30, Strawberry Rs. 35 and Chocolate Rs. 50. A customer can
chose one or more ice-creams, with quantities more than one for each of the variety
chosen. To calculate the bill parlor manager selects the appropriate check boxes according
to the verities of ice-cream chosen by the customer and enter their respective quantities.
Write Java code for the following:
115
(a) On the click event of the button 'Bill', the application finds and displays the total bill of
the customer. It first displays the rate of various ice-creams in the respective text fields.
If a user doesn't select a check box, the respective ice-cream rate must become zero.
The bill is calculated by multiplying the various quantities with their respective rate and
later adding them all.
(b) On the Click event of the clear button all the text fields and the check boxes get
cleared.
(c) On the click event of the close button the application gets closed.
Ans: (a) private void jBtnCalculateMouseClicked(java.awt.event.MouseEvent evt)
{
if(jchkStrawberry.isSelected()==true) jTxtPriceStrawberry.setText("35");
else
{
jTxtPriceStrawberry.setText("0"); jTxtQtyStrawberry.setText("0");
}
if(jChkChocolate.isSelected()==true)
jTxtPriceChocolate.setText("50"); else
{
jTxtPriceChocolate.setText("0"); jTxtQtyChocolate.setText("0");
}
if(jChkVinella.isSelected()==true)
jtxtPriceVinella.setText("30"); else
{
jtxtPriceVinella.setText("0"); jTxtQtyVinella.setText("0"); }
int r1,r2,r3,q1,q2,q3,a1,a2,a3,gt;
r1=Integer.parseInt(jTxtPriceStrawberry.getText());
r2=Integer.parseInt(jTxtPriceChocolate.getText());
r3=Integer.parseInt(jtxtPriceVinella.getText());
q1=Integer.parseInt(jTxtQtyStrawberry.getText());
q2=Integer.parseInt(jTxtQtyChocolate.getText());
q3=Integer.parseInt(jTxtQtyVinella.getText()); a1=r1*q1; jTxtAmtStrawberry.setText(""+a1); a2=r2*q2;
116
jTxtAmtChocolate.setText(""+a2); a3=r3*q3; jTxtAmtVinella.setText(""+a3); gt=a1+a2+a3; jTxtTotalAmt.setText(""+gt);
}
(a) private void jBtnClearActionPerformed(java.awt.event.ActionEvent evt)
{
jTxtPriceStrawberry.setText("");
jTxtPriceChocolate.setText("");
jtxtPriceVinella.setText("");
jTxtQtyStrawberry.setText("");
jTxtQtyChocolate.setText("");
jTxtQtyVinella.setText("");
jTxtAmtStrawberry.setText("");
jTxtAmtChocolate.setText("");
jTxtAmtVinella.setText("");
jchkStrawberry.setSelected(false);
jChkChocolate.setSelected(false);
jChkVinella.setSelected(false);
}
(c ) private void jBtncloseActionPerformed(java.awt.event.ActionEvent evt)
{
System.exit(0);
}
117
Exercises
1. What is the difference between Radio button and Check Box control? Explain with the help
of an example.
2. Explain the following methods of a Check box control?
(a) getText( )
(b) setText(String S)
(c) isSelected( )
(d) setSelected( )
3. Write a Java code for the following window to convert the temperature from Fahrenheit to
Celsius and Celsius to Fahrenheit.
4. Write a code for following window, the addition will be performed if the user clicks the
Addition check box and so that the product will be performed if the user clicks the Product
check box. Both or only one might be checked at any one time. The result will be displayed
on click of CALCULATE button.
118
5. Write a code for following Windows, on click of EXECUTE button the currency and the conversion into paise will be displayed if the user select the India Option button and so that currency and the conversion of Dollar to cents will be displayed if the user select the United States Option button. Only one will be selected at one time.
119
9. List Box and Combo Box
A List(also called list box) component displays a list of values/options from which single or multiple
values/items can be selected. When we place a list on JFrame form the default model property of
the list (default values in the list) has values as Item1, Item2and so on as shown in below Fig1.
The selectionMode property is set to MULTIPLE_INTERVAL by default ensuring that a user can
select multiple items from the list. These properties can be changed using the properties window
as shown in Fig:2.
Fig:1 (default values in the list)
Fig:2 Common Property of List
The selectionMode property has three possible values. The usage of each of these values is
explained below:
SINGLE implies that List box will allow only a single value to be selected.
SINGLE_INTERVAL implies that List box allows single continuous selection of options
using shift key of keyboard (i.e. values which occur in succession).
MULTIPLE_INTERVAL implies that List box allows multiple selections of options using
ctrl key of keyboard.
The model property is used to change the choices displayed in the list. The values can be updated
by clicking on the ellipsis(..) next to the property in the properties window as displayed in the
below Figure:
120
Modifying the model property of the jList component results in a change in the values displayed in
the list as shown in the below Figure.
Let us now design an application Restra Order using the food list created to help us understand
how to use a list component in an application. Design the form as shown in the above Figure. The
form consists of a list, a button, a text field and two labels - one for explaining the selection
process and one for indicating that the payable amount is in rupees. The aim of the application is
to allow the user to place an order for multiple items displayed in the list and display the bill
amount in the text field which will be calculated on the basis of the items selected. The menu
options are shown in the below Figure:
121
Let us now write the code for the above application as shown below:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
int Total=0;
//Bhel Puri, Pasta, Pizza, Burger;
if (jList1.isSelectedIndex(0)==true)
{
Total=Total+150;
JOptionPane.showMessageDialog(this,"Bhel Puri Ordered Rs.150");
}
if (jList1.isSelectedIndex(1)==true)
{
Total=Total+300;
JOptionPane.showMessageDialog(this,"Pasta Ordered Rs.300");
}
if (jList1.isSelectedIndex(2)==true)
{
Total=Total+200;
JOptionPane.showMessageDialog(this,"Pizza Ordered Rs.200");
}
if (jList1.isSelectedIndex(3)==true)
{
Total=Total+180;
JOptionPane.showMessageDialog(this,"Burger Ordered Rs.180");
122
}
if (jList1.isSelectedIndex(4)==true)
{
Total=Total+220;
JOptionPane.showMessageDialog(this,"Pav Bhaji Ordered Rs.220");
}
jTextField1.setText(Integer.toString(Total));
}
The above code introduces us to a new method - isSelectedIndex() method. This method is used
to check whether the index specified in the parenthesis has been selected or not.
The syntax of this method is given below:
Syntax:
jList.isSelectedIndex(int num)
The num is an integer value and represents the index value to be checked. The index numbering
starts at 0. This method returns a boolean value i.e. true or false. The true indicates that the value
at the specified index is selected and false indicates that the value is not selected.
123
Commonly used methods of List control are as follows:
Method Description
getSelectedValue() Returns the selected value when only a
single item is selected. If multiple items
are selected then it returns the first
selected value. Returns null incase no
item is selected.
isSelectedIndex(int index) Returns true if specified index is selected.
Combo Box
This control is used to display a list of choices from which the user can choose a single option.
The difference between combo box and list box control is that a list box control allows user to
make one or more selections whereas a combo box control allows the user to make single
selection.
A Simple Combo Box
When we place a combo box on the JFrame form by default it shows Item1 as the first value as
shown in the above Figure. A Combo box appears like a text field with a drop down list arrow.
The common properties of the Combo Box can be edited using the properties window as shown
in below Figure.
124
Common Properties of the Combo Box Component
The default values displayed in a combo box are Item1, Item 2 and so on. These can be edited by
clicking on the ellipse(…) next to the values. Let us create a combo box having the name of cities.
Drag the Combo Box component from the Swing Controls tab and then type the items that we
want to be displayed in the combo box by clicking on the model property ellipse button. The new
values we typed in are shown in the below Figure.
Modifying the model Property of a Combo Box
Now Bangalore is the first value in the model property therefore on the form Bangalore will be
displayed with a drop down list arrow as shown in the above Figure.
Let us design an application called City Highlights to learn the usage of combo box. Design a
simple form with a combo box (containing names of 5 cities) and a button with display text as
"Know More". The required functionality is that on executing the application City Highlights, the
125
user should select a particular city and click on the button to view some additional information
about the city. Sample run of the application is shown in the below Figure.
Sample Run of the City Highlights Application
126
The code for the City Highlights application is as shown below:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
if (jComboBox1.getSelectedIndex()==0)
JOptionPane.showMessageDialog(this,jComboBox1.getSelectedIte m()+
" - Known as Silicon Valley of India");
else if (jComboBox1.getSelectedIndex()==1)
JOptionPane.showMessageDialog(this,jComboBox1.getSelectedI tem()+
" - Capital City of India");
else if (jComboBox1.getSelectedIndex()==2)
JOptionPane.showMessageDialog(this,jComboBox1.getSelectedI tem()+
" - Known for broad Industrial Base");
else if (jComboBox1.getSelectedIndex()==3)
JOptionPane.showMessageDialog(this, jComboBox1.getSelectedItem()+
" - Known for literary, artistic and revolutionary heritage");
else if (jComboBox1.getSelectedIndex()==4)
JOptionPane.showMessageDialog(this,jComboBox1.getSelectedI tem()+
" - Known for hub of Bollywood");
}
This code introduces us to two new methods, the getSelectedIndex() method and
thegetSelectedItem() method. The syntax and usage of each of these methods is explained
below:
1. getSelectedIndex() - This method is used to return the index of the selected item. If an item is
selected only then will the getSelectedIndex method return a value else it returns -1. The syntax of
this method is given below:
Syntax:
jComboBox.getSelectedIndex()
2. getSelectedItem() - This method is used to return the selected item. The syntax of this method
is given below:
Syntax:
jComboBox.getSelectedItem()
127
Exercises
1. What methods adds new items to a list box?
2. Which method determines the number of items in a list box?
3. What is the difference between List box and Combo box?
4. While working in Netbeans, Abhishek included a Listbox in the form. Now he wants the list
of her friends' names to be displayed in it. Which property of Listbox control should he use
to do this?
5. Glamour Garments has developed a GUI application for their company as shown below :
The company accepts payments in 3 modes- Cheque, cash and credit cards. The discount given
as per mode of payment is as follows.
If the Bill Amount is more than 15000 then the customer gets an additional discount of 10% on Bill
Amount.
(i) Write the code to make the textfields for Discount (named txtDisc) and Net Amount
(named txtNetAmt) uneditable.
(ii) Write code to do the following:
128
(a) . When "Calculate Discount" button is clicked the discount should be calculated as per the
given criteria and it should be displayed in the discount textfield. "Calculate Net Amount"
button (named btnCalcNetAmt) should also be enabled.
(b) When "Calculate Net Amount" button is clicked the net amount should be calculated and it
should be displayed in the net amount textfield.
6. Write a code for the following window that builds a list as the user enters new values. As the user enters more and more name of books the list should grow. Add four command buttons :
(a) Add a command button to the form with the caption ADD when the user clicks the command button, the name of book just entered in the textbox goes to the list. (b) REMOVE command button to remove a particular item from the list. (c) “>>” command button to move an item from left list box to right list box. (Move the books which you like to list box2) (d) END command button to end the application.
129
10. Menus
You can add menus to your Java forms, things like File, Edit, View, etc. Each menu has menu items, and these in turn can have sub menus.
Return to Design view. In the NetBeans palette, locate the Menu Bar item:
Drag one to the top of your form. When you let the mouse button go, you'll have a default File and Edit menu bar:
There's no menu items added by default, though. To add your own, click on the File menu item to select it. With the File menu item selected, right-click. A new menu will appear. Select Add From Palette > Menu Item:
130
A Menu Item will be added to your File menu:
What we'll do is to add menu items to open and save a file. Double click on the default text jMenuItem1. It will then be highlighted, so that you can type over it:
Type Open, then press the enter key on your keyboard:
Add another menu item in the same way. This time, type Save as the menu item:
As you can see above, you can add shortcuts for your menu items. Click on to the Open menu item, then onto the shortcut for it:
With the shortcut item selected, have a look at the properties window:
Locate the Accelerator item, and click the small button to the right of the row. A dialogue box appears. You can set which shortcut keys you want for a menu item from this dialogue box. An open shortcut is usually CTRL + O.
131
Type an O in the box, and Shift + O will appear. Uncheck the Shift item and check Ctrl instead:
Click OK, and the shortcut will be added to your Java menu item:
To see if all this works, click back on the Open menu item to highlight it. Now right click. From the menu that appears, select Events > Action > Action Performed. This will create a code stub for the menu item. Enter the following for the code:
JOptionPane.showMessageDialog(null,"Open");
This will display just a message box.
Run your programme and try it out. Click File > Open and you should see the message box
appear. Click OK to get rid of it. Now try your shortcut. Hold down the Ctrl key on your keyboard.
Keep it held down and press the letter O. Again, the menu should appear. Sample run of the
application is shown in the below Figure.
132
Exercise
1. Create a Menu containing Project, Format, Run as menu items.
2. Create a drop down menu with the following menu bar items:
Project, Format and Run. The menu structure is as follows:
A. File
1. New Project
2. New File
B. Edit
1. Undo
2. Redo
C. View
1. Editors
2. Split
3. Create a drop down Menu as shown in following figure:
133
11. Sample Applications and Case Studies
Application 1: Create an application that works similar to a text editor and provides the
following features:
Allows a user to type text in this text editor
Allows the user to copy, cut and paste the text
Allows the user to exit from the text editor
Answer:
Perform the following steps to create the required GUI application:
1. Start the NetBeans IDE and create a new project.
2. Add a frame to the project.
3. Set the title of frame as Text Editor Form.
4. Now add the four Button controls and a Text Area control from a swing controls
section of the Palette pane. Arrange these controls in the TextEditor frame, as
shown in the following figure.
5. Type the following code in the action event handler of the copy button:
jTextArea1.copy();
134
6. Type the following code in the action event handler of the cut button:
jTextArea1.cut();
7. Type the following code in the action event handler of the paste button:
jTextArea1.paste();
8. Type the following code in the action event handler of the exit button:
System.exit(0);
9. Save and run your application. The output appears, as shown in the following
figure:
10. To perform the copy operation, type some text in the text area, as shown in the
following figure:
135
11. Select the text that you want to copy and click the copy button, as shown below
figure:
12. Now, select the desired location where you want to copy the selected text and
click the Paste button, as shown in the following figure:
136
Application 2: Create a Java Swing toolbar using the Tool Bar control.
Answer:
Perform the following steps to create the required GUI application:
1. Create a new Java application in the Netbeans IDE and add a frame to it. After that, go to
the design view of the GUI builder and drag a Tool Bar from the Swing Container section of
the Palette pane onto the frame, as shown in the figure below:
An empty toolbar (or a place holder for buttons) will be added to the frame. By default, a
horizontal toolbar is added. However, you change its orientation to vertical using the
Properties window.
2. Now, on the empty place holder (that is, toolbar), you are required to add buttons. To do
this, drag and drop the Button control from the Swing Controls section to the toolbar
container, as shown in the below figure:
137
3. Select the added button and set its icon property to display an image on it.
4. Set the text property if you want display a text label along with icon on the button. After
adding few button and after setting these properties, the toolbar will look like, as shown in
the below figure
5. In the action event handler of these buttons, we are simply displaying the names of buttons
through the JoptionPane’s dialog box. Following are the lines of code for each button
defined on the toolbar container:
JOptionPane.showMessageDialog(null,"You are selected Home option");
JOptionPane.showMessageDialog(null,"You are selected Mail option");
JOptionPane.showMessageDialog(null,"You are selected Department option");
JOptionPane.showMessageDialog(null,"You are selected Faculty option");
JOptionPane.showMessageDialog(null,"You are selected Job option");
JOptionPane.showMessageDialog(null,"You are selected About us option");
6. Save and press F6 key on the keyboard to run your application.
138
7. Click the Home button or any other button. A message dialog box appears as shown in
below figure
The new toolbar with Mail Button’s message dialog box.
The newtoolbar with Faculty button’s message dialog box.
139
Application 3:
Create a GUI application to obtain the details of a student, such as roll
number, name, class, subject, and marks through text fields and add them in a table. The
application should also provide the option to display total count of records in the table along
with the option to exit from the application. The GUI of the application should appear as
shown the below figure:
Answer: Perform the following steps to create such an application:
1. Create a new application in NetBeans IDE and add a frame to it.
2. Add a Table control by dragging and dropping it onto the frame from the Swing controls
section of Palette pane, as shown in the below figure:
3. Right-click on the table and change the variable name as StdntTbl.
4. While keeping the table selected, click the ellipsis button of the model property in the
Properties dialog box. A dialog box appears.
5. Set the number of rows (initially) as well as the heading of columns in this dialog box. Now,
specify the column headings as RollNO, Name, Class, Subject, MaxMarks, MarksObt. Set
the rows field in the button left corner as 0 (zero), because we do not want any initial rows
(rows will be added during the runtime). After that, click the OK button, as shown in the
below figure:
140
Adding Column Names to Table’s Model
After adding the column’s heading to the StdntTbl table, your application will appear shown
in the below figure:
The Application GUI after Adding Column Headings
141
6. Now, add the text fields and button controls to your application and arrange them as shown
in the below figure:
7. To append the values that are entered in the text fields to the StdntTbl table as rows, you
need to double click the Add Row button and type the following code:
Object [] addRows={jTextField1.getText(),jTextField2.getText(),jTextField3.getText(),
jTextField4.getText(), jTextFiled5.getText(), jTextField6.getText()};
DefaultTableModel dtm=(DefaultTableModel) jTable1.getModel();
dtm.addRow(addRows);
jTextField1.setText(" ");
jTextField2.setText(" ");
jTextField3.setText(" ");
jTextField4.setText(" ");
jTextField5.setText(" ");
jTextField6.setText(" ");
To display total number of records in table, double click the Count Total Record button and
add the following lines of code:
JOptionPane.showMessageDialog(null,"Total Number of records are
:"+jTable1.getRowCount());
142
8. Finally double click the Exit button and type the following code to the action event handler
of this button:
System.exit(0);
9. Save the application and run it. The output will be as shown in the below figure:
The Output of the New Application
Getting Total Records in the Table
143
Application 4:
Create an application consisting of a color chooser, buttons and a label as
shown in the below figure:
Answer: Perform the following steps to design an application similar to the one as shown
in the above figure:
1. Create a new application using NetBeans IDE and add a frame to the application.
2. Now drag a color chooser control from the swing windows section of the Palette pane
and drop it on the frame as shown in the below figure.
144
3. Add three button controls and one label control to the frame and name them
accordingly. Moreover, ensure that the Opaque property of the label is set to true by
selecting its check box. If you do not set this property, you will not able to view the filled
color. After adding all the components to the frame, your application will look similar to
the one shown in the below figure.
4. First you need to include import statement import java.awt.Color; at the top of your
application. Now double click the apply foreground button (forBtn) button and add the
following code in the action event handler of this button:
Color forgrndColor=jColorChooser1.getColor();
disLabel.setForeground(forgrndColor);
5. Double click the apply Background (backBn) button and add the following code in the
action event handler of this button:
Color backgrndColor= jColorChooser1.getColor();
disLabel.setBackground(backgrndColor);
6. Double click the exit (exitBtn) button and add the following code in the action event
handler of this button:
System.exit(0);
145
7. Finally save and run your application. The output is shown in the below figure:
Using the application shown in the above figure, you can choose a desired color from the color
chooser control by selecting any of the three tabs: Swatches, HSB and RGB.
The Output of the Application
146
Application 5:
Create a Quiz application similar to the one shown in the below figure:
The main frame QuizForm.java provide the following functionality:
The main frame QuizForm.java consists of a menu bar containing three menus: Hardware,
Software and Exit. The Hardware menu contains three menu items (namely- Input Devices,
Memory Devices and Output Devices), the Software menu contains two menu items
(namely- System Software and Application Software) and Exit menu to exit the application.
Answer: Perform the following steps to design an application similar to the one as shown
in the above figure:
1. Create a new application using NetBeans IDE and add a frame (QuizForm.java.) to the
application. Change the title of the frame TEST YOUR KNOWLEDGE.
2. Add menus and menu items to the main frame QuizForm.java. Add two label controls by
dragging and dropping it onto the frame from the Swing controls section of Palette pane.
147
Change the text of jLabel1 “TEST YOUR KNOWLEDGE” and change the icon of
jLabel2 that display an image for Quiz as shown in the below figure:
3. Add a new frame HardwareInputJPanel.java and design it as shown in the below figure:
148
4. Similarly design add new frames
HardwareOutputJPanel.java, HardwareMemoryJPanel.java,SoftwareApplicationJPanel.java
and SoftwareSystemJPanel.java as shown in the below figures:
HardwareOutputJPanel.java
HardwareMemoryJPanel.java
150
5. The code for main frame (QuizForm.java) is as below:
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt)
{
HardwareInputJPanel s=new HardwareInputJPanel();
s.setVisible(true);:
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt)
{
HardwareOutputJPanel s=new HardwareOutputJPanel();
s.setVisible(true);
}
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt)
{
HardwareMemoryJPanel s=new HardwareMemoryJPanel();
s.setVisible(true);
}
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt)
{
SoftwareSystemJPanel s=new SoftwareSystemJPanel();
s.setVisible(true);
}
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt)
{
SoftwareApplicationJPanel s=new SoftwareApplicationJPanel();
s.setVisible(true);
}
151
6. The code for Submit Button of HardwareInputJPanel.java is as follows:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
if (jRadioButton3.isSelected())
jLabel6.setText("Correct");
else
jLabel6.setText("Incorrect");
if (jRadioButton8.isSelected())
jLabel7.setText("Correct");
else
jLabel7.setText("Incorrect");
}
7. The code for Submit Button of HardwareOutputJPanel.java is as follows:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
if (jRadioButton4.isSelected())
jLabel3.setText("Correct");
else
jLabel3.setText("Incorrect");
if (jRadioButton7.isSelected())
jLabel5.setText("Correct");
else
jLabel5.setText("Incorrect");
}
8. The code for Submit Button of HardwareMemoryJPanel.java is as follows:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
if (jRadioButton3.isSelected())
jLabel3.setText("Correct");
else
jLabel3.setText("Incorrect");
if (jRadioButton8.isSelected())
jLabel5.setText("Correct");
else
jLabel5.setText("Incorrect");
}
152
9. The code for Submit Button of SystemSoftwareJPanel.java is as follows:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
if (jRadioButton2.isSelected())
jLabel4.setText("Correct");
else
jLabel4.setText("Incorrect");
if (jRadioButton5.isSelected())
jLabel7.setText("Correct");
else
jLabel7.setText("Incorrect");
}
10. The code for Submit Button of ApplicationSoftwareJPanel.java is as follows:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
if (jRadioButton4.isSelected())
jLabel3.setText("Correct");
else
jLabel3.setText("Incorrect");
if (jRadioButton5.isSelected())
jLabel5.setText("Correct");
else
jLabel5.setText("Incorrect");
}
11. The code for Close sub menu of Exit menu is as follows:
System.exit(0) ;
12. Finally save and run your application. The output is shown in the below figures: