Abdullah Al Mubin Abdullah Al Mubin - 23 days ago 6
Java Question

NullPointerException at LexicalAnalyzer in Java

My code is this-

package LexicalAnalyzer;

import java.util.Scanner;

public class MainClass {
public static void main(String args[]){
String i = null;
String in = null;
for( ; !i.equals(";;"); ){
Scanner inpu = new Scanner(System.in);
in=inpu.nextLine();
int j = in.length();

}

System.out.println(""+in);

Token t=new Token();
t.inp=in;
}
}


I am getting this error for my code-

"Exception in thread "main" java.lang.NullPointerException
at LexicalAnalyzer.MainClass.main(MainClass.java:9)
Java Result: 1"


Can anyone please help me to find out the error?

Thanks

Mox Mox
Answer
!i.equals(";;")

i is null, therefore calling the equals function on a null object will result in null pointer exception

you may want to set i to an empty string with

String i = "";

this will instantiate the string with a valid object reference. And now you can access the equals method