Showing posts with label using packages in java. Show all posts
Showing posts with label using packages in java. Show all posts

Friday, 29 August 2025

Steps to create Packages in Java

 

Here are the steps to create a package in Java:


1. Define the Package

  • Use the package keyword at the very top of the Java file.
  • Example:
    package mypackage;
    

2. Organize Your Files

  • Create a sub directory in the current directory with a name that matches the package name.
  • For example, if your package is mypackage, create a folder named mypackage.

3. Write Your Java Class

  • Save your Java file inside the corresponding folder.
  • Example:
    package mypackage;
    
    public class MyClass {
        public void displayMessage() {
            System.out.println("Hello from MyClass in mypackage!");
        }
    }
    

4. Compile the Package

  • After saving the file, move to the parent directory by entering cd.. at the command prompt.
  • Navigate to the parent directory of the package folder in the terminal/command prompt.
  • Use the javac command to compile the file:
    javac mypackage/MyClass.java
    

5. Use the Package

  • To use the package in another Java file, import it using the import statement.
  • Example:
    import mypackage.MyClass;
    
    public class Main {
        public static void main(String[] args) {
            MyClass obj = new MyClass();
            obj.displayMessage();
        }
    }
    

Benefits of Using Packages

  • Organizes your code.
  • Avoids naming conflicts.
  • Provides access control.

Let me know if you'd like further clarification! 😊