Welcome!

Java Authors: Pat Romanski, Liz McMillan, Carmen Gonzalez, Elizabeth White, Trevor Parsons

Related Topics: Java, XML, SOA & WOA, Websphere, Weblogic, Linux, Virtualization, IT SOLUTIONS GUIDE, Eclipse

Java: Article

Java Basics: Lesson 11, Java Packages and Imports (Live Video Education)

Lesson 11 in the Hugely Popular "Java Basics" Series by JDJ Editorial Board Member Yakov Fain

Java comes with thousands of classes that are organized in packages (similar to files and directories on you disk). Some packages include classes responsible for drawing, while other have classes for the Internet access, and so on. For example the class String is located in the package called java.lang, and the fully qualified name of this class is java.lang.String.

The Java compiler only knows where to find classes that are located in the package java.lang, but there are many other packages with useful classes, and it's your responsibility to let the compiler know where the classes that are used in your program live. For example, the package java.io contains classes responsible for input/output operations, while most of the Swing classes live in the following two packages:


javax.swing
javax.swing.event

It would be annoying to write a full class name every time you use it, for example:

javax.swing.JButton myButton = new javax.swing.JButton();
javax.swing.JFrame myFrame = new javax.swing.JFrame();

To avoid this you can use import statements right above the class declaration line, for example:

import javax.swing.JFrame;
import javax.swing.JButton;

class Calculator{
JButton myButton = new JButton();
JFrame myFrame = new JFrame();
}

These import statements allow you to use short class names like JFrame or JButton, and the Java compiler will know where to find them. Please note, that nothing is actually imported into your program: it's just a name resolution mechanism that helps the compiler to find classes and make your program more readable. If your need to use several classes from the same package, you do not have to list each of them in the import statement, just use the wild card. In the following example the asterisk (*) makes all classes from the package javax.swing visible to your program:

import javax.swing.*;

Still, it's better to use separate import statements, so you can see clearly which classes are imported from a particular package.

When programmers work on large projects that have lots of classes, they usually organize them in different packages. For example, one package can have all classes that display graphical windows, while another can contain data access classes.

Let's create a new project called PingPong in the Eclipse IDE. This project will have classes in two packages: screens and engine. Now create a new class PingPongTable and enter the word screens in the field Package:  

Press the button Finish and Eclipse will generate the code that will include the line with the package name.

package screens;

public class PingPongTable {

public static void main(String[] args) {
}
}

By the way, if your class includes the line with the keyword package, you are not allowed to write anything but the program comments above this line.

Since each package is stored in a different folder on a disk, Eclipse creates the folder called screens and puts the file PinPongTable.java there. Check it out - there should be a folder c:\eclipse\workspace\PingPong\screens on your disk with files PingPongTable.java and PingPongTable.class.

Now create another class called PingPongEngine and enter the word engine as the package name. The PingPong project has two packages now:

Since our two classes are located in two different packages (and folders), the class PingPongTable won't see the class PingPongEngine unless you add the appropriate import statement.

package screens;

import engine.PingPongEngine;

public class PingPongTable {

public static void main(String[] args) {
  PingPongEngine gameEngine = new
      PingPongEngine();
}
}

Java packages not only help better organize your classes, but also can be used to hide their classes from the "foreigners" living in other packages. In Java you can use public, private and protected keywords to specify the access level to a particular method or a class. But if you do not use any of these keywords in the method or class declaration, you'll be able to access them only from the classes located in the same package. We've discussed access levels briefly in Lesson 3 of this series.

More Stories By Yakov Fain

Yakov Fain is a co-founder of two software companies: Farata Systems and SuranceBay. He authored several technical books and lots of articles on software development. Yakov is Java Champion (https://java-champions.java.net). He leads leads Princeton Java Users Group. Two of Yakov's books will go in print this year: "Enterprise Web Development" (O'Reilly) and "Java For Kids" (No Starch Press).

Comments (5) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Howard N-H 04/13/05 02:53:31 PM EDT

I'm glad you mentioned the use of interfaces as repositories of constants. While it may not be recommended in the strict sense of why interfaces exist, I've used this technique for years on large projects as a good way of organizing and reusing constants.

static imports 04/12/05 06:23:33 AM EDT

So you can use wildcards in the import? Can you use static import for static classes?

Java Basics series 04/12/05 06:12:49 AM EDT

Will the other 10 lessons be on SYS-CON.TV?

Java Live 04/11/05 10:17:40 AM EDT

Is it Yakov Fain who is speaking at the moment? A live Java lesson - cool!

sundeep 04/11/05 06:43:13 AM EDT

I used this lesson in conjunction with the last one, lesson ten on eclipse IDE and it really helped me

@ThingsExpo Stories
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., showed what is needed to leverage the IoT to transform your business. He discussed opportunities and challenges ahead for the IoT from a market and technical point of vie...
IoT is still a vague buzzword for many people. In his session at @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, discussed the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. He also discussed how IoT is perceived by investors and how venture capitalist access this space. Other topics discussed were barriers to success, what is new, what is old, and what the future may hold. Mike Kavis is Vice President & Principal Cloud Architect at Cloud Technology Pa...
The Internet of Things (IoT) is rapidly in the process of breaking from its heretofore relatively obscure enterprise applications (such as plant floor control and supply chain management) and going mainstream into the consumer space. More and more creative folks are interconnecting everyday products such as household items, mobile devices, appliances and cars, and unleashing new and imaginative scenarios. We are seeing a lot of excitement around applications in home automation, personal fitness, and in-car entertainment and this excitement will bleed into other areas. On the commercial side, m...
Dale Kim is the Director of Industry Solutions at MapR. His background includes a variety of technical and management roles at information technology companies. While his experience includes work with relational databases, much of his career pertains to non-relational data in the areas of search, content management, and NoSQL, and includes senior roles in technical marketing, sales engineering, and support engineering. Dale holds an MBA from Santa Clara University, and a BA in Computer Science from the University of California, Berkeley.
The Industrial Internet revolution is now underway, enabled by connected machines and billions of devices that communicate and collaborate. The massive amounts of Big Data requiring real-time analysis is flooding legacy IT systems and giving way to cloud environments that can handle the unpredictable workloads. Yet many barriers remain until we can fully realize the opportunities and benefits from the convergence of machines and devices with Big Data and the cloud, including interoperability, data security and privacy.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Performance is the intersection of power, agility, control, and choice. If you value performance, and more specifically consistent performance, you need to look beyond simple virtualized compute. Many factors need to be considered to create a truly performant environment. In his General Session at 15th Cloud Expo, Harold Hannon, Sr. Software Architect at SoftLayer, discussed how to take advantage of a multitude of compute options and platform features to make cloud the cornerstone of your online presence.
SYS-CON Media announced that Splunk, a provider of the leading software platform for real-time Operational Intelligence, has launched an ad campaign on Big Data Journal. Splunk software and cloud services enable organizations to search, monitor, analyze and visualize machine-generated big data coming from websites, applications, servers, networks, sensors and mobile devices. The ads focus on delivering ROI - how improved uptime delivered $6M in annual ROI, improving customer operations by mining large volumes of unstructured data, and how data tracking delivers uptime when it matters most.
In this Women in Technology Power Panel at 15th Cloud Expo, moderated by Anne Plese, Senior Consultant, Cloud Product Marketing at Verizon Enterprise, Esmeralda Swartz, CMO at MetraTech; Evelyn de Souza, Data Privacy and Compliance Strategy Leader at Cisco Systems; Seema Jethani, Director of Product Management at Basho Technologies; Victoria Livschitz, CEO of Qubell Inc.; Anne Hungate, Senior Director of Software Quality at DIRECTV, discussed what path they took to find their spot within the technology industry and how do they see opportunities for other women in their area of expertise.
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, discussed how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money!
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, examined three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics is e...
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges. In his session at @ThingsExpo, Jeff Kaplan, Managing Director of THINKstrategies, will examine why IT must finally fulfill its role in support of its SBUs or face a new round of...
The BPM world is going through some evolution or changes where traditional business process management solutions really have nowhere to go in terms of development of the road map. In this demo at 15th Cloud Expo, Kyle Hansen, Director of Professional Services at AgilePoint, shows AgilePoint’s unique approach to dealing with this market circumstance by developing a rapid application composition or development framework.

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

Advanced Persistent Threats (APTs) are increasing at an unprecedented rate. The threat landscape of today is drastically different than just a few years ago. Attacks are much more organized and sophisticated. They are harder to detect and even harder to anticipate. In the foreseeable future it's going to get a whole lot harder. Everything you know today will change. Keeping up with this changing landscape is already a daunting task. Your organization needs to use the latest tools, methods and expertise to guard against those threats. But will that be enough? In the foreseeable future attacks w...