Friday, January 22, 2016

Topci 21: String Class in Java

  • In Java, every string, including string constant, we create is actually an object of type String

  • Objects of type String are immutable; once a String object is created, its contents cannot be altered. 

  • Java defines a peer class of String, called StringBuffer, which allows strings to be altered.

The String class contains several methods that you can use. For ex, we can test two strings for equality by using equals( ). We can obtain the length of a string by calling the length( ) method. We can obtain the character at a specified index within a string by calling charAt( ). We can have arrays of strings. For ex: String str[] = { "one", "two", "three" }


Using Command-Line Arguments


If we require to pass information into our Java program during run-time, we can accomplish this by passing command-line arguments to main( ).

A command-line argument is the information that directly follows the program’s name on the command line when it is executed.

Command-line arguments are stored as strings in a String array passed to the args parameter of main( ). The first command-line argument is stored at args[0], the second at args[1], and so on. For ex, the following program displays all of the command-line arguments that it is called with:

// Display all command-line arguments.
class CommandLine
{
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}


Important note: All command-line arguments are passed as strings. We must convert numeric values to their internal forms manually. 

 

Click for NEXT article.

 

Please feel free to correct me by commenting your suggestions and feedback.

No comments:

Post a Comment