A method is identified by a method name
Methods that serves a similar purpose are stored in the same class
A class is identified by a class name
For the lecturer:
|
Examples:
|
Each package consists of a number of classes (that provide similar functionality)
|
Some commonly used packages:
|
Example:
|
Note:
|
java.PackageName.ClassName |
(The package name can be composite (e.g. name1.name2), but the most commonly used packages has a non-composite name)
|
java.lang.Math.sin( ... ) |
public class ClassPath1 { public static void main(String[] args) { double x = 1.234; double r; r = java.lang.Math.sin( x ); System.out.print("Sin of " + x); System.out.println(" = " + r ); } } |
How to run the program:
|
|
The import clauses must occur before any class definitions
import classPathName ; |
Examples:
import java.lang.Math; // After the import clauses, you can use the class // by its name, without the entire classPath // This program can now use all things defined inside // the class java.lang.Math without the classPathName public class MyProgram { public static void main(String[] args) { double a; a = Math.sqrt(2.0); // Save computed value in variable System.out.println(a); // You can print the saved value later } } |
It would be a pain to write a long list of import clauses
Example:
import java.lang.Math; import java.lang.Double; import java.lang.Integer; ... import java.util.Scanner; import java.util.Stack; ... |
import java.lang.* ; // import all classes in java.lang package import java.util.* ; // import all classes in java.util package |
|
we must:
|
In other words, we should have written:
import java.lang.Math; // We MUST import this class to use Math.sqrt // without the class path public class Abc { double a, b, c, x1, x2; // Define 5 variable a = 1.0; b = 0.0; c = -4.0; x1 = ( -b - Math.sqrt( b*b - 4*a*c ) ) / (2*a); x2 = ( -b + Math.sqrt( b*b - 4*a*c ) ) / (2*a); System.out.print("a = "); System.out.println(a); System.out.print("b = "); System.out.println(b); System.out.print("c = "); System.out.println(c); System.out.print("x1 = "); System.out.println(x1); System.out.print("x2 = "); System.out.println(x2); } |
|
all classes in the java.lang package are automatically included in every Java program (the Java compiler is programmed to do this)
That is why we did not need to import java.lang.Math in our program.
|