Strings & Things: Introduction To The Java API
Strings & Things: Introduction To The Java API
String literal
String methods
Like most classes, the String class contains
several member methods that can be called
from String objects (variables)
Several of these are listed and described on
pages 38 42 of your textbook; we will
examine some of these
Program example
public class StrNotes {
public static void main (String [] args){
final String NAME = new String ("Cate");
String frag = new String (NAME.substring(1, NAME.length()));
String nonsns1 = new String ("Bo-b");
String nonsns2 = new String ("Banana fana fo-f");
String nonsns3 = new String ("Fe fi mo-m");
char space = ' ';
System.out.println(NAME + space + NAME + space + nonsns1 + frag);
System.out.println(nonsns2 + frag);
System.out.println(nonsns3 + frag + space + NAME);
}
}
Example
// computing the roots of a quadratic equation:
double
a,
// coefficient of x squared
b,
// coefficient of x
c,
// 3rd term in equation
x1,
// first root
x2;
// second root
// read in values for a, b, and c not shown here
x1 = (-b + Math.sqrt(Math.pow(b, 2) (4 * a * c))) / (2 * a);
x2 = (-b - Math.sqrt(Math.pow(b, 2) (4 * a * c))) / (2 * a);
Examples
If rg is a previously-constructed Random object,
then the following expressions produce the values
indicated:
rg.nextInt(10) produces a value between 0 and 9
rg.nextInt(10) + 1 produces a value between 1 and 10
2 * (rg.nextInt(10) + 1) produces an even number
between 2 and 20
rg.nextInt(21) 10 produces an number between -10
and 10