Packages in Java

Packages are used in Java for organizing your class files. It is similar to folders to organize your files within your file system. You can put related class files together in one package. Java groups predefined classes into different packages like java.lang, java.util, java.io etc.

When no package is specified, the class is said to be in the default package, which is not a good programming practice. 

 

Package statement

To add your class to a package, you need to add a package structure definition to your class, compile to generate class file and then place your class file in a folder structure corresponding to your package definition.

You can write a package statement within your class using the package keyword:

package com.javajee.example;

 

Example 1

Example Code:

package com.javjee.example;

public class HelloWorld {

  public static void main(String[] args)

  {

    System.out.println("Hello World");

  }

}

Save this class in a file HelloWorld.java.

You can compile this using the javac command as:

javac HelloWorld.java

You should see HelloWorld.class inside if the compilation went well. However, to execute the .class file, you need to place the class file in a folder structure corresponding to the package definition. So, if the package definition is 'package com.javjee.example', then the folder structure would be com\javajee\example.

From the working folder (say java programs), create a folder structure as com\javajee\example and place the file HelloWorld.java in the example folder.

Now go to the working folder (javaprograms in our case) from command prompt and run the below command:

java com.javajee.example.HelloWorld

You should see the output as "Hello World".

 

Common errors

Error 1: If you don't put the class file in the correct folder structure and try to run the above command, you will get an exception like below:

Error: Could not find or load main class com.javajee.example.HelloWorld

If you see this error, make sure you have put your HelloWorld.class under javaprograms\com\javajee\example and is running the statement from javaprograms folder.

 

Error 2: If you try to run without the qualifier (e.g. java HelloWorld instead of java com.javajee.example.HelloWorld), you will get an error like below:

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name: com/javjee/example/HelloWorld)
        at java.lang.ClassLoader.defineClass1(Native Method)
        ...

If you see this error, make sure you have put the fully qualified name of the class when using java command.

 

Using - d option

Instead of copying the .class file to the destination folder (com/javjee/example), you can use javac command with the -d option to create the folder structure and copy the .class file there. For this, compile the source code as:

javac -d . HelloWorld.java

-d option should be follwed by a path. Dot (.) reprecent current directory.

If compilation is successful, this will create a folder structure as com/javjee/example under current directory (javaprograms) and the class file (HelloWorld.class) is copied to com/javajee/example. Now you can run the java command from the parent folder (javaprograms).

 

Using classpath

If you are executing from some other folder than the parent folder (javaprograms), then you can specify the parent folder in the classpath and run the java command.

java -classpath C:\javaprograms com.javajee.example.HelloWorld

You can give relative or absolute path.

 

Few valid and invalid cases

Consider that the class HelloWorld exists in the /apps/com/javajee/example directory. Assume the CLASSPATH environment variable is set to "." (current directory).

 

Valid executions:

$ java com.javajee.example.HelloWorld if run from the /apps directory

$ java -classpath /apps com.javajee.example.HelloWorld if run from any other directory

 

Invalid executions:

$ java HelloWorld if run from anywhere.

Remember the rule above that you need to specify the fully qualified name of the class from outside the package.

$ java com.javajee.example.HelloWorld if run from the /apps/com/javajee/example directory

Here, we are executing from example directory and hence java will look for a directory corresponding to the qualified name as com/javajee/example/HelloWorld.class from the current directory (application directory).

 

Important points to remember

  1. A package statement should be the first java line in a java file (if present); only comments and whitespaces are allowed before that.

  2. There can be at most one package statement in a java file.

  3. Java's built in packages start with java keyword (e.g. java.io.*, java.lang.*). User defined package are prohibitted to start with java. 

  4. To execute a class within a package from command line, you need to use its fully qualified name (e.g. java com.javajee.MyClass). For compilation, you just need to specify the file name to javac command without a fully qualified name.

  5. To access a class or method in another package, you need to either use the fully qualified name of the file (e.g. com.javajee.example.HelloWorld) or you can use import statements

Comments

Get back for any doubts.

Was it useful?

hi

very good explanation on packages .

but why we use classpath if we set path variable and class contain in current dir. can we omit classpath law.

thanks

ajay

Was it useful?

Both of them are for different purposes. Path is used by your operating system like Windows or Linux to find the location of javac or java. Class path is used by Java to find where the classes are present. By default current folder is added to class path. So if your classes are in any other location you need to set them. Please refer to http://javajee.com/path-vs-classpath for more details.

Was it useful?

instead of using your example terms  to explain ,you could replace it with common terms like packagename or classname ,it will be crystal clear to understand the concept  

according to me ,we could replace example program with much better one and the explanation is little bit messy i feel so ....bcoz if a beginner tries to work it out , it would be difficult for  them incase  it could be better .

 

Was it useful?

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)