> << s2 will be “ C"D”>> << StringIndexOutOfBoundsException>> << Creating String from another String>>"> > << s2 will be “ C"D”>> << StringIndexOutOfBoundsException>> << Creating String from another String>>">
Download presentation
Presentation is loading. Please wait.
Published byUriel Huitt Modified over 9 years ago
1
Strings in Java 1. strings in java are handled by two classes String &
StringBuffer 2. String -- Immutable class, StringBuffer - Mutable class 3. Constructors : String() 2. String(char chars[]) 3. String(char chars[],int start, int numChars) 4. String(String x) 5. String(byte bytes[]) 6. String(byte bytes[],int start, int numChars) << Creates an Empty String >> << Creates a String frorm char Array>> << Creates a String frorm char Array from start to start+numChars -1 >> << Creates a String frorm another String >> << Creates a String frorm byte Array>> << Creates a String frorm byte Array from start to start+numChars -1 >>
2
String Examples String s1 = “Object” OR String s1 = new String(“Object”); String s1 = new String(); 3. char[ ] names ={ ‘O’,’B’, ‘J’,’E’, ‘C’,’T’, ‘ ‘,‘O’,’R’, ‘I’,’E’, ‘N’,’T’, ‘E’,’D’}; String s1 = new String(names); String s2 = new String(names,2,4); String s3 = new String(names,6,10); String s4 = new String(names,6,-4); 4. byte[ ] values = { 10,45,67,34,68,66 }; String s1 = new String(values); String s2 = new String(values, 2,3); String s3 = new String(values,2,6); 5. String s1 = “Object”; String s2 = new String(s1); << Empty String Created>> << s1 will be “OBJECT ORIENTED”>> << s2 will be “JECT”>> << StringIndexOutOfBoundsException>> << s1 will be “ -C"DB”>> << s2 will be “ C"D”>> << StringIndexOutOfBoundsException>> << Creating String from another String>>
3
String s1 = new String(“OOP”);
String Examples cont.. String s1 =“OOP”; String s2 =“OOP”; String s3 =“OOP”; String s1 = new String(“OOP”); String: s1 OOP s2 s3
4
String Length int length() << Returns the length of String>> Usage : <string>.length(); Examples : S.O.P(“Object”.length()); s1.length(); name.length(); 6
5
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); 3. System.out.println(“xyz”.concat(“oop”)); 4. String s1 = “Hello”+”How are You”; // s1 will be “HelloHowareYou2020” // s1 will be “40HelloHowareYou”
6
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
7
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 Invoking String End index in Invoking String char Array where characters from string are to be stored Start index in char Array from where the characters are to be stored characters will be extracted from sourceStart to sourceEnd-1 Extracted Characters will be stored in target[] char array from index targetStart Every index either in invoking or target string should be within specified limits
8
D:\java\bin>java StringExamples j e c t t o
getChars() Example 1 class StringExamples { public static void main(String args[]) String s1="object oriented"; char[] name = new char[10]; 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); System.out.print(name1[i]+" "); } D:\java\bin>java StringExamples j e c t t o
9
getChars() Example 2 s1.getChars(6,2,name,0); 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); System.out.print(name1[i]+" "); } D:\java\bin>java StringExamples Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String in ex out of range: -4 at java.lang.String.getChars(String.java:724) at StringExamples.main(StringExamples.java:8)
10
getChars() Example 3 s1.getChars(0,13,name,0); 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); System.out.print(name1[i]+" "); } D:\java\bin>java StringExamples Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at java.lang.System.arraycopy(Native Method) at java.lang.String.getChars(String.java:726) at StringExamples.main(StringExamples.java:8)
11
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
12
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 o b j e c t o r i e n t e d
13
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>>
14
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
15
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
16
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
17
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);
18
equals Vs == String s1 = new String(“OOP”);
How Many Objects are created? TWO if (s1 == s2) S.O.P(“Hello”); else S.O.P(Hi”); What will be output? Hi = = checks whether two string references are pointing to same string object or not. if (s1.equals(s2)) S.O.P(“Hello”); else S.O.P(Hi”); What will be output? Hello equals( ) checks whether contents of two strings are pointing two same object or not.
19
equlas Vs == cont.. String s1 = new String(“OOP”);
String s2 = s1 How Many Objects are created? ONE if (s1 == s2) S.O.P(“Hello”); else S.O.P(Hi”); What will be output? Hello if (s1.equals(s2)) S.O.P(“Hello”); else S.O.P(Hi”); What will be output? Hello
20
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
21
String Comparison Examples
String s1 = "OOP"; String s2 = "OOP"; String s3 = "java"; if( s1 == s2) System.out.println("Hello"); else System.out.println("Hi"); System.out.println(s1.compareTo(s3)); System.out.println(s3.compareTo(s1)); How Many Objects are created here?. ONE Hello -27 27
22
Searching Strings
23
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 int indexOf(int ch) / int lastIndexOf(int ch) int indexOf(String str) / int lastIndexOf(String str) int indexOf(int ch, int startIndex) / int lastIndexOf(int ch, int startIndex) int indexOf(String str,startIndex) / int lastIndexOf(String str, int startIndex)
24
Example 7 66 33 49 49 33 System.out.println(s1.indexOf('t'));
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
25
Extracting a SubString From String
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);
26
all good men to come forward to aid their country
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)); System.out.println(s1.substring(20,40)); System.out.println("object oriented".substring(6)); System.out.println("object oriented".substring(5,10)); Index 20 to end all good men to come forward to aid their country Index 20 to 39 all good men to come Index 6 to end oriented Index 5 to 9 t ori
27
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); }
28
Character Replacement in a String
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>> String trim() Removes any leading and trailing whitespaces “ Hello World “.trim(); << returns Hello World>> 3. Useful for processing user commands
29
Changing Case of Characters Within a String
String toLowerCase() String toUpperCase() Examples : S.O.P(“object”.toUpperCase()); S.O.P(“OBJECT”.toLowerCase());
30
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> }
31
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); } Name of class HashCode of Object OUTPUT
32
public static void main(String args[]) A a1 = new A(10,8);
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
33
Home Exercise 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)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.