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:

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Advertisements

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 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
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.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Programming 2 CS112- Lab 2 Java
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
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,
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
Strings Reading for this Lecture, L&L, 3.2. Strings String is basically just a collection of characters. Thus, the string “Martyn” could be thought of.
String StringBuffer. class StringExample { public static void main (String[] args) { String str1 = "Seize the day"; String str2 = new String(); String.
Lab session 3 and 4 Topics to be covered Escape sequences Escape sequences Variables /identifiers Variables /identifiers Constants Constants assignment.
28-Jun-15 String and StringBuilder Part I: String.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
1 Strings and String Operations  What is a Strings?  Internal Representation of Strings  Getting Substrings from a String  Concatenating Strings 
String Class in Java java.lang Class String java.lang.Object java.lang.String java.lang.Object We do not have to import the String class since it comes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
String Class. Objectives and Goals Identify 2 types of Strings: Literal & Symbolic. Learn about String constructors and commonly used methods Learn several.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
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.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called.
CSI 3125, Preliminaries, page 1 String. CSI 3125, Preliminaries, page 2 String Class Java provides the String class to create and manipulate strings.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
String class. Method concat Create string object –> String st1, st2; Input character to string object –> st1=br.readLine(); st2= br.readLine(); Use method.
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.
Chapter 8 String Manipulation
Introduction to programming in java
String and StringBuffer classes
C# - Strings.
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
String class in java Visit for more Learning Resources string.
Advanced Programming Behnam Hatami Fall 2017.
Modern Programming Tools And Techniques-I Lecture 11: String Handling
String and StringBuilder
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.
String and StringBuilder
CS2011 Introduction to Programming I Strings
String methods 26-Apr-19.
Strings in Java.
JAVA – String Function PROF. S. LAKSHMANAN,
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

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: char[] ch={‘B','a',’n',’g',’l',‘a',’d',’e',’s',’h'}; String s=new String(ch); is same as: String s=“Bangladesh"; 2

Create String object Two ways to create String object: By string literal By new keyword 3

String Literal Java String literal is created by using double quotes. For Example: String s="welcome"; 4

String Literal 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. For example: String s1="Welcome"; String s2="Welcome";//will not create new instance 5

String Literal 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). 6

By new keyword String s=new String("Welcome");//creates two objects and one reference variable In such case, 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). 7

Example public class StringExample{ public static void main(String args[]){ String s1="java";//creating string by java string literal char ch[]={'s','t','r','i','n','g','s'}; String s2=new String(ch);//converting char array to string String s3=new String("example");//creating string by new keyword System.out.println(s1); System.out.println(s2); System.out.println(s3); } OUTPUT: Java strings example 8

Immutable String 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=“Dhaka"; s.concat("Bangladesh");//concat() method appends the string at the end System.out.println(s);//will print Dhaka because strings are immutable objects } Output: Dhaka 9

Immutable String 10

Immutable String class Testimmutablestring1{ public static void main(String args[]){ String s=" Dhaka"; s=s.concat(" Bangladesh"); System.out.println(s); } Output: Dhaka Bangladesh 11

Advantages Of Immutability Uses less memory. String word1 = "Java"; String word2 = word1; String word1 = “Java"; String word2 = new String(word1); word1 OK Less efficient: wastes memory “Java" word2 word1 word2

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) There are three ways to compare string : By equals() method By = = operator By compareTo() method 13

String compare by equals() method The String equals() method compares the original content of the string. 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. 14

String compare by equals() method class Teststringcomparison1{ public static void main(String args[]){ String s1=“Dibya"; String s2=“Dibya"; String s3=new String(“Dibya"); String s4=“Sneha"; System.out.println(s1.equals(s2));//true System.out.println(s1.equals(s3));//true System.out.println(s1.equals(s4));//false } 15

String compare by equals() method class Teststringcomparison2{ public static void main(String args[]){ String s1=“Dibya"; String s2=“DIBYA"; System.out.println(s1.equals(s2));//false System.out.println(s1.equalsIgnoreCase(s3));//true } 16

String compare by == operator The = = operator compares references not values. class Teststringcomparison3{ public static void main(String args[]){ String s1=“Dibya"; String s2=“Dibya"; String s3=new String(“Dibya"); 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 ) } 17

String compare by compareTo() method The String compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string. Suppose s1 and s2 are two string variables. If: s1 == s2 :0 s1 > s2 :positive value s1 < s2 :negative value 18

String compare by compareTo() method 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 ) } 19

charAt() charAt() method returns a char value at the given index number. The index number starts from 0 public class CharAtExample{ public static void main(String args[]){ String name=“TechnoBangla"; char ch=name.charAt(4);//returns the char value at the 4th index System.out.println(ch); } 20

Length() length() method length of the string. It returns count of total number of characters. public class LengthExample{ public static void main(String args[]){ String s1=“TechnoBangla"; String s2=“Java"; System.out.println("string length is: "+s1.length());//12 is the length of TechnoBangla string System.out.println("string length is: "+s2.length());//4 is the length of Java string } 21

Substring() public String substring(int startIndex) public String substring(int startIndex, int endIndex) public class SubstringExample{ public static void main(String args[]){ String s1="TechnoBangla"; System.out.println(s1.substring(2,4));//returns chn System.out.println(s1.substring(2));//returns chnoBangla } 22

contains() contains() method searches the sequence of characters in this string. It returns true if sequence of char values are found in this string otherwise returns false public boolean contains(CharSequence sequence) true if sequence of char value exists, otherwise false. class ContainsExample{ public static void main(String args[]){ String name="what do you know about me"; System.out.println(name.contains("do you know")); System.out.println(name.contains("about")); System.out.println(name.contains("hello")); }} OUTPUT: true false 23

format() string format() method returns the formatted string public static String format(String format, Object... args) public class FormatExample{ public static void main(String args[]){ String name="sonoo"; String sf1=String.format("name is %s",name); String sf2=String.format("value is %f", ); String sf3=String.format("value is %.12f", );//returns 12 char fractional part filling with 0 System.out.println(sf1); System.out.println(sf2); System.out.println(sf3); }} 24

join() join() method returns a string joined with given delimiter. In string join method, delimiter is copied for each elements. In case of null element, "null" is added. The join() method is included in java string since JDK 1.8. public static String join(CharSequence delimiter, CharSequence... elements) public class StringJoinExample{ public static void main(String args[]){ String joinString1=String.join("-","welcome","to",“TechnoBangla"); System.out.println(joinString1); } Output: welcome-to-TechnoBangla 25

Concat() concat() method combines specified string at the end of this string. It returns combined string. It is like appending another string. public String concat(String anotherString) public class ConcatExample{ public static void main(String args[]){ String s1="java string"; s1.concat("is immutable"); System.out.println(s1); s1=s1.concat(" is immutable so assign it explicitly"); System.out.println(s1); } Output: java string java string is immutable so assign it explicitly 26

replace() replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence public String replace(char oldChar, char newChar) and public String replace(CharSequence target, CharSequence replacement) public class ReplaceExample1{ public static void main(String args[]){ String s1=" According to Sun, 3 billion devices run java "; String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e' System.out.println(replaceString); }} 27

trim() trim() method eliminates leading and trailing spaces. The unicode value of space character is '\u0020'. The trim() method in java string checks this unicode value before and after the string, if it exists then removes the spaces and returns the omitted string. public class StringTrimExample{ public static void main(String args[]){ String s1=" hello string "; System.out.println(s1+“TechnoBangla");//without trim() System.out.println(s1.trim()+" TechnoBangla ");//with trim() }} Output: hello string TechnoBangla 28

split() split() method splits this string against given regular expression and returns a char array public String split(String regex) and public String split(String regex, int limit) regex : regular expression to be applied on string. limit : limit for the number of strings in array. If it is zero, it will returns all the strings matching regex. 29

split() public class SplitExample{ public static void main(String args[]){ String s1="java string split method by JDK"; String[] words=s1.split(“ ");//splits the string based on string for(String w:words){ System.out.println(w); } }} public class SplitExample2{ public static void main(String args[]){ String s1="welcome to split world"; System.out.println("returning words:"); for(String w:s1.split("\\s",0)){ System.out.println(w); } System.out.println("returning words:"); for(String w:s1.split("\\s",1)){ System.out.println(w); } System.out.println("returning words:"); for(String w:s1.split("\\s",2)){ System.out.println(w); } }} 30

intern() intern() method returns the interned string. It can be used to return string from pool memory, if it is created by new keyword. public class InternExample{ public static void main(String args[]){ String s1=new String("hello"); String s2="hello"; String s3=s1.intern();//returns string from pool, now it will be same as s2 System.out.println(s1==s2);//false because reference is different System.out.println(s2==s3);//true because reference is same }} 31

indexOf() indexOf() method returns index of given character value or substring. If it is not found, it returns -1. No.MethodDescription 1int indexOf(int ch)returns index position for the given char value 2int indexOf(int ch, int fromIndex) returns index position for the given char value and from index 3int indexOf(String substring)returns index position for the given substring 4int indexOf(String substring, int fromIndex)returns index position for the given substring and from index 32

indexOf() public class IndexOfExample{ public static void main(String args[]){ String s1="this is index of example"; //passing substring int index1=s1.indexOf("is");//returns the index of is substring int index2=s1.indexOf("index");//returns the index of index substring System.out.println(index1+" "+index2);//2 8 //passing substring with from index int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index System.out.println(index3);//5 i.e. the index of another is //passing char value int index4=s1.indexOf('s');//returns the index of s char value System.out.println(index4);//3 }} Output:

toLowerCase(), toUpperCase() toLowerCase() method converts all characters of the string into lower case letter toUpperCase() method converts all characters of the string into upper case letter public class StringLowerExample{ public static void main(String args[]){ String s1=“TechnoBangla HELLO stRIng"; String s1lower=s1.toLowerCase(); System.out.println(s1lower); }} public class StringUpperExample{ public static void main(String args[]){ String s1=“TechnoBangla hello string"; String s1upper=s1.toUpperCase(); System.out.println(s1upper); }} 34

valueOf() valueOf() method converts different types of values into string By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string. public static String valueOf(boolean b) public static String valueOf(char c) public static String valueOf(char[] c) public static String valueOf(int i) public static String valueOf(long l) public static String valueOf(float f) public static String valueOf(double d) public static String valueOf(Object o) String str1 = String.valueOf(10); // right way to convert from an integer to String int i = Integer.parseInt("10"); // right way to convert from a String to an int 35

valueOf() public class StringValueOfExample{ public static void main(String args[]){ int value=30; String s1=String.valueOf(value); System.out.println(s1+10);//concatenating string with 10 } OUTPUT:

startsWith() startsWith() method checks if this string starts with given prefix It returns true if this string starts with given prefix else returns false. public boolean startsWith(String prefix) Or public boolean startsWith(String prefix, int toffset) prefix -- the prefix to be matched. toffset -- where to begin looking in the string. 37

startsWith() import java.io.*; public class Test{ public static void main(String args[]){ String Str = new String("Welcome to our Tutorials"); System.out.print("Return Value :" ); System.out.println(Str.startsWith("Welcome") ); System.out.print("Return Value :" ); System.out.println(Str.startsWith("Tutorials") ); System.out.print("Return Value :" ); System.out.println(Str.startsWith("Tutorials", 15) ); } Output: Return Value :true Return Value :false Return Value :true 38

endsWith() endsWith() method checks if this string ends with given suffix public boolean endsWith(String suffix) public class EndsWithExample{ public static void main(String args[]){ String s1="java by TechnoBangla"; System.out.println(s1.endsWith(“a")); //true System.out.println(s1.endsWith("Bangla")); //true }} 39

Java Programs 40