Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Chapter 1 :


Published on

Understanding Packages

Understanding Package-Derived Classes

Compiling and Interpreting Java Code

Published in: Technology, Education
  • Be the first to comment

Chapter 1 :

  1. 1. Packaging, Compiling, and Interpreting Java Code 1
  2. 2. Session Objectives • Understanding Packages • Understanding Package-Derived Classes • Compiling and Interpreting Java Code • Q&A Self Test 2
  3. 3. Exam Objective 5.1 Describe the purpose of packages in the Java language, and recognize the proper use of import and package statements. • Packaging is a common approach used to organize related classes and interfaces. • Most reusable code is packaged. • Packages are thought of as containers for classes, but actually they define where classes will be located in the hierarchical directory structure. • Packaging your classes also promotes code reuse, maintainability, and the objectoriented principle of encapsulation and modularity. 3
  4. 4. The package Statement • Package statements are optional. • Package statements are limited to one per source file. • Standard coding convention for package statements reverses the domain name of the organization or group creating the package. For example, the owners of the domain name may use : com.scjaexam.utilities. • Package names equate to directory structures. The package name com.scjaexam.utils would equate to the directory com/scjaexam/utils. • 4
  5. 5. Source Files • All Java source files must end with extension. • A source file may contain an unlimited number of non-public class definitions. • Three top-level elements known as compilation units may appear in a file. 1.Package declaration 2.Import statements 3.Class, interface, and enum definitions • Use only alphanumeric characters in package names. • You must be careful that each component of your package name hierarchy is a legitimate directory name on all platforms. • Sometimes you might use classes with the same name in two different packages, such as the Date classes in the packages java.util And java.sql Ben Abdallah Helmi Architect en 5 J2EE
  6. 6. 4. If all three top-level elements occur in a source file, they must appear in which order? A. Imports, package declarations, classes/interfaces/enums B. Classes/interfaces/enums, imports, package declarations C. Package declaration must come first; order for imports and class/interfaces/enum definitionsis not significant D. Package declaration, imports, class/interface/enum definitions. E. Imports must come first; order for package declarations and class/interface/enum definitionsis not significant Ben Abdallah Helmi Architect en 6 J2EE
  7. 7. 4. D. Package declaration must come first, followed by imports, followed by class/interface/enum definitions. Ben Abdallah Helmi Architect en 7 J2EE
  8. 8. 8
  9. 9. package and import Statements • To place a source file into a package, use the package statement at the beginning of that file. • You may use zero or one package statements per source file. • To import classes from other packages into your source file, use the import statement. • The java.lang package that houses the core language classes is imported by default. 9
  10. 10. • The package names beginning with java.* and javax.* are reserved for use by JavaSoft, the business unit of Sun Microsystems that is responsible for Java technologies. • Package names should be lowercase. Individual words within the package name should be separated by underscores. 10
  11. 11. The import Statement 11
  12. 12. Importing Java’s static import facility, which was introduced in rev 5.0, allows you to import static data and methods, as well as classes. In other words, you may refer to static data and methods in external classes without using full names. For example, the java.awt.Color class contains static data members names RED, GREEN, BLUE, and so on. Suppose you want to set myColor to GREEN. Without static imports, you have to do the following: import java.awt.Color; … myColor = Color.GREEN; import static java.awt.Color.GREEN; … myColor = GREEN; Note that the import keyword is followed by static. This tells the compiler to import the name of a static element of a class, rather than a class name. Ben Abdallah Helmi Architect en J2EE 12
  13. 13. Static importing gives you access to static methods as well as static data. Suppose class measure.Scales has a method called poundsToMicrograms() that looks like this: public static float poundsToMicrograms(float pounds) { return pounds * KGS_PER_LB * 1.0e6f; } Any source file can import this method as follows: import static measure.Scales.poundsToMicrograms(); A source file that performs this import may invoke the method as (for example) float ugs = poundsToMicrograms(lbs); This is a bit more convenient than float ugs = Scales.poundsToMicrograms(lbs); Ben Abdallah Helmi Architect en 13 J2EE
  14. 14. As with ordinary imports, static imports have only a slight compile-time cost and zero runtime cost. Many programmers are unclear on this point, perhaps because the word “import” feels like such an active verb; it seems as if surely the class loader or some other mechanism must be hard at work. Remember that importing does nothing more than bring a name into the local namespace. So importing and static importing are quite inexpensive. Ben Abdallah Helmi Architect en 14 J2EE
  15. 15. 11. Suppose a source file contains a large number of import statements. How do the imports affect the time required to compile the source file? A. Compilation takes no additional time. B. Compilation takes slightly more time. C. Compilation takes significantly more time. Ben Abdallah Helmi Architect en 15 J2EE
  16. 16. 12. Suppose a source file contains a large number of import statements and one class definition. How do the imports affect the time required to load the class? A. Class loading takes no additional time. B. Class loading takes slightly more time. C. Class loading takes significantly more time. Ben Abdallah Helmi Architect en 16 J2EE
  17. 17. 12. A.. Importing is strictly a compile-time function. It has no effect on class loading or on any other runtime function. Ben Abdallah Helmi Architect en 17 J2EE
  18. 18. 13. Which of the following are legal import statements? A. import java.util.Vector; B. static import java.util.Vector.*; C. import static java.util.Vector.*; D. import java.util.Vector static; Ben Abdallah Helmi Architect en 18 J2EE
  19. 19. 13. A, C. The import keyword may optionally be followed by the static keyword. Ben Abdallah Helmi Architect en 19 J2EE
  20. 20. 14. Which of the following may be statically imported? (Choose all that apply.) A. Package names B. Static method names C. Static field names D. Method-local variable names Ben Abdallah Helmi Architect en 20 J2EE
  21. 21. 14. B, C. You may statically import method and field names. Ben Abdallah Helmi Architect en 21 J2EE
  22. 22. Class Paths When the Java compiler or the Virtual Machine needs a classfile, it searches all the locations listed in its classpath. The classpath is formed by merging the CLASSPATH environment variable and any locations specified in -classpath or -cp command line arguments. The members of a classpath may be directories or jar files. Let’s take an example. Suppose the compiler is looking for class sgsware.sphinx.Domain. The package structure sgsware.sphinx requires that the Domain.class file must be in a directory called sphinx, which must be in a directory called sgsware. So the compiler checks each classpath member to see if it contains sgswaresphinxDomain.class. On Windows platforms, directories and jar files in a classpath are separated by a semicolon (“;”). On UNIX platforms the separator is a colon (“:”). Ben Abdallah Helmi Architect en 22 J2EE
  23. 23. 15. What happens when you try to compile and run the following code? public class Q15 { static String s; public static void main(String[] args) { System.out.println(“>>” + s + “<<”); } } A. The code does not compile B. The code compiles, and prints out >><< C. The code compiles, and prints out >>null<< Ben Abdallah Helmi Architect en 23 J2EE
  24. 24. 15. C. The code compiles without error. At static initialization time, s is initialized to null (and not to a reference to an empty string, as suggested by C). Ben Abdallah Helmi Architect en 24 J2EE
  25. 25. Understanding Package-Derived Classes • Exam Objective 5.3 Describe the purpose and types of classes for the following Java packages: java.awt, javax.swing,,, java.util. 25
  26. 26. These include packages for Java utilities, basic input/output, networking, AWT and Swing. • • • • • Java Utilities API Java Basic Input/Output API Java Networking API Java Abstract Window Toolkit API Java Swing API 26
  27. 27. Java Utilities API 27
  28. 28. 28
  29. 29. Java Basic Input/Output API 29
  30. 30. 30
  31. 31. 31
  32. 32. Reader and Writer class hierarchy 32
  33. 33. Various classes of the Networking API 33
  34. 34. Java Abstract Window Toolkit API 34
  35. 35. Java Swing API • The Java Swing API is contained in the package javax.swing. This API provides functionality for creating lightweight (pure-Java) containers and components. • The Swing API superseded the AWT API. Many of the new classes were simply prefaced with the addition of “J” in contrast to the legacy AWT component equivalent. 35
  36. 36. 36
  37. 37. 37
  38. 38. 38
  39. 39. • Be familiar with the package prefixes java and javax. The prefix java is commonly used for the core packages. • The prefix javax is commonly used for packages comprised of Java standard extensions. Take special notice of the prefix usage in the AWT and Swing APIs: java.awt and javax.swing. 39
  40. 40. 40
  41. 41. Compiling and Interpreting Java Code • Exam Objective 5.2 Demonstrate the proper use of the “javac” command (including the command-line options: -d and –classpath ) and demonstrate the proper use of the “java” command (including the command-line options: -classpath, -D and –version ). 41
  42. 42. Compiling with javac • javac [options] [source files] • javac -help • javac -classpath com:. -g • Whenever you specify multiple options and/or files they should be separated by spaces. 42
  43. 43. Compiling with -d • By default, the compiler puts a .class file in the same directory as the .java source file > This is fine for very small projects • The -d option lets you tell the compiler in which directory to put the .class file(s) it generates (d is for destination) myProject | |--source || | |-- | |-- classes | |-- cd myProject javac -d classes source/ 43
  44. 44. myProject | |--source | | | |--com | | | |--wickedlysmart | | | | | |--classes | | • In this case, the compiler will build two directories called com and com/wickedlysmart in order to put the resulting MyClass.class file into the correct package directory : 44
  45. 45. • The last thing about -d that you'll need to know for the exam is that if the destination directory you specify doesn't exist, you'll get a compiler error. • If, in the previous example, the classes directory did NOT exist, the compiler would say something like: • java:5: error while writing MyClass: classes/MyClass.class (No such file or directory) 45
  46. 46. Launching Applications with java • In Chapter 5 we talked about the assertion mechanism and when you might use flags such as -ea or -da when launching an application. • java [options] class [args] java -DmyProp=myValue MyClass x 1 • Sparing the details for later, this command can be read as "Create a system property called myProp and set its value to myValue. Then launch the file named MyClass. • class and send it two String arguments whose values are x and 1." 46
  47. 47. Using System Properties If this file is compiled and invoked as follows: import java.util.*; java -DcmdProp=cmdVal TestProps public class TestProps { public static void main(String[] args) { You'll get something like this: ... Properties p = OS X System.getProperties(); myProp=myValue p.setProperty("myProp", "myValue"); ... p.list(System.out); java.specification.vendor=Sun Microsystems Inc. } user.language=en java.version=1.5.0_02 } ... cmdProp=cmdVal ... 47
  48. 48. • When using the -D option, if your value contains white space the entire value should be placed in quotes like this: • java -DcmdProp="cmdVal take 2" TestProps 48
  49. 49. Handling Command-Line Arguments public class CmdArgs { compiled and then invoked as follows public static void main(String[] java CmdArgs x 1 args) { the output will be int x = 0; 0 element = x for(String s : args) 1 element = 1 System.out.println(x++ + " element = " + s); } } The following are all legal declarations for main(): static public void main(String[] args) public static void main(String... x) static public void main(String bang_a_gong[]) 49
  50. 50. Searching for Other Classes Both java and javac use the same basic search algorithm: 1. They both have the same list of places (directories) they search, to look for classes. 2. They both search through this list of directories in the same order. 3. As soon as they find the class they're looking for, they stop searching for that class. In the case that their search lists contain two or more files with the same name, the first file found will be the file that is used. 4. The first place they look is in the directories that contain the classes that come standard with J2SE. 50
  51. 51. 5. The second place they look is in the directories defined by classpaths. 6. Classpaths should be thought of as "class search paths." They are lists of directories in which classes might be found. 7. There are two places where classpaths can be declared: > A classpath can be declared as an operating system environment variable. The classpath declared here is used by default, whenever java or javac are invoked. > A classpath can be declared as a command-line option for either java or javac. Classpaths declared as command-line options override the classpath declared as an environment variable, but they persist only for the length of the invocation. 51
  52. 52. Declaring and Using Classpaths • -classpath /com/foo/acct:/com/foo • specifies two directories in which classes can be found: /com/foo/acct and /com/foo • the java and javac commands don't search the current directory by default. You must tell them to search there. : . • -classpath /com/foo/acct /com/foo: 52
  53. 53. It's also important to remember that classpaths are searched from left to right. •-classpath /com:/foo:. •is not the same as •-classpath .:/foo:/com • Finally, the java command allows you to abbreviate classpath with -cp 53
  54. 54. Packages and Searching import com.wickedlysmart.Utils; class TestClass { void doStuff() { Utils u = new Utils(); // simple name u.doX("arg1", "arg2"); com.wickedlysmart.Date d = new com.wickedlysmart.Date(); // full name d.getMonth("Oct"); } } 54
  55. 55. • On Windows systems, classpath directories are delimited with backward slashes, and paths are delimited with semicolons: -classpath .;dir_aclasses_a;dir_bclasses_b • On POSIX-based systems, classpath directories are delimited with forward slashes and paths are delimited with colons: • -classpath .:/dir_a/classes_a/:/dir_b/classes_b/ Again, the period represents the present (or current) working directory. 55
  56. 56. Interpreting Your Bytecode with the -D Option • java -D<name>=<value> class 56
  57. 57. Retrieving the Version of the Interpreter with the -version Option 57
  58. 58. • Check out the other JDK utilities at your disposal. You can find them in the bin directory of your JDK. JConsole in particular is a valuable GUI-based tool that is used to monitor and manage Java applications. • Among the many features, JConsole allows for viewing memory and thread usages. JConsole was released with J2SE 5.0. 58
  59. 59. Compiling and Interpreting Java Code • The Java compiler is invoked with the javac[.exe] command. • The .exe extension is optional on Microsoft Windows machines and is not present on UNIX-like systems. • The compiler’s -d command-line option defines where compiled class files should be placed. • The compiler’s -d command-line option will include the package location if the class has been declared with a package statement. • The compiler’s -classpath command-line option defines directory paths in search of classes. • The Java interpreter is invoked with the java[.exe] command. • The interpreter’s -classpath switch defines directory paths to use at runtime. • The interpreter’s -D command-line option allows for the setting of system property values. • The interpreter’s syntax for the -D command-line option is -Dproperty=value. • The interpreter’s -version command-line option is used to return the version of the JVM and exit. 59
  60. 60. 60
  61. 61. 61
  62. 62. 62
  63. 63. 63
  64. 64. 64
  65. 65. 65
  66. 66. 66
  67. 67. 67
  68. 68. 68
  69. 69. 69
  70. 70. 70
  71. 71. 71
  72. 72. 72