Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.

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.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Java Programming Strings Chapter 7.
Kernighan/Ritchie: Kelley/Pohl:
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Constants and Data Types Constants Data Types Reading for this class: L&L,
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.
Introduction to Computers and Programming Lecture 7:
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
Java Syntax Primitive data types Operators Control statements.
Working with the data type: char  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Fundamental Programming Structures in Java: Strings.
Lab session 3 and 4 Topics to be covered Escape sequences Escape sequences Variables /identifiers Variables /identifiers Constants Constants assignment.
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 8 Characters and Strings.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
Characters and Strings. Characters In Java, a char is a primitive type that can hold one single character A character can be: –A letter or digit –A punctuation.
1 Lab Session-III CSIT-120 Spring 2001 Revising Previous session Data input and output While loop Exercise Limits and Bounds GOTO SLIDE 13 Lab session.
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.3 The Class String.
1 Strings and String Operations  What is a Strings?  Internal Representation of Strings  Getting Substrings from a String  Concatenating Strings 
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
String Escape Sequences
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
CSCI 1100/1202 January 16, Why do we need variables? To store intermediate results in a long computation. To store a value that is used more than.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Characters In Java, single characters are represented.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
Vladimir Misic: Java1 Basic Java Syntax The java language will be described by working through its features: –Variable types and expressions.
Introduction to Java Java Translation Program Structure
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.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs -
Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; Copyright © 2012 Pearson Education,
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
Copyright Curt Hill Variables What are they? Why do we need them?
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.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
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.
Computer Programming 2 Lab (1) I.Fatimah Alzahrani.
CS 31 Discussion, Week 7 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
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.
17-Mar-16 Characters and Strings. 2 Characters In Java, a char is a primitive type that can hold one single character A character can be: A letter or.
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.
The Methods and What You Need to Know for the AP Exam
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Java Variables and Types
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
String class.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Multiple variables can be created in one declaration
Basic Java Syntax The Java language will be described by working through its features: variable types and expressions selection and iteration classes exceptions.
Primitive Types Vs. Reference Types, Strings, Enumerations
Advanced Programming Behnam Hatami Fall 2017.
Advanced Programming in Java
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
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.
Can store many of the same kind of data together
Java Programming Language
Presentation transcript:

Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings

Vladimir Misic: Characters and Strings2Tuesday, 9:39 AM Characters The data type char represents a single character in Java. –Character values are written as a symbol: ' a ', ' ) ', ' % ', ' A ', etc. –A char value in Java is really represented as an integer. Each character has an associated 16-bit integer value*. 0* …………. + 0* * * * * * * *2 0 … bits *Digression:

Vladimir Misic: Characters and Strings3Tuesday, 9:39 AM Characters –So: a char value in Java is really represented as an integer. Thus: –The integer value associated with the character is based upon a code. The ASCII code represents 256 characters including all upper and lower case English letters, the numbers between 0 and 9, punctuation, and some unprintable characters. ASCII is a subset of the UNICODE character set. The UNICODE character set contains 34,168 distinct characters. –The major languages from the Americas, Europe, Middle East, Africa, India, Asia, and Pacifica are represented. –Unicode (16 bits) support for every character in the world: ‘\u0000’ to ‘\uFFFF’

Vladimir Misic: Characters and Strings4Tuesday, 9:39 AM Characters The printable ASCII characters include tabs, new lines, carriage return, single and double quote. –New line = ' \n ' –Tab = ' \t ' –Carriage return = ' \r ' –Single quote = ' \ '' –Double quote = ' \ "‘ System.out.println(“Line one \nLine two”);

Vladimir Misic: Characters and Strings5Tuesday, 9:39 AM Non-printable Characters There are also characters contained in ASCII that are not printable. –Bell tone = bel(ASCII 7) –Characters 0 to 32 are non-printable characters. –Character 127 (delete) is also non-printable character

Vladimir Misic: Characters and Strings6Tuesday, 9:39 AM Characters To define a character use the char data type. char firstChar = 'a', secondChar = 'A'; Notice that two integers are declared and initialized on the same lane. To convert an integer into a character you can type cast the integer. char thirdCharacter = (char) 120; char thirdCharacter = ‘x’;

Vladimir Misic: Characters and Strings7Tuesday, 9:39 AM Characters You can print a char as an integer using type casting. System.out.println( (int) 'C'); Output: 67 Comparing characters is done based upon their integer representation. True or false? ' c ' < ' C ' True or false? ' 1 ' < ' 4 '

Vladimir Misic: Characters and Strings8Tuesday, 9:39 AM Characters import java.io.* ; public class CharString { public static void main( String args[] ) { System.out.println('A'); System.out.println('\u0041'); System.out.println((char)65); } import java.io.* ; public class CharString { public static void main( String args[] ) { System.out.println('A'); System.out.println('\u0041'); System.out.println((char)65); } AAAAAA A A A Output:

Vladimir Misic: Characters and Strings9Tuesday, 9:39 AM Characters import java.io.* ; public class CharString { public static void main( String args[] ) { int a = 98; System.out.println(a); System.out.println((char)a); System.out.println('a'); } import java.io.* ; public class CharString { public static void main( String args[] ) { int a = 98; System.out.println(a); System.out.println((char)a); System.out.println('a'); } 98 b a 98 b a Output:

Vladimir Misic: Characters and Strings10Tuesday, 9:39 AM Strings A string is composed of individual characters that are treated as a single unit. –The individual characters ' h ', ' e ', ' l ', ' l ', and ' o ' are combined into the string " hello ". A string may contain letters, digits, and special characters such as +, -, etc. String Examples: –" My name is Matilda. " –" = 3 “

Vladimir Misic: Characters and Strings11Tuesday, 9:39 AM Strings The data type of a string is String. –The capital S of String indicates that this data type is not a primitive data type. –In fact, String is a complex data type. When an individual string is created, it is an object of type String. Here comes string content. stringName

Vladimir Misic: Characters and Strings12Tuesday, 9:39 AM String Constructors Java provides various string constructors. Assume String s1; (What’s the value of s1 so far?) –s1 = new String( ); This creates a string of length zero with no characters. –s1 = new String( s ); This creates a string that is a copy of the characters stored in String s that is passed to the constructor. –s1 = "This is a string"; This is a special shortcut constructor, ONLY available to Strings.

Vladimir Misic: Characters and Strings13Tuesday, 9:39 AM Strings Each character of a String has an associated index. –The first letter of a string has an index of zero (0), the second letter has an index of one (1), … the last letter has an index of (string length – 1). –What is the string length of " hello " ? –What is the index of the second ' l ' in the word " hello " ?

Vladimir Misic: Characters and Strings14Tuesday, 9:39 AM String Methods The length of a string can be found by: –stringName.length(); The first element of a string is always zero. A character at a specific position can be found by: –stringName.charAt( 3 ); Where 3 is an index into the string Sumatra stringName.charAt(3)stringName The variable refers to the whole string The method returns the character at position #3

Vladimir Misic: Characters and Strings15Tuesday, 9:39 AM Strings Strings are immutable !!! Once you create a string and initialize it you can not change the string. –You can assign a new string to the string variable. The original string is lost (will be handled by the java garbage collection process. –You can not add new characters or remove existing characters.

Vladimir Misic: Characters and Strings16Tuesday, 9:39 AM Changing Case To change the case of characters in a string: –stringName.replace( ' l ', ' L ' ); This returns a String with all characters ' l ' in the String replaced by ' L '. If there are no ' l ' s in the String, the original string is returned. –stringName.toUpperCase( ); This will return a String with all lower case letters to capital letters. –stringName.toLowerCase( ); This will return a String with all capital letters to lower case letters.

Vladimir Misic: Characters and Strings17Tuesday, 9:39 AM String Comparison Are two strings equal to one another? –stringName1.equals( stringName2 ); The result is true if the two strings are the same and false if the two strings are different. Capital and Lower case letters are considered to be different. –stringName1 == stringName2; The result is only true if stringName1 and stringName2 both refer to the same object in memory.

Vladimir Misic: Characters and Strings18Tuesday, 9:39 AM String Comparison You can ignore the case of letters during comparison using: –stringName1.equalsIgnoreCase( StringName2 ); That means that " hello " is equal to " HELLO " You can also compare strings using –stringName1.compareTo( StringName2 ); This comparison returns 0 if the strings are equal, a negative number if stringName less than stringName2, and a positive number if stringName greater than stringName2.

Vladimir Misic: Characters and Strings19Tuesday, 9:39 AM String Comparison To compare portions of two strings: –stringName1.regionMatches( 0, StringName2, 0, 5 ); The first parameter 0 is the starting index in stringName1, the third parameter is the starting index in stringName2, and the last argument is the number of characters to compare. This method returns true only if the members compared are equal. –" ello " == " ello " but " ello " != " Ello “ –stringNam1e.regionMatches( true, 0, StringName2, 0, 5 ); Here, the true says we want to ignore case

Vladimir Misic: Characters and Strings20Tuesday, 9:39 AM Locating Characters and Substrings indexOf can be used to find characters in strings. –stringName.indexOf( (int) ' a ' ); This returns the index of the first ‘a’ in the string if it is found. If it is not found the result is -1. –stringName.indexOf( (int) ' a ', 2 ); This is similar to the first except the second parameter specifies which index of the string the search should begin. –stringName.indexOf( " a " ); This is the same as the first except the parameter is a String rather than an int.

Vladimir Misic: Characters and Strings21Tuesday, 9:39 AM Characters import java.io.* ; public class CharString { public static void main( String args[] ) { String s = "Vladimir"; System.out.println( s.indexOf((int) 'i') ); System.out.println( s.indexOf((int) 'i',5) ); System.out.println( s.indexOf("i") ); System.out.println( s.indexOf('i') ); } } import java.io.* ; public class CharString { public static void main( String args[] ) { String s = "Vladimir"; System.out.println( s.indexOf((int) 'i') ); System.out.println( s.indexOf((int) 'i',5) ); System.out.println( s.indexOf("i") ); System.out.println( s.indexOf('i') ); } } Output:

Vladimir Misic: Characters and Strings22Tuesday, 9:39 AM Extracting Substrings Methods to get substrings out of strings are: –stringName.substring( 10 ); This returns the string that begins at index 10 and ends at the end of the original string. –stringName.substring( 10, 15 ); This returns the string that begins at index 10 and ends at one index before 15.

Vladimir Misic: Characters and Strings23Tuesday, 9:39 AM Concatenating Strings We have already used string concatenation with: – " this is a string " + stringName To concatenate two string variables: –stringName3 = stringName1.concat( stringName2 ); This returns the second string added to the end of the first string.

Vladimir Misic: Characters and Strings24Tuesday, 9:39 AM Name.java public class Name { public static void main( String args[] ) { String name; int midLoc; name = "Nan"; name = name.concat( " Schaller" ); midLoc = name.indexOf( " " ); name = name.substring( 0, midLoc ) + " Carol" + name.substring( midLoc ); System.out.println( name ); // Print out first name, a character per line for (int i=0; i<name.length() && name.charAt(i) != ' '; i++ ) { System.out.println( name.charAt(i) ); } There is a simpler way to write this: for(int i=0; i<midLoc; i++) { System.out.println(name.charAt(i)); } There is a simpler way to write this: for(int i=0; i<midLoc; i++) { System.out.println(name.charAt(i)); }

Vladimir Misic: Characters and Strings25Tuesday, 9:39 AM Other String Methods Using the Javadoc documentation you can learn about the many other String methods. –Methods for comparing regions of strings. –Converting variables of other data types to strings.

Vladimir Misic: Characters and Strings26Tuesday, 9:39 AM Primitive vs. Complex Data Types When you define a primitive data type (int, char, double, bool) the memory location is allocated. –The number of bytes is always the same to store a value. –char let = ' A ' ; let A

Vladimir Misic: Characters and Strings27Tuesday, 9:39 AM Primitive vs. Complex Data Types A complex data type is a data type defined by a class. –String is an example of a complex data type. –Complex data types usually begin with a capital letter. –The amount of storage required for a complex data type varies depending upon how large the actual values are. –Complex data types are also called reference data types.

Vladimir Misic: Characters and Strings28Tuesday, 9:39 AM Primitive vs. Complex Data Types When we define a String a memory location is allocated to hold a reference to the actual location of the information. –The reference is the location of the first item in memory. –The information is stored sequentially beginning at the reference location.

Vladimir Misic: Characters and Strings29Tuesday, 9:39 AM Primitive vs. Complex Data Types String nameA, nameB; nameA = "Rochester"; nameB = nameA; String nameA, nameB; nameA = "Rochester"; nameB = nameA; nameA … R o c h e s t e r nameB nameA Rochester

Vladimir Misic: Characters and Strings30Tuesday, 9:39 AM Primitive vs. Complex Data Types If we define another string and assign it equal to name then they will both point to the same location in memory. string nameB = nameA; –Now nameA and nameB both point to memory location nameA Rochester nameB 2044

Vladimir Misic: Characters and Strings31Tuesday, 9:39 AM Passing Primitive Data to Methods If a program passes a variable that has a primitive data type to a method, the actual value is passed using call-by-value. –The advantage is that the original value can not be modified by the method. –The disadvantage is that a copy of the original value is made, this requires more memory. –In fact, Java always passes method arguments by value! Even if variables are reference types. I’ll try to explain this – hope you’ll get it!

Vladimir Misic: Characters and Strings32Tuesday, 9:39 AM Passing Objects to methods When we pass a String to a method we are passing it using call-by-reference mechanism. –This means that we do not pass the actual string, we are passing the contents of the memory location that holds the reference (address) to the actual string. A problem associated with call-by-reference is that the original object may be modified. All objects (both Java defined and user defined) are passed using call-by-reference.

Vladimir Misic: Characters and Strings33Tuesday, 9:39 AM Passing Objects to methods Some of the String methods require a String as a parameter to the method. –For example, stringName1.equals(stringName2); –The method definition requires a String object to be passed to the method equals. –Sometimes == results in different value than stringName1.equals(stringName2); –When? We want some example !!!

Vladimir Misic: Characters and Strings34Tuesday, 9:39 AM Passing Objects to methods Sometimes == results in different value than *.equals !!! word2 word1 : String Java word1 == word2 is true word1.equals(word2)is true word2 word1 : String Java word1 == word2 is false word1.equals(word2)is true String Java

Vladimir Misic: Characters and Strings35Tuesday, 9:39 AM Returning Things from Methods When a method returns an object, a memory reference is really returned. –Not the actual data. When a method returns a primitive data type, then the actual value is returned.

Vladimir Misic: Characters and Strings36Tuesday, 9:39 AM StringBuffer The String class provides string objects that cannot be changed (are immutable). The StringBuffer class provides mutable objects.

Vladimir Misic: Characters and Strings37Tuesday, 9:39 AM Palindrome // This program checks a given string to see if it is a palindrome public class Palin { public static void main( String args[] ) { String original = "mom", reverse = ""; // Reverse it for (int i=0; i<original.length(); i++) { reverse = original.charAt( i ) + reverse; } // Now check it ( note that orig == reverse does not work ) if (original.equalsIgnoreCase(reverse)) { System.out.println( "Palindrome" ); } else { System.out.println( "Not a palindrome !!!" ); }