03 Strings

Embed Size (px)

Citation preview

  • 7/23/2019 03 Strings

    1/101

    Strings and String Operations

    Overview

    Creating String Objects

    Substring methods

    The Concatenation Operator

    Strings are Immutable

    Other Methods of the String Class

    Example using String Methods

    Formatting Floatingpoint !umbers

  • 7/23/2019 03 Strings

    2/102

    Creating String Objects

    Strings are Objects String is a se"uence of characters enclosed in

    "uotes# E#g# $%ello&

    String processing is one of the most important andmost fre"uent applications of a computer

    'ava recogni(es this fact and therefore providesspecial support for strings to ma)e their useconvenient

    Ever* string is an instance of 'ava+s built in Stringclass, thus, Strings are objects#

    Declaration -i)e an* object, a string can be created using new

    as in the following example.

    String str1 = new String(Hello dear);

    %owever, as an extra support, 'ava allows Stringobject to be created without the use of new, as in.

    String str2=How are you;

    This is inconsistent with the wa* 'ava treats otherclasses#

  • 7/23/2019 03 Strings

    3/103

    Substrings

    String objects are represented as a se"uence of

    characters indexed from /#

    Example. String greeting = Hello, World;

    0 common operation on Strings is extracting a

    substring from a a given string#

    'ava provides two methods for this operation.

    Examples:

    String sub = greetingsubstring!", #$;$%ell&

    String % = greetingsubstring!&, '($;$1orld&

    String tail = greetingsubstring!&$;$1orld2&

    H e l l o , W o r l d )

    / 3 4 5 6 7 8 9 : ; 3/ 33 34

    substring ?eturns the substring from start tothe end of the string

    substring ?eturns a substring from start to endbut not including the character atend#

  • 7/23/2019 03 Strings

    4/104

    Concatenation Operator

    0nother common operation on String is

    concatenation# 0s another special support for String, 'ava

    overloaded the @ operator to be used to concatenatetwo String objects to get a bigger one#String *irst+ame = mr;

    String last+ame = l-.bra/im;

    String *ull+ame = last+ame0 0*irst+ame;

    $0lIbrahim 0mr&

    If one of the operands of the @ operator is a string,the other is automaticall* converted to string and

    the two strings are then concatenated#String course = .1S;

    int code = '"(;

    String course1ode = course0code$ICS3/4&

    1e fre"uentl* use the concatenation operator inprintlnstatements#

    S2stemoutprintln!3/e area =0area$;

    Aou need to be careful with concatenation operator#For example, what do *ou this the following printB

    S2stemoutprintln!Sum =0405$;

  • 7/23/2019 03 Strings

    5/105

    Strings are Immutable

    0nother special feature of Strings is that the* 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);

    Instead of changing the str3 object, another objectis created# The former is garbage collected, thus,the reference to the former is lost#

    The fact that Strings are immutable allows the 'avas*stem to process Strings ver* efficientl*#

    For example, consider the following.

    String str1 = Hello;

    String str2 = Hello;

    1e would expect the following

    ut in fact, this is what happens

    The 'ava s*stem is smart enough to )now that thetwo strings are identical and allocates samememor* location for the two objects

  • 7/23/2019 03 Strings

    6/106

    Methods of the String Class

    .n addition to t/e substring met/ods, se6eral

    prede*ined met/ods are pro6ided in t/e built-inString class Some o* t/ese are:

    nt length() returns the number ofcharacters in this String

    String toUpperCase()

    String toLowerCase()

    returns a new String,

    e"uivalent to the Dpperlowercase of this String

    boolean equals(s)

    booleanequalsIgnoreCase(s)

    returns true if sthe same as thisString#

    nt compareTo(String s)ntcompareToIngoreCase(s)

    returns @ve number, /, or venumber if this String is greaterthan, e"ual to or less than s#

    char charAt(index) returns the char in this String,at the indexposition#

    nt indexOf(ch)nt lastIndexOf(ch)

    ?eturns the index of the first last occurrence of chin thisstring, If not fount3 is returned

    String trim() returns a String, obtained b*removing spaces from the startand end of this string#

    static String valueOf (anyprimitive type)

    ?eturns a String representationof the argument

    String concat(s) equivalent to symbol

  • 7/23/2019 03 Strings

    7/107

    !xample using methods of Stringclass

    3/e *ollo%ing program generates a pass%ord *or

    a student using /is initials and age

    public class a!e"assword #

    public static $oid %ain(String&' args) #

    String irsta%e = *+%r*;

    String %iddlea%e = *Sa%ir*;

    String lasta%e = *,bra-i%*;

    e/tract initials

    String initials =

    irsta%e.substring(01)

    %iddlea%e.substring(01)

    lasta%e.substring(01);

    append age

    int age = 20;

    String password =initials.to3owerase()age;

    Syste%.out.println(*5our "assword

    =*password);6

    6

  • 7/23/2019 03 Strings

    8/108

    "ormatting #oating$point numbers

    Some times %e %ould li7e to print *loating

    point numbers onl2 up to certain number o*decimal places

    8or example %e %ould %ant print t/e cost o*an item in t/e *orm: S9'54"

    3o ac/ie6e t/is, %e use t/eget+umber.nstance met/od o* t/e t/enumber8ormat class o* t/e ja6atextpac7age, to create an object

    We t/en use t/e setaximum8ractionDigitsand setinimum8ractionDigits met/ods toset t/e decimal places reuired

    8inall2, %e use t/e *ormat met/od to *ormatour number

    3/e *ormat met/od returns a string, so %ecan print it

    3/e example in t/e next slide demonstratet/is process

  • 7/23/2019 03 Strings

    9/109

    "ormatting #oating$point numbers

    i%port 7a$a.te/t.u%ber8or%at;

    public class u%ber8or%atting #public static $oid %ain(String&' args) #

    u%ber8or%at or%atter =u%ber8or%at.getu%ber,nstance();

    or%atter.seta/i%u%8raction9igits(2);

    or%atter.setini%u%8raction9igits(2);

    double annualSalary = :200;

    double %ont-lySalary =annualSalary12;

    Syste%.out.println(**%ont-lySalary);

    Syste%.out.println(*8or%atted SalaryS>*or%atter.or%at(%ont-lySalary));

    6

    6

  • 7/23/2019 03 Strings

    10/10

    10

    "ormatting #oating$point numbers

    1e can also use the Decimal8ormatclass of the

    same pac)age to format floatingpoint numbers# In this approach, we create an object of the

    ecimalFormat class, specif*ing the format we

    want as a parameter#

    The difference between this approach and theprevious is that the comma is not used b* default#

    import ja6atextDecimal8ormat;

    public class Decimal8ormatting args$