0% found this document useful (0 votes)
17 views63 pages

Unit 2

Uploaded by

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

Unit 2

Uploaded by

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

Class

• Class is basis in OOP.


• Class defines new data type.
– Ex: int a, b;
– struct student
{
};
class student
{
}
Student s;
• It can be used to create objects of that type.
• Thus, a class is a template for an object, and an object is an instance of a
class.
object=instance (both are same)

Suresh Yadlapati
Class
A class is declared by use of the class keyword. The data, or variables,
A simplified general form of a class definition is shown here: defined within a class are
modifier class classname called instance variables.
{ The code is contained
type instance-variable1; within methods.
type instance-variable2;
Collectively, the methods
// ...
and variables defined
type instance-variableN; within a class are called
type methodname1(parameter-list) { members of the class.
// body of method
In most classes, the
} instance variables are
// ... accessed by the methods
type methodnameN(parameter-list) { defined in that class.
// body of method
}
} Suresh Yadlapati
Example
class Box {
double width;
double height;
double depth;
}

Suresh Yadlapati
Declaration of object
Box mybox = new Box();
This statement combines the two steps just described. It can be rewritten like this to
show each step more clearly:
class-var = new classname ( );
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object

- constructor

Suresh Yadlapati
/* A program that uses the Box class. Call this file BoxDemo.java */
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}

Suresh Yadlapati
// This program declares two Box objects.
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
Suresh Yadlapati
Introducing Methods
This is the general form of a method:
modifier type method_name(parameter-list) {
// body of method
}

Methods that have a return type other than void return a value to the calling routine using the
following form of the return statement:
– return value;
Here, value is the value returned.

-Example, returning value


-Example, passing parameters

Suresh Yadlapati
Adding a Method that takes Parameters

A parameterized method can operate on a variety of data and/or be used in a number of slightly
different situations.
For example. Here is a method that returns the square of the number 10:
int square()
{
return 10 * 10;
}

int square(int i)
{
return i * i;
}
Now, square( ) will return the square of whatever value it is called with.

Suresh Yadlapati
Assigning Object Reference Variables

Box b1 = new Box();


Box b2 = b1;

Box b1 = new Box();


Box b2 = b1;
// ...
b1 = null;

Suresh Yadlapati
Constructors
• Java allows objects to initialize themselves when they are created. This automatic
initialization is performed through the use of a constructor.
• A constructor initializes an object immediately upon creation. It has the same name
as the class in which it resides and is syntactically similar to a method.
• Once defined, the constructor is automatically called immediately after the object
is created.
• Constructors look a little strange because they have no return type, not even void.
• This is because the implicit return type of a class’ constructor is the class type
itself.

• Ex: default, parameterized

Suresh Yadlapati
• If there is no constructor in a class, compiler automatically
creates a default constructor.

Suresh Yadlapati
this keyword
• Refers to the current object
• Can be used in any method of that class.

• Example

Dr Suresh Yadlapati
Garbage collection
Since objects are dynamically allocated by using the new operator,
deallocation is done automatically.
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. There is no explicit need to
destroy objects as in C++. Garbage collection occurs sporadically
during the execution of your program.
Suresh Yadlapati
Method Overloading
• In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different.
• When this is the case, the methods are said to be overloaded, and the process is referred to
as method overloading.
• Method overloading is one of the ways that Java supports polymorphism.
• When an overloaded method is invoked, Java uses the type and/or number of arguments
as its guide to determine which version of the overloaded method to actually call. Thus,
overloaded methods must differ in the type and/or number of their parameters.
• While overloaded methods may have different return types, the return type alone is
insufficient to distinguish two versions of a method.

Automatic type conversion - if no exact match is found

Suresh Yadlapati
Using Objects as Parameters
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}

Suresh Yadlapati
Call-by-value, call-by-reference
• In JAVA, there are two ways to pass an argument to a subroutine.
• The first way is call-by-value.:
– This approach copies the value of an argument into the formal parameter of the subroutine.
Therefore, changes made to the parameter of the subroutine have no effect on the argument.
• The second way an argument can be passed is call-by-reference:
– In this approach, a reference to an argument (not the value of the argument) is passed to the
parameter. Inside the subroutine, this reference is used to access the actual argument specified in
the call. This means that changes made to the parameter will affect the argument used to call the
subroutine.
• When you pass a primitive type to a method, it is passed by value.
• When you pass an object to a method, the situation changes dramatically, because objects
are passed by what is effectively call-by-reference .

Suresh Yadlapati
Returning Objects
• A method can return any type of data,
including class types that you create.

Suresh Yadlapati
Use of final
• The final keyword in java is used to restrict the user.
• The java final keyword can be used in many contexts.
• Final can be:
– variable
– method
– class

• A final variable that have no value is called blank final variable or uninitialized final variable.
• It can be initialized inside the class/ constructor only.

• Ex: Final_Demo.java

Suresh Yadlapati
Introducing Access Control

• Now we can understand why main( ) has always been preceded by the public
modifier. It is called from outside the program—that is, by the Java run-time
system.
• When no access modifier is used, then by default the member of a class is public
(default) within its own package, but cannot be accessed outside of its package.

Suresh Yadlapati
Recursion
• Recursion is the process of defining
something in terms of itself.
• A method that calls itself is said to be
recursive.
• Ex: Recursion_Fact.java

• There are two cases:


• Base Case: This is the condition that
stops the recursion. It prevents infinite
recursion by providing a simple, direct
answer for a specific case.
• Recursive Case: This is the part where
the method calls itself with a modified
argument, progressively working
towards the base case.

Suresh Yadlapati
Use of static
• There will be times when you will want to define a class member that will be used
independently of any object of that class.
• To create such a member, precede its declaration with the keyword static.
• You can declare both methods and variables to be static.
• The most common example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist.

Default values for static and non-static variables are same.


primitive integers(long, short etc): 0
primitive floating points(float, double): 0.0
boolean: false
object references: null

Suresh Yadlapati
• Variables declared as static are, essentially, global variables
• All instances (objects) of the class share the same static
variable.
• Methods declared as static have several restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way

• We can also create static block. Static block gets executed


exactly once, when the class is first loaded.

Suresh Yadlapati
• If you wish to call a static method from outside its class, you can do so
using the following general form:
classname.method( )
Or
Object.method()

Ex: UseStatic.java
StaticVariableDemo.java
StaticByName.java

Suresh Yadlapati
Static memory is allocated during the compile time.
Dynamic Memory allocation is done during run time.

• Why a static method can’t call a non-static method?


– Now that we know the constraints of using static in our methods, let’s
find out more on why a static method can’t call a static method?
– Simple answer — Compile-time or Early binding
– Usage of static keyword instructs the compiler to store the program
instructions and variables into a physical memory. Compile time
binding is done before loading the program into memory.
– Whereas, a non-static method/variables are examples of Run-time or
Late binding, where an object is required to be created before it is
called.

Suresh Yadlapati
Static Method vs. Instance Method

Static Methods Instance Methods

Require an object creation to call an instance


Can be called without the objects,
method
Associated with the class Associated with the objects

Can access only static attributes. Can access all attributes of a class

Requires to be declared using static


Doesn’t require any keyword
keyword

Suresh Yadlapati
Suresh Yadlapati
Nested Classes:
• A nested class is one that is declared entirely in the body of
another class or interface.
• The class that contains the other class is known as the outer
class and the contained class is known as inner class.
OuterClass
{
// Body of OuterClass
InnerClass
{
/// Body of InnerClass
}
}
Suresh Yadlapati
• The class which is nested, exists only as long as the enveloping
class exists.
• So, the scope of inner class is limited to the scope of
enveloping class.

• Nested classes enables us to logically group classes that are


only used in one place, thus this increases the use of
encapsulation

Suresh Yadlapati
• Nested classes are divided into two categories:
– static nested class: Nested classes that are declared static are called
static nested classes.
– Nested non-static classes or inner classes which may be member inner
class, local class and anonymous class.

Suresh Yadlapati
Static Nested Classes
• In Java, a static nested class is a nested class that is declared
with the static keyword.
• These classes may be declared with the access specifiers:
public, private and protected.
• These classes cannot access non-static data members and
methods of outside class. They can access only static variables
and methods of outer class including private.

Suresh Yadlapati
• The main benefit of these classes is that their reference is not
attached to the outside class reference. Their objects can be
created and accessed directly. In other words, an instance of
outer class is not required to create static class instance.
class College Accessing:
{ OuterClassName.StaticNestedClassName;
// variables and method of College class Ex: College.Student;
static class Student {
// variables and method of Student class Object Creation:
} OuterCN.StaticNestedCN objectName = new
} outerCN.StaticNestedCN();

Ex:
College.Student object = new College.Student();

Suresh Yadlapati
Member Inner Class
• The nested inner class is the simplest form of an inner class in Java.
• It is also known as member inner class because we can declare the class as
a member of another class.
• The member inner class is always outside the method and inside the class.
• A member inner class can be declared with any access modifier
like private, protected, public, and default.

Suresh Yadlapati
Member Inner Class
• We can’t create an object or instance of a member inner class directly. The
object/instance of a member inner class totally depends on the object of
the outer class.
• Unlike a normal class, the nested class has a different way to create an
object or instance.

OuterClass objOfOuter = new OuterClass();


InnerClass objOfInner = objOfOuter.new InnerClass();

Suresh Yadlapati
Member Inner Class
• The inner class has access to all the members of the
enveloping class including the members declared public,
protected, or private.
• The enveloping/outer class does not have direct access
to nested class members. It is only through the reference
of inner class.
• An instance of inner class can only be created with an
instance of outer class.

Suresh Yadlapati
• Accessing the members of the Inner class from the
Outer class:
– Scenario 1: In the static method we can access the
member of the Inner class only when we create an
object of the Inner class. To create an instance of Inner
class we have to use the object of the Outer class.
– Scenario 2: But in the instance method (non-static
method) we can directly create the object of the Inner
class. Let’s take an example and see how we can access
it.
• Ex: Outerclass.java
Suresh Yadlapati
• Accessing the members of the Outer class
from the Inner class:
– The inner class has access to all the members of
the enveloping class including the members
declared public, protected, or private.
• Ex: OuterClass1.java

Suresh Yadlapati
• Accessing the static members of Outer Class:
We can access the static member of the Outer class.
Although we can’t use static keyword in the Inner
class, we can access the static member of the outer
class. We don’t need to create an object of Outer
class to access the static members.
Ex: OuterClass2.java

Suresh Yadlapati
• Accessing private inner class from outer class:
Create an object inside the method of outer
class and access the fields of inner class.

Ex:AccessingPrivateClass.java

Suresh Yadlapati
Anonymous Inner Class
• Java anonymous inner class is an inner class without a name and for
which only a single object is created.
• In simple words, a class that has no name is known as an anonymous
inner class in Java.
• It is used if you want to override a method of class or interface.
• An anonymous class is defined by operator new followed by class
name it extends, argument list for the constructor of super class, and
then, the anonymous class body.

class-name obj=new class-name ([argument list]){class body};

• Java Anonymous inner class can be created in two ways:


– Class (may be abstract or concrete).
– Interface

Suresh Yadlapati
Method Inner Class or Local Inner Class

• A class i.e., created inside a method or a block, is called local


inner class in Java.
• Block may be method or if clause or loop.

Ex: OuterClass4.java and OuterClass5.java

Suresh Yadlapati
Strings
• A string is a sequence of characters. In Java, string is an object
of class, and therefore there is no automatic appending of null
character by the system.
• In Java, there are three classes that can create strings and
process them with nearly similar methods.
– class String
– class StringBuffer
– class StringBuilder
• All the three classes are part of java.lang package.

Suresh Yadlapati
• Class String:
– In the case of String class, an object may be
created as
• String str1=”abcd”;
• String str2=”bell”;
• and these are equavelent to char
s1={‘a’,’b’,’c’,’d’}
and
char s2={‘b’,’e’,’l’,’l’}

Suresh Yadlapati
Objects of class String may also be created by operator
new
String str=new String(“abcd”);
In the case of other two classes, the objects can be
created only by the operator new as

StringBuffer sb=new StringBuffer(“PVPSIT”);


StringBuilder sb=new StringBuilder(“PVPSIT”);

Suresh Yadlapati
Storage of Strings
• The objects of class String have a special storage facility, which
is not available to objects of other two String classes or to
objects of any other class.
• The memory allocated to a Java program is divided into two
segments:
(i) Stack (ii) Heap

Suresh Yadlapati
• Within the heap, there is a memory segment called ‘String
constant pool’.
• The String class objects can be created in two different ways:
String s1 = “Cat”;
String strz = new String(“Cat”);

Suresh Yadlapati
String vs StringBuffer vs StringBuilder

Suresh Yadlapati
Interface CharSequnece:

• It is an interface in java.lang package.


• It is implemented by several classes including the classes String,
StringBuffer, and StringBuilder.

Modifier Method Name

char charAt(int index): Returns the char value at the specified


index.
int length(): Returns the length of this character sequence.

CharSequence subSequence(int start, int end): Returns a


new CharSequence that is a subsequence of this
sequence.
String toString(): Returns a string containing the characters in
this sequence in the same order as this sequence.

Suresh Yadlapati
Class String:

• The class String is used to represent strings in


Java. It is declared as
public final class String extends Object implements serializable,
comparable<String>, charSequence

Suresh Yadlapati
• Constructors:
• String() - This constructor creates a string without any characters.
• String str = new String();
• String str1 = “”;

• String(byte[] barray) – It constructs a new string by decoding the


specified byte[] array using computers default character set(ASCII).
• byte []barray = new byte[]{65, 66, 67, 68, 69};
• String str2 = new String(barray); // str2 = “ABCDE”.

• String (byte [] barray, Charset specifiedset) - It constructs a new string


by decoding the specified byte array (bray) by using specified character
set. Some of the Charsets supported by Java are UTF8, UTF16, UTF32,
and ASCII. These may be written in lower case such as utf8, utf16,
utf32, and ascii.
• byte []barray = new byte[]{65, 66, 67, 68, 69};
• String str=new String(barray, “ascii”);

Suresh Yadlapati
• String(byte[] byte_arr, int start_index, int length)
• - Construct a new string from the bytes array depending on
the start_index(Starting location) and length(number of
characters from starting location).
• byte[] b_arr = {71, 101, 101, 107, 115};
• String s = new String(b_arr, 1, 3); // eek

Suresh Yadlapati
• String(byte[] byte_arr, int start_index, int
length, Charset char_set)
• - Construct a new string from the bytes array depending on
the start_index(Starting location) and length(number of
characters from starting location). Uses char_set for
decoding.

– byte[] b_arr = {71, 101, 101, 107, 115};


– String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks

Suresh Yadlapati
• String(char[] value) – Constructs the string
based on the specified character array.
char char_arr[] = {'S', 'u', 'r', 'e', 's',’h’};
String s = new String(char_arr); //Suresh

• String(char[] char_array, int start_index, int


count)
- Allocates a String from a given character array but
choose count characters from the start_index.
char char_arr[] = {'G', 'e', 'e', 'k', 's'};
String s = new String(char_arr , 1, 3); //eek

Suresh Yadlapati
• String(StringBuffer s_buffer) - Allocates a new string
from the string in s_buffer.

StringBuffer s_buffer = new StringBuffer("Geeks");


String s = new String(s_buffer); //Geeks

• String(StringBuilder s_builder) - Allocates a new string


from the string in s_builder

StringBuilder s_builder = new StringBuilder("Geeks");


String s = new String(s_builder); //Geeks

Suresh Yadlapati
Methods for Extracting Characters from Strings:

Method Description
char charAt(int index) returns char value for the particular index

int length() returns string length

void getChars(
int start, int end,
Extracts more than one character at a time the
char[]
string and copies into destination array at
destination_array, int
specified location.
destination_array_posi
tion)

Encodes a given string into a sequence of bytes


byte[] getBytes()
and return an array of bytes
Converts the string into an array of characters
char toCharArray()
and returns the array.

Suresh Yadlapati
Methods for comparision of Strings
is used for comparing two strings
lexicographically. Each character of both the
int compareTo(String str) strings is converted into a Unicode value for
comparison. If both the strings are equal
then this method returns 0 else it returns
positive or negative value.
int compareToIgnoreCase (String
comparison of two strings irrespective of
str)
cases. Returns the value same as above.
Compares the characters inside the two
strings. It is different from ==( it checks
boolean equals()
references), where as equals() checks
content.
boolean equalsIgnoreCase(String Compares with another string. It doesn't
another) check case. Returns boolean value.

Suresh Yadlapati
boolean startsWith(String chars) The startsWith() method checks whether a string
starts with the specified character(s).

boolean endsWith(String chars) The endsWith() method checks whether a string ends
with the specified character(s).

boolean regionMatches(boolean
ignoreCase, int offset, String
other, int otherOffset, int length)
regionMatches() method compares regions in two
boolean regionMatches(int different strings to check if they are equal.
offset, String other, int
otherOffset, int length)

Suresh Yadlapati
Methods for Modifying Strings:
• In Java, string is an object of class String, and therefore it cannot be modified. The
ways to modify strings are:
1. Define a new string
2. Create a new string using substring() from existing string
3. Creating new string by adding two or more substrings

Method Description

String substring(int Returns substring from the begin index to


beginIndex) last character
String substring(int Returns substring from the begin index to
beginIndex, int endIndex) end index-1

Suresh Yadlapati
Method Description
The replace() method searches a string
String replace(char for a specified character, and returns a
searchChar, char newChar) new string where the specified
character(s) are replaced
String replace( Returns new string in which all
char searchCharSeq, occurences of a string of characters is
char replaced with another sequence of
newCharSeq) characters.
String trim() The trim() method removes whitespace
from both ends of a string.

Suresh Yadlapati
Methods for Searching Strings
Method Description
The indexOf() method returns the position of
int indexOf(String str/char ch) the first occurrence of specified character(s) in
a string.
The indexOf() method returns the position of
int indexOf(String str/char ch,
the first occurrence of specified character(s) in
int fromIndex)
a string. Search starts from specified location.
The lastIndexOf() method returns the position
int lastIndexOf(String str/char
of the last occurrence of specified character(s)
ch)
in a string.
The lastIndexOf() method returns the position
int lastIndexOf(String str/char of the last occurrence of specified character(s)
ch, int fromIndex) in a string. Search starts from specified
location.

Suresh Yadlapati
Class StringBuffer:
Constructors:
1. StringBuffer(): It reserves room for 16 characters without reallocation
StringBuffer s = new StringBuffer();

2. StringBuffer( int size): It accepts an integer argument that explicitly sets the size
of the buffer.
StringBuffer s = new StringBuffer(20);

3. StringBuffer(String str): It accepts a string argument that sets the initial contents
of the StringBuffer object and reserves room for 16 more characters without
reallocation.
StringBuffer s = new StringBuffer("PVPSIT");

Suresh Yadlapati
Sl. No Method Description

is used to append the specified string with this


string. The append() method is overloaded
1 append(String s) like append(char), append(boolean),
append(int), append(float), append(double)
etc

is used to insert the specified string with this


2 insert(int offset, String s)
string at the specified position.

replace(int startIndex, int endIndex, is used to replace the string from specified
3
String str) startIndex and endIndex.

is used to delete the string from specified


4 delete(int startIndex, int endIndex)
startIndex and endIndex

5 reverse() is used to reverse the string

Suresh Yadlapati
is used to ensure the capacity at
ensureCapacity(int
6 least equal to the given
minimumCapacity)
minimum.
is used to return the character
7 charAt(int index)
at the specified position.
is used to return the length of
8 length() the string i.e. total number of
characters
String substring(int is used to return the substring
9
beginIndex) from the specified beginIndex.
is used to return the substring
substring(int beginIndex,
10 from the specified beginIndex
int endIndex)
and endIndex.

Suresh Yadlapati
• Elaborate
System.out.println()?
public static void main(String ad[])

Suresh Yadlapati

You might also like