Sunteți pe pagina 1din 12

Handout 33

Programming - 2

Umair Javed
BTE

Strings
Please note that this topic is not discussed in detail in the lecture. Please cover it by
yourself. Any queries are warmly welcomed.

What is a string?
A string is commonly considered to be a sequence of characters stored in memory and
accessible as a unit.

What is a string in Java?


Strings in Java are represented as objects.

What is a string literal?


Java considers a series of characters surrounded by quotation marks to be a string literal
or string constant. In the following example s is a string literal.
String s = "This is a string literal in Java "

How to create String Objects?


The first thing to notice is that a String object can be created using either of the following
constructs:
String str1 = new String("String named str2");
String str2 = "String named str1";

The first approach uses the new operator to instantiate an object while the shorter version
doesn't use the new operator.

Umair 2006, All Rights Reserved

-1-

TA: Munawar Nadeem

Handout 33
Programming - 2

Umair Javed
BTE

String Concatenation
String concatenation in Java
Java supports string concatenation using the + operator as shown in the following
example
String cat = "cat";
System.out.println("con" + cat + "enation");

In addition, it will convert many different types (int, float etc) to objects of a String as
we have been using this form of code in many examples since the beginning of the
course.
int myVar = 25;
Var has a value " + myVar + " at this point."
//So, it will be converted into string as
Var has a value 25 at this point."

Note: string concatenation can also be achieved by using the concat method of the
string class. We see the example of using concat shortly.

You Can't Modify a String Object, but You Can Replace It


Contents of a String object cannot be modified, a reference to a String object can point
to a different String object as illustrated in the following sample program. Sometimes
this makes it appear that the original String object is being modified.

class StringTest{
public static void main(String[] args){
String str1 = "first string";
String str2 = "second string";
System.out.println("Display original string values");
System.out.println(str1);
System.out.println(str2);
System.out.println("Replace str1 with another string");

str1 = str1 + " " + str2;

Umair 2006, All Rights Reserved

-2-

TA: Munawar Nadeem

Handout 33
Programming - 2

Umair Javed
BTE

System.out.println("Display new str1 string");


System.out.println(str1);
}//end main()
}//end class String01

Output
File StringTest.java
This application illustrates the fact that while a
String object cannot be modified, the reference variable
can be modified to point to a new String object which
can have the appearance of modifying the original String
object.
The output from this program is
Display original string values
first string
second string
Replace str1 with another string
Display new str1 string
first string second string

It is important to note that the following statement does not modify the original object
pointed to, by the reference variable named str1.
str1 =

str1 + " " + str2;

Rather, this statement creates a new object which is concatenation of two existing objects
and causes the reference variable named str1 to point to the new object instead of the
original object.
The original object then becomes eligible for garbage collection. See handout on Memory
Management & Garbage Collection for more info.
The above discussion is summarized in the diagram below

Umair 2006, All Rights Reserved

-3-

TA: Munawar Nadeem

Handout 33
Programming - 2

Umair Javed
BTE

str1

Fist string

str2

second string

str1

second string second string

str2

second string

str1 pointing to new string after


execution of following line

str1 and str2 after their


creation and initialization

Umair 2006, All Rights Reserved

Fist string

str1 = str1 + + str2;

-4-

TA: Munawar Nadeem

Handout 33
Programming - 2

Umair Javed
BTE

Comparing Strings
While comparing strings, never use == operator. The String class equals method should
be used for the comparison purposes. The example of comparing strings is given in the
coming next program.

Remember
everything is a reference (except primitives)

==

Compares references only! (shallow comparison)


Does not compare what is pointed to by the pointers

equals() method
Default implementation same as ==
String class overrides to do a deep comparison, i.e. comparison of
characters.

Constructors and Methods of the String Class


The following chart shows some of the constructor and method declarations for the
String class. For complete list of methods, see the Java API documentation.
You will need a copy of that or some similar specification to determine the meaning of
some of the parameters in the constructors and methods in the String class.

String Class
// Constructors
public String();
// Methods
public char charAt(int
public String

index);

concat(String

str);

public boolean equals(Object anObject);


public boolean equalsIgnoreCase(String anotherString);
public String
public String

substring(int
substring(int

public String
public String

toLowerCase();
toUpperCase();

beginIndex);
beginIndex, int endIndex);

public String[] split(String regex)

Umair 2006, All Rights Reserved

-5-

TA: Munawar Nadeem

Handout 33
Programming - 2

Umair Javed
BTE

The Sample Program


The following program shows you the usage of some sample methods
public class StringMethodsApp {
public static void main (String args[]) {
String str1 = "Hello World";
String str2 = new String("Pakistan");
char c = str1.charAt(0);
System.out.println("char of str1 at 0 index: " + c);
System.out.println();
String conByMethod = str1.concat(str2);
String conByOperator = str1 + str2;
System.out.println("concatenate by method: " + conByMethod);
System.out.println("concatenate by method: " + conByOperator);
System.out.println();
System.out.println( "comapring strings");
if (str2 == "Paksitan") {
System.out.println("strings equal using ==");
}
if (str2.equals("Pakistan")) {
System.out.println("strings equal using equals method");
}
System.out.println();
String sub = str1.substring(5);
System.out.println("substring of str1: "+sub);
System.out.println();
String lower = str1.toLowerCase();
System.out.println("str1 in lower case: "+ lower);
}

Umair 2006, All Rights Reserved

-6-

TA: Munawar Nadeem

Handout 33
Programming - 2

Umair Javed
BTE

Output
File StringMethodsTest.java
This application illustrates the usage of some basic
methods of the string class
The output from this program is
char of str1 at 0 index: H
concatenate by method: Hello WorldPakistan
concatenate by operator: Hello WorldPakistan
comparing Strings
strings equals using equals method
substring of str1: World
str1 in lower case: hello world

split method of the String Class


The split ( ) method allows an application to break a string into tokens. A token is a
substring of the string. This method takes a delimiter (the character that separate
tokens) as an argument. The delimiter is not included in the token string.
The following program shows the usage of split method.
public class TokensTest {
public static void main (String args[ ]) {
String str1 = this is test;
Strign str2 = web design, development;
System.out.println(tokenizing string
String tokens1[] = str1.split( );
System.out.println(first token: +
System.out.println(second token: +
System.out.println(third token: +

using space);
tokens[0]);
tokens[1]);
tokens[2]);

System.out.println();
System.out.println(tokenizing string using comma);
String tokens1[] = str1.split(,);
System.out.println(first token: + tokens[0]);
System.out.println(second token: + tokens[1]);
}
}

Umair 2006, All Rights Reserved

-7-

TA: Munawar Nadeem

Handout 33
Programming - 2

Umair Javed
BTE

Output
File TokensTest.java
This application illustrates how to tokenize string
using delimiter
The output from this program is
tokenizing string using space
first token: this
second token: is
third token: test
tokenizing string using comma
first token: web design
second token: development

Umair 2006, All Rights Reserved

-8-

TA: Munawar Nadeem

Handout 33
Programming - 2

Umair Javed
BTE

Converting Strings to Numeric Primitive Data Types


How would you convert a string containing digits to a primitive data types?
The following table summarizes the list of methods that are used for the above mentioned
point.
Data Type
byte
new
short
new
int
new
long
new
float
new
double
new

Convert String using either


Byte.parseByte(string )
Byte(string ).byteValue()
Short.parseShort(string )
Short(string ).shortValue()
Integer.parseInteger(string
)
(string)
Integer(string ).intValue()
Long.parseLong(string )
Long(string ).longValue()
Float.parseFloat(string )
Float(string ).floatValue()
Double.parseDouble(string )
Double(string ).doubleValue()

The following program illustrates the conversion of string into integer and double. You
can follow the same pattern / procedure for other conversions
class ConvertStringTest{
public static void main(String[] args){
String intString = "20";
String doubleString = "35.573";

//converting string into int using parseInt method


System.out.println(converting string into int);
int num1 = Integer.parseInt (intString);
System.out.println(num1);
//converting string into int using intValue method
int num2 = new Integer(intString).intValue();
System.out.println(num2);
//converting string into double using parseDouble method
System.out.println(converting string into double);
double double1 = Double.parseDouble (doubleString);

Umair 2006, All Rights Reserved

-9-

TA: Munawar Nadeem

Handout 33
Programming - 2

Umair Javed
BTE

System.out.println(double1);

//converting string into double using doubleValue method


double double2 = new Double(doubleString).doubleValue();
System.out.println(double2);

Output
File ConvertTest.java
This application demonstrates how to convert string into
an integer and double.
The output from this program is
converting string into int
20
20
converting string into double
35.573
35.573

Umair 2006, All Rights Reserved

- 10 -

TA: Munawar Nadeem

Handout 33
Programming - 2

Umair Javed
BTE

Array of String References


Declaring and instantiating a String array
The following statement declares and instantiates an array of references to three string
objects.
String[] stringOfReferences = new String[3];

No string data at this point


Note however, that this array doesn't contain the actual string data. Rather, it simply sets
aside memory for storage of five references to strings. No memory has been set aside to
store the characters that make up the individual strings. You must allocate the memory
for the actual string objects separately using code similar to the following.

Allocating memory to contain the String objects


stringOfReferences[0] = new String(
"This is the first string.");
stringOfReferences[1] = new String(
"This is the second string.");
stringOfReferences[2] = "This is the third string.");

Now, the memory would be allocated to each reference

Umair 2006, All Rights Reserved

- 11 -

TA: Munawar Nadeem

Handout 33
Programming - 2

Umair Javed
BTE

References:

Sun java tutorial: http://java.sun.com/docs/books/tutorial/java


String Tutorial: http://www.eimc.brad.ac.uk/java/tutorial/Project/4/string.htm

Umair 2006, All Rights Reserved

- 12 -

TA: Munawar Nadeem

S-ar putea să vă placă și