In
C:\Dev\Java\MyFirstJavaClass\
I have a file named MyFirstJavaClass.java, so the path looks like this
C:\Dev\Java\MyFirstJavaClass\MyFirstJavaClass.java
and in "C:\Dev\Java\MyFirstJavaClass" I have a subdirectory called 'src'.
So the path looks like this:
C:\Dev\Java\MyFirstJavaClass\src
In this directory I want to put a file named "MyName.java", so the path would look like this
C:\Dev\Java\MyFirstJavaClass\src\MyName.java
In MyFirstJavaClass.java I have this code
public class MyFirstJavaClass{
public static void main(String[] args){
System.out.println("You have your first Java program running!!\n\n");
}
}
This file compiles, but I'd like to add the files in ./src into my MyFirstJavaClass.java file, how do I #include the file(s) in 'src' in MyFirstJavaClass.java?
Thanks
1) You should check some tutorials about packages and classpath .
https://www.ntu.edu.sg/home/ehchua/programming/java/J9c_PackageClasspath.html
http://www.tutorialspoint.com/java/java_packages.htm
2) You should create the package and structure as described below
package dev.java.myfirstjavaclass;
public class MyFirstJavaClass {
}
It will create your class file inside the folder structure dev/java/myfirstjavaclass in your classpath, Also as per the java naming conventions packages name should be in lower cases.
package dev.java.myfirstjavaclass.src;
public class MyName{
}
It will create your class file inside the folder structure dev/java/myfirstjavaclass/src inside your classpath.
Now as you have called #include the file. You have to use the import statement to include the file where you want to use it.
import dev.java.myfirstjavaclass.src.MyName;
public class MyFirstJavaClass {
public static void main(String[] args) throws IOException{
MyName test=new MyName();
}
}
3) Also look some tutorials on objects and java concepts about how to use them.
Related
public class Main {
public static void main(String[] args) {
}
}
i want to add package how to add it in intellij idea. Is the problem in the beginning of creating a new project ?
Lets assume you have an existing class, and you want it to be in a package. This is called refactoring
Right click on your class name (Main in this case)
In the context menu expand the "refactor"
In the refactor menu select "move to ..."
Then a dialog should appear that lets you enter the name of the package you would like to move your class to.
If it is a new package, it will create a folder and move the source file there.
Your code in file named Main.java
Just add two directories named com and codewithmosh, respectivly inside each other and then move your Main.java class inside it.
After that you can add package statement to your code:
package com.codewithmosh;
public class Main {
public static void main(String[] args) {
}
}
Direcory structure for your project is:
────project
└───com
└───codewithmosh
└───Main.java
Purpose
I want to be able to create a package and call it.
Alternatively, I would like to create separate files for my method (to avoid having x classes in one file).
Setup
Here is my LetterGrader.java file:
package grade.util;
import java.util.*;
import java.io.*;
public class LetterGrader {
private void readArgs() {
System.out.println("Hello, read CLA!");
}
}
Here is my TestLetterGrader.java file:
import java.util.*;
import java.io.*;
public class TestLetterGrader {
public static void main(String[] args) {
LetterGrader letterGrader = new LetterGrader(); // instantiate
letterGrader.readArgs(); // call method
}
}
Steps Taken
First, I compile LetterGrader:
This auto creates the bin/grade/util/LetterGrader.class file
javac -d bin -sourcepath src src/grade/util/LetterGrader.java
Here is my working directory at this point
Second, I compile TestLetterGrader:
This fails
javac -d bin -sourcepath src src/grade/util/TestLetterGrader.java
The error message:
src/grade/util/TestLetterGrader.java:6: error: cannot find symbol
LetterGrader letterGrader = new LetterGrader(); // instantiate
^
symbol: class LetterGrader
location: class TestLetterGrader
Question
I believe I am misunderstanding how to call a classes from separate files (in the same location). How can I accomplish this?
You are importing class that is in bin folder. Don’t do that it would not work. You don’t need any import, because the classes are in the same place. Make package under src folder and place the classes there. Remove package grade.util and rename it to the package where you place the classes.
File structure:
src
\
\
yourpackage
\
\
LetterGrader.java TestLetterGrader.java
Then delete everything in your build folder and compile the classes. Java will make it’s magic. You do need to worry about bin folder, it is only for storing compiled classes.
Classes will look like this:
//package name that you created
package yourpackage;
public class LetterGrader {
//need to be public when calling from another class
public void readArgs() {
System.out.println("Hello, read CLA!");
}
}
And
//folder that you placed the .java files
package yourpackage;
//without any import
public class TestLetterGrader {
public static void main(String[] args) {
LetterGrader letterGrader = new LetterGrader(); // instantiate
letterGrader.readArgs(); // call method
}
}
Your second question:
You can use classes from other folders, but you you have to import them and they have to be under src folder.
Tell you have class A.java in folder Second and class B.java in folder Main. You will import the the folder in this case import Second.A;
And then call the class A a = new A();
When you have method in a that you want to call simply do:
a.yourmethod();
You have to change private void ... to public void... because you cannot call private outside of the class.
When you are running compiled classes they have to be in the same folder.
Thanks #maratonec for the guidance.
My initial mistake was that I was misunderstanding/misassigning the classpath assignment variable when running a program via terminal. The below helped me.
Compiling and Running a Java Program (on a PC)
• Set the working directory (say, JavaBook)
C:\> cd JavaBook
• Compile HelloWorld.java
C:\JavaBook> javac -d bin src\HelloWorld.java
•Run the program
C:\JavaBook> java -classpath bin HelloWorld
Also, the approach of having all my class files in the same location simplified things. I didn't have to worry about classpath. But not ideal as I have many files to work with.
As for the package creation, I am going to play around with java a bit more before using it. I think I need to solidify my understanding.
Thanks for helping me!
I have a Main class. I also have another class I have made (call it the "Runner" class). I would like to, however, have more Runner classes (the difference between them being modifications to each respective Runner class by other people). Would it be possible to have each Runner class in separate folders and have the folders in the same directory as the Main class, and then reference the Runner objects in the Main class as if they were a class in the same directory as the Main class?
Yes, this question strikes me like you're viewing Java like php or ruby, etc which isn't quite accurate. With Java, each class has what's called a "Fully Qualified Name" which is derived from the folder it's stored in (like Python). Because Java is compiled, you tell the compiler where to find the code needed to compile a java file, rather than putting a reference to those needed files in the top of the file (like a require statement in php) which would be an instruction to the interpreter.
Say for instance you had a structure like this:
src/
Main.java
/runner1
SomeRunner.java
/runner2
SomeOtherRunner.java
Main.java
public class Main{
public static void main(String[] args){
//use SomeRunner
runner1.SomeRunner.run();
//use SomeOtherRunner
runner2.SomeOtherRunner.run();
}
}
SomeRunner.java
package runner1;
public class SomeRunner{
public void run(){ ... }
}
SomeOtherRunner.java
package runner2;
public class SomeOtherRunner{
public void run(){ ... }
}
Alternatively, you can use imports:
Main.java
import runner1.SomeRunner;
import runner2.SomeOtherRunner;
public class Main{
public static void main(String[] args){
//use SomeRunner
SomeRunner.run();
//use SomeOtherRunner
SomeOtherRunner.run();
}
}
In this example, I chose arbitrary package names (runner1 and runner) which is technically fine. However, best practices state that your package names should be the reverse domain name of your project (i.e. com.myproject) to avoid collisions with other libraries etc. You can read more about that here. When you compile your Main class, you will need to supply the SomeRunner and SomeOtherRunner files to the compiler so it knows where to find them.
My file name is Temp.java and inside it I have this. I'm using eclipse IDE
/*package*/ class Test {
public static void main(String args[]) {
System.out.println("test");
}
}
So I was unable to run this as java application. I change my class name to Temp
class Temp {
....
}
Now I can. Can someone explain me why ?
This is probably a limitation of Eclipse. The code runs well from command line.
As I understand, you are trying to embed your unit tests in the same file with the class under test. This is a nice idea and I totally concur with it. You can read more about how you can succeed in Ben J. Christensen's blog post. Generally, he suggests placing the tests in a static inner class, not a standalone class in the same file.
An example from the Netflix Hystrix framework: HystrixCircuitBreaker.UnitTest
The code below, located in Temp.java, compiles and runs fine with Netbeans:
class Whatever {
public static void main(String[] args) {
System.out.println("hello");
}
}
The problem is with eclipse, i think you are trying to run using right click -> run as -> Java Application, unfortunately eclipse is not showing this option if the class is not public.
But you can still run the class using Alt+Shift+X,J.
Its not the problem with Java, its with Eclipse.
The name of the file should be the same as the class name which is public and has the main() method. In your first case the file name Temp.java will compile and will create Test.class file not Temp.class because there is no Temp class declared in your file.
after .class file is created , run it with java Test
so here's an example
//Filename abc.java
public class hi
{
public static void main(String[] args)
{
System.out.println("Hell");
}
}
the output
abc.java:1: class hi is public, should be declared in a file named hi.java
public class hi
^
1 error
but if you do this
//Filename abc.java
class hi
{
public static void main(String[] args)
{
System.out.println("Hell");
}
}
it will create hi.class file so
D:\>java hi
Hell
The class (which main should be run) inside the .java file must have the same name as the file. If the class is not public (as in your case) the class will compile but it can't be run since Eclipse tries to load the class according to the file name.
I've been running different individual Java .java files in the Netbeans IDE by right-clicking the .java files themselves in the Project Explorer of Netbeans (the portion normally at the upper left part of Netbeans).
However, i've been googling on how to make a class file run another class file using code, but to no avail.
I have a project named "loadanotherfile" with 2 files, namely: Loadanotherfile.java and otherfile.java
I'm trying to make Loadanotherfile.java run otherfile.java, but I'm not exactly sure how. I read about Classloaders and URLClassloaders however these methods don't seem suitable for my purpose of running another .java file.
Below is the code of the 2 files i mentioned.
Loadanotherfile.java
package loadanotherfile;
public class Loadanotherfile {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Hello World!");
// TODO code application logic here
}
}
otherfile.java
package loadanotherfile;
public class otherfile {
public static void main(String args[])
{
System.out.println("This is the other file.");
}
}
I have a feeling that the task has something to do with using the "import" syntax (namely something like import loadanotherfile.* but even if my guess is correct, I'm still not sure on how to make my Loadanotherfile.java run otherfile.java using code.
How can I load otherfile.java using Loadanothefile.java?
Cheers
In Loadanotherfile.java
otherfile.main(args);
Compile the two together, and then from Loadanotherfile,
otherfile.main(args);
will do the trick. You don't need to import since you're in the same package. Note the linked tutorial.
I would investigate (however) class instantiation, and creating an instance of a new class to invoke upon. Invoking static methods from static methods isn't very OO.
Try This:
className.main(Args){
}
This works! ive tested it myself.
Check the public void main line. If there IOException and not there then insert
in Loadanotherfile.java
use this
otherfile.main(args);{
}