Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a question about save

 
po-ting Yeh
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class t1{
public static void main(String[] args) {
System.out.println("ok");
}
}
if I save this to file t1,
then compile and runtime are ok,
but after doing this step,
if I just save it to another file t2 without changing class name,
then compile t2 is ok,
but producing runtime exception,
please tell me why?
thx
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Becuase the fully qualified (package) name of the class must match the relative path (from the CLASSPATH) of the file that contains the class. In your case the package is the default (or root) so the compiled class file must be located at ./t1.class from any of the paths defined in the CLASSPATH. That is how the bootstrap ClassLoader locates the class files that are necessary to run the application. If you had placed the class in the com.mypackage package then it would need to be located at com/mypackage/t1.class for the ClassLoader to find it.
 
Natraj Gudla
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you say "java t2" to execute the java code, the class file needs to contain a class by name "t2" with the the proper main method declared.
As you have renamed the file name , but did not change the class name, it gives a RuntimeException.
Hope this explanation helps.
 
Robert MacEwan
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm a COMPLETE newbie with java but

class t1 {
public static void main(String[] args) {
System.out.println("ok");
}
}
Will have to be saved as tl.java

class t2 {
public static void main(String[] args) {
System.out.println("ok");
}
}
Will have to be saved as t2.java
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
macewan,
Welcome to JavaRanch!
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy. A single part display name doesn't cut it.
Thanks Pardner! Hope to see you 'round the Ranch!
----
Note that it's public outer classes that must be in a file with the same name as the class. If the classes aren't declared to be public, then they can be in just about any ol' source file - no matter the file name.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic