You are on page 1of 58

Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269

banand.cool@gmail.com

Object Oriented Thinking:

Everywhere you look in the real world you see objects—people, animals, plants, cars, planes,
buildings, computers and so on. Humans think in terms of objects. Telephones, houses, traffic
lights, microwave ovens and water coolers are just a few more objects. Computer programs, such
as the Java programs you’ll read in this book and the ones you’ll write, are composed of lots of
interacting software objects.

Object-Oriented:
Although influenced by its predecessors, Java was not designed to be source-code compatible
with any other language. This allowed the Java team the freedom to design with a blank slate.
One outcome of this was a clean, usable, pragmatic approach to objects. Borrowing liberally
from many seminal object-software environments of the last few decades, Java manages to strike
a balance between the purist’s “everything is an object” paradigm and the pragmatist’s “stay out
of my way” model. The object model in Java is simple and easy to extend, while simple types,
such as integers, are kept as high-performance nonobjects.

Languages like Java are object oriented. Programming in such a language is called object-
oriented programming (OOP), and it allows computer programmers to implement an object-
oriented design as a working system. Languages like C, on the other hand, are procedural, so
programming tends to be action oriented. In C, the unit of programming is the function.
Groups of actions that perform some common task are formed into functions, and functions are
grouped to form programs.

Classes can have relationships with other classes. For example, in an object-oriented design of a
bank, the “bank teller” class needs to relate to the “customer” class, the “cash drawer” class, the
“safe” class, and so on. These relationships are called associations.

NEED FOR OOP PARADIGM:


Object-Oriented Programming:
Object-oriented programming is at the core of Java. In fact, all Java programs are object-
oriented—this isn’t an option the way that it is in C++, for example. OOP is so integral to Java.
Therefore, this chapter begins with a discussion of the theoretical aspects of OOP.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Two Paradigms of Programming:


As you know, all computer programs consist of two elements: code and data. Further more,a
program can be conceptually organized around its code or around its data. That is, some
programs are written around “what is happening” and others are written around “who is being
affected.” These are the two paradigms that govern how a program is constructed.

Procedure oriented Programming:


In this approach, the problem is always considered as a sequence of tasks to be done. A number
of functions are written to accomplish these tasks. Here primary focus on “Functions” and little
attention on data.

There are many high level languages like COBOL, FORTRAN, PASCAL, C used for
conventional programming commonly known as POP.

Drawback: It does not model real world problems very well, because functions are action
oriented and do not really corresponding to the elements of the problem.

Chars of POP:
➢ Emphasis is on doing actions.
➢ Large programs are divided into smaller programs known as functions.
➢ Most of the functions shared global data.
➢ Data move openly around the program from function to function.
➢ Functions transform data from one form to another.
➢ Employs top-down approach in program design.

OOP:
OOP allows us to decompose a problem into a number of entities called objects and then builds
data and methods around these entities.

DEF: OOP is an approach that provides a way of modularizing programs by creating portioned
memory area for both data and methods that can used as templates for creating copies of such
modules on demand.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

OOP Chars:
➢ Emphasis on data .
➢ Programs are divided into what are known as methods.
➢ Data structures are designed such that they characterize the objects.
➢ Methods that operate on the data of an object are tied together .
➢ Data is hidden.
➢ Objects can communicate with each other through methods.
➢ Reusability.
➢ Follows bottom-up approach in program design.
Organization of OOP:

A way of viewing World-Agents and Responsibility:


Object-oriented languages use objects to encapsulate the details. Each object simulates an object
in real life, carrying state data as well as behaviors. State data are represented as instance data.
Behaviors are represented as methods.

OOP establish the communication between Distributed Objects. It is possible with the help of
clients and servers in the form of agents. It helps for Distributed Applications.

OOP Chars with Distributed Applications:

Inter process Communication: A distributed application require the participation of two or more
independent entities. To do so, the processes must have the ability to exchange data among
themselves.

Event Synchronization: In a distributed application, the sending and receiving of data among the
participants of a distributed application must be synchronized.
◼ A distributed system is a collection of independent computers, interconnected via a
network, capable of collaborating on a task.
◼ Distributed computing is computing performed in a distributed system.
Peer-to-Peer distributed computing: The peer-to-peer paradigm can be implemented with facilities
using any tool that provide message-passing, or with a higher-level tool such as one that supports the
point-to-point model of the Message System paradigm.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

For web applications, the web agent is a protocol promoted by the XNSORG (the XNS Public
Trust Organization) for peer-to-peer inter process communication
“Project JXTA is a set of open, generalized peer-to-peer protocols that allow any connected
device (cell phone, to PDA, PC to server) on the network to communicate and collaborate. JXTA
is short for Juxtapose, as in side by side. It is a recognition that peer to peer is juxtapose to client
server or Web based computing -- what is considered today's traditional computing model. “

The Distributed Objects Paradigms


The idea of applying object orientation to distributed applications is a natural extension
of object-oriented software development.

Applications access objects distributed over a network.


Objects provide methods, through the invocation of which an application obtains access to
services.

Object-oriented paradigms include:


◼ Remote method invocation (RMI)
◼ Network services
◼ Object request broker
◼ Object spaces
MESSAGES:

An OOP consists of objects that communicate with each other. The process of programming in
an object-Oriented language, therefore, involves the basic concepts:

1. Creating classes that define objects and their behavior.


2. Creating objects from class definitions.
3. Establishing communication among objects.

Objects communicate with one another by sending and receiving information much the same
way as people pass messages to one another.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

The concept of message passing makes it easier to talk about building systems that directy model
or simulate their real-world counter parts.
A message for an object is a request for execution of a procedure, and therefore will invoke a
procedure in the receiving object that generates the desired results.

History of Java:
Before Proceeding with java, first we need to know what is a programming language?

A Programming language is an artificial language designed communicate


instructions to a machine, particularly a computer. Programming languages can be used to
create programs that control the behavior of a machine. In history there were many programming
languages, in 1970, the most popular programming language was C. Since C was the most
powerful language many people were using this language. This language was being used in
business applications, scientific applications, artificial applications etc. Since, C has the
procedure oriented programming features, it was having many limitations

Limitations of C are:

• Difficult to implement today's client requirements.


Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

• No code reusability.
• No Code Enhancement
• Platform Dependent
• As length of the application increases, causes slow in performance.
• Code maintenance and enhancements are difficult.
• No Exception Handling mechanisms
In order to solve those disadvantages and new programming paradigm was introduce, named
Object Oriented Programming(OOPs).

OOPs is basically based on objects and classes. OOPs can be defined as grouping of data and
methods. OOPs basically have 4 features.

1. Inheritance
2. Polymorphism
3. Abstraction
4. Encapsulation

During the late 1970s and early 1980s, C became the dominant computer programming
language, but in C complexity was more. The increasing complexity of programs has driven the
need for better ways to manage that complexity. C++ is a response to that need. C++ was
developed from C syntax, all the syntaxes were similar in C++ with C the only change was C++
was having OOPs features. By the end of the 1980s and the early 1990s, object-oriented
programming using C++ took hold. C++ has overcome all the disadvantages of C, but still C++
was having its own disadvantages.

• Pointers.
• Explicitly memory allocation and de allocation.
• Platform Dependent.
Creation Of java:

Java was created by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working
version. This language was initially called “Oak” but was renamed “Java” in 1995. Java’s
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

primary motivation was the need for a platform-independent language that could be used to
create software to be embedded in various consumer electronic devices, such as microwave
ovens and remote controls. The trouble with C and C++ (and most other languages) is that they
are designed to be compiled for a specific target. Although it is possible to compile a C++
program for just about any type of CPU, to do so requires a full C++ compiler targeted for that
CPU. The problem is that compilers are expensive and time-consuming to create. An easier—
and more cost-efficient—solution was needed. In an attempt to find such a solution, Gosling and
others began work on a portable, platform-independent language that could be used to produce
code that would run on a variety of CPUs under differing environments. This effort ultimately
led to the creation of Java.

The Java Buzzwords


• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
Platform independent:
Java is platform independent because java programs are executed by the any operating
system irrespective of its development and compilation. Java program is compiled into bytecode.
This bytecode is platform independent and can be run on any machine, plus this bytecode format
also provide security. Any machine with Java Runtime Environment can run Java Programs.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Simple:
There are various features that makes the java as a simple language. Programs are easy to
write and debug because java does not use the pointers explicitly. The other reason is, if we
know C and C++ then it is very easy to learn java, as we know all the syntaxes and rules of java
are taken from C and C++. It also has the automatic memory allocation and deallocation system.

Secure:

Java provides internal and external security. Internal security is provided by the
JVM(Java Virtual Machine). External security is provided by the developer using cryptographic
techniques(Encryption, Decryption).

Portable:
The feature Write-once-run-anywhere makes the java language portable. Byte code
and JVM in java makes java as a platform independent. Java Byte code can be carried to any
platform. No implementation dependent features. We have different versions of JVM for
different platforms. Windows machines have their own version of JVM, Linux has its own and
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

macOS has its own version of JVM. So if you distribute your bytecode to any machine, the JVM
of that machine would translate the bytecode into the respective machine code.

Object-oriented:
Java is pure Object oriented programming language because everything we write in java
comes under classes and objects. Java is pure object oriented programming language but it is not
100% object oriented programming language because java uses primitive data types which are
defined using C and C++.
The main concepts of any Object Oriented Programming language are given below:
❖ Class and Object
❖ Encapsulation
❖ Abstraction
❖ Inheritance
❖ Polymorphism
Robust:
Java has the strong memory allocation and automatic garbage collection mechanism. It
provides the powerful exception handling and type checking mechanism as compare to other
programming languages. Compiler checks the program whether there any error and interpreter
checks any run time error and makes the system secure from crash. All of the above features
make the java language robust.
Multithreaded:
Java supports multithreaded programming, which allows you to write programs that do
many things simultaneously. Thread is nothing but a piece of program and multithreading means
executing more than one program simultaneously. For example consider an online examination
application, in this application at one side one timer will be running and at the same time
application will be displaying you question with options.
Architecture-neutral:
One of the main problems facing programmers is that no guarantee exists that if you write a
program today, it will run tomorrow—even on the same machine. Operating system upgrades, processor
upgrades, and changes in core system resources can all combine to make a program malfunction. But in
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

java this problem was overcome. We can run java program anytime, anywhere, forever even though
operating system, processor or other system resources upgrades.

Interpreted& High performance:


Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. This code can be executed on any system that implements
the Java Virtual Machine. the Java bytecode was carefully designed so that it would be easy to
translate directly into native machine code for very high performance by using a just-in-time
compiler.
Distributed:
Java is designed for the distributed environment of the Internet, because it handles TCP/IP
and HTTP protocols. Java achieves distributed features by RMI and by Socket Programming.

Dynamic:
Java is a dynamic language. It supports the dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C and C++.
A First Simple Program:

Now that the basic object-oriented underpinning of Java has been discussed, let’s look at some
actual Java programs. Let’s start by compiling and running the short sample program shown
here.

public class Example {


public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}

Write the above program in any text editor or in note pad and save it as Example.java. If we are
declaring our class as a public then we need to give the file name as the class name. If we are not
declaring the class as a public then we can give any name to the file with the extension .java.

Note: before showing compilation show how to set the “path”.


Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

For Compilation use the command

Syntax: javac Filename.java

ex: javac Example.java

For Execution use the command

Syntax: Java Classname

Ex: java Example

Note: For execution we will use the class name not the filename. In a file if we have more than one class
then we will use the class which has main method.

A Closer Look at the First Program:

class Example
This line uses the keyword class to declare that a new class is being defined. Example is an
identifier that is the name of the class. The entire class definition, including all of its members,
will be between the opening curly brace ({) and the closing curly brace (}).
public static void main(String args[])
This line begins the main( ) method. This is the line at which every java program will begin
executing. All Java applications begin execution by calling main( ). (This is just like C/C++.)
The public keyword is an access specifier, which allows the programmer to control the visibility
of class members. When a class member is preceded by public, then that member may be
accessed by code outside the class in which it is declared. (The opposite of public is private,
which prevents a member from being used by code defined outside of its class.) In this case,
main( ) must be declared as public, since it must be called by code outside of its class when the
program is started. The keyword static allows main( ) to be called without having to instantiate a
particular instance of the class. This is necessary since main( ) is called by the Java interpreter
before any objects are made. The keyword void simply tells the compiler that main() does not
return a value.
As main() is a method it takes a array argument of type String. Whenever we are providing
inputs to the program through command line, then those inputs are stored in args[] which is of
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

type String. Whatever input we provide they are taken as String only, later in the program we can
convert.
All methods in java starts with opening curly brace({) and ends with closing curly brace(}).
System.out.println("This is a simple Java program.");
This line outputs the string “This is a simple Java program.” followed by a new line on the
screen. Output is actually accomplished by the built-in println( ) method which is defined in
PrintStream class. System is a predefined class available in java.lang package. In System class
PrintStream object is created with the name out, and this object is a static.
Data types:
Data types can specify the size and different values stored in a variable. Data
types are used to allocate sufficient memory to the variables. Data types represent the different
values to be stored in the variable. In java, there are two types of data types:
o Primitive data types
o Non-primitive data types

Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float, double,
and boolean.

These can be put in four groups:


Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

• Integers: This group includes byte, short, int, and long, which are for whole valued
signed numbers.
• Floating point numbers: This group includes float and double, which represent
numbers with fractional precision.
• Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
• Boolean: This group includes boolean, which is a special type for representing true/false
values.

Datatype Memory Range


Byte 1 byte(8 bits) -27 to 27-1
Short 2 bytes(16 bits) -215 to 215-1
Int 4 bytes(32 bits) -231 to 231-1
Long 8 bytes(64 bits) -263 to 263-1
Float 4 bytes(32 bits) -231 to 231-1
Double 8 bytes(64 bits) -263 to 263-1
Char 2 bytes(16 bits) -215 to 215-1
boolean 1 bit ---------------------------
Primitive data types are capable of holding only one value in a variable at a time.

Non primitive data types are capable of holding more than one value at a time.

Type Conversion and Casting

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. The data type to which the
conversion happens is called the destination data type, and the data type from which the
conversion happens is called the source data type. If the source and destination data types are
compatible, then automatic type conversion takes place.

For type conversion to take place, the destination data type must be larger than the source type.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

public class TypeConversion {

public static void main(String[] args) {

short a = 256; //2 bytes source data type

int b; //4 bytes destination data type

b = a; // a(short)converted to b(int).

System.out.println(b);

float x = 217.55f; //4 bytes source data type

double y; //8 bytes destination data type

y = x; // x(float)converted to y(double).

System.out.println(y);

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. Unlike type conversion, the
source data type must be larger than the destination type in type casting. The below flow chart
has to be followed for successful type casting.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

public class TypeCasting {

public static void main(String[] args) {

int a = 89; //4 bytes source data type

byte b; //1 bytes destination data type

b = (byte)a; // a(int)converted to b(byte).

System.out.println(b);

double x = 963.45; //8 bytes source data type

float y; //4 bytes destination data type

y = (float)x; // x(float)converted to y(double).

System.out.println(y);

Variables:
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime. These elements are examined next.

Declaring a Variable

In Java, all variables must be declared before they can be used. The basic form of a variable

declaration is shown here:

type identifier [ = value][, identifier [= value] ...] ;


The identifier is the name of the variable. You can initialize the variable by specifying an equal
sign and a value. Keep in mind that the initialization expression must result in a value of the
same (or compatible) type as that specified for the variable. To declare more than one variable of
the specified type, use a comma-separated list.

int a, b, c; // declares three ints, a, b, and c.

int d = 3, e, f = 5; // declares three more ints, initializing

// d and f.

byte z = 22; // initializes z.

double pi = 3.14159; // declares an approximation of pi.

char x = 'x'; // the variable x has the value 'x'.


The identifiers that you choose have nothing intrinsic in their names that indicates their type.
Java allows any properly formed identifier to have any declared type.

Rules to declare the variables:


❖ Variable name contains alphabets, digits and underscore( _ ) .
❖ Variable names must start with alphabets or underscore.
❖ Variable name should not contain blanks.
❖ Variable name must not be a keyword.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows variables
to be initialized dynamically, using any expression valid at the time the variable is declared.
For example, here is a short program that computes the length of the hypotenuse of a right
triangle given the lengths of its two opposing sides:
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Here, three local variables—a, b, and c—are declared. The first two, a and b, are initialized by
constants. However, c is initialized dynamically to the length of the hypotenuse (using the
Pythagorean theorem). The program uses another of Java’s built-in methods, sqrt( ), which is a
member of theMath class, to compute the square root of its argument. The key point here is that
the initialization expression may use any element valid at the time of the initialization, including
calls to methods, other variables, or literals.

The Scope and Lifetime of Variables:

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. Java allows variables to be declared within any block. A block is begun
with an opening curly brace and ended by a closing curly brace. A block defines a scope. Thus,
each time you start a new block, you are creating a new scope. Whenever we are creating a
variable within a block, the scope of the variable will be within the block, or in inner blocks.
Note: Scope of a variable means the area in which variable can be used.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Eg:
{ // block 1
int a , b ;
{ // block 2
int c ;
-------;
-------;
}
-------;
-------;
}

In the above example variable a and b can be used in block1 and as well as in block 2. Variable c
can only be used in block 2 but not in block 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. Local variables mainly used for intermediate calculations.
A local variable cannot be defined with "static" keyword.
Scope: Within the block it is declared.
Lifetime: Until control leaves the block in which it is declared.
Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable.
It is called instance variable because its value is instance specific and is not shared among
instances.
Scope: Throughout the class except in the static methods.
Lifetime: Until the object of the class stays in the memory.
Static variable
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

A variable which is declared as static is called static variable. A variable which is declared inside
a class, outside all the blocks and is declared as static is known as class/static variable. It cannot
be local. You can create a single copy of static variable and share among all the instances of the
class. Memory allocation for static variable happens only once when the class is loaded in the
memory.
public class Employee {
private String empId; // Instance variable
private String empName; // Instance variable
private double salary; // Instance variable
private static String company; //static variable
public void display() {
int pincode = 508206; //local variable
System.out.println("Name :"+empName);
System.out.println("ID :"+empId);
System.out.println("Salary :"+salary);
System.out.println("Company :"+company);
System.out.println(pincode);

}
public static void main(String[] args) {
Employee obj1;
obj1 = new Employee();
Employee obj2;
obj2 = new Employee();
obj1.empName = "Santhosh";
obj1.empId = "ID6628";
obj1.salary = 35000.00;
Employee.company = "TCS";
obj2.empName = "Taufeeq";
obj2.empId = "ID6605";
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

obj2.salary = 45000.00;
obj1.display();
obj2.display();
}
}
Output:

Classes and Objects:

Classes are used to bind the data and code into a single container. Class contains data members
and methods. It is a template or blueprint from which objects are created. It is a logical entity. It can't be
physical.

A class in Java can contain:

❖ Fields
❖ Methods
❖ Constructors
❖ Nested class and interface

A simplified general form of a class definition is shown here:

class classname {

type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

// 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, as a general rule, 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.We will come back to this point shortly,
but it is an important concept to learn early.
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. Notice that the general form
of a class does not specify a main( ) method. Java classes do not need to have a main( ) method.

Objects:

Object is nothing but instance of a variable / blue print of a class. Objects have states and
behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the
tail, barking, eating.

Object Definitions:

❖ An object is a real-world entity.


❖ An object is a runtime entity.
❖ The object is an entity which has state and behavior.
❖ The object is an instance of a class

There are three steps when creating an object from a class −


Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

• Declaration − A variable declaration with a variable name with an object type.

• Instantiation − The 'new' keyword is used to create the object.

• Initialization − The 'new' keyword is followed by a call to a constructor. This call


initializes the new object.

Syntax:

class ClassName

-------------------

-------------------

public static void main(String[] args)

ClassName objectName1=new ClassName(); /*This is one way*/

ClassName objectName2;

objectName2=new ClassName(); /*this is anotherway*/

Example:

public class Employee {

private String empId;


Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

private String empName;

private double salary;

public void display() {

System.out.println("Name :"+empName);

System.out.println("ID :"+empId);

System.out.println("Salary :"+salary);

public static void main(String[] args) {

Employee obj1;

obj1 = new Employee();

Employee obj2;

obj2 = new Employee();

obj1.empName = "Santhosh";

obj1.empId = "ID6628";

obj1.salary = 500000.00;

obj1.display();

obj2.display();

}
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Expressions:

An expression is a construct made up of variables, operators, and method invocations,


which are constructed according to the syntax of the language, that evaluates to a single value.
You've already seen examples of expressions, illustrated in bold below:

int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2; // result is now 3
if (value1 == value2)
System.out.println("value1 == value2");

The data type of the value returned by an expression depends on the elements used in the
expression. The expression cadence = 0 returns an int because the assignment operator returns
a value of the same data type as its left-hand operand; in this case, cadence is an int. As you
can see from the other expressions, an expression can return other types of values as well, such
as boolean or String.

Methods:
A Java method is a block of code (collection of statements) that are grouped together to
perform an operation. Methods are having the following syntaxes:
Syntax:
returntype methodname (Parameter-list)
{
Method body/statements
return value;
}
Ex:
int addition (int num1, int num2)
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

{
int result=num1+num2;
return result;
}
Example:
import java.util.*;
class Factorail{
public int getFactorail(int number) {
int fact = 1;
for(int i = 1; i<= number; i++) {
fact = fact * i;
}
return fact;
}

}
public class FactorialExample {
public static void main(String[] args) {
Factorail obj = new Factorail();
System.out.println("Factorial is : "+obj.getFactorail(5));
}
}

Method Overloading:

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

(Or)

Same method in a class exist multiple times with different parameters is known as method
overloading.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Method Overloading is done in following ways

❖ Different order of parameters


❖ Different types of parameters
❖ Different number of parameters

class Addition{
void add(int a, int b) {
int c = a + b;
System.out.println("Two int numbers addition: "+c);
}
void add(float a, float b) {
float c = a + b;
System.out.println("Two float numbers addition: "+c);
}
void add(int a, int b, int c) { //calle
int d = a + b + c;
System.out.println("Three int numbers addition: "+d);
}
}
public class MethodOverloading {
public static void main(String[] args) { //caller
Addition obj = new Addition();
obj.add(10,52,45);
obj.add(10,53);
obj.add(53.4f, 63.5f);
}
}
Constructors:
Constructors are special methods that are used to initialize an object. It has the same
name as that of its class and is syntactically similar to methods.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

1) Constructors are used to initializing the objects.


2) Constructors are used to eliminating the default values of the variables.
Syntax:-

Classname (parameter-list)

------------ statements
------------

Method Constructor
1) Method name can be any user defined 1) It’s name should be the class name
name
2) It will be called automatically
2) It should be called explicitly
whenever object is created
3) Method should have return type (any
3) Constructor should not have any return
data type (or) void)
type (even void also)
4) Method can be either
4) Constructor cannot be
static/final/abstract
static/final/abstract

Types of constructor:-

These are classified into following types

Constructor

Deafult constructor parameterized Constructor

Default Constructor: If any constructor doesn’t have list of parameters in its signature known
as non parameterized or default constructor

Syntax:-

Classname()

{
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Example:

class Student{
private String name;
private String rollNo;
public Student() { //Default constructor
System.out.println("Default constructor");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
public class StudentExample {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("Laxman");
s1.setRollNo("22c11A6649");
System.out.println(s1.getName());
System.out.println(s1.getRollNo());
}
}
Parameterized constructor:-

It is any constructor contains list of parameters in it’s signature know as parameterized


constructor.

Syntax:-

Classname (datatype var1, datatype var2)

---------------------------------------

---------------------------------------
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Example:
class Student{
private String name;
private String rollNo;
public Student(String name, String rollNo) { //Parameterised constructor
this.name = name;
this.rollNo = rollNo;
}
public String toString() {
return name +"\n"+ rollNo;
}
}
public class StudentExample {
public static void main(String[] args) {
Student s2 = new Student("Lahari", "22C11A6613");
System.out.println(s2);
}
}

Example 2:

Overloading Constructor :

In addition to overloading normal methods, you can also overload constructor methods. In fact,
for most real-world classes that you create, overloaded constructors will be the norm, not the
exception.
Example:
class Student{
private String name;
private String rollNo;
public Student() { //Default constructor
System.out.println("Default constructor");
}
public Student(String name, String rollNo) { //Parameterised constructor (Overloaded)
this.name = name;
this.rollNo = rollNo;
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

}
}
public class StudentExample {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Lahari", "22C11A6613");
}
}
Access control:

An access specifier is a keyword that is used to specify how to access a member of a class. Java
provides many levels of protection to allow fine-grained control over the visibility of variables
and methods within classes, subclasses, and packages using access specifiers.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

protected Y Y Y N

Public Y Y Y Y

We can protect the data from unauthorized access. To do this ,we are using access specifiers.
There are four access specifiers in java:
private: private members of a class are not available outside the class. You can access private
members of a class in side the class only.
public: public members of a class are available anywhere outside the class and package.
protected: Protected members accessed by any member in the same package and sub class of
other package.
default: If no access specifier is used then default specifier is used by java compiler.
default members of a class are available with in the same package in which it is defined.

this keyword:
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

"this" keyword is used to refer the current class object that invoked it. "this" keyword can be
used inside any method to refer to the current object.
Syntax:
this.member;
Instance variable hiding:
Sometimes the names of instance variables and the names of formal parameters of a method /
constructor in that class may be same. In such case, the instance variables are hidden by formal
parameters. To access the hidden instance variables "this" can be used.
Example:
public class Faculty {
private String facName;
private String facId;
public Faculty(String facName, String facId) {
this.facName = facName;
this.facId = facId;
}
public void display() {
System.out.println(facName+" "+facId);
}
public static void main(String[] args) {
Faculty obj = new Faculty("Nikhil", "ID6620");
obj.display();
}
}
Garbage Collection
Garbage collection is the process of looking at heap memory, identifying which objects are in
use and which are not, and deleting the unused objects automatically.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Since objects are dynamically allocated by using the new operator, you might be wondering how
such objects are destroyed and their memory released for later reallocation. In some languages,
such as C++, dynamically allocated objects must be manually released by use of a delete
operator. Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is Called garbage collection. It works like this: when no
references to an object exist, that object is assumed to be no longer needed, and the memory
occupied by the object can be reclaimed.
static keyword:
When a member declared as static, it can be accessed independently of any object. We can
declare both variables and methods to be static. The static keyword is mostly used in Java for
efficient memory management of variables and methods. When object is created, no copy of
static variable made. All objects of that class share same static variables. A method declared as
static can be called without the help of any object. A static method has some restrictions.
❖ They called only other static methods. If you want to call other non-static methods, you
must call them using object.
❖ Then can access only static variables. If you want to access instance, you must access
them using object.
❖ They cannot refer to this or super keywords.
Example:
public class StaticExample {
static int a = 3;
static int b;
static void meth(int x) {
b = 4 *x;
System.out.println("x = "+x);
System.out.println("a = "+a);
System.out.println("b = "+b);
}
public static void main(String[] args) {
meth(42);
}
}
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Arrays in Java:

Normally, array is a collection of similar type of elements that have contiguous


memory location.

Java array is an object the contains elements of similar data type. It is a data structure
where we store similar elements. We can store only fixed set of elements in a java array.

How to declare an array:


datatype[] arrName;
arrName=new datatype[Size Of Array];
(or)
datatype arrName[]=new datatype[Size of Array];
Example:
int[] rollno;
rollno=new int[10];
(or)
int rollno[]=new int[10];
Consider the following example:
import java.util.Scanner;
public class OneDimArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String names[] = new String[5];
for(int i = 0; i< names.length ; i++) {
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

names[i] = sc.next();
}

for(int i = names.length-1; i>=0 ; i--) {


System.out.println(names[i]);
}
}
}

Two-dimensional array:

In such case, data is stored in row and column based index (also known as matrix form).

dataType [ ][ ] arrayRefVar;
(or)
dataType arrayRefVar[ ][ ];

Example to instantiate Multidimensional Array in java


int[ ][ ] arr=new int[3][3]; //3 row and 3 column

Example to initialize Multidimensional Array in java


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Program:
import java.util.Scanner;
public class TwoDimArray {
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int arr[][] =new int[3][3];
for(int i = 0; i < 3 ; i++) {
for(int j = 0; j < 3 ; j++) {
System.out.println("Enter value at"+ i+" "+j);
arr[i][j] = sc.nextInt();
}
}
for(int i = 0; i < 3 ; i++) {
for(int j = 0; j < 3 ; j++) {
System.out.print(arr[i][j]+" ");
if(j == 2)
System.out.println();
}
}
}
}

Control Statements:

Control Statements in Java are used to control the execution flow of the program. It is
one of the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
1. Decision Making statements
❖ if statements
❖ switch statement

2. Loop statements
❖ for loop
❖ while loop
❖ do while loop
❖ for-each loop
3. Jump statements
❖ break statement
❖ continue statement
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

If statement
The if statement is Java’s conditional branch statement. It can be used to route program
execution through two different paths. It will evaluate given expression if it is evaluated to true if
block will be executed, if expression evaluated to false by neglecting if block else will be
executed. Here is the general form of the if statement:
if (condition){
statement1; /* if condition is true it is executed*/
}
else{
statement2; /* if condition is false it is executed*/
}
Example:

import java.util.Scanner;
public class IfExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter age:");
int age = sc.nextInt();
if(age >= 18)
System.out.println("Eligible for vote");
else
System.out.println("Not eligible for vote");
}
}
The if-else-if Ladder
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

A common programming construct that is based upon a sequence of nested ifs is the
if-else-if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;

Example:

import java.util.Scanner;
public class ElseIfLadderExample {
double per;
Scanner sc = new Scanner(System.in);
void getGrade() {
System.out.println("Enter percentage:");
per = sc.nextDouble();
if(per >=0 && per <=100) {
if(per>=90) {
System.out.println("A Grade");
}
else if(per>=75) {
System.out.println("B Grade");
}
else if(per>=60) {
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

System.out.println("C grade");
}
else if(per >=40) {
System.out.println("D grade");
}
else {
System.out.println("Failed.....");
}
}
else {
System.out.println("Invalid percentage");
}
}
public static void main(String[] args) {
ElseIfLadderExample obj = new ElseIfLadderExample();
obj.getGrade();
}
}
Switch Statement:

The switch statement is Java’s multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression. As such, it
often provides a better alternative than a large series of if-else-if statements. Here is the general
form of a switch statement:

switch (expression) {
case value1:
// statement sequence
break;
case value2:
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char; each of the values specified in the case
statements must be of a type compatible with the expression. An enumeration value can also be
used to control a switch statement.
// A simple example of the switch.
import java.util.Scanner;
public class SwitchExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String language = sc.next();
switch(language) {
case "Java":
System.out.println("Java is a object oriented programming
language");
break;
case "C":
System.out.println("C is a procedure oriented programming
language");
break;
case "C++":
System.out.println("C++ is a partially object oriented
programming language");
break;
default:
System.out.println("Sorry we dont have any info about this.....");
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

break;
}
}
}
break:
break is a keyword. It is used within any control statements. It is used to terminate the execution
of the current loop or switch statements.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement. It breaks only the inner loop in the case of the nested
loop.
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int number = sc.nextInt();
boolean isNotPrime = false;
for(int i = 2; i <= number/2; i++) {
if(number % i == 0) {
isNotPrime = true;
break;
}
}
if(isNotPrime) {
System.out.println("Not prime");
}
else {
System.out.println("Prime number");
}
}
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

}
Continue:
To jump to the next iteration of the loop, we make use of the continue statement. This
statement continues the current flow of the program and skips a part of the code at the specified
condition. Unlike break statement, the continue statement doesn't break the loop, whereas, it
skips the specific part of the loop and jumps to the next iteration of the loop immediately.
public class ContinueExample {
public static void main(String[] args) {
for(int i = 1 ; i<=20 ; i++) {
if(i%2 != 0)
continue;
System.out.print(i +" ");
}
}
}

Loops:

Loops in Java is a feature used to execute a particular part of the program repeatedly if a
given condition evaluates to be true.

while Loop:

The while statement or loop continually executes a block of statements while a particular
condition is true. The while statement continues testing the expression and executing its block
until the expression evaluates to false. Use it when you don’t know how many times you want
the iteration to repeat.
Here is its general form:
while(condition) {
// body of loop
}
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

The condition can be any Boolean expression. The body of the loop will be executed as long as
the conditional expression is true. When condition becomes false, control passes to the next line
of code immediately following the loop. The curly braces are unnecessary if only a single
statement is being repeated.
Example:
import java.util.Scanner;
public class WhileExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("Enter name for wishes");
System.out.println("Enter exit for exit");
String name = sc.next();
switch(name) {
case "exit":
System.exit(0);
break;
default:
System.out.println("Hello " +name);
break;
}
}
}
}
Since the while loop evaluates its conditional expression at the top of the loop, the body of the
loop will not execute even once if the condition is false to begin with. For example, in the
following fragment, the call to println( ) is never executed.
do-while:
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop. After the first execution, it repeats the iteration until the
boolean condition is become false. Its general form is:
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates
the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop
terminates. As with all of Java’s loops, condition must be a Boolean expression.
// Demonstrate the do-while loop.
public class DoWhile {
public static void main(String[] args) {
int i = 1;
while(i >= 5) {
System.out.println(i);
i++;
}
do {
System.out.println(i);
i++;
}while(i >= 5);
}
}
for loop: For loop in Java iterates a given set of statements multiple times.
Use it when you know the exact number of times to execute the part of the program.
Here is the general form of the traditional for statement:
for(initialization; condition; iteration) {
// body
}
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

The for loop operates as follows. When the loop first starts, the initialization portion of the loop
is executed. Generally, this is an expression that sets the value of the loop control variable,
which acts as a counter that controls the loop. It is important to understand that the initialization
expression is only executed once. Next, condition is evaluated. This must be a Boolean
expression. It usually tests the loop control variable against a target value. If this expression is
true, then the body of the loop is executed. If it is false, the loop terminates. Next, the iteration
portion of the loop is executed. This is usually an expression that increments or decrements the
loop control variable. The loop then iterates, first evaluating the conditional expression, then
executing the body of the loop, and then executing the iteration expression with each pass. This
process repeats until the controlling expression is false. Here is a version of the “tick” program
that uses a for loop:
// Demonstrate the for loop.
class HelloFor
{
public static void main(String[] args)
{
for (int i=0;i<10 ;i++ )
{
System.out.println("Hello");
}
}
}
Operators:
Operators are special symbols that perform specific operations on one, two, or
three operands, and then return a result. Most of its operators can be divided into the following
four groups: arithmetic, bitwise, relational, and logical. Java also defines some additional
operators that handle certain special situations.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

The operands of the arithmetic operators must be of a numeric type. You cannot use them on
boolean types, but you can use them on char types, since the char type in Java is, essentially, a
subset of int.
The Bitwise Operators
Java defines several bitwise operators that can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands. They are
summarized in the following table:

Relational Operators
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here:

Boolean Logical Operators

The Boolean logical operators shown here operate only on boolean operands. All of the binary
logical operators combine two boolean values to form a resultant boolean value.

The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they
operate on the bits of an integer. The logical ! operator inverts the Boolean state:
!true == false and !false == true. The following table shows the effect of each logical operation:
Parameter passing:

There are two ways that a program can pass arguments to a method.

1. Call-by-value.
2. Call-by-reference.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

In call by value the method copies the value of an argument into the formal
parameter. The changes made to the parameter of the method does not affect the
argument used to call it.
class Demo{
void change(int a) {
a = a*a;
System.out.println(a); // prints 100
}
}
public class Callbyvalue {
public static void main(String[] args) {
int argValue = 10;
Demo obj = new Demo();
obj.change(argValue); //prints 10 not affected
System.out.println(argValue);
}
}
In call-by-reference, a reference to an argument is passed to the parameter. This
reference is used to access the actual argument specified in the call. The changes
made to the parameter will affect the argument used to call it.

class Test{
int x;
public Test(int x) {
this.x = x;
}
void change(Test obj1) {
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

obj1.x = obj1.x * obj1.x;


System.out.println(obj1.x); //prints 100
}
}
public class Callbyreference {
public static void main(String[] args) {
Test obj2 = new Test(10);
obj2.change(obj2);
System.out.println(obj2.x); // prints 100 affected
}
}
Recursion:

In Java recursion is a process that allows a method to call itself. A method that
calls it self is called recursive. The classic example of recursion is the computation
of the factorial of a number. The factorial of a number N is the product of all the
whole numbers between 1 and N.

Comparison Basis Recursion Iteration

Implemented by a function
Implementation Implemented using loops
calling itself

Includes initialization,
Only termination condition is condition, and
Syntax
required increment/decrement of the
control variable

Condition defined within the Defined within the definition


function body and when this of the loop and when this
Termination
condition becomes true, the condition becomes false, the
recursion ends loop terminates
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

In the case of an absence of a


base condition, a situation of
If no termination condition is
infinite recursion occurs. In
No Termination Statement specified then the infinite loop
situation can cause stack
uses CPU cycles
overflow error or can crash
the system

Code size Smaller than iteration Bigger

Slower due to the overhead of


Speed Faster
maintaining a stack

Its time complexity is easier


to calculate by calculating the
number of times the loop
Time complexity High time complexity
body gets executed.
Generally, it has lower time
complexity

Utilization of Stack Yes No

There is more memory


There is less memory required
Memory Utilization required in the case of
in the case of iteration
recursion

Exploring String class:


In java, string is basically an object that represents sequence of characters. An array of characters
works same as java string. In java language we are able to perform various operations on string
values to perform these operations some predefined methods are available in either String (or)
String Buffer class.
String:
It is a predefined class in java.lang package, can be used to defined the string values these
are "immutable" that means In any case, if a modification happens in a string, a completely new
string is constructed.
Syntax:

String varname=value;
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

(or)

String Objectname=new string(value);

String class methods:

length():

Which can be used to find the length of the string

Ex:

String x = "Bharath";

System.out.println(x.length()); // 7

charAt():

This method is used to return a character from main string based on the given index value.

String m = "Java Programming Java Object";

System.out.println(m.charAt(22)); // O

toLowerCase():

This method is used to convert upper case string into lower case String.

String book1 = "JAVA PROGRAMMING";

System.out.println(book1.toLowerCase());//Output: java programming

toUpperCase():

This method is used to convert lower case string into upper case

String book2 = "c programming";

System.out.println(book1.toLowerCase());

System.out.println(book2.toUpperCase()); //Output: C PROGRAMMING

concat():

This method is used to combined to two strings

String a = "Anand";
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

String b = " Kumar";

System.out.println(a.concat(b)); Output: Anand Kumar

compareTo():

which can be used to compare two strings it compares ASCII values of characters in
string and returns “0” if both the string are equal otherwise it returns either +ve(or) –ve value
(Difference ASCII value). It will consider the case also(Upper case and Lowercase) while
comparision.

Syntax:

String email1 = "ANAND@GMAIL.COM";

String email2 = "anand@gmail.com";


System.out.println(email1.compareTo(email2)); // Output: -32

compareToIgnoreCase():

Which is also similar to compareTo() but it is case insensitive method, It will not
consider the case.

Syntax:

String email1 = "ANAND@GMAIL.COM";

String email2 = "anand@gmail.com";

System.out.println(email1.compareToIgnoreCase(email2)); // return 0

equals():

Which can be used to compare two strings are the same returns true otherwise returns
false (it is Boolean method). It will consider the case also(Upper case and Lowercase) while
comparison.

Syntax:

String name1 = "Anand";

String name2 = new String("Karthik");

String name3 = new String("Karthik");

String name4 = "Anand";


Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

It is case sensitive method

Example:

System.out.println(name1 == name4); // true

System.out.println(name1.equals(name4)); // true

System.out.println(name2 == name3); // false

System.out.println(name2.equals(name3)); // true

equalsIgnoreCase():

It is similar to equals method but it is case insensitive. It will not consider the case.

Syntax:

String email1 = "ANAND@GMAIL.COM";

String email2 = "anand@gmail.com";

System.out.println(email1.equalsIgnoreCase(email2)); //true

Startwith():

It is a Boolean method used to check whether the string value is start with any specific
substring (or) not

Ex: String s6="Hello Friend how are you";

s6.startwith("Hello"); true

s6.startwith("hello"); false

endsWith():

It is a Boolean method can be used to check whether the given string is ends with given
substring or not

Ex:

String s1=”Anurag Engineering College”;

s6.endsWith(“College”); //output: true


Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

s6.endsWith(“college”); //output: false

indexOf():

This method is used to get the index value of a string or character (always it gives the
index value of first occurrence of first occurrence of either character or string )

String y = "Web Programming";

System.out.println(y.indexOf("Programming"));//output:4

lastIndexOf():

This method is used to get the index of value of any character or substring in the given
string(Last occurence).

String m = "Java Programming Java Object";

System.out.println(m.lastIndexOf("Java")); Output: 17

subString():

which can be used to retrieve substring from the main string It can be used in 2 ways

(a)substring(indexvalue)

Which can be used to retrieve a substring starting from given index value to last character of
main string

(b)substring(startindex,endindex)

Which can be used to retrieve a substring from given string based on starting and ending index
values

String m = "Java Programming Java Object";

Ex: System.out.println(m.substring(17)); ===> Java Object

Ex: System.out.println(m.substring(0,17));===> Java Programming

In real time it is used to comparing only the some part of two string

trim():

Which can be used to remove blank spaces before starting of string and also after ending of
string
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Ex: String s7=" abcd ";

System.out.println(s7.trim()); // abcd

split():

Which can be used to split a string into no of substring based on delimiter

Syntax:

stringobject.Split(delimiter)

In the above syntax delimiter can be any special symbol

Ex:

String lang = "Java is an object oriented";

String[] arr = lang.split(" ");

System.out.println(arr.length);

for(int i = 0;i <arr.length; i++ ) {

System.out.println(arr[i]);

Output:

Java

is

an

object

oriented

StringBuffer:
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an


alternative to the immutable String class, allowing you to modify the contents of a string without
creating a new object every time.

Using Stringbuffer class we can we can able to perform almost all operations on the string
which we have done using String class along with that some multiple operations insertion
deletion etc.

insert():

Which can be used to insert a new string or character at a given index value this method can be
used in 2 ways

insert (into pos, “string”)used to insert string value

insert (int pos, char value) used to insert character value

Ex :

StringBuffer obj = new StringBuffer("Anand ");

obj.insert(6, "Kumar");

System.out.println(obj);

Output:

Anand Kumar

delete():

Which can be used to delete specific substring from given string this can be used in 2 ways

(a)delete (index) == which will delete a substring from the given main string starting from the
given index value to the last character

(b) delete (starting index,ending index);


Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Which can be used to delete a substring from the main string based on starting and ending index
value

Ex:

StringBuffer name = new StringBuffer("Uday Kumar khan");

name.delete(10, 15);

System.out.println(name);// Uday Kumar

deleteCharAt():

Which is used to delete a specific character at given index value

Example:

StringBuffer book2 = new StringBuffer("Web Serviaces");

book2.deleteCharAt(9);

System.out.println(book2);//Output: Web Services

replace():

Which can be used to replace new string with old string based on index values

Replace(startingindex,endingindex,”string”);

Ex:

StringBuffer book = new StringBuffer("Web Technologies");

book.replace(4, 16, "Programming");

System.out.println(book);

Output: Web Programming

append():
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

Which can be used to add substring value to the given string at the end

StringBuffer sb=new StringBuffer("Java ");

sb.append("Notes");

System.out.println(sb);

Output: Java Notes

String StringBuffer
String class is immutable. StringBuffer class is mutable.
String is slow and consumes more memory StringBuffer is fast and consumes less memory
when you concat too many strings because when you cancat strings.
every time it creates new instance.
String class overrides the equals() method of StringBuffer class doesn't override the equals()
Object class. So you can compare the contents method of Object class.
of two strings by equals() method.
Java UNIT I(R22 CSE(AI& ML) JNTUH) By Buddarapu Anand Kumar 7386019269
banand.cool@gmail.com

You might also like