String and StringBuffer classes

Slides:



Advertisements
Similar presentations
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Advertisements

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Strings in Java 1. strings in java are handled by two classes String &
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Strings.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Programming 2 CS112- Lab 2 Java
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
23-Jun-15 Strings, Etc. Part I: String s. 2 About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects,
Fundamental Programming Structures in Java: Strings.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
28-Jun-15 String and StringBuilder Part I: String.
1 Strings and String Operations  What is a Strings?  Internal Representation of Strings  Getting Substrings from a String  Concatenating Strings 
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 8 Strings 1.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Working with string In java Four classes are provided to work with String:1) String 2)String Buffer 3)String Tokenizer 4)String Builder Note: An object.
Chapter 7: Characters, Strings, and the StringBuilder.
String Handling StringBuffer class character class StringTokenizer class.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
1 The String Class F Constructing a String: F Obtaining String length and Retrieving Individual Characters in a string F String Concatenation (concat)
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
Strings And other things. Strings Overview The String Class and its methods The char data type and Character class StringBuilder, StringTokenizer classes.
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
17-Feb-16 String and StringBuilder Part I: String.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
Strings A string is a sequence of characters that is treated as a single value. Strings are objects. We have been using strings all along. For example,
2 Arrays Array is a data structure that represents a collection of the same type of data. A "fixed length list".
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
The String class is defined in the java.lang package
Introduction to programming in java
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Strings.
EKT 472: Object Oriented Programming
University of Central Florida COP 3330 Object Oriented Programming
Programming in Java Text Books :
String and String Buffers
String Handling in JAVA
Primitive Types Vs. Reference Types, Strings, Enumerations
String class in java Visit for more Learning Resources string.
Modern Programming Tools And Techniques-I Lecture 11: String Handling
String and StringBuilder
F4105 JAVA PROGRAMMING F4105 Java Programming
Chapter 7: Strings and Characters
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
String and StringBuilder
Chapter 9 Strings and Text I/O
String and StringBuilder
Java – String Handling.
Lecture 07 String Jaeki Song.
String and StringBuilder
String methods 26-Apr-19.
Strings in Java.
Chapter 10 Thinking in Objects Part 2
Object Oriented Programming
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

String and StringBuffer classes

Java String Java String provides a lot of concepts that can be performed on a string such as compare, concat, equals, split, length, replace, compareTo, intern, substring etc. In java, string is basically an object that represents sequence of char values. An array of characters works same as java string. char[] ch={'j','a','v','a','t','p','o','i','n','t'};   String s=new String(ch); or String s="javatpoint"; 

Java String Cont. The java String is immutable i.e. it cannot be changed but a new instance is created. For mutable class, you can use StringBuffer and StringBuilder class. There are two ways to create String object: By string literal By new keyword

By string literal String s1="Welcome"; String s2="Welcome"; //will not create new instance   Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool.

Note: String objects are stored in a special memory area known as string constant pool. Why java uses concept of string literal? To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

By new keyword String s=new String("Welcome"); //creates two objects and one reference variable   JVM will create a new string object in normal (non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).

Example public class StringExample { public static void main(String args[]) String s1="java"; char ch[]={'s','t','r','i','n','g','s'}; String s2=new String(ch); String s3=new String("example"); System.out.println(s1); System.out.println(s2); System.out.println(s3); }

Immutable String in Java In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once string object is created its data or state can't be changed but a new string object is created.

class Testimmutablestring { public static void main(String args[]) String s="Sachin"; s.concat(" Tendulkar"); //concat() method appends the string at the end System.out.println(s); //will print Sachin because strings are immutable objects }

Because java uses the concept of string literal. class Testimmutablestring1 { public static void main(String args[]) String s="Sachin"; s=s.concat(" Tendulkar"); System.out.println(s); } Why string objects are immutable in java? Because java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "sachin". If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

Java String class methods The java.lang.String class provides many useful methods to perform operations on sequence of char values. The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc. Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based or mobile application.

Java String toUpperCase() and toLowerCase() method The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter. public class Testmethodofstringclass { public static void main(String args[]) String s="Sachin"; System.out.println(s.toUpperCase()); //SACHIN System.out.println(s.toLowerCase()); //sachin System.out.println(s); //Sachin(no change in original) }

Java String trim() method The string trim() method eliminates white spaces before and after string. Java String startsWith() and endsWith() method boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes then it returns true else false. boolean endsWith(String suffix): Checks whether the string ends with the specified suffix. String s="  Sachin  ";   System.out.println(s);//  Sachin     System.out.println(s.trim());//Sachin  

Java String charAt() method public char charAt(int index)   This method returns a character at specified index. Java String length() method The string length() method returns length of the string. Java String valueOf() method The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string. OUTPUT: 1010  int a=10;   String s=String.valueOf(a);   System.out.println(s+10);  

Java String replace() method The string replace() method replaces all occurrence of first sequence of character with second sequence of character. String s1="Java is a programming language. Java is a platform. Java is an Island.";    String replaceString=s1.replace("Java","Kava");      System.out.println(replaceString)

Java String compare We can compare string in java on the basis of content and reference. It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc. There are three ways to compare string in java: By equals() method By = = operator By compareTo() method

1) String compare by equals() method The String equals() method compares the original content of the string. It compares values of string for equality. String class provides two methods: public boolean equals(Object another) compares this string to the specified object. public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring case.

Example class Teststringcomparison1 { public static void main(String args[]) String s1="Sachin"; String s2="Sachin"; String s3=new String("Sachin"); String s4="Saurav"; System.out.println(s1.equals(s2)); System.out.println(s1.equals(s3)); System.out.println(s1.equals(s4)); }

2) String compare by == operator The = = operator compares references not values. class Teststringcomp2{ public static void main(String args[]) { String s1="Sachin"; String s2="Sachin"; String s3=new String("Sachin"); System.out.println(s1==s2); //true (because both refer to same instance) System.out.println(s1==s3); //false(because s3 refers to instance created in nonpool) }

3) String compare by compareTo() method int compareTo(String string): This method compares the two strings based on the Unicode value of each character in the strings. Suppose s1 and s2 are two string variables. If: s1 == s2 :0 s1 > s2   :positive value s1 < s2   :negative value

Example class Teststringcomparison4 { public static void main(String args[]) String s1="Sachin"; String s2="Sachin"; String s3="Ratan"; System.out.println(s1.compareTo(s2)); //0 System.out.println(s1.compareTo(s3)); //1(because s1>s3) System.out.println(s3.compareTo(s1)); //-1(because s3 < s1 ) }

String Concatenation in Java In java, string concatenation forms a new string that is the combination of multiple strings. There are two ways to concat string in java: By + (string concatenation) operator By concat() method

1) String Concatenation by + (string concatenation) operator Java string concatenation operator (+) is used to add strings. The Java compiler transforms above code to this: String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();   class TestStringConcatenation1 { public static void main(String args[]) String s="Sachin"+" Tendulkar"; System.out.println(s); }

String concatenation In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its append method. String concatenation operator produces a new string by appending the second operand onto the end of the first operand. The string concatenation operator can concat not only string but primitive values also.

EXAMPLE class TestStringConcatenation2 { public static void main(String args[]) String s=50+30+"Sachin"+40+40; System.out.println(s); } OUTPUT 80Sachin4040 Note: After a string literal, all the + will be treated as string concatenation operator.

2) String Concatenation by concat() method The String concat() method concatenates the specified string to the end of current string. Syntax: public String concat(String another)   class TestStringConcatenation3 { public static void main(String args[]) String s1="Sachin "; String s2="Tendulkar"; String s3=s1.concat(s2); System.out.println(s3); }

Substring in Java A part of string is called substring. Or substring is a subset of another string. In case of substring startIndex is inclusive and endIndex is exclusive. Index starts from 0. You can get substring from the given string object by one of the two methods: public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive). public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex. In case of string: startIndex: inclusive endIndex: exclusive String s="hello";   System.out.println(s.substring(0,2)); 0 points to h but 2 points to e

Java StringBuffer class Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

public synchronized StringBuffer append(String s): is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc. public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex.

public synchronized StringBuffer reverse(): is used to reverse the string. public int capacity(): is used to return the current capacity. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum. public char charAt(int index): is used to return the character at the specified position. public int length(): is used to return the length of the string i.e. total number of characters. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the string from specified startIndex and endIndex.

public String substring(int beginIndex): is used to return the substring from the specified beginIndex. public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex.

1) StringBuffer append() method The append() method concatenates the given argument with this string. SYNTAX: StringBuffer append(String s); class A {   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 A {   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 A {   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 A {   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. class A {   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 A { public static void main(String args[]) StringBuffer sb=new StringBuffer("HELLO "); sb.append("JAVA"); System.out.println(sb); sb.insert(6,"program"); sb.replace(0,2,"he"); sb.delete(1,6); sb.reverse(); System.out.println(sb.capacity()); sb.append("java is my favourite language"); System.out.println(sb.length()); }

class A {   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   }  

7) StringBuffer ensureCapacity() method The ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the 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 A {   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   sb.ensureCapacity(10); //now no change   System.out.println(sb.capacity()); //now 34   sb.ensureCapacity(50); //now (34*2)+2   System.out.println(sb.capacity()); //now 70   }