Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads and valueOf() method

 
Daniel Curtis
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I'm really struggling to understand this homework problem and the concepts behind it:

Write a program called MyQ12Class.java 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
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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



 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic