Unit I Java
Unit I Java
Thinking Object-Oriented:
Object-Oriented Programming was introduced by Alan Kay during 1960 – 1967. At that time
it was not so popular. object oriented languages really came to the attention of the computing public-
at-large in the 1980's. But nowadays the software is becoming more popular and the size of the
software has increased.
The object oriented Programming Language is based upon the concept of “objects”, which
contains data as attributes in methods.
Object:
Objects are the basic run time entities in an object oriented system. They may represent a
person, a place, a bank account, a table of data or any item that the program has to handle.
Data Member:
Variables declared within a class preceded by a data type which define the state of an
object are called data members
Member Function:
Functions which define the behavior of an object of that class are called member functions.
Example:
class human
{
private: string name; // data member
int age; // data member
public: void run() // member function
{ };
void eat() // member function
{ };
};
For Example – Consider a Television, It is an object. And the properties related to it are.
It’s With and Height, color, type (Smart TV or CRT TV), etc. And the behavior can be – we can
change the channel, Adjust volumes and settings, switch off, switch on, etc are lots of behavior
are there. The operation on the behavior will affect the properties. Changing the channel will
affect its property.
So, similar things happen in Object-Oriented programming also, that each object has some properties
and behavior associated with it, that are defined in the class.
1. Objects – Object is the entity that makes the classes to be implemented into the program. It
makes the features, properties, and behaviors of the class to be implemented. Example – A car
is an object that has property color, model, brand name, fuel type, etc, and behaviors like, it
runs. So these properties and behavior make an object (CAR).
2. Classes – A class can be stated as the blueprint of the object. This states what an object can
do. It contains all the features, attributes, and behavior of what the model can do. We can say
that class contains the definition of the object. Example – Car color, engine type, etc. And
with the definition, we can create any number of objects.
3. Methods – Methods are the attributes of the class which are defined for the specified
behavior of the object. It can also modify the state of the class. Example – Method to drive a
car, It changes the state of the car from parking state to running state.
4. Instances – It is the members of the class who holds some values related to the objects of the
class.
Object-Oriented Paradigm:
The main necessity behind inventing object oriented approach is to remove the drawback
encountered in the procedural approach.
Object-oriented programming paradigm methods enable us to create a set of objects that work
together to produce software that is better understandable and models their problem domains
than produced using traditional techniques.
Programs are divided into objects.
Focus is on properties and functions rather than procedure.
Data is hidden from external functions.
Functions operate on the properties of an object.
Objects may communicate with each other through a function called messaging.
Follow the bottom-up approach in oop design
The major aspects of Object Oriented Programming (OOP) paradigm are as follows:
1. Reduced Maintenance :
The primary goal of object-oriented development is the assurance that the system will enjoy a
longer life while having far smaller maintenance costs. Because most of the processes within the
system are encapsulated, the behaviors may be reused and incorporated into new behaviors.
2. Real-World Modeling :
Object-oriented system tend to model the real world in a more complete fashion than do
traditional methods. Objects are organized into classes of objects, and objects are associated with
behaviors. The model is based on objects, rather than on data and processing.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
1. It emphasis on algorithm.
2. Large programs are divided into smaller programs known as functions.
3. Function can communicate by global variable.
4. Data move freely from one function to another function.
5. Functions change the value of data at any time from any place. (Functions transform data from one
form to another.)
6. It uses top-down programming approach.
Advantages of OOPs
1. Re-usability
It means reusing some facilities rather than building them again and again. This is done with the use
of a class.
2. Data Redundancy
This is a condition created at the place of data storage where the same piece of data is held in two
separate places. So the data redundancy is one of the greatest advantages of OOP.
3. Code Maintenance
This feature is more of a necessity for any programming languages; it helps users from doing re-work
in many ways. It is always easy and time-saving to maintain and modify the existing codes by
incorporating new changes into them.
4. Security
With the use of data hiding and abstraction mechanism, we are filtering out limited data to exposure,
which means we are maintaining security and providing necessary data to view.
5. Easy troubleshooting
lets witness some common issues or problems any developers face in their work.
6. Polymorphism Flexibility
Let’s see a scenario to better explain this behavior.
7. Problems solving
The broken components can be reused in solutions to different other problems
A WAY OF VIEWING THE WORLD:
a) To illustrate the major ideas in object-oriented programming, let us consider how we might go
about handling a real-world situation and then ask how we could make the computer more closely
model the techniques employed.
Suppose I wish to send owers to a friend who lives in a city many miles away. Let me call my
friend Sally. Because of the distance, there is no possibility of my picking the owers and carrying
them to her door myself. Nevertheless, sending her the owers is an easy enough task; I merely go
down to my local orist (who happens to be named Flora), tell her the variety and quantity of owers I
wish to send and give her Sally's address, and I can be assured the owers will be delivered expediently
and automatically.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
let me emphasize that the mechanism I used to solve my problem was to find an appropriate
agent (namely, Flora) and to pass to her a message containing my request.
If I investigated however, I might discover that Flora delivers a slightly different message to
another florist in my friend's city. That florist, in turn, perhaps has a subordinate who makes the
flower arrangement. The florist then passes the flowers, along with yet another message, to a delivery
person, and so on. Earlier, the florist in Sally's city had obtained her flowers from a flower wholesaler
who, in turn, had interactions with the flower growers, each of whom had to manage a team of
gardeners.
So, our first observation of object oriented problem solving is that the solution to my problem
required the help of many other individuals. . Without their help, my problem could not be easily
solved. We phrase this in a general fashion as the following:
An object oriented program is structured as a community of interacting agents, called objects. Each
object has a role to play. Each object provides a service, or performs an action, that is used by other
members of the community.
b) 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 delevery community), tell them the variety
and quantity of food and the hotel name from which I wish to delever the food to my family members.
Look at the following image.
To solve my food delivery problem, I used a solution by finding an appropriate agent (Zomato) and
pass a message 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.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
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.
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.
To solve my problem, I started with a request to the agent, which led to still more requests
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.
Responsibilities:
A traditional program often operates by acting on data structures, for example changing fields in an
array or record. In contrast, an object oriented program requests data structures to perform a service.
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.
Classes Hierarchies
A graphical representation is often used to illustrate the relationships among the classes
(objects) of a community. This graphical representation shows classes listed in a hierarchical tree-like
structure. In this more abstract class listed near the top of the tree, and more specific classes in the
middle of the tree, and the individuals listed near the bottom.
This technique shows classes listed in a hierarchical tree-like structure, with more abstract
classes (such as Material Object or Animal) listed near the top of the tree, and more specific classes,
and finally individuals, are listed near the bottom.
Classes can be organized into a hierarchical inheritance structure. A child class (or subclass)
will inherit attributes from a parent class higher in the tree. An abstract parent class is a class (such as
Mammal) for which there are no direct instances; it is used only to create subclasses.
In the class hierarchy, both parent and child classes may have the same method which
implemented individually. Here, the implementation of the parent is overridden by the child. Or a
class may provide multiple definitions to a single method to work with different arguments
(overloading).
The search for the method to invoke in response to a request (message) begins with the class
of this receiver. If no suitable method is found, the search is performed in the parent class of it. The
search continues up the parent class chain until either a suitable method is found or the parent class
chain is exhausted. If a suitable method is found, the method is executed. Otherwise, an error message
is issued.
Everything is an object.
An object is a runtime entity in an object oriented programming
Computation is performed by objects communicating with each other.
Objects communicate by sending and receiving messages.
A message is a request for action bundled with whatever arguments may be necessary to
complete the task.
Each object has its own memory, which consists of other objects.
Every object is an instance of a class.
A class simply represents a grouping of similar objects, such as integers or lists.
The class is the repository for behavior associated with an object.
That is, all objects that are instances of the same class can perform the same actions.
Classes are organized into a singly rooted tree structure, called the inheritance hierarchy.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
Memory and behavior associated with instances of a class are automatically available to any
class associated with a descendant in this tree structure.
1. Objects
2. Classes
3. Data abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Overloading
8. Dynamic binding
9. Message passing
OBJECTS:
Objects are the basic run-time entities in an object-oriented system. They may represent
a person, a place, a bank account, a table of data or any item that the program must handle.
The fundamental idea behind object oriented approach is to combine both data and function
into a single unit and these units are called objects.
The term objects means a combination of data and program that represent some real word
entity.
For example: consider an example named kumar. kumar is 25 years old and his salary is 25000. The
Kumar may be represented in a computer program as an object. The data part of the object would be
(name: Kumar, age: 25, salary: 25000)
The program part of the object may be collection of programs (retrive of data, change age,
change of salary). In general even any user –defined type-such as employee may be used. In the Amit
object the name, age and salary are called attributes of the object.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
CLASS:
A class can be considered as a blue print of object. A group of objects that share common
properties for data part and some program part are collectively called as class.
Class is a collection of objects of similar type. Objects are variables of the type of class. Once
a class has been defined, we can create any number of objects belonging to that class.
DATA ABSTRACTION :
Abstraction is the process of hiding the internal details of an application from the outer world.
Classes use the concept of abstraction and are defined as size, width and cost and functions to operate
on the attributes.
Types of Abstraction
There are two types of abstraction.
1. Data Abstraction
2. Process Abstraction
DATA ENCAPSULATION :
The wrapping up of data and function into a single unit (called class) is known as
encapsulation.
Data encapsulation combines data and functions into a single unit called class. Data
encapsulation will prevent direct access to data. The data can be accessed only through methods
(function) present inside the class. The data cannot be modified by an external nonmember function of
a class. Data encapsulation enables data hiding or information hiding.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
INHERITENCE:
Inheritance is a process of creating a new class from the base class. Inheritance is the process
by which objects of one class acquire the properties of another class. In the concept of inheritance
provides the idea of reusability.
POLYMORPHISIM:
The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism is a person who at the same time can have different characteristics.
A man at the same time is a father, a husband, and an employee. So the same person
exhibits different behavior in different situations. This is called polymorphism. Polymorphism is
considered one of the important features of Object-Oriented Programming.
Types of Polymorphism
Compile-time Polymorphism
Runtime Polymorphism
OVERLOADING:
Overloading allows objects to have different meaning depending uponcontext. There are 2
types of overloading namely
1. Operator overloading
2. Function overloading
When an existing operator operates on new data type, it is called operator overloading.
Function overloading means two or more functions have same name ,but differ in the number of
arguments or data type of arguments. Therefore it is said that (function name) is overloaded. Function
overloading therefore is the process of defining same function name to carry out similar types of
activities with various data items.
DYNAMIC BINDING:
Binding is the process of connecting one program to another. Dynamic binding means code
associated with a procedure call is known only at the time of program execution routine.
MESSAGE PASSING:
An object oriented program consists of a set of objects that communicate with each other.
A message for an object is a request for execution of a procedure and therefore will invoke a
function (procedure) in the receiving object that generates the desired result. Message passing
involves specifying the name of the object, the name of the function (message) and information to be
sent.
1. Encapsulation:
Encapsulation is the bundling of data and the methods that operate on that data into a single
unit, known as a class. It hides the internal details of the object and exposes only what is necessary.
This reduces complexity by providing a clear interface and allowing changes to be made within the
class without affecting the external code.
2. Abstraction:
Abstraction involves simplifying complex systems by modeling classes based on the essential
properties and behaviors they share. It allows developers to focus on the relevant details while
ignoring unnecessary complexities. Abstraction also enables the creation of abstract classes and
interfaces, which define common behaviors without specifying the implementation details.
3. Inheritance:
Inheritance allows a class to inherit properties and behaviors from another class. This
promotes code reuse and helps manage complexity by creating a hierarchy of classes. Common
functionalities can be defined in a base class, and more specific classes can inherit from it, inheriting
and extending its features.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
4. Polymorphism:
Polymorphism allows objects to be treated as instances of their base class rather than their
specific class type. This simplifies code by enabling the use of a common interface for different types
of objects. Polymorphism can take the form of method overloading or method overriding.
5. Modularity:
OOP promotes modularity by breaking down a complex system into smaller, manageable
modules or classes. Each class is responsible for a specific aspect of the system, making it easier to
understand, test, and maintain.
6. Message Passing:
Objects in OOP communicate by sending messages to each other. This message passing
mechanism helps in reducing complexity by encapsulating the interactions between objects. Objects
only need to know the interface of the objects they interact with, not their internal details.
OOP encapsulates both state (data) and behavior (methods) within objects. This encapsulation
helps in managing complexity by keeping related data and methods together, making it easier to
understand and modify the behavior of objects.
OVERVIEW OF JAVA:
Java is a programming language created by James Gosling from Sun Microsystems in 1991. Java
allows to write a program and run it on multiple operating systems.
Java Terminology
1. Java Compiler: The JDK includes the Java compiler (javac), which converts Java source code
(.java files) into byte code (.class files) that can be executed by the Java Virtual Machine (JVM).
VM (Java Virtual Machine): The JVM is a virtual machine that executes Java bytecode. It provides an
environment for running Java programs and translates the bytecode into machine code that can be
understood by the underlying hardware.
The Java Development Kit (JDK) is a software development environment used for developing Java
applications. It includes a set of tools, libraries, and compilers that are necessary for writing,
compiling, and running Java programs.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
The JRE is a subset of the JDK and includes the JVM, libraries, and other files necessary for running
Java applications. It does not contain the development tools (such as the compiler) included in the
JDK.
The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features which play
an important role in the popularity of this language. The features of Java are also known as java
buzzwords.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
1. Simple:
2. Object-Oriented:
3. Platform independent:
A program or technology is said to be platform independent if and only if which can run on
all available operating systems with respect to its development and compilation.
4.Secured:
It is more secured language compare to other language; in this language all code is converted
into byte code after compilation which is not readable by human.
5.Robust:
6. Architecture neutral:
7. Portable:
If any language supports platform independent and architectural neutral feature known as
portable. The languages like C, CPP, and Pascal are treated as non-portable language. It is a portable
language.
8. Dynamic:
It supports Dynamic memory allocation, due to this memory wastage is reduced and
performance of application is improved. The process of allocating the memory space to the input of
the program at a run-time is known as dynamic memory allocation. To allocate memory space
dynamically we use an operator called 'new'. 'new' operator is known as dynamic memory allocation
operator.
9. Interpreted:
11. Multithreaded:
A flow of control is known as thread. When any Language executes multiple threads at a time
that language is known as multithreaded Language. It is multithreaded Language.
12. Distributed:
Using this language we can create distributed application. RMI and EJB are used for creating
distributed applications. In distributed application multiple client system are depends on multiple
server systems so that even problem occurred in one server will never be reflected on any client
system.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
There are mainly 4 type of applications that can be created using java
a. Standalone Application:
It is also known as desktop application or window-based application. An application that we
need to install on every machine such as media player, antivirus etc. AWT and Swing are used in java
for creating standalone applications.
b. Web Application:
An application that runs on the server side and creates dynamic page, is called web
application. Currently, Servlet, JSP, struts, JSF etc. technologies are used for creating web
applications in java.
c. Enterprise Application:
An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for creating
enterprise applications.
d. Mobile Application:
An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.
Data Types in Java:
Data type is a special keyword used to allocate sufficient memory space for the data, in other
words Data type is used for representing the data in main memory (RAM) of the computer.
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
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
The primitive data types include Boolean, char, byte, short, int, long, float and double.
1. Integers: This group includes byte, short, int, and long, which are for whole-valued signed
numbers.
2. Floating-point numbers: This group includes float and double, which represent numbers with
fractional precision.
3. Characters: This group includes char, which represents symbols in a character set, like letters and
numbers.
4. Boolean: This group includes Boolean, which is a special type for representing true/false values.
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:
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
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
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:
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:
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:
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:
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
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:
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:
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
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.
Example:
double d1 = 12.3
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:
System.out.println("Hello world!");
Example
Obj.display();
}}
A package is a collection of classes, interfaces and sub-packages. A sub package contains collection
of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and this
package is known as default package.
Class is keyword used for developing user defined data type and every java program must start with a
concept of class.
"ClassName" represent a java valid variable name treated as a name of the class each and every class
name in java is treated as user-defined data type.
Data member represents either instance or static they will be selected based on the name of the class.
User-defined methods represents either instance or static they are meant for performing the
operations either once or each and every time.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
Block of statements represents set of executable statements which are in term calling user-defined
methods are containing business-logic.
The file naming conversion in the java programming is that which-ever class is containing main()
method, that class name must be given as a file name with an extension .java.
A java Program is made up of Classes and Methods and in the Methods are the Container of
the various Statements And a Statement is made up of Variables, Constants, operators etc .
Tokens are the various Java program elements which are identified by the compiler and
separated by delimiters. The delimiters are not part of the tokens. A token is the smallest element of a
program that is meaningful to the compiler. The compiler breaks lines into chunks of text called
tokens.
Keywords
Identifiers or names
Literals
Separators
Operators
KEYWORDS:
These are special words defined in Java and represent a set of instructions.
The keywords represent groups of instructions for the compiler.
• These are special tokens that have a predefined meaning and their use is restricted.
• keywords cannot be used as names of variables, methods, classes, or packages.
• These are written in the lower case.
• Keywords of Java Language are as follows:
IDENTIFIERS OR NAMES:
Identifier is the name of variables, methods, classes etc. Rules for framing Names or
Identifiers.
It should be a single word which contains alphabets a to z or A to Z, digits 0 to 9, underscore
(_).
It should not contain white spaces and special symbols.
It should not be a keyword of Java.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
SEPARATORS:
These include comma, semicolon, period(.), Parenthesis (), Square brackets [], etc
VARIABLES:
It is an identifier that denotes a storage location used to store a data value. A variable provides us with
named storage that our programs can manipulate.
As mentioned earlier, variable names may consist of alphabets, digits, the underscore ( _) and dollar
characters, subject to the following conditions:
Declaration of Variables:
In Java, variables are the names of storage locations. After designing suitable variable names, we must
declare them to the compiler.
Variables are separated by commas. A declaration statement must end with a semicolon. Some valid
declarations are:
Example:
Local variables
Instance variables
Class/static variables
Example:
class A
{
int data=50; //instance variable
static int m=100; //static variable
void method( )
{
int n=90; //local variable
}
} // end of class
Local Variable:
A variable declared inside the body of the method is called local variable.
There is no default value for local variables so local variables should be declared and an initial
value should be assigned before the first use.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
Example:
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to
this method only.
int age = 0;
age = age + 7;
test.pupAge();
Output:
Instance Variable:
A variable declared inside the class but outside the body of the method, is called instance variable. It
is not declared as static.
Instance variables are created when an object is created with the use of the keyword 'new' and dest
royed when the object is destroyed.
Instance variables have default values. For numbers the default value is 0
Instance variables can be accessed directly by calling the variable name inside the class.
Class/Static variable:
Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block.
Static variables are created when the program starts and destroyed when the program stops.
Static variables can be accessed by calling with the class name . ClassName.VariableName.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
The scope of a variable refers to the areas or the sections of the program in which the variable
can be accessed, and the lifetime of a variable indicates how long the variable stays alive in the
memory.
The scope and lifetime of a variable is “how and where the variable is defined.”
JAVA ARRAYS
An array is a collection of similar data types with a contiguous memory location. It is used to
store multiple values in a single variable instead of declaring separate variables for each value. It is
also known as static data structure because size of an array must be specified at the time of its
declaration.
Arrays are indexed, meaning each array element has a specific position (also called index)
that is used to access it. Array starts from zero index and goes to n-1 where n is length of the array.
One-Dimensional Arrays.
Multi-Dimensional Arrays.
One-Dimensional Arrays:
Syntax:
dataType[] arr;
dataType []arr;
dataType arr[];
Example:
class Testarray1
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}}
Output : 33
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
Multi-Dimensional Arrays
In Java, a multidimensional array is an array of arrays. It is a data structure that allows you to store
multiple arrays in a single array. The most common types of multidimensional arrays are two-
dimensional (2D) and three-dimensional (3D) arrays, but Java also supports arrays with more than
three dimensions. These types of arrays are also known as jagged arrays.
Syntax
<data-type>[][] <variable-name>
<data-type> <variable-name>[][]
class array2d
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
for(int j=0;j<3;J++)
System.out.print(arr[i][j]+" ");
System.out.println();
}}}
Output:1 2 3
245
445
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
Jagged Array:
Jagged array is an array that has different numbers of columns elements. In java, a jagged
array means to have a multi-dimensional array with uneven size of columns in it.
At the time of array creation compulsory we should specify the size otherwise we will get
compile time error.
It is legal to have an array with size zero in java.
The allowed data types to specify array size are byte, short, char, int. By mistake if we are
using any other type we will get compile time error.
The maximum allowed array size in java is maximum value of int size [2147483647].
class twodarrayaddition
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
System.out.println();//new line
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
}}}
Output : 2 6 8
6 8 10
TYPE CONVERSION
Type conversion is a process in which the data type is automatically converted into another
data type.
The compiler does this automatic conversion at compile time. This type of type conversion is also
called Widening Type Conversion/ Implicit Conversion/ Casting Down.
For type conversion to take place, the destination data type must be larger than the source type. In
short, the below flow chart has to be followed.
In this case, as the lower data types with smaller sizes are converted into higher ones with a larger
size, there is no chance of data loss. This makes it safe for usage.
TYPE CASTING
Type casting is a process in which the programmer manually converts one data type into
another data type. For this the casting operator (), the parenthesis is used. Type casting is also
called Narrowing Type Casting/ Explicit Conversion/ Casting Up.
This case, as the higher data types with a larger size are converted into lower ones with a smaller size,
there is a chance of data loss.
Java Expressions
An expression is a series of variables, operators, and method calls that evaluates to a single value.
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.
In the java programming language, expressions are divided into THREE types. They are as follows.
Infix Expression
Postfix Expression
Prefix Expression
Infix Expression
The expression in which the operator is used between operands is called infix expression.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
OPERATORS
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. They usually form a part of mathematical or logical expressions.
Arithmetic Operators
Relational operators
Logical operators
Assignment operators
Increment and decrement operators
Conditional operators
Bitwise operators
Special operators
Arithmetic Operators:
Relational Operators
We often compare two quantities, and depending on their relation, take certain decisions. For
example, we may compare the age of two persons, or the price of two items, and so on. These
comparisons can be done with the help of relational operators.
a < b or x < 20
Logical Operators
The logical operators && and | | are used when we want to form compound conditions by combining
two or more relations. An example is:
a > b && x == 10
An expression of this kind which combines two or more relational expressions is termed as a logical
expression or a compound relational expression.
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, Java has a set of ‘shorthand’ assignment
operators which are used in the form
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
where v is a variable, exp is an expression and op is a Java binary operatory. The operator op
= is known as the shorthand assignment operator.
Java has two very useful operators not generally found in many other languages. These are the
increment and decrement operators.
++ and ––
Conditional Operator
The character pair ? : is a ternary operatory available in Java. This operator is used to
construct conditional expressions of the form
The operator ? : works as follows: exp1 is evaluated first. If it is nonzero (true), then the expression
exp2 is evaluated and becomes the value of the conditional expression. If exp1 is false, exp3 is
evaluated and its value becomes the value of the conditional expression. None that only one of the
expressions (either exp2 or exp3) is evaluated. For example, consider the following statements:
In this example, x will be assigned the value of b. This can be achieved using the if….else statement
as follows:
if(a > b)
x = a;
else
x = b;
Bitwise Operators:
Java has a distinction of supporting special operators known as bitwise operators for
manipulation of data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or left. Bitwise operators
may not be applied to float or double.
Java supports some special operators of interest such as instanceof operatory and member selection
operator (.).
The instanceof is an object operator and returns true of the object on the left-hand side is an instance
of the class given on the right-hand side. This operator allows us to determine whether the object
belongs to a particular class or not.
CONTROL STATEMENTS
The Java selection statements allow your program to choose a different path of execution
based on a certain condition. Java selection statements provide different type of statements such as:
1. if statement.
2. if-else statement.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
4. nested if statement.
if Statement:
Syntax:
if(condition)
Statement(s);
Flowchart:
Example
int num=70;
}}
Output:
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
if-else Statement:
if statement is used to decide whether a certain statement or block of the statement will be
executed or not. If a certain condition is true, then the block of statement is executed, otherwise not.
But, if you want to do something else if the condition is false then we should use else statement. We
can use else statement with if statement to execute the block of code when the condition is false.
Syntax:
if(condition)
else{
int num=120;
else
}}}
Output:
if-else-if Statement:
if-else-if statement is used when we need to check multiple conditions. As soon as one of the
conditions controlling the if is true, the statement associated with that if is executed, If none of the
conditions is true, then the final else statement will be executed. The final else acts as a default
condition; that is, if all other conditional tests fail, then the last else statement is performed.
Syntax
if(condition1)
{
//statement1;
}
else if(condition2)
{
//statement2;
}
else if(condition3)
{
//statement3;
}
.........
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
.........
.........
Else
{
//default statement;
}
Example:
public class IfElseIfExample
{
public static void main(String args[])
{
int num=1234;
if(num <100&&num>=1)
{
System.out.println("Its a two digit number");
}
else if(num <1000&&num>=100)
{
System.out.println("Its a three digit number");
}
else if(num <10000&&num>=1000)
{
System.out.println("Its a four digit number");
}
else if(num <100000&&num>=10000)
{
System.out.println("Its a five digit number");
}
Else
{
System.out.println("number is not between 1 & 99999");
}
}
}
Output:
Nested if statement:
When there is an if statement inside another if statement then it is called the nested if statement.
Syntax:
if(condition1){
if(condition2){
Example
Switch case statement is used when we have number of options (or choices) and we may need to
perform a different task for each choice.
A switch statement can work with byte, short, char, and int primitive data types. It also works with
enumerated types and the String class.
The value of the expression is compared with each of the literal values in the case statements.
If a match is found, the code sequence following that case statement is executed. If none of the
constants matches the value of the expression, then the default statement is executed.
The default statement is optional.
The break statement is used inside the switch to terminate a statement sequence.
Syntax
switch(expression)
{
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
case value1:
//statement sequence
break;
case value2:
//statement sequence
break;
.......
.......
.......
case valueN:
//statement sequence
break;
default:
//default statement sequence
}
Example
class WeekDays
{
public static void main(String s[])
int day = 2;
switch(day)
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid");
break;
}}}
Java Iteration statements allow program execution to repeat one or more statements. java Iteration
statements provide different type of statements such as:
1. For loop.
2. While loop.
3. Do While loop.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
1. For loop.
Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
The for loop in java is used to iterate a part of the program several times.
The Java for loop consumes initialization, condition, and increment/decrement in one line.
Syntax
condition: In this step, we can check the condition. If the condition is true, then the body of the loop
is executed otherwise not.
class ForLoop
{
public static void main(String args[]){
System.out.println("The values from 1 to 10 is: ");
While Loop:
The while loop in java is the most fundamental looping statement. Java while loop repeats a
statement or a block while a particular condition is true. You can use a while loop if the number of
iteration is not fixed.
Syntax
while(boolean condition)
{
//body of the loop.
}
class WhileLoopExample
{
public static void main(String args[])
{
int i=10;
while(i>1)
{
System.out.println(i);
i--;
}}}
Output:
10
9
8
7
6
5
4
3
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
Do While loop:
do-while loop is similar to while loop. In while loop, condition is evaluated before the execution of
loop’s body but in do-while loop condition is evaluated after the execution of loop’s body.
Do
{
statement(s);
}
while(condition);
class DoWhileLoopExample
{
public static void main(String args[])
{
int i=10;
do
{
System.out.println(i);
i--;
}
while(i>1);
}}
Output:
10
9
8
7
6
5
4
3
2
Jump Statements:
Java Jump statements transfer the control to other parts of the program. java Jump statements
provide different type of statements such as:
1. break statement.
2. continue statement
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
break statement
Java break statement can be used to terminate the loop. It can be used inside a loop. We can use a
break statement in all types of loops such as: while loop, do-while loop, and for loop. When a break
statement is encountered inside a loop, the loop is terminated and the program control goes to the next
statement following the loop.
break;
case 3:
System.out.println("Case 3 ");
break;
default:
System.out.println("Default ");
}}}
continue statement:
Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control
directly jumps to the beginning of the loop for next iteration, skipping the execution of statements
inside loop’s body for the current iteration.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
Introducing Classes:
Class fundamentals
How to create classes by using the following basics:
The parts of a class definition
Declaring and using instance variables
Defining and using methods
Creating Java applications, including the main() method and how to pass arguments to a Java
program from a command line
method;
}
Declaration of Object and its initialization
To create an object of the class we use new keyword as shown below syntax
classname objectname=new classname( );
1. By reference variable
2. By method
3. By constructor
class Student
int id;
String name;
class TestStudent2
s1.id=101;
s1.name="Sonoo";
}}
}
}
class TestStudent4{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}}
Output:
111 Karan
222 Aryan
Object and Class Example: Initialization through a constructor
class Employee
{
int id;
String name;
float salary;
void insert(int i, String n, float s)
{
id=i;
name=n;
salary=s;
}
void display()
{
System.out.println(id+" "+name+" "+salary);
}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}}
Output:
101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0
DIFFERENCE BETWEEN OBJECT AND CLASS
OBJECT CLASS
Object is an instance of a class. Class is a blueprint or template from which
objects are created.
Object is a real world entity such as pen, laptop, Class is a group of similar objects.
mobile, bed, keyboard, mouse, chair etc.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
Method in Java
A method is a block of statements. A method is like a function which is used to expose the behavior
of an object. Every method is used to perform a specific task. a method defined as a behavior of an
object.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.
Advantage of Method
Code Reusability
Code Optimization
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.
Syntax:
class <ClassName>
...
block of statements;
...
}}
//where we deposit and withdraw amount from our account. //Creating an Account class which
has deposit() and withdraw() methods
class Account
int acc_no;
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
String name;
float amount;
acc_no=a;
name=n;
amount=amt;
//deposit method
amount=amount+amt;
System.out.println(amt+" deposited");
//withdraw method
if(amount<amt){
System.out.println("Insufcient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}}
class TestAccount{
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}
Output:
40000.0 deposited
15000.0 withdrawn
The String class defined in the package java.lang package. The String class
implements Serializable, Comparable, and CharSequence interfaces.
String literal:
In java, Strings can be created like this: Assigning a String literal to a String instance:
In Java, the access specifiers (also known as access modifiers) used to restrict the scope or
accessibility of a class, constructor, variable, method or data member of class and interface. There are
four access specifiers, and their list is below.
The private members can be accessed only inside the same class.
The protected members are accessible to every child class (same package or other packages).
The default members are accessible within the same package but not outside the package.
Example:
class ParentClass
{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData()
{
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class ChildClass extends ParentClass{
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
}}
CONSTRUCTORS IN JAVA
Constructors are used to initialize the state of an object when it is created.
Constructors are invoked while creating objects, usually after the new keyword. Every time
an Object is created using the new() keyword, at least one constructor is called.
It is called when an instance of the class is created. At the time of calling constructor, memory
for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Default Constructor:
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>()
{}
Example:
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}}
Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
The parameterized constructor is used to provide diferent values to distinct objects.
Example
class Student4
{
int id;
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
String name;
Student4(int i,String n) //creating a parameterized constructor
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]) //creating objects and passing values
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display(); //calling method to display the values of object
s2.display();
}}
CONSTRUCTOR OVERLOADING
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different task.
Example
class Student5
{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n)
{
id = i;
name = n;
}
//creating three arg constructor
COPY CONSTRUCTOR
There is no copy constructor in java. But, we can copy the values of one object to another like
copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
//Java program to initialize the values from one object to another object.
class Student6
{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n)
{
id = i;
name = n;
}
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
ABSTRACT CLASSES
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its method
implemented.
Syntax:
ABSTRACT METHOD
A method that is declared as abstract and does not have implementation is known as abstract
method. The method body will be defined by its subclass.
Syntax:
The Object class is the parent class of all the classes in java by default (directly or indirectly).
The java.lang.Object class is the root of the class hierarchy. Some of the Object class are Boolean,
Math, Number, String etc.
GARBAGE COLLECTION
The Garbage Collection (GC) feature in the Java Virtual Machine (JVM). Java garbage
collection is the process by which Java programs perform automatic memory management. Java
programs compile to bytecode that can be run on a Java Virtual Machine. When Java programs run on
the JVM, objects are created on the heap, which is a portion of memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage collector finds these unused objects
and deletes them to free up memory.
Java garbage collection is an automatic process. The programmer does not need to explicitly mark
objects to be deleted.
Java developers don't need to explicitly free memory as in languages like C or C++. The garbage
collector takes care of deallocating memory.
2. Heap Memory:
The memory allocated for Java objects is managed in the heap. The heap is divided into two main
areas: the Young Generation and the Old Generation.
Java's garbage collector uses a generational garbage collection algorithm. Objects are initially created
in the Young Generation. The objects that survive multiple garbage collection cycles in the Young
Generation are eventually moved to the Old Generation.
Java Virtual Machines may use different garbage collector implementations, such as Serial, Parallel,
CMS (Concurrent Mark-Sweep), G1 (Garbage First), and more.
The choice of garbage collector depends on factors like application requirements, available hardware,
and JVM version.
Java provides options to tune garbage collection to meet specific application requirements. This can
include setting parameters related to the heap size, garbage collector algorithm, and other options.
Various tools, like VisualVM, JConsole, and others, allow developers to monitor and analyze the
behavior of the garbage collector and overall memory usage.
While developers don't explicitly manage memory, they can still influence garbage collection
behavior by writing efficient code, avoiding memory leaks, and tuning JVM parameters.
8. Memory Leaks:
Despite garbage collection, memory leaks can occur if references to objects are unintentionally
maintained, preventing them from being garbage collected. Developers need to be mindful of
managing references appropriately.
1. Automation and simplification: Automatic garbage collection in Java takes the burden off
developers. In contrast, languages like C or C++ require explicit memory allocation and
deallocation, which can be error-prone and lead to crashes if not handled properly.
2. Increased Developer Productivity: With automatic memory management, developers can focus
on writing application logic, leading to faster development cycles.
3. Preventing OutOfMemoryError: By automatically tracking and removing unused objects,
garbage collection prevents memory-related errors like OutOfMemoryError errors.
4. Eliminates dangling pointer bugs: These are bugs that occur when a piece of memory is freed
while there are still pointers to it, and one of those pointers is dereferenced. By then the memory
may have been reassigned to another use with unpredictable results.
5. Eliminates Double free bugs: These happen when the program tries to free a region of memory
that has already been freed and perhaps already been allocated again.
POLYMORPHISM
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java:
1. Compile-time polymorphism or Ad hoc polymorphism
2. Runtime polymorphism. Or Pure polymorphism
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
Example
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2(); //creating object
obj.run(); //calling method
}}
Output: Bike is running safely
Parameter passing refers to the process of providing input values to a function or method
when it is called during program execution. In programming, parameters are variables or values that
are used to pass information into a function or method.
1. Pass by value
2. Pass by reference
Pass by value:
In pass-by-value, the actual value of the parameter is passed to the function or method. This
means that changes made to the parameter inside the function or method do not affect the original
value in the calling code.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
This method is commonly used for primitive data types like integers, floats, and booleans.
Example:
class Swapper
{
int a;
int b;
Swapper(int x, int y)
{
a = x;
b = y;
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
}
class SwapDemo
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20);
System.out.println("Before swapping value of a is "+obj.a+" value of b is "+obj.b);
obj.swap(obj.a, obj.b);
System.out.println("After swapping value of a is "+obj.a+" value of b is "+obj.b);
}
}
Output:
Before swapping value of a is 10 value of b is 20
After swapping value of a is 10 value of b is 20
Pass-by-Reference:
This method is commonly used for objects and complex data structures.
class Swapper
int a;
int b;
Swapper(int x, int y)
a = x;
b = y;
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
int temp;
temp = ref.a;
ref.a = ref.b;
ref.b = temp;
class SwapDemo
obj.swap(obj);
}}
Output:
RECURSION:
Syntax:
returntype methodname()
{ //code to be executed
methodname(); //calling same method
}
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
In the above example, we have called the recurse() method from inside the main method.
(normal method call). And, inside the recurse() method, we are again calling the same recurse method.
This is a recursive call.
Example
} }
Java Nested and Inner Class
The Java language allows you to define a class within another class.
class OuterClass
{ // ...
class NestedClass
{ // ...
}}
Types of Nested Classes:
Static Nested Class (Static Inner Class)
Inner Class (Non-static Nested Class)
Anonymous Inner Class
class InnerClass {
}}
Often used for one-time use, such as implementing an interface or extending a class.
{
// Implementation
}
}; }}
String Operations
Method Description
char charAt(int index) It returns char value for the particular index
int length() It returns string length
static String format(String format, Object... args) It returns a formatted string.
static String format(Locale l, String format, Object... args) It returns formatted string with given locale.
String substring(int beginIndex) It returns substring for given begin index.
It returns substring for given begin index and
String substring(int beginIndex, int endIndex)
end index.
It returns true or false after matching the
boolean contains(CharSequence s)
sequence of char value.
static String join(CharSequence delimiter, CharSequence...
It returns a joined string.
elements)
static String join(CharSequence delimiter, Iterable<?
It returns a joined string.
extends CharSequence> elements)
It checks the equality of string with the given
boolean equals(Object another)
object.
boolean isEmpty() It checks if string is empty.
String concat(String str) It concatenates the specified string.
It replaces all occurrences of the specified
String replace(char old, char new)
char value.
It replaces all occurrences of the specified
String replace(CharSequence old, CharSequence new)
CharSequence.
It compares another string. It doesn't check
static String equalsIgnoreCase(String another)
case.
String[] split(String regex) It returns a split string matching regex.
It returns a split string matching regex and
String[] split(String regex, int limit)
limit.
String intern() It returns an interned string.
int indexOf(int ch) It returns the specified char value index.
It returns the specified char value index
int indexOf(int ch, int fromIndex)
starting with given index.
int indexOf(String substring) It returns the specified substring index.
It returns the specified substring index starting
int indexOf(String substring, int fromIndex)
with given index.
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
charAt() method
String charAt() function returns the character located at the specified index.
public class Demo
{
public static void main(String[] args) {
String str = "studytonight";
System.out.println(str.charAt(2));
}}
Output: u
NOTE: Index of a String starts from 0, hence str.charAt(2) means third character of the String str.
equalsIgnoreCase() method
String equalsIgnoreCase() determines the equality of two Strings, ignoring their case (upper
or lower case doesn't matter with this method).
public class Demo
{
public static void main(String[] args)
{
String str = "java";
System.out.println(str.equalsIgnoreCase("JAVA"));
}}
Output:
True
concat() method:
We can join two strings in Java using the concat() method. The concat() method joins
the second string to the first string and assigns it to the joinedString variable.
We can also join two strings using the + operator in Java. To learn more, visit Java String concat().
class Main
{
public static void main(String[] args)
{
// create first string
String first = "Java ";
System.out.println("First String: " + first);
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}
}
Output
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
replace() method
String replace() method replaces occurances of character with a specified new character.
public class Demo {
public static void main(String[] args) {
String str = "Change me";
System.out.println(str.replace('m','M'));
}}
OUTPUT:
Change Me
substring() method
String substring() method returns a part of the string. substring() method has two override methods.
1. public String substring(int begin);
2. public String substring(int begin, int end);
public class Demo {
public static void main(String[] args) {
String str = "0123456789";
System.out.println(str.substring(4));
System.out.println(str.substring(4,7));
}}
OUTPUT:
Abcdef
toUpperCase() method
This method returns string with all lowercase character changed to uppercase.
public class Demo {
(R22) II YEAR I SEMESTER OOPS THROUGH JAVA
valueOf() method
String class uses overloaded version of valueOf() method for all primitive data types and for type
Object.
NOTE: valueOf() function is used to convert primitive data types into Strings.
public class Demo {
public static void main(String[] args) {
int num = 35;
String s1 = String.valueOf(num); //converting int to String
System.out.println(s1);
System.out.println("type of num is: "+s1.getClass().getName());
}}
OUTPUT:
35
type of num is: java.lang.String
toString() method
String toString() method returns the string representation of an object. It is declared in the
Object class, hence can be overridden by any java class. (Object class is super class of all java
classes).
public class Car {
public static void main(String args[])
{
Car c = new Car();
System.out.println(c);
}
public String toString()
{
return "This is my car object";
}}
OUTPUT:
This is my car object
trim() method
This method returns a string from which any leading and trailing whitespaces has been removed.
boolean b = a.contains("studytonight.com");
System.out.println(b);
System.out.println(a.contains("javatpoint"));
}}
OUTPUT:
true
false
endsWith() Method
String endsWith() method is used to check whether the string ends with the given suffix or
not. It returns true when suffix matches the string else it returns false.
public class Demo {
public static void main(String[] args) {
String a="Hello welcome to studytonight.com";
System.out.println(a.endsWith("m"));
System.out.println(a.endsWith("com"));
}}
OUTPUT:
true
true
format() Method
String format() is a string method. It is used to the format of the given string.
System.out.println(ex);
} }}
OUTPUT:
Welcom
isEmpty() Method
String isEmpty() method is used to check whether the string is empty or not. It returns true when
length string is zero else it returns false.