String Handling: Part-I

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 72

String Handling

Part-I

M.Srilatha Assistant Professor CSE


Strings in java
• String is a sequence of characters enclosed within
double quotes (" ").
• Java String is differ from string in C or C++, where
(in C or C++) string is simply an array of char.
• In java String is a class encapsulated under
java.lang package.
• In java, every string that you create is actually an
object of type String.
• One important thing to notice about string object
is that string objects are immutable that means
once a string object is created it cannot be
altered.

M.Srilatha Assistant Professor CSE


• To perform various operation on String data,
we have three predefined classes they are:
– String
– StringBuffer
– StringBuilder

M.Srilatha Assistant Professor CSE


String Constructors
• The String class supports several constructors.
1. String():
To create an empty String, we call the default constructor. For
example:
String s = new String();
Where String object S is created and initialize with empty string.
2. String(“…..”):
creates a String object initialized to the value of the string literal.
Example: String strl =new String("Java");
Where String object S is created and initialize with “JAVA”.
3. String(character array name):
To create a String initialized by an array of characters, use the
following constructor
String(char chars[ ])
Example: char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string "abc".

M.Srilatha Assistant Professor CSE


4. String( character array, int index , int count):
You can specify a subrange of a character array as an initializer
using the following constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange
begins, and numChars specifies the number of characters to use.
Example: char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters “cde”.
5. String (String object):
This constructor initializes string object with the value of another
object.
Example: String s = new String(“hello”);
String s1=new String(s)
where s1 reference to object s;
6. String (byte [] bytes):
It constructs a new String object by converting the bytes array into
characters using the default charset.
Example: byte[] ascii ={65,66,67,68,70,71,73};
String s4 = new string (ascii);
This initializes s4 with the characters “ABCDEFG”.
M.Srilatha Assistant Professor CSE
7. String (byte [] bytes, int startlndex, int count)
It constructs a new String object by converting the bytes
array starting from index startlndex upto a maximum of
count bytes into characters using the default charSet.
Example: byte[] ascii ={65,66,67,68,70,71,73};
String s4 = new string (ascii,4,2);
This initializes s4 with the characters “EF”.
8. String (byte [] bytes, String charsetName) :
It constructs a new String object by converting bytes array
into characters using the specified charset.
9. String(byte[] bytes, int startlndex, int count, String
charsetName) :
It constructs a new String object by converting the bytes
array starting from index startlndex upto a maximum of
count bytes into characters using the specified charset.
10. String (StringBuffer buffer) :It constructs anew String
object from a StringBuffer object.
M.Srilatha Assistant Professor CSE
• Example to illustrate String Constructor
public class StringConstructors
{
public static void main(String[] args)
{
char[] charArray ={'H','i',' ','D','I','N','E','S','H'};
byte[] ascii ={65,66,67,68,70,71,73};
String str = "Welcome";
String strl =new String("Java");
String str2 =new String(charArray);
String str3 =new String(charArray,3,3);
String str4 =new String(ascii);
String str5 =new String(ascii,2,3);
String str6 =new String();
String str7 =new String(str);
System.out.println("str : "+ str);
System.out.println("strl : "+ strl);
System.out.println("str2 : "+ str2);
System.out.println("str3 : "+ str3);
System.out.println("str4 : "+ str4);
System.out.println("str5 : "+ str5);
System.out.println("str6 : "+ str6);
System.out.println("str7 : "+ str7);
}
} M.Srilatha Assistant Professor CSE
String class functions
I. String Length
length() method returns the number of characters presents in the string.
The signature of the string length() method is given below:

Syntax: int string.length();

Example:
1. String s1="javatpoint";
s1.length();
// 10 is the length of javatpoint string
2. “hello”.legnth();
// 5 is the length of hello string
Note :
length is a final variable applicable for arrays. With the help of length
variable, we can obtain the size of the array.
Example:
int[] array = new int[4];
array.length; // it returns the value as 4
M.Srilatha Assistant Professor CSE
1. concat() :
II. String Concatenation
This method concatenates one string to the end of another string. This
method returns a string
Syntax: String concat(String anostr)
Example:
String s = “vrsec";
s = s.concat("! welocmes.");
The value of s is “vrsec! Welcomes”.
2. + (string concatenation) operator:
Which concatenates two strings
Syntax: string1+string2;
Example:
1. String s="Sachin“;
S+ " Tendulkar“;
// returns “Sachin Tendulkar”
2. String s =“Hello”+2+2;
// returns “Hello22”
3. String s =“Hello”+(2+2);
// returns “Hello4”
M.Srilatha Assistant Professor CSE
III. String Conversion
• toString():
 Object class contains toString() method.It means
toString() is efined in Java.lang.Object pacakge.
 We can use toString() method to get string
representation of an object.
 If we did not define toString() method in your
class then Object class toString() method is
invoked.
 If we define toString() method then Overridden
toString() method will be called.

M.Srilatha Assistant Professor CSE


Example for toString()
//Without toString() // With toString()
Class person Class person
{ {
String name; String name;
int age; int age;
Person(String name, int age) Person(String name, int age)
{ {
this.name = name; this.name = name;
this.age = age; this.age = age;
} }
public static void main(String[] args) public String toString()
{ {
person b= new person(“ sai”, 22); return name + " " + age + " “;
System.out.println(b); }
System.out.println(b.toString()); public static void main(String[] args)
} {
• Output : person b= new person(“ sai”,
person@232204a1 22);
person@232204a1 System.out.println(b);
System.out.println(b.toString());
}
M.Srilatha Assistant Professor CSE
Output : sai 22
IV. Character Extraction methods
1. charAt()
charAt() method is used to extract a single character at an index.
Syntax : char charAt(int index)
String str="Hello";
char ch=str.charAt(2);
// the value of ch is ’l’.
2. getChars()
It is used to extract more than one character.
Syntax :
void getChars(int Startindex, int Endinedx, char arr[], int arrStart)

 copies characters of a string object starting from string Startindex to Endindex.


 arr is the character array that will contain the substring.
 arrStart is the index inside arr at which substring will be copied
Example:
String str="Hello World";
char ch[]=new char[4];
str.getChars(1,5,ch,0); // M.Srilatha
the value array
Assistant of chCSE
Professor is ’ello ’.
3. getBytes()
getBytes() extract characters from String object and then
convert the characters in a byte array
Syntax: byte [] getBytes();
Example: String str="Hello";
byte b[]=str.getBytes();
// values of array b are 72 101 108 108 111 32
4. toCharArray()
It is an alternative of getChars() method. toCharArray()
convert all the characters in a String object into an array of
characters
Syntax: char [] toCharArray();
String str="Hello World";
char ch[]=str.toCharArray();
// values of array ch are Hello World

M.Srilatha Assistant Professor CSE


V. String Comparison methods
1. compareTo() :
The method compareTo() is used for comparing two strings
lexicographically in Java
Syntax: int compareTo(String str) ;
It returns the following values:
 if (string1 > string2) it returns a positive value.
 if both the strings are equal lexicographically
i.e.(string1 == string2) it returns 0.
 if (string1 < string2) it returns a negative value.
Example:
String s1 = "Ram";
String s2 = "Ram";
String s3 = "Shyam";
String s4 = "ABC";

now s1.compareTo(s2). // returns value as 0


s1.compareTo(s3). // returns value as -1
s1.compareTo(s4). // returns value as 17

M.Srilatha Assistant Professor CSE


2. equals()
This method compares two Strings character by character, ignoring
their address and returns Boolean value.
Example:
String string1 = "using equals method";
String string2 = "using equals method";
String string3 = "using EQUALS method";
String string4 = new String("using equals method");
string1.equals(string2); // returns true
string3.equals(string4) // returns false
3. equalsIgnoreCase():
This method compares two Strings character by character by
ignores casing in characters.
Example:
String string1 = "using equals method";
String string2 = "using equals method";
String string3 = "using EQUALS method";
String string4 = new String("using equals method");
string1.equals(string2); // returns true
string3.equals(string4) // returns true

M.Srilatha Assistant Professor CSE


4. regionMatches():
This method returns a boolean value true or
false. we are comparing two strings out of the
substrings of those string sources.
Syntax: 1. public boolean regionMatches(int toffset, String other, int
ooffset,int len);
2. public boolean regionMatches(boolean ignoreCase,int toffset,String
other,int ooffset,int len)
Example: String source = "helloworld";
String anotherString = "World of java";
source.regionMatches(6, anotherString, 0, 5);
// it returns false.

M.Srilatha Assistant Professor CSE


5. startsWith():
This method checks if this string starts with given
prefix. startsWith() method checks if this string starts
with given prefix
Example:
String s1="java string”.
s1.startsWith("ja“); // it returns true
6. endsWith():
This method checks whether the String ends with a
specified suffix. If the specified suffix is found at the
end of the string then it returns true else false.
Example:
String s1="java string”.
s1.endsWith(“ung“); // it returns flase

M.Srilatha Assistant Professor CSE


7. Equal() verses ==
• == operators for reference
comparison (address Example 2:
comparison or refrerence) .
• it means == checks if both
objects point to the same
memory location or same
reference .
• equals() method checks for for
content comparison
• it evaluates to the comparison
of values in the objects.

Example: String s1 = new


String("HELLO");
String s2 = new String("HELLO");
s1 == s2 // returns false
s1.equals(s2) // returns true

M.Srilatha Assistant Professor CSE



VI. Searching Strings
The String class provides 2 methods for searching a string.
1. indexOf() : Searches for the first occurrence of a character or
substring. It starts searching from beginning to the end of the
string and returns the corresponding index if found otherwise
returns -1.
Note: If given string contains multiple occurrence of specified
character then it returns index of only first occurrence of specified
character.
1.1 Syntax: int indexOf(char ch);
This method will return the index of the first occurrence of a
character variable ch in the invoked string.
Example:
String str = "The Sun rises in the east and sets in the west.";
str.indexOf('i'); // returns 9

1. 2. Syntax: int indexOf(String st)


This method will return the index of the first occurrence of a
substring st in the invoked string.
str.indexOf("st"); // returns 23
M.Srilatha Assistant Professor CSE
1.3 Sysntax: int indexOf(char ch, int startIndex)
Here startIndex specifies the starting point of
search. The search runs from startIndexto end
of the String.
Example: str.indexOf('e', 2); // returns 2
1.4 Sysntax: int indexOf(String st, int startIndex)
Example: str.indexOf("st", 2); // returns 44

M.Srilatha Assistant Professor CSE


• lastIndexOf(char c): It starts searching backward from end of the string
and returns the index of specified character whenever it is encountered.
Example: String str = "pqrpqrpqr";
System.out.println(str.lastIndexOf('p')); // prints 6

• int lastIndexOf(String str): Returns the index number of the last


occurrence of the string str passed as parameter, in the given string. If
matching is not found, returns -1.
Example: String str = "This is last index of example";
int index = str.lastIndexOf("of"); // returns 19

• lastIndexOf(char c, int fromIndex): It starts searching backward from the


specified index in the string. And returns the corresponding index when
the specified character is encountered otherwise returns -1.
Example: String str = "This is index of example";
int index = str.lastIndexOf('s',5); // returns 3
• Int lastIndexOf(String substring, int fromIndex): returns last index
position for the given substring and from index
Example: index = str.lastIndexOf("of", 10);
System.out.println(index); // -1, if not found
M.Srilatha Assistant Professor CSE
VII. Modifying Strings
1. Substring(): Returns a new string that is a substring of
this string.
1.1 Syntax: String substring(int beginIndex, int endIndex)
WhereThe substring begins at the specified beginIndex
and extends to the character at index endIndex.
Example: String str = “Happy birth day”;
str.substring(4,8); // returns y bir
1.2 Syntax: String substring(int beginIndex)
The beginIndex specifies the index of the first character.
Here, the returned substring extends to the end of the
original string.
Example: String str = “Happy birth day”;
str.substring(4); // returns y birth day

M.Srilatha Assistant Professor CSE


2. replace(): method returns a string replacing all the old
characters with to new characters.
• There are two types of replace methods in java string.
2.1 public String replace(char oldChar, char newChar)
Example: String str = “Happy new year”
str.replace(‘e’,’7’); // now str value is Happy n7w y7ar
2.2 public String replace(CharSequence target, CharSequence replacement)
Example: String s1=“ my name is java";
s1.replace("is","was"); // now s1 value is “ my name was java”;
3. trim():
Which eliminates leading and trailing spaces.
Example: String s1=" hello string ";
System.out.println(s1+"javatpoint");//without trim()
System.out.println(s1.trim()+"javatpoint");//with trim()
Output is:
hello string javatpoint
hello stringjavatpoint
M.Srilatha Assistant Professor CSE
VII. Case Conversation methods
1. The method toLowerCase() converts the
characters of a String into lower case characters.
Example: String str= “THIS”;
str. toLowerCase(); // returns this

2. The method totoUpperCase( () converts the


characters of a String into upper case characters.
Example: String str= “this”;
str. toLowerCase(); // returns THIS

M.Srilatha Assistant Professor CSE


String Buffer Classes
• In Java StringBuffer class is used to create
mutable (modifiable) string.
• The StringBuffer class in java is same as String
class except it is mutable i.e. it can be
changed.
Important Constructors of StringBuffer class
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity
of 16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int capacity) Creates an empty string buffer with the specified
capacity as length.

M.Srilatha Assistant Professor CSE


1. StringBuffer append() method:
The append() method concatenates the given
argument with this string.
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java

2. StringBuffer insert() method


The insert() method inserts the given string
with this string at the given position
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello

M.Srilatha Assistant Professor CSE


3. StringBuffer replace() method
The replace() method replaces the given string from
the specified beginIndex and endIndex.
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
4. StringBuffer delete() method
The delete() method of StringBuffer class deletes the
string from the specified beginIndex to endIndex.
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo

M.Srilatha Assistant Professor CSE


5. StringBuffer reverse() method
The reverse() method of StringBuilder class
reverses the current string.
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH

M.Srilatha Assistant Professor CSE


String Tokenizer Class
• This Class allows an application to break a string into tokens.
• It doesn't provide the facility to differentiate numbers, quoted strings,
identifiers etc
Constructors of StringTokenizer class
• There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) creates StringTokenizer with


specified string.
StringTokenizer(String str, String creates StringTokenizer with
delim) specified string and delimeter.
StringTokenizer(String str, String creates StringTokenizer with
delim, boolean returnValue) specified string, delimeter and
returnValue. If return value is true,
delimiter characters are considered
to be tokens. If it is false, delimiter
characters serve to separate tokens.

M.Srilatha Assistant Professor CSE


Methods of StringTokenizer class
Public method Description

boolean hasMoreTokens() checks if there is more tokens


available.
String nextToken() returns the next token from the
StringTokenizer object.
String nextToken(String delim) returns the next token based on
the delimeter.
boolean hasMoreElements() same as hasMoreTokens()
method.
Object nextElement() same as nextToken() but its
return type is Object.
int countTokens() returns the total number of
tokens.

M.Srilatha Assistant Professor CSE


Inheritance
• Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviors
of a parent object.
• It is an important part of OOPs .
• Using this concept we can create new classes that
are built upon existing classes.
• While inheriting from an existing class, we can
reuse methods and fields of the parent class.
Moreover, we can add new methods and fields in
the current class also.
• Inheritance represents the a parent-child
relationship.

M.Srilatha Assistant Professor CSE


Terms used in Inheritance
• Class: A class is a group of objects which have common
properties. It is a template or blueprint from which
objects are created.
• Sub Class/Child Class: Subclass is a class which inherits
the other class. It is also called a derived class,
extended class, or child class.
• Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a
base class or a parent class.
• Reusability: reusability is a mechanism which
facilitates you to reuse the fields and methods of the
existing class when we create a new class. we can use
the same fields and methods already defined in the
previous class.

M.Srilatha Assistant Professor CSE


The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
• The extends keyword indicates that we are
making a new class that derives from an
existing class.

M.Srilatha Assistant Professor CSE


Simple Example for Inheritance
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.sala
ry);
System.out.println("Bonus of Programmer is:"+p.b
onus);
}
} M.Srilatha Assistant Professor CSE
Types of Inheritance
1. Single Inheritance : 2. Multilevel Inheritance :
In single In Multilevel
inheritance, Inheritance, a derived
subclasses inherit class will be inheriting a
the features of one base class and as well
superclass. as the derived class also
act as the base class to
other class

M.Srilatha Assistant Professor CSE


3. Hierarchical Inheritance : 4. Multiple Inheritance:
In Hierarchical Inheritance, In Multiple inheritance
one class serves as a ,one class can have
superclass (base class) for more than one
more than one sub class. superclass and inherit
features from all parent
classes.

Please note that Java does


not support multiple
M.Srilatha Assistant Professor CSE
inheritance
5. Hybrid Inheritance(Through Interfaces) : It is
a mix of two or more of the above types of
inheritance. Since java doesn’t support
multiple inheritance with classes, the hybrid
inheritance is also not possible with classes.
In java, we can achieve hybrid inheritance only
through Interfaces.

M.Srilatha Assistant Professor CSE


// Example for Single Inheritance
Class A
{
public void methodA() { System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

M.Srilatha Assistant Professor CSE


// Example for Mutilevel Inheritance
Class Z extends Y
Class X
{
{
public void methodZ()
public void methodX()
{ System.out.println("Class X {
method"); System.out.println("class Z
} method");
} }
Class Y extends X public static void main(String
{ args[])
public void methodY() {
{ Z obj = new Z();
System.out.println("class Y obj.methodX(); //calling grand
method"); parent class method
} obj.methodY(); //calling parent
} class method
obj.methodZ(); //calling local
method
M.Srilatha Assistant Professor CSE
}}
// Example for Hierarchical Inheritance
Class X Class Z extends X
{ {
public void methodX() public void methodZ()
{ System.out.println("Class X {
method"); System.out.println("class Z
} method");
} }
Class Y extends X public static void main(String
args[])
{
{
public void methodY()
Z obj = new Z();
{
obj.methodX(); //calling grand
System.out.println("class Y parent class method
method"); //obj.methodY(); invalid
} statement;
} obj.methodZ(); //calling local
method
}}

M.Srilatha Assistant Professor CSE


Using super
• The super keyword in java is a reference variable that is
used to refer parent class objects.
1. Use of super with variables: This scenario occurs when a
derived class and base class has same data members. In
that case there is a possibility of ambiguity for the JVM. To
reslove this issue we use super key word.
2. Use of super with methods: This is used when we want
to call parent class method. So whenever a parent and child
class have same named methods then to resolve ambiguity
we use super keyword.
3. Use of super with constructors: super keyword can also be
used to access the parent class constructor. One more
important thing is that, ‘’super’ can call both parametric as
well as non parametric constructors depending upon the
situation.

M.Srilatha Assistant Professor CSE


Let us consider following code // Using Super keyword to access
class Superclass value of variable
{ class Superclass
int num = 100; {
} int num = 100;
class Subclass extends Superclass }
{
int num = 110; class Subclass extends Superclass
void printNumber() {
{ int num = 110;
System.out.println(num); void printNumber()
} {
public static void main(String args[]) System.out.println(super.num);
{
Subclass obj= new Subclass(); }
obj.printNumber(); public static void main(String
} args[])
} {
Out put: 110 Subclass obj= new
Subclass();
To get the value of num variable with respect obj.printNumber();
to super class we have to use super }
keyword }
Out put: 100

M.Srilatha Assistant Professor CSE


// Using Super keyword to access parent class Test
class method {
class Person public static void main(String args[])
{ {
void message() Student s = new Student();
{
System.out.println("This is person
class"); s.display();
} }
} }
class Student extends Person
{
void message()
{
System.out.println("This is student
class");
}
void display()
{
message(); // it calls Student
class method
super.message(); // it calls
Person class method
} M.Srilatha Assistant Professor CSE
}
class Test
//Use of super with constructors: {
class Person public static void main(String[] args)
{ {
Person() Student s = new Student();
{ }
System.out.println("Person class }
Constructor");
}
}

class Student extends Person


{
Student()
{
// invoke or call parent class
constructor
super();

System.out.println("Student class
Constructor");
}
}
M.Srilatha Assistant Professor CSE
Method Overriding
• When a method in a subclass has the same name,
same parameters or signature and same return
type(or sub-type) as a method in its super-class,
then the method in the subclass is said to override
the method in the super-class. Example:

M.Srilatha Assistant Professor CSE


Example:
class Human
{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human
{
//Overriding method
public void eat()
{
System.out.println("Boy is eating");
}
public static void main( String args[])
{
Boy obj = new Boy();
obj.eat(); //This will call the child class version of eat()
} M.Srilatha Assistant Professor CSE
}
Dynamic Method Dispatch
• Method overriding is one of the ways in which
Java supports Runtime Polymorphism.
• Dynamic method dispatch is the mechanism by
which a call to an overridden method is resolved
at run time, rather than compile time.
• When an overridden method is called by a
reference, java determines which version of that
method to execute based on the type of object it
refer to.
• In simple words the type of object which it
referred determines which version of overridden
method will be called.
M.Srilatha Assistant Professor CSE
Let Us consider an Example

Upcasting
When Parent class reference variable refers to Child class object, it is
known as Upcasting

M.Srilatha Assistant Professor CSE


if a superclass contains a method that is
overridden by a subclass, then when different
types of objects are referred to through a
superclass reference variable, different
versions of the method are executed. Here is
an example that illustrates dynamic method
dispatch:

M.Srilatha Assistant Professor CSE


class A
{ class Dispatch
void m1() {
{ public static void main(String args[])
System.out.println("Inside A's m1 {
method"); // object of type A
} A a = new A();
} // object of type B
B b = new B();
class B extends A // object of type C
{ C c = new C();
// overriding m1() // obtain a reference of type A
void m1() A ref;
{ // ref refers to an A object
System.out.println("Inside B's m1 ref = a;
method"); // calling A's version of m1()
} ref.m1();
} // now ref refers to a B object
ref = b;
class C extends A // calling B's version of m1()
{ ref.m1();
// overriding m1() // now ref refers to a C object
void m1() ref = c;
{ // calling C's version of m1()
System.out.println("Inside C's m1 ref.m1();
method");
}
} M.Srilatha Assistant Professor CSE
}
}
Why Overriding Methods

it allows a general class to specify methods


that will be common to all of its derivatives,
while allowing subclasses to define the
specific implementation of some or all of
those methods. Overridden methods are
another way that Java implements the “one
interface, multiple methods” aspect of
polymorphism.

M.Srilatha Assistant Professor CSE


Using Abstract Class
• A class which is declared with the abstract keyword is
known as an abstract class in Java.
• It can have abstract and non-abstract methods
• the user will have the information on what the object
does instead of how it does it.
• Abstraction is a process of hiding the implementation
details and showing only functionality to the user.
• But, if a class has at least one abstract method, then
the class must be declared abstract.
• There are two ways to achieve abstraction in java
 Abstract class (0 to 100%)
 Interface (100%)

M.Srilatha Assistant Professor CSE


Points to Remember
• An abstract class must be declared with an
abstract keyword.
• It can have abstract and non-abstract methods.
• It can have constructors and static methods also.
• It can have final methods which will force the
subclass not to change the body of the method.

M.Srilatha Assistant Professor CSE


Example:
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}

M.Srilatha Assistant Professor CSE


final with inheritance

M.Srilatha Assistant Professor CSE


Packages
• A java package is a group of similar types of classes,
interfaces and sub-packages.
OR
• Package in Java is a mechanism to encapsulate a group
of classes, sub packages and interfaces.
OR
• It helps organize our classes into a folder structure
• Each package in Java has its unique name
• Package in java can be categorized in two form, built-in
package and user-defined package.
• There are many built-in packages such as java, lang,
awt, util etc.

M.Srilatha Assistant Professor CSE


Advantage of Java Package
1) Java package is used to categorize the classes
and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

M.Srilatha Assistant Professor CSE


Defining a package
• While creating a package, you should choose a name for the
package and include a package statement along with that
name at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that you want
to include in the package.
• The package statement should be the first line in the source
file
• There can be only one package statement in each source file
• If a package statement is not used then the class, interfaces,
enumerations, and annotation types will be placed in the
current default package.
Syntax for creating package:-
package nameOfPackage;
• We can create hierarch of package as follows
package pkg1[.pkg2][.pkg3];
• The package name is closely associated with the directory structure

M.Srilatha Assistant Professor CSE


Finding packages and CLASS PATH
• How does java runtime system knows path
(location) of our package?
it can be possible in three ways
1) by default: java uses the current working
directory as its starting point an if the package is
in a subdirectory of the current directory it will
be found
2) CLASSPATH is an environment variable needed
for the Java compiler and runtime to locate the
Java packages.
3) -classpath (-cp) options with java and javac to
specify the path to our class

M.Srilatha Assistant Professor CSE


Example for package
package myPackage; public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
public static void main(String args[])
{
MyClass obj = new MyClass();
obj.getNames(“hello”);
}
}

M.Srilatha Assistant Professor CSE


1. Write the source code
2. Save the file
3. Complie the source code
4. javac –d . Program name.java
This command forces the compiler to create a
package.
The "." operator represents the current working
directory.
5. Execute the code with fully qualified name of
class
java package name. program name

M.Srilatha Assistant Professor CSE


Accesses Protection In java
• Packages are meant for encapsulating, it works as
containers for classes and other subpackages.
• Class acts as containers for data and methods.
• There are four categories, provided by Java
regarding the visibility of the class members
between classes and packages:
1. Subclasses in the same package
2. Non-subclasses in the same package
3. Subclasses in different packages
4. Classes that are neither in the same package nor
subclasses
M.Srilatha Assistant Professor CSE
The three access modifiers are :
1. public
2. private
3. protected

While the access control mechanism of Java may seem


complicated, we can simplify it as follows.

Anything declared as public can be accessed from anywhere.


Anything declared as private can't be seen outside of its class.
M.Srilatha Assistant Professor CSE
Private Access Modifier - Private
• Methods, variables, and constructors that are
declared private can only be accessed within
the declared class itself.
• Private access modifier is the most restrictive
access level

M.Srilatha Assistant Professor CSE


Public Access Modifier - Public
• A class, method, constructor, interface, etc.
declared public can be accessed from any other
class. Therefore, fields, methods, blocks declared
inside a public class can be accessed from any
class belonging to the Java Universe.
• However, if the public class we are trying to
access is in a different package, then the public
class still needs to be imported. Because of class
inheritance, all public methods and variables of a
class are inherited by its subclasses.
M.Srilatha Assistant Professor CSE
Protected Access Modifier - Protected
• Variables, methods, and constructors, which
are declared protected in a superclass can be
accessed only by the subclasses in other
package or any class within the package of the
protected members' class.
• The protected access modifier cannot be
applied to class and interfaces. Methods,
fields can be declared protected, however
methods and fields in a interface cannot be
declared protected.
M.Srilatha Assistant Professor CSE
Importing Packages
• Java has import statement that allows you to
import an entire package or use only certain
classes and interfaces defined in the package.
1. To import entire package
If we use packagename.*, then all the classes
and interfaces of this package will be accessible
but the classes and interface inside the
subpackages will not be available for use.
2. To import only the classes/ interfaces
If we want to import class or interface then we
use packagename.classname

M.Srilatha Assistant Professor CSE


Example for package importing
package myPackage; public import myPackage.MyClass;
class MyClass public class PrintName
{ {
public void getNames(String s) public static void
{ main(String args[])
System.out.println(s); {
} String name = "GeeksforGeeks";
MyClass obj = new MyClass();
}
obj.getNames(name);
}
}

M.Srilatha Assistant Professor CSE


Interfaces in Java
Defining an interface
• Like a class, an interface can have methods and
variables, but the methods declared in interface are by
default abstract (only method signature, no body).
• A class implements an interface, thereby inheriting the
abstract methods of the interface.
• Interfaces specify what a class must do and not how.
• An interface is written in a file with a .java extension,
with the name of the interface matching the name of
the file.
Why do we use interface ?
• It is used to achieve total abstraction.
• Since java does not support multiple inheritance in
case of class, but by using interface it can achieve
multiple inheritance .
M.Srilatha Assistant Professor CSE
an interface is different from a class in several ways, including −
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that can appear
in an interface must be declared both static and final.
• An interface is not extended by a class; it is implemented by a class.
• An interface can extend multiple interfaces.
Declaring an interface Syntax :
public interface <interface_name>
{
// declare fields
// declare methods that abstract
}
• An interface is implicitly abstract. You do not need to use the abstract
keyword while declaring an interface.
• all fields are public, static and final by default.
• A class that implement interface must implement all the methods
declared in the interface.
• To implement interface use implements keyword.
M.Srilatha Assistant Professor CSE
Implementing Interfaces
• A class uses the implements keyword to
implement an interface.
• If a class does not perform(implements) all the
behaviors of the interface, the class must
declare itself as abstract.

M.Srilatha Assistant Professor CSE


Example for implementing interface
import java.io.*; public void printStates()
interface Vehicle {
{ System.out.println("speed: " + speed
void changeGear(int a); + " gear: " + gear);
void speedUp(int a); }
void applyBrakes(int a); }
} class GFG
class Bicycle implements Vehicle {
{
int speed; public static void main (String[] args)
int gear; {
public void changeGear(int Bicycle bicycle = new Bicycle();
newGear) bicycle.changeGear(2);
{ bicycle.speedUp(3);
gear = newGear; bicycle.applyBrakes(1);
} System.out.println("Bicycle present
public void speedUp(int increment) state :");
{ bicycle.printStates();
}
speed = speed + increment;
}
public void applyBrakes(int
decrement)
{
speed = speed - decrement;
}

M.Srilatha Assistant Professor CSE

You might also like