0% found this document useful (0 votes)
82 views

Strings: Developed by

Uploaded by

barla geetha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

Strings: Developed by

Uploaded by

barla geetha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Strings

Definition:- Strings are sequences of Unicode(Unicode is a universal character encoding standard)


characters. In many programming languages strings are stored in arrays of characters. However, in Java
strings are a separate object type, String. The "+" operator is used for concatenation, but all other
operations on strings are done with methods in the String class.
The CharSequence interface(it is similar to class. It is a collection of abstract methods) is used to
represent sequence of characters. It is implemented by String, StringBuffer and StringBuilder classes. It
means, we can create string in java by using these 3 classes.

The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new instance is
created. For mutable string, you can use StringBuffer and StringBuilder classes.
Java provides 4 types of string handling classes
String class -defined in “java.lang” package
- Once an object is created, no modifications can be done on that.
StringBuffer class and StringBuilder class– defined in “java.lang” package
- Modifications can be allowed on created object.
StringTokenizer class - defined in “java.util” package
- Used to divide the string into substrings based on tokens.
Declaration & Creation of String:
We can declare a string using String data type.
Syntax: String string_name; //Decl
Different Ways to Create String
There are many ways to create a string object in java, some of the popular ones are given below.
1. Using string literal
This is the most common way of creating string. In this case a string literal is enclosed with double quotes.
Example:String str = "abc";

When we create a String using double quotes, JVM looks in the String pool to find if any other String is
stored with same value. If found, it just returns the reference to that String object else it creates a new
String object with given value and stores it in the String pool.
2. Using new keyword
We can create String object using new operator, just like any normal java class. Java also supports the
creation & usage of arrays that contain strings .
Example
1 Developed by: Rajani, CSE Dept, RGUKT
String str = newString("abc");
char[] a = {'a', 'b', 'c'};
String str2 = newString(a);
//String( char chars[], int startIndex, int numChars)
//To create a string by specifying positions from an array of characters
char chars[]={„a‟,‟b‟,‟c‟,‟d‟,‟e‟,‟f‟};
String s=new String(chars,2,3);

Examples:-
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
Output:
Java
Java
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
Output:
ABCDEF
CDE

Creating Format Strings


printf() and format() methods to print output with formatted numbers. Using String's static format()
method allows you to create a formatted string that you can reuse, as opposed to a one-time print
statement.
Example
System.out.printf"The value of the float variable is %f while the value of the integer variable is %d, and
the string is %s\n", floatVar,intVar, stringVar);
String fs;
fs =String.format("The value of the float variable is "+

2 Developed by: Rajani, CSE Dept, RGUKT


"%f, while the value of the integer "+
"variable is %d, and the string "+
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);

String Methods:-
Method Call Return Task Performed
Type

s2=s1.toLowerCase() String Converts the string s1 to all lowercase

s2=s1.toUpperCase() String Converts the String s1 to all Uppercase

s2=s1.replace(„x‟,‟y‟) String Replaces all appearances of „x‟ with „y‟

s2=s1.trim() String Remove white spaces at the beginning & end of the
string s1

s1.equals(s2) Boolean Returns „true‟ if s1 is same as s2, same characters


in same order (case-sensitive) „false‟ otherwise

s1.equalsIgnoreCase(s2) Boolean „‟ „‟ , ignoring the case of characters

s1.length() Int Returns the no. of characters in s1

s1.charAt(n) char Returns the nth characters in s1

s1.getChars(m,n,c,0) Void Extracts more than one character at a time & copies
into a character array „c‟
m-source start
n-source end
0-Target start

s1.compareTo(s2) Int Returns zero, if s1=s2 (case sensitive)


-ve , if s1<s2
+ve , if s1>s2

s1.compareToIgnoreCase(s2) Int ignoring case sensitive

3 Developed by: Rajani, CSE Dept, RGUKT


s1.regionMatches(m,s2,n,c) Boolean Compares a specific region inside a string with
another specific region in another string
True if same
Else False
m-start index of s1
n-start index of s2
c-no. of characters to compare

s1.regionMatches(B,m,s2,n,c) Boolean if B is true ,ignores case

s1.indexOf(„ch‟) Int Searches for the 1st occurrence of a character or


s1.indexOf(“str”) string in s1 & returns the index value else returns „-
1‟

s1.indexOf(„ch‟,n) Int „‟ „‟ from the nth position in s1


s1.indexOf(“str”,n)

s1.lastIndexOf(„ch‟) Int Searches for last occurrence of a character or string


s1.lastIndexOf(“str”) in s1. The search is performed from the end of the
string towards beginning & returns the index value
else „-1‟

S1.lastIndexOf(„ch‟,n) Int „‟ „‟ from the nth position from end to


S1.lastIndexOf(“str”,n) begin

S1.substring(n) String Gives substring starting from nth character

S1.substring(n,m) String „‟ „‟ „‟ upto mth character


( not including mth character )

S1.startsWith(“str”) Boolean Determines whether a given string „s1‟ begins with


a specific string or not

S1.endsWith(“str”) Boolean „‟ „‟ „‟ „‟ ends „‟


„‟

S1.concat(s2) String Concatenates s1&s2 stored

S1.toCharArray() Char [ ] Returns a character array containing a copy of the


characters in a string

4 Developed by: Rajani, CSE Dept, RGUKT


o.toString() String Converts all objects into string objects

String.valueOf(o) String Creates a string object of the parameter „o‟ (Simple


type or Object type)

String.valueOf(var) String Converts the parameter value to String


representation
Examples using above methods
Example 1:
import java.util.Arrays;
import java.util.Scanner;
class str {
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
//System.out.println("Enter any string ");
//String s=in.nextLine();
String s="cat dog rat cat tiger rat dog rat";
System.out.println(s);
System.out.println("Lower case: "+s.toLowerCase());
System.out.println("Upper case: "+s.toUpperCase());
System.out.println("String replace: "+s.replace("cat","goat"));// goat dog rat goat tiger rat dog rat
System.out.println("String lenght: "+s.length());
System.out.println("Character at index: "+s.charAt(4));
System.out.println("Trim the string: "+s.trim());
System.out.println(s);
String s1="Hello";
String s2="hello";
System.out.println("Euqal: " +s1.equals(s2));//Output:false
System.out.println("Equal Ignorecase: "+s1.equalsIgnoreCase(s2));//Output:true
System.out.println("compareTo: " +s1.compareTo(s2));//Output:-32
System.out.println("first occurrence of a string: "+s.indexOf("cat"));//0
System.out.println("last occurrence of a string: "+s.lastIndexOf("cat"));//12
System.out.println("first occurrence of a string: "+s1.indexOf("l",3));//3
System.out.println("last occurrence of a string: "+s1.lastIndexOf("l",4));//3
System.out.println("sub string: "+s1.substring(2));//llo
System.out.println("sub string: "+s1.substring(2,3));//l
System.out.println("starts with: "+s1.startsWith("he"));
System.out.println("ends with: "+s1.endsWith("lo"));
System.out.println("Concat two strings "+s1.concat(s2) );
char s3[]=new char[s1.length()];
s3=s1.toCharArray();
System.out.println(Arrays.toString(s3));
}

5 Developed by: Rajani, CSE Dept, RGUKT


}

Example 2(Character Extratction using getChars method)

class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println (buf);
}
}
Output:
demo

Example 3 (getBytes() Method)

class GetBytesDemo{
public static void main(String[] args){
String str = "abc“ + ”ABC”;
byte[] b = str.getBytes();
//char[] c=str.toCharArray();
System.out.println(str);
for(int i=0;i<b.length;i++){
System.out.print(b[i]+"");
//System.out.print(c[i]+"");
}
}
}
Output:

97 98 99 65 66 67
//a b c A B C

String Comparison:
1. boolean equals(Object str)
To compare two strings for equality. It returns true if the strings contain the same characters in the
same order, and false otherwise.
2. boolean equalsIgnoreCase(String str)
To perform a comparison that ignores case differences.
Example 4
// Demonstrate equals() and equalsIgnoreCase().

6 Developed by: Rajani, CSE Dept, RGUKT


class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
System.out.println(s1.equalsIgnoreCase(s4));
}
}
Output:
true
false
false
true

String Comparison using regionMatches Method:-


boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)
 The regionMatches( ) method compares a specific region inside a string with another specific
region in another string.
 startIndex specifies the index at which the region begins within the invoking String object.
 The String being compared is specified by str2. The index at which the comparison will start
within str2 is specified by str2StartIndex.
 The length of the substring being compared is passed in numChars.
Example 5:-
class RegionTest{
public static void main(String args[]){
String str1 = "This is Test";
String str2 = "THIS IS TEST";
if(str1.regionMatches(5,str2,5,3)) {
// Case, pos1,secdString,pos1,len
System.out.println("Strings are Equal");
}
else{
System.out.println("Strings are NOT Equal");
}
}
}
Output:
Strings are NOT Equal
Example 6
//Sorting of String using compareTo method.

7 Developed by: Rajani, CSE Dept, RGUKT


class SortString {
public static void main(String args[]) {
String arr[] = { "good","morning","students","welcome","to","java"};
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
Java String split() Method

Java Stringsplit method is used for splitting a String into its substrings based on the given delimiter.
Syntax
String[] split(String regex)
String[] split(String regex, int limit)

This Java String split method is used when we want the substrings to be limited. The only difference
between this method and above method is that it limits the number of strings returned after split up. For
e.g. split("anydelimiter", 3) would return the array of only 3 strings even if the delimiter is present in the
string more than 3 times.
If the limit is negative then the returned array would be having as many substrings as possible however
when the limit is zero then the returned array would be having all the substrings .
Java String join() Method
The java.lang.string.join() method concatenates the given elements with the delimiter and returns the
concatenated string.Note that if an element is null, then null is added

Example

import java.util.Arrays;

public class split_join{

public static void main(String[] args) {


String line = "I am a java developer";

String[] words = line.split(" ");

8 Developed by: Rajani, CSE Dept, RGUKT


String[] twoWords = line.split(" ", 2);

System.out.println("String split with delimiter: " + Arrays.toString(words));

System.out.println("String split into two: " + Arrays.toString(twoWords));

// split string delimited with special characters


String wordsWithNumbers = "I,am,a,java,developer";

String[] numbers = wordsWithNumbers.split(",");

System.out.println("String split with special character: " + Arrays.toString(numbers));


String gfg1 = String.join(" ",words);

System.out.println(gfg1);

}
}

StringBuffer Class:
Java StringBuffer class is used to create mutable (modifiable) string object. A string buffer is like a String,
but can be modified.
As we know that String objects are immutable, so if we do a lot of modifications to String objects, we may
end up with a memory leak. To overcome this we use StringBuffer class.
StringBuffer class represents growable and writable character sequence. It is also thread-safe i.e. multiple
threads cannot access it simultaneously.
Every string buffer has a capacity. As long as the length of the character sequence contained in the string
buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the
internal buffer overflows, it is automatically made larger.

StringBuffer Constructors

 StringBuffer ( ) : Creates an empty string buffer with the initial capacity of 16.
 StringBuffer ( int capacity ) : Creates an empty string buffer with the specified capacity as
length.
 StringBuffer ( String str ) : Creates a string buffer initialized to the contents of the specified
string.

Methods

1) StringBuffer append() method


The append() method concatenates the given argument with this string.
9 Developed by: Rajani, CSE Dept, RGUKT
class StringBufferExample{
public static void main(String args[]){
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.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}

3) StringBuffer replace() method

The replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
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.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

5) StringBuffer reverse() method

The reverse() method of StringBuilder class reverses the current string.

10 Developed by: Rajani, CSE Dept, RGUKT


class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

6) StringBuffer capacity() method

The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity
of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity
by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
StringBuilder
 StringBuilder is same as the StringBuffer , that is it stores the object in heap and it can also be
modified .
 The main difference between the StringBuffer and StringBuilder is that StringBuilder is not thread
safe. StringBuilder is fast as it is not thread safe .
Constructors:
 StringBuilder demo2= new StringBuilder("Hello");
The above object too is stored in the heap and its value can be modified
 demo2=new StringBuilder("Bye");
Above statement is right as it modifies the value which is allowed in the StringBuilder

String Tokenizer class:-


 The string tokenizer class allows an application to break a string into tokens.
 The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings,
nor do they recognize and skip comments.
 StringTokennizer class is used to split a String into different tokens as by defined delimiter.(space
is the default delimiter).
Constructors:-
1. StringTokenizer(String str) :
str is string to be tokenized. Considers default delimiters like new line, space, tab, carriage return
and form feed.
2. StringTokenizer(String str, String delim) :
delim is set of delimiters that are used to tokenize the given string.

11 Developed by: Rajani, CSE Dept, RGUKT


3. StringTokenizer(String str, String delim, boolean flag):
The first two parameters have same meaning.

The flag serves following purpose.

If the flag is false, delimiter characters serve to separate tokens. For example, if string is "hello
RGUKT" and delimiter is "", then tokens are "hello" and "RGUKT".

If the flag is true, delimiter characters are considered to be tokens. For example, if string is "hello
RGUKT" and delimiter is " ", then tokens are "hello", " " and "RGUKT".
Methods
 int countTokens( ) //returns number of tokens in the string.
 boolean hasMoreTokens( ) //checks whether tokens are there or not
 String nextToken( ) //returns the token in the string

Example 1

import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}

Example 2:-
import java.util.StringTokenizer;
public class StringTokenizer_Test {
static String str = "Hello,Welcome,to,Java,Programming";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(str);
StringTokenizer st1 = new StringTokenizer(str,",");
StringTokenizer st2 = new StringTokenizer(str,",",true);
while(st.hasMoreTokens()) {
String tokens = st.nextToken();
System.out.print(tokens + "\n");
}
while(st1.hasMoreTokens()) {
String tokens = st1.nextToken();
System.out.print(tokens + "\n");
}
while(st2.hasMoreTokens()) {
String tokens = st2.nextToken();
System.out.print(tokens + "\n");
}
}
}
Output:
12 Developed by: Rajani, CSE Dept, RGUKT
Hello,Welcome,to,Java,Programming
Hello
Welcome
to
Java
Programming
Hello
,
Welcome
,
to
,
Java
,
Programming

Exercise

1. Write a Java program to find Length of the longest substring?


import java.util.Arrays;
class longeststring{
public static void main(String[] args){
String str = "hello good morning students";

String[] c=str.split(" ");


System.out.println(Arrays.toString(c));
int l=(c[0].length());
String k=c[0];
for(int i=1;i<c.length;i++)
{
if(c[i].length()>l);
k=c[i];
}
System.out.println("longest word is : "+k);

}
}

2. Write a Java program to read a string and return true if it ends with "ing".?
import java.util.Scanner;
class test {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);

String s = in.next();
13 Developed by: Rajani, CSE Dept, RGUKT
int l=s.length()-3;
if(s.substring(l).equals("ing"))
System.out.println("string ends with ing");
else
System.out.println("String not ends with ing");

}
}
3. Write a java program that reads a line of integers and then displays each integer and find the
sum of the integers (using StringTokenizer)?
import java.util.Scanner;
import java.util.*;
class Token{
static int sum=0;
public static void main(String sree[]){
Scanner s=new Scanner(System.in);
System.out.print("Enter sum of integers: ");
String str=s.next();
StringTokenizer st=new StringTokenizer(str,"+");
while(st.hasMoreTokens()){
sum=sum+Integer.parseInt(st.nextToken());
}
System.out.println("Sum of "+str+“is: "+sum);
}
}
Input:
Enter sum of integers: 10+20+30+40
Output:
Sum of 10+20+30+40 is: 100

14 Developed by: Rajani, CSE Dept, RGUKT

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy