Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassNotFoundException when executing from cmd

I've written the below code in a text file and saved it as Exercise1.java:

import java.util.*;
public class Exercise1
{
 public static void main(String[] args)
 {
  char myChar;
  int myInt;
  System.out.println(myChar);
  System.out.println(myInt);

 }
}

then in cmd I write

javac D:\Projects\Exercise1.java

I get 2 errors both saying the declared variables might not be initialized. But if I initialize the variables the above code generates the "Exercise1.class" file. And then when I write

java D:\Projects\Exercise1

I get java.lang.ClassNotFoundException. Now what I wonder are:

  1. Aren't primitive types initialized to default values in Java (I thought and read they did).
  2. Why can't I run my program and get the Exception as there do not not seem to be any mistakes?
like image 302
Mikayil Abdullayev Avatar asked Apr 10 '26 04:04

Mikayil Abdullayev


2 Answers

The java command doesn't take a filename - it takes a classname. The name of your class is just "Exercise1" - if it were in a package, it might be something like "foo.bar.Exercise1". You then separately specify the classpath to tell the JVM how to find classes, e.g.

java -cp D:\Projects Exercise1

... or you can change directory and take advantage of the fact that without a classpath specified, the JVM will include the current directory in the classpath:

cd D:\Projects
java Exercise1

EDIT: I'd assumed you'd already fixed the errors in the code. Don't try to run the code before it compiles without errors. The errors are due to your uninitialized local variables. Only instance and static variables are given default values.

like image 67
Jon Skeet Avatar answered Apr 11 '26 17:04

Jon Skeet


cd D:\Projects
java -cp . Exercise1
like image 29
AlexR Avatar answered Apr 11 '26 17:04

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!