Java Forums

Main Menu
Home
Today's Posts
FAQ
Search
Contact Us

Java Network
Java Tips
Java Tips Blog

Sponsored Links





Welcome to the Java Forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community, you will:

  • have access to post topics
  • communicate privately with other members (PM)
  • not see advertisements between posts
  • have the possibility to earn one of our surprises if you are an active member
  • access many other special features that will be introduced later.

Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact us.

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 07-29-2007, 01:29 AM
Senior Member
 
Join Date: Dec 2006
Posts: 748
levent is on a distinguished road
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 (it’s 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:

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:

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:

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:

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 it’s 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:

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:

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:

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

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:

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:

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.

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:

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:

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:

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:

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:

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:

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:

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:

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:

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:

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. Java’s utility package has a class called StringTokenizer (java.util.Stringtokenizer) that can be used to get tokens from a large String.

Example:

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.
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 07-29-2007, 03:56 AM
Senior Member
 
Join Date: Jul 2007
Posts: 130
cruxblack will become famous soon enough
Wow, should've read this tutorial before i asked bout that String to char conversion in my thread Mr. levent, good one
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 07-29-2007, 08:19 AM
Senior Member
 
Join Date: Mar 2007
Posts: 136
goldhouse is on a distinguished road
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:
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
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Using java.util.Scanner to search for a String in a String Java Tip Java Tips 0 11-20-2007 05:59 PM
Help with string and array in java zoe New To Java 1 08-07-2007 07:12 AM
Error: cannot resolve symbol' on Person (java.lang.String, java.lang.String) baltimore New To Java 1 08-06-2007 08:45 AM
Char to String in java trill New To Java 1 08-01-2007 02:42 PM
Can't convert java.lang.String to int. Albert AWT / Swing 2 07-13-2007 06:05 PM


All times are GMT +3. The time now is 01:16 PM.


VBulletin, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2007, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org