This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Niko Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Niko Question" Watch "Niko Question" New topic
Author

Niko Question

Simran Dass
Ranch Hand

Joined: Jan 09, 2010
Posts: 183

class Test2<String> {
String my = "Hello!";
}

Cannot understand why above code gives Compiler Error -

niko1.java:17: incompatible types
found : java.lang.String
required: String
String my = "Hello!";
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9303
    
  17

In that declaration, <String> doesn't mean java.lang.String, you are creating a new type, just like <T>, so in the class, when you use String, it will not represent java.lang.String. The code actually can be written like this too


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Sumukh Deshpande
Ranch Hand

Joined: Feb 17, 2008
Posts: 87

Ankit then what should be the correct syntax to achieve what Simran Dass is trying to do?
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9303
    
  17

Sumukh Deshpande wrote:Ankit then what should be the correct syntax to achieve what Simran Dass is trying to do?

Rohan Kayan
Ranch Hand

Joined: Sep 17, 2004
Posts: 123


If I am not wrong. the generic type "String" is creating confusion , we generally use <T> or some other character for generic types , in above code we are using "String" to represent generic type.


SCWCD 1.4, SCJP 1.4
Vivek K Singh
Ranch Hand

Joined: Dec 22, 2009
Posts: 85

in the modified code sample by Ankit:



The generic type String will never be used as the type parameter String is hiding the type String.

The code sample compiles as the we gave the full reference to java.lang.String but in your code you will never be able to use the generic type "String".


SCJP 6
 
GeeCON Prague 2014
 
subject: Niko Question