Top Banner
1 Packaging, Compiling, and Interpreting Java Code
72

Chapter 1 :

Dec 03, 2014

Download

Technology

It Academy

Understanding Packages

Understanding Package-Derived Classes

Compiling and Interpreting Java Code
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 1 :

1

Packaging, Compiling, and InterpretingJava Code

Page 2: Chapter 1 :

2

Session Objectives

• Understanding Packages

• Understanding Package-Derived Classes

• Compiling and Interpreting Java Code

•Q&A Self Test

Page 3: Chapter 1 :

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.

Page 4: Chapter 1 :

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 scjaexam.com 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.•

Page 5: Chapter 1 :

5

Source Files• All Java source files must end with the.java 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 J2EE

Page 6: Chapter 1 :

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/enumsB. Classes/interfaces/enums, imports, package declarationsC. Package declaration must come first; order for imports

and class/interfaces/enum definitionsis not significantD. 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 J2EE

Page 7: Chapter 1 :

7

4. D. Package declaration must come first, followed by imports, followed by class/interface/enum definitions.

Ben Abdallah Helmi Architect en J2EE

Page 8: Chapter 1 :

8

Page 9: Chapter 1 :

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.

Page 10: Chapter 1 :

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.

Page 11: Chapter 1 :

11

The import Statement

Page 12: Chapter 1 :

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

Page 13: Chapter 1 :

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 thanfloat ugs = Scales.poundsToMicrograms(lbs);

Ben Abdallah Helmi Architect en J2EE

Page 14: Chapter 1 :

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 J2EE

Page 15: Chapter 1 :

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 J2EE

Page 16: Chapter 1 :

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 J2EE

Page 17: Chapter 1 :

17

12. A.. Importing is strictly a compile-time function. It has no effect on class loading or on any other run-time function.

Ben Abdallah Helmi Architect en J2EE

Page 18: Chapter 1 :

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 J2EE

Page 19: Chapter 1 :

19

13. A, C. The import keyword may optionally be followed by the static keyword.

Ben Abdallah Helmi Architect en J2EE

Page 20: Chapter 1 :

20

14. Which of the following may be statically imported? (Choose all that apply.)

A. Package namesB. Static method namesC. Static field namesD. Method-local variable names

Ben Abdallah Helmi Architect en J2EE

Page 21: Chapter 1 :

21

14. B, C. You may statically import method and field names.

Ben Abdallah Helmi Architect en J2EE

Page 22: Chapter 1 :

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 sgsware\sphinx\Domain.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

J2EE

Page 23: Chapter 1 :

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 compileB. The code compiles, and prints out >><<C. The code compiles, and prints out >>null<<Ben Abdallah Helmi Architect en

J2EE

Page 24: Chapter 1 :

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 J2EE

Page 25: Chapter 1 :

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.io, java.net, java.util.

Page 26: Chapter 1 :

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

Page 27: Chapter 1 :

27

Java Utilities API

Page 28: Chapter 1 :

28

Page 29: Chapter 1 :

29

Java Basic Input/Output API

Page 30: Chapter 1 :

30

Page 31: Chapter 1 :

31

Page 32: Chapter 1 :

32

Reader and Writer class hierarchy

Page 33: Chapter 1 :

33

Various classes of the Networking API

Page 34: Chapter 1 :

34

Java Abstract Window Toolkit API

Page 35: Chapter 1 :

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.

Page 36: Chapter 1 :

36

Page 37: Chapter 1 :

37

Page 38: Chapter 1 :

38

Page 39: Chapter 1 :

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.

Page 40: Chapter 1 :

40

Page 41: Chapter 1 :

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 ).

Page 42: Chapter 1 :

42

Compiling with javac

• javac [options] [source files]• javac -help• javac -classpath com:. -g Foo.java

Bar.java•Whenever you specify multiple options

and/or files they should be separated by spaces.

Page 43: Chapter 1 :

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| || |-- MyClass.java||-- classes||--

cd myProjectjavac -d classes source/MyClass.java

Page 44: Chapter 1 :

44

• 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 :

myProject||--source| || |--com| || |--wickedlysmart| || |--MyClass.java||--classes| |

Page 45: Chapter 1 :

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)

Page 46: Chapter 1 :

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."

Page 47: Chapter 1 :

47

Using System Properties

import java.util.*;public class TestProps {public static void main(String[] args) {Properties p =

System.getProperties();p.setProperty("myProp", "myValue");p.list(System.out);}}

If this file is compiled and invoked as follows:

java -DcmdProp=cmdVal TestPropsYou'll get something like this:...

os.name=Mac OS X

myProp=myValue

...

java.specification.vendor=Sun Microsystems Inc.

user.language=en

java.version=1.5.0_02

...

cmdProp=cmdVal

...

Page 48: Chapter 1 :

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

Page 49: Chapter 1 :

49

Handling Command-Line Arguments

public class CmdArgs {public static void main(String[]

args) {int x = 0;for(String s : args)System.out.println(x++ + "

element = " + s);}}

compiled and then invoked as followsjava CmdArgs x 1the output will be0 element = x1 element = 1

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[])

Page 50: Chapter 1 :

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.

Page 51: Chapter 1 :

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.

Page 52: Chapter 1 :

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:.

Page 53: Chapter 1 :

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

Page 54: Chapter 1 :

54

Packages and Searching

import com.wickedlysmart.Utils;class TestClass {void doStuff() {Utils u = new Utils(); // simple nameu.doX("arg1", "arg2");com.wickedlysmart.Date d =new com.wickedlysmart.Date(); // full named.getMonth("Oct");}}

Page 55: Chapter 1 :

55

• On Windows systems, classpath directories are delimited with backward slashes, and paths are delimited with semicolons:

-classpath .;\dir_a\classes_a\;\dir_b\classes_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.

Page 56: Chapter 1 :

56

Interpreting Your Bytecode with the -D Option

• java -D<name>=<value> class

Page 57: Chapter 1 :

57

Retrieving the Version of the Interpreterwith the -version Option

Page 58: Chapter 1 :

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.

Page 59: Chapter 1 :

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.

Page 60: Chapter 1 :

60

Page 61: Chapter 1 :

61

Page 62: Chapter 1 :

62

Page 63: Chapter 1 :

63

Page 64: Chapter 1 :

64

Page 65: Chapter 1 :

65

Page 66: Chapter 1 :

66

Page 67: Chapter 1 :

67

Page 68: Chapter 1 :

68

Page 69: Chapter 1 :

69

Page 70: Chapter 1 :

70

Page 71: Chapter 1 :

71

Page 72: Chapter 1 :

72