SE-1010 Dr. Mark L. Hornick 1 Some Java Classes using & calling methodsS
Java’s pre-built classes are stored in the API class libraries ~200 packages 1000’s of classes 10,000’s of methods Winter 2004CS-1010 Dr. Mark L. Hornick 2 Moral: Don’t reinvent the wheel
To use a method, you need to know how to interface to it For example, to round a value to the nearest whole number, use the round method of the Math class: public static long round(double a) This is the method signature as it appears in the API documentation round – the name of the method public – tells us we can call it static – we call the method via the class long – it returns a long datatype as a result double – the datatype of the argument (value) we supply a – the method’s internal name for the value we supply CS-1010 Dr. Mark L. Hornick 3
The call to a method must conform to the signature The round method of the Math class’s signature: public static long round(double a) Suppose we have a variable x containing some value. We make a call to Math.round using the following syntax: long roundedValue = Math.round( x ); or long y = Math.round( 7.0/3 ); Internally, round uses ‘a’ to hold our argument’s value; we can use any identifier name or double expression as the supplied value CS-1010 Dr. Mark L. Hornick 4
The Math class contains many static methods and a few constants: Math.PI – the ratio of the circumference of a circle to its diameter Math.E – the base of the natural logarithms Winter 2004CS-1010 Dr. Mark L. Hornick 5
SE-1010 Dr. Mark L. Hornick 6 The String datatype is a built-in class that represents a sequence of characters “a” “SE-1010” “123” “This is a 6 word string.” “” There is no fundamental restriction on the maximum length of a Java String How does this differ from a int that represents 123? This represents an empty String
Methods of the String class are both static and non-static A static method: static String format( String format, Object… args) double area = ; String s = String.format(“Area is %8.3f”, area); // s contains “Area is 6.123” A non-static method: char charAt( int index ) String s = “Hello”; char c = s.charAt(1); // c contains ‘e’ Winter 2004CS-1010 Dr. Mark L. Hornick 7
Non-static methods of a class are called via a class instance Here, s is an instance of a String: String s = “Hello”; char c = s.charAt(1); // c contains ‘e’ Winter 2004CS-1010 Dr. Mark L. Hornick 8