Why does empty variable declaration of type show compile error but not for null declaration?

compiler-errors, java, string, variable-assignment

Solution

Because `s2` is not initialized and `s1` is initialized with `null`

For Que 1: You are performing `trim()` Operation on `null` actually, so it will throw NPE (`NullPointerException`) as it should be.

For Que 2: See §4.12.5 of the JLS for a very detailed explanation:

A local variable must be explicitly given a value before it is used, by either initialization or assignment, in a way that can be verified by the compiler using the rules for definite assignment.

Problem

``` public static void main(String[] args) { String s1 = null; String s2; s1.trim(); //No compile error. But run time error s2.trim(); //compile error. } ``` In the above code there is no assignment for `s1` after initialization compiler knows `s1` is `null`. Then why not showing compile error for `s1.trim()` like `s2`?

Original source