21 C
Texas

Top 5 Java Errors with Solutions

A beginner in any domain is prone to making mistakes, and a lot of mistakes. But if you’re gutsy enough to learn to program, then make these errors 10x than any other thing you’ve ever learned before. All experts were once beginners. And all beginners make mistakes, get stuck, frustrated, and exhausted meanwhile. But if you’re serious about your development career, stick around till you’re comfortable with problem-solving, debugging, and exception handling. As a learner, we advise you to get in touch with any credible java programming blog. Going through quality subject matter will polish your programming skills in a rather seamless way.

Let’s look at some of the most recurring errors by freshmen.

Illegal Type Assignment

Java restricts its users to assign only the same type of variables. On a simpler note, you can not assign an “Integer” type value to a “Double” type variable.

Example

public class IllegalTypeAssignment {
      public static void main(String[] args) {
            int first = 25;
            Double second = first;

            System.out.print(“Is first equal to second? “);
            if (first == second) {
                  System.out.print(true);
            } else {
                  System.out.print(false);
            }
      }
}

Output

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
      Type mismatch: cannot convert from int to Double

Solution

Replace line 5 of the above program for casting in to double. Test the output in your IDE.

            Double second = (double)first;

Invalid Return Type

- Advertisement -

By the rules of the Java language, you can only return the type of variable specified as the return type. A void type method is not capable of returning a String if you try to do so. And hence, you will get a compile-time error.

Example

public class InvalidReturnType {
      public static void printName(String name) {
            System.out.println(name);
            return name;
      }
      public static void main(String[] args) {
            String name = “Lubaina Khan”;
            printName(name);
      }
}

Output

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
      Void methods cannot return a value
      at InvalidReturnType.printName(InvalidReturnType.java:4)
      at InvalidReturnType.main(InvalidReturnType.java:8)

Solution

Remove line 4 to run this void method properly.

Invalid Arguments Type

Let’s say you define a method passing two arguments. This method takes two integers to find their sum. Now if you try to pass two floating points in place of two integers, java will give you a compile-time error.

Example

public class InvalidArgumentsType {
      public static Double sum(Double x, Double y) {
            return x + y;
      }
      public static void main(String[] args) {
            float x = 5;
            int y = 2;
            System.out.println(“Sum of ” + x + ” and ” + y + ” = ” + sum(x,y));
      }
}

Output

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
      The method sum(Double, Double) in the type InvalidArgumentsType is not applicable for the arguments (float, int)

      at InvalidArgumentsType.main(InvalidArgumentsType.java:8)

Solution

Either declare both variables of type “Double” or alter the method header to accept “float” and “int” type arguments

Null Pointer Exceptions

These are most redundant and tricky to handle as a novice. However, there’s no rocket science behind it if you take care of some fundamentals. A null pointer exception arises when you try to access a resource whose value is null and not initialized to a concrete value. Majorly, the null pointer is used to allocate a unique reference to a resource. If you do not have such a requirement then make sure all values are initialized properly before accessing them.

Example 1

public class NullPtrException {
      public static void main(String[] args) {
            String name = null;
            System.out.println(“Length of name is ” + name.length());
      }
}

Output 1

Exception in thread “main” java.lang.NullPointerException
      at NullPtrException.main(NullPtrException.java:4)

Solution 1

Initialize “name” to a string literal say “Alexa” and test the output.

Example 2

public class NullPtrException {
      public static int getEven(int num) {
            return num % 2;
      }
      public static void main(String[] args) {
            int[] arr = { 2, 3, 5, (Integer) null};
            for (int i : arr) {
                  System.out.print(“Is ” + i + ” even? “);
                  if (getEven(i) != 1) {
                        System.out.println(true);
                  } else {
                        System.out.println(false);
                  }
            }
      }
}

Output 2

Exception in thread “main” java.lang.NullPointerException
      at NullPtrException.main(NullPtrException.java:7)

Solution 2

Initialize the arr[3] to a valid integer.

Another advanced way to resolve un-checked exceptions like null pointer exceptions is the exception handling mechanism in Java. Feel free to check out java exceptions examples for a more profound understanding.

Syntax Errors

Anything that does not comply with the Java language rules is categorized as a syntax error.
From beginners to experts, we all are guilty of it at some point. If you have just started working in Java, you must comprehend what I’m talking about. The analogy of syntax rules can be grammatical rules in the English language. The syntax is defined to maintain the standards across the board. Not following naming conventions, misplaced semicolons, un-balanced parenthesis, and misspelled method names, etc are some of the typical syntax errors.

Example

public class SyntaxError {
      public static void main(String[] args) {
            int[] arr = { 2, 3, 5};
            for (int i ; arr) {
                  System.out.println(i);
            }
      }
}

Output

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
      Syntax error on token “;”, : expected
      at SyntaxError.main(SyntaxError.java:4)

Solution

Replace the semicolon after “i” with a colon (:) in line 4.
for (int i : arr)

 

Conclusion

By this point, you must be aware of the most recurring java errors of beginners. It’s okay to have loads of errors when you start learning. The key is not to get afraid of them, and rather keep improving yourself. Till then, keep growing! 🙂

- Advertisement -
Everything Linux, A.I, IT News, DataOps, Open Source and more delivered right to you.
Subscribe
"The best Linux newsletter on the web"

LEAVE A REPLY

Please enter your comment!
Please enter your name here



Latest article