Java
Java
LABORATORY MANUAL
PREPARED BY
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
Evaluator
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
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
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.
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
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 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.
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.
7
Go to the NetBeans website ([Link] and download
the NetBeans IDE 8.1 installer.
During the installation process, you will be prompted to choose the installation options.
Make sure to select the appropriate options for your needs.
When prompted, select the JDK installation that you previously installed on your system.
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.
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
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.
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.
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.
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
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
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
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
Manual 1
Data+data1 Manual 2
Data+data2
Procedure 1
Procedure 2 Procedure 3
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
Object3 Data
Object4 Data
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
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).
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
Source file
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.
Data_type variable
Data_type variable=value;
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
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.
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.
Char-holds characters.
size: 2 bytes
27
Eg. 2.3 data types in java.
Aim-used to understand basic data types in java and the use of each data type.
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 }}
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.
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!";
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 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
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.
Name Symbol
Parenthesis ()
braces {}
brackets []
semicolon ;
comma , ,
period .
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
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
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.
38
Relational Operators-There are the following relational operators supported by the Java
language.
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.
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
Problem-write a java program using Bitwise operator within the given number
num1=11(00001011) and num2=22(00010110).
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 }}
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.
43
Assignment Operators-the following are assignment operators supported by Java language
Problem-write a java program by using the concept of Assignment operator with the given
number num1=100 and num2=300.
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.
46
12 [Link]("num1++ is: "+num1);
13 [Link]("num2-- is: "+num2);
14 [Link]("++num3 is: "+num3);
15 [Link]("--num4 is: "+num4);
16 }}
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 }}
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
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
Java statements
Decision statement
Repetition Statements
If, if-else, and switch statements
Array and pros and cons of array
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.
55
Eg. 4.1 if statement.
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.
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;
}
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 }}}
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.
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
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
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.
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.
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.
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
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
Problem-write a java program that displays the sum of 1-4 using for loop.
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 }}
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.
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.
loopVal++;
}
while ( loopVal < 5 );
Problem-write a java program that display the sum of 1-4 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.
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.
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
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.
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.
Name
Variable
Method
72
Inner Class-is a class within another class.
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 {}.
student student1;
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.
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.
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.
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
Problem-write a program that display a given id,grade and name of student using Constructor.
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.
}}
Call a Method-To call a method in Java, write the method's name followed by two parentheses
() and a semicolon;
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.
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
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.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.
Problem-write a program that display the given age,SSN and name of employee using
encapsulation concept.
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.
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.
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.
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.
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)
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)
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).
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
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
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.
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);
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.
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 }}
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
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.
}}
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.
[Link] (“Neigh”);
}} and
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.
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
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
Problem-write a program that indicates Interface can extend any number of interfaces at a time.
109
26 [Link]("display3 method");
27 }}
Difference No.2: Abstract class can be extended (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.
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.
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.
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.
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.
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.
Problem-write a program that indicates in interfaces the keyword ‘abstract’ is optional to declare
a method.
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.
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 }}
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.
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.
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.
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
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.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.
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.
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
125
Lab Thirteen- Exception handling syntax
Objective- At the end of these lessons students will able to understand.
An object of this class gets created whenever a member is invoked with a “null” 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.
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 }}}
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 }}}
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 }}}
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
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
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
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>
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
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
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
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.
140