Results 1 to 7 of 7
Like Tree7Likes
  • 7 Post By levent

Thread: Java String

  1. #1
    levent Guest

    Default Java String

    A string is an ordered sequence of symbols. Sting class is included in java.lang package. So each class in Java, can use String class without importing any package. The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

    Java String Class/Java String API

    Java String class or Java String API is under package java.lang. String class provides various methods to play with strings for example: length(), charAt(int index), substring(int begin, int end), StringTokenizer (its a class), toUpperCase(), equals(). and some others.

    Java String Array

    We may also declare arrays of type string. String Array can store strings in it.

    Example:

    Java Code:
    	String[] str_array = new String[2]; 
    	str_array[0] = "Java String";
    	str_array[1] = "Java String Array";
    		
    	System.out.println("Index 0: " + str_array[0]);
    	System.out.println("Index 1: " + str_array[1]);
    Output:

    Index 0: Java String
    Index 1: Java String Array

    Arrays in Java start from index 0. In the above example, first we declared an array named str_array of size 2. It means it will have index 0 and 1. We added some text in arrays index 0 and 1 and then displayed on the console.

    Java String Concatenation

    Java Strings can be concatenated using operator +.

    Example:

    Java Code:
    String a = "Java String1";
    String b = "Java String2";
    		
    System.out.println("Concatenating strings: " + a + b);
    Output:

    Concatenating strings: Java String1Java String2

    In the above example, we concatenated 3 strings and printed on the console.

    Java: Convert String to int

    In Java programming, converting String to integer is easy. Though programmer who had worked in C++, might think converting String to Integer will be tricky, but its not the case. Java has wrapper classes for this purpose. We will use Integer wrapper class to convert String to int.

    Example:

    Java Code:
    String str_int = "10";
    int a = Integer.parseInt(str_int);
    // printing a which is integer
    System.out.println("Java String to int: " + a);
    Output:

    Java String to int: 10

    Java Split String:

    Java String class has many functions that can be used to split string according to requirements.

    Example:

    Java Code:
    String str_a = "Java String";
    // Java String Length
    int len = str_a.length();
    System.out.println("Length of string is: " + len);
    // start index is 0
    System.out.println("Character at 5: " + str_a.charAt(5));
    System.out.println("Characters form 5 till end: " + str_a.substring(5, len));
    Output:

    Length of string is: 11
    Character at 5: S
    Characters form 5 till end: String

    In the given example, first we used length() function to get the length of the string. We stored the length into a variable for later use. Then we used chatAt() function to simply print the character at 5th position of the string. Point to note is that indexes also start here with zero as in arrays. At the end we used function substring() to extract a string from str_a. substring() function takes two input parameters. First one is the start index and second one is the ending index. This function will extract string between the given indexes (inclusive).

    Java String Comparison

    Java String compare is very commonly used by Java programmers but its a bit tricky. Some of us might make mistake while doing it and get wrong
    results. Normally we use == (double equal) for comparison. This should not be used for reference datatypes. String is a reference data type so one should avoid using == for String comparison. If we use == for comparison, it wont be a syntax error. It will actually compare references of two strings.

    Example:

    Java Code:
    String a  = new String("Java String1");
    String b = new String("Java String1");
    		
    if(a == b)
            System.out.println("Both Java Strings are equal.");
    else
    	System.out.println("Java Strings are not equal.");
    		
    if(a.equals(b))
    	System.out.println("Both Java Strings are equal.");
    else
    	System.out.println("Java Strings are not equal.");
    Output:

    Java Strings are not equal.
    Both Java Strings are equal.

    In the given example, first we compared the references of the two strings. If condition failed as both have different references. Then we compared the contents of the strings using eduals() method and got the desired output.

    In Java, string can lexicographically be compared using compareTo() and compareToIgnoreCase() functions. These functions return value 0 if the argument is a string lexicographically equal to the string with which it is called; a value less than 0 if the argument is a string lexicographically greater than string with which it is called; and a value greater than 0 if the argument is a string lexicographically less than string with which it is called.

    Java String Replace:

    You are not supposed to make your own methods for replacing characters in a String. Java String class provides methods for replacing characters in Strings. There are many situations. Lets start with a simple one. Lets say we want to replace all occurrences of a given character in a String.

    Example:

    Java Code:
    String str_original = "A Java String";
    String str_replaced = str_original.replace( 'a', 'b' );
    System.out.println( "Original String = " + str_original );
    System.out.println( "Replaced String = " + str_replaced );
    Output:

    Original String = A Java String
    Replaced String = A Jbvb String
    Java is case sensitive so character a is replaced by character b and character A has remained unchanged.

    Now lets assume we want to replace a character in a String at a specified position. We can use the following function for this purpose:

    Java Code:
    public static String replaceCharAt(String s, int pos, char c) {
       return s.substring(0,pos) + c + s.substring(pos+1);
    }
    Example:

    Java Code:
    System.out.println( "Replacing char at given position: " + replaceCharAt("Java String",1,'J') );
    Output:

    Replacing char at given position: JJva String

    Java: String to Char Array:

    Sometimes, programmers need to convert a String to character array. Java String API provides a method called toCharArray() that simple convert the String passed as argument to a character array.

    Example:

    Java Code:
    String str_a = "Java String";
    char[] char_array = new char[str_a.length()];
    		
    char_array = str_a.toCharArray();		
    	
    for (int i = 0; i < str_a.length(); i++){
    	System.out.print (char_array[i]);
    }
    Output:

    Java String

    The above example is obvious but it contains some important programming tips. As we know that array cannot be of open size and we have to mention the size of array while declaring it. Now we could have declared a character array of large size to cope with the problem in hand. But better way is to declare the array to exactly the size we need. Since we want to store characters of String str_a in our array, so we used length() function to get the size of string and then we declared the character array of that size.

    char[] char_array = new char[str_a.length()];

    Later we printed each character of the character array.

    Java: Convert String to Date

    Sometimes you face situation, where the date is in some String variable and you need to store it in Date object for calculations. Java provides support for this as well.

    Example:

    Java Code:
    String strTmp = "05/17/07";
    Date dtTmp = new SimpleDateFormat("MM/dd/yy").parse(strTmp);
    System.out.println("Date is : " + dtTmp);
    Output:

    Date is : Thu May 17 00:00:00 CEST 2007

    Please note, you have to import following packages before using the above code.

    Java Code:
    import java.util.Date;
    import java.text.SimpleDateFormat;
    dtTmp is of type Date and it contains date and can be used in further calculations.

    Java: Convert Number to String

    Many times while coding, situation will arise when you have to convert an integer into String. String API provides a was for that too. We have to use Wrapper class for this.

    Example:

    Java Code:
    int int_num = 10;
    String str_num = Integer.toString(int_num);
    System.out.println("Integer converted to String: " + str_num);
    Output:

    Integer converted to String: 10

    Java: String to Long

    Converting value stored in String variable to Long is also very simple. Just use Wrapper class Long and method parseLong() and you will get Long value. Store it in Long variable or just simply use it in your calculations.

    Example:

    Java Code:
    String str_num = "1001";
    long long_num = Long.parseLong(str_num);
    System.out.println("String converted to Long: " + long_num);
    Output:

    String converted to Long: 1001

    Java. String to Double:

    Converting value stored in String variable to Double is also very simple. Just use Wrapper class Double and method parseDouble() and you will get Double value. Store it in Double variable or just simply use it in your calculations.

    Example:

    Java Code:
    String str_num = "1001.66";
    double double_num = Double.parseDouble(str_num);
    System.out.println("String converted to double: " + double_num);
    Output:

    String converted to double: 1001.66

    Java: char to String:

    Sometimes, it happens that you are required to convert value stored in a character to String. Again Wrapper classes provides the solution. Character wrapper class can be used to achieve the results.

    Example:

    Java Code:
      char a= 'a';
      String myString = Character.toString(a);
      System.out.println("Character converted to String: " + myString);
    Output:

    Character converted to String: a

    Java: Byte Array to String:

    Converting ByteArray to String is simple in Java. You just have to use constructor of String class.

    Example:

    Java Code:
    byte[] byteArray = null;
    //someInputStream.read(byteArray);
    String str = new String(byteArray);
    In the above example, we assume that byte array will be filled by inputstream. InputStream might be reading from some socket connection.

    Java String Manipulation:

    String manipulation in Java is very easy as java.lang.String API (commonly known as string API) provides a lot of useful function to make the life of developer easier. Let consider the following example:

    Example:

    Java Code:
    int int_a = 25;
    String str_a = "I have ";
    String str_b = " dollars.";
    String str_c = str_a + int_a + str_b;
    System.out.println(str_c);
     
    // now we want to add int_b value
    int int_b = 30;
    
    int int_c = int_a + int_b;
    		
    str_c = str_c.replace(Integer.toString(int_a),Integer.toString(int_c));
    System.out.println(str_c);
    Output:

    I have 25 dollars.
    I have 55 dollars

    This example will clear your concepts about Java String manipulation. We have an integer value in int_a that has to be placed between two Strings. It is simply done by:

    Java Code:
    String str_c = str_a + int_a + str_b;
    Java 5 compilier implicitly converted int_a to String. Now we want to add int_b into int_a. This is simple and easily done:
    int int_c = int_a + int_b;

    Now we have to replace int_a with int_c in String str_c. We will use replace() function of Java String API but problem is, replace() function expects two String arguments and we have int arguments. So we have to convert both int to String. This can be done using Wrapper classes. So replace statement will look like:

    Java Code:
    str_c = str_c.replace(Integer.toString(int_a),Integer.toString(int_c));
    Now str_c has the updated text.

    Java String Upper/Lower cases:

    Java String API provides methods to change the case of the String. Methods like toUpperCase(), toLowerCase are very useful for programmers. If these were not provided, consider the coding you have to do to change each character one by one in loops.

    Example:

    Java Code:
    String str_orig = "Java String";
    System.out.println("Original String: " + str_orig);
    String str_low = str_orig.toLowerCase();
    System.out.println("Lower case String: " + str_low);
    String str_upper = str_low.toUpperCase();
    System.out.println("Upper case String. " + str_upper);
    Output:

    Original String: Java String
    Lower case String: java string
    Upper case String. JAVA STRING

    Java String Trim:

    Java String API includes a function called trim() that is used to return a copy of the string, with leading and trailing whitespace omitted. It does not remove spaces inbetween strings.

    Example:

    Java Code:
    String str_a = "  Java  String  ";
    System.out.println("String is: " + str_a + " of length: " + str_a.length()  );
    System.out.println("Trimmed String is: " + str_a.trim() + " of length: " + str_a.trim().length());
    Output:

    String is: Java String of length: 16
    Trimed String is: Java String of length: 12

    Java StringTokenizer Class:

    Sometimes it's necessary to break a large string into smaller components. These small components are called tokens. Javas utility package has a class called StringTokenizer (java.util.Stringtokenizer) that can be used to get tokens from a large String.

    Example:

    Java Code:
    String str_a = "Java String API Conversions";
    		
    StringTokenizer st = new StringTokenizer(str_a);
    while (st.hasMoreTokens()) {
       System.out.println(st.nextToken());
    }
    Output:

    Java
    String
    API
    Conversions

    The aim of this Java String tutorial was to give you basic understanding of Java String API and also to introduce you with some useful String functions. I hope this helps.

  2. #2
    cruxblack is offline Senior Member
    Join Date
    Jul 2007
    Posts
    130
    Rep Power
    0

    Default

    Wow, should've read this tutorial before i asked bout that String to char conversion in my thread Mr. levent, good one :D

  3. #3
    goldhouse is offline Senior Member
    Join Date
    Mar 2007
    Posts
    134
    Rep Power
    0

    Default

    little more

    a reference Reference text book
    String canonicalization

    There can be some confusion about whether Strings are already canonicalized. There is no guarantee that they are, although the compiler can canonicalize Strings that are equal and are compiled in the same pass. The String.intern( ) method canonicalizes strings in an internal table. This is supposed to be, and usually is, the same table used by strings canonicalized at compile time, but in some earlier JDK versions (e.g., 1.0), it was not the same table. In any case, there is no particular reason to use the internal string table to canonicalize your strings unless you want to compare Strings by identity (see ). Using your own table gives you more control and allows you to inspect the table when necessary. To see the difference between identity and equality comparisons for Strings, including the difference that String.intern( ) makes, you can run the following class:
    Java Code:
    {
      public static void main(String[] args)
      {
        System.out.println(args[0]); 	//see that we have the empty string
     
        //should be true
        System.out.println(args[0].equals(""));
     
        //should be false since they are not identical objects
        System.out.println(args[0] == "");
     
        //should be true unless there are two internal string tables
        System.out.println(args[0].intern(  ) == ""); 
      }
    }
    This Test class, when run with the command line:
    java Test ""

    gives the output:
    true
    false
    true
    Changeable objects

    Canonicalizing objects is best for read-only objects and can be troublesome for objects that change. If you canonicalize a changeable object and then change its state, then all objects that have a reference to the canonicalized object are still pointing to that object, but with the object's new state. For example, suppose you canonicalize a special Date value. If that object has its date value changed, all objects pointing to that Date object now see a different date value. This result may be desired, but more often it is a bug.

    If you want to canonicalize changeable objects, one technique to make it slightly safer is to wrap the object with another one, or use your own (sub)class.[5] Then all accesses and updates are controlled by you. If the object is not supposed to be changed, you can throw an exception on any update method. Alternatively, if you want some objects to be canonicalized but with copy-on-write behavior, you can allow the updater to return a noncanonicalized copy of the canonical object.

    Note that it makes no sense to build a table of millions or even thousands of strings (or other objects) if the time taken to test for, access, and update objects in the table is longer than the time you are saving canonicalizing the

  4. #4
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    6

    Default String literals *are* interned!

    It is part of the Java Language Specification that all String literals are interned, using the same method that String.intern() uses. There's really no ambiguity-- if a VM doesn't do this, it's a broken VM and you shouldn't use it!

  5. #5
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    6

    Default

    I don't think there's any ambiguity: String literals are always interned, using the same internal table as String.intern(), according to the Java Language Specification!

  6. #6
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    6

    Default

    If you're canonicalising Strings to save memory, then it's worth bearing a few other things in mind about the memory usage of strings.
    - When you call substring() on a String, the substring shares the same character buffer as the parent String. So if you then throw away the parent string, you effectively waste memory (you can solve by wrapping new String(...) around the substring).
    - StringBuilder and StringBuffer, when trimmed to their current length, use a little bit less space than String objects.
    - In many cases you can use any old CharSequence rather than specifically a String, and then you can define your own CharSequence implementation to use (say) one byte per character instead of two (if you don't need full Unicode).
    Related articles I've written:
    - Memory usage of Java Strings: how to calculate their usage (and that of other objects)
    - Memory usage of StringBuffer and StringBuilder
    - How to save memory used by Strings: a look at the various techniques mentioned, with an example CompactCharSequence class that uses one byte per character.

  7. #7
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

Similar Threads

  1. Replies: 2
    Last Post: 09-18-2008, 07:30 AM
  2. Replies: 0
    Last Post: 11-20-2007, 04:59 PM
  3. Help with string and array in java
    By zoe in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 06:12 AM
  4. Char to String in java
    By trill in forum New To Java
    Replies: 1
    Last Post: 08-01-2007, 01:42 PM
  5. Can't convert java.lang.String to int.
    By Albert in forum AWT / Swing
    Replies: 2
    Last Post: 07-13-2007, 05:05 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •