1

I'm learning Java and one of the examples of the book runs perfectly from command line, but throws an error from Eclipse. The script is this:

    /**
     * This program displays a greeting from the authors.
     * @version 1.20 2004-02-28
     * @author Cay Horstmann
     */
    public class Welcome
    {
       public static void main(String[] args)
       {
          String[] greeting = new String[3];
          greeting[0] = "Welcome to Core Java";
          greeting[1] = "by Cay Horstmann";
          greeting[2] = "and Gary Cornell";

          for (String g : greeting)
          System.out.println(g);
       }
    }

The error I get in Eclipse is 'Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error, 'for each' statements are only available if source level is 1.5 or greater' The book says I would get an error in that line (the for) if the JDK was too old, but then why does it run well from the command line? Thanks

Haniver
  • 192
  • 2
  • 12
  • You probably haven’t set up your jdk for eclipse at all. Make sure you go into your class path and verify it has a reference to your jdk. – Nick Humrich May 12 '14 at 21:53
  • You probably have a version of java newer than 1.5 installed in JAVA_HOME, but have your compiler compliance level < 1.5 in your eclipse settings. – azurefrog May 12 '14 at 21:53
  • Try this: http://stackoverflow.com/questions/1944468/what-version-of-java-is-running-in-eclipse – EyeOfTheHawks May 12 '14 at 21:57

2 Answers2

3

The reason is because your Eclipse instance uses a different version of Java compared to when run from the command line. In order to check which java version is being used as default, type java -version on the command prompt

C:>java -version

java version "1.6.0_45" Java(TM) SE Runtime Environment (build 1.6.0_45-b06) Java HotSpot(TM) Client VM (build 20.45-b01, mixed mode, sharing)

In order to check the Java version that your eclipse instance uses, check out

Welcome Project-->Properties--> Java Build Path--> Libraries--> JRE System Library.

You can verify the Java version for your project from the package explorer as well. enter image description here

Piyush Mattoo
  • 15,454
  • 6
  • 47
  • 56
3

Right click on your project --> properties and change version in below screen

enter image description here

upog
  • 4,965
  • 8
  • 42
  • 81
  • Thank you. That did it. Now how do I change the default compiler version for future projects? – Haniver May 12 '14 at 22:06
  • click on that particular project and then properties...Then Java version will be updated to that particular project – upog May 12 '14 at 22:08