More on Strings


Converting Strings to Char Arrays

A String's characters can be easily stored in a char array: toCharArray() method

Example:
String str = "Mary";
char[] myChars = str.toCharArray();
for(int i = 0; i < myChars.length; i++)
    System.out.println(myChars[i]);

Output:
M
a
r
y



Parsing  Strings to Numeric Types


Example:
String str1 = "3.5";
String str2 = "14";

double num1 = Double.parseDouble(str1);
int num2 = Integer.parseInt(str2);

System.out.println("sum of nums: " + (num1 + num2));

Output:
sum of nums: 17.5


Command Line Arguments


Example:
public class TryCommand
{
    public static void main(String[] args)
    {
       // print the sum of the 2 integer command line arguments
       System.out.println("Sum: " + (Integer.parseInt(args[0]) + Integer.parseInt(args[1])));
    }
}

Sample Run: Compiling and Excuting from the command line
javac TryCommand.java
java TryCommand 3 5
Output:
Sum: 8



Reading Text from a File



Example:
File myFile = new File("sample.txt");
Scanner scan = new Scanner(myFile);

// print first token in file
System.out.println(scan.next());