This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
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

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
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: 13869

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 7 API documentation
Scala Notes - My blog about Scala
meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 305

Thank you, why that compile error occurred ?
Matthew Brown

Joined: Apr 06, 2010
Posts: 4240

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
Similar Threads
Very Basic Question ....
Check String for null without error?
Hi to all
IF strings are immutable why is the variable s appending and changing its obect
how to replace the bracket in java?