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 Threads and valueOf() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Threads and valueOf() method" Watch "Threads and valueOf() method" New topic

Threads and valueOf() method

Daniel Curtis

Joined: Jun 18, 2012
Posts: 3
Hello, I'm really struggling to understand this homework problem and the concepts behind it:

Write a program called that takes in an integer as an argument, creates that many Threads, and prints out the name of the Threads to the standard output.
Example: "Hi, I am Thread1", "Hi, I am Thread2", and so on and so forth.

Remember to covert the element in args[0] into an Integer, using the valueOf() method.
Remember that if the valueOf method fails it can throw Exceptions, so you will need a try/catch block.

Override the run method to print the Thread name to the standard output. The teacher provided me some help with this code, but I'm not understanding the concepts behind it:

I guess my main questions are:

What type of exceptions are appropriate?
How to instantiate the threads?

Any help would be greatly appreciated!
David Blevins

Joined: May 03, 2010
Posts: 18
What type of exceptions are appropriate?

Simply put, you need to catch the exceptions that are declared in the method you are calling:

Using the String class as an example, it has the following method:

If you want to call that method on a String you need to catch what is listed in the throws clause. In this case you must catch(UnsupportedEncodingException e)

It's a minor detail at this stage in your learning, but understand that any exception that is a direct or indirect subclass of RuntimeException is optional. You can catch it or not, up to you. Your teacher will probably give you extra points if you catch any RuntimeExceptions the javadoc mentions for the given method.

How to instantiate the threads?

Sounds like the teacher wants you to override the run method, in which case you need to learn how to create a subclass. You'll subclass Thread and override the run method. Then you need to instantiate the subclass with the new keyword and choosing the appropriate constructor.

Here's an example of subclassing Object and overriding toString

I agree. Here's the link:
subject: Threads and valueOf() method
It's not a secret anymore!