SlideShare a Scribd company logo
Packaging, Compiling, and Interpreting
Java Code

1
Session Objectives

• Understanding Packages
• Understanding Package-Derived Classes
• Compiling and Interpreting Java Code
• Q&A Self Test

2
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
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.
•
4
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
5
J2EE
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
4. D. Package declaration must come first, followed by
imports, followed by class/interface/enum definitions.

Ben Abdallah Helmi Architect en
7
J2EE
8
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
• 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
The import Statement

11
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
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
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
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
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
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
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
13. A, C. The import keyword may optionally be
followed by the static keyword.

Ben Abdallah Helmi Architect en
19
J2EE
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
14. B, C. You may statically import method and field
names.

Ben Abdallah Helmi Architect en
21
J2EE
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
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
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
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.

25
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
Java Utilities API

27
28
Java Basic Input/Output API

29
30
31
Reader and Writer class hierarchy

32
Various classes of the Networking API

33
Java Abstract Window Toolkit API

34
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
37
38
• 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
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
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.
42
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 myProject
javac -d classes source/MyClass.java

43
myProject
|
|--source
|
|
|
|--com
|
|
|
|--wickedlysmart
|
|
|
|--MyClass.java
|
|--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
• 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
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
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.name=Mac 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
• 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
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
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
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
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
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
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
• 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
Interpreting Your Bytecode with the -D
Option
• java -D<name>=<value> class

56
Retrieving the Version of the Interpreter
with the -version Option

57
• 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
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
61
62
63
64
65
66
67
68
69
70
71
72

More Related Content

PPT
Java non access modifiers
Srinivas Reddy
 
PPT
Lecture 3 java basics
the_wumberlog
 
PDF
C progrmming
Shivam Singhal
 
PPTX
java: basics, user input, data type, constructor
Shivam Singhal
 
PDF
Unit VI
Bhavsingh Maloth
 
PDF
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
JAXLondon2014
 
PPTX
Java
Sneha Mudraje
 
DOCX
Unit2 java
mrecedu
 
Java non access modifiers
Srinivas Reddy
 
Lecture 3 java basics
the_wumberlog
 
C progrmming
Shivam Singhal
 
java: basics, user input, data type, constructor
Shivam Singhal
 
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
JAXLondon2014
 
Unit2 java
mrecedu
 

What's hot (20)

ZIP
Introduction to the Java(TM) Advanced Imaging API
white paper
 
PDF
web programming UNIT VIII python by Bhavsingh Maloth
Bhavsingh Maloth
 
PDF
THE CLR AND THE .NET FRAMEWORK, C#
MANOJ BURI
 
PPTX
Skillwise Elementary Java Programming
Skillwise Group
 
PPTX
java training in jaipur|java training|core java training|java training compa...
infojaipurinfo Jaipur
 
PPT
web programming Unit VI PPT by Bhavsingh Maloth
Bhavsingh Maloth
 
PDF
Java SE 8 library design
Stephen Colebourne
 
PPTX
Introduction to computer science
umardanjumamaiwada
 
PPTX
Core Java introduction | Basics | free course
Kernel Training
 
PDF
Core Java
Prakash Dimmita
 
PPTX
Introduction to java
Kalai Selvi
 
PPTX
Improved Developer Productivity In JDK8
Simon Ritter
 
PDF
Core Java Tutorial
eMexo Technologies
 
PDF
Basic Java Programming
Math-Circle
 
PPTX
Object oriented programming-with_java
Hoang Nguyen
 
PPT
Introduction to llvm
Tao He
 
PDF
Unit 5 quesn b ans5
Sowri Rajan
 
PDF
Core java part1
VenkataBolagani
 
PPT
JAVA BASICS
VEERA RAGAVAN
 
PPT
Savitch Ch 12
Terry Yoast
 
Introduction to the Java(TM) Advanced Imaging API
white paper
 
web programming UNIT VIII python by Bhavsingh Maloth
Bhavsingh Maloth
 
THE CLR AND THE .NET FRAMEWORK, C#
MANOJ BURI
 
Skillwise Elementary Java Programming
Skillwise Group
 
java training in jaipur|java training|core java training|java training compa...
infojaipurinfo Jaipur
 
web programming Unit VI PPT by Bhavsingh Maloth
Bhavsingh Maloth
 
Java SE 8 library design
Stephen Colebourne
 
Introduction to computer science
umardanjumamaiwada
 
Core Java introduction | Basics | free course
Kernel Training
 
Core Java
Prakash Dimmita
 
Introduction to java
Kalai Selvi
 
Improved Developer Productivity In JDK8
Simon Ritter
 
Core Java Tutorial
eMexo Technologies
 
Basic Java Programming
Math-Circle
 
Object oriented programming-with_java
Hoang Nguyen
 
Introduction to llvm
Tao He
 
Unit 5 quesn b ans5
Sowri Rajan
 
Core java part1
VenkataBolagani
 
JAVA BASICS
VEERA RAGAVAN
 
Savitch Ch 12
Terry Yoast
 
Ad

Viewers also liked (19)

PPTX
Chapter 11:Understanding Client-Side Technologies
It Academy
 
PPT
Dunya gokyuzu
Emirali Karagözlü
 
PPTX
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
It Academy
 
PPTX
chap 7 : Threads (scjp/ocjp)
It Academy
 
PPTX
Chapter 6:Working with Classes and Their Relationships
It Academy
 
PPTX
chap 2 : Operators and Assignments (scjp/ocjp)
It Academy
 
PPTX
Chapter8:Understanding Polymorphism
It Academy
 
PPTX
Chap 9 : I/O and Streams (scjp/ocjp)
It Academy
 
PPTX
Chapter 12:Understanding Server-Side Technologies
It Academy
 
PPTX
Chapter 3
It Academy
 
PPTX
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
It Academy
 
PPTX
Chapter 9:Representing Object-Oriented Concepts with UML
It Academy
 
PPTX
Chapter 5:Understanding Variable Scope and Class Construction
It Academy
 
PPTX
3 boyutlu cisimler
Emirali Karagözlü
 
PPTX
chap4 : Converting and Casting (scjp/ocjp)
It Academy
 
PPTX
Chapter 10:Understanding Java Related Platforms and Integration Technologies
It Academy
 
PPTX
Chapter 3 : Programming with Java Operators and Strings
It Academy
 
PPTX
Chapter 7:Understanding Class Inheritance
It Academy
 
PPTX
Chapter 3:Programming with Java Operators and Strings
It Academy
 
Chapter 11:Understanding Client-Side Technologies
It Academy
 
Dunya gokyuzu
Emirali Karagözlü
 
chap4 ; Flow Control, Assertions, and Exception Handling (scjp/ocjp)
It Academy
 
chap 7 : Threads (scjp/ocjp)
It Academy
 
Chapter 6:Working with Classes and Their Relationships
It Academy
 
chap 2 : Operators and Assignments (scjp/ocjp)
It Academy
 
Chapter8:Understanding Polymorphism
It Academy
 
Chap 9 : I/O and Streams (scjp/ocjp)
It Academy
 
Chapter 12:Understanding Server-Side Technologies
It Academy
 
Chapter 3
It Academy
 
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
It Academy
 
Chapter 9:Representing Object-Oriented Concepts with UML
It Academy
 
Chapter 5:Understanding Variable Scope and Class Construction
It Academy
 
3 boyutlu cisimler
Emirali Karagözlü
 
chap4 : Converting and Casting (scjp/ocjp)
It Academy
 
Chapter 10:Understanding Java Related Platforms and Integration Technologies
It Academy
 
Chapter 3 : Programming with Java Operators and Strings
It Academy
 
Chapter 7:Understanding Class Inheritance
It Academy
 
Chapter 3:Programming with Java Operators and Strings
It Academy
 
Ad

Similar to Chapter 1 : (20)

PDF
JAVA 2-studenttrreadexeceptionpackages.pdf
msurfudeen6681
 
PPT
20-packages-jar.ppt
bharanidaranramaling
 
PPT
9 cm604.26
myrajendra
 
PPTX
Packages,static,this keyword in java
Vishnu Suresh
 
PPTX
Package in Java
lalithambiga kamaraj
 
PPTX
Chap1 language fondamentale of java ( scjp /ocjp)
It Academy
 
PPTX
java package in java.. in java packages.
ArunPatrickK1
 
PPTX
java package java package in java packages
ArunPatrick2
 
PDF
Class notes(week 7) on packages
Kuntal Bhowmick
 
PPT
Packages(9 cm604.26)
myrajendra
 
PPTX
Packages in java
Elizabeth alexander
 
PPTX
packages in java object oriented programming
vamsiKrishnasai3
 
PPTX
java interface and packages
VINOTH R
 
PPTX
chap 10 : Development (scjp/ocjp)
It Academy
 
PPT
7.Packages and Interfaces(MB).ppt .
happycocoman
 
DOCX
Class notes(week 7) on packages
Kuntal Bhowmick
 
PPTX
OCA JAVA - 1 Packages and Class Structure
Fernando Gil
 
PPTX
Introduction to package in java
Prognoz Technologies Pvt. Ltd.
 
PPTX
Java package
CS_GDRCST
 
PPTX
javapackage,try,cthrow,finallytch,-160518085421 (1).pptx
ArunPatrick2
 
JAVA 2-studenttrreadexeceptionpackages.pdf
msurfudeen6681
 
20-packages-jar.ppt
bharanidaranramaling
 
9 cm604.26
myrajendra
 
Packages,static,this keyword in java
Vishnu Suresh
 
Package in Java
lalithambiga kamaraj
 
Chap1 language fondamentale of java ( scjp /ocjp)
It Academy
 
java package in java.. in java packages.
ArunPatrickK1
 
java package java package in java packages
ArunPatrick2
 
Class notes(week 7) on packages
Kuntal Bhowmick
 
Packages(9 cm604.26)
myrajendra
 
Packages in java
Elizabeth alexander
 
packages in java object oriented programming
vamsiKrishnasai3
 
java interface and packages
VINOTH R
 
chap 10 : Development (scjp/ocjp)
It Academy
 
7.Packages and Interfaces(MB).ppt .
happycocoman
 
Class notes(week 7) on packages
Kuntal Bhowmick
 
OCA JAVA - 1 Packages and Class Structure
Fernando Gil
 
Introduction to package in java
Prognoz Technologies Pvt. Ltd.
 
Java package
CS_GDRCST
 
javapackage,try,cthrow,finallytch,-160518085421 (1).pptx
ArunPatrick2
 

Recently uploaded (20)

PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
 
PDF
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Doc9.....................................
SofiaCollazos
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PDF
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
DOCX
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
 
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Doc9.....................................
SofiaCollazos
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
Software Development Company | KodekX
KodekX
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 

Chapter 1 :

  • 1. Packaging, Compiling, and Interpreting Java Code 1
  • 2. Session Objectives • Understanding Packages • Understanding Package-Derived Classes • Compiling and Interpreting Java Code • Q&A Self Test 2
  • 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. 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. • 4
  • 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 5 J2EE
  • 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. 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
  • 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. • 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
  • 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. 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. 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. 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. 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. 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. 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. 13. A, C. The import keyword may optionally be followed by the static keyword. Ben Abdallah Helmi Architect en 19 J2EE
  • 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. 14. B, C. You may statically import method and field names. Ben Abdallah Helmi Architect en 21 J2EE
  • 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. 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. 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. 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. 25
  • 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
  • 28. 28
  • 30. 30
  • 31. 31
  • 32. Reader and Writer class hierarchy 32
  • 33. Various classes of the Networking API 33
  • 34. Java Abstract Window Toolkit API 34
  • 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
  • 37. 37
  • 38. 38
  • 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
  • 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. 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. 42
  • 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 myProject javac -d classes source/MyClass.java 43
  • 44. myProject | |--source | | | |--com | | | |--wickedlysmart | | | |--MyClass.java | |--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. • 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. 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. 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.name=Mac 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. • 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. 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. 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. 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. 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. 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. 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. • 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. Interpreting Your Bytecode with the -D Option • java -D<name>=<value> class 56
  • 57. Retrieving the Version of the Interpreter with the -version Option 57
  • 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. 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
  • 61. 61
  • 62. 62
  • 63. 63
  • 64. 64
  • 65. 65
  • 66. 66
  • 67. 67
  • 68. 68
  • 69. 69
  • 70. 70
  • 71. 71
  • 72. 72