Java Packages | |||
| |||
Java Packages & API A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:
Built-in Packages The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment. The library contains components for managing input, database programming, and much much more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/. The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package. To use a class or a package from the library, you need to use the
Import a Class If you find a class you want to use, for example, the
In the example above, To use the
Import a Package There are many packages to choose from. In the previous example, we used the To import a whole package, end the sentence with an asterisk sign (
User-defined Packages To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer:
MyPackageClass.java
Save the file as MyPackageClass.java, and compile it:
Then compile the package:
This forces the compiler to create the "mypack" package. The -d keyword specifies the destination for where to save the class file. You can use any directory name, like c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot sign ".", like in the example above. Note: The package name should be written in lower case to avoid conflict with class names.
When we compiled the package in the example above, a new folder was created, called "mypack". To run the MyPackageClass.java file, write the following:
The output will be:
Tags: Java Java Packages | |||
| |||
| |||
Login for comment |
OTHER POSTS IN THE SAME CATEGORYJava Servlet ExampleHow do I replace content that based on the HTML UI TemplateCreating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft WindowsDataset of California FoodbanksJava Tutorials associated with AP Computer Science AJava Inner ClassesJava PolymorphismJava Inheritance (Subclass and Superclass)Java Abstract Classes and MethodsJava Classes and ObjectsJava RecursionJava ScopeJava MethodsJava ArraysJava While Loop/Do While Loop/For Loop/For-Each Loop/Break/ContinueJava Switch StatementsJava Short Hand If...Else (Ternary Operator)Java If ... ElseJava MathJava VariablesJava CommentsThe Print() MethodJava Syntax |