File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Generic error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generic error" Watch "Generic error" New topic

Generic error

meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 305 error: non-static type variable String cannot be referenced from a static context
public static void main(String[] args)
1 error

My one regret in life is that I am not someone else.
- Woody Allen
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

In this example "String" does not mean what you think it does.

It is not the name of the class java.lang.String. Instead, you've declared a type parameter in line 1, which is confusingly named "String".

Normally people use single upper case letters for type variables, for example "T", so you'd write "class Box<T>" in line 1. But you can name a type parameter anything you like, including the name of an existing class such as "String".

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 305

Thank you, why that compile error occurred ?
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

As Jesper said, you've used String as a generic type variable, and it's clashing with the class String. The generic type takes precedence, so on line 10 that's what the compiler things you're referring to. And because the type variable applies to specific instances of Box, it can't be used in a static context.
I agree. Here's the link:
subject: Generic error
It's not a secret anymore!