Why is there a NullPointerException in this function call? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
What are the rules for evaluation order in Java?
(5 answers)
Closed 2 years ago.
public class Bar {
private Foo m_foo;
private int getNumbers(){
m_foo=new Foo();
return 5;
}
public void test1(){
m_foo.print(getNumbers());
}
}
public class Foo {
public void print(int x){
System.out.println(x);
}
}
public class Main {
public static void main(String args[]){
new Bar().test1();
}
}
The NullPointerException occurs in test1()call, but I can't understand the reason behind. Isn't the m_foo supposed to be instantiated in the getNumbers() which should get evaluated first?

NullPointer occurs at
m_foo.print(getNumbers());
because m_foo is initialized in getNumbers method, and it is never got called before calling test1.
Java executes statement in a sequence from left to right. So first
it will check for m_foo object. Ideal way to do this in a constructor
of Bar.
public Bar(){
m_foo=new Foo();
}

Related

java static method why is needed [duplicate]

This question already has answers here:
"Non-static method cannot be referenced from a static context" error
(4 answers)
Closed 6 years ago.
I'm using eclipse as IDE for java.
I wrote the following code, but I have one error on loadStrade(). Eclipse suggested me to change loadStrade from public void to public static, and I don't understand why?
I've looked for similar problem and I've found some problems like mine, but I still not understand why I have to change method to static. Uffa!
In the code, routesNet is a graph (jgraphT), and loadStrade() is used to populate vertex and edge.
Can I have help. Thanks, Fabrizio
public class GestioneStrade {
private Stradario routesNet;
public static void main(String[] args) {
/*
* Instantiate Stradario and fill it with routes and cross
*
*/
GestioneStrade m = new GestioneStrade(); //istance of gestionestrade ok?
// now I set new routesNet
m.setRoutesNet(new Stradario());
loadStrade(m.getRoutesNet()); // why loadStrade must be static :-(
}
public Stradario getRoutesNet() {
return routesNet;
}
public void setRoutesNet(Stradario routesNet) {
this.routesNet = routesNet;
}
public void loadStrade(Stradario str) {
// some code to fill routesNet
}
In "main" you should replace
loadStrade(m.getRoutesNet());
to
m.loadStrade(m.getRoutesNet());
And leave loadStrade as non-static.

Why it throws null pointer exception when object is initialized to null and then trying to access class method? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class Abc
{
public static void main(String args[])
{
def obj=null;
obj.method();
}
}
class Def
{
void method()
{
System.out.println("class def->>> method()");
}
}
The output of this code is generating a NullPointerException and why?
The NullPointerException means you tried to deference a null value so you get the expected behaviour.
It doesn't have anything to do with detecting uninitialised values. It's not called UninitialisedException

Static method getting called using a null reference [duplicate]

This question already has answers here:
Why I am not getting NullPointerException? [duplicate]
(6 answers)
Closed 6 years ago.
public class Test {
public static void main(String[] args) {
Test test = null;
test.func();
}
static void func(){
System.out.println("Hello!!");
}
}
Why this program is getting executed successfully?
This is because static methods are not related to instances. Compiler internally convert this and call Test.func()
You call a static method. Static methods are invoked on Classes.
The call is like this Test.func().
Tip: In your code when you call static methods. Call them Class.method() not on object.

In Java, why Object class object in method parameter can not accept null [duplicate]

This question already has answers here:
How to do method overloading for null argument?
(7 answers)
Closed 8 years ago.
Please explain why i'm getting "Method with String param" in output.
And when i remove the comments from display(Test x) method, it says "Reference to display is ambiguous".
class Test
{
int a;
int b;
}
public class TestIt
{
public static void display(String x)
{
System.out.println("Method with String param");
}
public static void display(Object x)
{
System.out.println("Method with Object param");
}
/*
public static void display(Test x)
{
System.out.println("Method with Test param");
}
*/
public static void main(String args[])
{
display(null);
}
}
Because null is a valid value for Object and String. You can cast,
display((String) null);
Will output
Method with String param
or
display((Object) null);
for
Method with Object param
Because when figuring out which method to call, the compiler picks the most specific method it can find that matches the argument. Both display(String) and display(Object) match a call to display(null), but display(String) is more specific than display(Object), so the compiler uses that. When you uncomment the display(Test) version, though, the compiler can't make a choice because both display(String) and display(Test) are equally specific.
For all the gory details, see ยง15.12 of the JLS.

"Main method not found" error - what is missing in this code? [duplicate]

This question already has answers here:
"Main method not found" error when starting program? [duplicate]
(7 answers)
Closed 9 years ago.
I was just re-reading my lecture scripts and trying out the code there. The problem is that the professor gave us only fragments of code and I really stuck on this one. I keep getting this error in Eclipse:
no main method
I still get the error even if I put public static void main(String[] args) in the code. What should I change in it?
The main idea of this program is to calculate a square or square root.
public class MeineKlasse {
private String job;
private String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
System.out.println(job);
}
public double myMethode(double x) throws Exception {
if (job.equals("quadrat"))
return x * x;
if (job.equals("wurzel"))
return Math.sqrt(x);
System.out.println(myMethode(x) + "=");
throw new Exception("Fehler:Aufgabe nicht korrekt definiert");
}
}
Every program needs entry point. The entry point to any java program is
public static void main(String[] args)
You have to implement this method. It will run the rest of your application.
If you get error like no main method it means you had to put your main method in the incorrect place. Make sure also your curly brackets are closed and follow this structure
public static MeineKlasse {
public static void main(String[] args) {
//your code
//...
//...
//...
}
}
What AlexR said is correct. Every program needs a main method, which is what runs the program.
You can fix it with something like this:
public class MeineKlasse {
private String job;
public static void main(String[] args) { //main method
MeineKlasse meineKlasse = new MeineKlasse();
meineKlasse.setJob("quadrat");
System.out.println(meineKlasse.myMethode(3.6));
} //end main method
private String getJob() {
return job;
}
.
.
.
}
Another problem you have is in myMethode(double x).
public double myMethode(double x) throws Exception {
if (job.equals("quadrat"))
return x * x;
if (job.equals("wurzel"))
return Math.sqrt(x);
System.out.println(myMethode(x) + "="); //this line
throw new Exception("Fehler:Aufgabe nicht korrekt definiert");
}
On line 6, the method calls itself. When it calls itself, it repeats the method over again, including calling itself. Because it just called itself again, it will go through the code until it calls itself, etc. This results in a StackOverflowException, because the method would otherwise repeat itself forever. To fix this, you can just remove the line, as the program already prints the result in the main method.

Categories

Resources