KEMBAR78
OOP Using JAVA Unit-I | PDF | Object Oriented Programming | Class (Computer Programming)
0% found this document useful (0 votes)
9 views63 pages

OOP Using JAVA Unit-I

The document provides an overview of Object-Oriented Programming (OOP) concepts using Java, detailing its principles such as classes, objects, inheritance, polymorphism, and encapsulation. It compares procedural and object-oriented programming paradigms, highlighting the advantages of OOP, including code reusability and data security. Additionally, it covers the structure of a Java program, its history, and key features that make Java a versatile programming language.

Uploaded by

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

OOP Using JAVA Unit-I

The document provides an overview of Object-Oriented Programming (OOP) concepts using Java, detailing its principles such as classes, objects, inheritance, polymorphism, and encapsulation. It compares procedural and object-oriented programming paradigms, highlighting the advantages of OOP, including code reusability and data security. Additionally, it covers the structure of a Java program, its history, and key features that make Java a versatile programming language.

Uploaded by

Varaprasad Mella
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

OOP using JAVA

UNIT-I

OOPs Concepts and Java Programming: Introduction to Object-Oriented


concepts, procedural and object-oriented programming paradigm

Java programming: An Overview of Java, Java Environment, Data types,


Variables, constants, scope and life time of variables, operators, type conversion
and casting, Accepting Input from the Keyboard, Reading Input with
Java.util.Scanner Class, Displaying Output with System.out.printf(), Displaying
Formatted Output with String.format(), Control Statements

Definition of Object-Oriented Programming

Object-Oriented Programming is 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.

Object-Oriented Paradigm

 The major objective of Object-Oriented approach is to eliminate some of the


flaws encountered in the Procedural approach.
 OOP allows us to decompose a problem into a number of entities called
Objects.
 The combination of data and methods make up an object.
 The combination of data and methods make up an object.

Some of the features of Object-Oriented Paradigm are as follows:

 Programs are divided into what are known as Objects.


 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through methods.
 New data and methods can be easily added whenever necessary.
 Data Structures are designed such that they characterize the objects.
 Follows bottom-up approach in program design.

1
OOP using JAVA

Fig. Organization of data and methods in OOP

Object Oriented Programming Concepts (OR) Object Oriented Programming


Principles:

When we represent the data in Object Oriented Programming language we


get the security. Examples of Object Oriented Programming Languages are LISP,
ADA, ALGOL, SMALLTALK, OBJECT COBAL, OBJECT PASCAL, Cpp,
JAVA, DOT NET, etc. In order to say any language is an Object Oriented
Programming Language it has to satisfy the following principles of OOPs.

OOP Principles

 Class
 Object
 Data Abstraction and Data Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing

Class:

“A Class is a way of binding the data and associated methods in a single


unit”. Any JAVA program if we want to develop then that should be developed
with respective to Class only i.e., without Class there is no JAVA program.

2
OOP using JAVA

The entire set of data and code of an object can be made a user defined data
type using the concept of a class. In fact Objects are treated as variables of the type
Class. Once a Class has been defined, we can create any number of objects
belonging to that Class.

Class Diagram for defining a class:

Syntax for defining a class:

Class <clsname>
{
Variable Declaration;
Methods Definition;
}
Object:

Objects are the basic runtime entities in an object-oriented system. In order


to store the data for the data members of the class, we must create an object.

Definitions of an Object

1. Instance (instance is a mechanism of allocating sufficient amount of memory


space for data members of a class) of a class is known as an object.
2. Class variable is known as an object.
3. Blue print of a class is known as an Object.
4. Real world entities are called as Objects.

3
OOP using JAVA

The following figure is the representation of an object

Fig: Representation of an Object

Data Abstraction and Data Encapsulation:

Data Abstraction:

 Abstraction and Encapsulation in Java are two important Object oriented


programming concept and they are completely different to each other.

 Data abstraction is a mechanism of retrieving the essential details without


dealing with background details.

 Abstraction represent taking out the behavior from how exactly it’s
implemented.

Data Encapsulation:

 Encapsulation means hiding details of implementation from outside world so


that when things change nobody gets affected.

 The wrapping up of data and methods into a single unit is known as


Encapsulation. The data is not accessible to the outside world and only those
methods, which are wrapped in the class, can access it.

Inheritance:

Inheritance is the process of by which objects of one class acquire the


properties of objects of another class.

Inheritance supports the concept of hierarchical classification. The concept


of inheritance provides the idea of reusability. This means that we can add
4
OOP using JAVA

additional features to an existing class without modifying it. The following is an


example for the inheritance concept.

Polymorphism:

Polymorphism means the ability to take more than one form. For example,
an operation may exhibit different behavior in different instances. The behavior
depends upon the type of data used in the operation. The following is an example
for polymorphism concept.

Dynamic Binding:

Binding refers to the linking of a procedure call to the code to be executed in


response to the call. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at runtime.

5
OOP using JAVA

Message passing:

The Object Oriented Program consists of a set of objects that communicate


with each other. Objects communicate with one another by sending and receiving
information. It involves the following basic steps.

 Creating classes that define objects and their behavior.


 Creating objects from class definitions.
 Establishing communication among objects.

Exchanging the data between multiple objects is known as Message Passing.


Objects communicate with one another by sending and receiving information much
the same way as people pass message to one another.
Message passing involves specifying the name of the object, the name of the
method (message) and the information to be sent. Example
employee.salary (name);

object message information

Objects have a life cycle. They can be created and destroyed. Communication with
an object is feasible as long as it is alive.

Benefits of OOP:

OOP offers several benefits to the program designer and the user. The
principal advantages are:

 Through inheritance, we can eliminate redundant code and extend the use of
existing classes.

 We can build programs from standard working modules that communicate


with one another rather than, having to start writing the code from scratch.
This leads to saving of development time and higher productivity.

6
OOP using JAVA

 The principle of data hiding helps the programmers to built secure program.

 It is possible to have multiple objects to coexist without any interference.

 It is easy to partition the work in a project based on objects.

 Object-oriented systems can be easily upgraded from small to large system.

 Message passing technique for communication between objects makes the


interface descriptions with external system much simpler.

 Software complexity can be easily managed.

Applications of OOP

The following are some of areas of Object Oriented Programming

 Real-time systems
 Simulation and modeling
 Object oriented databases
 Hypertext, hypermedia and expert text.
 AI and expert systems.
 Neural networks and parallel programming.
 Decision support and office automation systems.

*************************************************************
Procedural and Object-Oriented Programming paradigm
Below are some of the differences between procedural and object-oriented
programming:

Procedural Oriented Programming Object-Oriented Programming


1. In procedural programming, the 1. In object-oriented programming, the
program is divided into small parts program is divided into small parts
called functions. called objects.
2. Procedural programming follows 2. Object-oriented programming follows
a top-down approach. a bottom-up approach.
3. There is no access specifier in 3.Object-oriented programming has access
procedural programming. specifiers like private, public, protected, etc.

7
OOP using JAVA

4. Adding new data and functions is not 4. Adding new data and function is easy.
easy.
5. Procedural programming does not 5. Object-oriented programming provides
have any proper way of hiding data so it data hiding so it is more secure.
is less secure.
6. In procedural programming, 6. Overloading is possible in object-oriented
overloading is not possible. programming.
7. In procedural programming, there is 7. In object-oriented programming, the
no concept of data hiding and concept of data hiding and inheritance is
inheritance. used.
8. In procedural programming, the 8. In object-oriented programming, data is
function is more important than the data. more important than function.
9. Procedural programming is based on 9. Object-oriented programming is based on
the unreal world. the real world.
10. Procedural programming is used for 10. Object-oriented programming is used
designing medium-sized programs. for designing large and complex programs.
11. Procedural programming uses the 11. Object-oriented programming uses the
concept of procedure abstraction. concept of data abstraction.
12.Code reusability absent in procedural 12. Code reusability present in object-
programming, oriented programming.
Examples: C, FORTRAN, Pascal, Examples: C++, Java, Python, C#, etc.
Basic, etc.

*******************************************************************

8
OOP using JAVA

An Overview of Java

Overview of Java Language

Java is a general purpose, Object-Oriented programming language. We can


develop two types programs. They are

 Stand- Alone applications


 Web-Applications

Structure of a java program

To write a java program, we first define classes and then put them together.
A Java program may contain one or more sections as shown in below.

9
OOP using JAVA

Documentation Section

The documentation section contains a set of comment lines giving the name
of the program, the author and other details.

There are three types of comments in java – single line, multi line, and Java
documentation.

 Single line Comments

These comments are for making a single line as a comment. These


comments start with double slash symbol (//) and after this, whatever is written
till the end of the line is taken as a comment.

Example: // This is my comment of one line

 Multi line comments

These comments are used for representing several lines as comments.


These comments start with /* and end with */. In between /* and */ , whatever
is written is treated as a comment.

Example:

/* This is a first line


This is second line */
 Java Documentation Comments

These comments start with /** and end with */. These comments are used
to provide description for every feature in a java program.

Package Statement

The first statement allowed in a java file is a package statement. This


statement declares a package name and informs the compiler that the classes
defined here belong to this package. The package statement is optional.

Example

package student;
10
OOP using JAVA

Import Statement

The next statement after a package statement may be a number of import


statements. This is similar to the #include statement in C. Using import
statements; we can access to classes, that are part of other named packages.

Example: import student.test;

This statement instructs the interpreter to load the test class contained in the
package student.

Interface Statements

An interface statement is like a class, but includes a group of method


declarations. This is also an optional section and is used only when we wish to
implement the multiple inheritance features in the program.

Class Definitions

A Java program may contain multiple class definitions. Classes are the
primary and essentials of a Java program.

Main Method Class

Since every Java stand-alone program requires a main method as its starting
point, this class is the essential part of a java program. A simple java program may
contain only this part. The main method creates objects of various classes and
establishes communications between them. On reaching the end of main, the
program terminates and the control passes back to the operating system.

Simple java program

The following is a simple java program

//Sample.java

Class Sample

Public static void main (String args [])

11
OOP using JAVA

System.out.println(“Welcome to Java Programming Language……”);

The above simple java program contains the following..

Class Declaration

The first line

class Sample

declares a class, which is an object oriented construct. class is a keyword


used to declare a new class definition. Sample indicates the name of the class.

Opening Brace

Every class definition in java begins with an opening brace “{“ and ends
with a matching closing brace “ } ”.

The Main Line

The third line

public static void main(String args[])

defines a method named main. Every Java application program must include
the main () method. This is the starting point of the interpreter to begin the
execution of the program.

A Java program can have any number of classes but only one of them must include
a main method to initiate the execution.

This line indicates a number of keywords, public , static and void

public: The keyword public is an access specifier that declares the main
method is accessible to all other classes.

12
OOP using JAVA

static Static is reserved keyword which means that a method is accessible


and usable even though no objects of the class exist.
void This keyword states that the main method does not return any value.

The Output line

The executable statement in this program is,

System.out.println(“ Welcome to Java Programming Language……”);

a. System: It is name of Java utility class.


b. out: It is an object which belongs to System class.
c. println(): It is utility method name which is used to send any String to
console.

Welcome to Java Programming Language…….

The method println() always append a new line character to the end of the string.

*******************************************************************

History of JAVA

13
OOP using JAVA

1. Java is a programming language used to develop distributed applications.


2. Java was developed at SUN Micro System INC USA by a person called
James Gosling and others in the year of 1990.
3. Originally Sun Micro System is one of the Academic University (Stanford
University of Networks) developed “rules” for development of java and
those rules are programmatically implemented by Java Soft INC USA. Java
Soft is one of the software divisions of Sun Micro System.
4. The original name of java language is OAK (Scientifically it is a tree name).
5. The software OAK was not fulfilling or not solving industry problems or
demands.
6. Hence the software OAK was revised in the year of 1995 and released to the
industry on the name of Java.
JAVA released to the market in three categories J2SE (JAVA 2 Standard
Edition), J2EE (JAVA 2 Enterprise Edition) and J2ME (JAVA 2 Micro/Mobile
Edition).
 J2SE is basically used for developing client side applications/programs.
 J2EE is used for developing server side applications/programs.
 J2ME is used for developing mobile or wireless applications.
*****************************************************************
Features or Buzzwords of JAVA

The following are the features of the JAVA language.


1. Compiled and Interpreted.
2. Simple and Small.
3. Platform Independent.
4. Architectural Neutral.
5. Portable.
6. Multithreaded.
7. Distributed.
8. Robust
9. Secure.
10.High Performance.
11.Interpreted.
12.Dynamic.
13.Object Oriented and these are explained below.

14
OOP using JAVA

Compiled and Interpreted


Usually a computer language is either compiled or interpreted. Java
combines both these approaches thus Java is a two-stage system.
First, Java compiler translates source code into what is known as byte code
instructions. Byte codes are not machine instructions.
In the second stage, the Java interpreter generates machine code that can be
directly executed by the system.
Thus Java is both compiled and interpreted language.

Simple and Small


Java is small and simple language. For example, Java does not use pointers,
preprocessor header files, goto statement and many others. It also eliminates
operator overloading and multiple inheritance.

**Platform Independent
A program or technology is said to be platform independent if and only if
which can run on all available operating systems.
The language JAVA will have a common data types and the common
memory spaces on all operating systems. The JAVA software contains the special
programs which converts the format of one operating system to another format of
other operating system. Hence JAVA language is treated as platform independent
language.

**Architectural Neutral
A language or technology is said to be architectural neutral which can run on
any available processors in the real world. The languages like C, C++ are treated as
architectural dependent. The language Java can run on any of the processor
irrespective of their architecture and vendor.

Portable
A portable language is one which can run on all operating systems and on all
processors irrespective of their architectures and providers. The languages like C,
C++ are treated as non-portable languages whereas the language Java is called
Portable language.
Portability= Platform Independent + Architectural Neutral
15
OOP using JAVA

Multithreaded
Multithreaded means handling multiple tasks simultaneously. Java supports
multithreaded programs. This means that we need not wait for the application to
finish one task before beginning another. For example, we can listen to an audio
clip while scrolling a page and at the same time download an applet from a remote
computer.

Distributed
Java is designed as a distributed language for creating the applications on
networks. It has the ability to share both data and programs. Java programs can
open and access remote objects on Internet as easily as they can do in a local
system.

Robust
Java is one of the Robusted programming language. Since java programming
language effectively addresses the run time errors. In Java programming runtime
errors are known as Exceptions.
The languages like C, C++ are treated as week programming languages (Not
Robust), since they are unable to deal with runtime errors. Runtime errors are
occurred when we enter invalid input.
Note:
Compile time errors are occurring when the programmer is not following
syntax rules of the programming language.

Secure
Java is one of the most secured programming languages. To provide the
security to our java real time applications, we need not to write our own security
code. Since java library (API) contains readily available security programs for
protecting confidential information from unauthorized users.
Hence java is one of the powerful secured programming languages.

High Performance
Java is one of the High-Performance programming languages because of the
following reasons.
 Automatic memory management (Garbage Collector).
16
OOP using JAVA

 Magic of byte code (Execution of the java application is very faster


compared to other programming language applications).
 According to industry expert’s java programmer performance is high
because java programming environment is free from pointers. Hence
development of an application takes less time.

Interpreted
In the older versions of java, compilation phase is so fast than the
interpretation phase. It was the industry complaint on older versions of java.
In the newer versions of java, to speed up the interpretation phase, sun micro
system had developed JIT (Just in Time) compiler and added to JVM.
In the current versions of java interpretation phase is so faster than
compilation phase. Hence java is one of the highly interpreted programming
languages.

Dynamic
In any programming language memory can be allocated in two ways. They
are
 Static Memory Allocation
 Dynamic Memory Allocation
Java programming does not follow the static memory allocation but it always
follows dynamic memory allocation.
Dynamic memory allocation is one in which memory will be allocated at run
time. In java programming to allocate the memory space dynamically we use an
operator called “new”. “new” operator is known as dynamic memory allocation
operator.

Object Oriented
Any programming language that satisfies all the principles of OOP is called
as an Object-Oriented Programming Language. The Java language satisfies all the
principles of OOP. Hence it is called an Object-Oriented Programming Language.
Java is a true object-oriented language. Almost everything in java is an object.

******************************************************************

17
OOP using JAVA

Java Environment:
Java Environment includes a large number of development tools and
hundreds of classes and methods. The development tools are part of the system
known as Java Development Kit (JDK) and the classes and methods are part of the
Java Standard Library (JSL), also known as the Application Programming
Interface (API).

Java Development Kit (JDK):


The Java Development Kit comes with a collection of tools that are used for
developing and running Java programs. They include
Applet viewer: Enables us to run Java applets.
Java (Java Interpreter): Java Interpreter, which runs applets and applications by
reading and interpreting byte code files.
Javac (Java Compiler): The Java Compiler, which translates Java source code to
bytecode files that the interpreter can understand.
Javadoc (for creating HTML documents): Creates HTML- format
documentation from Java source code files.
javah (for C header files): Produces header files for use with native methods.
Javap (Java disassembles): Which enables us to convert byte code files into a
program description.
Jdb (Java debugger) : Which helps us to find errors in our programs.

18
OOP using JAVA

Application Programming Interface:


The Java Standard Library includes hundreds of classes and methods
grouped into several functional packages. Most commonly used packages are
 Language Support Package: A collection of classes and methods required
for implementing basic features of java.
 Utility Package: A collection of classes to provide utility functions such as
date and time functions.
 Input/output Package: A collection of classes required for input/output
manipulations.
 Networking Package: A collection of classes for communicating with other
computers via Internet.
 AWT Package: The Abstract Window Tool Kit package contain classes that
implements platform independent graphical user interface.
 Applet Package: This includes a set of classes that allows us to create Java
apllets.

Java Runtime Environment:


The Java Runtime Environment (JRE) facilitates the execution of java
programs. It primarily comprises of the following:
 Java Virtual Machine (JVM): It is a program that interprets the
intermediate Java byte code and generates the desired output.
 Runtime class libraries: These are a set of core class libraries that are
required for the execution of java programs.
 User interface tool kit: AWT and Swing are example of toolkits that
support varied input methods for the users to interact with the application
program.
 Deployment technologies: JRE comprises the following key deployment
technologies.
 Java plug-in: Enables the execution of a Java applet on the browser.
 Java Web Start: Enables remote-deployment of an application.

*****************************************************************

19
OOP using JAVA

Data types in Java

“Data types are used for representing the data in main memory of the computer.”

In java we have eight data types which are grouped in four groups. They
are Integer category Data types, Floating point data types, Character category
data types, Boolean category data types.

Integer category data types


They are used to represent integer data. This category of data type
contains four data types. Which are given in the following table

Data type Size Range


byte 1 +127 to -128
short 2 +32767 to -32768
int 4 +2147483647 to -2147483648
long 8

20
OOP using JAVA

Whatever the data type we should not exceed the predefined value

Float category data types


Float category data types are used for representing the data in the form of
scale, precision i.e., these category data types are used for representing float
values.
This category contains two data types they are given in the following table.

Data type size Range


Float 4 +2147483647 to -2147483648
Double 8

Whenever we take any decimal constant directly in a Java program it is by


default treated as highest data type in float category i.e., double.

Character category data types

 A character is an identifier which is enclosed within single quotes.


 In JAVA to represent character data, we use a data type called char.
This data type takes two bytes since it follows UNICODE character
set.
char
.

C/Cpp JAVA

1 byte 2 bytes

English 18 International languages

ASCII UNICODE

21
OOP using JAVA

Data type Size Range


char 2 +32767 to -32767

UNICODE character set is one which contains all the characters which are
available in 18 international languages and it contains 65536 characters.

Boolean category data types

 Boolean category data types is used for representing logical values i.e.,
TRUE or FALSE values.
 To represent logical values we use a keyword called Boolean.
 This data type takes o bytes of memory space.

NOTE: All keywords in JAVA must be written in small letters only.

*****************************************************************

Constants & Variables


Constants in java

A constant is an identifier which takes a fixed value during the program


execution same rules we should follow while declaring the constants of variables.

Types of constants:

We have 4 types of constants. which are given below.

1. Integer constants: A constants which is formed with integers including with


zero, which can take positive and negative.

Ex: 123,-12, 0, 22

2. Floating point constants: A constants which is formed with real values


including fractional part apart from integers

22
OOP using JAVA

Ex: 12.5,-12.0, 3.14, 6.1

The real numbers are formed with two parts known as mantissa and
exponent where mantissa is either decimal or integer and exponent is an integer
either positive (or) negative

Ex: 26.506, 26.506+e-2, 26.506+e3

3) Character constants: A Character constant is a single character i.e., enclosed


with a pair of single code

Ex: ‘a’, ’8’, ’4’,’_’,’c’

Every character is having integer values known as ASCII (American


standard code for information interchange) values

4) String constants: A group of characters combined with the a pair of double


codes is known as string constants.

Ex: “BVRICE”,” INDIA

******************************************************************

Variables in java

A Variables is an identifier this takes different values at different times


during the program execution. In java language a variable can be declared as
follows

Syntax: Data type variable name:

Example:

 int marks, total;


 float average;
 char x;
 long area;
 double volume;

While declaring the variable we should follow some precautions. Which are
given below.

23
OOP using JAVA

Rules for defining variables

1) They must begin with a character including underscore.


2) They should not start with digits.
3) They can take any of length.
4) Keywords are not used in the variable names.
5) Upper case and lower case are distinct i.e., sum & SUM are not the same.

Scope and life time of variables

These are of three types


 Instance variables: These are declared and created when the objects are
instantiated. They take different values for each object.
 Class variables: These are present within the class.
 Local variables: are the variables that are present within the method.

******************************************************************

Operators in Java

Java supports a rich set of operators. An Operator is a symbol that tells the
computer to perform certain mathematical or logical manipulations. Operators are
used in programs to manipulate data and variables.

Java Operators are classified into a number of related categories as shown in


below.

 Arithmetic Operators
 Relational Operators
 Logical Operators.
24
OOP using JAVA

 Assignment Operators
 Increment and Decrement Operators.
 Conditional Operators.
 Bitwise Operators
 Special Operators

Arithmetic Operators

Java provides all the basic arithmetic operators. They are listed below. These
can be used to construct the mathematical expressions. The operators work the
same way as they do in any other languages. These can operate on any built-in
numeric data type of java.

Operator Meaning
+ Addition or unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulo Division
Arithmetic Operators are used as follows

a+b, a-b, a*b, a/b, a%b

where a and b are may be variables or constants and are known as operands.

Relational Operators

We often compare two quantities, and depending on their relation, take


certain decisions. These comparisons can be done with the help of relational
operators. The list of operators as shown in below

Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to

25
OOP using JAVA

A simple relational expression contains only one relational operator and is of


the following form.

exp1 reloperator exp2

here exp1 and exp2 are any two arithmetic expressions, which may be
simple constants, variables or combination of them. When arithmetic expressions
are used on either side of a relational operator, the arithmetic expressions will be
evaluated first and then the results compared. That is, arithmetic operators have a
higher priority over relational operators.

Logical Operators

In addition to relational operators, java has three logical operators listed


below in the table.

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
The logical operators && and || are used when we want form compound
conditions by combining two or more relations.

Example: (a>b && b<c)

An expression of this kind which combines two or more relational


expressions is termed as a logical expression or a compound relational expression.
Like the simple relational expressions, a logical expression also yields a value of
true or false, according to the truth table of AND and OR.

exp1 exp2 exp1 && exp2 exp1 || exp2


True True True True
True False False True
False True False True
False False False False

26
OOP using JAVA

Assignment Operators

Assignment Operators are used to assign the value of an expression to a


variable. We have seen the usual assignment operator, ‘=’. In addition to that java
has a set of short hand assignment operators which are used in the form

var op=exp

Where var is a variable, exp is an expression and op is a java binary


operator. The operator ‘op=’ is known as shorthand assignment operator.

Example:

x+=y+4

This actually means,

x=x+(y+4).

There are three advantages using the shorthand operators, they are

 What appears on the left hand side need not be repeated and therefore it
becomes easier to write.
 The statement is more concise and easier to read.
 Use of shorthand operator’s result in a more efficient code.

Increment and Decrement Operators

Java has two very useful operators called the increment (++) and decrement
(--) operators. The operator ++ adds one to the operand while the operator –
subtracts one. Both are unary operators.

Example: ++a, a++, --a, a--.

++a is called as pre-increment and a++ is called post increment.

Though ++a and a++ mean the same thing when they form statements
independently, they behave differently when they are used in expressions on the
right-hand side of an assignment statement.

Example:

27
OOP using JAVA

a=5;

b=++a;

the result is a=6, b=6;

a=5;

b=a++;

the result is a=6, b=5;

A prefix operator fist adds one to the operand and then the result is assigned to the
variable on left. On the other hand, a post fix operator first assigns the value to the
variable on left and then increments the operand.

The ?:Operator (or )conditional operator (or )ternary operator:

The character pair ?: is a ternary operator available in java. This operator is


used to construct conditional expressions of the form

exp1 ? exp2 : exp3

where exp1, exp2 and exp3 are all expressions.

Here first the expression exp1 was evaluated, if it is true, exp2 is evaluated. If it is
false, exp3 is evaluated. However, it has to be clearly understood that among both
exp2 and exp3, only one of it is evaluated at any time.

Example:

a=10;

b=15;

x=(a>b) ? a : b;

In this example, x will be assigned the value b.

28
OOP using JAVA

Bitwise operators:

These operators are act on individual bits(0 and 1) of the operands. They act on
only integer datatypes i.e. byte, short, int, long. There are different types of
operators, they are:

1. Bitwise Complement operator(~)


2. Bitwise and operator (&)
3. Bitwise or operator (|)
4. Bitwise xor operator (^)
5. Bitwise left shift operator (<<)
6. Bitwise right shift operator (>>)

Bitwise Complement operator ( ~)

This operator gives the complement form of a given number. This operator symbol
is ~ which is pronounced as tilde.

Complement form of a positive number can be obtained by changing 0’s as 1’s and
visa versa.

Bitwise and operator (&):

This operator performs and operations on the individual bits of the number. The
symbol for the operator is (&) which is called ampersand.

If int X=10, Y=11 then find the value of X&Y.


X Y X&Y

X=10=0000 1010 1 1 1

Y=11=0000 1011 1 0 0

------------------------- 0 1 0

X&Y=00001010 0 0 0

From the above table, by multiply the bits, we get X&Y=0000 1010.

29
OOP using JAVA

Bitwise or operator (|)

This operator performs or operations on the individual bits of the number. The
symbol for the operator is (|) which is called pipe.

If int X=10, Y=11 then find the value of X|Y.


X Y X|Y

1 1 1
X=10=0000 1010
1 0 1
Y=11=0000 1011
0 1 1
-------------------------
0 0 0
X|Y=00001011

From the above table, by adding the bits, we get X|Y=0000 1011.

Bitwise xor operator (^)

This operator performs (exclusive or) xor operations on the individual bits of the
number. The symbol for the operator is (^) which is called cap,carat.

If int X=10, Y=11 then find the value of X^Y.


X Y X^Y

1 1 0
X=10=0000 1010
1 0 1
Y=11=0000 1011
0 1 1
-------------------------
0 0 0
X^Y=00000001

From the above table, when odd numbers of 1’s are there, we can get a 1 in the
output.

Bitwise left shift operator (<<)

The left shift operator will shift the bits towards left for the given number of times.

30
OOP using JAVA

int a=2<<1;

Let’s take the binary representation of 2 assuming int is 1 byte for simplicity.

Position 7 6 5 4 3 2 1 0

Bits 0 0 0 0 0 0 1 0

Now shifting the bits towards left for 1 time, will give the following result

Position 7 6 5 4 3 2 1 0

Bits 0 0 0 0 0 1 0 0

Now the result in decimal is 4. You can also note that, 0 is added as padding the in
the position 0.

Bitwise right shift operator (>>)

The right shift operator will shift the bits towards right for the given number of
times.

int a=8>>1;

Let’s take the binary representation of 8 assuming int is 1 byte for simplicity.

Position 7 6 5 4 3 2 1 0

Bits 0 0 0 0 1 0 0 0

Now shifting the bits towards right for 1 time, will give the following result

Position 7 6 5 4 3 2 1 0

Bits 0 0 0 0 0 1 0 0

Now the result in decimal is 4. Right shifting 1 time, is equivalent to dividing the
value by 2.

31
OOP using JAVA

Write a java program using bitwise operators:

class bits
{
public static void main(String[] args)
{
byte x,y;
x=10;
y=11;
System.out.println("~x=" +(~x));
System.out.println("x&y="+(x&y));
System.out.println("x|y="+(x|y));
System.out.println("x^y="+(x^y));
System.out.println("x<<2="+(x<<2));
System.out.println("~x>>2"+(x>>2));
}
}
OUTPUT:

Special Operators:

a. Instanceof Operator
b. Dot(.) Operator

Instanceof Operator

In java instanceof operator is used to test whether an object is an instance


of the specified type (class or subclass or interface).

This operator returns “true” if an object given at the left hand side is an instance of
the class given at right hand side. Otherwise, it returns “false”.

32
OOP using JAVA

class person
{
String name;
int age;
void talk()
{
System.out.println("my name is"+ name);
System.out.println("my age is"+ age);
}
}

class Demo1

{
public static void main(String[] args)
{
person raju=new person();
raju.name="ravindra";
raju.age=29;
raju.talk();
boolean k=raju instanceof person;
System.out.println(k);
}
}

Output:

Dot operator

This operator is used to access the variables and methods of a class.

Example 1

Syntax: Object name. variable name;

33
OOP using JAVA

raju.name;

Here we are accessing the variable “name” of the “raju” object

Example 2

Syntax:

Object name. method name();

raju.talk();

Here we are accessing the method “talk()” of the “raju” object.

This operator also can be used to access classes, packages etc.

****************************************************************

Type Casting in Java

In Java, type casting is a method or process that converts one data type into
another data type in both ways manually and automatically. The automatic
conversion is done by the compiler and manual conversion performed by the
programmer. In this section, we will discuss type casting and its types with proper
examples.

Type Casting

Convert a value from one data type to another data type is known as type casting.

Types of Type Casting

There are three types of type casting:

34
OOP using JAVA

1. Widening Type Casting or Implicit casting


2. Narrowing Type Casting or Explicit casting
3. Boolean Casting

1. Widening Type Casting

Converting a lower data type into a higher one is called widening type
casting. It is also known as implicit conversion or casting down. It is done
automatically. It is safe because there is no chance to lose data. It takes place
when:

o Both data types must be compatible with each other.


o The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double

For example, the conversion between numeric data type to char or Boolean is not
done automatically. Also, the char and Boolean data types are not compatible with
each other. Let's see an example.

Example:

class Implicitcast

public static void main(String args[])

int x=10; // occupies 4 bytes

double y=x; // occupies 8 bytes

System.out.println("===Implicit Typecasting===");

System.out.println("Before Conversion:x="+x);

35
OOP using JAVA

System.out.println("After Conversion:y="+y);

Output:

2. Narrowing Type Casting:

Converting a higher data type into a lower one is called narrowing type
casting. It is also known as explicit conversion or casting up. It is done
manually by the programmer. If we do not perform casting then the compiler
reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte
Example:
class Explicitcast
{
public static void main(String args[])
{
double x=10.5;
int y=(int)x;
System.out.println("====Explicit Typecasting====");
System.out.println("Before Conversion:x="+x);
System.out.println("After Conversion:y="+y);
}
}

36
OOP using JAVA

Output:

Boolean casting:
A boolean value cannot be assigned to any other data type. Except boolean,
all the remaining 7 data types can be assigned to one another either implicitly or
explicitly; but boolean cannot. We say, boolean is incompatible for conversion.
Maximum we can assign a boolean value to another boolean.
Following raises error.

boolean x=true;
int y=x; // error
boolean x=true;
int y=(int)x; // error

******************************************************************

Reading Input with Java.util.Scanner Class

The Scanner class in Java is part of the java.util package and provides a simple
way to read input from various sources, such as keyboard input, files, or streams. It
is commonly used for reading user input from the console.

Reading Different Types of Input:

o Strings: nextLine(), next()


o Integers: nextInt()
o Doubles: nextDouble()
o Booleans: nextBoolean()

37
OOP using JAVA

o Other Primitive Types: nextFloat(), nextLong(), nextShort(),


nextByte()

Program:

import java.util.*;

class Addition

public static void main(String args[])

Scanner sc=new Scanner(System.in);

int a,b,c;

System.out.println("Enter the First number:");

a=sc.nextInt();

System.out.println("Enter the Second number:");

b=sc.nextInt();

c=a+b;

System.out.println("After Addition="+c);

Output:

38
OOP using JAVA

Accepting Input from the Keyboard

The DataInputStream class in Java is part of the java.io package and is used to read
primitive data types from an input stream in a portable way. It provides methods to
read Java primitive types (like int, float, double, etc.) from an underlying input
stream.

Key Features

1. Reading Primitive Data Types:


o DataInputStream allows reading data in a binary format, which can be
more efficient and consistent across different platforms compared to
reading text.
2. Supports Various Data Types:
o The class provides methods for reading int, float, double, long, short,
byte, char, and boolean values.

Program:

import java.io.*;

class Student

public static void main(String args[])throws IOException

DataInputStream d=new DataInputStream(System.in);

int num;

39
OOP using JAVA

String name;

System.out.println("Enter the Student Number:");

num=Integer.parseInt(d.readLine());

System.out.println("Enter the Student Name:");

name=d.readLine();

System.out.println("The Student Details are");

System.out.println("Student Number:"+num);

System.out.println("Student Name:"+name);

Output:

******************************************************************

Displaying Output with System.out.printf()

System.out.printf() in Java is a method used to format and print text to the console
with precise control over the output's appearance. It allows you to create formatted
strings with placeholders that are replaced by values provided as arguments. This
method is part of the PrintStream class, which is used to output data to the console.

40
OOP using JAVA

Basic Syntax

System.out.printf(String format, Object... args);

 format: A format string that specifies how the output should be formatted. It
includes text and format specifiers.
 args: Arguments that are inserted into the format specifiers in the format
string.

Format Specifiers

Format specifiers are placeholders in the format string that are replaced with the
corresponding arguments. Each specifier starts with a % symbol and ends with a
conversion character.

Here are some common format specifiers:

 %s: String
 %d: Decimal integer
 %f: Floating-point number
 %x: Hexadecimal integer
 %o: Octal integer
 %c: Character
 %b: Boolean

Program:

public class Main {

public static void main(String[] args) {

String name = "Alice";

int age = 30;


41
OOP using JAVA

double salary = 12345.6789;

System.out.printf("Name: %s%n", name);

System.out.printf("Age: %d%n", age);

System.out.printf("Salary: %.2f%n", salary);

Output:

Displaying Formatted Output with String.format()

String.format() in Java is a method used to create a formatted string. It provides


functionality similar to System.out.printf(), but instead of printing the formatted
string directly to the console, it returns the formatted string. This allows you to use
the formatted string in various contexts, such as storing it in a variable or including
it in other strings.

Syntax

String.format(String format, Object... args);

 format: A format string that specifies how the output should be formatted. It
contains text and format specifiers.
 args: The arguments to be formatted according to the format string.

42
OOP using JAVA

Format Specifiers

The format specifiers used in String.format() are the same as those used in
System.out.printf(). Here are some common ones:

 %s: String
 %d: Decimal integer
 %f: Floating-point number
 %x: Hexadecimal integer
 %o: Octal integer
 %c: Character
 %b: Boolean

Program:

public class Main {

public static void main(String[] args) {

String name = "Alice";

int age = 30;

double salary = 12345.6789;

// Create a formatted string

String formattedString = String.format("Name: %s%nAge: %d%nSalary:


%.2f", name, age, salary);

// Print the formatted string

System.out.println(formattedString);

43
OOP using JAVA

Output:

**********************************************************
Control Statements:

Decision Making and Branching

Introduction:

Generally a program executes its statements from beginning to end. When a


program breaks the sequential flow and jumps to another part of the code, it is
called selection or branching.

When the branching is based on a particular condition, it is known as


conditional branching.

If branching takes place without any condition, it is known as unconditional


branching.
44
OOP using JAVA

Decision Making :

An if statement tests a particular condition. If the condition is true then


statement or set of statements is executed. Otherwise (if the condition evaluates to
false) then it will come out of loop.

 Simple if statement
 If-else statement
 Nested if-else statement
 else if ladder

Simple If Statement: The syntax of the if statement is shown below

Syntax: if(expression)

{
Statements;
}
Statement-x;

Example Program

File Name : SimpleIfDemo1.java


class SimpleIfDemo1
{
public static void main(String args[])
{
int test=10;
if(test>5)
{

45
OOP using JAVA

System.out.println("Success");
}
System.out.println("Executed successfully");
}
}

Output

if-else statement:

Syntax:

if(condition)

Statement block 1;

else

Statement block2;

Statement-n

If the condition is true ,then the statement block1 and then statement-n and so on
executed in order. If the condition is false, statement block2 and then statement-n

46
OOP using JAVA

and so no are executed in order. In either case, only one of the statement statement
block1 or statement block2 is executed but not both.

Write a program to illustrate if else statement:

public class si
{

public static void main(String args[])


{
int a = 10;
int b = 20;
if(a>b)
{
System.out.println("a is greater than b");
}
else
{
System.out.println("b is less than a");
}
}
}

Output:

Nesting if-else statements:


When a series of decisions are involved, we may have to use more than
one if statements in nested as follows.

47
OOP using JAVA

Syntax:

if(condition)
{
if(condition)
{
Statement block1;
}
else
{
Statement block 2;
}
}
else
{
if(condition)
{
Statement block 3;
}
else
{
Statement block 4;
}
Statement-n;

Example Prograam
Class ifelsenesting
{
public static void main(String args[])
{
int a=325,b=712,c=478;
System.out.println(“largest value is:”);
if(a>b)
{
if(a>c)
{
System.out.println(a);
}
else

48
OOP using JAVA

{
System.out.println(a);
}
}
else
{
if(b>c)
{
System.out.println(b);
}
else
{
System.out.println(c);
}
}
}
Output: Largest value is :712

else if ladder:

A common programming construct in the java is the if-else-if ladder , which


is often also called the if-else-if staircase because of it's appearance.

Syntax:
if (condition1)
statement1;
else if (condition2)
statement2;
else if(condition3)
statement3;
…………………
…………………

49
OOP using JAVA

else if(condition n)
statement n;
else
default-statement;
statement-x;
This construct is known as the else if ladder. The conditions are evaluated
from the top of the ladder. As soon as the true condition is found, the statement
associated with it is executed and the control is transferred to the statement-x.
When all the n conditions becomes false, then the final else containing the default-
statement will be executed.

Example Program:

class ei
{
public static void main(String args[])
{
int marks=70;
if(marks>79)
{
System.out.println("honours");
}
else if(marks>59)
{
System.out.println(" I Division");
}
else if(marks>79)
{
System.out.println("II Division");
}

else
{
System.out.println(" Fail");

50
OOP using JAVA

}
}
Output:

The Switch Statement:

Java provides a multiple branch selection statement known as switch. This


selection statement successively tests the value of an expression against a list of
integer or character constants. When a match is found, the statements associated
with that constant are executed.

Syntax:

switch(expression)
{
case value1:
block-1
break;
case value2:
block-2
break;
. . . . . . . . ..
..........
default:
default-block

51
OOP using JAVA

break;
}
Statement-x;
The optional default label is used to specify the code segment to be
executed, when the value of the variable or expression does not match with any of
the case values. If there is no break statement as the last statement in the code
segment for a certain case, the execution will continue on into the code segment for
the next case clause without checking the case value.

Example Program:

class SwitchDemo
{
public static void main(String[] args)
{

int month = 8;
switch (month)
{
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");
}

52
OOP using JAVA

}
}
Output:

Looping

The process of repeatedly executing a block of statements is known as


looping. The statements in the block may be executed any number of times, from
zero to infinite number of times. If a loop continues forever, it is called an infinite
loop.

The Java Language provides three constructs for performing loop


operations. They are

 while construct
 do construct
 for construct

While statement

The basic format of the while statement is as follows

Initialization:
while (test condition)
{
Body of the loop;
}
The while is an entry-controlled loop statement. The test condition is
evaluated and if the condition is true, then the body of the loop is executed. After
execution of the body, the test condition is once again evaluated and if it is true,
the body is executed once again. This process is repeated until the test condition
returns a false value.

The following program illustrates the use of while loop in java.

53
OOP using JAVA

Aim: To read a string from the keyboard character by character and to display it on
the screen.

Program:

import java.io.*;
class WhileTest
{
public static void main(String[] args) throws IOException
{
int i=1;
while(i<=10)
{
System.out.println("i=" + i);
i++;
}
}
}
Output:

The do..while Statement

The following is the syntax for the do statement

Initialization;

54
OOP using JAVA

do
{
Body of the loop;
} while (test condition);
On reaching the do statement, the program proceeds to execute the body of
the loop first. At the end of the loop, the test condition in the while statement is
evaluated. If the condition is true, the program continues to evaluate the body of
the loop once again. This process continues as long as the condition is true. When
the condition is false, the loop will be terminated.

Since the test condition is evaluated at the bottom of the loop, the do…while
constructs provides an exit-controlled loop and therefore the body of the loop is
always executed at least once.

The following program illustrates the do…while construct

Aim: To display the multiplication table.

Program:

class dow {

public static void main(String args[]){

int i=0;

do{

System.out.println(i);

i++;

}while(i<10);

55
OOP using JAVA

Output:

Difference between while and do…while constructs

while Do…while
It is a looping construct that will It is a looping construct that will
execute only if the test condition is execute at least once even if the test
true. condition is false.
It is entry controlled loop. It is an exit controlled loop.
It is generally used for implementing It is typically used for implementing
common looping situations. menu based programs where the menu
is required to be printed at least once.

The for statement

The for loop is another entry controlled loop that provides a more concise
loop control structure. The general form of the loop is as follows.

for(initialization ; test condition ; increment/decrement)


{
Body of the loop;
}
The execution of the for statement is as follows

1. initialization of the control variable is done first, using assignment


statements such as i=1 and count=0. The variables I and count are known as
loop-control variables.

56
OOP using JAVA

2. The value of the control variable is tested using the test condition. If the test
condition is true, the body of the loop is executed; otherwise the loop is
terminated.
3. When the body of the loop is executed, the control is transfer back to the for
statement after evaluating the last statement in the loop. Now, the control
variable is incremented or decrement.

Additional Features of a for Loop

The for loop has several capabilities that are not found in other loop
constructs. They are
1. More than one variable can be initialized at a time in the for statement.
The statements
p=1;
for(n=0;n<10;n++)
Can be written as
for(p=1,n=0;n<10;n++)
2. Like the initialization section, the increment section may also have more
than one part. For example
for(n=1,m=50;n<=m;n++,m--)
3. The test condition may have any compound relation and the testing need
not be limited only to the control variable. Consider the following

sum=0;
for(i=1;i<20&&sum<100;i++)
{
………………
……………..
}
4. Another unique aspect of for loop is that one or more sections can be
omitted, if necessary. Consider the following example
…………..
………….
m=5;
for( ; m!=100 ; )
57
OOP using JAVA

{
System.out.println(m);
m=m+5;
}
………….
………….

Example:

Nesting of for loops

Nesting of loops means one for statement within another for statement, is
allowed in java. The for loops can be nested as follows

Aim: Program to display a right angled triangle of @

Program:

class NestedLoop
{
public static void main(String[] args)
{
int i,j;
System.out.println("The right angle triangle of @ is shown in
below:\n");
for(i=1;i<=9;i++)
{
for(j=1;j<=i;j++)
{
System.out.print("@");
}
System.out.println(" ");
}
}
}

58
OOP using JAVA

Output:

The Enhanced for loop

The enhanced for loop, also called for each loop. This feature helps us to
retrieve the array of elements efficiently rather than using array indexes.

The Enhanced for loop takes the following form

for(Type Identifier : Expression)


{
//Statements
}
The following program illustrates the use of Enhanced for loop.

Write a java program using enhanced for loop.

import java.util.*;
import java.lang.*;

class foreach
{
public static void main(String[] args)
{
int arr[]={1,2,3,4};
for(int i : arr)
{
59
OOP using JAVA

System.out.println(i);
}
}
}

Output:

Jumping Control Statements

Java permits a jump from one statement to the end or beginning of a loop as
well as a jump out of a loop.

Jumping Out of loop (break statement)

When the break statement is encountered inside a loop, the loop is


immediately exited and the program continues with the statement immediately
following the loop. When the loops are nested, the break would only exit from the
loop containing it. The break will exit only a single loop.

This statement can also be used within while, do or for loops as illustrated below.

60
OOP using JAVA

Example:

class Breakdemo
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
if(i==5)
break;
System.out.println("i="+i);
}
}
}
Output:

Skipping a part of a Loop (continue statement)

Like the break statement java supports another similar statement called
continue statement. Whenever the continue statement is encountered within the
loop, that causes the loop to be continued with the next iteration after skipping any
statements in between. The continue statement tells the compiler “ SKIP THE
FOLLOWING STATEMENTS AND CONTINUE WITH THE NEXT
ITERATION”.

The use of the continue statement in loops is illustrated below.

61
OOP using JAVA

Example:

class Continuedemo
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
if(i==5)
continue;
System.out.println("i="+i);
}
}
}

Output:

62
OOP using JAVA

3. return:

The return keyword finishes the execution of a method, and can be used to return a
value from a method.

Example:

public class ReturnExample1 {

int display()
{
return 10;
}
public static void main(String[] args) {
ReturnExample1 e =new ReturnExample1();
System.out.println(e.display());
}

}
Output:

10

63

You might also like