[go: up one dir, main page]

0% found this document useful (0 votes)
20 views31 pages

Unit 7 String, Packages and Interfaces

Uploaded by

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

Unit 7 String, Packages and Interfaces

Uploaded by

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

String, Packages and Interface

Subject: Object Oriented Programming Language using JAVA

Faculty name: Bhushan Shewale


• String:
1. String is a literal or data.

2. It is a group of character which are enclosed written double quotes are (“ ”).

3. It is a non – primitive multivalued data.

4. Non – primitive data always stored inside object.

5. We can store the string literal by creating object for the following classes.
a. java.lang.String ;
b. java.lang.StringBuffer ;
c. java.lang.StringBuilder ;

6. If you want to create one object you have ‘class’.

7. Whenever we create a string object, implicitly our compiler will create one object for java.lang.String class
inside the String Constant Pool.
• String Literal:

Anything which is enclose written inside in double quotes is known as String Literals.

• Characteristics of String Literals:

1. Whenever we used string literal in our java program an object is created implicitly by our
compiler for java.lang.String class inside String constant pool.

2. In case if the object is already present with same data then instead of creating new object,
the existing object reference is given.
Ex.
// When we give same data in the form of String Literal.
public class Demo
{
public static void main(String[] args)
{
String s1 = " Car ";
String s2 = " Car ";
System.out.println(s1 == s2 );
System.out.println(s1.equals(s2));
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
}
}

Note: In the string class the equals( ) method, hashCode( ), and toString( ) is already
overridden. Based on overridden it will compare two object on their states.
• java.lang.String

1. java.lang.String is a predefined class.

2. It is a final class in java hence we can not inherited string class.

3. String class inherits object class.

4. Inside string class toString ( ), hashCode ( ), equals ( ) of object class is overridden.

5. String class implements interfaces like comparable, serializable , char sequence.


• Constructor in String class:

1. String ( ) : It is used to creates an empty string object.

2. String ( string literal ) : It is used to creates string object by initializing with string literals.

3. String ( char[] ch) : It is used to creates strings by converting character array into string.

4. String ( byte[] b ) : It is used to creates string by converting byte array into string.

5. String ( stringBuffer sb ) : It is used to creates string by converting stringBuffer to String.

6. String ( stringBuilder sb ) : It is used to create to string by converting stringBuilder to


String.
Ex. String Literal
String s1 = new String(“Laila”);
String s2 = new String(“Laila”);
String s3 = new String(“Laila”);
Ex.
public class Demo1
{
public static void main(String[] args)
{
String s1 = new String("Laila");
String s2 = new String("Laila");
System.out.println(s1);
System.out.println(s2);
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}

Output
Laila
Laila
False
true
• String Handling Methods:

String Handling in Java the methods are provided by the String class that allow you to
manipulate, analyze, and work with strings. The String class is part of the java.lang package
and provides a full set of methods for various string operations. Here are some of the key
string handling functions in Java.
Method Description Return Type

charAt() Returns the character at the specified index (position) char

compareTo() Compares two strings lexicographically int

compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences int

concat() Appends a string to the end of another string String

contains() Checks whether a string contains a sequence of characters Boolean

compareTo() Compares two strings lexicographically int

compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences int

equals() Compares two strings. Returns true if the strings are equal, and false if not boolean

equalsIgnoreCase() Compares two strings, ignoring case considerations boolean

getBytes() Encodes this String into a sequence of bytes using the named charset, storing byte[]
the result into a new byte array
isEmpty() Checks whether a string is empty or not boolean

lastIndexOf() Returns the position of the last found occurrence of specified characters in a int
string

length() Returns the length of a specified string int

getChars() Copies characters from a string to an array of chars void

hashCode() Returns the hash code of a string int

indexOf() Returns the position of the first found occurrence of specified characters in a Int
string

split() Splits a string into an array of substrings String[]

substring() Returns a new string which is the substring of a specified string String
toCharArray() Converts this string to a new character array char[]

toLowerCase() Converts a string to lower case letters String

toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a string String

valueOf() Returns the string representation of the specified value String

These are just a subset of the many functions provided by the String class in Java.
Remember that strings in Java are immutable, meaning that operations that appear to modify
a string actually create a new string object. This is why classes like StringBuilder and
StringBuffer are often used when there are a lot of string concatenation or modification
operations involved.
Ex.
public class StringManipulation
{
public static void main(String[] args)
{
String s1 = new String("Hello");
String s2 = "Hello";
String s3 = "Hi";
String s4 = s3;
String s5 = new String("Hi");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(s3 == s4);
System.out.println(s3.equals(s4));
System.out.println(s5 == s3);
System.out.println(s5.equals(s3));
}

}
Ex.
public class StringManipulation
{
public static void main(String[] args)
{
String s1 = new String("Hello");
String s2 = new String("Hello");
String s3 = "Hello";
String s4 = "Hello";
String s5 = s1;
String s6 = s5;
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(s3 == s4);
System.out.println(s3.equals(s4));
System.out.println(s5 == s6);
System.out.println(s5.equals(s6));

}
Note: String is immutable in nature that’s why you cannot be modified the string. Still if you
try to modify the string object then the new object is created and modified data and reference
will return.
Ex.
public class StringImmutable
{
public static void main(String[] args)
{
String s1 = "Hello";
System.out.println(s1);
s1 = s1.concat(" World");
System.out.println(s1);

}
Que: How to iterate the String?
Ans:

public class StringIterate


{
public static void main(String[] args)
{
String s1 = " Rajnikant Anna!! ";
for(int i = 0; i <= s1.length()- 1; i++)
{
System.out.println(s1.charAt(i));
}
}
}
Que: How to reverse the string?
Ans:

public class StringIterate


{
public static void main(String[] args)
{
String s1 = " !!aanA takinjaR ";
for(int i = s1.length()-1; i>= 0; i--)
{
System.out.print(s1.charAt(i));
}

}
Que: How to Reverse the String with concatenation?
Ans:

public class ReverseString


{
public static void main(String[] args)
{
String s1 = "Hello";
String rev = " ";
for(int i = s1.length()-1; i>=0; i--)
{
rev = rev + s1.charAt(i);
}
System.out.println(rev);
}
}
Disadvantage:
1. String object is immutable in nature.
2. Whenever if we try to perform modification on string object a new object will created
which will occupy more memory and can reduced the performance of a program.
3. To overcome disadvantage of string we can make use of String Buffer and String Builder
classes.
• String Buffer( ):

1. It is inbuild class which is defined in java.lang package.

2. String Buffer class is to create mutable objects.

3. It is a final class.

4. String buffer doesn’t have string constant pool hence the object of String Buffer class are
mutable in nature.

5. String Buffer class inherits object of classes.

6. toString( ) method, hashCode( ) method and equals( ) method of object class are
overridden in String Buffer class.

7. It implements interface like series able and charSequance.


Constructor in string Buffer classes:
1. StringBuffer(): It creates an empty String buffer with the initial capacity of 16.
2. StringBuffer(String s): It creates a String buffer with the specified string..
3. StringBuffer(int capacity): It creates an empty String buffer with the specified capacity as
length.
Characteristics of String Buffer:
1. It is mutable in nature.
2. String constant pool is not applicable for string Buffer object.
3. If you want to go for frequently update then make used of String Buffer and String Builder
classes.
Disadvantages of String Buffer:
1. Multithread can’t execute the String Buffer object simultaneously because of all the
methods are synchronized. So execution time is more in order.
2. To overcome this problem we will go for String Builder.
Ex.
public class StringBuffer
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello, ");
sb1.append("World!");
System.out.println("After append: " + sb1);
sb1.insert(7, "Java ");
System.out.println("After insert: " + sb1);
sb1.delete(5, 9);
System.out.println("After delete: " + sb1);
sb1.reverse();
System.out.println("After reverse: " + sb1);
sb1.replace(0, 6, "Hi");
System.out.println("After replace: " + sb1);
int length = sb1.length();
System.out.println("Length of the buffer: " + length);
int capacity = sb1.capacity();
System.out.println("Capacity of the buffer: " + capacity);
sb1.ensureCapacity(20);
System.out.println("After ensuring capacity: " + sb1);
sb1.setLength(10);
System.out.println("After setting length: " + sb1);
}
}
• String Builder:
1. StringBuilder class is used to create mutable (modifiable) String.
2. The Java StringBuilder class is same as StringBuffer class except that it is non-
synchronized.
Constructor of String Builder:
1. StringBuilder(): It creates an empty String Builder with the initial capacity of 16.
2. StringBuilder(String s): It creates a String Builder with the specified string.
3. StringBuilder(int length): It creates an empty String Builder with the specified capacity as
length.
Ex.
public class StringBuilder
{
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder("Hello, ");
sb.append("World!");
System.out.println("StringBuilder: " + sb);
sb.insert(7, "Java ");
System.out.println("After insert: " + sb);
sb.delete(5, 9);
System.out.println("After delete: " + sb);
sb.reverse();
System.out.println("After reverse: " + sb);
sb.replace(0, 3, "Hi");
System.out.println("After replace: " + sb);
int length = sb.length();
System.out.println("Length of StringBuilder: " + length);
int capacity = sb.capacity();
System.out.println("Capacity of StringBuilder: " + capacity);
sb.ensureCapacity(20);
System.out.println("After ensuring capacity: " + sb);
sb.setLength(10);
System.out.println("After setting length: " + sb);
// Using StringBuffer (similar methods)
StringBuffer sb1 = new StringBuffer("Hello, ");
sb1.append("World!");
System.out.println("\nStringBuffer: " + sb1);
}
}
Que: Difference Between String and StringBuffer class

No. String StringBuffer


1) The String class is immutable. The StringBuffer class is mutable.
2) String is slow and consumes more memory StringBuffer is fast and consumes less memory
when we concatenate too many strings when we concatenate t strings.
because every time it creates new instance.

3) String class overrides the equals() method of StringBuffer class doesn't override the equals()
Object class. So you can compare the method of Object class.
contents of two strings by equals() method.

4) String class is slower while performing StringBuffer class is faster while performing
concatenation operation. concatenation operation.

5) String class uses String constant pool. StringBuffer uses Heap memory
Que: Difference between StringBuffer and StringBuilder

No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. thread safe. It StringBuilder is non-synchronized i.e. not thread
means two threads can't call the methods of safe. It means two threads can call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.

2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.

3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
• Importing Packages:
Importing packages in Java allows you to use classes from other packages in your code. It
helps you organize and modularize your codebase by separating functionalities into different packages.
Here's how you can import packages and classes in Java

1. Importing a Specific Class: If you want to use a specific class from a package, you can import it
using the import statement at the beginning of your Java file. For example, if you want to use the
ArrayList class from the java.util package.
Ex.
import java.util.ArrayList;
public class MyArrayListExample
{
public static void main(String[] args)
{
ArrayList<String> myList = new ArrayList<>();// Use the ArrayList class here
}
}
2. Importing the Entire Package:
You can also import the entire package using the import statement. This allows you to
use any class within that package without specifying the package name each time. However,
you need to be careful if there are class name conflicts between packages.
Ex.
import java.util.*;

public class MyArrayListExample


{
public static void main(String[] args)
{
ArrayList<String> myList = new ArrayList<>(); // Use the ArrayList class here
}
}

3. Using Fully Qualified Class Names:


If you don't want to import a package or if there are naming conflicts, you can use the
fully qualified class name (including the package name) to reference the class.
Ex.
public class MyArrayListExample
{
public static void main(String[] args)
{
java.util.ArrayList<String> myList = new java.util.ArrayList<>();

// Use the ArrayList class using the fully qualified name


}
}

Note:
1. Remember that classes from the java.lang package (like String) are automatically imported, so you
don't need to explicitly import them.
2. Import statements must appear at the beginning of your Java file, before the package statement (if
present) and before the class declaration.
3. It's good practice to only import the specific classes you need rather than importing entire
packages, as this helps keep your code more organized and prevents potential naming conflicts.
public class PalindromeNaiveMethod
{
public static boolean isPalindrome(String str)
{
String rev = " ";// Initializing an empty string to store the reverse of the
original str
boolean ans = false;// Initializing a new boolean variable for the answer
for (int i = str.length() - 1; i >= 0; i--)
{
rev = rev + str.charAt(i);
}
if (str.equals(rev)) // Checking if both the strings are equal
{
ans = true;
}
return ans;
}
public static void main(String[] args)
{
String str = "bhushan";// Input string
str = str.toLowerCase();// Convert the string to lowercase
boolean A = isPalindrome(str);
System.out.println(A);
}
}

You might also like