Published April 24, 2024

All About String In Java

String represents a sequence of characters. It is immutable, meaning once created, its value cannot be changed. But If someone try to change then, the updated data would stored in new Stirng object with same reference.

image

String represents a sequence of characters. It is immutable, meaning once created, its value cannot be changed. But If someone try to change then, the updated data would stored in new Stirng object with same reference.

String str="India";
System.out.println(str);  //India
String ctr=new String("India");//create new object whether same content found or not
String ptr="India";
String ktr=str;
str=str+"n"; //creating new object and store the updated data

System.out.println(str);  //Indian

How many objects and references in the above code:
Number of reference=4
Number of object=3

There are two ways to create a String object:

By string literal : String literal is created by using double quotes.
String str="India";

By new keyword : It is created by using a keyword "new".
String ptr=new String("India"); 

Java String Pool: It refers to collection of Strings which are stored in heap memory.

String is in java lang package. String class having N number of methods:
String str = "Welcome to Cyberinfomines.com";
System.out.println(str); 
// Output: Welcome to Cyberinfomines.com

length():
It returns the length of the string(count number of characters including spaces also.
        int size=str.length();
        System.out.println("length of str is :"+size); //29

charAt(int index): 
It returns the character at the specified index.
System.out.println(str.charAt(8));

substring(int beginIndex): 
It returns a substring starting from the specified index.
System.out.println(str.substring(11)); //Cyberinfomines.com

substring(int beginIndex, int endIndex): 
It returns a substring from the specified begin index to the end index (exclusive).
System.out.println(str.substring(11,25)); //Cyberinfomines

indexOf(String str): 
It returns the index of the first occurrence of the specified substring.
System.out.println(str.indexOf("C")); //11

contains(CharSequence s): 
It checks if the string contains the specified sequence of characters.
System.out.println(str.contains("fomi")); //true

toUpperCase(): 
It converts all characters in the string to uppercase.

toLowerCase(): 
It converts all characters in the string to lowercase.

trim(): 
It removes leading and trailing white spaces.

split(String regex): 
It splits the string into an array of substrings based on the given regular expression.

boolean endsWith(String suffix)
It tests if this string ends with the specified suffix.


boolean equals(Object anObject)
It compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)
It compares this String to another String, ignoring case considerations.

int compareTo(String anotherString)
It compares two strings lexicographically.

int compareToIgnoreCase(String str)
It compares two strings lexicographically, ignoring case differences.

String concat(String str)
It concatenates the specified string to the end of this string.

int hashCode()
It returns a hash code for this string.

boolean isEmpty()
It returns true if, and only if, length() is 0.

int lastIndexOf(int ch)
It returns the index within this string of the last occurrence of the specified character.

int lastIndexOf(int ch, int fromIndex)
This method returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
malayalam

int lastIndexOf(String str)
It returns the index within this string of the rightmost occurrence of the specified substring.

int lastIndexOf(String str, int fromIndex)
It returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.


String toString()
It returns the string itself.

static String valueOf(boolean b)
This method returns the string representation of the boolean argument.

static String valueOf(char c)
It returns the string representation of the char argument.

static String valueOf(char[] data)
This method returns the string representation of the char array argument.

static String valueOf(double d)
It returns the string representation of the double argument.

static String valueOf(float f)
It returns the string representation of the float argument.

static String valueOf(int i)
This method returns the string representation of the int argument.

static String valueOf(long l)
It returns the string representation of the long argument.

static String valueOf(Object obj)
It returns the string representation of the Object argument.

Use Case1:
You are required to get name of a person as firstName, lastName and surName.
Make short name.

Test Case1:
firstName="Sanjay";
lastName="Kumar";
surname="Chandel";

Output:
shortName=S.K.Chandel

Test Case2:
firstName="sanjay";
lastName="kumar";
surname="chandel";

Output:
shortName=S.K.Chandel

Test Case3:
firstName="SANJAY";
lastName="KUMAR";
surname="CHANDEL";

Output:
shortName=S.K.Chandel
sol:
public class StringBasic {
    public static  String getShortName(String firstName,String lastName,String surName){
        String shortName=firstName.toUpperCase().charAt(0)
                +"."+lastName.toUpperCase().charAt(0)
                +"."+surName.toUpperCase().charAt(0)
                +surName.toLowerCase().substring(1);
        return shortName;
    }
    public static void main(String[] args) {
        System.out.println(getShortName("Sanjay","kumar","Chandel"));
        System.out.println(getShortName("sanjay","kumar","chandel"));
        System.out.println(getShortName("SANJAY","KUMAR","CHANDEL"));
    }
}

Use Case2:
You are required to make an application that works for all scenarios:
Test Case1:
Integrated Development Environment

Expected Output:
IDE

Test Case2:
Local area NETWORK

Expected Output:
LAN

Test Case3:
No Issue

Expected Output:
Requirement is not enough, pass a string having 3 words

Solution:
    public static  void getShortName(String str){
        String ans="";
        String arr[]=str.split(" ");
        if(arr.length!=3) {
            System.out.println("Requirement is not enough, pass 3 words");
        }
        else {
            for(String i:arr) {
                ans+=i.toUpperCase().charAt(0);
            }
        }
        System.out.println(ans);
    }


Use Case3:
You are required to get a string and check whether it is palindrom or not with following test cases.

Test Case1:
Input:
Vt
Output:
ERROR: At least 3 characters required as input

Test Case2:
Input:
Madam

Output:
Yes, It is a palindrome

Test Case3:
Input:
computer

Output:
Its not a palindrome
Solution:
public static int palindrome(String st) {
        int start=0,end=st.length()-1;
        if(st.length()<3) {
            return -1;
        }
        for(int i=0;i<st.length()/2;i++) {
            if(st.charAt(start)==st.charAt(end)) {
                start++;
                end--;
                continue;
            }else {
                return 0;
            }
        }
        return 1;
    }

StringBuffer:
The StringBuffer class is mutable and provides methods to modify strings. It is synchronized, making it safe for use in multithreaded environments.


StringBuffer buffer = new StringBuffer("Hello");
buffer.append(", World!");
System.out.println(buffer); // Output: Hello, World!

append(String str): 
Add the specified string to the end of the buffer.

insert(int offset, String str): 
It inserts the specified string at the specified offset.

delete(int start, int end): 
Deletes characters from the buffer.

reverse(): 
Reverses the characters in the buffer.

replace(int start, int end, String str): 
Replaces characters in the buffer with the specified string.

 

StringBuilder:
The StringBuilder class is similar to StringBuffer but is not synchronized, making it more efficient in single-threaded environments.

StringBuilder builder = new StringBuilder("Hello");
builder.append(", World!");
System.out.println(builder); // Output: Hello, World!

append(String str): 
It appends the specified string to the end of the builder.

insert(int offset, String str): 
It inserts the specified string at the specified offset.

delete(int start, int end): 
Deletes characters from the builder.

reverse(): 
Reverses the characters in the builder.

replace(int start, int end, String str): 
Replaces characters in the builder with the specified string.

 

StringTokenizer
It allows an application to break strings into tokens. 
It implements the Enumeration interface. It is used for parsing data. 
To use the String Tokenizer class we have to specify an input string and a string that contains delimiters. Delimiters are the characters that separate tokens.

Use Case 1: Word Count
Write a Java program that takes a sentence as input and counts the number of words in it.

Solution:
import java.util.StringTokenizer;
public class WordCount {
    public static void main(String[] args) {
        String sentence = "This is a sample sentence.";
        StringTokenizer tokenizer = new StringTokenizer(sentence);
        int wordCount = tokenizer.countTokens();
        System.out.println("Word count: " + wordCount);
    }
}

Use Case 2: Reverse Words:
Get a string from user and find out its reverse.

Solution:
import java.util.StringTokenizer;
public class ReverseWords {
    public static void main(String[] args) {
        String sentence = "This is a sample sentence.";
        StringTokenizer tokenizer = new StringTokenizer(sentence);
        StringBuilder reversed = new StringBuilder();
        while (tokenizer.hasMoreTokens()) {
            reversed.insert(0, tokenizer.nextToken() + " ");
        }
        System.out.println("Reversed sentence: " + reversed.toString().trim());
    }
}

Use Case 3: Extract Numbers
Java code to extract numbers from a string and calculate their sum.

Solution:
import java.util.StringTokenizer;
public class ExtractNumbers {
    public static void main(String[] args) {
        String str = "There are 10 apples, 20 bananas, and 5 oranges.";
        StringTokenizer tokenizer = new StringTokenizer(str);
        int sum = 0;
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            if (token.matches("\\d+")) { // Check if token is a number
                sum += Integer.parseInt(token);
            }
        }
        System.out.println("Sum of numbers: " + sum);
    }
}

Try Now Answer Of Following:
Why String objects are immutable?
How to create an immutable class?
What is string constant pool?
What code is written by the compiler if you concatenate any string by + (string concatenation operator)?
Why String class is Final in Java?
What is the difference between StringBuffer and StringBuilder class?

Download Lecture Pdf..

Reviews

Leave a Comment