Presentation is loading. Please wait.

Presentation is loading. Please wait.

1. strings in java are handled by two classes String & StringBuffer 2. String --  Immutable class, StringBuffer -  Mutable class 3. Constructors : Strings.

Similar presentations


Presentation on theme: "1. strings in java are handled by two classes String & StringBuffer 2. String --  Immutable class, StringBuffer -  Mutable class 3. Constructors : Strings."— Presentation transcript:

1 1. strings in java are handled by two classes String & StringBuffer 2. String --  Immutable class, StringBuffer -  Mutable class 3. Constructors : Strings in Java 1.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) >

2 String Examples 1.String s1 = “Object” OR String s1 = new String(“Object”); 2.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); >

3 String Examples cont.. 6.String s1 =“OOP”; String s2 =“OOP”; String s3 =“OOP”; String: OOP s1 String s1 = new String(“OOP”); s2 s3

4 String Length int length() > Usage :.length(); Examples : S.O.P(“Object”.length()); s1.length(); name.length(); 6

5 String Concatenation Adding Strings together > ‘+’ 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 > 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 1. characters will be extracted from sourceStart 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

8 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;ijava StringExamples j e c t t o

9 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;ijava 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)

10 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;ijava 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)

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;ijava 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;ijava 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”); > (ii) “xyz”.equalsIgnoreCase(“XYZ”) (iii) s1.equals(s2) > (iv) s1.equalsIgnoreCase(s2) >

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 String with whom invoking string will be matched Start index within str2 String No of characters to be matched

15 Comparing Regions For matching 2. boolean regionMatches(boolean ignorecase, int startIndex, String str2,int str2StartIndex, int numChars) > 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); S1.regionMatches(14,s2,17,17); S1.regionMatches(14,s3,17,17); S1.regionMatches(true,14,s2,17,17); false true false 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”) > “Indians love cricket”.endsWith(“cricket”); > Second Form of startsWith allows to specify the starting point: boolean startsWith(String str, int startIndex); “Indians love cricket”.startsWith(“love”,8); > endsWith has only one form and is not available in boolean endsWith(String str, int startIndex);

18 equals Vs == String s1 = new String(“OOP”); String s2 = 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)); Hello How Many Objects are created here?. ONE

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 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)

24 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));

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

26 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)); all good men to come forward to aid their country all good men to come oriented t ori Index 20 to 39 Index 5 to 9 Index 20 to end Index 6 to end

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) 1.Replaces all occurences of one character with replacement character in the invoking string 2.“Hello”.replace(‘l’,’w’); > String trim() 1.Removes any leading and trailing whitespaces 2.“ Hello World “.trim(); > 3. Useful for processing user commands

29 Changing Case of Characters Within a String String toLowerCase() String toUpperCase() Examples : 1.S.O.P(“object”.toUpperCase()); 2.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 }

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); } OUTPUT Name of class HashCode of Object

32 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) 1.“RAM” and “MAR” are reflexive mirrors 2.“XYZ” and “ZYX” are reflexive mirrors 3.“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)


Download ppt "1. strings in java are handled by two classes String & StringBuffer 2. String --  Immutable class, StringBuffer -  Mutable class 3. Constructors : Strings."

Similar presentations


Ads by Google