"... what exactly is the difference between the two and why is one of them working and the other is not? ..."
The reason the first example is not working is because new non() has no context.
Since non is an inner-class you'll need to access it from an instance of nonstatic.
For example,
nonstatic nonstatic = new nonstatic();
non A = nonstatic.new non();
Although, since non is nested, you could declare it as static; making it easier to reference.
public static void main(String[] args) {
non A = new nonstatic.non();
}
static class non{
public void greeting(){
System.out.println("Hej");
}
}
Additionally, the nonstatic identifier is redundant; so you could just leave the assignment the way it is.
public static void main(String[] args) {
non A = new non();
}
static class non{
public void greeting(){
System.out.println("Hej");
}
}
In your second example you simply have two classes, non-nested.
This doesn't have much use in Java; although I imagine it may help in certain situations.
Essentially, you can have more than one class within a file, as long as not more than one is declared as public.
So, for example, the following will cause an error.
public class nonstatic {
public static void main(String[] args) {
non A = new non();
}
}
public class non{
public void greeting(){
System.out.println("Hej");
}
}
Error
java: class non is public, should be declared in a file named non.java
Here is the Java tutorial on classes and nested classes.
Nested Classes (The Java™ Tutorials > Learning the Java Language > Classes and Objects).
And, here is a relevant discussion regarding your second example.
StackOverflow – Can a java file have more than one class?.