CIS 160 Strings and parsing

Objectives

  • Convert a String into a numeric value
  • Discuss and use some common String methods
  • Discuss and use wrapper classes

parsing and wrapper classes

  • Java gets most input as Strings.
  • You will often have to convert Strings into numeric values.
  • All of the built-in numeric data types have conversion routines to help.
  • Assuming you want to convert the String variable strWidth:
    • into a byte: byte width = Byte.parseByte(strWidth)
    • into a short: short width = Short.parseShort(strWidth)
    • into a int: int width = Integer.parseInt(strWidth)
    • into a long: long width = Long.parseLong(strWidth)
    • into a float: float width = Float.parseFloat(strWidth)
    • into a double: double width = Double.parseDouble(strWidth)
  • The classes used above to do the conversions are called wrapper classes. They are classes that add additional functionality for each built-in data type (eg. the Integer class for int values).

Strings

  • declaring: String name;
  • declaring and initializing: String name = "Dave";
  • concatenating: String strGreeting = "Hello, " + name;
  • displaying: System.out.println(strGreeting);
  • displaying: System.out.println("Hello, " + name);

Common Java String methods

MethodPurpose
s1.equals(s2)returns true or false
s1.equalsIgnoreCase(s2)returns true or false
s1.compareTo(s2)returns an integer less than 0 if s1 is less than s2, greater than 0 if s1 is greater than s2, and equal to 0 if s1 is the same as s2
s1.compareToIgnoreCase(s2)returns an integer less than 0 if s1 is less than s2, greater than 0 if s1 is greater than s2, and equal to 0 if s1 is the same as s2
s1.toUpperCase()returns the upper case version of string s1
s1.toLowerCase()returns the lower case version of string s1
s1.length()returns the length of string s1

External resource