08_references_and_packages
Pointers vs java references
Pointer arithmetic is not allowed in java.
Reference holds internal representation of address
Array handling
Array of primitive types
Array of References
Packages
What is a package ?
Collection of functionally similar classes & interfaces.
Why packages?
To group functionally similar classes together.
Avoids name space collision
Finer control over access specifiers.
About Packages
Creation : package statement has to be placed as the 1st statement in Java source.
Package names are mapped to folder names.
A
class must exist in folderp1
.
For simplicity create folder p1 under
src
folder & compile fromsrc
From
src
folder, run the commandjavac will automatically create the sub-folder
p1
under thebin
folder & place A.class withinp1
.
NOTE: Its not mandatory to create java sources(.java) under package named folder. BUT its mandatory to store packged compiled classes(.class) under package named folders.
Earlier half is just maintained as convenience so that javac can then automatically detect dependencies & compile classes.
To run the packaged classes from any folder, you must set Java specific environment variables : classpath
classpath is the Java's only environment variable
Class path is mainly used by JRE's classloader, to locate & load the classes.
Class loader will try to locate the classes from current folder, if not found it will refer to classpath entries and try to resolve & load Java classes.
What should be value of classpath ?
Must be set to top of packged hierarchy (i.e .class eg : bin)
OR better, set it in environment variables.
Rules about packages
If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file.
If there are no package or import statements, the class declaration must be the first line in the source code file.
import and package statements apply to all classes within a source code file.
In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports.
Note: Normally package names are all lower cased.
For installing open JDK, setting path and setting java home variable in Ubuntu. Refer this.
Linux/Mac classpath setting
Open the terminal window
echo ${CLASSPATH}
export CLASSPATH=.:/home/user/day2/bin (folder name pointing to top of the pkged hierarchy).
Another option can be, run the command
java -cp /home/user/day2/bin p1.Test
Last updated