Strings Handling :String functions in java ,string operations in java

 

String handling in java:
(OR)
String manipulations in java:


Strings represents a sequence of immutable characters.
Or
string is an object that represents a sequence of characters or char values. The java.lang.String class is used to create a Java string object.


--->The length of the String object is fixed. 


--->String object is immutable and cannot be modified. 


--->Strings are used for storing text.


How many ways we can create the string object?

There are two ways to create a String object:
1.Using string literal
2.Using new keyword


Strings may  be declared and created as follows:
1.By string literal :
Java String literal is created by using double quotes.


For Example: String s="HelloWorld";  


2.By new keyword : Java String is created by using a keyword "new".


For example:
String stringName;
StringName=new String("HelloWorld");

Or
We can combine above statements.
 String s=new String("HelloWorld");  

It creates two objects (in String pool and in heap) and one reference variable where the variable ‘s’ will refer to the object in the heap.


String Methods :

String class defines a number of methods that allow us to accomplish a variety of string manipulation task.

String manipulation or string operations in java :


1. length():
it is used to get the number of charecters of any string.
Or
It is used to return the length of given string in integer.


Example :
public class stringopera
{
public static void main(String args[])
{
String s="Java";
int l=s.length();
System.out.println("Length="+l);
}
}


Output:
Length=4


2. toUpperCase():
This is used to convert lowercase  string to uppercase.
Or
It is used to convert lowercase letters to uppercase.


Example :
public class stringopera
{
public static void main(String args[])
{
String s="Java";
s.toUpperCase();
System.out.println("Uppercase:"+s);
}
}


Output:
Uppercase: JAVA


3. toLowerCase():
This is used to convert uppercase  string to lowercase.
Or
It is used to convert uppercase letters to lowercase.


Example :
public class stringopera
{
public static void main(String args[])
{
String s="Java";
s.toLowerCase();
System.out.println("Lowercase:"+s);
}
}


Output:
Lowercase: java


4. concat() :
This method is used to combine two strings.

It is used for concatenation of 2 strings.


Example :
public class stringopera
{
public static void main(String args[])
{
String s1="omkar";
String s2="dengi";

System.out.println("combined string:"+s1.concat(s2));
}
}


Output:
combined string:omkardengi


5. trim() :
This method is used for remove whitespaces at begining and end of the string.
Or
It is used to remove space which are available before starting of string and after ending of string.


Example :
public class stringopera
{
public static void main(String args[])
{
String s=" Java ";
System.out.println("Before trim:"+s);
s.trim();
System.out.println("After trim:"+s);
}
}


Output:
Before trim:  Java
After trim:Java


6. charAt(index):
This method is used to get the character at a given index value.
Or
This will obtain a character from specified position.


Example :
public class stringopera
{
public static void main(String args[])
{
String s="Java";
char c=s.charAt(3);
System.out.println("character is="+c);
}
}


Output:
character is=a


7. indexOf(string):
This method is used to find the index value of given string.
It always gives the starting index value of first occurance of string.


Example :
public class stringopera
{
public static void main(String args[])
{
String s="Java is programming language";
int i=s.indexOf("programming");
System.out.println("index value is="+i);
}
}


Output :
Index value is:8


8. startsWith():
This method return true, if string is start with given another string otherwise false.


Example :
public class stringopera
{
public static void main(String args[])
{
String s="Java is programming language";

System.out.println(s.startsWith("Java"));
}
}


Output :
true


9. endsWith():
This method return true, if string is end with given another string otherwise false.


Example :
public class stringopera
{
public static void main(String args[])
{
String s="Java is programming language";

System.out.println(s.endsWith("language"));
}
}


Output :
true


10. subString():
This method is used to get the part of given string.
It is used to extract a substring from given string.

substring(n):it gives substring from nth character.


Example :
public class stringopera
{
public static void main(String args[])
{
String s="Java is programming language";

System.out.println(s.subString(8));
}
}


Output :
programming language


Or
Substring(n,m) :
It gives substring starting from nth character upto mth(not including mth).


Example :
public class stringopera
{
public static void main(String args[])
{
String s="Java is programming language";

System.out.println(s.subString(8,15));
}
}


Output:
program


11. replace():
This method is used to return a duplicate string by replacing old charecter with new charecter.

replace('x','y') :
It replaces all apperence of x with y.


Example :
public class stringopera
{
public static void main(String args[])
{
String s="java";
String S=s.replace(j,k)
System.out.println(S);
}
}


Output:
kava

Note:This method data of original string will never be modify.


12. equals() :
This method used to compare two strings. it returns true if contents of both strings are same otherwise false. it is case sensitive method.


Example :
public class stringopera
{
public static void main(String args[])
{
String s1="java";
String s2="omkar";
String s3="java";
System.out.println("compare string:"+s1.equals(s2));
System.out.println("compare string:"+s1.equals(s3));
}
}


Output:
compare string:false
compare string:true


13. equalsIgnoreCase():
This method is case insensitive.
It return true if the contents of both string are same otherwise false.


Example:
public class stringopera
{
public static void main(String args[])
{
String s1="java";
String s2="omkar";
String s3="OMKAR";
System.out.println("compare string:"+s1.equalsIgnoreCase(s2));
System.out.println("compare string:"+s2.equalsIgnoreCase(s3));
}
}


Output:
compare string:false
compare string:true


14. isEmpty():
This method is used to check whether the string contains anything or not.
If java string is empty, it returns true otherwise false.


Example:
public class stringopera
{
public static void main(String args[])
{
String s1="java";
String s2=" ";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}
}


Output:
false
true


15. compareTo():
This method is used to compare two strings by taking unicode values ,it returns 0 if the strings are same otherwise return +ve or -ve integer values.

Let us consider s1 & s2 are two strings.

-ve value: s1 is less than s2.(s1<s2)
+ve value:s1 is greater  than s2.(s1>s2)
0 value : s1 is equals to s2.


Example:
public class stringopera
{
public static void main(String args[])
{

String s1="omkar";
String s2="Omkar";
int i;
i=s1.compareTo(s2);
if(i==0)
{
System.out.println("strings are same");
}
else
{
System.out.println("strings are not same");
}
}
}


Output:
strings are  not same


16. compareToIgnoreCase():

It is case insensitive method .similar to compareTo() method.
is method is used to compare two strings by taking unicode values ,it returns 0 if the strings are same otherwise return +ve or -ve integer values.

Let us consider s1 & s2 are two strings.

-ve value: s1 is less than s2.(s1<s2)
+ve value:s1 is greater  than s2.(s1>s2)
0 value : s1 is equals to s2.


Example:
public class stringopera
{
public static void main(String args[])
{

String s1="omkar";
String s2="Omkar";
int i;
i=s1.compareToIgnoreCase(s2);
if(i==0)
{
System.out.println("strings are same");
}
else
{
System.out.println("strings are not same");
}
}
}


Output:
string are same.


17. join() :
it is used forJoining Strings.
It is used to concatenate two or more
strings, separating each string with a delimiter, such as a space or a comma. It has two forms.
Its first is shown here:
static String join(CharSequence delim, CharSequence . . . strs)
Here, delim specifies the delimiter used to separate the character sequences specified by strs.
Because String implements the CharSequence interface, strs can be a list of strings.
// Demonstrate the join() method defined by String.


Example :
class Stringopera
{
public static void main(String args[])
{
String s = String.join(" ", "Alpha", "Beta", "Gamma");
System.out.println(s);
}
}


Output:
Alpha Beta Gamma


Write a program to implement all string operations.
(OR)
Write a java program to perform all string manipulations.
Or

Write a Java program to demonstrate String handling methods.
Or
Write a java program to demonstrate atleast 5 string methods using Scanner  class.


Ans:


import java.util.*;
class StringOperation
{
    public static void main(String[] args)
      {
        String first="",second="";


        Scanner sc=new Scanner(System.in);
            System.out.println("String Operation");
            System.out.println();


            System.out.print("Enter the first Sting: ");
             first=sc.nextLine();
        System.out.print("Enter the second Sting: ");
              second=sc.nextLine();


            System.out.println("The strings are: "+first+" , "+second);


         System.out.println("The length of the first string is :"+first.length());


                System.out.println("The length of the second string is :"+second.length());


            System.out.println("The concatenation of first and second string is :"+first.concat(" "+second));


             System.out.println("The first character of " +first+" is: "+first.charAt(0));


            System.out.println("The uppercase of " +first+" is: "+first.toUpperCase());


            System.out.println("The lowercase of " +first+" is: "+first.toLowerCase());


            System.out.print("Enter the occurance of a character in "+first+" : ");
            String str=sc.next();
             char c=str.charAt(0);
            System.out.println("The "+c+" occurs at position " + first.indexOf(c)+ " in " + first);


             System.out.println("The substring of "+first+" starting from index 3 and ending at 6 is: " + first.substring(3,7));


            System.out.println("Replacing 'a' with 'o' in "+first+" is: "+first.replace('a','o'));      

 
            boolean check=first.equals(second);
            if(!check)
                System.out.println(first + " and " + second + " are not same.");
            else
                System.out.println(first + " and " + second + " are same."); 


    }
}


Output :
String operation
Enter the first Sting:
The World is Beautiful.
Enter the second String:
Learn to enjoy every moment.
The strings are: The World is Beautiful. , Learn to enjoy every moment.
The length of the first string is :23
The length of the second string is :28
The concatenation of first and second string is :The World is Beautiful. Learn to enjoy every moment.
The first character of The World is Beautiful. is: T
The uppercase of The World is Beautiful. is: THE WORLD IS BEAUTIFUL.
The lowercase of The World is Beautiful. is: the world is beautiful.
Enter the occurance of a character in The World is Beautiful. : e
The e occurs at position 2 in The World is Beautiful.
The substring of The World is Beautiful. starting from index 3 and ending at 6 is:  Wor
Replacing 'a' with 'o' in The World is Beautiful. is: The World is Beoutiful.
The World is Beautiful. and Learn to enjoy every moment. are not same



Write a java program to find reverse of an given string.

Or
java program to reverse a given string.


import java.lang.*;

import java.io.*;

import java.util.*;

public class strReverse
{
    public static void main(String[] args)
    {
    String s= "java"; 
int Length;
for(Length=s.length();Length >0;--Length)
{
System.out.print(stringInput.charAt(Length -1)); 
}

}

}


Output:
avaj


Write a java program to check whether a given string is palindrome or not.


Program:

import java.util.Scanner;
public class ChkPalindrome
{
public static void main(String args[])
{
String str, rev = " ";
Scanner sc = new Scanner(System.in);

System.out.println("Enter a string:");
str = sc.nextLine();

int length = str.length();

for ( int i = length - 1; i >= 0; i-- )
rev = rev + str.charAt(i);

if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
}
}


Output:
Enter a string:
MADAM
MADAM is a palindrome.


Write a program to add two strings using command line arguments.
Or

Java Program to Perform String Concatenation.


Ans :
class Stringopera
{
public static void main(String args[])
{
String s1=args[0]; //Accept first string command line
String s2=args[1]; //Accept second string command line
String s3= s1+s2;
System.out.println("Concatnated String is : "+s3);
}
}


( OR )

class Concats
{
public static void main(String args[])
{
String s1=args[0]; //Accept first string command line
String s2=args[1]; //Accept second string command line
String s3=s1.concat(s2);
System.out.println("Concatnated String is : "+s3);
}
}


What are different ways to represent string in java?
Or
How to represent string in java ?


There are 4 ways to represent string:
1.Character Array
2.string class
3.stringBuffer class
4.stringBuilder class

1.Character Array:
This is easiest way to represent sequence of characters in java is charecter array.


Example:
char []c=new char[5];
c[0]='H';
c[1]='e';
c[2]='l';
c[3]='l';
c[4]='o';

String s=new String(c);


2.String class:
It is used to create immutable string.


Example:
String s="Hello";


3.StringBuffer class:
It is used to create mutable string.


Example :
StringBuffer sb=new StringBuffer("Hello");


3.StringBuilder class:
It is used to create mutable string.
It is similar to StringBuffer class except that nonsynchronized.


Example :
StringBuilder sb=new StringBuilder("Hello");


Describe the following string class methods with examples :
(i) length()
(ii) charAt()
(iii) CompareTo()

Ans:

You  can refer above examples also:
1. length():


Syntax: int length()
It is used to return length of given string in integer.


Eg.
String str="INDIA"
System.out.println(str);
System.out.println(str.length());
// Returns 5


2. charAt():

Syntax: char charAt(int position)
The charAt() will obtain a character from specified position .


Eg.
String s="INDIA"
System.out.println(s.charAt(2) );
// returns D


3. compareTo():


Syntax:
int compareTo(Object o)

int compareTo(String anotherString)

There are two variants of this method. First method compares this String to another Object .
second method compares two strings lexicographically.


Eg.
String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";

int result = str1.compareTo( str2 );
System.out.println(result);
//0
result = str2.compareTo( str3 );
System.out.println(result);
//-ve or -ve value


Java String Pool: Java String pool refers to collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned.


Write a java program to implement following functions of string:
(1) Calculate length of string
(2) Compare between strings
(3) Concatenating strings

Ans:

class Stringopera
{
public static void main(String args[])
{
String str1="INDIA";
String str2="India";
String str3="My India";
String str4="India";
System.out.println("The length of string INDIA is "+str1.length());

System.out.println("Comparing String India and India is "+str2.equals(str4));

System.out.println("Comparing String INDIA and India is "+str1.equals(str2));

System.out.println("Comparing String INDIA and India with equalsIgnoreCase is
"+str1.equalsIgnoreCase(str2));

String str5="I Love";
System.out.println("Result of concatinating of string is "+str5.concat(str3));
}
}


Output :
The length of string INDIA is 5
Comparing String India and India is true
Comparing String INDIA and India is false
Comparing String INDIA and India with equalsIgnoreCase is true
Result of concatenating of string is 
I LoveMy India



Special String Operations(+) :

Java has added special support for several string operations within the syntax of the language.
These operations include the automatic creation of new String instances from string literals, concatenation of
multiple String objects by use of the + operator, and the conversion of other data types to a string representation. There are explicit methods available to perform all of these functions, but Java does them automatically as a convenience for the programmer and to add clarity.


Example:
public class stringopera
{
public static void main(String args[])
{
String s1="omkar";
String s2="dengi ";
String fullname=s1+s2;
System.out.println("Fullname:"+fullname);
}
}


Output:
Fullname:omkardengi

Comments

Popular posts from this blog

Control Statements:Selection statement ,Iteration statement and Jump statement in Java

Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of an applet, passing parameters to applets, applet security issues.

Java Database Connectivity (JDBC) ,Steps to connect to the database in Java