1 Strings and String Operations Overview l Creating String Objects l Substring methods l The Concatenation Operator l Strings are Immutable l Other Methods.

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.
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.
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.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
Programming 2 CS112- Lab 2 Java
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
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.
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.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
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.
From C++ to Java A whirlwind tour of Java for C++ programmers.
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.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Strings Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 2: Fundamental Data Types 1 Chapter 2 Fundamental Data Types.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
Introduction to Programming
Chapter 7: Characters, Strings, and the StringBuilder.
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)
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
Data Types and Statements MIT 12043: Fundamentals of Programming Lesson 02 S. Sabraz Nawaz Fundamentals of Programming by
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
CSC Programming I Lecture 9 September 11, 2002.
Strings and ArrayLists April 23, 2012 ASFA AP CS.
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.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
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.
Computer Programming 2 Lab (1) I.Fatimah Alzahrani.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
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,
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings Chapter.
2 Arrays Array is a data structure that represents a collection of the same type of data. A "fixed length list".
String and StringBuffer classes
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Strings.
String class.
Primitive Types Vs. Reference Types, Strings, Enumerations
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
Chapter 9 Strings and Text I/O
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. Every time.
16 Strings.
Lecture 07 String Jaeki Song.
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 .
Strings in Java Strings in Java are also a reference type.
Presentation transcript:

1 Strings and String Operations Overview l Creating String Objects l Substring methods l The Concatenation Operator l Strings are Immutable l Other Methods of the String Class l Example using String Methods l Formatting Floating-point Numbers

2 Creating String Objects Strings are Objects l String is a sequence of characters enclosed in quotes. E.g. “Hello” l String processing is one of the most important and most frequent applications of a computer l Java recognizes this fact and therefore provides special support for strings to make their use convenient Every string is an instance of Java’s built in String class, thus, Strings are objects. Declaration Like any object, a string can be created using new as in the following example: String str1 = new String(“Hello dear”); l However, as an extra support, Java allows String object to be created without the use of new, as in: String str2=”How are you”; l This is inconsistent with the way Java treats other classes.

3 Substrings l String objects are represented as a sequence of characters indexed from 0. Example: String greeting = “Hello, World”; l A common operation on Strings is extracting a substring from a a given string. l Java provides two methods for this operation: Examples: String sub = greeting.substring(0, 4);  “Hell” String w = greeting.substring(7, 12);  “World” String tail = greeting.substring(7);  “World!” Hello,World! substring(start); Returns the substring from start to the end of the string substring(start, end); Returns a substring from start to end but not including the character at end.

4 Concatenation Operator l Another common operation on String is concatenation. l As another special support for String, Java overloaded the + operator to be used to concatenate two String objects to get a bigger one. String firstName = “Amr”; String lastName = “Al-Ibrahim”; String fullName = lastName+ ” “ +firstName;  “Al-Ibrahim Amr” l If one of the operands of the + operator is a string, the other is automatically converted to string and the two strings are then concatenated. String course = “ICS”; int code = 102; String courseCode = course+code  “ICS102” l We frequently use the concatenation operator in println statements. System.out.println(“The area =“+area); l You need to be careful with concatenation operator. For example, what do you this the following print? System.out.println(“Sum =“+5+6);

5 Strings are Immutable l Another special feature of Strings is that they are immutable. That is, once a string object is created, its content cannot be changed. For example, consider the following: String str1 = “Hello World”; str1 = str1.substring(4); l Instead of changing the str1 object, another object is created. The former is garbage collected, thus, the reference to the former is lost. l The fact that Strings are immutable allows the Java system to process Strings very efficiently. l For example, consider the following: String str1 = “Hello”; String str2 = “Hello”; l We would expect the following l But in fact, this is what happens l The Java system is smart enough to know that the two strings are identical and allocates same memory location for the two objects

6 Methods of the String Class l In addition to the substring methods, several predefined methods are provided in the built-in String class. Some of these are: int length() returns the number of characters in this String String toUpperCase() String toLowerCase() returns a new String, equivalent to the Upper/lower case of this String boolean equals(s) boolean equalsIgnoreCase(s) returns true if s the same as this String. int compareTo(String s) int compareToIngoreCase(s) returns +ve number, 0, or -ve number if this String is greater than, equal to or less than s. char charAt(index) returns the char in this String, at the index position. int indexOf(ch) int lastIndexOf(ch) Returns the index of the first / last occurrence of ch in this string, If not fount-1 is returned String trim() returns a String, obtained by removing spaces from the start and end of this string. static String valueOf (any primitive type) Returns a String representation of the argument String concat(s) equivalent to + symbol

7 Example using methods of String class l The following program generates a password for a student using his initials and age. public class MakePassword { public static void main(String[] args) { String firstName = "Amr"; String middleName = "Samir"; String lastName = "Ibrahim"; //extract initials String initials = firstName.substring(0,1)+ middleName.substring(0,1)+ lastName.substring(0,1); //append age int age = 20; String password = initials.toLowerCase()+age; System.out.println("Your Password ="+password); }

8 Formatting floating-point numbers l Some times we would like to print floating point numbers only up to certain number of decimal places. l For example we would want print the cost of an item in the form: SR16.50 l To achieve this, we use the getNumberInstance method of the the numberFormat class of the java.text package, to create an object. l We then use the setMaximumFractionDigits and setMinimumFractionDigits methods to set the decimal places required. l Finally, we use the format method to format our number. l The format method returns a string, so we can print it. l The example in the next slide demonstrate this process.

9 Formatting floating-point numbers import java.text.NumberFormat; public class NumberFormatting { public static void main(String[] args) { NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMaximumFractionDigits(2); formatter.setMinimumFractionDigits(2); double annualSalary = 72500; double monthlySalary = annualSalary/12; System.out.println("Unformatted Salary: SR"+monthlySalary); System.out.println("Formatted Salary: SR"+formatter.format(monthlySalary)); }

10 Formatting floating-point numbers l We can also use the DecimalFormat class of the same package to format floating-point numbers. l In this approach, we create an object of the DecimalFormat class, specifying the format we want as a parameter. l The difference between this approach and the previous is that the comma is not used by default. import java.text.DecimalFormat; public class DecimalFormatting { public static void main(String[] args) { DecimalFormat formatter = new DecimalFormat("0.00"); double celsius = 37; double fahrenheit = 9.0/5.0*celsius+32; System.out.println("Unformatted: "+celsius+"oC = "+fahrenheit+"oF"); System.out.println("Formatted: "+celsius+"oC = "+formatter.format(fahrenheit)+"oF"); }