Java String

String in Java


String in Java

Definition: A string is a group of characters. In Java, String is class objects and implemented by two classes (String and String Buffer).  Java String Class is immutable (an immutable object you cannot modify any of its attribute’s values), it means once it is created, it cannot be changed on the same reference. It is denoted by a double quote.

Why java String is immutable? 

Ans: For better performance, it is immutable. A reference cannot be used to modify a String, it is safe to have many references to one String object.

String Methods:

The string is a "class" and as such has methods that are properties of the class.  To use a method, we need the dot operator.

length( )  This is a numerical returning method that gives the length of the string.  It returns an integer value.
Example:
String name=”inspireskill”;
 int l = name.length( );     //stores the length of a name into an int 
 System.out.println(l)   //prints the length
 Output: 12

charAt ()  This is a value returning method. The argument states which character to return. The subscripting of the locations of the characters starts with zero.
String str = "india";
System.out.println(str.charAt(1));
Output : n


trim()This method returns a string from which any leading and trailing whitespaces has been removed.  The string will not be changed in memory.
Example:
String str = "   hello  ";
System.out.println(str.trim());
Output: hello

toLowerCase()   method returns a string with all uppercase characters converted to lowercase.
Example:
String name = "INDIA";
System.out.println (name.toLowerCase() );
Outpu: india

toUpperCase() This method returns String

substring (Start, End)  This is a value returning method.  A string is returned beginning at Start subscript up to but not including the End subscript.
Example:
String sport = "football";
System.out.println (sport.substring (1,4) ); 
Output: oot
substring ( Start)  This is an alternate version.  It returns the substring beginning at Start subscript up to and including the end of the string.
Example:
String sport = "football";
System.out.println (sport.substring (4) );
Output: ball

indexOf() This method returns the index(Position number) of the String.
Example:
String str=”HELLO”;
int n=str.indexOf(‘E’);
System.out.println (n);
Output: 1



equals ( )   Used to compare two strings with the method to see if they are exactly the same, this includes any blanks or spaces within the string.

if (name.equals("INDIA");
System.out.println ( "The user entered INDIA.);


compareTo()  Compares strings to determine alphabetic location.  Returns a zero if the two strings are equal, a negative if the first string is alphabetically before the compared string, and a positive if the first string is alphabetically after the compared string.
Example:
String subject = "MUMBAI";
boolean answer;
answer = subject. compareTo ("CALCUTTA"); // returns is a positive
answer = subject. compareTo("PATNA"); // answer is negative
answer = subject.compareTo (" MUMBAI"); //answer is zero

endwith() This method is used to check whether a given String has specified suffix or not. It returns a boolean value(true/false).
String a=” HOWRAH IS CITY”;
String b=”CITY”;
boolean  ans=a.endwith(b);
System.out.println (ans);
Output: true

startwith()This method is used to check whether a given String has specified prefix or not. It returns a boolean value(true/false).
String a=” HOWRAH IS CITY”;
String b=”CITY”;
boolean  ans=a. startwith (b);
System.out.println (ans);
Output: false

Conversion from String to primitive types

We can use wrapper classes to convert from string to primitive types as follows:
String to integer, long, float, double type
String str=”100”;
int n=str.parseInt(str);
return 100 without quotes
String str=”28373100”;
long n=str.parseLong(str);
return 28373100 without quotes
 we can use valueOf() method also to convert the same.

Conversion from primitive to String types

toString() method is used to convert primitive to a String.
int n=250;
String s=Integer.toString(n)
Here an integer type gets converted to a string.


Some Java String program

String Palindrome in Java 

class StringPalindrom
{
            public static void main(String args[])
            {
                        String st="madam";
                        int l,i;
                        char s;
                        String rev="";
                        l=st.length();
                        for(i=0;i<l;i++)
                        {
                                    s=st.charAt(i);
                                    rev=s+rev;
                        }
                        if(st.equals(rev))
                                    System.out.println("Palindrom");
                        else
                                    System.out.println("Not Palindrom");
            }
}

// Java program for vowel counter

public class VowelFromWordFinder
{
    public static void main(String args[])
    {
        String st="the quick brown dog jump over";
        String word="";
        int i,l,l1,j,v;
        char ch,ch1;
        st=st+" ";
        l=st.length();
        for(i=0;i<l;i++)
        {
            v=0;
            ch=st.charAt(i);
            if(ch!=' ')
            {
                word=word+ch;
            }
            else
            {
                l1=word.length();
                for(j=0;j<l1;j++)
                {
                    ch1=word.charAt(j);
                    if(ch1=='a' || ch1=='e' || ch1=='i'|| ch1=='o' || ch1=='u')
                     v++;
                }
                System.out.println(word+" contain " + v+" vowel");
                        word="";
            }
        }
    }
}

// Java program for Word, Vowel, Consonant and Space counter

import java.io.*;
class Sentence
{
            public static void main(String args[])throws IOException
            {
                        String st="";
                        int i,l,v,c,space;
                        char a;
                        v=c=space=0;
                        InputStreamReader in=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(in);
                        System.out.println("Enter a sentence:");
                        st=br.readLine();
                        l=st.length();
                        for(i=0;i<l;i++)
                        {
                                    a=st.charAt(i);
                                    if(a=='a' || a=='A' || a=='e' || a=='E' || a=='i' || a=='I' || a=='o' || a=='O' || a=='u' || a=='U')
                                     v++;
                                     if(a==' ')
                                      space++;

                        }
                        c=l-(v+space);
                        System.out.println("Total Vowel="+v);
                        System.out.println("Total Space="+space);
                        System.out.println("Total Consonent="+c);
                        System.out.println("Total Words="+(space+1));
            }

}
Java program to print number into word
Become A Professional Java Developer From Scratch

//Bubble Sort Program using String data

public class BubbleSort
{
        public static void main(String arg[])
        {
            String n[]={"Zain","Akbar","Sham","Tony","Bokka"};
            int i,j,l;
            String t="";
            l=n.length;
            System.out.println("UnSorted order");
            for(i=0;i<l;i++)
            {
                System.out.print(n[i]+"  ");
            }
            for(i=0;i<l-1;i++)
            {
                for(j=0;j<(l-1)-i;j++)
                {
                    if(n[j].compareTo(n[j+1])>0)
                    {
                        t=n[j];
                        n[j]=n[j+1];
                        n[j+1]=t;
                    }
                }
            }
            System.out.println("\nSorted order");
            for(i=0;i<l;i++)
            {
                System.out.print(n[i]+"  ");
            }
        }
}


//Vowel, Lower and Upper program

import java.util.*;
class UpperLowerVowel
{
public static void main(String args[])
{
String st="";
int i,l,v,low,up;
char a;
v=low=up=0;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence:");
st=sc.nextLine();
l=st.length();
for(i=0;i<l;i++)
{
a=st.charAt(i);
if(a=='a' || a=='A' || a=='e' || a=='E' || a=='i' || a=='I' || a=='o' || a=='O' || a=='u' || a=='U')
v++;
if(Character.isLowerCase(a))
low++;
if(Character.isUpperCase(a))
up++;

}
System.out.println("Total Vowel="+v);
System.out.println("Total Lower="+low);
System.out.println("Total Upper="+up);

}
}


SHARE THIS
Previous Post
Next Post