100%(2)100% found this document useful (2 votes) 3K views114 pagesObject Oriented Programming Using Core Java Nirali
Object Oriented Programming Using Core Java Nirali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
THIRD YEAR B. Sc.
COMPUTER SCIENCE
OBJECT ORIENTED
PROGRAMMING USING JAVA-I
Dr. Ms. MANISHA BHARAMBE
Ms. MANISHA GADEKARgen 4 Book OF
OBJECT ORIENTED
PROGRAMMING USING
JAVA - |
For T.Y.B.Sc. Computer Science : Semester - V
[Course Code CS 355 : Credits - 2]
te a)
As Per New Syllabus, Effective from June 2021
Dr. Ms. Manisha Bharambe
‘M.Sc. (Comp. Sci.), M.Phil. Ph.D. (Comp. Sci.)
Vice Principal, Associate Professor, Department of Computer Science
MES's Abasaheb Garware College
Pune
Ms. Manisha Gadekar
M.C.A., (Science), UGC-NET
Assistant Professor, Annasaheb Magar College
PuneOBJECT ORIENTED PROGRAMMING USING JAVA -1 ISBN 978-93-5451-188-2
First Edition ‘August 2021
© : Authors
‘The text of this publication, or any part thereof, should not be reproduced or transmitted in any form or stored in any
computer storage system or device for distribution including photocopy, recording, taping or information retrieval system or
reproduced on any disc, tape, perforated media or other information storage device etc, without the written permission of
‘Authors with whom the rights are reserved. Breach of this condition is liable for legal action.
Every effort has been made to avoid errors or omissions in this publication. In spite of this, errors may have crept in. Any
mistake, error or discrepancy so noted and shall be brought to our notice shall be taken care of in the next edition. Itis notified
that neither the publisher nor the authors or seller shall be responsible for any demage or loss of action to any one, of any kind, in
‘any manner, therefrom. The reader must cross check all the facts and contents with original Govemment notification or
publications.
Published By : Polyplate
NIRALI PRAKASHAN
Abhyudaya Pragati, 1312, Shivaji Nagar,
Off IM. Road, Pune ~ 411005
Tel - (020) 25512336/37/39
Email :niralipune@ pragationline.com
ISTRIBUTION CENTRI
PUNE
Nirali Prakashan Nirali Prakashan
(For orders outside Pune) (For orders within Pune)
S. No, 28/27, Dhayari Narhe Road, Near Asian College 119, Budhwar Peth, Jogeshwari Mandir Lane
Pune 411041, Maharashtra Pune 411002, Maharashtra
Tel : (020) 24690204; Mol 9657703143, Tel : (020) 2445 2044; Mobile : 9657703145
Email: bookorder@ pragationline.com Email: nralilocal@pragationline,com
MUMBAI
Nirali Prakashan
Rasdhara Co-op. Hsg. Society Ltd, 'D' Wing Ground Floor, 385 SVP, Road
Girgaum, Mumbai 400004, Maharashtra
Mobile : 7045821020, Tel ; (022) 2385 6339 / 2386 9976
Email: niralimumbai@ pragationline.com
DISTRIBUTION BRANCHES|
DELHI BENGALURU NAGPUR
Nirali Prakashan Nirali Prakashan Nirali Prakashan
Room No. 2 Ground Floor Maitri Ground Floor, Jaya Apartments, | Above Maratha Mandir, Shop No. 3,
4575/15 Omkar Tower, Agarwal Road No. 99, 6" Cross, 6" Main, First Floor, Rani Jhanshi Square,
Darya Ganj, New Delhi 110002 Malleswaram, Bengaluru 560003 Sitabuldi Nagpur 440012 (MAH)
Mobile : 9555778814/9818561840 Kamataka; Mob : 9686821074 Tel: (0712) 254 7129
+ delhi@niralibooks.com Email: bengaluru@niralibooks.com | — Email: nagpur@niralibooks.com
KOLHAPUR JALGAON SOLAPUR
Nira Prakashan Nirali Prakashan Nirali Prakashan
New Mahadvar Road, Kedar Plaza, 34, V. V. Golani Market, Navi Peth, R-158/2, Avanti Nagar, Near Golden
1* Floor Opp. IDBI Bank Jalgaon 425001, Maharashtra Gate, Pune Naka Chowk
Kolhapur 416 012 Maharashtra Tel : (0257) 222 0395, Solapur 413001, Maharashtra
Mob : 9850046155 Mob : 94234 91860 Mobile 9890918687
Email : kolhapur@niralibooks.com Email : jalgaon@niralibooks.com Email : solapur@niralibooks.com
Tere eaePreface
We take an opportunity to present this Text Book on “Object Oriented Programming
Using Java - I" to the students of Third Year B.Sc. (Computer Science) Semester-V as per the
New Syllabus, June 2021.
The book has its own unique features. It brings out the subject in a very simple and
lucid manner for easy and comprehensive understanding of the basic concepts. The book
covers theory of An Introduction to Java, Objects and Classes, Inheritance and Interface,
Exception and File Handling and User Interface with AWT and Swing.
A special word of thank to Shri. Dineshbhai Furia, and Mr. Jignesh Furia for
showing full faith in us to write this text book. We also thank to Mr. Amar Salunkhe and
Mr. Akbar Shaikh of M/s Nirali Prakashan for their excellent co-operation.
We also thank Ms. Chaitali Takle, Mr. Ravindra Walodare, Mr. Sachin Shinde, Mr. Ashok
Bodke, Mr. Moshin Sayyed and Mr. Nitin Thorat.
Although every care has been taken to check mistakes and misprints, any errors,
omission and suggestions from teachers and students for the improvement of this text book
shall be most welcome.
AuthorsSyllabus
L
An Introduction to Java (6 Lectures)
.
Object Oriented Programming Concepts
A Short History of Java
Features or Buzzwords of Java
Java Environment
Simple Java Program
Java Tools — jdb, javap, javadoc
Types of Comments
Data Types
Final Variable
Declaring 1D, 2D Array
Accepting Input (Command Line Arguments, BufferedReader, Scanner)
Objects and Classes (7 Lectures)
.
Defining Your Own Classes
Access Specifiers - (public, protected, private, default)
Array of Objects
Constructors, Overloading Constructors and Use of ‘this’ Keyword, Static Block, Static Fields
and Methods.
Predefined Classes
© Object Class, Methods (equals(), toString), hashcode0, getClass)
© String Class and StringBuffer Class, Formatting String Data using format() Method
Creating, Accessing and Using Packages
Wrapper Classes
. Inheritance and Interface (8 Lectures)
Inheritance Basics (extends Keyword) and Types of Inheritance
Superclass, Subclass and Use of Super Keyword
Method Overriding and Runtime Polymorphism
Use of Final Keyword related to Method and Class
Use of Abstract Class and Abstract Methods
Defining and Implementing Interfaces
Runtime Polymorphism using Interface
Concept of Marker and Functional InterfacesException and File Handling (5 Lectures)
Dealing with Errors, Exception Class, Checked and Unchecked Exception
Catching Exceptions, Multiple Catch Block, Nested Try Block
Creating User Defined Exception
Introduction to Files and Streams
Input-OutputStream: FileInput/OutputStream, Bufferedinput/OutputStream,
Datalnput/Outputstream
Reader-Writer. _FileReader/Writer, _ButferedReader/Writer, _InputStreamReader,
OutputStreamWriter
User Interface with AWT and Swing (10 Lectures)
What is AWT? What is Swing? Difference between AWT and Swing
The MVC Architecture and Swing
Layouts and Layout Managers
Containers and Components - JFrame, JButton, JLabel, JText, JTextArea, JCheckBox and
JRadioButton, JList, JComboBox, JMenu and related Classes
Dialogs (Message, Confirmation, Input), JFileChooser, JColorChooser
Event Handling; Event Sources, Listeners
‘Adapters and Anonymous Inner ClassContents ...
1. An Introduction to Java
2. Objects and Classes
3. Inheritance and Interface
4. Exception and File Handling
5. User Interface with AWT and Swing
1.1-1.104
2.1 - 2.92
3.1 - 3.62
41-472
5.1 -5.126f
aaa
An Introduction to Java
Objectives...
> To understand Basic Concepts of Java Programming
> Toleam Java Environment
> To study Java Tools
> To study Arrays in Java
INTRODUCTION
Java is a general-purpose, high level, robust, Object-Oriented Programming (OOP)
language developed by Sun Microsystems in 1991.
OOP is a programming paradigm that uses objects and their interactions to design
applications and computer programs.
A programming paradigm describes the structure of a program. In other words, it
determines how the instructions are placed in a program.
Java programming language was initiated by James Gosling. He is called father of Java
programming.
The first version of Java 1.0 was released by Sun Microsystems in 1995. It made the
promise of "Write Once, Run Anywhere (WORA)", with free (no cost) runtimes on
popular platforms such as Enterprise applications.
With the advancement of Java and its widespread popularity, use new enhanced
versions of Java have been released. The new J2 versions were renamed as Java SE,
Java EE, and Java ME respectively.
Java Platform, Standard Edition (Java SE) is a computing platform for development
and deployment of portable code for desktop and server environments. Java SE was
formerly known as Java 2 Platform, Standard Edition (J2SE).
Java Platform, Micro Edition (Java ME) is a computing platform for development and
deployment of portable code for embedded and mobile devices (micro-controllers,
sensors, mobile phones, Personal Digital Assistants (PDAs etc.)). Java ME was formerly
known as Java 2 Platform, Micro Edition (J2ME).
Java Platform, Enterprise Edition (Java EE) is a computing platform, extending Java SE
with specifications for enterprise features such as distributed computing and web
services, Java EE was formerly known as Java 2 Platform, Enterprise Edition (J2EE).
.
.
.
1Object Oriented Programming using Java - 1 An Introduction to Java
.
The latest release/version of the Java programming language is Java SE 16. Java 16
contains new features, enhancements and bug fixes to improve efficiency to develop
and run Java programs.
Java programming language is mainly used to create these following four types of
applications:
1. Web Applications: Web application is an application which creates a dynamic
page and runs on the side of server. At present time, technologies that are used to
create web application in Java programming language are Struts, Spring, Servlet,
Hibernate, JSP, JSF, etc.
2. Mobile Applications: Mobile application refers to application that is developed for
mobile devices. At present time, platforms that are used to develop mobile
applications in Java programming language are Java ME and Android,
3. Standalone Applications: Desktop applications and Window based applications
are the other name of standalone applications, We need to install this traditional
software on every machine. Media player and antivirus are the examples of these
applications. At current time, for the creation of standalone applications AWT and
swing are used in Java programming language.
4. Enterprise Applications: Enterprise applications are those applications which are
distributed in nature. Banking application is the example of enterprise
applications. It gives programmer the advantage of high level security, clustering
and load balancing. At present time, EJB is used in Java programming language for
developing enterprise applications.
OBJECT ORIENTED PROGRAMMING CONCEPTS
.
Java is an Object Oriented Programming (OOP) language. The fundamental idea
behind an OOP is to combine both data and the functions that operate on the data into
asingle unit i.e., an object.
An approach that provides a way of modularizing programs by creating partitioned
memory area for both data and functions that can be used as templates for creating
copies of such modules on demand is known as Object Oriented Programming (OOP).
The popular object-oriented languages include Simula, Ada, Smalltalk, Java, C#, PHP,
Python, C++ and so on,
Java is a high-level programming language designed and developed to accommodate
object-oriented concepts like polymorphism, class, object, abstraction, encapsulation,
inheritance, message passing and so on.
Features of OOP:
1. OOP emphasis on data rather than procedure.
2. OOP follows bottom-up approach in program design.
3. Programs in OOP are divided into objects.
4, Objects in OOP may communicate with each other through functions.
12Object Oriented Programming using Java - 1 An Introduction to Java
5. Objects in OOP are characterized by functions or data structure that operates on
data.
6. In OOP new data and functions can be easily added whenever necessary.
7. In OOP data is hidden and cannot be accessed by external functions.
« The fundamental concepts of object oriented programming are explained below:
1. Classes:
* A class is a blueprint/template from which individual objects are created. A class is a
collection of objects of similar type of objects.
« Classes are user defined data type. Once, class has been defined, we can create any
number of object belonging to that class.
* A class consists of data and methods. A method is a collection of statements that are
group together to perform an operation.
¢ Following example define class Person with data and methods:
class Person
f
String name; //data
int age;
void accept( String n, int a) // methods
{
name=n;
age=a;
Wi
void display()
{
System. out. print1n(“Name="+name) ;
System. out.print1n(“Age="+age) ;
}
»
2, Objects:
* Objects are basic run time entities in OOP. Objects may represent a real-world entity
such as a book, a chair, a place, a bank account, a table ete.
« An object is an instance of a class. Objects are variables of class because it is created by
the class data type.
« An object has two general characteristics namely, state and behavior. An object's
state represents what the object knows. The state is maintained in one or more
variables associated with the object.
© An object's behavior represents what the object can do. The behavior is implemented
by defined methods that the object can access. Simply put, a method is a named block
of code that does something.
13Object Oriented Programming using Java - I An Introduction to Java
« An object has identity which differentiates one object from the other. Object name is
used to identify the object. Hence, name itself is an identity.
* Objects are generally used to access members (data and methods) of class.
For example: Person p = new Person();. In this statement 'p' is an object of Person
class.
* Fig. 1.1 shows example of class and objects. Fig. 1.1 shows class Car has objects like
Audi, Nissan, Volvo.
class objects
‘pT
fla uy
(oo) | a mm
SPT
Audi Nissan Volvo
1.1: Example of Class and Object
Comparison between Object and Class:
Object is an instance of a class. Class is a blueprint or template from
which objects are created.
2. Object is a real world entity such as a | Class is a group of similar type
pen, a laptop, a keyboard, etc, objects,
3. Object is a physical entity. Class is a logical entity.
4. Mainly Object is created through new | Class is declared using class keyword
keyword like like class Student{ ... }
Student _si=new Student();
5. Object is created many times as per | Class is declared or created once.
requirement.
6. Object allocates memory when it is | Class doesn't allocated memory when
created. itis created.
3, Data Abstraction:
« Data abstraction refers to act of representing essential features without including
background details or explanations.
* Classes use the concept of abstraction. They encapsulate all essential properties of
objects that they are to be created.
«Since, the class used the concept of data abstraction they are known as Abstract Data
Types (ADT).
4. Data Encapsulation:
* Data encapsulation means wrapping or binding of data and functions into a single
unit.
14Object Oriented Programming using Java +I An Introduction to Java
«The data is not accessible to the outside world and only functions which are wrapped
in the class can access it.
* Thus, insulation of data from direct access from program is called data hiding.
Inheritance:
* Inheritance is the process by which object of one class can acquire the properties of
the objects of another class.
« Inheritance means one class of object inherits the data and behavior (methods) from
another class.
« The old class is referred as a base class (parent class or super class) and new class is
called as derived class (child class or sub class). The new class has combined features
of both the classes.
«Fig. 1.2 shows a class called Vehicle, which has two subclasses called Car and Truck.
The Vehicle class is the superclass of Car and Truck.
Fig. 1.2: Classes Car and Truck inherits from the class Vehicle
6. Polymorphism:
* Polymorphism is the ability to take more than one form. In short, polymorphism is the
ability of an object to take on many forms.
* The most common use of polymorphism in OOP occurs when a parent class reference
is used to refer to a child class object.
« For example: An operation may demonstrate different behavior in different instance.
The behavior depends upon the type of data used in the operation. As addition of two
integer numbers give addition while addition of two strings give concatenation.
. Dynamic Binding:
« Binding refers to the linking of a procedure call to the procedure definition (code) to
be executed in response to the call.
« Binding is classified as static binding and dynamic binding as explained below:
@ Static Binding means that the code associated with given procedure call is known
at compile time.
Gi) Dynamic Binding means that the code associated with given procedure call is not
known until the time of the call at run time. Dynamic binding associated with
polymorphism and inheritance.
8. Message Passing:
* In OOP objects are communicate with each other through message passing. A message
for an object is a request for execution of a method.
1sObject Oriented Programming using Java - An Introduction to Java
* Message passing involves specifying the name of object, the name of the method and
the information to be sent.
* For example: p.accept(“abc”,18); here, p is an object of Person class, accept is
message and abc, 18 are arguments is information.
Advantages of OOP:
1 Software is easily developed for complex problems.
Using OOP, software reuse is enhanced.
Using OOP, software maintenance cost can be reduced.
Modularity is achieved using OOP.
Software has improved performance.
Software quality is improved.
7. Data access is restricted providing better data security.
Disadvantages of OOP:
1. OOP requires intensive testing procedures.
2. Solving a problem using OOP approach consumes more time than the time taken
by structured.
PVN
* In 1990, Sun Micro Systems Inc. (US) was conceived a project to develop software for
consumer electronic devices that could be controlled by a remote. This project was
called Stealth Project but later its name was changed to Green Project.
* Java was developed at Sun Microsystems in 1991, by a team (also called as Green
Team) comprising James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike
Sheridan as its members to initiated the project (Green Project) to develop a language
for digital devices such as set-top boxes, televisions, etc. in the early 1990s.
* Java was originally designed for small and embedded systems in digital appliances
such as television and set top boxes, etc.
But later it suits internet programming and now it is used in mobile applications,
enterprise applications, windows applications, etc.
* James Gosling is known as the father of Java. At first James Gosling called it
"Greentalk” but later on the project was developed as green project's part and it was
named "Oak",
* It was later termed as Java. Sun Microsystems released the first public implementation
as Java 1.0 in 1996,
* The Java software was released as a development kit. The first two versions were
named JDK 1,0 and JDK 1.1.
* In 1998, while releasing the next version, Sun Microsystems changed the
nomenclature from Java Development Kit (JDK) to Software Development Kit (SDK).
Also, it added "2" to the name. The released version of Java was called Java 2 SDK 1.2.
16Object Oriented Programming using Java -1 An Introduction to Java
* With every version, Java became stronger and stronger. At the time of writing of the
book, Java had come up with its version SE 8 in April 2014.
+ Table 1.1 illustrates the various versions released of Java language, till date.
Table 1.1: History of Java
Version Release Date Major Additions
JDK 1.0 January 1996 Initial release
JDK1.1 February 1997 Inner classes, JavaBeans JDBC, RMI
J2SE 1.2 December 1998 Swing and Collections Framework
J2SE.1.3 May 2000 HotSpot JVM, RMI, JavaSound
J2SE 1.4 February 2002 Regular expressions, Java Web Start
J2SE 5.0 September 2004 Generics, autoboxing, enumeration
J2SE SE 6 December 2006 Database manager and many new facilities,
JAVASE7 | July 2011 New invoked dynamic bytecode under JSR-292
JAVASE8 | March 2014 JDK Enhancement Proposals (JEPS).
JAVASE9 | September, 2017 Fix some open issues and concerns, and to
refine some critical technical questions.
JAVA SE 10 | March, 2018 Security fixes and critical bug fixes.
JAVA SE 11 | September, 2018 Open for bug fixes. It offers LTS( Long Term
Support).
JAVA SE 12 | March, 2019 Add new features, bug fixes.
JAVA SE 13 | September, 2019 Text block, bug fixes and security.
JAVA SE 14 | March, 2020 Pattern matching for instanceof record,
Security and Bug fixes,
JavaSE15 | September, 2020 Security and bug fixes.
JavaSE16 | March, 2021 Timezone database update, bug fixes, and
security updates.
FEATURES OR BUZZWORDS OF JAVA
* There are various features of Java as given in Fig. 1.3. Each feature of Java will tell us
about how and why Java is a powerful object-oriented programming language.
7Object Oriented Programmin, Java -1 An Introduction to Java
Fig. 1.3: Features/Buzzwords of Java
Let us see Java features in detail:
1. Simple: Java is a simple language. There are various concepts that make the Java
as a simple language. Java is designed to he easy to learn. Programs in Java are
easy to write and debug because Java does not use the pointers, preprocessor
header files, operator overloading etc.
2. Object-oriented: Java is object-oriented language like C++, Python etc. Almost
everything in Java language is an object based. All program code and data in Java
reside within objects and classes. Java language can be easily extended since it is
based on the Object model.
3. Platform Independent: Java Language is platform independent language.
A platform is the hardware or software environment in which a program runs.
Java code/program can be run on multiple platforms like Windows, Linux, Sun
Solaris, and Mac Os etc.
4. Interpreted: Java is an interpreted language, i.e. programs run directly from the
source code. Java interpreter can execute Java bytecode directly on any computer
machine. This machine should have the interpreter ported on it. Generally, we
know that interpreters are very slow. But in Java, the interpreter uses the
compiled code called bytecode, so it is faster than typical interpreter.
There are compilers available for bytecode called JIT i.e. Just-In Time compilers.
These compilers are used to compile the bytecode into native code. So they
improve the speed.
18Object Oriented Programming using Java - I An Introduction to Java
5. Distributed: Java facilitates the building of distributed application by a collection
of classes for use in networked applications. Java is designed for the distributed
environment of the Internet.
6. Dynamic: Java language is capable of dynamically linking in new class libraries,
methods and objects. Because Java is interpreted, Java is an extremely dynamic
language, at runtime, the Java environment can extends itself by linking in classes
that may be located on remote servers on a network, (for example; the Internet).
7. Robust: Java is a robust language because it provides many safeguards to ensure
reliable code. Java does not allow pointer which avoids security problem. There is
no concept of reference variable. This eliminates the possibility of overwriting
memory and corrupting data. Automatic garbage collection eliminates memory
leaks,
8. Secure: Java is aimed to be used in networked or distributed environments. Java
does not allocate direct pointer to memory, this makes it impossible to accidentally
reference memory that belongs to other program.
9. Architecture Neutral: Java compiler generates an architecture-neutral object file
format which makes the compiled code to be executable on many processors, with
the presence of Java runtime system.
10. Portable: Being architectural-neutral and having no implementation dependent
aspects of the specification makes Java portable. Java code is portable. It was an
important design goal of Java that it be portable so that as new architectures (due
to hardware, operating system, or both) are developed, the Java environment
could be ported to them.
Additionally, Java is portable because the compiler itself is written in Java.
Compiler in Java is written in ANSI C with a clean portability boundary which is a
POSIX subset.
11. Multithreading: A thread is like a separate program, executing concurrently.
Multithreaded means handling multiple tasks simultaneously. With Java's
multithreaded feature it is possible to write programs that can perform many tasks
simultaneously. This design feature allows developers to construct smoothly
running interactive applications.
12, High Performance: With the use of Just-In-Time (JIT) compilers, Java enables high
performance.
13. Interactive: Java is called as interactive because code of Java supports CGI
(Common Gateway Interface) and GUI (Graphical User Interface) programs.
JAVA ENVIRONMENT
* Java environment includes a large number of development tools [part of system
known as JDK (Java Development Kit)] and hundreds of classes and methods [(part of
the JSL (Java Standard Library)].
19Object Oriented Programming using Java - 1 ‘An Introduction to Java
The Java Development Kit (JDK) is a software development environment which is used
to develop Java applications.
JSL also known as the Application Programming Interface (API). The JSL (or API)
includes hundreds of classes and methods grouped into several functional packages.
Fig. 1.4 depicts a typical Java environment,
Fig. 1.4: Java Environment
The Java source code is stored as a ‘java’ file and is compiled by Java compiler (javac)
to get an executable ‘.class’ file. Java compiler translates source code into byte code
instructions (.class file). The byte code is executed by JVM (Java Virtual Machine)
which is a runtime environment for Java.
A ClassLoader is use to download the executable file, the bytecode (instruction set for
the Java Virtual Machine (JVM)) of which is then interpreted, a process which makes
the file understood by the underlying processor which executes the file instructions.
The interpretation process carried by interpreter which reads the instructions and
then executes the instructions, step by step. After the bytecode of a class is loaded by
the class loader, it has to be inspected by the Java bytecode verifier.
Byte code verifier verifies the bytecode so that the code does not make any sort of
disturbance for the interpreter. Byte code verifier checks the code fragments for illegal
codes that can violate access right to the object.
Java uses the Just-In-Time (JIT) compiler with the interpreter, enables all the
frequently used class files to be compiled into native code just the once, rather than
each time they are used.
The API provided by the language is constantly available to the JVM, and the entire
package, excepting the compiler that generates the .class file from the java file, is
referred to as the Java Runtime Environment (JRE).
JRE is an acronym for Java Runtime Environment is a set of software tools which are
used for developing Java applications. It is used to provide the runtime environment.
1.10Object Oriented Programming using Java -1 ‘An Introduction to Java
Java Virtual Machine (JVM):
A JVM is a virtual machine that enables a computer to run Java programs as well as
programs written in other languages that are also compiled to Java bytecode.
A Java virtual machine’s main job is to load class files and execute the byte codes they
contain.
Fig. 1.5 shows the Java virtual machine contains a class loader, which loads class files
from both the program and the Java API.
Only those class files from the Java API that are actually needed by a running program
are loaded into the virtual machine. The byte codes are executed in an execution
engine.
The execution engine of JVM is responsible for executing the instructions contained in
the methods of loaded classes.
When a Java virtual machine runs a program, it needs memory to store many things,
including byte codes and other information it extracts from loaded class files, objects
the program instantiates, parameters to methods, return values, local variables, and
intermediate results of computations.
The Java virtual machine organizes the memory it needs to execute a program into
several runtime data areas.
Runtime data areas
Fig. 1.5: Java Virtual Machine (JVM)
Java API:
The Java API is set of runtime libraries that give us a standard way to access the
system resources of a host computer.
141Object Oriented Programming usit
An Introduction to Java
* When we run a Java program, the virtual machine loads the Java API class files that
are referred to by the programs class files.
* The combination of all loaded class files (from your program and from the Java API)
and any loaded dynamic libraries (containing native methods) constitute the full
program executed by the Java virtual machine.
Java methods (Java API)
Native methods (Dynamic libran
Fig. 1.6: Java API
* The class files of the Java API are inherently specific to the host platform. To access the
native resources of the host, the Java API calls native methods.
« As we can see in Fig. 1.6, the class files of the Java API invoke native methods so your
Java program doesn’t have to.
« In this manner, the Java API’s class files provide a Java program with a standard,
platform-independent interface to the underlying host.
+ Precisely because the Java virtual machine and Java API are implemented specifically
for each particular host platform, Java programs themselves can be platform
independent.
* The Java Standard Library (JSL or APD includes hundreds of classes and methods
grouped into several functional packages.
* Most commonly used packages are given in following Table 1.2.
Table 1.2: Common Packages of JSL
Package ‘Name of
Name Package
java.lang Language A collection of classes and methods required for
Support Package | implementing basic features of Java.
Description
java.util Utility Package _| A collection of classes to provide utility functions
such as date and time.
contd.
LizObject Oriented Programming using Java -1 An Introduction to Java
java.io Input/Output A collection of classes for input and output
Package manipulation.
java.net Networking A collection of classes for communicating with other
Package computers.
java.awt AWT Package An Abstract Window Toolkit which contains classes
and methods for implementing Graphical User
Interface.
java.applet | Applet Package Set of classes to create Java Applets.
«Program is a set of instructions that tell a computer what to do. A Java program is a
collection or set of objects that communicate via invoking each other’s methods.
¢ It is necessary to know the exact structure of the Java program. Java program
structure means - the way (or general format) to write a Java program.
¢ Fig. 1.7 shows basic structure of a Java program.
_ Documentation Section } Suggested
Package Statement
Import Statement
Interface Statement al
Class Definition
main method Class.
{
Main method definition Esseruel
Fig. 1,7: Structure of Java Program
° Fig. 1.7 shows following sections of a Java Program.
1, Documentation Section: This section is not compiled by java compiler. This
section is a set of comment lines giving the name of the program, the author and
the other details, which the programmer would like to, refer.
Package Statement: Package statement is used by programmer whenever they
‘want to create a package. Package is collection of classes and interface. In Java
files, the first statement allowed is a package statement which declares a package
name and informs the compiler that the classes defined here belong to this
package. Package statement an optional statement. Package statement is written
as, package PackageName; For example: package employee;
N
113Object Oriented Programming using Java -1 An Introduction to Java
3. Import Statement: Import statement is used to include java packages or user
defined packages in to the program. For example, to include java input output
package user can use the statement, import java.io.*;.
4, Interface Statement: An interface is like class used to group of related methods.
Interfaces are used when we want to implement or implement multiple
inheritance.
5. Class Definition: Classes are an essential part of any Java program. To write a
Java program, we first define classes. A Java program may contain many/multiple
class definitions. As Java is pure object oriented so each and every code will comes
under a class, which consist of main() method. Every program in Java will have at
least one class with the main() method.
6. main Method Class: This is essential part of the Java program which is a starting
point for JVM to start execution of a Java program. Without the mainQ method,
JVM will not execute the program. In simple words, the execution of a java
program starts from main() method.
The steps in writing a Java program are illustrated in Fig. 1.8,
Step1
Write Source Codes
Step2
‘Compile (Build)
Java Bytecodes (.class)
IDK or 3rd-party APIs
‘and Native Libraries. Step 3
Input Run (Execute)
Output
Fig. 1.8: Steps for create a Java Program
Fig. 1.8 shows following steps for creation of a Java program.
Step 1: Write the source codes (java) using a programming text editor or an IDE
(Integrated Development Environment) like Eclipse, NetBeans etc.
Step 2: Compile the source codes (.java) into Java portable bytecodes (.class) using the
JDK compiler ("javac"), IDE compiles the source codes automatically while
they are entered,
Step 3: Run the compiled bytecodes (.class) with the input to produce the desired
output, using the Java Runtime ("java").
114Object Oriented Programming using Java +I ‘An Introduction to Java
* To write Java programs, we will need a text editor. A text editor is a type of program
used for editing plain text files. The text editors for Java includes Notepad++, jEdit,
Editplus and so on.
* There are even more sophisticated IDEs (Integrated Development Environment)
available in the market like Eclipse, Netbeans, JCreator and so on,
First Java Program: (ee
public class HelloJavaWorld
{
18]}
public static void main(String[] args)
{
System, out. print ("Hello") ;
System. out.printIn("Java world!");
}
Output:
Hello
Java World!
Explanation of above Program:
o The class keyword is used to declare a class in Java. In the above program,
‘HelloWorld' defines the class name in Java, Every class definition in Java begins
with an opening brace { and ends with closing brace }.
o The public is a keyword and a access specifier indicates that the class member can
be accessed from anywhere in the program.
o The static keyword indicates that this method can be invoked simply by using the
name of the class without creating any class-object.
o The void keyword specifies that this method will not return any type of data.
The mainQ method is the main entry point of the program, to start execution. First
of all JVM calls the main method of a class and start execution. JVM (ava Virtual
Machine) is responsible for running Java programs.
o args is a string array that takes values from Java command line. It's index starts
from '0'. We can access values by writing args[0], args[1] etc.
o The print word sends the information into a buffer. This buffer is not flushed till a
newline or end-of-line character is send. So it prints output on one line and cursor
is blinking on the same line.
o The printIn( function prints the output to the standard output stream i.e. monitor.
o The out word represents the standard output stream (monitor).
Compiling the Program: oa)
o To compile the HelloWorld program, execute the compiler, javac specifying the
name of the source file on the command line. This is shown below:
$ javac HelloJavaWorld.java
115Object Oriented Programming using Java =I ‘An Introduction to Java
co Javac compiler creates a file named 'HelloJavaWorld.class' which contains the byte
code version of the program. It is an intermediate representation of the program.
Executing the Program:
o To actually run the program we must use the Java application launcher called
‘java’. This is shown below:
$ java HelloJavaWorld
Java platform includes a tool set for development of Java programs. These tools run in
a command-line window and provide basic functionality.
« The Java Development Kit (JDK) comes with a set of tools that are used for developing
and running Java program. JDK has a collection of tools for Java program development
as shown in Table 1.3.
Table 1.3: Java Development Tools
Tool Description
javac The java compiler that translates javacode to bytecode file which java
interpreter can understand.
java java is a Java application launcher. It launches a java application by
starting Java Runtime Environment, loading a specified class and
invoking that class’s main method to run the program.
appletviewer | Enables us to run java applets. Normally applets are the programs
those can be embedded in a web page and run in web browser. This
is very useful tool which gives the same effect but on console.
javadoc Creates HTML formatted documentation from Java source code files.
jdb Java debugger that helps us in finding errors in Java programs.
jar Java achieve file, creates a zip/jar file.
javah Produces header files for use with native methods.
javap Java dissembler which enables us to convert bytecode files into a
program description.
GA javac
* javac is the primary java compiler included in the JDK. javac is used to compile Java
source into bytecode.
«The java source code is written in files with extension java. In order to execute the
program, these files need to be compiled in .class files. javac translates or converts the
“ java" file to a “.class" file.
Syntax: $ javac filename. java
Example: $ javac HelloJavaWorld. java
116Object Oriented Programming using Java -1 An Introduction to Java
* Fig. 1.9 illustrates the operation of the Java compiler.
Compiler Referenced
options classes
Program
outputresults
java Source files class files (Bytecode)
Fig. 1.9: The operation of the Java compiler (javac)
GB java
* In Java language, java is launcher for Java program. java is the interpreter which
launches a java program,
* The java interpreter executes the bytecode files produced by the Java compiler. It
translates the Java bytecode into the code that can be understood by the Operating
System (OS).
Syntax: $ java filename
Example: $ java HelloJavaWorld
* Fig, 1.10 shows java interpreter process.
Win 32 Solaris Mac
Fig. 1.10: Java interpreter process
HBB Appletviewer
* An Applet is a Java program that runs in a Web browser. Java AppletViewer is the
utility which runs Applets outside the web browser.
* AppletViewer is a standard JDK tool which has following facilities:
1. To create dynamic applet, and
2. To view java applet.
* A Java applet is a Java program designed to be included in a HyperText Markup
Language (HTML) document and run inside a web browser.
117Object Oriented Programming using Java - 1 An Introduction to Java
* Fig. 1.11 shows steps in Applet.
Wats HTML Document,
J t Bytecod
Will Bare lava Applet Bytecode
1. User selects HTML page with embedded applet.
2. Java bytecode is downloaded by browser and
‘executed by integrated bytecode interpreter.
jdb
* The Java debugger (jdb) is a tool for Java classes to debug a program in command line.
jdb helps us to find and fix bugs in Java language programs.
* Debugging is a technical procedure to find and remove bugs or defects in a program
and get expected results,
« A debugger allows us to step through every aspect of a code, inspect all the elements,
and remove errors, if any.
« jdb helps in detecting and fixing bugs in a Java program using Java Debug Interface
(DI). Fig. 1.12 shows the role of jdb in JDK.
* jdb contains three units i.e., Java Virtual Machine Tool Interface (VM TD, Java Debug
Wiring Pool (JDWP) and Java Debugger Interface (JDI) as shown in Fig. 1.12.
Java Development Kit Debuggee JVM
(JDK)
Debugger JVM (idb)
Fig. 1.12: Architecture of jdb
118Object Oriented Programming using Java - 1 An Introduction to Java
ia javadoc es E))
The javadoc tool is a document generator tool in Java for generating standard
documentation in HTML format.
* javadoc is a tool which comes with JDK and it is used for generating Java code
documentation in HTML format from Java source code, which requires
documentation in a predefined format.
* The javadoc is a documentation generator created by Sun Microsystems for the Java
language generating API documentation in HTML format from Java source code.
* The documentation comments (also called doc comments) starts with a slash and two
asterisks (/**) and it is terminated with one asterisk and a slash (*/). That is why they
appear as:
BF
af
* Tags are keywords recognized by javadoc which define the type of information that
follows, We can use javadoc tags in the doc comments. The syntax of a tag is, @ tag.
© Alljavadoc tags start with @ character.
o Each tag must start on a new line.
o Various tags are used to provide the heading.
o All tags should follow the order.
* Some common pre-defined tags for javadoc are given below:
1. @author [author name]: Identifies author(s) of a class or interface.
2. @version [version]: Version info of a class or interface.
3. @param [argument name] [argument description]: Describes an argument of
method or constructor.
4, @return [description of return]: Describes data returned by method
(unnecessary for constructors and void methods),
5. @exception [exception thrown] [exception description]: Describes exception
thrown by method.
1.6.6 javap (Gras E3]
« The javap tool of Java is used to get the information of any class. In Java the javap
command disassembles a class file.
* The javap command (also known as the Java Disassembler) disassembles one or more
class files.
* The javap tool disassemblies compiled Java files and prints out a representation of the
Java program. This may be helpful when the original source code is no longer
available on a system.
119Object Oriented Programming using Java -1 An Introduction to Java
+ The javap command displays information about the fields, constructors and methods
present in a class file.
Syntax: javap class_name
Example:
class Simple
t
public static void main(String args[])
{
System.out.println("hello java");
}
}
* Now let use the javap tool to disassemble the class file.
javap simple
Output: Compiled from "java"
class Simple
{
Simple ();
public static void main(java.lang.String[]);
)
* It's output depends on the options used. The important options of javap tools are as
follows:
Option Description
-help Print the help message.
a Prints line number and local variable.
< Disassembles the code.
Ss Prints internal type signature.
-sysinfo Shows system info (path, size, date, MDS hash).
-constants Shows static final constants.
-version Shows version information.
EH jar
* jar stands for Java archive. The jar tool is a java application that combines multiple
files into a single JAR archive file.
jar is a general-purpose archiving and compression tool based on ZIP and the ZLIB
compression format.
« However, jar was designed mainly to facilitate the packaging of java applets or
applications into a single archive.
Syntax: jar option destinationfile_list
1.20Object Oriented Programming using Java +1
An Introduction to Java
Where, destination file_list can have more than one file separated by space, ?, & and *
are the wildcard characters used with filenames.
Creates new or empty -jar file.
Created jar file named on command line.
Lists the table of contents.
Generates additional output.
x Extract the file on command line.
0 (digit zero) | _ No compression and store the file.
Example: jar cf first.jar
jar tf newjar.jar
BASIC CONCEPTS IN JAVA
In this section we will study basic concepts in Java like variables, data types, constants,
comments, identifiers and so on.
second.class
7a Comments
Comments are non-executable statements and are ignored by the Java compiler. The
comment increases the readability of the programs.
Comments help the person/user reading the code better understand the intent and
functionality of the program.
All characters available inside any comment are ignored by Java compiler. Java
language provides three styles or types of comments as given in following table:
/* Multiline comment */
// Single line comment
Multi line comments start with /* and ends
with */. Any text between /* and */ will be
ignored by Java compiler.
Example: /* Welcome to Nirali Prakashan.
A text book publishing firm */
Single-line comments start with two forward
slashes (//). Any text between // and the end of
the line is ignored by Java (will not be
executed).
Example: // Welcome to Nirali Prakashan.
contd. ...
121Object Oriented Programming using Java - 1
An Introduction to Java
3.
/** Documentation comment */
A doc comment is an ordinary multiline
comment that begins with /** and ends with */.
A doc comment appears immediately before a
class, interface, method, or field definition and
contains documentation for that class,
interface, method, or field. The documentation
can include simple HTML formatting tags and
other special keywords that provide additional
information,
Example:
/** Welcome to Nirali Prakashan.
A text book publishing firm */
Program 1.1: Program for Java comment.
public class CommentsDemoExample
/** This is a Documentation Comment. */
public static void main(String args[])
{
/* This is a Multi line Comment */
System. out.printIn("Hello World"); // This is a Single Live Comment.
Output:
Hello World
Data Types
Data types specify the different values that can be stored in the variable. Variables are
nothing but reserved memory locations to store values.
The type of value that a variable can hold is called as data type. The main purpose of
data types in Java is to determine what kind of value we can store into the variable.
The data type of a variable determines the value which a variable can contain and the
operations that can be performed on it. Every variable must have a data type.
Java has a rich set of data types. The data types in Java are shown in Fig. 1.13.
1.22Object Oriented Programming using Java -I An Introduction to Java
Fig. 1.13: Data Types in Java
* Java supports two kinds of data types namely, primitive data types or predefined data
types and non-primitive data types or reference data types.
1. Primitive Data Types: (CET)
«Primitive data types also known as built-in data types, are the fundamental data types
provided by a programming language.
« In Java language primitive data types include integer, floating point, character and
Boolean.
«The eight primitive data types supported by the java programming language are:
@ byte: The byte data type is an 8-bit signed two’s complement integer. It has a
maximum value of -128 and a maximum value of 127 (inclusive).
(ii) short: The short data type is 16-bit singed two’s complement integer. It has a
maximum value of -32,768 and a maximum value of 32,767 (inclusive).
(iii) int: The int data type is 32-bit singed two’s complement integer. It has a
maximum value of -2,147,483,648 and a maximum value of 2,147,483,647
(inclusive).
(iv) long: The long data type is 64-bit singed two’s complement integer. It has a
maximum value of -9,223,372,036,854,775,808 and a maximum value of
9,223,372,036,854,775,808 (inclusive). Use this data type when you need a range
of values wider than those provided by int.
(v) float: The float data type is a single-precision 32-byte IEEE 754 Floating point.
(vi) double: The float data type is a double-precision 64-byte IEEE 754 Floating point.
(vii) boolean: The Boolean data type has only two possible values namely, True and
False. Use this data type for simple flags that track true/false conditions.
(viii)char: The char data type is single 16-bit Unicode character. It has a maximum
value of ‘\(u0000"(or 0) and a maximum value of ‘uffff(or 65,535 inclusive).
1.23Object Oriented Programming using Java - 1 An Introduction to Java
* Table 1.4 shows data types with their size in bytes.
Table 1.4: Data types with their size
Sr. No. Data Type Size in Bytes
4 byte a
2. short 2
3. int 4
4, long 8
5. float 4
6. double 8
a char Z
2. Non-Primitive Data Types:
* Non-primitive data types also known as reference data types are derived from the
primitive data types.
«In Java, derived data types include classes, interface, arrays etc.
1.7.3 Tokens —__
« The smallest individual units in a Java program are called tokens. Java tokens are
smallest elements of a Java program which are identified by the compiler.
* Tokens in Java include variables, constants, identifiers, keywords, literals, operators,
special characters, separators and so on.
Java Identifiers:
« Identifiers are used for naming classes, methods, variables, objects, labels, packages
and interfaces in a program.
* In Java, there are several rules for identifiers. They are as follows:
1, Allidentifiers should begin with a letter (A to Z or a to z), currency character ($) or
an underscore (_).
2. After the first character, identifiers can have any combination of characters.
3. A keyword cannot be used as an identifier.
4, Identifiers are case sensitive so Amar and amar has different meaning.
«Examples of legal identifiers: age, $salary, _phone, _1D.
«Examples of illegal identifiers: 123abc, -salary.
Constants in Java:
* In java constants, refer to fixed values that do not change during the execution of a
program.
1.24Object Oriented Programming using Java -1 ‘An Introduction to Java
L
Constants are also called as literals which has fixed values in a program. Java supports
several types of constants below:
Integer Constants:
An integer constant means the sequence of digits. There are three types of integers:
@ Decimal Integer: Decimal integers consists of a set of digits, 0 through 9
preceded by an optional minus sign.
For example: 325, -978, 45673.
Embedded spaces, commas and non-digits characters are not allowed between
digits.
For example: 15 78, $657-, #47 is illegal number,
(ii) Octal Integer: An octal integer constant consists of any combination of digits
from the set 0 through 7, with al leading 0.
For example: 027, @, 0231, 0341.
(iii), Hexadecimal Integer: A sequence of digits preceded by OX or OX is considered a
hexadecimal integer (hex integer). They may also include alphabet A through F or
a through f. A letter A through F represents the number 1 through 15.
For example: 0X4, 9X15, @xabed.
Real Constant:
Integers numbers are insufficient to represents quantities that vary continuously,
such as distance heights, temperature, prices, and so on.
Numbers having fractional parts like 17.548 represents these quantities. Such
numbers are called real (or floating point) constants.
For example: 1.9783, @ 0047
The real number constant can comprise of four parts namely, whole number, decimal
point, fractional part and exponent part.
These numbers are shown in decimal notation, having a whole number followed by a
decimal point and the fractional part, which is an integer.
For example: @.035, 111.98.
A real number may also be expressed as in exponential (or scientific) notation. For
example, the value 215.65 may be written as 2.1565e2 in exponential notation. e2
means multiply by 1042. ,
For example: @.65e4, 15e-5, 2.6e+6 56.E4.
Character Constant:
A single character constant or character constant contains a single character enclosed
within a pair of single quote marks.
Examples are ‘7’, ‘A’, °*?, * 7.
The character constant ‘7’ is not the same as the number 7. The last constant is blank
space.
String Constant:
A string constant is a sequence of character enclosed between double quotes in which
the character may be alphabets, digits, special characters and blank spaces.
For example: “WELCOME”, “@june”, “abhishek”, “!NIDHI!”
125Object Oriented Programming using Java - I ‘An Introduction to Java
Backslash Characters:
* The backslash character constant are used with output statements for getting more
effects like tab, new line, single quote etc. Java support some special backslash
character constants.
e A backslah (\) precedes that character to represent it as an escape sequence. For
example, the character n represents the alphabet n, where \n represents a new line
character. Here, \n is an escape sequence that uses an available printable character n.
* A list of such backslash character constant is given following table. Each one of them
represents one character, although they consist of two character. These characters
combinations are known as escape sequences.
Backslash Character Constant Meaning
\b Back space
\t Form feed
\n New line
\c Carriage return
\t Horizontal tab
¥ Single quote
Ne Double quote
\ Backslash
Keywords:
° There are certain words that have a standard, predefined, special meaning in Java.
They are called as keywords or reversed words and they can be used only for their
intended purposes.
* These reserved words may not be used as constant or variable or any other identifier
names. The keywords in Java are formed using lower case letters only.
* Keywords in Java are given below:
abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while
1.26Object Oriented Programming using Java - I An Introduction to Java
Separator:
« In java separators are symbols used to show the separated code, they describe
function of our code.
«Table 1.5 shows various type of separators used in Java.
Table 1.5: Type of Separators
Name Use
0 Parameter in method definition, containing statements for
conditions, etc.
i} Used for define a code for method and classes.
t] Used for declaration of array.
3 Used to show that separate statement.
: Used to show the separation in identifier in variable declaration.
Used to show the separate package name from sub-packages and
classes, separate variable and method from reference variable.
Operators in Java:
«© Operator is a symbol that represents some operation that can be performed on data.
Operators perform some specific operations using the operands and operator.
«For example, answer can be given using expression 4 + 5 is equal to 9. Here, 4 and 5
are called operands and + is called operator.
« The operator that uses a single operand is called a unary operator and that which uses
two operands is known as a binary operator. A ternary operator uses three operands.
* Java provides a rich set of operators to manipulate variables. We can divide all the
Java operators into the various groups Arithmetic Operators, Relational Operators,
Bitwise Operators, Logical Operators, and Assignment Operators and so on.
1. Arithmetic Operators:
« Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra.
« Table 1.6 lists the arithmetic operators, Assume integer variable A holds
10 and variable B holds 20.
Table 1.6: Arithmetic Operators
on Operator Description Example
1. |+ (Addition Adds values on either side of the | A +B will give 30
Operator) operator.
2. |- (Subtraction | Subtracts right hand operand from left | A - B will give - 10
Operator) hand operand,
contd. ...
1.27Object Oriented Programming using Java -1 An Introduction to Java
3, | ™* (Multiplication | Multiplies values on either side of the | A“ B will give 200
Operator) operator.
4. |/ (Division Divides left hand operand by right | B/A will give 2
Operator) hand operand.
5. | % (Modulus Divides left hand operand by right | B % A will giveO
Operator) hand operand and returns remainder.
6. | ++ (ncrement Increases the value of operand by 1. B++ gives 21
Operator)
7, |-- (@ecrement | Decreases the value of operand by 1. B-- gives 19
Operator)
Program 1.2: Program for arithmetic operators.
public class Test
i
public static void main(String args[])
{
int a = 10;
int b = 20;
int ¢ = 25;
int d= 25;
System.out.printIn("a + + (a+b) );
System.out.println("a - + (a-b) );
System. out.printin("a * + (a *b) );
system.out.println("b / + (b / a) );
system.out.printin("b % + (b % a) );
System. out.println("c % + (c%a) );
System. out. println("at+ + (att) )5
system.out.printin("b-- = "+ (a--) )3
// Check the difference in d++ and ++d
System. out.print1n("d++ "+ (dt) )5
System.out.printin("#+d = "+ (+d) )3
1.28Object Oriented Programming using Java -1
An Introduction to Java
2. Relational Operators:
* Relational operators are also called as comparison operators used for comparing
values of two variables,
* Table 1.7 shows relational operators supported by Java language. Assume variable A
holds 10 and variable B holds 20.
Table 1.7: Relational Operators
Operator Example
== Checks if the values of two operands are equal or | (A = = B) is not
(Equal to | not, if yes then condition becomes true. true.
Operator)
2. ‘=(Not | Checks if the values of two operands are equal or | (A != B) is true.
Equal to | not, if values are not equal then condition becomes
Operator) | true.
& > Checks if the value of left operand is greater than | (A > B) is not
(Greater | the value of right operand, if yes then condition | true.
than becomes true.
Operator)
4, <(Less | Checks if the value of left operand is less than the | (A < B) is true.
than value of right operand, if yes then condition
Operator) | becomes true.
5. >=( Checks if the value of left operand is greater than | (A >= B) is not
Greater | or equal to the value of right operand, if yes then | true,
than or | condition becomes true.
Equal to
Operator)
6. <=(Less | Checks if the value of left operand is less than or | (A <= B) is true.
thanor | equal to the value of right operand, if yes then
Equal to | condition becomes true.
Operator)
Program 1.3: Program for relational operators.
public class Sample
{
public static void main(String args[])
{
int a
int b
int ¢
int d
10;
= 20;
253
25;
system.out.printin("a < b=" + (a b = "+ (c > b) )s
1.29Object Oriented Programming using Java -1 ‘An Introduction to Java
system.out.printIn("c <= d=" + (c <= d) );
system.out.printIn("c >= d= "+ (c >= d) );
system.out.printIn("c == d= "+ (c==d) );
}
:
Output:
¢
3. Logical Operators:
* When we want to form compound conditions by combining two or more relations,
then we can use logical operators.
Logical operators are used to check whether an expression is True or False. Table 1.8
lists the logical operators. Assume Boolean variables A holds True and variable B holds
False.
Table Logical Operators
a Operator Description Example
a && (Logical AND Operator) If both the operands are non-| (A && B) is
zero, then the condition | False.
becomes true.
2. || (Logical OR Operator) If any of the two operands are | (A || B) is True,
non-zero, then the condition
becomes true.
x ! (Logical NOT Operator) Use to reverses the logical]! (A && B) is
state of its operand. If a | True.
condition is true then Logical
NOT operator will make false.
Program 1.4: Program for logical operators.
public class Sample
= true
public static void main(String args[])
int a = 60;
int b = 20;
int ¢ = 255
int d= 25;
System,out.printin("(a > b &
System.out.printIn("(a < b &
System.out.println("(a d) = true
(a< d) = false
(ac d) true
Va > Right shift AND | C >>=2 is sameasC =C>>2
Assignment Operat
3. Bitwise AND Assignment | C &=2 is sameasC=C&2
Operator.
10. ne Bitwise Exclusive OR AND | C A= 2is same as C= C42
Assignment Operator.
2. = Bitwise Inclusive OR AND | C |= 2is same as C=C | 2
Assignment Operator.
131