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

Can anyone help me find the error in this??

public class Contructor {
 int id;
 String name;
 Constructor() {
  System.out.println("This is default constructor");
  System.out.println("Student Id:"+id+"\nStudent Name:"+name);
 }
 Constructor(int i,String n) {
  System.out.println("This is parameterized constructor");
  id=i;
  name=n;
  System.out.println("Student Id:"+id+"\nStudent Name:"+name);
 }
 public static void main(String[] args)
 {
  Constructor s=new Constructor();
  Constructor Student=new Constructor(10,"Ash");
 }
}

What error do you get when you compile this code?

Hint: Check your spelling :upside_down_face:

1 Like