Errors

By now, you’ve probably seen a few errors, either when compiling or running your code. They can be frustrating, but they can also give you a lot of information about exactly how you can fix the problems in your code. This tutorial covers the types of errors you’ll see when programming in Java, and how to fix them.


This is a companion discussion topic for the original entry at https://happycoding.io/tutorials/java/errors

Inside the Debugging section, for the NullPointerException example: there is one way in which we don’t need to use “this” and also deal with the error.
THIS COULD BE A BAD PRACTICE THOUGH. BUT I THOUGHT THAT I SHOULD POINT IT OUT.
→ If we change the code from

public LineSegment(Point startPoint, Point endPoint){
	startPoint = startPoint;
	endPoint = endPoint;
}

to something like this, then the variables wont remain uninitialized and the code works.

  public LineSegment(Point startPnt, Point endPnt) {
    startPoint = startPnt;
    endPoint = endPnt;
  }

Sure, you could do that!

Other languages use a convention where an underscore is added after argument names to avoid collisions with member fields:

public LineSegment(Point startPoint_, Point endPoint_){
	startPoint = startPoint_;
	endPoint = endPoint_;
}

This is allowed in Java, but generally discouraged by most coding conventions I’ve seen.

I think the this. approach is most common, but this is one of those things that comes down to personal preference.

1 Like