Be ensure that the package folder mypackage and Main.class share the parent folder.

package mypackage;
public class Child {}

I presume that the Main class is created in default package.

public class Main {
   public static void main(String []args){
         mypackage.Child child=new mypackage.Child();
   }
}

and your directory structure should be:

main-directory/
              |
              |----/mypackage/
                            Child.class
              |
              | Main.class
              | Main.java
              | Child.java

and to launch/load the Main issue following command,

java Main

Answer from KV Prajapati on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_files.asp
Java Files
assert abstract boolean break byte case catch char class continue default do double else enum exports extends final finally float for if implements import instanceof int interface long module native new package private protected public return requires short static super switch synchronized this throw throws transient try var void volatile while Java String Methods
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 8 )
April 21, 2026 - If the file is recognized then the content type is returned. If the file is not recognized by any of the installed file type detectors then a system-default file type detector is invoked to guess the content type. A given invocation of the Java virtual machine maintains a system-wide list of file type detectors.
Discussions

netbeans 8 - How do i "import" a java file into another file - Stack Overflow
I'm currently having trouble with my program, what I'm trying to do is to "import" a file that contains my variables into my main Java file, so that it recognizes the variables without adding them ... More on stackoverflow.com
🌐 stackoverflow.com
[JAVA] When do I need to import classes, in Main file or class files?
Your Main file is a class file. See the "public class Main" bit? It doesn't even need to be named main- you can start your program from any class that has a method with the signature public static void main(String[] args). You could, for example, copy that main() method into your Planner file and then delete Main.java altogether. Things need to be imported where they are used. If you're using something in the class with the main method, then you import it there. If you're using it in a different class, you import it in the other class file. More on reddit.com
🌐 r/learnprogramming
4
1
October 23, 2017
How do I find the java command "import"?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
32
7
January 10, 2024
How To Import A Package From Another Directory
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
7
2
May 31, 2023
Top answer
1 of 2
2

A few things that you may want to try:

Make the variables public static if you only want one instance of them.

Instantiate your variables class Variables vars = new Variables(); and then call the variables from the instance vars.first_name = "First Name";

If you are using the instance method then i would suggest using Getters and Setters

This may also help you in understanding how to get the class variables better.

Doing it the static way:

    public class Main {

    public static void main(String[] args){
        Variables.first_name = "Hello, you.";
        System.out.println("first_name: " + Variables.first_name);
    }

    private static class Variables {

        private static Scanner input = new Scanner(System.in);

        public static String first_name;
        public static int age;
    }
}

Doing it the OOP way:

    public class Main {

    public static void main(String[] args) {
        Variables var = new Variables();

        var.setFirst_name("First Name Here");
        System.out.println(var.getFirst_name());
    }

    private static class Variables {

        private Scanner input = new Scanner(System.in);

        public String first_name;
        public int age;

        public String getFirst_name() {
            return first_name;
        }

        public void setFirst_name(String first_name) {
            this.first_name = first_name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}
2 of 2
1

You need to create an instance of Variables class:

public static void main(String[] args) {
    Variables variables = new Variables();
    System.out.println("Please enter your first name:");
    variables.first_name = variables.input.next();
    System.out.println("Hi " + variables.first_name + "!");
}
🌐
Rutgers CS
cs.rutgers.edu › courses › 111 › classes › fall_2011_tjang › texts › notes-java › language › 10basics › import.html
Java: Packages and Import
Java classes can be grouped together in packages. A package name is the same as the directory (folder) name which contains the .java files. You declare packages when you define your Java program, and you name the packages you want to use from other libraries in an import statement.
🌐
GeeksforGeeks
geeksforgeeks.org › java › file-class-in-java
Java File Class - GeeksforGeeks
November 3, 2025 - Example 1: Program to check if a file or directory physically exists or not. ... import java.io.File; // Displaying file property class CheckFileExist { public static void main(String[] args){ // Accept file name or directory name through // command line args String fname = args[0]; // pass the filename or directory name to File // object File f = new File(fname); // apply File class methods on File object System.out.println("File name :" + f.getName()); System.out.println("Path: " + f.getPath()); System.out.println("Absolute path:" + f.getAbsolutePath()); System.out.println("Parent:" + f.getParent()); System.out.println("Exists :" + f.exists()); if (f.exists()) { System.out.println("Is writable:" + f.canWrite()); System.out.println("Is readable" + f.canRead()); System.out.println("Is a directory:" + f.isDirectory()); System.out.println("File Size in bytes " + f.length()); } } }
Find elsewhere
🌐
Reddit
reddit.com › r/learnprogramming › [java] when do i need to import classes, in main file or class files?
r/learnprogramming on Reddit: [JAVA] When do I need to import classes, in Main file or class files?
October 23, 2017 -

So, I'm currently creating a planner as one of my first projects (just a simple console planner, tells you the date, who the owner is, and eventually the user will be able to input things on a list and read off the list.

I noticed when importing my code from IntellijIDE to Eclipse (Just wanted to try them both out so I'm giving Eclipse ago) that the IDE only flagged errors if I didn't import the needed classes in the Planner.java source file.

Here's some code so all this doesn't just sound like gibberish:

This is my Main file:

public class Main {

 public static void main(String[] args) {
	final String PLANNER_OWNER = Planner.getOwner();
	final String CURRENT_DATE = Planner.getCurrentDate();
	System.out.println("This planner belongs to " + PLANNER_OWNER + "\nToday is " + CURRENT_DATE);
	System.out.println("--------------------------------");
  }
	
} 

And currently my only Class is:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Scanner;
import java.util.Date;

public class Planner {

    private static Scanner scanner;
    public static final String getOwner() {
        System.out.println("Who owns this planner? ");
        scanner = new Scanner(System.in);
        String name = scanner.nextLine();
    return name;
 }

public static final String getCurrentDate() {
    Date date = new Date();
    DateFormat dateFormat = new SimpleDateFormat("EEEE");
    return  dateFormat.format(date);
 }
}    

So do I only need to import in my class file or is that bad practice? Also, if there's any other bad practices in this please let me know so I can not make a habit of them! This is the first thing I've built from a blank slate without tutorial help (besides documentation and already answered quora questions lol) So any advice would more than likely be extremely helpful!

p.s. if any of this is poorly formatted, or I use the wrong terminology for things I apologize it is both late and I'm a nooby at this stuff.

Edit: BTW this actually does work 100% as intended, it was simple but super fun to figure out

Also, here are screenshots of the code if you'd prefer to look at it with proper color coding Main.java Planner.java

🌐
DigitalOcean
digitalocean.com › community › tutorials › java-files-nio-files-class
Java Files - java.nio.file.Files Class | DigitalOcean
August 4, 2022 - Files class provides createFile(Path filePath, FileAttribute<?>… attrs) method to create file using specified Path. Let’s have a look at the below example program. package com.journaldev.examples; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Java Create file using Files class * * @author pankaj * */ public class FilesCreateFileExample { public static void main(String[] args) { //initialize Path object Path path = Paths.get("D:/data/file.txt"); //create file try { Path createdFilePath = Files.createFile(path); System.out.println("File Created at Path : "+createdFilePath); } catch (IOException e) { e.printStackTrace(); } } } Output of the above program is below: File Created at Path : D:\data\file.txt ·
🌐
DataCamp
datacamp.com › doc › java › import
import Keyword in Java: Usage & Examples
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming ... The import keyword in Java is used to bring other classes or entire packages into visibility within your current class.
🌐
W3Schools
w3schools.com › java › java_files_read.asp
Java Read Files
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A ... In the previous chapters, you learned how to create and write to a file. In the following example, we use the Scanner class to read the contents of the text file we created in the previous chapter: import java.io.File; // Import the File class import java.io.FileNotFoundException; // Import this class to handle errors import java.util.Scanner; // Import the Scanner class to read text files public class ReadFile { public st
🌐
Reddit
reddit.com › r/javahelp › how do i find the java command "import"?
r/javahelp on Reddit: How do I find the java command "import"?
January 10, 2024 -

I thought that I had posted this question 3 days ago. However, given that I've received no responses to that earlier and that I cannot locate that post on this site, I gather that said earlier post was not recorded or was not accepted as a result of some error on my part. At any rate I am trying again.

PROBLEM: My attempt to execute the import command in a console window results in the following error message:

C:\Users\rwhoe>

C:\Users\rwhoe>import java.util.Scanner

'import' is not recognized as an internal or external command,

operable program or batch file.

C:\Users\rwhoe>

A search for “import command” via reddit r/javahelp suggests that other users do not have this problem. What am I missing?

ABOUT ME: I am a retired systems engineer and have extensive c++ programming experience but am a total newb to anything HTML or JAVA related. I recently completed the w3schools java tutorial.

ABOUT MY PC: My PC is a hp 64-bit machine running 64-bit Windows 11. I have downloaded and installed the following 64-bit java 21 JDK app for Windows from Oracle:

openjdk-21.0.1_windows-x64_bin

I set my environmental path variable to

C:\Program Files\Java\jdk-21\bin, which successfully provides access to the java command and to the javac command.

🌐
Marco Behler
marcobehler.com › guides › java-files
How To Work With Files In Java
December 9, 2020 - You can use this guide to learn how to work with files in Java through the Path API. From reading and writing files, to watching directories & using in-memory file systems. Java has two file APIs.
🌐
CS4114 Course Notes
opendsa.cs.vt.edu › ODSA › Books › vt › ttip-bridge › summer-i-2022 › Self-Paced › html › 2114_eclipse_examples_setup.html
13.2. Importing and Using Downloaded Examples in Eclipse — Masters of Engineering Bridge Course
Select the option labelled “Select archive file”, then Browse to find the location of the Project you wish to import · Make sure the Project you want is checked (see below), then click FinishDownloading and importing standalone Java files
🌐
GeeksforGeeks
geeksforgeeks.org › java › import-statement-in-java
Import Statement in Java - GeeksforGeeks
July 23, 2025 - Java Source Code file that imports the class defined under the CustomPackage
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-import-package-in-java
How to Import Package in Java? - GeeksforGeeks
July 30, 2025 - Note: This will define a package named as mypackage. Now any class which is defined in this file will basically belong to this package. 2. Use the Package: To use a class from a user-defined package, we need to import it into our program he syntax is similar to importing built-in packages.
🌐
Learnjavacoding
learnjavacoding.com › import-folder-java-files-eclipse
How to import a folder with .java files ? – Learn Java Coding
select import · select: File System · select the folder that contains the .java files · select the .java files · press finish ·
🌐
Reddit
reddit.com › r/javahelp › how to import a package from another directory
r/javahelp on Reddit: How To Import A Package From Another Directory
May 31, 2023 -

Noob question. I made a simple project. The main method initializes a "Sort" object which has its own method called Bubblesort (which accepts an int[] ) . My folder structure is as follows

Main.java

    /Sorters
      /sorters
        Sort.class

What happened was, I manually made a folder called Sorters (not knowing that when you compile the sort java file with the '-d' flag, it will automatically make a folder. But instead of changing it, I decided to work with that.

However I'm not sure how to import the Sort class with the given folder structure.

Here is my Main dot java file

     package Sorters.sorters;
import sorters.Sort;
    public class Main{ public static void main(String[] Args){   
     int[] test = {2, 1, 8, 5, 18, 11, 16, 24, 12, 14, 13};

    Sort s1 = new Sort();

    s1.bubbleSort(test);



    for(int x=0; x<test.length; x++){
        System.out.print(test[x] + " , ");
    }

    System.out.println();
  

    }
    }

and here is my sort file

    package sorters;


public class Sort{

    public void bubbleSort(int[] arr){
        for(int x=arr.length-2; x>=1; x=x-1){
            for(int y=0; y<=x; y++){
                if(arr[y] > arr[y+1]){
                    swap(arr, y, y+1);
            }
        }
    }
}





private void swap(int[] arr, int Left, int Right){

int temp = arr[Right];
arr[Right] = arr[Left];
arr[Left] = temp;

}



}

What am I doing wrong? Doesn't the line "package Sorters.sorters" first navigate to the Sorters folder and then navigate to the inner sorters folder after the period symbol?

Top answer
1 of 2
3
So Main.java is in folder X, which contains Sorters? Is Sort.java in the same folder as Sort.class? IS THERE AN ERROR MESSAGE? ANY time you have an error message concerning something about which you are asking a question, give us the blankety-blank MESSAGE. Do not leave it out, Do NOT paraphrase it, just copy it into the question. Are you using an IDE such as eclipse or NetBeans or something else? Or are you editing with Notepad or something and compiling on a command line? The OS you're using would also be helpful here. I see a couple of things that I think are wrong, but I'm not going to waste time explaining them if I can't even make sense out of your question.
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Oracle
docs.oracle.com › javame › dev-tools › jme-sdk-3.0-mac › UserGuide-html › z40005631313125.html
Add Files to a Project - Java Platform Micro Edition Software Development Kit
For all projects, right-click to ... add a MIDlet, Java class, Java package, Java interface or Other files, right‐click the project name or the Source Packages node, choose New, and select the file type....
🌐
Sybase
infocenter.sybase.com › help › topic › com.sybase.stf.ws.doc-SWS-2.0.0 › projects › workspace › ws › en › source › t_importing_java_source_files.html
Importing Java Source Files
Ensure you are using a Java project or a project with the Java nature. If you have not done so already, configure source folders for the project. Using a file system explorer window, such as Windows Explorer, or a Linux graphical shell, copy and paste or drag and drop the source files into your project using one of these techniques: Note: You can also import source files using the Import wizard.