0% found this document useful (0 votes)
5 views150 pages

Java

The document is a laboratory manual for second-year computer science students at Debark University, focusing on Object-Oriented Programming (OOP) using Java. It covers a range of topics including Java history, programming paradigms, and various Java concepts such as classes, methods, and exception handling, structured into 15 lab lessons. The manual aims to equip students with the necessary skills to code, debug, and run Java programs effectively.

Uploaded by

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

Java

The document is a laboratory manual for second-year computer science students at Debark University, focusing on Object-Oriented Programming (OOP) using Java. It covers a range of topics including Java history, programming paradigms, and various Java concepts such as classes, methods, and exception handling, structured into 15 lab lessons. The manual aims to equip students with the necessary skills to code, debug, and run Java programs effectively.

Uploaded by

ermiyigzaw
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

DEBARK UNIVERSITY

COLLEGE OF NATURAL AND COMPUTATIONAL SCIENCE

DEPARTMENT OF COMPUTER SCIENCE

OBJECT ORIENTED PROGRAMMING (CoSc2082)

LABORATORY MANUAL

FOR SECOND YEAR COMPUTER SCIENCE STUDENTS

PREPARED BY

ABRAHAM ALAMIREW (MSC)

DECEMBER, 2024

DEBARK, ETHIOPIA
Table of Contents
List of Figure...............................................................................................................................................iv
List of Table.................................................................................................................................................iv
Acknowledgment.........................................................................................................................................v
Certificate...................................................................................................................................................vi
Manual Objective.......................................................................................................................................vii
Preface......................................................................................................................................................viii
Acronyms....................................................................................................................................................ix
Lab One- Introduction to Object-Oriented Programming............................................................................1
1.1 Introduction to Object-Oriented Programming (OOP).................................................................1
1.2 What is Java?.....................................................................................................................................2
1.3 Java History and Evolution.................................................................................................................2
1.4 Language Characteristics of java........................................................................................................3
1.5 Java Editions......................................................................................................................................3
1.6 What is the Java Runtime Environment (JRE)....................................................................................3
1.7 What is Java Virtual Machine (JVM)..................................................................................................4
1.8 What is the Java Development Kit (JDK)............................................................................................4
1.9 Free java integrated development environment (IDE)......................................................................4
1.10 Java comments..............................................................................................................................15
1.11 Program Sharing............................................................................................................................16
1.12 keywords (Reserved words)...........................................................................................................17
1.13 Types of programming paradigm...................................................................................................18
1.14 Overview of Object-oriented principles.....................................................................................21
1.15 Overview of Java Programming and types of Java Program......................................................22
Lab two- Basics in Java Programming........................................................................................................24
2.1 Basics in Java Programming.............................................................................................................24
2.2 Variable types..................................................................................................................................25
2.3 Data type.........................................................................................................................................26
2.4 Number types and strings................................................................................................................29
Lab Three- Operators................................................................................................................................37

i
3.1 Operators.........................................................................................................................................37
3.2 Operator precedence......................................................................................................................50
3.3 Type Casting....................................................................................................................................51
Lab Four- Java statements.........................................................................................................................54
4.1 Overview of Java statements...........................................................................................................54
4.2 Decision and Repetition Statements................................................................................................55
4.3 If, if-else and Switch.........................................................................................................................55
4.4 Array in Java.....................................................................................................................................59
Lab Five- Loops..........................................................................................................................................63
5.1 For loop...........................................................................................................................................64
5.2 While loop.......................................................................................................................................65
5.3 Do-while loop..................................................................................................................................66
5.4 Java Break Statement......................................................................................................................68
5.5 Java Continue Statement.................................................................................................................68
Lab Six-objects and classes........................................................................................................................70
6.1 Object..............................................................................................................................................71
6.2 Classes.............................................................................................................................................71
6.3 instantiating and using objects........................................................................................................73
Lab Seven-Constructor and method.........................................................................................................75
7.1 Constructor......................................................................................................................................76
7.2 Method............................................................................................................................................78
Lab Eight- Encapsulation and Inheritance..................................................................................................81
8.1 Object-oriented programming concepts.........................................................................................81
8.2 Encapsulation..................................................................................................................................82
8.3 Inheritance......................................................................................................................................83
Lab Nine- Method Overloading.................................................................................................................97
9.1 Method overloading........................................................................................................................97
9.2 Method Overriding..........................................................................................................................99
9.3 Advantage of method overriding.....................................................................................................99
9.4 method overloading vs overriding in Java.....................................................................................100
Lab Ten- Polymorphism...........................................................................................................................102
10.1 Polymorphism..............................................................................................................................102

ii
Lab Eleven- Abstract Class and Interfaces...............................................................................................106
11.1 Abstract Class characteristics.......................................................................................................106
11.2 Interfaces characteristics.............................................................................................................106
11.3 Abstract class vs interface in Java................................................................................................107
Lab Twelve – Exception...........................................................................................................................122
12.1 Exception handling overview.......................................................................................................122
12.2 Exception.....................................................................................................................................122
12.3 Why an exception occurs.............................................................................................................123
12.4 Advantage of exception handling................................................................................................123
12.5 Difference between error and exception.....................................................................................123
12.6 Types of exceptions.....................................................................................................................123
Lab Thirteen- Exception handling syntax.................................................................................................125
13.1 Exception handling syntax...........................................................................................................125
Lab Fourteen –Java Applets.....................................................................................................................131
14.1 Java Applets.................................................................................................................................131
14.2 Features of Applets over HTML...................................................................................................132
14.3 Restrictions imposed on Java applets..........................................................................................132
14.3 Applet life cycle...........................................................................................................................132
Lab Fifteen- Java applications..................................................................................................................136
15.1 What is an Application?...............................................................................................................136
15.2 Difference between Application and Applet................................................................................137
References...............................................................................................................................................139

iii
List of Figure
Figure 1-1 unstructured Programming.......................................................................................................18
Figure 1-2 Procedural programming..........................................................................................................19
Figure 1-3 Structured Programming..........................................................................................................20
Figure 1-4 Object-oriented Programming..................................................................................................21

List of Table
Table 1-1 keywords (reserved words) in java............................................................................................17
Table 2-1 java separators...........................................................................................................................34
Table 3-1 Arithmetic operators in java......................................................................................................37
Table 3-2 Relational operators in java.......................................................................................................39
Table 3-3 Bitwise operator in java.............................................................................................................41
Table 3-4 Logical operators in java...........................................................................................................42
Table 3-5 Assignment operator in java......................................................................................................44
Table 3-6 Increment and decrement operator in java.................................................................................46

iv
Acknowledgment
First and foremost we are ever grateful to our God to whom we owe our life. Next, I express my
heart full appreciation and owe a deep sense of gratitude to the manual reviewer Mr.
xxxxxxxxxxxxxxxx for his professional support and encouragement throughout this manual. Our
efforts would not have been successful without the guidance of reviewer Mr. xxxxxxxxxxx
useful inputs, helpful comments, insightful comments, and most of all his patience with me from
the beginning to the end of the manual. And also I need to release the feeling of our gratitude to
several persons who helped me directly or indirectly to conduct this manual work, The
completion of this undertaking could not have been possible without the participation and
assistance of them, I appreciated and gratefully acknowledged those of them. Finally, I would
like to thank the Debark University Department of Computer Science manual committee for their
contribution to the achievement of the manual.

v
Certificate
This is to certify that this manual entitled Object-Oriented Programming(OOP) Laboratory
manual written by:

Name Sign
Abraham Alamirew

The fulfillment and the requirements for the manual approved by me for submission. I certify
further that, to the best of my knowledge, the manual represents work carried out by Abraham
Alamirew and free from plagiarism.

Manual Reviewer

_______________________________ ___________ ____________

Name of Reviewer Signature Date

Evaluator

_______________________________ ___________ ____________

_______________________________ ___________ ____________

Name of Evaluator Signature Date

Manual Objective
After successful completion of the Manual students will be able to
vi
 Explain the basic Object-oriented concepts
 Work on more advanced programs written in Java
 Successfully code, debug and run java programs with the appropriate development
environment
 Understand the difference between structural and Object-oriented programming
paradigms

vii
Preface
Java is the preeminent language of the Internet. Moreover, it is the universal language of Web
programmers around the world. To be a professional Web developer today implies proficiency in
Java. Therefore, if Internet-based programming is in your future, you have chosen the right
language to learn and this Manual will help you learn it. The purpose of this Manual is to teach
you the fundamentals of Java programming. It uses a step-by-step approach complete with
numerous Eg. self-tests, and questions. It assumes no previous programming experience. The
manual starts with the basics, such as how to open, compile, and run a Java program. It then
discusses java, java history, keywords, features, java statement, object, class, constructor,
method, abstract class, interface, exception, java applet, java application, and constructs that
form the core of the Java language. By the time you finish, you will have an affirmed grasp of
the essentials of Java programming. It is important to state at the outset that this Manual is just a
starting point. Java is more than just the elements that define the language. Java also includes
extensive libraries and tools that aid in the development of programs. To be a top-notch Java
programmer implies mastery of these areas, too. After completing this Manual, you will have the
knowledge to pursue any and all other aspects of Java.

This laboratory manual has 15 lab lessons for each lesson it require one week(3 credit hour) to
complet.

viii
Acronyms
 AC-Alternate current
 JVM-Java virtual machine
 GUI-Graphical user interface
 JDK- Java Development Kit
 WORA-Write once run anywhere
 OOP-Object-oriented programming
 JRE- Java Runtime Environment
 IDE- Integrated development environment
 OOPL- Object-oriented programming language
 HTML-Hyper text markup language
 VCR-Video cassette recorder
 CRT-Cathode ray tube

ix
Lab One- Introduction to Object-Oriented Programming
Objective- At the end of these lesson students will able to understand

 Java History and Evolution


 Language Characteristics for java
 Java Editions
 Java Runtime Environment (JRE)
 Java keywords
 Free java integrated development environment (IDE)
 Types of programming paradigm
 How to open, run and share program using NetBeans IDE
 Java comments and its type

1.1 Introduction to Object-Oriented Programming (OOP)


Object-Oriented Programming (OOP) is a programming paradigm that empowers us to construct
specific objects and define methods to interact with these objects [1]. The fundamental concept
of OOP revolves around creating objects, utilizing them repeatedly within the program, and
manipulating them to achieve desired outcomes. The central goal of object-oriented
programming is to improve the maintainability and adaptability of applications. By consolidating
data and its corresponding behavior (methods) within a unified entity (object), OOP simplifies
the comprehension of program functionality [2].

Benefits of Object-Oriented Programming

 Enhanced software quality


 Accelerated development cycles
 Reduced development costs
 Enhanced software maintainability
 Increased productivity in software development

1
Advantages of OOPs over Procedure-oriented programming language
 Object-oriented Programming simplifies code development and maintenance, making it
easier to handle larger projects. In contrast, managing code in a procedure-oriented
programming language becomes challenging as the project size increases.
 Object-oriented Programming incorporates data hiding, ensuring that global data cannot
be accessed from any location as is possible in a procedure-oriented programming
language.
 Object-oriented Programming excels at simulating real-world events more effectively
compared to procedural-oriented programming. By utilizing an Object-Oriented
Programming language, we can readily solve real-world problems with greater ease.
Challenges associated with OOP

 Steep learning curve


 Larger program size
 Slower program execution
 It is not a one-size-fits-all solution

1.2 What is Java?


Java is an object-oriented programming language developed by Sun Microsystems [1]. It is
intended for the development of platform-independent software i.e. executing the same Java
program on multiple targets (platforms) requires no porting efforts. Modeled after C++, the Java
language was designed to be small, simple, and portable across platforms and operating
[Link] Technology is both a programming language and a platform. Java is an object-
oriented programming language (OOPL) and an open architecture means developed once and
implemented everywhere [3].

1.3 Java History and Evolution


Java language was developed at Sun Microsystems in 1991 as part of a research project (called
Green project) to develop software for consumer electronics devices-television sets, VCRs,
toasters, and other sorts of machines. Java's goals at that time were to be small, fast, efficient,
and easily portable to a wide range of hardware devices [4]. The original impetus (motivation)
for Java was the need for platform-independent language for embedded systems that is to

2
develop special software that could be used to manipulate consumer electronic devices such as
microwave ovens, remote control, toasters, etc… and what made Java popular was the web.

1.4 Language Characteristics of java


Java programming language is case-sensetive high-level language that can be characterized by
all of the following[10].
 Simple
 Familiar
 Object-oriented
 Portable
 High performance
 Multithreaded
 Dynamic
 Secure

1.5 Java Editions


In order to accommodate the very different requirements of different classes of computers, an
important split has been made. Instead of one all-purpose Java, different flavors of Java
specifications [4].
1. Standard edition
2. Enterprise edition
3. Micro Edition

1.6 What is the Java Runtime Environment (JRE)


The Java Runtime Environment (JRE) encompasses the necessary libraries, the Java Virtual
Machine, and additional components essential for executing applets and applications coded in
the Java programming language [3]. However, it is important to note that the JRE does not
include development tools or utilities like compilers or debuggers for creating applets and
applications. Its primary function is to facilitate the runtime execution of Java programs.

JRE is a collection of tools. These tools together allow the development of applications and
provide a runtime environment [4]. JVM is a part of JRE. JRE is also platform-dependent like
JVM.

3
1.7 What is Java Virtual Machine (JVM)
Java Virtual Machine provides a runtime environment in which we can execute the byte code [1].
JVM is platform-dependent. It performs the following tasks

 Loading the code


 Verifying the code
 Executing the code
 Providing a runtime environment

1.8 What is the Java Development Kit (JDK)


The Java Development Kit (JDK) offers a comprehensive environment for developing and
running Java programs[10]. Within the JDK, you'll find a set of Development Tools designed to
provide a conducive environment for Java programming. In addition to the JRE, the JDK
encompasses various resources such as the interpreter, loader, compiler, archiver (jar), and
documentation generator (Javadoc) [2]. These components work in unison to facilitate the
construction of Java programs with efficiency and effectiveness.

1.9 Free java integrated development environment (IDE)


Eclipse-is free java IDE for developers and programmers and mostly written with java this IDE
used to create various cross-platform java applications for use on mobile, web, desktop, and
enterprise applications [4].

NetBeans IDE

The Smarter and Faster Way to Code- NetBeans IDE is a great tool for Java, mobile, and web
app development, including HTML5. It also supports PHP and C/C++. Free and open source
with a strong global community. Enjoy easy and fast development on multiple platforms.

Best Support for Latest Java Technologies- NetBeans IDE is the official IDE for Java 8.
Quickly upgrade applications to use new Java 8 features like lambdas and method references.

4
Fast & Smart Code Editing-An IDE does more than a text editor. NetBeans Editor indents
lines, matches words and brackets, and highlights source code syntactically and semantically. It
allows easy code refactoring with powerful tools, as well as code templates, tips, and generators.

Easy & Efficient Project Management- Managing large applications with numerous folders,
files, and extensive code can be overwhelming [4]. NetBeans IDE simplifies this task by offering
various data views, multiple project windows, and efficient tools for application setup and
management. It allows you to navigate through your data swiftly, enabling easy access to
specific details. Additionally, NetBeans IDE provides built-in support for versioning tools such
as Subversion, Mercurial, and Git, ensuring seamless integration for effective code version
control. With NetBeans IDE, you can maintain a clear and organized overview of your large
applications, enhancing productivity and reducing complexity.

5
Rapid User Interface Development- Design GUIs for Java SE, HTML5, Java EE, PHP, C/C++,
and Java ME applications quickly and smoothly by using editors and drag-and-drop tools in the
IDE.

Write Bug Free Code- Fixing buggy code promptly reduces long-term costs [4]. NetBeans
offers static analysis tools, including integration with FindBugs, to identify and resolve common
Java code issues. The NetBeans Debugger allows for breakpoints, field watches, code stepping,
method running, snapshots, and real-time execution monitoring.

6
Support for Multiple Languages- NetBeans IDE is a powerful development environment with
support for many programming languages and technologies [3]. It has tools for Java, HTML5,
PHP, C/C++, XML, Groovy, Javadoc, JavaScript, and JSP. It is free, open-source, and has a
large user community worldwide. Ideal for managing complex applications.

Cross Platform Support- NetBeans IDE can be installed on all operating systems that support
Java, from Windows to Linux to Mac OS X systems. Write Once, Run Anywhere, is as true for
NetBeans IDE as it is for your own applications.

Rich Set of Community Provided Plugins- The NetBeans community is large and active; many
users are developing new plugins all the time because NetBeans IDE is extensible and has well-
documented APIs.

NetBeans IDE 8.1-for this course we use this IDE.

NetBeans IDE 8.1 offers pre-built code analyzers and editors designed to seamlessly integrate
with the latest Java 8 technologies, including Java SE 8, Java SE Embedded 8, and Java ME
Embedded 8 [4]. The IDE introduces a host of new tools for HTML5/JavaScript development,
specifically catering to [Link], KnockoutJS, and AngularJS. It also includes enhancements that
enhance its support for Maven and Java EE, incorporating PrimeFaces. Furthermore, NetBeans
IDE 8.1 brings improvements to its PHP and C/C++ support. The IDE is available in multiple
languages, including English, Brazilian Portuguese, Japanese, Russian, and Simplified Chinese,
catering to a diverse user base.

NetBeans IDE 8.1 Installation Instructions

Step 1: Install JDK

 Before installing NetBeans, you need to have the Java Development Kit (JDK) installed
on your system. You can download the JDK from the Oracle website.

Step 2: Download NetBeans IDE 8.1

7
 Go to the NetBeans website ([Link] and download
the NetBeans IDE 8.1 installer.

Step 3: Run the Installer

 Once the installer is downloaded, run it on your system.

Step 4: Choose Installation Options

 During the installation process, you will be prompted to choose the installation options.
Make sure to select the appropriate options for your needs.

Step 5: Select JDK Installation

 When prompted, select the JDK installation that you previously installed on your system.

Step 6: Complete the Installation

 Follow the on-screen instructions to complete the installation process.

Step 7: Launch NetBeans IDE

 After the installation is complete, you can launch NetBeans IDE from the start menu or
desktop shortcut.

That's it! You have successfully installed NetBeans IDE 8.1 on your system.

Uninstalling the Software from Microsoft Windows- to uninstall software from Microsoft
Windows, you can follow these step-by-step instructions [2]

1. Open the Control Panel by typing "Control Panel" in the search box on the taskbar and
selecting it from the results
2. In the Control Panel, select "Programs" or "Programs and Features"
3. Find the program you want to uninstall, either by scrolling through the list or using the
search function

8
4. Press and hold (or right-click) on the program and select "Uninstall" or
"Uninstall/Change"
5. Follow the on-screen prompts to complete the uninstallation process
Steps to create a new project in NetBeans IDE

1. When you first run Net Beans, you'll see a screen something like this [Link] start a new
project, click on File New Project from the Net Beans menu at the top[4]. You'll see the
following dialogue box appear

2. We are going to be creating a Java Application, so select Java under Categories, and then Java
Application under Projects. Click the Next button at the bottom to go to the next step. You'll see
the following dialogue box appear.

9
Type project name

3. The default location to save your projects is shown in the Project Location text box. If you
want, you can change this location. NetBeans will create a folder with your project name in the
chosen location. After you click the Finish button, NetBeans will start creating all the files you
need. When NetBeans brings you back to the IDE, take a look at the Projects area in the top left
of the screen. If you can't see it, click on Window and then Projects on the menu bar at the top of
the software.

4. Click the plus symbol to expand your project, and you'll see the following

10
5. Expand your project name

Now expand Source Packages to see your project name again. Expand this and you'll see the
Java file that is your source code.

Project Name

6. This same source code should be displayed to the right, in the large text area. It will be
called [Link] if you can't see a code window, simply double-
click [Link] in your Projects window above. The code will appear, ready for you to

start work. The coding window that appears should look like this (we've changed the author's
name)

11
One thing to note here is that the class is called Firstjavaproject.

Public class Firstjavaproject {

This is the same name as the java source file in the project window [Link]. When
you run your programs, the compiler demands that the source file and the class name match. So
if your .java file is called firstjavaproject but the class is called Firstjavaproject then you'll get an
error on compile because the first one is lowercase "f" and the second one uppercase F.

Note-the name of the package doesn't have to be the same as the java source file, or the class in
the source files. It’s just the name of the java source file and the name of the class that must
match. See the following Eg. to check the difference

12
Eg. 1.1 the difference between package name class name

Source file

Java source file name and class


name must be the same but not the
Package Name same as

Package name differ by upper and


lower case
Class Name

How to run java source codes in NetBeans IDE

When you run a program in NetBeans, it will run in the Output window at the bottom of your
screen, just underneath your code[4]. This is so that you don't have to start a terminal or console
window[4].

There are various ways to run your program in NetBeans but the easiest way is to press F6 on
your Keyboard.

1. Run the program by clicking the green arrow on the NetBeans toolbar

13
2. Run the program using the menus as the top of NetBeans. Locate the Run menu, and then
select Run Main Program

3. Run your program is from the Projects window. This will ensure that the right source code is
being run. Simply right-click your java source file in the project window and you'll see a menu
appear. Select Run File.

14
1.10 Java comments
When you create a New Project in NetBeans, you'll notice that some text is greyed out, with lots
of slashes and asterisks [3]. The greyed-out areas are comments. When the program runs,
comments are ignored. So you can type whatever you want inside of your comments. But it's
usual to have comments that explain what is you're trying to do. You can have a single line
comment by typing two slashes, followed by your comment.

//This is a single line comment


If you want to have more than one line, you can either do this:
//This is a comment spreading
//over two lines or more
Or you can do this:
/*
This is a comment spreading
over two lines or more
*/

Eg. 1.2 write java program using java comments

15
1.11 Program Sharing
You can send your program to other people so that they can run them. To do that, you need to
create a JAR file (Java Archive). NetBeans can do all this for you.

Aim-used to share your program to other people.

1. From the Run menu at the top select Clean and Build Main

When you do, NetBeans saves your work and then creates all the necessary files. It will create a
folder called dist. and place all the files in there.

2. Have a look in the place where your NetBeans projects are and you'll see the dist folder.

16
3. Double click the dist folder to see what's inside of it

You should see a JAR file and README text file. The text file contains instructions on how to
run the program from a terminal/console window.

1.12 keywords (Reserved words)


Keywords are words with special meaning to the compiler (Eg. Class, new, static, import, this,
etc…). You have to be able to identify all Java programming language keywords and correctly
constructed identifiers.
Table 1-1 keywords (reserved words) in java

abstract Float public


Boolean For return
Break If short
Byte Implements static

17
Case Import super
Catch Instance of switch
Char Int synchronized
Class Interface this
continue Long throw
default Native throws
Do New transient
double Null try
Else Operator void

1.13 Types of programming paradigm


A programming paradigm is a fundamental style of programming. A programming paradigm
provides the view that the programmer has of the execution of the program. A paradigm is an Eg.
or model. A model is an Eg. or sample that helps understand how the world works.

Example- A computer model can be expressed as having a monitor, keyboard, system unit, etc…
Some of the common programming paradigms are discussed below.
1. Unstructured Programming-Usually, people start learning programming by writing
small and simple programs consisting only of one large (usually main program) program.
Here “main program'' stands for a sequence of commands or statements which modify
data that is global throughout the whole program. As you should all know, this
programming technique provides tremendous disadvantages once the program gets
sufficiently large. Program

Main program
Data

Figure 1-1 unstructured Programming

18
2. Procedural programming- is a way of writing code that is based on the idea of using
procedures or routines. These procedures are like sets of instructions that can be called
upon to solve a problem. They can be called at any point in a program, even by other
procedures or themselves. Procedural programming is a good choice when dealing with
moderately complex tasks or when maintainability is important. It allows you to organize
and combine sets of statements in one central place, making it easier to work with. A
procedure call is used to invoke the procedure. Possible benefits
 The ability to be strongly modular or structured
 The ability to re-use the same code at different places in the program without
copying it
 An easier way to keep track of program flow than a collection of "GOTO" or
"JUMP" statements.
 With procedural programming, you are able to combine returning sequences of
statements into one single place. A procedure call is used to invoke the procedure.
After the sequence is processed, the flow of control proceeds right after the
position where the call was made Procedural programming languages facilitate
the programmer's task in following a procedural programming approach.
Program

Main program data

Procedure1 Procedure2 Procedure3

Figure 1-2 Procedural programming

19
3. Structured Programming- Structured programming enforces a logical structure on
programs, making them efficient and easier to understand. Procedures with common
functionality are grouped into separate Manuals, each managing its own data and state.
This approach promotes a top-down design model and efficient memory usage. The use
of "Go-To" statements is discouraged.

Program

Main program data

Manual 1
Data+data1 Manual 2
Data+data2

Procedure 1
Procedure 2 Procedure 3

Figure 1-3 Structured Programming

20
4. Object-oriented Programming (OOP) The idea behind object-oriented programming is
that a computer program is composed of a collection of individual units, or objects.

Program

Object1 Data Object2 Data

Object3 Data

Object4 Data

Figure 1-4 Object-oriented Programming

1.14 Overview of Object-oriented principles


Object orientation represents a fundamentally different way of thinking about problem-solving
[3]. It is a technique of modeling some kind of system based on objects. If you've never used an
object-oriented language before, you need to understand the underlying concepts before you
begin writing code [4]. You need to understand what an object is, what a class is, how objects
and classes are related, and how objects communicate by using messages.
Class- In Java, everything is encapsulated under classes. Class is the core of the Java language.
A class can be defined as a template/ blueprint that describes the behaviors /states of a particular
entity. A class defines a new data type. Once defined this new type can be used to create an
object of that type. A class is declared using the class keyword. A class contains both data and
code that operate on that data. The data or variables defined within a class are called instance
variables and the code that operates on this data is known as methods. Class is the logical entity
only.

21
Object-An entity that has state and behavior is known as an object. An object is an instance of a
class. You may also call it a physical existence of a logical template [Link] is both a logical and
physical entity. An object has three characteristics.
1. State-represents data (value) of an object
2. Identity-Object identity is typically implemented via a unique ID
3. Behavior-represents the behavior (functionality) of an object

1.15 Overview of Java Programming and types of Java Program


It is intended to let application developers "write once, run anywhere" (WORA), meaning
that code that runs on one platform does not need to be recompiled to run on another.

Java technology is both a programming language and a platform. Java is a high-level, robust,
secured, and object-oriented programming language.

Note-java source code has .java extension but java byte code has .class file [Link] source
code runs on java compiler (javc).Java code is compiled into byte code, not machine code so
interpreted by java virtual machine (JVM).

There are four platforms of the Java programming language

1. Java Platform, Standard Edition (Java SE)


2. Java Platform, Enterprise Edition (Java EE)
3. Java Platform, Micro Edition (Java ME)
4. JavaFX

Types of Java programs


1. Java Application - executes on a client computer
2. Java Applet - small program written in Java and that is downloaded from a website and
executed within a web browser on a client computer
Note-JAR file (Java archive) - used to package Java files together into a single file.

22
Summary
Java has become a popular and useful programming language because of its excellent features,
which play a very important role in contributing to the popularity of this language. The Java
features are called “Java BuzzWords”. Object-Oriented Programming refers to programming
that helps us to create the objects that we want and create methods to handle these objects. The
principle of OOP is to create objects, reuse the objects throughout the program, and manipulate
these objects to get desired outputs. The primary objective of object-oriented programming is to
enhance the maintainability and flexibility of applications. Object-oriented programming brings
together data, and its behavior (methods) in a single location(object) makes it easier to
understand how a program works. The objective of OOP concepts in Java is to save time and
gain security and ease of use.

Questions

1. What are packages in Java and what are the advantages of them?
2. Why do you need to import packages?
3. Why do you need to specify access modifiers?
4. How does Java achieve high performance?
5. Can we convert byte code into source code?
6. Explain the process of Java code compilation and execution.
7. What is the difference between the byte code and source code?
8. What is JVM? Is it the same or different for different Operating Systems?
9. What are the major components of JVM?
10. What is the role of the class loader in JVM?
11. What is the role of the Execution Engine in JVM?
12. What is the advantage of the programming paradigm?
13. Is Java a platform-independent language? If yes, Why?

23
Lab two- Basics in Java Programming
Objective- At the end of these lesson students will able to understand

 Basics in Java Programming


 Variable types and identifiers
 Identifier Rules
 Number types, strings, and constants
 Separators
 Expressions

2.1 Basics in Java Programming


Java is a pure Object-oriented language, and hence everything is written within a class block.
Eg. 2.1 Structure of java Program
Aim-to know the basic java program Structure.

Source file

Main- is a entry point of the program.

String [] args-is used for command line argument

Package Name [Link] ()- is used print statement.

Class-is a keyword used to declare a class in java.

Public-is a keyword is an access modifier which represents visibility, it


means it is visible to all.

Class Name void -is a keyword the return type of method, it means it doesn't return any
value.

24
2.2 Variable types
What is a variable?-Java variable is a piece of memory that can contain a data value.
A variable thus has a data type [3]. Variables are typically used to store information which
your Java program needs to do its job [1]. Variables must be declared before used.

Variable declaration syntax

Data_type variable

Eg. float sum;

Variable initialization syntax

Data_type variable=value;

Eg. float sum=0;

Types of variables-there are three types of variables.

1. Local variables-declared inside a method


2. Class variables-declared as static it cannot be local
3. Instance variables-declared inside class but outside method not declared as static

Eg. 2.2 variable scope in java.

1 //variable scope in java


2 package javaprogram;
3 class scopeofvariable{
4 //instance variable not declared as static
5 float radious;
6 //static variable is constant value
7 //static variable means class variable
8 static double pi=3.14;
9 void method(){
10 //local variable area
11 float area;

25
12 }}
13 public class Javaprogram {
14 public static void main(String[] args) {
15 //variable declaration and intaliation
16 int a=20,b=50;
17 //variable declaration
18 int sum;
19 sum=a+b;
20 //that print the value of sum
21 [Link]("the sum is="+sum);
22 }}

Identifiers-are programmer given names used to identify classes, methods, variables, objects,
packages[4]. Java is case sensitive language.
Eg. Mathvar, mathVar, MathVar, etc… are different identifiers.
Identifier Rules
 Must begin with letters or underscore characters (_)
 The remaining characters must be letters digits
 As long as you like until you are tired of typing

2.3 Data type


The data type defines the values that a variable can take [4].
For Eg. if a variable has an int data type, it can only take integer values. In java, we have two
categories of data type.
1. Primitive data types
2. Non-primitive data types
Arrays and Strings are non-primitive data types [4]. In Java, we have eight primitive data types
(Boolean, char, byte, short, int, long, float, double). Java developers included these data types to

26
maintain the portability of java as the size of these primitive data types do not change from one
operating system to another.
 Byte, short, int, and long data types are used for storing whole numbers
 Float and double are used for fractional numbers
 Char is used for storing characters (letters)
 Boolean data type is used for a variable that holds either true or false

Byte- can hold the whole number between -128 and 127. Mostly used to save memory and when
you are certain that the numbers would be in the limit specified by byte data type.
The default size of this data type: 1 byte.
Default value: 0.

Short- is greater than byte in terms of size and less than an integer. Its range is -32,768 to 32767.

The default size of this data type is 2 byte.

Int-Used when short is not large enough to hold the number, it has a wider range: -2,147,483,648
to 2,147,483,647.
Default size: 4 bytes.
Default value: 0.

Long-Used when int is not large enough to hold the value, it has wider range than int data type,
range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Size: 8 bytes.
Default value: 0.
double- Sufficient for holding 15 decimal digits.
size: 8 bytes.

Float-Sufficient for holding 6 to 7 decimal digits


size: 4 bytes.

Boolean-holds either true or false.

Char-holds characters.
size: 2 bytes

27
Eg. 2.3 data types in java.

Problem-write a java program using all data types.

Aim-used to understand basic data types in java and the use of each data type.

1 //code for datatype in java


2 package datatype;
3 public class Datatype {
4 public static void main(String[] args) {
5 //byte can hold whole number between -128 and 127
6 //Initialize num to byte data type
7 byte num=120;
8 //byte num=129; error b/c 129 not included in the range
9 //that print the value of num in byte
10 [Link]("byte="+num);
11 //short Its range is -32,768 to 32767.
12 //Initialize nums to short data type
13 short nums =(short) 45678;
14 //print the value of nums to output screren
15 [Link]("short="+nums);
16 //long ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
17 //Initialize numl to long
18 long numl = -12332252626L;
19 //display the value of numl
20 [Link]("long="+numl);
21 //int range -2,147,483,648 to 2,147,483,647
22 //Initialize numi to integer
23 int numi = 567;
24 //print or display the value of numi
25 [Link]("int="+numi);
26 //double Sufficient for holding 15 decimal digits

28
27 double numd = -42937737.9d;
28 [Link]("double="+numd);
29 //float Sufficient for holding 6 to 7 decimal digits
30 float numf = 1300.98f;
31 [Link]("float="+numf );
32 //boolean holds either true of false.
33 boolean b = false;
34 [Link]("boolean="+b );
35 char ch = 'Z';
36 [Link]("char="+ch );
37 }}

2.4 Number types and strings


Number-in java number has six types that are Byte, integer, double, short, float, and long.

Strings-In java, a string is basically an object that represents a sequence of char values. The Java
platform provides the String class to create and manipulate strings.

A string is a sequence of characters.

Eg. “Hello” is a string of 5 characters. In java, a string is an immutable object which means it is
constant and cannot be changed once it has been created.

29
Creating Strings.
1. The most direct way to create a string is to write
String str1 = "Hello Java!";

2. Using another String object


String str2 = new String(str1);
3. Using new Keyword
String str3 = new String("Java");

4. Using + operator (Concatenation)


String str4 = str1 + str2;
or,
String str5 = "hello"+"Java";

Eg. 2.4 create string in java

Problem-write a java program that create string in different ways.

Aim-to know different ways that used to create string in java.

1 //code for string creation


2 package stringEg.1;
3 public class StringEg.1 {
4 public static void main(String[] args) {
5 //Eg. for creating string in 4 ways
6 //creating a string by java string literal
7 String str = "Java Module";
8 char arrch[]={'h','e','l','l','o'};
9 //converting char array arrch[] to string str2
10 String str2 = new String(arrch);
11 //creating another java string str3 by using new keyword
12 String str3 = new String("Java String Eg.");
13 String str4="Advanced"+" Programming";
14 //Displaying all the three strings in new line for each

30
15 [Link]("Eg. for creating string");
16 [Link]("using string literal="+str);
17 [Link]("Using another String object="+str2);
18 [Link]("using new keyword="+str3);
19 [Link]("Using + operator (Concatenation)="+str4);
20 }}

String Length.
length() method returns the number of characters contained in the string object.
String str1 = "Hello Java";
int len = [Link]();
[Link]( "String Length is : " + len );

Concatenating Strings.
The String class includes a method for concatenating two strings:
[Link](string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the
concat() method with string literals, as in
"Hello ".concat("Java");
Strings are more commonly concatenated with the + operator, as in
"Hello " + " Java" + "!"
which results in
"Hello Java!"

31
String Methods.

1. int length()-returns string length


2. boolean isEmpty()-checks if string is empty
3. String concat(String str)-concatenates specified string
4. char charAt(int index)-returns char value for the particular index
5. String substring(int begin Index)-returns substring for given begin index
6. boolean equals(Object another)-checks the equality of string with object
7. String replace(char old, char new)-replaces all occurrences of specified char value
8. String trim()-returns trimmed string omitting to lead and trailing space
9. int indexOf(int ch)-returns specified char value index
10. int indexOf(String substring)-returns specified substring index
11. String toLowerCase ()-returns string in lowercase
12. String toUpperCase ()-returns string in uppercase
13. String substring(int begin Index, int end Index)-returns substring for given begin index
and end index
14. String replace(Char Sequence old, Char Sequence new)-replaces all occurrences of
specified Char Sequence

Eg. 2.5 use string methods in java

Problem-write a java program java string methods.

Aim-to understand the use of java string methods.

1 package stringExample;
2 public class StringExample {
3 public static void main(String[] args) {
4 //creating string str
5 String str = "Hello World";
6 //toLowerCase() string method convert str to lowercase
7 String strLower = [Link]();
8 //toUpperCase() string method convert str to uppercase

32
9 String strUpper = [Link]();
10 //return the length of string str
11 int length=[Link]();
12 //print or display string str i.e Hello World
13 [Link]("Original String: " + str);
14 //display the length of string str i.e 11
15 [Link]("Original String length: " + length);
16 //case sensetive string compare strLower with strUpper i.e >0
17 [Link]("string compare="+([Link](strUpper)));
18 //case insensetive string compare strLower with strUpper i.e 0
19 [Link]("string compare ignore case="+
([Link](strUpper)));
20 //display string that changed into lowercase i.e hello world
21 [Link]("String changed to lower case: " + strLower);
22 //display string that changed into uppercase i.e HELLO WORLD
23 [Link]("String changed to upper case: " + strUpper);
24 //string concatination concatinate java with str i.e java Hello World
25 [Link]("String concat:"+("java "+str));
26 }}

Literals-are the data items that have fixed or constant values. Therefore we also call literals
constants in Java. Literals can represent various types of values such as numeric, character,
boolean, or String values. We can assign literals to any of the 8 primitive data types in Java.

33
Types of Java Literals

Java allows six kinds of literals which are

1. Integer literals
2. Floating literals
3. Boolean literals
4. Character literals
5. String literals
6. Null literals

Separators-Are symbols are used to indicate where groups of codes are divided and arranged.
They basically define the shape and function of our code. Some of them are.

Table 2-2 java separators

Name Symbol
Parenthesis ()
braces {}
brackets []
semicolon ;
comma , ,
period .

White space- is space, tab, and newline.


Expressions-is a series of variables, operators, and method calls (constructed according to the
syntax of the language) that evaluates to a single value [2]. Expressions perform the work of a
program. Among other things, expressions are used to compute and to assign values to variables
and to help control the execution flow of a program.

34
Summary

Java is a pure Object-oriented language, and hence everything is written within a class block.
Java variable is a piece of memory that can contain a data value. A variable thus has a data type.
Variables are typically used to store information which your Java program needs to do its job.
Variables must be declared before used. Identifiers are programmer given names used to identify
classes, methods, variables, objects, packages. The data type defines the values that a variable
can take. Arrays and Strings are non-primitive data types. In Java, we have eight primitive data
types (Boolean, char, byte, short, int, long, float, double). Java developers included these data
types to maintain the portability of java as the size of these primitive data types do not change
from one operating system to another.

35
Questions

1. A string class is immutable or mutable?


2. Explain public static void main (String args[])
3. List Different Data types in Java?
4. What are Literals?
5. What is an expression?
6. What is a static variable in Java?
7. Does Java support global variables?
8. Write a program to check if the given string is a palindrome.
9. What if I write static public void instead of a public static void?
10. What kind of variables a class can consist of?
11. Can we execute a program without the main () method?
12. What if the static modifier is removed from the signature of the main method?
13. When a byte data type is used?
14. Why java does not support pointers?
15. What is an immutable object?
16. What is javac?
17. What is the base class of all classes?
18. What are the advantages and disadvantages of String immutability?
19. What memory optimization is performed by the Java environment for Strings?
20. What are the differences between String Literal and String Object?
21. Write a Java Program to find duplicate characters in a String?
22. Write a Java Program to sort strings in alphabetical order?
23. Write a Java program to find the occurrence of a character in a String?
24. Write a Java program to count vowels and consonants in a String?
25. Write a Java Program to convert char to String and String to Char?
26. Write a Java Program to Find HCF and LCM of Two Numbers?
27. Write a Java Program to generate Random Numbers?
28. Write a Java Program to find the square root of a number without the sqrt method?
29. Write a Java Program to find the largest of three numbers?
30. Write a Java Program to find an average of 3 numbers?

36
Lab Three- Operators
Objective- At the end of these lessons students will able to understand.

 Java operators
 Types of operators
 Operator precedence
 Type conversion (casting)

3.1 Operators
Operators-Java provides a rich set of operators to manipulate variables [4]. An operator is a
character that represents an action, for Eg, + is an arithmetic operator that represents addition.
We can divide all the Java operators into the following groups [1].

1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators

Arithmetic Operators-are used in mathematical expressions in the same way that they are used
in algebra.
Table 3-3 Arithmetic operators in java

Operator Use Description

+ op1 + op2 Adds op1 and op2

- op1 - op2 Subtracts op2 from op1

* op1 * op2 Multiplies op1 by op2

/ op1 / op2 Divides op1 by op2

% op1 % Computes the remainder of dividing op1 by op2


op2

37
Eg. 3.1 Arithmetic operator in java

Problem-write a java program using the concept of Artimetic operators with the given number
num1=50 and num2=250.

Aim-to understand how to use Artimetic operators in java program.

1 //code for Artimethic operator


2 package artimoperetor;
3 public class Artimoperetor {
4 public static void main(String[] args) {
5 //Initialize num1 and num2
6 int num1 = 50, num2 = 250;
7 //addation operator add num1 and num2 i.e 300
8 [Link]("num1 + num2: " + (num1 + num2) );
9 //substracton operator substract num2 from num1 i.e -200
10 [Link]("num1 - num2: " + (num1 - num2) );
11 //multiplication operator multiplay num1 with num2 i.e 12500
12 [Link]("num1 * num2: " + (num1 * num2) );
13 //division operator divide num1 by num2 i.e 0
14 [Link]("num1 / num2: " + (num1 / num2) );
15 //moduls operator Computes the remainder of dividing num1 by num2 i.e 50
16 [Link]("num1 % num2: " + (num1 % num2) );
17 }}

38
Relational Operators-There are the following relational operators supported by the Java
language.

Table 3-4 Relational operators in java

Operato Use Returns true if


r

> op1 > op2 op1 is greater than op2

>= op1 >= op2 op1 is greater than or equal to op2

< op1 < op2 op1 is less than op2

<= op1 <= op2 op1 is less than or equal to op2

== op1 == op2 op1 and op2 are equal

!= op1 != op2 op1 and op2 are not equal

Eg. 3.2 Relational operator in java.

Problem-write a java program using Relational operators concepts with the given number
num1=30 and num2=60.

Aim-to understand Relational operators and the use of Relational operators in the program.

1 //code for Relational operators


2 package relationaloperators;
3 public class Relationaloperators {
4 public static void main(String[] args) {
5 //Initialize num1 and num2
6 int num1 = 30,num2 = 60;
7 //num1 and num2 are equal
8 if (num1==num2) {
9 [Link]("num1 and num2 are equal");}

39
10 else{[Link]("num1 and num2 are not equal");}
11 //num1 and num2 are not equal
12 if( num1 != num2 ){
13 [Link]("num1 and num2 are not equal");}
14 else{[Link]("num1 and num2 are equal");}
15 //num1 is greater than num2
16 if( num1 > num2 ){[Link]("num1 is greater than num2");}
17 else{[Link]("num1 is not greater than num2");}
18 //num1 is greater than or equal to num2
19 if( num1 >= num2 ){[Link]("num1 is greater than or equal to num2");}
20 else{[Link]("num1 is less than num2");}
21 //num1 is less than num2
22 if( num1 < num2 ){[Link]("num1 is less than num2");}
23 else{[Link]("num1 is not less than num2");}
24 //num1 is less than or equal to num2
25 if( num1 <= num2){[Link]("num1 is less than or equal to num2");}
26 else{[Link]("num1 is greater than num2");
27 }}}

Bitwise Operators-Java defines several bitwise operators, which can be applied to the integer
types, long, int, short, char, and byte.
Bitwise operator works on bits and performs a bit-by-bit operation.

40
Table 3-5 Bitwise operator in java

Operator Use Operation

& op1 & op2 bitwise and

| op1 | op2 bitwise or

^ op1 ^ op2 bitwise xor

~ ~op2 bitwise complement

Eg. 3.3 Bitwise operator in java.

Problem-write a java program using Bitwise operator within the given number
num1=11(00001011) and num2=22(00010110).

Aim-to understand Bitwise operator and how to use it in java program.

1 //code for bitwise operators


2 package bitwiseoperators;
3 public class BitwiseOperators {
4 public static void main(String[] args) {
5 //Bitwise operator works on bits and performs a bit-by-bit operation.
6 //convert 11 into byte
7 int num1 = 11; /* 11 = 00001011 */
8 //convert 22 into byte
9 int num2 = 22; /* 22 = 00010110 */
10 int result = 0;
11 //bitwise and i.e 2
12 result = num1 & num2;
13 [Link]("num1 & num2: "+result);
14 // bitwise or i.e 31

41
15 result = num1 | num2;
16 [Link]("num1 | num2: "+result);
17 //bitwise xor i.e 29
18 result = num1 ^ num2;
19 [Link]("num1 ^ num2: "+result);
20 //bitwise complement i.e -12
21 result = ~num1;
22 [Link]("~num1: "+result);
23 }}

Logical Operators-The following table lists the logical operators

Table 3-6 Logical operators in java

Operator Use Returns true if

&& op1 && op1 and op2 are both


op2 true

|| op1 || op2 either op1 or op2 is true

42
Eg. 3.4 Logical operator in java

Problem-write a simple java program using the concept of Logical operator with the given
variable boolean b1 = false, b2 = true.

Aim-to know how to use Logical operator in java.

1 //code for logical operators


2 package logicaloperators;
3 public class LogicalOperators {
4 public static void main(String[] args) {
5 //Initialize boolean variable b1 and b2
6 boolean b1 = false, b2 = true;
7 //logical and b1 and b2 are both true i,e false
8 [Link]("b1 && b2: " + (b1&&b2));
9 //logical or either b1 or b2 is true i.e true
10 [Link]("b1 || b2: " + (b1||b2));
11 //logical complment or negation i.e true
12 [Link]("!(b1 && b2): " + !(b1&&b2));
13 }}

43
Assignment Operators-the following are assignment operators supported by Java language

Table 3-7 Assignment operator in java

Operator Use Equivalent to

+= op1 += op2 op1 = op1 + op2

-= op1 -= op2 op1 = op1 - op2

*= op1 *= op2 op1 = op1 * op2

/= op1 /= op2 op1 = op1 / op2

%= op1 %= op2 op1 = op1 % op2

&= op1 &= op2 op1 = op1 & op2

|= op1 |= op2 op1 = op1 | op2

^= op1 ^= op2 op1 = op1 ^ op2

Eg. 3.5 Assignment operator in java.

Problem-write a java program by using the concept of Assignment operator with the given
number num1=100 and num2=300.

Aim-to understand how Assignment operators used in the program.

1 //code for assignment operators


2 package assignmentoperators;
3 public class AssignmentOperators {
4 public static void main(String[] args) {
5 //Initialize num1 and num2 t int
6 int num1 = 100,num2 = 300;
7 //assign num1 for num2 i.e num2=100

44
8 num2 = num1;
9 [Link]("= Output: "+num2);
10 //assign num2+num1 for num2 i.e num2=100+100=200
11 num2 += num1;
12 [Link]("+= Output: "+num2);
13 //assign num2-num1 for num2 i.e num2=200-100=100
14 num2 -= num1;
15 [Link]("-= Output: "+num2);
16 //assign num2*num1 for num2 i.e num2=100*100=10000
17 num2 *= num1;
18 [Link]("*= Output: "+num2);
19 //assign num2/num1 for num2 i.e num2=100
20 num2 /= num1;
21 [Link]("/= Output: "+num2);
22 //assign num2%num1 for num2 i.e num2=100%100=0
23 num2 %= num1;
24 [Link]("%= Output: "+num2);
25 }}

45
Increment and Decrement Operators-operators are used to add or subtract 1 from the current
value of the operand.

Table 3-8 Increment and decrement operator in java

Operato Use Description


r

++ op++ Increments op by 1; evaluates to the value of op before it was incremented

++ ++op Increments op by 1; evaluates to the value of op after it was incremented

-- op-- Decrements op by 1; evaluates to the value of op before it was decremented

-- --op Decrements op by 1; evaluates to the value of op after it was decremented

Increment and Decrement operators can be prefix or postfix.


In the prefix style, the value of the operand is changed before the result of the expression and in
the postfix style, the variable is modified after the result.

Eg. 3.6 increment and decrement operator in java

Problem-write a simple java program using increment and decrement operator.

Aim-to know how to use increment and decrement operator in java.

1 //code for increment and decrement operator


2 package [Link];
3 public class IncrementanddecrementOperators {
4 public static void main(String[] args) {
5 //Initialize num1,num2,num3 and num4
6 int num1=400,num3=500;
7 int num2=700,num4=200;
8 num1++;//post increment i.e num1=401
9 num2--;//post decrement i.e num2=699
10 ++num3;//pri increment i.e num3=501
11 --num4;//pri decrement i.e num4=100

46
12 [Link]("num1++ is: "+num1);
13 [Link]("num2-- is: "+num2);
14 [Link]("++num3 is: "+num3);
15 [Link]("--num4 is: "+num4);
16 }}

There are few other operators supported by Java Language.


Conditional Operator ( ? : )-is also known as the ternary operator.

The operator is written a


variable x = (expression)? Value if true: value if false

Eg. 3.7 Ternary operator in java.

Problem-Write a simple java program using Ternary operator.

Aim-to understand the use of Ternary operator.

1 //code for ternary operator


2 package ternaryoperator;
3 public class TernaryOperator {
4 public static void main(String[] args) {
5 //variable declaration
6 int num1, num2;
7 // variable Initialization
8 num1 = 25;
9 /* num1 is not equal to 10 that's why

47
10 * the second value after colon is assigned
11 * to the variable num2 i.e num2=200
12 */
13 num2 = (num1 == 10) ? 100: 200;
14 [Link]( "num2: "+num2);
15
16 /* num1 is equal to 25 that's why
17 * the first value is assigned
18 * to the variable num2 i.e num2=100
19 */
20 num2 = (num1 == 25) ? 100: 200;
21 [Link]( "num2: "+num2);
22 }}

Eg. 3.8 Operators in java.

Problem-write a simple java program using all type of operators.

Aim-to understand the use of all types of operators in java program.

1 //operators Example.
2 package operatorexample;
3 public class Operatorexample. {
4 public static void main(String[] args) {
5 //Initialize float variable a,b,c and d
6 float a=20,b=50,c=10,d=80;
7 //incrment and decrment operator
8 float e=a++,f=++b,g=--c,h=d--;
9 //addation operator i.e sum=160.0

48
10 float sum=a+b+c+d;
11 //addation and substraction in the form of expression i.e sub=40.0
12 float sub=(a+d)-(b+c);
13 //division operator i.e div=3.7619047
14 float div=d/a;
15 //miultiplication operator i.e mul=1071.0
16 float mul=a*b;
17 //modules operator use int data type i.e mod1=9 mod2=21
18 int mod1=(int) (b%a),mod2=(int) (a%b);
19 [Link]("Addation="+sum);
20 [Link]("Substraction="+sub);
21 [Link]("Division="+div);
22 [Link]("Multiplication="+mul);
23 [Link]("Modules="+mod1);
24 [Link]("Modules="+mod2);
25 //post increment i.e e=20.0 b/c datatype is float
26 [Link]("the value of e(post increment)="+e);
27 //pri incriment i.e f=51.0
28 [Link]("the value of f(pri increment)="+f);
29 //pri decriment i.e g=9.0 b/c float
30 [Link]("the value of g(pri decrement)="+g);
31 //post decriment i.e h=80.0 b/c float
32 [Link]("the value of h(post decrement)="+h);
}}

49
3.2 Operator precedence
Certain operators have higher priorities than others. Operator precedence determines the
grouping of terms in an expression. This affects how an expression is evaluated. Eg. the dot
operator has higher precedence than any other operator.

Precedence 1
() Parentheses
Precedence 2
++ Unary post-increment
-- Unary post-decrement
Precedence 3
+ Unary plus
- Unary minus
++ Unary pre-increment
-- Unary pre-decrement
! Unary logical negation
~ Unary bitwise complement
(type) Unary typecast
Precedence 4
* Multiplication
/ Division
% Modulus

50
Precedence 5
+ Addition
- Subtraction
Precedence 6
<< Bitwise left shift
>> Bitwise right shift with sign extension
>>> Bitwise right shift with zero extension
Precedence 7
< Relational less than
> Relational greater than
<= Relational less than or equal
>= Relational greater than or equal
Precedence 8
== Relational is equal to
!= Relational is not equal to
Precedence 9
& Bitwise AND
Precedence 10
^ Bitwise exclusive OR
Precedence 11
| Bitwise inclusive OR
Precedence 12
&& Logical AND
Precedence 13
|| Logical OR
Precedence 14
?: Ternary conditional
Precedence 15
= Assignment
+= Addition assignment
-= Subtraction assignment

51
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

3.3 Type Casting


Casting is an operation that converts a value of one data type into a value of another data type.
The syntax for typecasting is to give the target type in parenthesis followed by the variable name

Eg. float f = (float) 10.1;


Int i = (int)f;
in this case, the value of i is 10, the fractional part is discarded while using type casting there is a
chance of lost information that might lead to an inaccurate result.

Casts that results in no loss of information


byte => short, char, int, long, float, double
short => int, long, float, double
char => int, long, float, double
int => long, float, double

long => float, double


float => double

Eg. 3.9 Typecasting in java.

Problem-write a simple java program that performs typecasting.

Aim-how to perform typecasting and its disadvantage when we use it.

1 package typecasting;
2 public class Typecasting {
3 public static void main(String[] args) {
4 //declar and Initialize length and width
5 float length=60,width=10;
6 //Type Casting to int i.e area=60*10=600 b/c int datatype
7 int area=(int) (length*width);

52
8 [Link]("Area="+area);
9 //type casting to float
10 float length2=(float) 20.5;
11 //type casting to float
12 float width2=(float) 7.5;
13 //type casting to int i.e area2=153
14 int area2=(int) (length2*width2);
15 //type casting causes loss of information
16 [Link]("Area2="+area2);
17 //type casting to float
18 float length3=(float) 20.5;
19 //type casting to float
20 float width3=(float) 7.5;
21 //type casting to float i.e area3=153.75
22 float area3=(float) (length3*width3);
23 //type casting no loss of information
24 [Link]("Area3="+area3);
25 }}

Summary

An operator is a character that represents an action. We can divide all the Java operators into
Arithmetic Operators, Relational Operators, Bitwise Operators, Logical Operators and
Assignment [Link] operators have higher priorities than others. Operator precedence
determines the grouping of terms in an expression. This affects how an expression is evaluated.
typcasting is an operation that converts a value of one data type into a value of another data type.
The syntax for typecasting is to give the target type in parenthesis followed by the variable name.

53
Questions

1. What are the operators?


2. List the type of operator?
3. What is the advantage of the operator?
4. What is the advantage and disadvantage of typecasting?

Lab Four- Java statements


Objective- At the end of these lessons students will able to understand.

 Java statements
 Decision statement
 Repetition Statements
 If, if-else, and switch statements
 Array and pros and cons of array

4.1 Overview of Java statements


Java statements are instructions that tell the programming language what to do, like declaration
and string statements. Basic statements define variables and initiate Java methods or start the
execution of blocks of other statements. Assignment statements assign values to variables.
Statements are roughly equivalent to sentences in natural languages. A statement forms a
complete unit of execution.

In computer programming, a statement is a syntactic unit of an imperative programming


language that expresses some action to be carried out. A program written in such a language is
formed by a sequence of one or more statements.

There are four types of statements in java.

1. Decision-making statements-if else, nested if


2. Selection statements-switch case
54
3. Iteration statements-for loop, while loop, do-while loop
4. Jump statements-break and continue and return

4.2 Decision and Repetition Statements


Decision statement-provides a concise, well-ordered explanation of a decision made by an
individual or a team of individuals. It should include a basic premise of the problem addressed,
as well as the solution to that issue.

Eg. if statement.

Repetition Statements- also called a looping statement, an iteration statement or a loop allows
you to specify that an action should be repeated, depending on the value of a loop-continuation
condition or a loop-termination condition.

Eg. for loop, while and do-while loop statement.

4.3 If, if-else and Switch


IF Statements-executing code when one thing happens rather than something else is so common
in programming that the If Statement has been developed. The structure of the IF Statement in
Java is this.
if (Statement ) {
Display message
}

55
Eg. 4.1 if statement.

Problem-write a java program that checks a number is even using if statement.

Aim-to understand how to use if statement in java.

1 //if statment Eg.


2 package ifstatment;
3 public class Ifstatment {
4 public static void main(String[] args) {
5 //declar and Initialize variable number
6 int number=50;
7 //check 50%2 equal to zero
8 if(number%2==0){
9 [Link]("The number "+number+" is even");
10 }}}

If-else statement-Instead of using two If statements, you can use an If-else Statement instead.
Here's the structure of an IF … ELSE statement.

if ( condition_to_test ) {
}
else {
}

56
Eg. 4.2 if-else Statement.

Problem-write a java program that checks a number 53 is even or odd using if-else Statement.

Aim-to know the use of if-else Statement in a java program.

1 package ifelsestatment;
2 public class Ifelsestatment {
3 public static void main(String[] args) {
4 //declar and Initialize variable number
5 int number=53;
6 //check 53%2 equals to zero
7 if(number%2==0){
8 //if it is true display the next message
9 [Link]("The number "+number+" is even");}
10 else{
11 //display the next message if it is flase
12 //so it is flase display the next message
13 [Link]("The number "+number+" is odd");
14 }}}

Switch statement-Another way to control the flow of your program is with something called a
switch statement. A switch statement gives you the option to test for a range of values for your
variables. They can be used instead of long, complex if … else if statements. The structure of the
switch statement is this.

switch ( variable_to_test ) {
case value:
code_here;
break;

57
case value:
code_here;
break;
default:
values_not_caught_above;
}

Eg. 4.3 Switch statement.

Problem-write a simple java program using Switch statement.

Aim-to understand how to use Switch statement.

1 package switchexapmle.;
2 public class Switchexample. {
3 public static void main(String[] args) {
4 //declar and Initialize variable choice
5 int choice=3;
6 //choice is a variable to test
7 switch(choice){
8 case 1:
9 [Link]("your choice is first");
10 break;
11 case 2:
12 [Link]("your choice is second");
13 break;
14 case 3:
15 [Link]("your choice is third ");
16 break;
17 case 4:
18 [Link]("your choice is forth ");
19 break;
20 default:

58
21 //values_not_caught_above;
22 [Link]("your choice is invalid");
23 }}}

4.4 Array in Java


An array is a collection of similar types of elements that have contiguous memory locations. An
array is a container object that holds values of the homogenous type. It is also known as a static

data structure because the size of an array must be specified at the time of its declaration. An
array can be either primitive or reference type. It gets memory in the heap area. index of an array
starts from zero.

Advantage of Java Array

 Random access-We can get any data located at any index position
 Code Optimization-It makes the code optimized, we can retrieve or sort the data easily

The disadvantage of Java Array

 Size Limit-We can store the only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, a collection framework is used in java.

Types of Array

1. Single Dimensional Array


2. Multidimensional Array

Single Dimensional Array


Syntax
Data_type [ ] identifier; or Data_type identifier [ ];
Both are valid syntax for array declaration. But the former is more readable.
Eg. int[] arr;

59
short[] arr;
long[] arr; //one dimensional array

Initialization of Array
A new operator is used to initialize an array.
Eg. int[] arr = new int[10]; //declaration and instantiation
or
int[] arr = {10,20,30,40,50}; //declaration, instantiation and initialization
Accessing an array element
As mention earlier array index starts from 0. to access the nth element of an array.
Syntax:
array_name [ n-1 ];
Eg. To access the 4th element of a given array
int[] arr={10,20,30,40};
[Link]("Element at 4th place"+arr[3]);
The above code will print the 4th element of array arr on the console.

Using foreach or enhanced for loop to access elements of an array

JDK introduces a special type of for loop called foreach loop to access elements of an array.
Using foreach loop you can access the complete array sequentially without using the index of the
array. Let us see an Eg. of foreach loop.

60
Eg. 4.4 Single array using foreach.

Problem-write a java program that display a given number in single dimentional array using the
concept of foreach.

Aim-to understand how to use foreach in single dimentional array.

1 package singlearray;
2 public class Singlearray {
3 public static void main(String[] args) {
4 int[] arr={120,30,60};
5 //Using foreach or enhanced for loop to access array
6 //arr is array name
7 for(int x:arr)
8{
9 //x contain the contents of array arr
10 [Link](x);
11 }}}

Multidimensional Array

Syntax
Data_type[ ][ ] identifier; or Data_type identifier[ ][ ];
or
Data_type [ ]identifier[ ];

Instantiation of Array
int[ ][ ] arr=new int[3][3]; //3 row and 3 column
Let's see the simple Eg. to declare, initialize, and print the 2Dimensional array.

61
Eg. 4.5 Two dimensional array.

Problem-write java program that display a given number in 2D array.

Aim-in order to understand 2D array and how to use it.

1 package twodimenarray;
2 public class Twodimenarray {
3 public static void main(String[] args) {
4 //declaring and initializing 2D array
5 int arr[][]={{9,2,3},{4,1,5},{6,7,5}};
6
7 //printing 2D array
8 for(int i=0;i<3;i++){//row
9 for(int j=0;j<3;j++){//column
10 //display arr[i][j]
11 [Link](arr[i][j]+" ");
12 }
13 //used to print in new line
14 [Link]();
15 }}}

62
Summary

Java statements are instructions that tell the programming language what to do.
Basic statements define variables and initiate Java methods or start the execution of blocks of
other statements. Assignment statements assign values to variables. Statements are roughly
equivalent to sentences in natural languages. There are four types of statements in java that is
Decision-making statements, Selection statements, Iteration statements and Jump statements. An
array is a collection of similar types of elements that have contiguous memory locations. An
array is a container object that holds values of the homogenous type. It is also known as a static

data structure because the size of an array must be specified at the time of its declaration. An
array can be either primitive or reference type. It gets memory in the heap area. index of an array
starts from zero.

Questions

1. What are statements in java?


2. What is the difference between a decision and a repetition statement?
3. Write a program using if, if-else, and switch statements?
4. What are the pros and cons of an array?
5. Write a Java Program to Calculate the average of numbers using Array?
6. Write a Java Program to add the elements of an Array?
7. Write a Java Program to reverse an array?
8. Write a Java Program to sort an array in ascending order?
9. Write a Java Program to convert char array to String?
10. Write a Java Program to Add Two Matrix Using Multi-dimensional Arrays?

63
Lab Five- Loops
Objective-At the end of these lesson students will able to understand

 For loop
 While loop
 Do while loop
 Break and continue statements
 The difference between while and do-while loop
 The difference between break and continue statement

5.1 For loop


We'll start with For Loops, one of the most common types of loops. But you can think of it like
this: "Loop FOR a set number of times." The structure of the For Loop is this

for ( start_value; end_value; increment_number ) {


//your code here
}

Eg. 5.1 for loop.

Problem-write a java program that displays the sum of 1-4 using for loop.

Aim-to know how to use for loop in java program.

1 package forloop;
2 public class Forloop {
3 public static void main(String[] args) {
4 //declar and Initialize variable sum for future use
5 int sum=0;
6 //for loop start value; end value; increment number
7 for(int i=1;i<5;i++){
8 //display the value of i
9 [Link]("loop "+i);
10 //assign sum+i for sum

64
11 sum=sum+i;
12 }//end of for loop
13 //out of for loop
14 [Link]("The sum of all loop= "+sum);
15 }}

5.2 While loop


While loop is another type of loop you can use in Java. While loops are a lot easier to understand
than for loops. Here's what they look like.

while ( condition ) {

Statements
}

So you start with the word "while" in lowercase. The condition you want to test for goes between
round brackets. A pair of curly brackets comes next, and the code you want to execute goes
between the curly brackets.

65
Eg. 5.2 while loop.

Problem-write a java program that display the entered number from the user.

Aim-to understand how to use while loop in java.

1 //while loop
2 package whileloop;
3 import [Link];
4 public class Whileloop {
5 public static void main(String[] args) {
6 //declar variable n
7 int n;
8 //used to accept from the keyboard
9 Scanner input = new Scanner([Link]);
10 //accept from keyboard
11 [Link]("Input an integer");
12 //input any number if 0 it stoped
13 while ((n = [Link]()) != 0) {
14 [Link]("You entered " + n);
15 [Link]("Input an integer ");}
16 [Link]("Out of loop");
17 }}

66
5.3 Do-while loop
Do while loop Related to the while loop except that do-while loop executes at least once.

It looks like this:


int loopVal = 0;
do {
[Link]("Printing Some Text");

loopVal++;
}
while ( loopVal < 5 );

Eg. 5.3 do-while loop.

Problem-write a java program that display the sum of 1-4 using do-while loop.

Aim-to understand how to write a java program using do-while loop.

1 package dowhileloop;
2 public class Dowhileloop {
3 public static void main(String[] args) {
4 /*Do while Related to the while loop except that
5 do-while loop executes at least once.*/
6 //declar and Initialize variable i and sum
7 int i=1,sum=0;
8 do{
9 [Link]("loop "+i);
10 sum=sum+i;//assign sum+i for sum
11 i++;//incriment
12 }while(i<5);//test the condition
13 //display the sum of 1-4 i.e sum=1+2+3+4=10
14 [Link]("The sum of all loops="+sum);
15 }}

67
5.4 Java Break Statement
We can use a break statement in the following cases.

 Inside the switch, case to come out of the switch block


 Within the loops to break the loop execution based on some condition
 Inside labeled blocks to break that block execution based on some condition

Note-break outside switch or loop invalid

5.5 Java Continue Statement


Java continue statement used only within looping statements.

 When the continue statement is encountered, then it skips the current iteration and the
next iteration starts
 The remaining statements in the loop are skipped. The execution starts from the top of the
loop again
 We can use the continue statement to skip the current iteration and continue the next
iteration inside loops

Java Return Jumping Statement- the return statement is commonly used in methods to end a
method and go back to the method that called it. It is an optional statement, which means that
even if a method doesn't have a return statement, control will still go back to the caller method
after the method finishes executing. A return statement can also pass parameters back to the
caller method, but it doesn't have to.

68
Eg. 5.4 Jump Statement.

Problem-write a java program breake and continue statement.

Aim-to differenciate the use of breake and continue statement.

1 //jump statment
2 package jumpstatment;
3 public class Jumpstatment {
4 public static void main(String[] args) {
5 for(int j=1; j<5; j++){
6 if(j==3){
7 /*break statment stop next excution displat 1 and 2
8 at 3 break the loop so next itration not displyed */
9 break;
10 }
11 [Link](j);}
12 [Link]("outside of for loop");
13 for(int j=1; j<5; j++){
14 if(j==3){
15 /*skip the current iteration and the next iteration starts.
16 so 1,2 and 4 displayed */
17 continue;
18 }
19 [Link](j);}
20 [Link]("outside of for loop");
21 }}

69
Summary

For Loops are one of the most common types of loops[2]. But you can think of it like this: "Loop
for a set number of times." While loop is another type of loop you can use in Java. While loops
are a lot easier to understand than for loops[11]. Do while loop Related to the while loop except
that do-while loop executes at least once. We can use a break statement in the Inside the switch,
Within the loops and Inside labeled blocks but break outside switch or loop invalid. Java
continue statement used only within looping statements.

Questions

1. What is the use of loop statements?


2. What is the difference between while and do-while loop?
3. What is the difference between break and continue statement?
4. Write a program that displays the sum of numbers between 50 and 100 using for loop?
5. Write a program that displays a number between 1 and 17 except multiple of 5?
6. Write a program that displays a number between 1 and 20 until you reach a multiple of 9?
7. Write a program using the concept of for, while, do-while, break and continue statement?
8. Write a program that displays the sum of numbers between 50 and 100 using a while
loop?

70
Lab Six-objects and classes
Objective-At the end of these lessons students will able to understand.

 Objects
 Instantiating objects
 Using objects
 Classes
 The difference between objects and classes

6.1 Object
An object is real-world entity that has state and behavior is known as an [Link] is an instance
of class Eg. chair, marker, pen, etc… It can be physical or logical (tangible and intangible). The
Eg. of an intangible object is the banking system. An object has three characteristics.

1. State- represents data (value) of an object


2. Behavior-represents the behavior (functionality) of an object such as deposit, withdraw,
etc…
3. Identity-Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used internally by the JVM to identify each
object uniquely.

6.2 Classes
The core element of Object orientation in Java is the class. A class is often defined as the
blueprint or template for an object [4]. We can create multiple objects from a class. It is a logical
entity that does not occupy any space/memory. Memory is allocated when we create the objects
of a class type. A class contains properties and methods to define the state and behavior of its
object [4]. It defines the data and the methods that act upon that data. A class in Java can contain
fields, methods, constructors, blocks, nested class, and interface.

For programming in Java, a class is as important as breathing is to us to stay alive. It is the most
basic unit of Object-oriented programming in Java. We cannot create a single variable or
function outside a class. Everything in Java needs to exist inside the class.

Have you ever thought why a class is the blueprint of an object? The reason is

71
A class allows the programmer to define all the properties and methods that internally define the
state and behavior of an object, and all the APIs that externally define an object, and also the
complete syntax for handling encapsulation, abstraction, polymorphism, and inheritance.
Therefore, we can say that a class is the blueprint of an object.

Some Important points about a class


 In Java, we cannot declare a top-level class as private. Java allows only public and
defaults access specifiers for top-level classes. We can declare inner classes as private
 We can include any type of the three variables in Java – local, instance, and static
variables
 There can be only one public class in a single program and its name should be the same
as the name of the Java file. There can be more than one non-public class in a single Java
file
 A public class is visible to all classes from all the packages
 A class with default access is visible only to the classes within the same package
 We can also use the non-access modifiers for the class such as final and abstract
 We cannot create an object or instance of an abstract class
 No subclasses or child class can be created from a class that is declared as final
 A class cannot be declared both as final and abstract at the same time
A class can be visualized as a three-compartment box

1. Name (identity)- identifies the class


2. Variables (attribute, state, field)-contains the static attributes of the class
3. Methods (behavior, function, operation)-contains the dynamic behaviors of the class

Name

Variable

Method

72
Inner Class-is a class within another class.

Outer Class-is an enclosing class that contains the inner class.

Note-Compiler generates a separate class file for each inner class.

Declaration of Java Classes-contain five components

In order to bring class into existence, we should declare it. We can declare a class with the use of
a class keyword. The components of the Java Class declaration are

1. Access Modifiers-We can access Java classes using any access modifiers such as public,
private, protected, and default.
2. Class Name-In Java, the class name generally represents nouns which should begin with a
capital letter without any spaces.
3. Superclass (if any)-The name of the parent class is a superclass and its child class is a
subclass, and the child class inherits the properties of a parent using the extends keyword. A
subclass can only inherit a single parent.
4. Interfaces (if any)-To declare an interface, we just write the keyword interface followed by
the interface name.
5. Class Body-The class body follows the class declaration and embeds within curly braces {}.

6.3 instantiating and using objects


Accessing Objects- Newly created objects are allocated in the memory.

How can they be accessed?

Accessing an object using Reference Variables-Objects is accessed via object reference


variables, which contain references to the objects. Such variables are declared using the
following syntax: Class_Name object_RefVar; A class defines a type, known as a reference type.
Any variable of the class type can refer an instance of the class. The following statement declares
the variable student1 to be of the student type.

student student1;

Class_Name object_RefVar = new Class_Name ();

73
Eg. student student1 = new student (); the variable student1 holds a reference to a student object.

Accessing an Object using Data and Methods-After an object is created, its data can be accessed
and its methods invoked using the dot operator (.), also known as the object member access
operator.

Eg. 6.1 Class and objects.

Problem-write a program that display the given id,grade and name of student using the concept
of class and object.

Aim-to understand how to use object and class and how to acess objects in java.

1 package classandobject;
2 //declaring class
3 public class Classandobject {
4 public static void main(String[] args) {
5 //creat object stu for class student
6 student stu=new student();
7 //accessing student id in java class accessed by dot operator
8 [Link]("Student id="+[Link]);
9 //accessing student grade
10 [Link]("Student grade="+[Link]);
11 //accessing student name
12 [Link]("Student name="+[Link]);
13 }}
14 //creat class student
15 class student{
16 /*this is default argument constructor
17 constructor name the same as class name */
18 student(){
19 [Link]("information of student");
20 }

74
21 //declaration and intalization of student id
22 int id=186;
23 //declaration and intalization student grade
24 float grade=(float) 3.80;
25 //declaration and intalization student name
26 String name="Yosef Alamirew";
27 }//end of student class

Summary

An object is real-world entity that has state and behavior is known as an [Link] is an instance
of class. An object has three characteristics State, Behavior and Identity. The core element of
Object orientation in Java is the class. A class is often defined as the blueprint or template for an
object. We can create multiple objects from a class. It is a logical entity that does not occupy any
space. A class can be visualized as a three-compartment box that contain Name, Variables and
Methods.

Questions

1. What is a class?
2. What is the inner class?
3. What is the outer class?
4. What is the advantage of defining an inner class?
5. What is the base class of all classes?
6. What is an object in Java? How can you create an object in Java?

75
Lab Seven-Constructor and method
Objective- At the end of these lessons students will able to understand.

 Constructor
 Types of constructor
 Method
 Method calling
 Parameters and Arguments

7.1 Constructor

A constructor is a special block of code used to set up a new object. It's like a method in Java,
but with no return type. Constructors have the same name as the class they belong to. They can't
be inherited or declared final. Constructors can also call other constructors in the same class
using the "this" keyword. For example, "this()" calls the default constructor.

In Java, a constructor is a special type of method that is called when an object of a class is
created. It helps allocate memory for the object and initialize it. Whenever we use the "new()"
keyword to create an object, at least one constructor is called. Constructors are like blocks of
code that are similar to methods but with the purpose of initializing the object.

There are three rules defined for the constructor.

 Constructor name must be the same as its class name


 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized

Note-this () must be the first statement in the calling constructor. A constructor calls the
constructor of the parent class by default. We can use access modifiers while declaring a
constructor. It controls the object creation. In other words, we can have private, protected, public
or default constructor in Java.

76
Constructor Chaining in Java

Constructor Chaining in Java is a process in which a constructor calls another constructor of the
same class with the current/present object. The concept of constructor chaining helps to pass the
parameters through different constructors, but with the same object.

Constructor Overloading in Java

Overloading generally means “to have multiple instances of the same thing”. Constructor
Overloading in Java is a process of having more than one constructor with different parameters
list. It allows the constructor to behave differently and perform a different task with respect to its
parameters. Constructor overloading is the same as method overloading in java.
There are three types of constructors

1. Default argument constructor


2. No-argument constructor
3. Parameterized constructor

Eg. 7.1 Constructor in java.

Problem-write a program that display a given id,grade and name of student using Constructor.

Aim-in order to understand the use of Constructor in java program.

1 /* A constructor is a block of code that initializes the newly


2 created object. A constructor resembles an instance method in
3 java but it’s not a method as it doesn’t have a return type */
4 package constructor;
5 public class Constructor {
6 public static void main(String[] args) {
7 //creat object stu for class student
8 student stu=new student();
9 //accessing student id using dot opertor
10 [Link]("Student id="+[Link]);
11 //accessing student grade

77
12 [Link]("Student grade="+[Link]);
13 //accessing student name
14 [Link]("Student name="+[Link]);
15 }}
16 //creat class named student
17 class student{
18 /*this is constructor i.e constructor name the same as class
19 name this constructor is default argument constructor */
20 student(){
21 [Link]("Constructor Eg.");
22 [Link]("information of student");
23 }//end of constructor that named student
24 //declaration and intalization of student id
25 int id=1307;
26 //declaration and intalization student grade
27 float grade=(float) 3.99;
28 //declaration and intalization student name
29 String name="Lishan Eticha";
30 }//end of student class

78
7.2 Method
A method is a block of code that performs a specific task. It has two parts: the method header
and the method body [2]. Methods can be either static, which means they belong to the class
itself, or instance methods, which are associated with instances of the class. A class, on the other
hand, is a collection of methods, class variables, and instance variables. It is not directly
executable on its own.

The general syntax to create a method.

Modifier return_type method_name (parameter optional){//method header

Statements (method body)

Eg. public static void methodexample() {

[Link] ("Hello world");

}}

Call a Method-To call a method in Java, write the method's name followed by two parentheses
() and a semicolon;

Parameters and Arguments-Information can be passed to methods as a parameter. Parameters


act as variables inside the method. Parameters are specified after the method name, inside the
parentheses. You can add as many parameters as you want, just separate them with a comma.
When a parameter is passed to the method it is called an argument.

Note-parameters are optional it is not mandatory.

Difference between Constructor and Method in Java

The following points explain the difference between constructor and method in Java.

 A constructor is a block of code that instantiates a newly created object, while a method
is a set of statements that always return value depending upon its execution

79
 The constructor’s name should be the same as the class name. On the other hand, the
name of the method should not be the same as the class name
 Constructors are called implicitly, while we call the methods explicitly
 A constructor should not have any return type, not even void, but methods must have a
return type
 The compiler automatically creates the constructor if there is no constructor in the class.
But, in the case of the method, there is no default method provided by the compiler
 We can override a method but we can’t override a constructor
Eg. 7.2 Methods in java.

Problem-write a java program that display a string “This is OOP Module” using method.

Aim-to understand how to use methods in java program.

1 package method;
2 public class Method {
3 public static void main(String[] args) {
4 /*A method is just a chunk of code that does a particular job.
5 But methods are set out in a certain way.
6 You have a method header and a method body. */
7 [Link]("Method Example");
8 //calling a method
9 methodexample.();
10 }
11 /*creating method methodEg.
12 public and static is modifier
13 void is return type and methodEg. is method name */
14 //method no parameters
15 public static void methodexample()
16 {
17 [Link]("This is OOP Module");
18 }//end of method methodexample.

80
19 }

Summary

A constructor is a block of code that initializes the newly created object. A constructor resembles
an instance method in java but it’s not a method as it doesn’t have a return type. In short
constructors and methods are different. A constructor has the same name as the class. We cannot
inherit constructors. A constructor cannot be declared final. A constructor can call another
constructor of the same class using this keyword. A method is a procedure that executes within
the context of a class (static methods) or an instance of a class (instance methods).class is a
collection of methods, a collection of class variables, and a collection of instance variables - it is
not directly executable itself.

Questions

1. Explain constructors the types of constructors in Java?


2. What is the purpose of the default constructor?
3. Does the constructor return any value?
4. Is constructor inherited?
5. Can you overload a constructor in Java?
6. What is constructor chaining in Java?
7. Can you make the constructor final?
8. What is a static method?
9. Why the main method is static?
10. What are default and parameterized constructors?
11. Can a constructor call another constructor?
12. Can a constructor call the constructor of the parent class?
13. Explain ways to pass the arguments in Java?
14. What is a static method?

81
Lab Eight- Encapsulation and Inheritance
Objective- At the end of these lessons students will able to understand.

 Encapsulation
 Advantage of encapsulation
 Inheritance
 Advantage of inheritance
 Types of Inheritance

8.1 Object-oriented programming concepts


Object-oriented programming (OOP) is a programming approach that revolves around the idea of
"objects" containing both data and methods [4]. The main goal of OOP is to make programs
more flexible and easier to maintain. By organizing data and behavior together in objects, it
becomes simpler to grasp how a program functions. In our discussion, we will delve into each
aspect of OOP in depth, ensuring a clear understanding of OOP concepts without any difficulty.

8.2 Encapsulation
Encapsulation simply means binding object state (fields) and behavior (methods) together [4]. If
you are creating a class, you are doing encapsulation. In this guide we will see how to do
encapsulation in a java program, if you are looking for a real-life Eg. of encapsulation then refer
to this guide.

Note-The whole idea behind encapsulation is to hide the implementation details from users.

Eg. 8.1 Encapsulation in java.

Problem-write a program that display the given age,SSN and name of employee using
encapsulation concept.

Aim-in order to understand the use of Encapsulation.

1 package encapsulation;
2 public class Encapsulation {
3 public static void main(String[] args) {
4 /*Encapsulation simply means binding object state (fields) and behavior

82
5 (methods) together. If you are creating a class, you are doing
6 [Link] whole idea behind encapsulation is to hide the
7 implementation details from users. */
8 EncapsulationDemo obj = new EncapsulationDemo();
9 //Access objects using dot operator
10 [Link]("Samrawit Brihanu");
11 [Link](25);[Link](1300);
12 [Link]("Employee Name: " + [Link]());
13 [Link]("Employee SSN: " + [Link]());
14 [Link]("Employee Age: " + [Link]()); }}
15 /*create class named EncapsulationDemo so this class binding object state
16 (fields) and behavior (methods) together. */
17 class EncapsulationDemo{
18 //object state (fields)
19 private int ssn,empAge;
20 private String empName;
21 //behavior (methods) Getter and Setter methods
22 public int getEmpSSN(){
23 return ssn;}
24 public String getEmpName(){
25 return empName;}
26 public int getEmpAge(){
27 return empAge;}
28 public void setEmpAge(int newValue){
29 empAge = newValue;}
30 public void setEmpName(String newValue){
31 empName = newValue;}
32 public void setEmpSSN(int newValue){
33 ssn = newValue;}}

83
8.3 Inheritance
The process by which one class acquires the properties (data members) and functionalities
(methods) of another class are called inheritance [2]. The purpose of inheritance is to allow code
to be reused, so that a class only needs to define its unique features, while inheriting the common
properties and functionalities from another class. Inheritance is achieved using the "extends"
keyword to inherit a class. In inheritance, there are two classes involved.

1. Child Class-The class that extends the features of another class is known as child class,
subclass, or derived [Link] inherits all property of the parent class.
2. Parent Class-The class whose properties and functionalities are used(inherited) by
another class is known as the parent class, superclass, or Base class.

Note-The biggest advantage of Inheritance is that the code that is already present in the base
class need not be rewritten in the child class.

Types of inheritance in Java

1. Single- refers to a child and parent class relationship where a class extends the another
class.
2. Multiple- refers to the concept of one class extending more than one classes, which
means a child class has two parent classes. For Eg. class C extends both classes A and B.
Java doesn’t support multiple inheritance.
3. Multilevel- refers to a child and parent class relationship where a class extends the child
class. For Eg. class C extends class B and class B extends class A.
4. Hybrid- Combination of more than one types of inheritance in a single program. For Eg.
class A & B extends class C and another class D extends class A then this is a hybrid
inheritance Eg. because it is a combination of single and hierarchical inheritance.

84
5. Hierarchical- refers to a child and parent class relationship where more than one classes
extends the same class. For Eg., classes B, C & D extends the same class A.

Syntax Inheritance in Java

Class child extends parent {

Eg. 8.2 single inheritance in java.

Problem-write a program using the concept of Single inheritance with the given class and
properties of a class person(name,age,sex),student(gpa,department) N.B student extends person.

Aim-to understand how to use single inheritance in java program.

1 /* Single inheritance refers to a child and parent class


2 relationship where a class extends the another class */
3 package singleinhertance;
4 public class Singleinhertance {
5 public static void main(String[] args) {
6 /* create object for class student that is child class
7 i.e it share properties and methods of parent class person */
8 student stu1 = new student();
9 [Link]("==================================================");
10 [Link]("Single Inheritance Example");
11 [Link]("==================================================");
12 // acess parent class properties and methods
13 [Link]("student object properties acess from parent class person");
14 [Link]("Name="+[Link]);
15 [Link]("age="+[Link]);
16 [Link]("sex="+[Link]);
17 [Link]();
18 // acess child class properties

85
19 [Link]("_______________________________________________________");
20 [Link]("student object properties acess from child class student ");
21 [Link]("gpa="+[Link]);
22 [Link]("department="+[Link]);
23 [Link]("____________________________________________________");
24
25 }}
26 //Parent class named person
27 class person{
28 //parent class properties can acess by child class
29 String name = "Birhanu";
30 int age = 25;
31 char sex='M';
32 //parent class methodscan acess by child class
33 void does(){
34 [Link]("parent class method");
35 }}
36 /* child class student for parent class person so child class
37 acess the properties and methods of parent class person child class
38 properties and methods are only acess and use by child class */
39 class student extends person{
40 //child class properties only for this class
41 float gpa=(float) 3.67;
42 String dept="computer science";
43 }

86
44

Based on the above Eg. we can say that student is a person this means that a child class has an
IS-A relationship with the parent class. This is inheritance is known as IS-A relationship between
a child and parent class

Note-The derived class inherits all the members and methods that are declared as public or
protected. If the members or methods of a super class are declared as private then the derived
class cannot use them directly. The private members can be accessed only in its own class. Such
private members can only be accessed using a public or protected getter and setter methods of a
superclass as shown in the Eg. below.

Eg. 8.3 Multilevel inheritance.

Problem-write a simple java program using the concept of multilevel inheritance using the given
class and properties of a class preson(name,age,sex),student(gpa,department) and
extensionstudent(paymentforsemister)

N.B student is a child of person and extensionstudent is a child of student.

Aim-to understand multilevel inheritance in program.

1 /* Multilevel refers to a child and parent class relationship


2 where a class extends the child class. For Eg. class C

87
3 extends class B and class B extends class A */
4 package multilevelinhertance;
5 public class Multilevelinhertance {
6 public static void main(String[] args) {
7 /* create object for class extensionstudent that is child class
8 i.e it share properties and methods of parent class student and person */
9 extensionstudent stu=new extensionstudent();
10 [Link]("==================================================");
11 [Link]("multilevel Inheritance Example");
12 [Link]("==================================================");
13 // acess parent class properties and methods
14 [Link]("student object properties acess from parent class person");
15 [Link]("Name="+[Link]);
16 [Link]("age="+[Link]);
17 [Link]("sex="+[Link]);
18 [Link]();
19 // acess child class properties
20 [Link]("_________________________________________________________");
21 [Link]("student object properties acess from child class student ");
22 [Link]("gpa="+[Link]);
23 [Link]("department="+[Link]);
24 //acess child of child class properties
25 [Link]("_________________________________________________________");
26 [Link]("student object properties acess from class extensionstudent");
27 [Link]("payment="+[Link]);
28 [Link]("_________________________________________________________");
29 }}
30 //Parent class named person
31 class person{
32 //parent class properties can acess by child class
33 String name = "Birhanu";

88
34 int age = 25;
35 char sex='M';
36 //parent class methodscan acess by child class
37 void does(){
38 [Link]("parent class method");
39 }}
40 /* child class student for parent class person so child class
41 acess the properties and methods of parent class person child class
42 properties and methods are only acess and use by child class */
43 class student extends person{
44 //child class properties only for this class
45 float gpa=(float) 3.67;
46 String dept="computer science";
47 }
48 //antoher child class that extends child class student
49 class extensionstudent extends student{
50 float paymentforsemister=1560;
51 }

89
Eg. 8.4 Hierarchical inheritance

Problem-write a simple java program using the concept of hierarchical inheritance with the
given class and properties of a class person(name,age and sex),Student
(gpa,department),employee(montlysalary),worker(dialypayment)

Aim-to understand the hierarchical inheritance in a simple java program.

1 /* Hierarchical refers to a child and parent class relationship


2 where more than one classes extends the same class.
3 For Eg., classes B, C & D extends the same class A */
4 package heraricalinheritance;
5 public class Heraricalinheritance {
6 public static void main(String[] args) {
7 //create object for child class student
8 student stu=new student();
9 [Link]("================================================");
10 [Link]("Hierarchical Inheritance Example");
11 [Link]("================================================");
12 // acess parent class properties and methods
13 [Link]("student properties Acess from parent class person ");
14 [Link]("Name="+[Link]);
15 [Link]("age="+[Link]);
16 [Link]("sex="+[Link]);
17 [Link]();
18 [Link]("___________________________________________________");
19 // acess child class properties
20 [Link]("Student properties Acess form child class student");
21 [Link]("gpa="+[Link]);
22 [Link]("department="+[Link]);
23 //create object for child class employee
24 employee emp=new employee();

90
25 [Link]("_________________________________________________");
26 [Link]("employee object properties acess from parent class");
27 [Link]("Name="+[Link]);
28 [Link]("age="+[Link]);
29 [Link]("sex="+[Link]);
30 // acess child class properties
31 [Link]("_________________________________________________");
32 [Link]("employee object properties acess from child class");
33 [Link]("monthly salary="+[Link]);
34 //create object for child class worker
35 worker wo=new worker();
36 // acess child class properties and methods
37 [Link]("_________________________________________________");
38 [Link]("worker object properties Acess from parent class ");
39 [Link]("worker object properties");
40 [Link]("Name="+[Link]);
41 [Link]("age="+[Link]);
42 [Link]("sex="+[Link]);
43 // acess child class properties
44 [Link]("_________________________________________________");
45 [Link]("worker object properties Acess from child class ");
46 [Link]("daily payment="+[Link]);
47 [Link]("_________________________________________________");
48 }}
49 //Parent class named person
50 class person{
51 //parent class properties can acess by child class
52 String name = "Birhanu";
53 int age = 25;
54 char sex='M';
55 //parent class methods can acess by child class

91
56 void does(){
57 [Link]("parent class method");
58 }}
59 /* child class student for parent class person so child class
60 acess the properties and methods of parent class person child class
61 properties and methods are only acess and use by child class */
62 class student extends person{
63 //child class properties only for this class
64 float gpa=(float) 3.67;
65 String dept="computer science";
66 }
67 /* child class employee for parent class person so child class
68 acess the properties and methods of parent class person child class
69 properties and methods are only acess and use by child class */
70 class employee extends person{
71 float monthsalary=10450;
72 }
73 /* child class worker for parent class person so child class
74 acess the properties and methods of parent class person child class
75 properties and methods are only acess and use by child class */
76 class worker extends person{
77 float dialypayment=120;
78 }

92
Eg. 8.5 hibrid inheritnce

Problem-write a simple java program using the concept of hybrid inheritance class and
properties of a class person(name,age,sex),employee(montly salary),student and
extensionstudent(payment for semester).

Aim-to understand the use of hybrid inheritance in java program.

1 /* Hybrid inhertance is a Combination of more than one types of inheritance


2 in a single program. For Eg. class A & B extends class C
3 and another class D extends class A then this is a hybrid inheritance

93
4 because it is a combination of single and hierarchical inheritance */
5 package hibraidinhetance;
6 public class Hibraidinhetance {
7 public static void main(String[] args) {
8 /* create object for class extensionstudent that is child class
9 i.e it share properties and methods of parent class student and person */
10 extensionstudent stu=new extensionstudent();
11 [Link]("====================================");
12 [Link]("hibrid Inheritance Example");
13 // Acess parent class properties and methods
14 [Link]("====================================");
15 [Link]("Acess from parent class person");
16 [Link]("Name="+[Link]);
17 [Link]("age="+[Link]);
18 [Link]("sex="+[Link]);
19 [Link]();
20 // acess child class properties
21 [Link]("______________________________________");
22 [Link]("Acess from child class student ");
23 [Link]("gpa="+[Link]);
24 [Link]("department="+[Link]);
25 //acess child of child class properties
26 [Link]("________________________________________");
27 [Link]("Acess from child of child class extensionstudent ");
28 [Link]("payment="+[Link]);
29
30 //create objects for child class employee
31 employee emp= new employee();
32 [Link]("_________________________________________");
33 [Link]("Acess from parent class person ");
34 [Link]("Name="+[Link]);

94
35 [Link]("age="+[Link]);
36 [Link]("sex="+[Link]);
37 [Link]();
38 // acess child class properties
39 [Link]("_________________________________________");
40 [Link]("Acess from child class employee ");
41 [Link]("montly salary="+[Link]);
42 [Link]("________________________________________");
43 }}
44 //Parent class named person
45 class person{
46 //parent class properties can acess by child class
47 String name = "Birhanu";
48 int age = 25;
49 char sex='M';
50 //parent class methods can acess by child class
51 void does(){
52 [Link]("parent class method");
53 }}
54 /* child class student for parent class person so child class
55 acess the properties and methods of parent class person child class
56 properties and methods are only acess and use by child class */
57 class student extends person{
58 //child class properties only for this class
59 float gpa=(float) 3.67;
60 String dept="computer science";
61 }
62 /* child class employee for parent class person so child class
63 acess the properties and methods of parent class person child class
64 properties and methods are only acess and use by child class */
65 class employee extends person{

95
66 float monthsalary=10450;
67 }
68 //antoher child class that extends child class student
69 class extensionstudent extends student{
70 float paymentforsemister=1560;
71 }

96
Summary

Object-oriented programming (OOPs) is a programming paradigm based on the concept of


“objects” that contain data and methods. The primary purpose of object-oriented programming is
to increase the flexibility and maintainability of programs. Encapsulation simply means binding
object state (fields) and behavior (methods) together. If you are creating a class, you are doing
encapsulation. The process by which one class acquires the properties and functionalities of
another class are called inheritance. The aim of inheritance is to provide the reusability of code
so that a class has to write only the unique features and the rest of the common properties and
functionalities can be extended from another class.

Questions

1. What is encapsulation?
2. What is the advantage of encapsulation?
3. What is inheritance?
4. Why multiple inheritances not supported in java?
5. Write a program using the concept of encapsulation and inheritance?

97
Lab Nine- Method Overloading
Objective- At the end of these lessons students will able to understand.

 Method overloading
 Ways to overload a method
 Method overriding
 Advantage of method overriding
 The difference between method overloading and method overriding

9.1 Method overloading


Method Overloading is a method that can have the same name with different parameters [3].

To overload a method, the method signature must be different, return type doesn’t play any role
in method overloading. It is possible to overload the main () method of a class.

Three ways to overload a method

1. Number of parameters
Eg. Float sum (int a,int b); and Float sum (int a,int b,int c);
2. Change the Data type of parameters.
Eg. Float sum (int a,int b); and Float sum(float a,float b);
3. Change the Sequence of Data type of parameters.
Eg. Float sum (int a, float b); and Float sum (float a, int b);

Eg. 9.1 Method Overloading in java.

Problem-write a program that overload a method disp and dispnum.

Aim-in order to understand how to overload methods in a program.

1 package methodoverloading;
2 public class Methodoverloading {
3 public static void main(String[] args) {
4 /*Method Overloading is a method that can have the same name with different
5 parameters. It is possible to overload the main () method of a class */

98
6 // create object obj for class DisplayOverloading
7 DisplayOverloading obj = new DisplayOverloading();
8 [Link]("Computer");
9 [Link]("Computer","Science");
10 [Link](1621);
11 [Link](1621.0);
12 }}
13 //creating class named DisplayOverloading
14 class DisplayOverloading
15 {
16 //method with one parameter
17 public void disp(String a){
18 [Link](a);
19 }//overload by a Number of parameters
20 public void disp(String a, String b)//method with two parameters
21 {
22 [Link](a + " "+b);
23 }
24 //method overloading with Data type of parameters.
25 public void dispnum(int a)//method with parameters type int
26 {
27 [Link](a);}
28 public void dispnum(double a)//method with parameter type double
29 {
30 [Link](a);}}

99
9.2 Method Overriding
Method overriding refers to the act of declaring a method in a subclass that already exists in the
parent class. This allows the child class to provide its own implementation for a method that is
already defined in the parent class. The method in the parent class is referred to as the overridden
method, while the method in the child class is known as the overriding method.

9.3 Advantage of method overriding


The key benefit of method overriding is that a class can provide its own unique implementation
for an inherited method, without needing to modify the code of the parent class. This is
particularly useful when a class has multiple child classes. If a child class wants to use the
method from the parent class, it can do so. However, if other child classes require a different
implementation, they can utilize the overriding feature to make the necessary changes without
altering the code of the parent class.

Eg. 9.2 Method Overriding in java.

Problem-write a simple java program using the concept of Method Overriding.

Aim-to understand the main advantage of method overriding.

1 package methodoverriding;
2 /*The main advantage of method overriding is that the class
3 can give its own specific implementation to an inherited
4 method without even modifying the parent class code*/
5 public class Methodoverriding {
6 public static void main(String[] args) {
7 /*Here speedLimit() method of class Ford is overriding
8 the speedLimit() method of class CarClass*/
9 //create object obj for subclass Ford i.e obj is Ford object
10 CarClass obj = new Ford();
11 int num= [Link]();
12 //print object for subclass ford i.e num=80
13 [Link]("Speed Limit is: "+num);

100
14 }}
15 //create class named CarClass
16 class CarClass{
17 public int speedLimit() {
18 return 60;
19 }}
20 //create subclass ford i.e subclass of CarClass
21 class Ford extends CarClass{
22 public int speedLimit(){
23 return 80;
24 }}

9.4 method overloading vs overriding in Java

1. Overloading happens at compile-time while Overriding happens at the runtime-the binding


of an overloaded method call to its definition has happened at compile-time however
binding of the overridden method call to its definition happens at runtime.
2. Static methods can be overloaded which means a class can have more than one static
method of the same name. Static methods cannot be overridden, even if you declare the
same static method in child class it has nothing to do with the same method of the parent
class.
3. The most basic difference is that overloading is being done in the same class while
overriding base and child classes are required. Overriding is all about giving a specific
implementation to the inherited method of the parent class.
4. Static binding is being used for overloaded methods and dynamic binding is being used for
overridden/overriding methods.
5. Performance-Overloading gives better performance compared to overriding. The reason is
that the binding of overridden methods is being done at runtime.

101
6. Private and final methods can be overloaded but they cannot be overridden. It means a
class can have more than one private/final method of the same name but a child class
cannot override the private/final methods of their base class.
7. The return type of method does not matter in case of method overloading it can be the
same or different. However, in the case of method overriding the overriding method can
have a more specific return type.
8. The argument list should be different while doing method overloading. The argument list
should be the same in method Overriding.

Summary

Method Overloading is a method that can have the same name with different parameters. to
overload a method, the method signature must be different, return type doesn’t play any role in
method overloading. Method overriding is declaring a method in subclass which is already
present in the parent class is known as method overriding. Overriding is done so that a child class
can give its own implementation to a method that is already provided by the parent class. the
main advantage of method overriding is that the class can give its own specific implementation
to an inherited method without even modifying the parent class code.

Questions

1. What is method overloading?


2. Can we overload the main() method?
3. What is method overriding?
4. Can we override the static method?
5. Why Operator overloading is not supported in Java?
6. Why we cannot overload a method by just changing the return type?

7. What is the difference between method overloading and method overriding?

102
Lab Ten- Polymorphism
Objective- At the end of these lessons students will able to understand.

 Polymorphism
 Advantage of Polymorphism
 The relation between Polymorphism and inheritance

10.1 Polymorphism
Polymorphism is one of the OOPs features that allow us to perform a single action in different
ways. Polymorphism is the capability of a method to do different things based on the object that
it is acting upon. In other words, polymorphism allows you to define one interface and have
multiple implementations.

For Eg. let’s say we have a class Animal that has a method sound (). Since this is a generic class
so we can’t give it implementation like Roar, Meow, Oink, etc…We had to give a generic
message.

Public class Animal {

Public void sound () {

[Link] (“Animal is making a sound”);

}}

Now let’s say we two subclasses of Animal class Horse and Cat that extend (inheritance) Animal
class. We can provide the implementation to the same method as this.

Public class Horse extends Animal {

Public void sound () {

[Link] (“Neigh”);

}} and

Public class Cat extends Animal {

103
Public void sound () {

[Link] (“Meow”);

}}

As you can see that although we had the common action for all subclasses sound() but there were
different ways to do the same action. This is a perfect Eg. of polymorphism (a feature that allows
us to perform a single action in different ways). It would not make any sense to just call the
generic sound () method as each Animal has a different sound. Thus we can say that the action
this method performs is based on the type of object.

Eg. 10.1 Polymorphism in java.

Problem-write a program using the concept of polymorphism.

Aim-to know the use of polymorphism in java program.

1 /*Polymorphism is the capability of a method to do different things


2 based on the object that it is acting [Link] allows you
3 to define one interface and have multiple implementations */
4 public class Polymorphism {
5 public static void main(String[] args) {
6 //creat object for parent class Animal
7 Animal a=new Animal();
8 //create object for child class Horse
9 Animal h=new Horse();
10 //create object for child class cat
11 Animal c=new Cat();
12 //calling a method for parent class Animal
13 [Link]();
14 //calling a method for child class Horse
15 [Link]();
16 //calling a method for child class Cat
17 [Link]();

104
18 //sound() perform a single action in different ways
19 }}
20 class Animal{//parent class
21 //sound method for parent class Animal
22 void sound () {
23 [Link] ("Animal is making a sound");
24 }}
25 class Horse extends Animal{//child class Horse
26 @Override
27 //sound method for child class Horse
28 void sound () {
29 [Link] ("Neigh");}}
30
31 class Cat extends Animal{//child class Cat
32 @Override
33 //sound method for child class Cat
34 void sound () {
35 [Link] ("Meow");
36 }}

105
Summary

Polymorphism is one of the OOPs features that allow us to perform a single action in different
ways. Polymorphism is the capability of a method to do different things based on the object that
it is acting upon. polymorphism allows you to define one interface and have multiple
implementations.

Questions

1. What is polymorphism?
2. What is the advantage of polymorphism?
3. List the types of polymorphism?
4. Write a program using the concept of polymorphism?

106
Lab Eleven- Abstract Class and Interfaces
Objective- At the end of these lessons students will able to understand.

 Interfaces
 Abstract class
 The difference between abstract class and interfaces

11.1 Abstract Class characteristics


1. An abstract class can extend only one class or one abstract class at a time
2. An abstract class can extend another concrete (regular) class or abstract class
3. An abstract class can have both abstract and concrete methods
4. In abstract class keyword, “abstract” is mandatory to declare a method as an abstract
5. An abstract class can have protected and public abstract methods
6. An abstract class can have a static, final, or static final variable with any access specifies

11.2 Interfaces characteristics


1. An interface can extend any number of interfaces at a time
2. An interface can only extend another interface
3. An interface can have only abstract methods
4. In an interface keyword, “abstract” is optional to declare a method as an abstract
5. An interface can have only public abstract methods
6. An interface can only have public static final (constant) variable

Each of the above-mentioned points is explained with an Eg. below.

11.3 Abstract class vs interface in Java


Difference No.1: Abstract class can extend only one class or one abstract class at a time.

Eg. 11.1 Abstract class can extend only one class or one abstract class at a time.

Problem-write a program that indicates Abstract class can extend only one class or one abstract
class at a time.

Aim-in order to understand Abstract class can extend only one class or one abstract class at a
time.

107
1 /*Abstract class can extend only one class or one abstract class at a time
2 But Interface can extend any number of interfaces at a time */
3 package abstrandinter1;
4 public class Abstrandinter1 {
5 public static void main(String[] args) {
6 //create object obj for class Example4
7 Example4 obj=new Example4();
8 obj.display3();
9 //Example3 o=new Example3();error B/c abstract cannot be instantiated
10 }}
11 class Example1{
12 public void display1(){
13 [Link]("display1 method");
14 }}
15 abstract class Example2{
16 public void display2(){
17 [Link]("display2 method");
18 }}
19 abstract class Example3 extends Example1{
20 abstract void display3();
21 }
22 //Abstract class can extend only one class or one abstract class at a time.
23 class Example4 extends Example3{
24 @Override
25 public void display3(){
26 [Link]("display3 method");
27 }}

108
But Interface can extend any number of interfaces at a time

Eg. 11.2 Interface can extend any number of interfaces at a time.

Problem-write a program that indicates Interface can extend any number of interfaces at a time.

Aim-to understand Interface can extend any number of interfaces at a time.

1 /*Interface can extend any number of interfaces at a time but


2 Abstract class can extend only one class or one abstract class at a time */
3 package abstraandinter2;
4 public class Abstraandinter2 {
5 public static void main(String[] args) {
6 //create object obj for class Example4
7 Example4 obj=new Example4();
8 obj.display1(); }}
9 //create interface named Example1 first interface
10 interface Example1{
11 public void display1();
12 }
13 //create interface named Example2 second interface
14 interface Example2 {
15 public void display2();
16 }
17 /*create interface named Example3 This interface is
18 extending both the above interfaces */
19 interface Example3 extends Example1,Example2{
20 }
21 class Example4 implements Example3{
22 public void display1(){
23 [Link]("display2 method");
24 }
25 public void display2(){

109
26 [Link]("display3 method");
27 }}

Difference No.2: Abstract class can be extended (inherited) by a class or an abstract class.

Eg. 11.3 Abstract class can be inherited by a class or an abstract class.

Problem-write a program that makes Abstract class can be inherited by a class or abstract class.

Aim-in order to know Abstract class can be inherited by a class or an abstract class.

1 /* Abstract class can be inherited by a class or an abstract class


2 But Interfaces can be extended only by interfaces. Classes have to
3 implement them instead of extend */
4 package abstraandinterf3;
5 public class Abstraandinterf3 {
6 public static void main(String[] args) {
7 //create object named obj for class Example4
8 Example4 obj=new Example4();
9 obj.display2();
10 }}
11 //create class named Example1
12 class Example1{
13 public void display1(){
14 [Link]("display1 method");
15 }}
16 /*create abstract class named Example2 this Abstract class can
17 be inherited by a class or an abstract class */
18 abstract class Example2{
19 public void display2(){

110
20 [Link]("display2 method");
21 }}
22 //Abstract class Example2 inherited by a abstract class Example3
23 abstract class Example3 extends Example2{
24 abstract void display3();
25 }
26 //Abstract class Example3 inherited by class Example4
27 class Example4 extends Example3{
28 public void display2(){
29 [Link]("Example4-display2 method");
30 }
31 public void display3(){
32 [Link]("display3 method");
33 }}

But Interfaces can be extended only by interfaces. Classes have to implement them instead of
extend.

Eg. 11.4 Interfaces can be extended only by interfaces.

Problem-write a program that indicate Interfaces can be extended only by interfaces.

Aim- to understand Interfaces can be extended only by interfaces.

1 /*Interfaces can be extended only by interfaces


2 But Interfaces can be extended only by interfaces.
3 Classes have to implement them instead of extend.*/
4 package abstraandinter4;
5 public class Abstraandinter4 {
6 public static void main(String[] args) {

111
7 //create object obj for class Example3
8 Example3 obj=new Example3();
9 //access method display1() so display1 method displayed
10 obj.display1();
11 }}
12 //creat interface named Example1
13 interface Example1{
14 public void display1();
15 }
16 //interface extends interface
17 interface Example2 extends Example1{
18 }
19 //class implments interface but not extend
20 class Example3 implements Example2{
21 @Override
22 public void display1(){
23 [Link]("display1 method");
24 }}

Difference No.3: Abstract class can have both abstract and concrete methods

Eg. 11.5 Abstract class can have both abstract and concrete methods.

Problem-write a program that indicates Abstract class can have abstract and concrete methods.

Aim-in order to understand Abstract class can have both abstract and concrete methods.

1 /*Abstract class can have both abstract and concrete methods


2 But Interface can only have abstract methods,

112
3 they cannot have concrete methods.*/
4 package abstraandinterr5;
5 public class Abstraandinterr5 {
6 public static void main(String[] args) {
7 //create object for class
8 Example2 obj=new Example2();
9 //access object using dot opertor i.e display1 method displayed
10 obj.display1();
11 }}
12 //create abstract class
13 abstract class Example{
14 //abstract method Abstract class have abstract method
15 abstract void display1();
16 //concrete method Abstract class have concrete method
17 public void display2(){
18 [Link]("display2 method");
19 }}
20 //class Example2 inhert abstract class Example1
21 class Example2 extends Example1{
22 @Override
23 public void display1(){
24 [Link]("display1 method");
25 }}

But Interface can only have abstract methods, they cannot have concrete methods.

113
Eg. 11.6 Interface can only have abstract methods.

Problem-write a java program that indicates Interface can only have abstract methods.

Aim-to understamd Interface can only have abstract methods.

1 /*Interface can only have abstract methods */


2 package abstraandinterr6;
3 public class Abstraandinterr6 {
4 public static void main(String[] args) {
5 //create object for class Example2
6 Example2 obj=new Example2();
7 //calls concrete method display1() i.e display1 method displayed
8 obj.display1();
9 }}
10 //create interface using interface method
11 interface Example1{
12 //abstract method b/c Interface have abstract methods
13 public abstract void display1();
14 }
15 //create class Example2 that implments Example1
16 class Example2 implements Example1{
17 @Override
18 //concrete method for class b/c class has concrete method
19 public void display1(){
20 [Link]("display1 method");
21 }}

Difference No.4: In abstract class, the keyword ‘abstract’ is mandatory to declare a method as an
abstract.

114
Eg. 11.7 in abstract class the keyword ‘abstract’ is mandatory to declare a method.

Problem-write a simple java program that indicates in abstract class the keyword ‘abstract’ is
mandatory to declare a method.

Aim-to understand in abstract class the keyword ‘abstract’ is mandatory to declare a method.

1 /* In abstract class, the keyword ‘abstract’ is mandatory to declare


2 a method as an [Link] In interfaces, the keyword ‘abstract’ is
3 optional to declare a method as an abstract because
4 all the methods are abstract by default */
5 package abstraandinter7;
6 public class Abstraandinter7 {
7 public static void main(String[] args) {
8 //create object named obj for class Eg.2
9 Example2 obj=new Example2();
10 //access concrete method display1
11 obj.display1();
12 }}
13 //create abstract class Example1
14 abstract class Example1{
15 //abstract keyword is mandatory to declare a method in abstract class
16 public abstract void display1();
17 }
18 //class Example2 inherts class Example1
19 class Example2 extends Example1{
20 @Override
21 //create concrete methods for class Example2
22 public void display1(){
23 [Link]("display1 method");
24 }
25 public void display2(){

115
26 [Link]("display2 method");
27 }}

But In interfaces, the keyword ‘abstract’ is optional to declare a method as an abstract because
all the methods are abstract by default.

Eg. 11.8 in interfaces the keyword ‘abstract’ is optional to declare a method.

Problem-write a program that indicates in interfaces the keyword ‘abstract’ is optional to declare
a method.

Aim-to understand in interfaces the keyword ‘abstract’ is optional to declare a method.

1 /* in interfaces, the keyword ‘abstract’ is optional to


2 declare a method as an abstract because all the methods
3 are abstract by default but In abstract class, the keyword ‘abstract’
4 is mandatory to declare a method as an abstract. */
5 package abstraandinter8;
6 public class Abstraandinter8 {
7 public static void main(String[] args) {
8 Example2 obj=new Example2();
9 //acess abstract method display1 i.e display1 method displayed
10 obj.display1();
11 }}
12 interface Example{
13 // declare a method for interface without abstract b/c it is optional
14 public void display1();
15 }
16 interface Example1{
17 // declare a method for interface using abstract

116
18 public abstract void display1();
19 }
20 class Example2 implements Example1{
21 @Override
22 public void display1(){
23 [Link]("display1 method");
24 }
25 public void display2(){
26 [Link]("display2 method");
27 }}

Difference No.5: Abstract class can have protected and public abstract methods.

Eg. 11.9 Abstract class can have protected and public abstract methods.

Problem-write a program that indicates Abstract class can have protected and public abstract
methods.

Aim-to understand Abstract class can have protected and public abstract methods.

1 /*Abstract class can have protected and public abstract methods


2 But Interface can have only public abstract methods */
3 package abstraandinter9;
4 public class Abstraandinter9 {
5 public static void main(String[] args) {
6 //create object obj for class Example2
7 Example2 obj=new Example2();
8 //acess concrete method display1 i.e display1 method displayed
9 obj.display1();
10 }}

117
11 //abstract class named Example1
12 abstract class Example1{
13 //Abstract class can have protected and public abstract methods
14 protected abstract void display1();
15 public abstract void display2();
16 public abstract void display3();
17 }
18 class Example2 extends Example1{
19 public void display1(){
20 [Link]("display1 method");
21 }
22 public void display2(){
23 [Link]("display2 method");
24 }
25 public void display3(){
26 [Link]("display3 method");
27 }}

But Interface can have only public abstract methods.

Eg. 11.10 Interface can have only public abstract methods.

Problem-write a program that indicates Interface can have only public abstract methods.

Aim-in order to understand Interface can have only public abstract methods.

1 /* Interface can have only public abstract methods


2 but Abstract class can have protected and public abstract methods */
3 package abstraandinter10;
4 public class Abstraandinter10 {

118
5 public static void main(String[] args) {
6 //create object named obj for class Example2
7 Example2 obj=new Example2();
8 //acess method named display2 i.e display2 method displayed
9 obj.display2();
10 }}
11 //interface named Example1
12 interface Example1{
13 //Interface can have only public abstract methods
14 public void display1();
15 }
16 class Example2 implements Example1{
17 @Override
18 public void display1(){
19 [Link]("display1 method");
20 }
21 public void display2(){
22 [Link]("display2 method");
23 }}

Difference No.6: Abstract class can have static, final or static final variables with any access
specifier

119
Eg. 11.11 Abstract classs can have static, final, or static final variables.

Problem-write a program ihat indicates Abstract classs can have static, final, or static final
variables.

Aim-to understand Abstract classs can have static, final, or static final variables.

1 /* Abstract class can have static, final or static final


2 variables with any access specifier but But Interface
3 can have only public static final (constant) variable */
4 package abstraandinter11;
5 public class Abstraandinter11 {
6 public static void main(String[] args) {
7 //create object obj for class Example2
8 Example2 obj=new Example2();
9 //acess method display1
10 obj.display1();
11 //acess method display2
12 obj.display2();
13 }}
14 //abstract class named Example1
15 abstract class Example1{
16 /*Abstract class can have static, final or static
17 final variables with any access specifier*/
18 private int numOne=15;
19 protected final int numTwo=30;
20 public static final int numThree=100;
21 public void display1(){
22 [Link]("Num1="+numOne);
23 }}
24 class Example2 extends Example1{
25 public void display2(){

120
26 [Link]("Num2="+numTwo);
27 [Link]("Num2="+numThree);
28 }}

But Interface can have only public static final (constant) variable.

Eg. 11.12 Interface can have only public static final variables.

Problem-write a program indicates Interface can have only public static final variables.

Aim-in order to understand Interface can have only public static final variables.

1 /* Interface can have only public static final (constant) variable


2 but Abstract class can have static, final or static final
3 variables with any access specifier */
4 package abstraandinter12;
5 public class Abstraandinter12 {
6 public static void main(String[] args) {
7 //create object obj for class Example2
8 Example2 obj=new Example2();
9 //acess or call method display1
10 obj.display1();
11 }}
12 interface Example1{
13 //Interface have only public static final (constant) variable
14 int numOne=10;
15 }
16 class Example2 implements Example1{
17 public void display1(){

121
18 [Link]("Number="+numOne);
19 }}

Summary

An interface can extend any number of interfaces at a time. An interface can only extend another
interface. An interface can have only abstract methods. In an interface keyword, “abstract” is
optional to declare a method as an abstract. An interface can have only public abstract methods.
An interface can only have public static final (constant) variable. An abstract class can extend
only one class or one abstract class at a time. An abstract class can extend another concrete
(regular) class or abstract class. An abstract class can have both abstract and concrete methods.
In abstract class keyword, “abstract” is mandatory to declare a method as an abstract. An abstract
class can have protected and public abstract methods. An abstract class can have a static, final, or
static final variable with any access specifies.

Questions

1. What is an abstract class?


2. Can there be any abstract method without an abstract class?
3. Can you use abstract and final both with a method?
4. It is possible to instantiate an abstract class?
5. Can you declare an interface method static?
6. Can an interface be final?
7. Can we define private and protected modifiers for variables in interfaces?
8. When can an object reference be cast to an interface reference?

122
Lab Twelve – Exception
Objective- At the end of these lessons students will able to understand.

 Exception
 Why an exception occurs
 Exception handling and its Advantage
 Types of exceptions
 Errors
 Difference between error and exception

12.1 Exception handling overview


Exception handling is one of the most important features of java programming that allows us to
handle the runtime errors caused by exceptions.

12.2 Exception
An exception is an unwanted event that interrupts the normal flow of the program [1]. When an
exception occurs program execution gets terminated. In such cases, we get a system generated an
error message. The good thing about exceptions is that they can be handled in Java. By handling
the exceptions we can provide a meaningful message to the user about the issue rather than a
system-generated message, which may not be understandable to a user.

12.3 Why an exception occurs


There can be several reasons that can cause a program to throw an [Link]. Opening a non-
existing file in your program, Network connection problem, bad input data provided by the user,
etc…

12.4 Advantage of exception handling


Exception handling ensures that the flow of the program doesn’t break when an exception occurs
[4]. For Eg., if a program has a bunch of statements and an exception occurs mid-way after
executing certain statements then the statements after the exception will not execute and the
program will terminate abruptly. By handling we make sure that all the statements execute and
the flow of the program doesn’t break.

123
12.5 Difference between error and exception
Errors-indicate that something severe enough has gone wrong, the application should crash
rather than try to handle the error.

12.6 Types of exceptions


1. Checked exceptions- are checked at compile-time. It means if a method is throwing a
checked exception then it should handle the exception using a try-catch block or it should
declare the exception using throws keyword otherwise the program will give a
compilation error.
Eg. SQL, IO, and ClassNotFound Exceptions are checked exception.
2. Unchecked exceptions- are checked at runtime. It means if your program is throwing an
unchecked exception and even if you didn’t handle/declare that exception, the program
won’t give a compilation error. Most of the times these exception occurs due to the bad
data provided by the user during the user-program interaction. It is up to the programmer
to judge the conditions in advance, that can cause such exceptions and handle them
appropriately. All Unchecked exceptions are direct subclasses of the Runtime
Exception class.
Eg. Artimetic, NullPointer, ArrayIndexOutofBound exceptions are Unchecked
Exceptions.

124
Summary

An exception is an unwanted event that interrupts the normal flow of the program. When an
exception occurs program execution gets terminated. In such cases, we get a system generated an
error message. Exception handling is one of the most important features of java programming
that allows us to handle the runtime errors caused by exceptions. There can be several reasons
that can cause a program to throw an exception. Exception handling ensures that the flow of the
program doesn’t break when an exception occurs. Errors indicate that something severe enough
has gone wrong, the application should crash rather than try to handle the error. exception
divided into Checked exceptions and Unchecked exceptions.

Questions

1. What is exception handling?


2. What is the difference between checked and unchecked exceptions?
3. What is the base class for error and exception?
4. Is it necessary that each try block must be followed by a catch block?
5. What is finally blocks?
6. Can finally block be used without a catch?
7. What is the difference between throw and throws?
8. Exceptions are defined in which java package?

125
Lab Thirteen- Exception handling syntax
Objective- At the end of these lessons students will able to understand.

 Exception handling syntax


 How to handle different types of exceptions

13.1 Exception handling syntax


Exceptions-are events that occur in the code. A programmer can handle such conditions and take
necessary corrective actions. Eg.

NullPointerException-When you try to use a reference that points to null.

An object of this class gets created whenever a member is invoked with a “null” object.

Eg. 13.1 NullPointerException.

Problem-write a program that handles NullPointerException.

Aim-to understand how to handle NullPointerException.

1 /* NullPointerException-When you try to use a reference that


2 points to [Link] object of this class gets created whenever
3 a member is invoked with a “null” object */
4 package npoexception;
5 public class Npoexception {
6 public static void main(String[] args) {
7 try{
8 //create empty string named str
9 String str=null;
10 //try to acess string length that is empty that causes exception to occure
11 [Link] ([Link]());
12 /*Here, length() is the function, which should be used on an object.

126
13 However in the above Example String object str is null
14 so it is not an object due to which NullPointerException occurred */
15 }catch(NullPointerException e){
16 [Link]("NullPointerException..");
17 }}}

ArithmeticException-When bad data is provided by the user, for Eg. when you try to divide a
number by zero this exception occurs because dividing a number by zero is undefined.

Eg. 13.2 Arithmetic Exception.

Problem-write a program that handle Arithmetic Exception.

Aim-to understand and how to handle Arithmetic Exception in java program.

1 /* ArithmeticException-When bad data is provided by the


2 user e.g when you try to divide a number by zero this
3 exception occurs because dividing a number by zero is undefined */
4 package artimetexception;
5 public class Artimetexception {
6 public static void main(String[] args) {
7 try{
8 //Declar and Intalize num1 and num2
9 int num1=50, num2=0;
10 /* I’ve divided an integer by a zero and because
11 of this Arithmetic Exception is thrown
12 b/c dividing a number by zero is undefined */

127
13 int output=num1/num2;
14 //it causes exception to occure
15 [Link] ("Result: "+output);
16 }
17 catch(ArithmeticException e){
18 [Link] ("Arithmetic Exception");
19 [Link] ("You Shouldn't divide a number by zero");
20 }}}

ArrayIndexOutOfBoundsException-When you try to access the elements of an array out of its


bounds, the Eg. array size is 5 (which means it has five elements) and you are trying to access
the 10th element.

Eg. 13.3 ArrayIndexOutOfBoundsException.

Problem-write a program that handle ArrayIndexOutOfBoundsException.

Aim-to understand how to handle ArrayIndexOutOfBoundsException in java,

1 /* ArrayIndexOutOfBoundsException occure When you


2 try to access the elements of an array out of its bounds */
3 package arrayindexexception;
4 public class Arrayindexexception {
5 public static void main(String[] args) {
6 try{
7 //Array has only 10 elements
8 int a[]=new int[10];

128
9 /* assign value for non Exist array so try to acess this
10 array value leads ArrayIndexOutOfBounds exception */
11 a[11] = 9;
12 }catch(ArrayIndexOutOfBoundsException e){
13 [Link] ("ArrayIndexOutOfBounds");
14 }}}

StringIndexOutOfBoundException-An object of this class gets created whenever an index is


invoked of a string, which is not in the range. Each character of a string object is stored in a
particular index starting from 0. Each character of a string object is stored in a particular index
starting from 0. To get a character present in a particular index of a string we can use a method
charAt(int).

Eg. 13.4 StringIndexOutOfBoundException.

Problem-write a program that handle StringIndexOutOfBoundException.

Aim-to understand how to handle StringIndexOutOfBoundException.

1 /* StringIndexOutOfBoundException-An object of this class gets created


2 whenever an index is invoked of a string, which is not in the range */
3 package stringindexexcption;
4 public class Stringindexexcption {
5 public static void main(String[] args) {
6 try{
7 //create string str
8 String str="Computer Science";
9 //display string length for str object

129
10 [Link]("the length of string is="+[Link]());
11 char c = [Link](0);
12 //try to use string that not found in the range causes exception
13 c = [Link](35);
14 //display string that don not have index causes exception
15 [Link](c);
16 }catch(StringIndexOutOfBoundsException e){
17 [Link]("StringIndexOutOfBoundsException!!");

18 }}}

NumberFormatException- This exception occurs when a string is parsed to any numeric


variable. For Eg., the statement int num=[Link] (“java”) would throw because “java”
cannot be parsed to int.

Eg. 13.5 NumberFormatException.

Problem-write a simple java program that handle NumberFormatException.

Aim-to understand and how to handle NumberFormatException.

1 /* NumberFormatException occurs when string is parsed to any numeric variable*/


2 package numformatexception;
3 public class Numformatexception {
4 public static void main(String[] args) {
5 try{
6 /*string java is parsed to integer variable num.
7 this causes number format exception */
8 //type casting string into integer
9 int num=[Link] ("java") ;

130
10 //try to display string parsed into integer causes exception
11 [Link](num);
12 }catch(NumberFormatException e){
13 [Link]("Number format exception occurred");
14 }}}

Summary

Exceptions are events that occur in the code. A programmer can handle such conditions and take
necessary corrective actions. Eg. NullPointerException-when you try to use a reference that
points to null, ArithmeticException-when bad data is provided by the
user,ArrayIndexOutOfBoundsException-When you try to access the elements of an array out of
its bounds.

Questions

1. Can static block throw exception?


2. What is finally blocks?
3. Can we have a try block without a catch or finally block?
4. Can we have multiple catch blocks following a single try block?
5. When a finally block does not get executed?
6. Can we handle more than one exception in a single catch block?

131
Lab Fourteen –Java Applets
Objective- At the end of these lessons students will able to understand.

 Java applets
 Features of java Applets
 Restrictions imposed on Java applets
 standard ways in which you can run an applet

14.1 Java Applets

All Java programs are classified as Applications and Applets [3]. While applications are stand-
alone Java programs that run directly on your machine, applets are specific programs that require
use of a browser and should be included in an HTML web document.

In simple terms, application programs run with the help of a virtual machine independent of any
security restrictions, whereas an applet cannot run without the help of a browser and is subjected
to more harsh security restrictions in terms of network access. You can say, applets are kind of
an internet application that doesn’t require any kind of deployment procedure or installation.

An applet is a Java program that can be embedded into a web page It runs inside the web
browser and works on the client side. An applet is embedded in an HTML page using
the APPLET or OBJECT tag and hosted on a web server. Applets are used to make the web site
more dynamic and entertaining.

Applets are used to make the web site more dynamic and entertaining.

Important points
 All applets are sub-classes (either directly or indirectly) of [Link] class
 Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer. JDK provides a standard applet viewer tool called applet viewer
 In general, the execution of an applet does not begin at the main() method
 The output of an applet window is not performed by [Link](). Rather it is
handled with various AWT methods, such as drawString()

132
14.2 Features of Applets over HTML
 Displaying dynamic web pages of a web application
 Playing sound files
 Displaying documents
 Playing animations
14.3 Restrictions imposed on Java applets
Due to security reasons, the following restrictions are imposed on Java applets.
 An applet cannot load libraries or define native methods
 An applet cannot ordinarily read or write files on the execution host
 An applet cannot read certain system properties
 An applet cannot make network connections except to the host that it came from
 An applet cannot start any program on the host that’s executing it

14.3 Applet life cycle


Below is the description of each method of the applet life cycle.

1. init()-The init() is the initial method that executes when the applet execution starts. In
this method, the variable declaration and initialization operations take place
2. start ()-The start() method contains the actual code to run the applet. The start() method
runs immediately after the init() method executes. The start() method executes whenever
the applet gets restored, maximized, or moves from one tab to another tab in the browser
3. paint()-The paint() method is used to redraw the output on the applet display area. The
paint() method executes after the execution of the start() method and whenever the applet
or browser is resized
4. stop ()-The stop() method is used to stop the execution of the applet. The stop() method
executes when the applet gets minimized or moves from one tab to another in the browser
5. destroy()-The destroy() method gets executed when the applet window or tab containing
the webpage closes. The stop() method executes just before the invocation of the
destroy() method The destroy() method deletes the applet object from memory.

133
There are two standard ways in which you can run an applet
1. Executing the applet within a Java-compatible web browser
2. Using an applet viewer, such as the standard tool, applet-viewer. An applet viewer executes
your applet in a window. This is generally the fastest and easiest way to test your applet
Eg. 14.1 executing the applet within a Java-compatible web browser.
Problem-run applets using executing the applet within a Java-compatible web browser.
Aim-to understand how to run applets using executing the applet within a Java-compatible web
browser.
<!DOCTYPE html>
<html>
<head>
<title>java Applet</title>
</head>
<body>
<h1> Java applet Eg.</h1>
<p>

<applet code="[Link]" height="40" width="200">


This is where HelloWorld Applet runs.
</applet>
</p>
</body>
</html>

134
Eg. 14.2 run applet using applet viewer.
Problem-write a program that run applet using applet viewer.
Aim-to understand how to run applet using applet viewer.
1 /* run appiet Using an applet viewer, such as the standard tool,
2 applet-viewer. An applet viewer executes your applet in a window.
3 This is generally the fastest and easiest way to test your applet */
4 package helloworlds;
5 //The packages (libraries) to include.
6 import [Link];
7 //The packages (libraries) to include.
8 import [Link];
9 //Applet is the parent class
10 public class HelloWorlds extends Applet{
11 @Override
12 // paint() method is responsible for drawing to the screen
13 public void paint(Graphics g)
14 {
15 /* Draws the String object "Hello World!" to the (40,50) screen location.
16 at the pixel location (20,20) */
17 [Link]("Hello World!",40,50);
18 }
19 }

135
Summary
All Java programs are classified as Applications and Applets. While applications are stand-alone
Java programs that run directly on your machine, applets are specific programs that require use
of a browser and should be included in an HTML web document. An applet is a Java program
that can be embedded into a web page It runs inside the web browser and works on the client
[Link] applets are sub-classes (either directly or indirectly) of [Link]. There
are two standard ways in which you can run an applet Executing the applet within a Java-
compatible web browser and Using an applet viewer, such as the standard tool, applet-viewer.
An applet viewer executes your applet in a window. This is generally the fastest and easiest way
to test your applet.
Questions
1. What is the applet?
2. Applet extends in which class?
3. Explain the life cycle of an Applet.
4. What happens when an applet is loaded?
5. What are untrusted applets?
6. What Are The Attributes Of Applet Tags?
7. What is the applet class loader?
8. What is the applet security manager? What does it provide?

136
Lab Fifteen- Java applications
Objective- At the end of these lessons students will able to understand.

 Java application
 Types of application
 The difference between java applet and java application

15.1 What is an Application?

It is a stand-alone Java program that runs with the support of a virtual machine on a client or
server-side. Also referred to as an application program, a Java application is designed to perform
a specific function to run on any Java-compatible virtual machine regardless of the computer
architecture. An application is either executed for the user or for some other application program.
Eg.s of Java applications include database programs, development tools, word processors, text
and image editing programs, spreadsheets, web browsers, etc…

Java applications can run with or without a graphical user interface (GUI). It’s a broad term used
to define any kind of program in Java but limited to the programs installed on your machine. Any
application program can access any data or information or any resources available on the system
without any security restrictions. Java application programs run by starting the Java interpreter
from the command prompt and are compiled using the javac command and run using the java
command. Every application program generally stays on the machine on which they are
deployed. It has a single start point which has a main() method.

Java Application is just like a Java program that runs on an underlying operating system with the
support of a virtual machine. It is also known as an application program. The graphical user
interface is not necessary to execute the java applications it can be run with or without it.

Java application-Java program that runs stand-alone in a client or server. The Java Virtual
Machine interprets the instructions, and like any programming language running in its native
environment, Java programs have full access to all the resources in the computer in Contrast with
Java Applets.

137
There are mainly four types of applications that can be created using Java programming.
1. Standalone Application
2. Web Application
3. Enterprise Application
4. Mobile Application

15.2 Difference between Application and Applet


1. Definition of Application and Applet-Applets are feature-rich application programs that
are specifically designed to be executed within an HTML web document to execute small
tasks or just part of it. Java applications, on the other hand, are stand-alone programs that
are designed to run on a stand-alone machine without having to use a browser.
2. Execution of Application and Applet-Applications require the main method() to execute
the code from the command line, whereas an applet does not require the main method()
for execution. An applet requires an HTML file before its execution. The browser, in fact,
requires a Java plugin to run an applet.
3. Compilation of Application and Applet-Application programs are compiled using the
“javac” command and further executed using the java command. Applet programs, on the
other hand, are also compiled using the “javac” command but are executed either by
using the “applet viewer” command or using the web browser.
4. Security Access of Application and Applet-Java application programs can access all the
resources of the system including data and information on that system, whereas applets
cannot access or modify any resources on the system except only the browser-specific
services.
5. Restrictions of Application and Applet-unlike applications, applet programs cannot be
run independently, thus require the highest level of security. However, they do not
require any specific deployment procedure during execution. Java applications, on the
other hand, run independently and do not require any security as they are trusted.

138
Note- The fundamental difference between the two Java programs is that an application program
is designed to run on a stand-alone machine whereas an applet is a web-version of an application
that is used to run a program on a web browser. While an application can access all the resources
available on the system, an applet cannot have access to anything on the machine except the
browser-specific services.

Summary
Java application is designed to perform a specific function to run on any Java-compatible virtual
machine regardless of the computer architecture. An application is either executed for the user or
for some other application program. Java applications can run with or without a graphical user
interface (GUI). It’s a broad term used to define any kind of program in Java but limited to the
programs installed on your machine. Any application program can access any data or
information or any resources available on the system without any security restrictions. Java
Application is just like a Java program that runs on an underlying operating system with the
support of a virtual machine. It is also known as an application program. The graphical user
interface is not necessary to execute the java applications it can be run with or without it.

Questions

1. What is java application?


2. What is the key difference between java applet and application?

139
References
[1] “PROGRAMMING THROUGH JAVA MALLA REDDY COLLEGE OF
ENGINEERING &,” vol. 2, 2022.

[2] O. Programming, “Object-Oriented Programming Basics With Java,” pp. 1–48, 2003.

[3] B. Tech and I. Y. I. I. Sem, “OBJECT ORIENTED PROGRAMMING DIGITAL


NOTES,” vol. 2, 2018.

[4] B. Tech, I. I. Year, I. I. Sem, R. C. Shekar, and M. T. Shilpa, “OBJECT ORIENTED


PROGRAMMING THROUGH JAVA LAB ( R22A0586 ) LAB MANUAL Prepared
By :,” vol. 2, pp. 1–102, 2023.

140

You might also like