Java String Literals

 

string short intro

assignment

 

 

Run all the examples.

Java uses the class String to manipulate strings
17fig02n.gif (5290 bytes)

In Java, a String literal is defined by the lexical rule:

Java String Literal Examples

 

String str = "abc";
is equivalent to: 
	char data[] = {'a', 'b', 'c'};
	String str = new String(data);
System.out.println("abc");
     String cde = "cde";
     System.out.println("abc" + cde);
     String c = "abc".substring(2,3);
     String d = cde.substring(1, 2);
 

 

public class Substrings
{ public static void main(String[] args)
  { String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    System.out.println(alphabet);
    System.out.println("The substring from index 4 to index 8 is "
      + alphabet.substring(4, 8));
    System.out.println("The substring from index 4 to index 4 is "
      + alphabet.substring(4, 4));
    System.out.println("The substring from index 4 to index 5 is "
      + alphabet.substring(4, 5));
    System.out.println("The substring from index 0 to index 8 is "
      + alphabet.substring(0, 8));
    System.out.println("The substring from index 8 to the end is "
      + alphabet.substring(8));
    try { System.in.read(); }
    catch (Exception e) {}
  }
}

 

import java.io.*;

public class TelephoneNumbers
{ public static void main(String[] args) throws IOException
  { InputStreamReader reader = new InputStreamReader(System.in);
    BufferedReader input = new BufferedReader(reader);
    System.out.print("Enter 10-digit telephone number: ");
    String telephone = input.readLine();
    System.out.println("You entered " + telephone);
    String areaCode = telephone.substring(0,3);
    System.out.println("The area code is " + areaCode);
    String exchange = telephone.substring(3,6);
    System.out.println("The exchange is " + exchange);
    String number = telephone.substring(6);
    System.out.println("The number is " + number);
    System.out.println("The complete telephone number is "
      + "(" + areaCode + ")" + exchange + "-" + number);
    input.readLine();
  }
}

String str = "This is a string";
int len = str.length();

 

Here, the boolean variable result is equal to true, because str does indeed start with "This". In the following example, result is false:

String str = "This is a string";
boolean result = str.startsWith("is");

A similar method is endsWith(), which determines whether the string object ends with a given set of characters. You use that method as follows:

String str = "This is a string";
boolean result = str.endsWith("string");

In this example, result ends up equal to true, whereas the following code segment sets result equal to false:

String str = "This is a string";
boolean result = str.endsWith("This");

 

If you're setting up a table for strings that you want to be able to locate quickly, you can use a hash table. To get a hash code for a string, you can call the hashCode() method:

String str = "This is a string";
int hashcode = str.hashCode();

 

public class MyName
{ public static void main(String[] args)
  { String name = "John R. Hubbard";
    System.out.println(name);
    System.out.println("This string contains " + name.length()
      + " characters.");
    System.out.println("The character at index 4 is "
      + name.charAt(4));
    System.out.println("The index of the character Z is "
      + name.indexOf('Z'));
    System.out.println("The hash code for this string is "
      + name.hashCode());
  }
}

If you want to find the location of the first occurrence of a character within a string, use the indexOf() method:

String str = "This is a string";
int index = str.indexOf('a');

In this example, index is equal to 8, which is the index of the first a in the string.

To find the location of subsequent characters, you can use two versions of the indexOf() method. For example, to find the first occurrence of "i", you might use these lines:

String str = "This is a string";
int index = str.indexOf('i');

This gives index a value of 2. To find the next occurrence of "i", you can use a line similar to this:

index = str.indexOf('i', index+1);

By including the index+1 as the method's second argument, you're telling Java to start searching at index 3 in the string (the old value of index, plus 1). This results in index being equal to 5, which is the location of the second occurrence of "i" in the string. If you called the previous line again, index would be equal to 13, which is the location of the third "i" in the string.

You can also search for characters backwards through a string, using the lastIndexOf() method:

String str = "This is a string";
int index = str.lastIndexOf("i");

Here, index is equal to 13. To search backwards for the next "i", you might use a line like this:

index = str.lastIndexOf('i', index-1);

Now, index is equal to 5, because the index-1 as the second argument tells Java where to begin the backwards search. The variable index was equal to 13 after the first call to lastIndexOf(), so in the second call, index-1 equals 12.

There are also versions of indexOf() and lastIndexOf() that search for substrings within a string. For example, the following example sets index to 10:

String str = "This is a string";
int index = str.indexOf("string");

 

Comparing Strings

Often, you need to know when two strings are equal. For example, you might want to compare a string entered by the user to another string hard-coded in your program. There are two basic ways you can compare strings:

Calling the equals() method

Using the normal comparison operator.

The equals() method returns true when the two strings are equal and false otherwise. Here's an example:

String str = "This is a string";
boolean result = str.equals("This is a string");

Here, the boolean variable result is equal to true. You could also do something similar using the comparison operator:

String str = "This is a string";
if (str == "This is a string")
    result = true;

This also results in result's being true.

Although these two methods are the easiest way to compare strings, the String class gives you many other options. The equalsIgnoreCase() method compares two strings without regard for upper- or lowercase letters. That is, the following code sets result to false, because equals() considers the case of the characters in the string:

String str = "THIS IS A STRING";
boolean result = str.equals("this is a string");

This code fragment, however, sets result to true:

String str = "THIS IS A STRING";
boolean result = str.equalsIgnoreCase("this is a string");

If you want to know more than just if the strings are equal, you can call upon the compareTo() method, which returns a value less than zero when the string object is less than the given string, zero when the strings are equal, and greater than zero if the string object is greater than the given string. The comparison is done according to alphabetical order (or, if you want to be technical about it, according to the ASCII values of the characters). So, this code segment sets result to a value greater than zero, because "THIS IS A STRING" is greater than "ANOTHER STRING":

String str = "THIS IS A STRING";
int result = str.compareTo("ANOTHER STRING");

The following comparison, however, results in a result's being set to a value less than zero, because "THIS IS A STRING" is less than "ZZZ ANOTHER STRING":

String str = "THIS IS A STRING";
int result = str.compareTo("ZZZ ANOTHER STRING");

Finally, the following comparison results in zero, because the strings are equal:

String str = "THIS IS A STRING";
int result = str.compareTo("THIS IS A STRING");

C and C++ programmers will be very familiar with this form of string comparison.

If you really want to get fancy with your string comparisons, you can dazzle your Java programming buddies by using the regionMatches() method, which enables you to compare part of one string with part of another. Here's an example:

String str = "THIS IS A STRING";
boolean result = str.regionMatches(10, "A STRING", 2, 6);

The regionMatches() method's four arguments are:

The previous example sets result to true. In this case, Java starts looking in "THIS IS A STRING" at the tenth character (starting from 0), which is the "S" in "STRING." Java also starts its comparison at the second character of the given string "A STRING," which is also the "S" in "STRING." Java compares six characters starting at the given offsets, which means it is comparing "STRING" with "STRING," a perfect match.

There's also a version of regionMatches() that is case-insensitive. The following example sets result to true:

String str = "THIS IS A STRING";
boolean result = str.regionMatches(true, 10, "A string", 2, 6);

The new first argument in this version of regionMatches() is a boolean value indicating whether the comparison should be case-insensitive. A value of true tells Java to ignore the case of the characters. A value of false for this argument results in exactly the same sort of case-sensitive comparison you get with the four-argument version of regionMatches().

 

String Extraction

There may be many times in your programming career when you want to extract portions of a string. The String class provides for these needs with a set of methods for just this purpose. For example, you can determine the character at a given position in the string by calling the charAt() method, like this:

String str = "This is a string";
Char chr = str.charAt(6);

 

 

public class Alphabet
{ public static void main(String[] args)
  { String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    System.out.println(alphabet);
    System.out.println("This string contains " + alphabet.length()
      + " characters.");
    System.out.println("The character at index 4 is "
      + alphabet.charAt(4));
    System.out.println("The index of the character Z is "
      + alphabet.indexOf('Z'));
    System.out.println("The hash code for this string is "
      + alphabet.hashCode());
    try { System.in.read(); }
    catch (Exception e) {}
  }
}

In these lines, the character variable chr ends up with a value of "s", which is the seventh character in the string. Why didn't chr become equal to "i"? Because, as in C and C++, you start counting array elements at 0 rather than 1.

A similar method, getChars(), enables you to copy a portion of a String object to a character array:

String str = "This is a string";
char chr[] = new char[20];
str.getChars(5, 12, chr, 0);

In this code sample, the character array chr ends up containing the characters "is a st". The getChars() method's arguments are the index of the first character in the string to copy, the index of the last character in the string, the destination array, and where in the destination array to start copying characters.

The method getBytes() does the same thing as getChars() but uses a byte array as the destination array:

String str = "This is a string";
byte byt[] = new byte[20];
str.getBytes(5, 12, byt, 0);

Another way to extract part of a string is to use the subString() method:

String str1 = "THIS IS A STRING";
String str2 = str1.substring(5);

In this case, the String object str2 ends up equal to the substring "IS A STRING". This is because substring()'s single argument is the index of the character at which the substring starts. Every character from the index to the end of the string gets extracted.

If you don't want to extract all the way to the end of the string, you can use the second version of the substring() method, whose arguments specify the beginning and ending indexes:

        String str1 = "THIS IS A STRING";
        String str2 = str1.substring(5, 9);

These lines set str2 to the substring IS A.

 

 

String Manipulation

Although the String class is intended to be used for string constants, the class does provide some string-manipulation methods that "modify" the String object. I have the word "modify" in quotes because these string-manipulation methods don't actually change the String object, but rather create an additional String object that incorporates the requested changes. A good example is the replace() method, which enables you to replace any character in a string with another character:

String str1 = "THIS IS A STRING";
String str2 = str1.replace('T', 'X');

 

public class Replacing
{ public static void main(String[] args)
  { String inventor = "Charles Babbage";
    System.out.println(inventor);
    System.out.println(inventor.replace('B', 'C'));
    System.out.println(inventor.replace('a', 'o'));
    System.out.println(inventor);
    try { System.in.read(); }
    catch (Exception e) {}
  }
}

In this example, str2 contains "XHIS IS A SXRING", because the call to replace() requests that every occurrence of a "T" be replaced with an "X". Note that str1 remains unchanged and that str2 is a brand new String object.

Another way you can manipulate strings is to concatenate them. Concatenate is just a fancy term for "join together." So, when you concatenate two strings, you get a new string that contains both of the original strings. For example, look at these lines of Java source code:

String str1 = "THIS IS A STRING";
String str2 = str1.concat("XXXXXX");

Here, str2 contains "THIS IS A STRINGXXXXXX", whereas str1 remains unchanged. As you can see, the concat() method's single argument is the string to concatenate with the original string.

To make things simpler, the String class defines an operator, the plus sign (+), for concatenating strings. By using this operator, you can join strings in a more intuitive way. Here's an example:

String str1 = "THIS IS A STRING";
String str2 = str1 + "XXXXXX";

This code segment results in exactly the same strings as the previous concat() example. Note that you can use the concatenation operator many times in a single line, like this:

String str = "This " + "is " + "a test";

 

public class Concatenation
{ public static void main(String[] args)
{ String first = "James";
String last = "Gosling";
System.out.println(first + last);
System.out.println(first + " " + last);
System.out.println(last + ", " + first);
String name = first + " " + last;
System.out.println(name);
try { System.in.read(); }
catch (Exception e) {}
}
}

 

If you want to be certain of the case of characters in a string, you can rely on the toUpperCase() and toLowerCase() methods, each of which returns a string whose characters have been converted to the appropriate case. For example, look at these lines:

String str1 = "THIS IS A STRING";
String str2 = str1.toLowerCase();

Here, str2 is "this is a string", because the toLowerCase() method converts all characters in the string to lowercase. The toUpperCase() method, of course, does just the opposite: converting all characters to uppercase.

Sometimes, you have strings that contain leading or trailing spaces. The String class features a method called trim() that removes both leading and trailing whitespace characters. You use it like this:

String str1 = "   THIS IS A STRING   ";
String str2 = str1.trim();

In this example, str2 contains the string "THIS IS A STRING", missing all the spaces before the first "T" and after the "G".

Finally, you can use the String class's valueOf() method to convert just about any type of data object to a string, thus enabling you to display the object's value on-screen. For example, the following lines convert an integer to a string:

int value = 10;
String str = String.valueOf(value);

Notice that valueOf() is a static method, meaning that it can be called by referencing the String class directly, without having to instantiate a String object. Of course, you can also call valueOf() through any object of the String class, like this:

int value = 10;
String str1 = "";
String str2 = str1.valueOf(value);

 

public class TestValueOf
{ public static void main(String[] args)
  { boolean b = true;
    char c = '$';
    int n = 44;
    double x = 3.1415926535897932;
    System.out.println("b = " + b);
    System.out.println("c = " + c);
    System.out.println("n = " + n);
    System.out.println("x = " + x);
    String strb = String.valueOf(b);
    String strc = String.valueOf(c);
    String strn = String.valueOf(n);
    String strx = String.valueOf(x);
    System.out.println("strb = " + strb);
    System.out.println("strc = " + strc);
    System.out.println("strn = " + strn);
    System.out.println("strx = " + strx);
    try { System.in.read(); }
    catch (Exception e) {}
  }
}
conversions

 

public class TestConversions
{ public static void main(String[] args)
  { String today = "May 18, 1998";
    String todaysDayString = today.substring(4, 6);
    int todaysDayInt = Integer.parseInt(todaysDayString);
    int nextWeeksDayInt = todaysDayInt + 7;
	  String nextWeek = today.substring(0, 4) + nextWeeksDayInt
	    + today.substring(6);
    System.out.println("Today's date is " + today);
    System.out.println("Today's day is " + todaysDayInt);
    System.out.println("Next week's day is " + nextWeeksDayInt);
    System.out.println("Next week's date is " + nextWeek);
    try { System.in.read(); }
    catch (Exception e) {}
  }
}


ACTUAL PROBLEMS

 

1..Write a problem that takes a phone number in this form 9058274101. It then prints the following:

area code:             905

exchange number:  827

the number            4101

 

the complete number is (905)8274101

2. Write a program which prints the symbol

 

 

First it must be of a length of  a  

use UNICODE --- \u221E