-2

while using JFrame, I tried setting the icon image with the following code

ImageIcon image = new ImageIcon("C:\\barney.jpg");
frame.setIconImage(image.getImage());

It works as expected, but when I set the "C:\\barney.jpg" as aString variable

String var = "C:\\barney.jpg";
ImageIcon image = new ImageIcon(var);
frame.setIconImage(image.getImage()); 

The compiler displays Exception in thread "main" java.lang.Error: Unresolved compilation problem

Another point of confusion is why the line in the error code refer to the public static void main(String[] args) line instead of String var = "C:\\barney.jpg"; which actually causes the error?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Ser.T
  • 51
  • 4

1 Answers1

2

var is a reserved keyword in java. You can't name any variable var. Try some other name.

The reason behind this is that var is used for assigning variables so to not confuse the compiler you cannot use it as a variable name.

Note that it does compile in java 8 and prior as the var keyword has not had been implemented back then. Additionally starting from java 17 it is possible again to use it as a variable name.

var, with some limitations lets you replace standart assignments in java.

String someString1 = "Hello, World!";
// gets turned into
var someString2 = "Hello, World!";

This also works with other assignments

0xff
  • 181
  • 2
  • 11
  • Ah Interesting. Didn't know it was possible in java 17! – 0xff Oct 08 '21 at 15:13
  • @jadefalke changing the variable name still causes the same exception, i used `x` instead of `var` – Ser.T Oct 08 '21 at 15:19
  • @user16320675 `Exception in thread "main" java.lang.Error: Unresolved compilation problem: at a1.main(a1.java:5)` that's all i'm getting – Ser.T Oct 08 '21 at 15:23
  • 3
    @ser.T please don't edit a question in such a way that the original question is not inferable anymore – 0xff Oct 08 '21 at 15:23
  • That is not correct. **var** is __not__ a reserved keyword, rather it is a reserved type name in Java, and so you can use variable with **var** name. See here: https://stackoverflow.com/questions/49102553/what-is-the-conceptual-difference-between-a-restricted-keyword-and-reserved-t#:~:text=A%20%22reserved%20type%20name%22%20is,using%20an%20additional%20lookup%20step. – Mikhail2048 Mar 10 '23 at 08:29
  • P.S: See the JLS section about keywords: https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.9 – Mikhail2048 Mar 10 '23 at 08:57