
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we define a package after the import statement in Java?
No, we cannot define a package after the import statement in Java. The compiler will throw an error if we try to insert a package after the import statement.
A package is a group of similar types of classes, interfaces, and sub-packages. To create a class inside a package, declare the package name in the first statement in our program.
Important! If you use the package statement in an online compiler, you may still get an error even if it is defined correctly. This is because many online compilers do not support custom package structures.
Example
In the following example, we define a package after the import statement, which is "incorrect". When the program is compiled, it will throw an error:
import java.lang.*; package test; public class PackageAfterImportTest { public static void main(String args[]) { System.out.println("Welcome to Tutorials Point !!!"); } }
The above program throws the following error:
PackageAfterImportTest.java:3: error: class, interface, or enum expected package test; ^ 1 error
Additionally, we will also see how to define a package correctly in Java.
Defining a Package in Java
The correct way to define a package in Java is to place the "package statement" at the very top of your Java file, before any import statements or class declarations.
Syntax
The following is the syntax to define a package in Java:
//defining a package package com.example.tp; //defining an import statement after package import java.util.Scanner; public class MyClass { // class code here }
Example
The following program demonstrates how to define a package correctly in Java:
package test; import java.lang.*; public class PackageAfterImportTest { public static void main(String args[]) { System.out.println("Welcome to Tutorials Point !!!"); } }
Following is the output of the above program:
Welcome to Tutorials Point !!!