0% found this document useful (0 votes)
4 views

JAVA UNIT-I-part-1

Uploaded by

Shivasainath .k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JAVA UNIT-I-part-1

Uploaded by

Shivasainath .k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

OOPS THROUGH

JAVA
R 20 OOPS THROUGH JAVA

UNIT – I
OBJECT ORIENTED THINKING

A WAY OF VIEWING THE WORLD


A way of viewing the world is an idea to illustrate the object-oriented
programming concept with an example of a real-world situation. Let us consider
a situation, I am at my office and I wish to get food to my family members who
are at my home from a hotel. Because of the distance from my office to home,
there is no possibility of getting food from a hotel myself. So, how do we solve
the issue? To solve the problem, let me call Zomato (an agent in food delivery
community), tell them the variety and quantity of food and the hotel name from
which I wish to deliver the food to my family members. Look at the following
image.

Agents and Communities : To solve my food delivery problem, I used a


solution by finding an appropriate agent (Zomato) and pass a message

[1] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA
containing my request. It is the responsibility of the agent (Zomato) to satisfy
my request. Here, the agent uses some method to do this. I do not need to know
the method that the agent has used to solve my request. This is usually hidden
from me. So, in object-oriented programming, problem-solving is the solution
to our problem which requires the help of many individuals in the community.
We may describe agents and communities as follows. An object-oriented
program is structured as a community of interacting agents, called objects.
Where each object provides a service (data and methods) that is used by other
members of the community. In our example, the online food delivery system is
a community in which the agents are zomato and set of hotels. Each hotel
provides a variety of services that can be used by other members like zomato,
myself, and my family in the community.

Messages and Methods : To solve my problem, I started with a request


to the agent zomato, which led to still more requestes among the members of
the community until my request has done. Here, the members of a community
interact with one another by making requests until the problem has satisfied. In
object-oriented programming, every action is initiated by passing a message to
an agent (object), which is responsible for the action. The receiver is the
object to whom the message was sent. In response to the message, the receiver
performs some method to carry out the request. Every message may include
any additional information as arguments. In our example, I send a request to
zomato with a message that contains food items, the quantity of food, and the
hotel details. The receiver uses a method to food get delivered to my home.

Responsibilities: In object-oriented programming, behaviors of an


object described in terms of responsibilities. In our example, my request for
action indicates only the desired outcome (food delivered to my family). The
agent (zomato) free to use any technique that solves my problem. By discussing
a problem in terms of responsibilities increases the level of abstraction. This
enables more independence between the objects in solving complex problems.

[2] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA

Classes and Instances : In object-oriented programming, all objects are


instances of a class. The method invoked by an object in response to a
message is decided by the class. All the objects of a class use the same method
in response to a similar message. In our example, the zomato a class and all the
hotels are sub-classes of it. For every request (message), the class creates an
instance of it and uses a suitable method to solve the problem.

OBJECT ORIENTED PROGRAMMING FEATURES

OOP stands for Object-Oriented Programming. OOP is a programming


paradigm in which every program follows the concept of object. In other words,
OOP is a way of writing programs based on the object concept.
The object-oriented programming paradigm has the following core concepts.
• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
The popular object-oriented programming languages are Smalltalk, C++, Java,
PHP, C#, Python, etc.

Encapsulation
Encapsulation is the process of combining data and code into a single unit
(object / class). In OOP, every object is associated with its data and code. In
programming, data is defined as variables and code is defined as methods. The
java programming language uses the class concept to implement encapsulation.

[3] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA
Inheritance
Inheritance is the process of acquiring properties and behaviours from
one object to another object or one class to another class. In inheritance, we
derive a new class from the existing class. Here, the new class acquires the
properties and behaviours from the existing class. In the inheritance concept, the
class which provides properties is called as parent class and the class which
receives the properties is called as child class. The parent class is also known as
base class or super class. The child class is also known as derived class or sub
class. In the inheritance, the properties and behaviours of base class extended to
its derived class, but the base class never receive properties or behaviours from
its derived class. In java programming language the keyword extends is used to
implement inheritance.

Polymorphism
Polymorphism is the process of defining same method with different
implementation. That means creating multiple methods with different
behaviours. The java uses method overloading and method overriding to
implement polymorphism. Method overloading - multiple methods with same
name but different parameters. Method overriding - multiple methods with same
name and same parameters.

Abstraction
Abstraction is hiding the internal details and showing only essential
functionality. In the abstraction concept, we do not show the actual
implementation to the end user, instead we provide only essential things. For
example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how
music system works? etc.

OVERVIEW OF JAVA
Java is a computer programming language. Java was created based on C
and C++. Java uses C syntax and many of the object-oriented features are taken
from C++. Before Java was invented there were other languages like COBOL,
FORTRAN, C, C++, Small Talk, etc. These languages had few disadvantages
which were corrected in Java. Java also innovated many new features to solve

[4] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA
the fundamental problems which the previous languages could not solve. Java
was invented by a team of 13 employees of Sun Microsystems, Inc. which is led
by James Gosling, in 1991. The team includes persons like Patrick Naughton,
Chris Warth, Ed Frank, and Mike Sheridan, etc., Oak is a discontinued
programming language created by James Gosling in 1991, initially for Sun
Microsystems' set-top box project. The language later evolved to become Java.
The name Oak was used by Gosling after an oak tree that stood outside his
office. Java was developed as a part of the Green project. Initially, it was called
Oak, later it was changed to Java in 1995.

History of Java :
• The C language developed in 1972 by Dennis Ritchie had taken a decade to
become the most popular language.
• In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language
with included OOP fundamentals and features.
• A project named “Green” was initiated in December of 1990, whose aim was
to create a programming tool that could render obsolete the C and C++
programming languages.
• Finally in the year of 1991 the Green Team was created a new Programming
language named “OAK”.
• After some time they found that there is already a programming language with
the name “OAK”.
• So, the green team had a meeting to choose a new name. After so many
discussions they want to have a coffee. They went to a Coffee Shop which is
just outside of the Gosling’s office and there they have decided name as
“JAVA”.

Applications:

[5] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA
According to Sun, 3 billion devices run Java. There are many devices
where Java is currently used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player,


antivirus, etc.
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

Types of Java Applications:

There are mainly 4 types of applications that can be created using Java
programming:

1) Standalone Application
Standalone applications are also known as desktop applications or
window-based applications. These are traditional software that we
need to install on every machine. Examples of standalone
application are Media player, antivirus, etc. AWT and Swing are
used in Java for creating standalone applications.

2) Web Application
An application that runs on the server side and creates a dynamic
page is called a web application. Currently, Servlet, JSP, Struts,
Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.

3) Enterprise Application
An application that is distributed in nature, such as banking
applications, etc. is called enterprise application. It has advantages
of the high-level security, load balancing, and clustering. In Java,
EJB is used for creating enterprise applications.

4) Mobile Application

[6] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA
An application which is created for mobile devices is called a
mobile application. Currently, Android and Java ME are used
for creating mobile applications.

Java Platforms / Editions:

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)


It is a Java programming platform. It includes Java programming
APIs such as java.lang, java.io, java.net, java.util, java.sql,
java.math etc. It includes core topics like OOPs, String, Regex,
Exception, Inner classes,
Multithreading,I/OStream,Networking,AWT,Swing,Reflection,Col
lection etc.,

2) Java EE (Java Enterprise Edition)


It is an enterprise platform which is mainly used to develop web
and enterprise applications. It is built on the top of the Java SE
platform. It includes topics like Servlet, JSP, Web Services, EJB,
JPA, etc.

3) Java ME (Java Micro Edition)


It is a micro platform which is mainly used to develop mobile
applications.

4) JavaFX
It is used to develop rich internet applications. It uses a light-weight user
interface API.

CLASS IN JAVA
The class is at the core of Java. It is the logical construct upon
which the entire Java language is built because it defines the shape
and nature of an object. As such, the class forms the basis for object-
oriented programming in Java. Any concept you wish to implement
in a Java program must be encapsulated within a class. Because the
class is so fundamental to Java.

[7] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA

Thus, a class is a template for an object, and an object is an instance


of a class. Because an object is an instance of a class, you will often
see the two words object and instance used interchangeably. It is a
logical entity. It can't be physical.

A class in Java can contain:


o Variables
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax:
class <class_name>{
Variables;
method;
}

The General Form of a Class

When you define a class, you declare its exact form and nature. You do
this by specifying the data that it contains and the code that operates on
that data. While very simple classes may contain only code or only
data, most real-world classes contain both.

A class is declared by use of the class keyword.

[8] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA
The general form of a class definition
is shown here:
class classname {
instance
variable1;
instance-
variable2; ...
type instance-variableN;

type
methodname1(parameter
-list) { // body of method
}
type
methodname2(parameter
-list) { // body of method
}
// ...
type
methodnameN(parameter
-list) { // body of method
}
}

The data, or variables, defined within a class are called instance


variables. The code is contained within methods. Collectively, the
methods and variables defined within a class are called members of
the class. In most classes, the instance variables are acted upon and
accessed by the methods defined for that class. Thus, it is the methods
that determine how a class‘ data can be used.
Variables defined within a class are called instance variables because
each instance of the class (that is, each object of the class) contains its own copy
of these variables. Thus, the data for one object is separate and unique from the
data for another. All methods have the same general form as main( ), which we
have been using thus far. However, most methods will not be specified as static
or public

CREATING AN OBJECT

In java, an object is an instance of a class. When an object of a class is


created, the class is said to be instantiated. All the objects that are created using
a single class have

[9] Syeda Sumaiya Afreen


R 20 OOPS THROUGH JAVA
the same properties and methods. But the value of properties is different for
every object. Following is the syntax of class in the java
Syntax
<ClassName> <objectName> = new <ClassName>( );

JAVA METHODS

A method is a block of statements under a name that gets executes only


when it is called. Every method is used to perform a specific task. The major
advantage of methods is code re-usability (define the code once, and use it
many times).
In a java programming language, a method defined as a behaviour of an object.
That means, every method in java must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.
• returnType - Specifies the data type of a return value.
• name - Specifies a unique name to identify it.
• parameters - The data values it may accept or recieve.
• { } - Defienes the block belongs to the method.

Creating a method
A method is created inside the class and it may be created with any access
specifier. However, specifying access specifier is optional.
Following is the syntax for creating methods in java.
Syntax
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}
🔔 The methodName must begin with an alphabet, and the Lower-case letter is
preferred.
🔔 The methodName must follow all naming rules.
🔔 If you don't want to pass parameters, we ignore it.
🔔 If a method defined with return type other than void, it must contain the
return statement, otherwise, it may be ignored.

Calling a method
In java, a method call precedes with the object name of the class to which it
belongs and a dot operator. It may call directly if the method defined with the

[10] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
static modifier. Every method call must be made, as to the method name with
parentheses (), and it must terminate with a semicolon.
Syntax
<objectName>.<methodName>( actualArguments );
🔔 The method call must pass the values to parameters if it has.
🔔 If the method has a return type, we must provide the receiver.

JAVA BUZZ WORDS/JAVA FEATURES


Java is the most popular object-oriented programming language. Java has
many advanced features, a list of key features is known as Java Buzz Words.
The java team has listed the following terms as java buzz words.

• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Architecture-neutral (or) Platform Independent
• Multi-threaded
• Interpreted
• High performance
• Distributed
• Dynamic
Simple

[11] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
Java programming language is very simple and easy to learn, understand, and
code. Most of the syntaxes in java follow basic programming language C and
object-oriented programming concepts are similar to C++. In a java
programming language, many complicated features like pointers, operator
overloading, structures, unions, etc. have been removed. One of the most useful
features is the garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have
pointers concept, java provides a feature "applet" which can be embedded into a
web application. The applet in java does not allow access to other parts of the
computer, which keeps away from harmful programs like viruses and
unauthorized access.

Portable
Portability is one of the core features of java which enables the java programs to
run on any computer or operating system. For example, an applet developed
using java runs on a wide variety of CPUs, operating systems, and browsers
connected to the Internet.
Object-oriented
Java is said to be a pure object-oriented programming language. In java,
everything is an object. It supports all the features of the object-oriented
programming paradigm. The primitive data types java also implemented as
objects using wrapper classes, but still, it allows primitive data types to archive
high-performance.
Robust
Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism (garbage
collector), java is a strictly typed language, it has a strong set of exception
handling mechanism, and many more.
Architecture-neutral (or) Platform Independent
Java has invented to archive "write once; run anywhere, any time, forever". The
java provides JVM (Java Virtual Machine) to to archive architectural-neutral or
platform independent. The JVM allows the java program created using one
operating system can be executed on any other operating system.
Multi-threaded

[12] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
Java supports multi-threading programming, which allows us to write programs
that do multiple operations simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode. The byte code is interpreted to
any machine code so that it runs on the native machine.
High performance
Java provides high performance with the help of features like JVM,
interpretation, and its simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to
support the distributed environment of the Internet. Java also supports Remote
Method Invocation (RMI), this feature enables a program to invoke methods
across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically
updated on a running system and it has a dynamic memory allocation and
deallocation (objects and garbage collector.

JAVA DATA TYPES


Java programming language has a rich set of data types. The data type is
a category of data stored in variables. In java, data types are classified into two
types and they are as follows.
• Primitive Data Types
• Non-primitive Data Types

[13] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

Primitive Data Types:


The primitive data types include boolean, char, byte, short, int, long, float and
double.

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

[14] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:

Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It is an 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It
can also be used in place of "int" data type.

Example:

byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between
-32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767.
Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.

Example:

short s = 10000, short r = -5000

[15] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.

Example:

int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between
-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1) (inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you
need a range of values more than those provided by int.

Example:

long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers. The float data type should never be
used for precise values, such as currency. Its default value is 0.0F.

Example:

float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just like
float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.

[16] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
Example:

double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.

Example:

char letterA = 'A'

Non-primitive Data Types :

In java, non-primitive data types are the reference data types or user-created
data types. All non-primitive data types are implemented using object concepts.
Every variable of the non-primitive data type is an object. The non-primitive
data types may use additional methods to perform certain operations. The
default value of non-primitive data type variable is null. In java, examples of
non-primitive data types are String, Array, List, Queue, Stack, Class, Interface,
etc.

JAVA VARIABLES
A variable is a named memory location used to store a data value. A
variable can be defined as a container that holds a data value.

Syntax:

data_type variable_name; (or)

data_type variable_name_1, variable_name_2,...; (or)

data_type variable_name = value; (or)

data_type variable_name_1 = value, variable_name_2 = value,...;

[17] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

In java programming language variables are classifiedp as follows.

• Local variables

• Instance variables or Member variables or Global variables

• Static variables or Class variables

• Final variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the class
aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not


shared among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local.


You can create a single copy of the static variable and share it among all the
instances of the class. Memory allocation for static variables happens only once
when the class is loaded in the memory.

Example:

1. public class A

[18] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class

4) Final variable
A final variable is a variable that declared using final keyword. The final
variable is initialized only once, and does not allow any method to change it's
value again. The variable created using final keyword acts as constant. All
variables like local, instance, and static variables can be final variables. Let's
look at the following example java program to illustrate final variable in java.

JAVA ARRAYS

An array is a collection of similar data values with a single name. An


array can also be defined as, a special type of variable that holds
multiple values of the same data type at a time.
In java, arrays are objects and they are created dynamically using
new operator. Every array in java is organized using index values.
The index value of an array starts with '0' and ends with 'zise-1'. We
use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.

• One Dimensional Array


• Multi Dimensional Array

[19] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
One Dimensional Array :
In the java programming language, an array must be created using
new operator and with a specific size. The size must be an integer
value but not a byte, short, or long. We use the following syntax to
create an array.
Syntax

In java, an array can also be initialized at the time of its declaration.


When an array is initialized at the time of its declaration, it need not
specify the size of the array and use of the new operator. Here, the
size is automatically decided based on the number of values that are
initialized.
For Example :

int list[ ] = {10, 20, 30, 40, 50};

Examples:
//Java Program to illustrate the use of declaration, instantiation and initialization
of Java array in a single line
1. class Testarray1{
2. public static void main(String args[]){
3. int a[]={33,3,4,5};//declaration, instantiation and initialization
4. //printing array
5. for(int i=0;i<a.length;i++)//length is the property of array
6. System.out.println(a[i]);
7. }}

Multidimensional Array:
In java, we can create an array with multiple dimensions. We can

[20] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
create 2- dimensional, 3-dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a
multidimensional array variable, specify each additional index
using another set of square brackets. We use the following syntax to
create two-dimensional array.
Syntax :

When an array is initialized at the time of declaration, it need not


specify the size of the array and use of the new operator. Here, the
size is automatically decided based on the number of values that are
initialized.
For Example :
int matrix_a[ ][ ] = {{1, 2},{3, 4},{5, 6}};

The above statement creates a two-dimensional array of three rows and two
columns.

Examples:
//Java Program to illustrate the use of multidimensional array

1. lass Testarray3{
2. public static void main(String args[]){
//declaring and initializing 2D array
3. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
4. //printing 2D array
5. for(int i=0;i<3;i++){
6. for(int j=0;j<3;j++){
7. System.out.print(arr[i][j]+" ");
8. }
[21] Syeda Sumaiya
Afreen
R 20 OOPS THROUGH JAVA
9. System.out.println();
10. }
11. }
}
JAVA OPERATORS

An operator is a symbol used to perform arithmetic and


logical operations. Java provides a rich set of operators.
In java, operators are clasiffied into the following four types.

• Arithmetic Operqators
• Relational (or) Comparision Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Conditional Operators

Let's look at each operator in detail.

Operator Category Precedence


Type

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

bitwise AND &


Bitwise
bitwise exclusive OR ^

[22] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator:


The Java unary operators require only one operand. Unary operators are
used to perform

various operations i.e.:

o incrementing/decrementing a value by one

o negating an expression

o inverting the value of a Boolean

Example: ++ and --

1. class OperatorExample{

2. public static void main(String args[]){

3. int x=10;

4. System.out.println(x++);//10 (11)

5. System.out.println(++x);//12

6. System.out.println(x--);//12 (11)

7. System.out.println(--x);//10 8. }}

Java Arithmetic Operators:

[23] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
Java arithmatic operators are used to perform addition, subtraction,
multiplication, and

division. They act as basic mathematical operations.

Example :

1. class OperatorExample{

2. public static void main(String args[]){

3. int a=10;

4. int b=5;

5. System.out.println(a+b);//15

6. System.out.println(a-b);//5

7. System.out.println(a*b);//50

8. System.out.println(a/b);//2

9. System.out.println(a%b);//0 10. }}

Java Left Shift Operator:


The Java left shift operator << is used to shift all of the bits in a value to the left

side of a specified number of times.

Example:

1. class OperatorExample{

2. public static void main(String args[]){

3. System.out.println(10<<2);//10*2^2=10*4=40

4. System.out.println(10<<3);//10*2^3=10*8=80

5. System.out.println(20<<2);//20*2^2=20*4=80

6. System.out.println(15<<4);//15*2^4=15*16=240

[24] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
7. }}

Java Right Shift Operator:


The Java right shift operator >> is used to move left operands value to right by
the number of bits specified by the right operand.

Example:

1. class OperatorExample{

2. public static void main(String args[]){

3. System.out.println(10>>2);//10/2^2=10/4=2

4. System.out.println(20>>2);//20/2^2=20/4=5

5. System.out.println(20>>3);//20/2^3=20/8=2

6. }}

Java AND Operator: Logical && and Bitwise &:


The logical && operator doesn't check second condition if first condition is
false.

It checks second condition only if first one is true.

The bitwise & operator always checks both conditions whether first condition is
true or false.

Example: 1

1. class OperatorExample{

2. public static void main(String args[]){

3. int a=10;

4. int b=5;

5. int c=20;

[25] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
6. System.out.println(a<b&&a<c); //false && true = false

7. System.out.println(a<b&a<c); //false & true = false

8. }}

Java OR Operator Example: Logical || and Bitwise |:

The logical || operator doesn't check second condition if first condition is true. It
checks second condition only if first one is false.

The bitwise | operator always checks both conditions whether first condition is
true or false.

Example:

1. class OperatorExample{

2. public static void main(String args[]){

3. int a=10;

4. int b=5;

5. int c=20;

6. System.out.println(a>b||a<c);//true || true = true

7. System.out.println(a>b|a<c);//true | true = true 8. //|| vs |

9. System.out.println(a>b||a++<c);//true || true = true

10. System.out.println(a);//10 because second condition is not checked

11. System.out.println(a>b|a++<c);//true | true = true

12. System.out.println(a);//11 because second condition is checked

13. }}

Java Ternary Operator :

[26] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
Java Ternary operator is used as one liner replacement for if-then-else
statement and used a lot in java programming. it is the only conditional
operator which takes three operands.

Example:

1. class OperatorExample{

2. public static void main(String args[]){

3. int a=2;

4. int b=5;

5. int min=(a<b)?a:b;

6. System.out.println(min);

7. }}

Java Assignment Operator:


Java assignment operator is one of the most common operator. It is used to
assign the value on its right to the operand on its left.

Example:

1. class OperatorExample{

2. public static void main(String args[]){

3. int a=10;

4. int b=20;

5. a+=4; //a=a+4 (a=10+4)

6. b-=4; //b=b-4 (b=20-4)

7. System.out.println(a);

8. System.out.println(b);

9. }}

JAVA EXPRESSIONS

[27] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
In any programming language, if we want to perform any
calculation or to frame any condition etc., we use a set of symbols
to perform the task. These set of symbols makes an expression. In
the java programming language, an expression is defined as
follows.
An expression is a collection of operators and operands that represents
a specific value.

In the above definition, an operator is a symbol that performs tasks


like arithmetic operations, logical operations, and conditional
operations, etc. Operands are the values on which the operators
perform the task. Here operand can be a direct value or variable or
address of memory location.

Expression Types:
In the java programming language, expressions are divided into
THREE types. They are as follows.

• Infix Expression
• Postfix Expression
• Prefix Expression

The above classification is based on the operator position in the expression.

Infix Expression :
The expression in which the operator is used between operands is
called infix expression.
The infix expression has the following general structure.
Example:

[28] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
Postfix Expression:
The expression in which the operator is used after operands is called
postfix expression.
The postfix expression has the following general structure.

Example:

Prefix Expression:
The expression in which the operator is used before operands is
called a prefix expression.
The prefix expression has the following general structure.

Example:

JAVA CONTROL STATEMENTS


In java, the default execution flow of a program is a sequential order. But the
sequential order of execution flow may not be suitable for all situations.
Sometimes, we may want to jump from line to another line, we may want to
skip a part of the program, or sometimes we may want to execute a part of the
program again and again. To solve this problem, java provides control
statements
In java, the control statements are the statements which will tell us that in which
order the instructions are getting executed. The control statements are used to
control the order of execution according to our requirements. Java provides
several control statements, and they are classified as follows.

[29] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

Types of Control Statements In java, the control statements are classified as


follows:

• Selection Control Statements ( Decision Making Statements )

• Iterative Control Statements ( Looping Statements )

• Jump Statements

Selection Control Statements


In java, the selection statements are also known as decision making statements
or branching statements. The selection statements are used to select a part of the
program to be executed based on a condition.
Java provides the following selection statements.
• simple if statement
• if-else statement
• if-elif statement
• nested if statement
• switch statement.

1. simple if statement

It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.

Syntax of if statement is given below:

if(condition) {

[30] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
1. statement 1; //executes when condition is true
2. }

Consider the following example in which we have used the if statement in the java
code.

Student.java

public class Student {

1. public static void main(String[] args) {


2. int x = 10;
3. int y = 12;
4. if(x+y > 20) {
5. System.out.println("x + y is greater than 20");
6. }
7. }
8. }

Output:

x + y is greater than 20

2. if-else statement :
The if-else statement
is an extension to the if-statement, which uses another block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.

Syntax:

if(condition) {

1. statement 1; //executes when condition is true


2. }
3. else{
4. statement 2; //executes when condition is false
5. }

Consider the following example.

Student.java

[31] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
public class Student {

1. public static void main(String[] args) {


2. int x = 10;
3. int y = 12;
4. if(x+y < 10) {
5. System.out.println("x + y is less than 10");
6. } else {
7. System.out.println("x + y is greater than 20");
8. }
9. }
10. }

Output:

x + y is greater than 20

3. if-elif statement : The if-else-if statement contains the if-statement


followed by multiple else-if statements. In other words, we can say that it is the
chain of if-else statements that create a decision tree where the program may
enter in the block of code where the condition is true. We can also define an
else statement at the end of the chain.

Syntax of if-else-if statement is given below.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }

Consider the following example.

Student.java

public class Student {

[32] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
1. public static void main(String[] args) {
2. String city = "Delhi";
3. if(city == "Meerut") {
4. System.out.println("city is meerut");
5. }else if (city == "Noida") {
6. System.out.println("city is noida");
7. }else if(city == "Agra") {
8. System.out.println("city is agra");
9. }
10. else {
11. System.out.println(city);
12. }
13. }
14. }

Output:

Delhi

4. nested if statement :

In nested if-statements, the if statement can contain a if or if-else statement inside


another if or else-if statement.

Syntax of Nested if-statement is given below.

if(condition 1) {

1. statement 1; //executes when condition 1 is true


2. if(condition 2) {
3. statement 2; //executes when condition 2 is true
4. }
5. else{
6. statement 2; //executes when condition 2 is false
7. }
8. }

Consider the following example.

Student.java

public class Student {

[33] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
1. public static void main(String[] args) {
2. String address = "Delhi, India";
3.
4. if(address.endsWith("India")) {
5. if(address.contains("Meerut")) {
6. System.out.println("Your city is Meerut");
7. }else if(address.contains("Noida")) {
8. System.out.println("Your city is Noida");
9. }else {
10. System.out.println(address.split(",")[0]);
11. }
12. }else {
13. System.out.println("You are not living in India");
14. }
15. }
16. }

Output:

Delhi

5. switch statement
In Java switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which
is being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.

switch
(expression) {
case value1:
// statement
sequence
break;
case value2:
// statement
sequence
break;
...
case valueN:
// statement
sequence
break;
default:

[34] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
// default statement
sequence }

Consider the following example :


class
SampleSwitch {
public static void main(String
args[]) { for(int i=0; i<6; i++)
swit
ch(i
){
case
0:
System.out.println("i is
zero."); break;
case 1:
System.out.println("i is
one."); break;
case 2:
System.out.println("i is
two."); break;
case 3:
System.out.println("i is
three."); break;
default:
System.out.println("i is greater
than 3."); }
}
}

The output produced by this program is


shown here: i is zero.

i is three.
i is greater
than 3. i is
greater
than 3.

ITERATIVE CONTROL STATEMENTS


The iterative statements are used to execute a part of the program
repeatedly as long as the given condition is True. Using iterative statements
reduces the size of the code, reduces the code complexity, makes it more
efficient, and increases the execution speed.
Java provides the following iterative statements.:
• while statement

[35] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
• do- while statement
• for statement
• for-each statement

1. while statement : The while statement is used to execute a single


statement or block of statements repeatedly as long as the given condition is
TRUE. The while statement is also known as Entry control looping statement.
The syntax and execution flow of while statement is as follows

The syntax of the while loop is given below:

while(condition){
//looping statements
}

Example Program:

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}

1. Output:
2. Printing the list of first 10 even numbers
3.
4. 0
5. 2
6. 4
7. 6
8. 8
9. 10

10. Printin

[36] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
11. g the list of first 10 even numbers
2. do-while statement : The do-while statement is used to execute a single
statement or block of statements repeatedly as long as given the condition is
TRUE. The do-while statement is also known as the Exit control looping
statement. The do-while statement has the following syntax.
do
{
//statements
} while (condition);

Example:

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}

Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

3. for statement : The for statement is used to execute a single statement or a


block of statements repeatedly as long as the given condition is TRUE. The for
statement has the following syntax and execution flow diagram.
for(initialization, condition, increment/decrement) {
//block of statements
}

[37] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
Example:

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}

Output:

The sum of first 10 natural numbers is 55

4. for-each statement : It provides an approach to traverse through an array or


collection in Java. The for-each statement also known as enhanced for
statement. The for-each statement executes the block of statements for each
element of the given array or collection.
for(data_type var : array_name/collection_name){
//statements
}

Example:

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
system.out.println(name);
}
}
}

Output:

[38] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
Printing the content of the array names:

Java
C
C++
Python
JavaScript

JUMP STATEMENTS
Jump statements are used to transfer the control of the program to the
specific statements. In other words, jump statements transfer the execution
control to the other part of the program.
In java, the jump statements are used to terminate a block or take the execution
control to the next iteration.
Java provides the following jump statements.

• break statement
• continue
• return

1. Break :

It is used to break the current flow of the program and transfer the control to the next
statement outside a loop or switch statement. However, it breaks only the inner loop in the
case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.

public class BreakExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}

[39] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA
}
}

Output:

0
1
2
3
4
5
6

2. Continue : It skips the specific part of the loop and jumps to the next
iteration of the loop immediately. The continue statement is used to move the
execution control to the beginning of the looping statement. When the continue
statement is encountered in a looping statement, the execution control skips the
rest of the statements in the looping block and directly jumps to the beginning
of the loop. The continue statement can be used with looping statements like
while, do-while, for, and for-each.
3. Return : In java, the return statement used to terminate a method with or
without a value. The return statement takes the execution control to the calling
function. That means the return statement transfer the execution control from
called function to the calling function by carrying a value.
🔔 Java allows the use of return-statement with both, with and without return
type methods. In java, the return statement used with both methods with and
without return type. In the case of a method with the return type, the return
statement is mandatory, and it is optional for a method without return type.
When a return statement used with a return type, it carries a value of return
type. But, when it is used without a return type, it does not carry any value.
Instead, simply transfers the execution control

return statement:

• return statement is useful to terminate a method and come back to the


calling method.
• return statement in main method terminates the application.
• return statement can be used to return some value from a method to a
calling method.

Syntax:
return;
(or)
return value; // value may be of any type

[40] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

STRING HANDLING METHODS

In java programming language, the String class contains various methods


that can be used to handle string data values. It contains methods like concat( ),
compareTo( ), split( ), join( ), replace( ), trim( ), length( ), intern( ), equals( ),
comparison( ), substring( ), etc.

Creating String object in java :


In java, we can use the following two ways to create a string object.
• Using string literal
• Using String constructor

1. Using string literal :


Java String literal is created by using double quotes.
For Example: String s="welcome";

2. Using String constructor:


String siteName = new String("www.btechsmartclass.com");
String s=new String("Welcome");

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

[41] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

Output:

java
strings
example

The above code, converts a char array into a String object. And displays the
String objects s1, s2, and s3 on console using println() method

JAVA STRING HANDLING


The java.lang.String class provides many useful methods to perform operations on
sequence of char values.

[42] Syeda Sumaiya


Afreen
No. Method Description
R 20 OOPS THROUGH JAVA
1 char charAt(int index) It returns char value for the particular index

2 int length() It returns string length

3 static String format(String format, It returns a formatted string.


Object... args)

4 static String format(Locale l, String It returns formatted string with given locale.
format, Object... args)

5 String substring(int beginIndex) It returns substring for given begin index.

6 String substring(int beginIndex, int It returns substring for given begin index and end index.
endIndex)

7 boolean contains(CharSequence s) It returns true or false after matching the sequence of char value.

8 static String join(CharSequence It returns a joined string.


delimiter, CharSequence... elements)

9 static String join(CharSequence It returns a joined string.


delimiter, Iterable<? extends
CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string with the given object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified string.

13 String replace(char old, char new) It replaces all occurrences of the specified char value.

String replace(CharSequence old, It replaces all occurrences of the specified CharSequence.


CharSequence new)

15 static String equalsIgnoreCase(String It compares another string. It doesn't check case.


another)

16 String[] split(String regex) It returns a split string matching regex.

17 String[] split(String regex, int limit) It returns a split string matching regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value index.

20 int indexOf(int ch, int fromIndex) It returns the specified char value index starting with given index.

[43] Syeda Sumaiya


Afreen
R 20 OOPS THROUGH JAVA

21 int indexOf(String substring) It returns the specified substring index.

22 int indexOf(String substring, int It returns the specified substring index starting with given index.
fromIndex)

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase using specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase using specified locale.

27 String trim() It removes beginning and ending spaces of this string.

28 static String valueOf(int value) It converts given type into string. It is an overloaded method.

[44] Syeda Sumaiya


Afreen

You might also like