You are on page 1of 33

Strings in Java

1. strings in java are handled by two classes String &

StringBuffer

2. String -- Immutable class, StringBuffer - Mutable class


3. Constructors :
1. String() << Creates an Empty String >> 2. String(char chars[]) << Creates a String frorm char Array>> 3. String(char chars[],int start, int numChars)
<< Creates a String frorm char Array from start to start+numChars -1 >>

4. String(String x) << Creates a String frorm another String >> 5. String(byte bytes[]) << Creates a String frorm byte Array>> 6. String(byte bytes[],int start, int numChars)
<< Creates a String frorm byte Array from start to start+numChars -1 >>

String Examples
1. String s1 = Object OR String s1 = new String(Object); 2. String s1 = new String(); << Empty String Created>> 3. char[ ] names ={ O,B, J,E, C,T, ,O,R, I,E, N,T, E,D}; String s1 = new String(names); << s1 will be OBJECT ORIENTED>> String s2 = new String(names,2,4); << s2 will be JECT>> String s3 = new String(names,6,10); << StringIndexOutOfBoundsException>> String s4 = new String(names,6,-4); 4. byte[ ] values = { 10,45,67,34,68,66 }; << s1 will be -C"DB>> String s1 = new String(values); String s2 = new String(values, 2,3); << s2 will be C"D>> String s3 = new String(values,2,6); << StringIndexOutOfBoundsException>> 5. String s1 = Object; String s2 = new String(s1); << Creating String from another String>>

String Examples cont.. 6. String s1 =OOP; String s2 =OOP; String s3 =OOP; String s1 = new String(OOP);

String: s1 s2 s3 OOP

String Length
int length() << Returns the length of String>> Usage : <string>.length(); Examples : S.O.P(Object.length()); 6 s1.length(); name.length();

String Concatenation
Adding Strings together <<Concatenation>> + operator can be used to concatenate two strings

String concat(String other) method can also be used


Examples : 1. String s1 = Hello+How are You+20+20; 2. String s2 = Object String s3 = Programming String s4 = s2 + s3 OR String s4 = s2.concat(s3);

// s1 will be HelloHowareYou2020

3. System.out.println(xyz.concat(oop));
4. String s1 = 20+20+Hello+How are You; // s1 will be 40HelloHowareYou

Extracting a Single Character from a String


char charAt(int where) charAt() method extracts a character from a string at a given index <<where>> parameter should be within range (0 to stringlength-1).
Otherwise StringIndexOutOfBoundsException will be thrown

Examples : char ch = xyz.charAt(1); // ch will be y char ch = xyz.charAt(3);


//StringIndexOutOfBoundsException

Extracting More than one character getChars()


To Extract more than one character we can use getChars() method Syntax:
void getChars (int sourceStart, int sourceEnd, char target[ ], int targetStart)

Start index in End index in char Array where Invoking String Invoking String characters from string are to be Start index in char stored Array from where the characters are 1. characters will be extracted from sourceStart to be stored to sourceEnd-1 2. Extracted Characters will be stored in target[] char array from index targetStart 3. Every index either in invoking or target string should be within specified limits

class StringExamples { public static void main(String args[]) { String s1="object oriented";
char[] name = new char[10];

getChars() Example 1

s1.getChars(2,6,name,0);
for(int i=0;i<name.length;i++) System.out.print(name[i]+" "); System.out.println(" "); char[] name1 = new char[10];

s1.getChars(5,8,name1,3);
for(int i=0;i<name.length;i++) System.out.print(name1[i]+" "); } }

D:\java\bin>java StringExamples ject t o

getChars() Example 2
class StringExamples { public static void main(String args[]) { String s1="object oriented";
char[] name = new char[10];

s1.getChars(6,2,name,0);
for(int i=0;i<name.length;i++) System.out.print(name[i]+" "); System.out.println(" ");
char[] name1 = new char[10];

s1.getChars(8,5,name1,3);
for(int i=0;i<name.length;i++) System.out.print(name1[i]+" "); } }

D:\java\bin>java StringExamples Exception in thread "main" java.lang.StringIndexOutOfBoundsExce ption: String in ex out of range: -4 at java.lang.String.getChars(String.java:72 4) at StringExamples.main(StringExamples.ja va:8)

getChars() Example 3
class StringExamples { public static void main(String args[]) { String s1="object oriented";
char[] name = new char[10];

s1.getChars(0,13,name,0);
for(int i=0;i<name.length;i++) System.out.print(name[i]+" "); System.out.println(" ");
char[] name1 = new char[10];

s1.getChars(0,5,name1,3);
for(int i=0;i<name.length;i++) System.out.print(name1[i]+" "); } }

D:\java\bin>java StringExamples Exception in thread "main" java.lang.ArrayIndexOutOfBoundsE xception at java.lang.System.arraycopy(Native Method) at java.lang.String.getChars(String.jav a:726) at StringExamples.main(StringExampl es.java:8)

String to byte Arrays byte[ ]

byte[] getBytes[]

Useful when exporting a String values to 8-bit ASCII code.


class StringExamples { public static void main(String args[]) {

String s1="object oriented"; byte[] values = s1.getBytes();


for(int i=0;i<values.length;i++) System.out.print(values[i]+" "); } } D:\java\bin>java StringExamples 111 98 106 101 99 116 32 111 114 105 101 110 116 101 100

String to character Arrays char[ ] char[ ] toCharArray[ ]

Coverts a string to an character array


class StringExamples { public static void main(String args[]) {

String s1="object oriented"; char[ ] values = s1.toCharArray();


for(int i=0;i<values.length;i++) System.out.print(values[i]+" "); } } D:\java\bin>java StringExamples object oriented

String Comparisons
boolean equals(Object str) boolean equalsIgnoreCase(String str) Examples :
(i) xyz.equals(abc); << false>> (ii) xyz.equalsIgnoreCase(XYZ) << true> (iii) s1.equals(s2) << returns if s1 and s2 are equal>> (iv) s1.equalsIgnoreCase(s2) << returns if s1 and s2 are equal by ignoring case>>

Comparing Regions For matching


Used for comparing selected regions within strings. Two Methods can be used:
1. boolean regionMatches(int startIndex, String str2,int str2StartIndex, int numChars)

Start index within invoking String

Start index within str2 String


No of characters to be matched

String with whom invoking string will be matched

Comparing Regions For matching


2. boolean regionMatches(boolean ignorecase, int startIndex, String str2,int str2StartIndex, int numChars)

<< Used When matching is to be done by ignoring case>>

True means case is ignored


False means case is not ignored. Same as previous method

Region matches Examples


String s1 = It is time to start preparation for the incoming exams; String s2 = Indian team will start preparation for the match; String s3 = INDIAN TEAM WILL START PREPARATION FOR THE MATCH;

S1.regionMatches(4,s2,6,10); false S1.regionMatches(14,s2,17,17); true S1.regionMatches(14,s3,17,17); false S1.regionMatches(true,14,s2,17,17); true

boolean startsWith(String str) boolean endsWith(String str)


Can be used to check whether a string starts/ends with a string str or not Examples : object.startsWith(obj) << true>> Indians love cricket.endsWith(cricket); << true>> Second Form of startsWith allows to specify the starting point: boolean startsWith(String str, int startIndex); Indians love cricket.startsWith(love,8); << true>>
endsWith has only one form and is not available in boolean endsWith(String str, int startIndex);

equals Vs ==
String s1 = new String(OOP); String s2 = new String(OOP); if (s1 == s2) S.O.P(Hello); else S.O.P(Hi); How Many Objects are created? TWO What will be output? Hi

= = checks whether two string references are pointing to same string object or not. if (s1.equals(s2)) What will be output? S.O.P(Hello); Hello else S.O.P(Hi); equals( ) checks whether contents of two strings are pointing two same object or not.

equlas Vs == cont..
String s1 = new String(OOP); String s2 = s1 if (s1 == s2) S.O.P(Hello); else S.O.P(Hi); if (s1.equals(s2)) S.O.P(Hello); else S.O.P(Hi); How Many Objects are created? ONE What will be output? Hello

What will be output? Hello

int compareTo(String str) int compareToIgnoreCase(String str)

Used for String comparisons. Returns one of the three possible values: <0 invoking string is less than str >0 invoking string is greater than str =0 if both strings are equal Used for ordering/sorting strings

String Comparison Examples

String s1 = "OOP"; String s2 = "OOP"; String s3 = "java"; if( s1 == s2) System.out.println("Hello"); else System.out.println("Hi");

How Many Objects are created here?. ONE

System.out.println(s1.compareTo(s3)); System.out.println(s3.compareTo(s1));

Hello -27 27

Searching Strings

indexOf() lastIndexOf()
Used searching first/last occurences of a character / substring Return the index of character or substring if found otherwise -1 These two methods are overloaded in several different ways 1. int indexOf(int ch) / int lastIndexOf(int ch)

2. int indexOf(String str) / int lastIndexOf(String str)


3. int indexOf(int ch, int startIndex) / int lastIndexOf(int ch, int startIndex) 4. int indexOf(String str,startIndex) / int lastIndexOf(String str, int startIndex)

Example
String s1 = "Now is the time for all good men to come forward to aid their country";

System.out.println(s1.indexOf('t')); System.out.println(s1.lastIndexOf('t')); System.out.println(s1.indexOf("to")); System.out.println(s1.lastIndexOf("to")); System.out.println(s1.indexOf("to",35)); System.out.println(s1.lastIndexOf("to",35));

7 66 33 49 49 33

Extracting a SubString From String


1. 2. 3. 1. 2. 3. String substring(int startIndex) Returns a substring from invoking string starting form startIndex up to last of the invoking string I Love India.substring(7); startIndex <= invoking string length 1. String substring(int startIndex, int endIndex) Returns a substring from invoking string starting form startIndex up to endIndex-1 endIndex > startIndex and both should be within permitted range. I Love India.substring(2,6);

Substring Example
String s1 = "Now is the time for all good men to come forward to aid their country";

System.out.println(s1.substring(20));

Index 20 to end

all good men to come forward to aid their country


System.out.println(s1.substring(20,40));

Index 20 to 39

all good men to come


System.out.println("object oriented".substring(6));

oriented
System.out.println("object oriented".substring(5,10));

Index 6 to end

t ori

Index 5 to 9

Complete the Constructor

class Course { private String courseNo; private int compCode; private String courseName; Course(String courseString) { // courseString has first 10 places for courseNo // Next 4 places for comp code // Next 30 places for courseName
courseNo = courseString.substring(0,10); compcode = Integer.parseInt(courseString.substring(10,14)); courseName = courseString.substring(14); } }

Character Replacement in a String


1. 2. String replace(char original, char replacement) Replaces all occurences of one character with replacement character in the invoking string Hello.replace(l,w); << l with w>>

1. 2.
3.

String trim() Removes any leading and trailing whitespaces Hello World .trim(); << returns Hello World>> Useful for processing user commands

Changing Case of Characters Within a String 1. 2. String toLowerCase() String toUpperCase() Examples : S.O.P(object.toUpperCase()); S.O.P(OBJECT.toLowerCase());

String toString()
Converts any object reference to String form This method is by default supplied by Object class. toString() method in Object class returns the hascode value of Object in String form Any class can override this method with following syntax: public String toString() { .. return <anyString> }

class A { int a,b; A(int a,int b) { this.a = a; this.b = b; } }

This class A does not supply any toString() method. So it will be called from Object class

class test100 { public static void main(String args[]) { A a1 = new A(10,8); System.out.println(a1); } } HashCode of Object OUTPUT A@10b62c9 Name of class

class A { int a,b; A(int a,int b) { this.a = a; this.b = b; } public String toString() { return "a="+a+"b="+b; } }

This class A supplies a toString() method. So it will be called from class A itself class test100 { public static void main(String args[]) { A a1 = new A(10,8); System.out.println(a1); } }

a=10b=8
Change this statement to return Hello Java; Recompile and ReExcecute the Program

Home Exercise
1. 2. 3. void sort(String[] arr, boolean isAscending) void sort(String[] arr, int fromIndex, int toIndex, boolean isAscending) boolean isRefelexiveMirror(String other) RAM and MAR are reflexive mirrors XYZ and ZYX are reflexive mirrors object and tebojc are reflexive mirrors static boolean isRefelexiveMirror(String first, String second) boolean contains(String other) << whether a string contains other or not. static boolean contains(String f1, String f2)

You might also like