4lex1v
4lex1v

Reputation: 21557

Java's new Scanner vs Scanner.create()?

I was looking through O'Reillys Java Cookbook (2ed) for some good stuff and found Scanner.create() method about 10 times. But there's no such in the API or class declaration\implementation. Ex: Page example

Upvotes: 5

Views: 1170

Answers (4)

idarwin
idarwin

Reputation: 647

As the author of the cited work, I apologize for the inconvenience caused by my writing that based on a Tiger (1.5) Beta. What is surprising is that I missed one incorrect example (Scanner sc = Scanner.create(System.in);) and that made it all the way through the 3rd and 4th edition, and nobody reported it on the O'Reilly errata site, nor did the tech reviewers catch it. Well, it's being fixed in the fifth edition, in preparation now!

Upvotes: 0

user166390
user166390

Reputation:

It's either referring to a non-SDK Scanner type or is an error in the book.

There is no static Scanner Scanner.create() in Java 1.5/5 (when it was introduced), or in the SDK 6 or SDK 7 APIs. There is also no mention of such a method being obsoleted (which, in Java SDK API, effectively means it never [officially] existed :-).

Update note: It appears that the create factory method did indeed exist in the earliest preview/beta versions of Java 5. RanRag found a relevant thread on the issue:

...and no, you aren't going crazy: Scanner had create() methods in [Java 5] tiger-beta1, but they switched to constructors in [Java 5] beta2.

(So the only correct way to is use the constructor.)

Happy coding.

Upvotes: 9

RanRag
RanRag

Reputation: 49577

It is mentioned in Oracle forums that Scanner had create() methods in tiger-beta1, but they switched to constructors in beta2.

This is no longer the way to do it. You should create an instance of the Scanner class in the same way you would create an instance of any other class, by using a constructor.

Scanner sc  = new Scanner(System.in)

Upvotes: 2

travega
travega

Reputation: 8415

Hmm looks like someone did not check the updated spec before the cookbook post! The only way to instatiate a Scanner objects is:

Scanner sc  = new Scanner(System.in)

according to the API documentation

Upvotes: 1

Related Questions