Java errors and solutions

Top 8 Common Java Errors for Beginners — and How to Solve Them

Did you know that in Java’s standard library, there are a total of more than 500 different exceptions! There lots of ways for programmers to make mistakes — each of them unique and complex. Luckily we’ve taken the time to unwrap the meaning behind many of these errors, so you can spend less time debugging and more time coding. To begin with, let’s have a look at the syntax errors!

Syntax Errors

If you just started programming in Java, then syntax errors are the first problems you’ll meet! You can think of syntax as grammer in English. No joke, syntax errors might look minimal or simple to bust, but you need a lot of practice and consistency to learn to write error-free code. It doesn’t require a lot of math to fix these, syntax just defines the language rules. For further pertinent information, you may refer to java syntax articles.

Читайте также:  Python float check is nan

Working with semicolons (;)

Think of semi-colons (;) in Java as you think of a full-stop (.) in English. A full stop tells readers the message a sentence is trying to convey is over. A semi-colon in code indicates the instruction for that line is over. Forgetting to add semi-colons (;) at the end of code is a common mistake beginners make. Let’s look at a basic example.

This snippet will produce the following error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error, insert ";" to complete BlockStatements at topJavaErrors.JavaErrors.main(JavaErrors.java:3)

You can resolve this error by adding a ; at the end of line 3.

Braces or parentheses [(), <>]

Initially, it can be hard keeping a track of the starting / closing parenthesis or braces. Luckily IDEs are here to help. IDE stands for integrated development environment, and it’s a place you can write and run code. Replit for example, is an IDE. Most IDEs have IntelliSense, which is auto-complete for programmers, and will add closing brackets and parentheses for you. Despite the assistance, mistakes happen. Here’s a quick example of how you can put an extra closing bracket or miss the ending brace to mess up your code.

If you try to execute this, you’ll get the following error.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error on token ")", delete this token at topJavaErrors.SyntaxErrors.main(SyntaxErrors.java:11)

You can resolve this exception by removing the extra ) on line 9.

My full name is: Justin Delaware 

Double Quotes or Quotation Marks (“ ”)

Another pit fall is forgetting quotation marks not escaping them propperly. The IntelliSense can rescue you if you forget the remaining double quotes. If you try including quotation marks inside strings, Java will get confused. Strings are indicated using quotation marks, so having quotation marks in a string will make Java think the string ended early. To fix this, add a backslash (\) before quotation marks in strings. The backslash tells Java that this string should not be included in the syntax.

Exception in thread "main" java.lang.Error: Unresolved compilation problems: Syntax error on token "Java", instanceof expected The preview feature Instanceof Pattern is only available with source level 13 and above is cannot be resolved to a type Syntax error, insert ")" to complete MethodInvocation Syntax error, insert ";" to complete Statement The method favourtie(String) is undefined for the type SyntaxErrors Syntax error on token "language", ( expected at topJavaErrors.SyntaxErrors.main(SyntaxErrors.java:5)

In order for you avoid such exceptions, you can add backslahes to the quotes in the string on line 4.

What did Justin say? Justin said, "Java is my favourite language"

Here’s your required output, nicely put with double quotes! 🙂

Other Miscellaneous Errors

Accessing the “Un-Initialized” Variables

If you’re learning Java and have experience with other programming languages (like C++) then you might have a habit of using un-initialized variables (esp integers). Un-initialized variables are declared variables without a value. Java regulates this and doesn’t allow using a variable that has not been initialized yet.

If you attempt to access an uninitialized variable then you’ll get the following exception.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The local variable contactNumber may not have been initialized at topJavaErrors.UninitialziedVars.main(UninitialziedVars.java:5)

You can initialize the variable “contactNumber” to resolve this exception.

int contactNumber = 9935856;

Accessing the “Out of Scope” Variables

If you define a variable in a certain method you’re only allowed to access that in the defined scope of it. Like each state has their legitimate currency, and that cannot be used in another state. You cannot use GBP in place of USD in America. Similarly, a variable defined in one method has restricted scope to it. You cannot access a local variable defined in some function in the main method. For further detailed illustration let’s look at an example.

As soon as you run this snippet, you’ll get the exception

Exception in thread "main" java.lang.Error: Unresolved compilation problem: country cannot be resolved to a variable at topJavaErrors.OutOfScopeVars.main(OutOfScopeVars.java:9)

You can not access the variable “country” outside the method getPersonalDetails since its scope is local.

Modifying the “CONSTANT” Values

Java and other programming languages don’t allow you to update or modify constant variables. You can use the keyword “final” before a variable to make it constant in Java. Apart from that, it’s a convention to write a constant in ALL CAPS for distinction purposes, As a constant resource is often used cross methods across a program.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final field ConstVals.SSN cannot be assigned at topJavaErrors.ConstVals.main(ConstVals.java:5)

Remove line 4 for the perfectly functional code.

Misinterpretted Use of Operators ( == vs .equals())

A lot of beginners start working with integers while learning the basics of a programming language. So it can be a challenge to remember that for string comparisons we use the “.equals()” method provided by Java and not == operator like in integers.

It's not a Wednesday! It's a Wednesday!

The output is contradictory because “today” and “thirdWeekDay” are referred to 2 different objects in the memory. However, the method “.equals()” compares the content stored in both arrays and returns true if it’s equal, false otherwise.

Accessing a non-static resource from a static method

If you want to access a non-static variable from a static method [let’s say the main method] then you need to create an instance of that object first. But if you fail to do that, java will get angry.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static field postalCode at topJavaErrors.NonStaticAccess.main(NonStaticAccess.java:17)

You can fix it, just by replacing line 9.

// Accessing the non-static member variable // by creating an instance of the object System.out.println("What's the postal code of your area? " + address.postalCode);

Conclusion

Programming errors are a part of the learning curve. Frequent errors might slow you down. But as a new programmer, it’s okay to learn things slowly. Now you’re familiar with some of the most common issues. Make sure you practise enough to get ahead of them. Happy coding and keep practising! 🙂

Источник

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

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

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

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

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

Solution 1

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

Solution 2

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

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! 🙂

Источник

Оцените статью