public void takeGuess () throws IOException
{ temp=" ";
  Hangman obj = new Hangman();
  System.out.println ("Enter a character or type in 'hint' for a hint!");
  DataInputStream input=new DataInputStream(System.in);
  temp= input.readLine();
  if (temp.length()==1)
  {
     guess=temp.charAt(0);
     if ((guess >= 'a' && guess <='z') || (guess >='A' && guess <='Z'))
     {System.out.println();}
     else 
     {System.out.println ("Special symbols or numbers are not present in fruit names yet!" );
     System.out.println ("Please give a correct input below");
     obj.takeGuess();}
  }
  else if (temp.length()!=1)
  {
      if (temp=="hh")
        System.out.println ("giveHint()");
      else 
        {System.out.println ("Please give a correct single-character input below");
         obj.takeGuess();}
  }
  
    System.out.println ( temp);
    System.out.println (guess);
}

I wrote this piece of code but sadly it does not function. the value of guess does not update. Can someone please help me out. I'm an absolute newbie ( 12 yrs. old ). Please explain why this is happening and also please give the updated code if possible. :)

Hangman obj = new Hangman();

This is a method of the class Hangman? This line makes a new Hangman object, with its own set of data, so it's starting from zero each time you call "takeGuess".
That's your main issue here. I think what you're trying to do when you call "obj.takeGuess()" at line 23 is to prompt for a new input if the user enters a multi-character String. What I would do instead would be to wrap the input in a loop which repeats if the input is not valid - in this case, if it's more than one character long.
so, schematically, something like:

boolean done = false;
while (not done)
{
  get input
  if input is 1 character
    do stuff with input and set done to true
  else print "Enter just one character, please" 
    //since you don't set done to true, it remains false, and you go through the loop again
}

Also, and this isn't a bug, just an observation, since you are checking

if (temp.length()==1)

at line 7, you don't need to check

if (temp.length()!=1)

in the else clause at 17. That's implied in the "else": a || !a is always true.

Good stuff, looks like you're doing pretty well - wish I'd learned this much at 12!

Thanks. Can you please refine the code for me? :) I understand what you say. You mean that instead of repeating the takeGuess method all over again, i should just use a loop. But please can you please rewrite this piece of code for me ?

Give it a try - you're doing well so far.

Do you know how to write a while loop?

while (condition)
{
  block of code
}

Where "condition" is an expression that evaluates to a boolean value. Each time the loop starts, the condition is evaluated. If it's true, the code in the curly brackets executes, if not you skip past it.

Im afraid I'm at work, and I have to write my own code - so you'll have to write your own game! :)

commented: Fast reply time.. great polite replies! +0

yes, I know. Thanks for the help.
:) Much appreciated. Thanks-a-lot.

OK... So I did the modification. But it still wont work. Dunno why but using boolean the terminal window won't open at all. As you might see in the logic, I wanted to accept a multiletter input only if it reads 'hint' but still it prints the invalid input message. Any help would be greatly appreciated!

public void takeGuess () throws IOException
{
  
  DataInputStream input = new DataInputStream ( System.in );
  while (done == 1)
  {
  System.out.println ("Enter an alphabet or type in 'hint' for a hint!");
  String temp = input.readLine();
  
  
    if (temp.length()==1)
  {
      guess=temp.charAt (0);
      if ((guess >= 'a' && guess <= 'z') || (guess >='A' && guess <='Z'))
      {
          System.out.println ();
          done = 0;
        }
      else
      {
          System.out.println ("Special Symbols or numbers are not accepted.");
        }
    }
    
    
    else
  {
      if (temp=="hint")
      {System.out.println ("takeGuess()");
          done = 0;
        }
        
      else
      {System.out.println ("Invalid input");
        }
    }
}


done = 1;
System.out.println ("Thanks");
}

I think your problem might be with the use of "==" instead .equals() for comparison of Strings. Try if temp.equals("hint") (or equalsIgnoreCase) and see if that clears it up.

This works!
Thanks for all your wonderful help. Why does '==' operator go wrong on this? Is it not valid to compare strings?

also can I use equalsIgnoreCase with characters ?
I didn't know yet about these methods. Thanks!

Aditya.

To understand this, you have to know a little more about Java than maybe you've picked up so far.
I'll try to make it clear - it's good stuff to understand, it'll actually be important to you in writing good Java code. So:

When you declare an int, call it "n" and give it a value, let's say 17, you're telling the machine to do a few things. First, you tell the machine that you want an area of memory of a certain size (four bytes for an int, eight for a long) and you want that piece of memory to have a name, "n". You want "n" to be treated as an integer: when you put "17" into it, it should store it as a twos complement binary representation of "17", rather than, perhaps, the floating-point representation of "17.0", which is quite different.
When you declare a String, call it "s", and put a value in it, like "foo", you're doing something very different. Now, you're telling the machine to set aside an area of memory, and to put into it a pointer to an address on the "heap" - another area of memory. The address that s points to will contain a lot of data which makes up a String, but when it manipulates s, it's only manipulating the pointer to all of that data. So we have this:

name        stack      heap
int i ->    17   
String s -> address -> "foo"

Now, what is "=="? It turns out that it compares the value of the contents of the memory on the stack, and returns a "true" if they are the same. For an integer, this works as you want it to. If "j" is also an int, and it also happens to be set to the value "17", it and i will have the same value, and so == will return true. But if you have two objects, for example two Strings, there is no guarantee that the will have the same address, even if they have the same value. What == will compare will be the addresses, not the values, so it will return false.

There is a case where you use == for a String, and that's when you're checking if (s == null) { } . What does this tell you about null?

Okay, then what about .equals and .equalsIgnoreCase? Well, these are not operators, they are methods of the String class. What these methods promise to do is to return a true if the object passed as an argument has the same contents as the object on which the method is called, and false otherwise. As consumers of the class, we are not concerned with how they do this, we only care that they return the correct answer in a reasonable amount of time, and since they do this, we use them.

So, in short, the reason '==' does not work here is because it's comparing the wrong thing when you try to use it for Strings.


For a related problem, consider what happens when you try to copy an object by assignment. Suppose I have a class Foo, which has one field, an integer "value", and a getter and a setter for "value".

Now, I do the following:

Foo bar = new Foo();
bar.setValue (17);
Foo baz = new Foo();
baz = bar;
baz.setValue(13);
System.out.println(bar.getValue());

What do I get in the last step? Why?

(you can write the class if you want - the above can go in the main method, and you know how to write the rest, I think - but try to figure out what'll happen before you do.)

import java.io.*;
import java.util.Random;


class Hangman
{

String str="";
int num=0;
char guess;
int done= 1;
String buffer2="";
String buffer="";



public String repository ()
{
  Random generator = new Random();
  String[] array  = { "apple", "apricot","orange", "pear", "plum", "peach",  "watermelon",
                      "banana", "guava", "litchi", "mango", "lemon", "melon", "pineapple",
                      "cherry","strawberry", "grapes", "kiwi", "blueberry", "pomegranate",
                      "figg", "sugarcane", "cucumber", "sapodilla", "pear", "olive",
                      "mulberry", "blackberry"};
  int rnd = generator.nextInt(array.length);
  return array[rnd];
}


public String fruitName ()
{
  str = repository();
  return str;
}


public int countLetters () throws Exception
{
  
  num = fruitName().length();
  return num;
}


public String createBuffer ()
{
 int i=0;
  for (i=1; i<=num; i++)
  {
      buffer = buffer + "-";
    }
return buffer;
}
  
  
public void test () throws Exception
{
  System.out.println (fruitName() + " " + countLetters() + " " + createBuffer() + searchGuess());
  
}


public char takeGuess () throws IOException
{
  
  DataInputStream input = new DataInputStream ( System.in );
  while (done == 1)
  {
  guess='-';
  System.out.println ("Enter an alphabet or type in 'hint' for a hint!");
  String temp = input.readLine();
  
  
    if (temp.length()==1)
  {
      guess=temp.charAt (0);
      if ((guess >= 'a' && guess <= 'z') || (guess >='A' && guess <='Z'))
      {
          System.out.println ();
          done = 0;
        }
      else
      {
          System.out.println ("Special Symbols or numbers are not accepted.");
        }
    }
    
    
    else
  {
      if (temp.equalsIgnoreCase("hint"))
      {System.out.println ("giveHint()");
        done = 0;}
        
      else
      {System.out.println ("No multi-character words are accepted except 'hint'");}
  }
}


done = 1;
return guess;
}


public String searchGuess () throws Exception
{ 
  buffer2="";
  Hangman obj= new Hangman();
  obj.countLetters();
  obj.takeGuess();
  int i=0;
  for ( i=0; i<num; i++)
  {
      if (guess==str.charAt(i))
      {buffer2 = buffer2 + guess;}
      else
      {buffer2 = buffer2 + "-";}
    }
buffer=buffer2;
return buffer;
}

}

okay here's the rest of the code. please read through it and advise me on how to get the result correct in searchGuess().

I'll be reading through what you wrote right now but posted this to stop you from going offline ;) Just kidding. I didn't mean to be rude. :)

For a related problem, consider what happens when you try to copy an object by assignment. Suppose I have a class Foo, which has one field, an integer "value", and a getter and a setter for "value". 

Now, I do the following:
Java Syntax (Toggle Plain Text)
Foo bar = new Foo();
bar.setValue (17);
Foo baz = new Foo();
baz = bar;
baz.setValue(13);
System.out.println(bar.getValue());

What do I get in the last step? Why?

(you can write the class if you want - the above can go in the main method, and you know how to write the rest, I think - but try to figure out what'll happen before you do.)

I did not understand this part. So basically Strings point to a heap of data stored elsewhere and contain only a pointer to this heap? This'll help me for sure!

I don't yet know what getters and setters are coz i am learning java by myself. it will be started in school a year late. If you could tell me what getter/setters are, maybe i'll be able to understand the snippet of code at the end of your post.

Thanks again!

import java.io.*;
import java.util.Random;


class Hangman
{

String str="";
int num=0;
char guess;
int done= 1, counter=0, triesnumber=0;
String buffer2="";
String buffer="";



public String repository ()
{
  Random generator = new Random();
  String[] array  = { "apple", "apricot","orange", "pear", "plum", "peach",  "watermelon",
                      "banana", "guava", "litchi", "mango", "lemon", "melon", "pineapple",
                      "cherry","strawberry", "grapes", "kiwi", "blueberry", "pomegranate",
                      "figg", "sugarcane", "cucumber", "sapodilla", "pear", "olive",
                      "mulberry", "blackberry"};
  int rnd = generator.nextInt(array.length);
  return array[rnd];
}



public String fruitName ()
{
  str = repository();
  return str;
}



public int countLetters () throws Exception
{
  num = str.length();
  return num;
}


public void createBuffer ()  throws Exception
{
 buffer="";
 int i=0;
  for (i=1; i<=num; i++)
  {
      buffer = buffer + "-";
    }
}
  


public void takeGuess () throws IOException
{
  
  DataInputStream input = new DataInputStream ( System.in );
  while (done == 1)
  {
  guess='-';
  System.out.println ("Enter an alphabet or type in 'hint' for a hint!");
  String temp = input.readLine();
  
  
    if (temp.length()==1)
  {
      guess=temp.charAt (0);
      if ((guess >= 'a' && guess <= 'z') || (guess >='A' && guess <='Z'))
      {
          System.out.println ();
          done = 0;
        }
      else
      {
          System.out.println ("Special Symbols or numbers are not accepted.");
        }
    }
    
    
    else
  {
      if (temp.equalsIgnoreCase("hint"))
      {System.out.println (giveHint());
        done = 0;}
        
      else
      {System.out.println ("No multi-character words are accepted except 'hint'");}
  }
}


done = 1;
triesnumber--;
}



public void searchGuess () throws Exception
{ 
  buffer2="";
  int i=0;
  for ( i=0; i<num; i++)
  {
      if (guess==str.charAt(i))
      {buffer2 = buffer2 + guess;}
      else
      {buffer2 = buffer2 + "-";}
    }
buffer=buffer2;
}



public void counter()
{
int i=0; counter = num;
for (i=0;i<num;i++)
{
  if (buffer.charAt (i) == '-')
  counter--;
}
}



public String giveHint()
{
int i=0; 
for (i=0; i<num ; i++)
{
  if (buffer.charAt (i) == 'a' || buffer.charAt (i) == 'i' || buffer.charAt (i) == 'e' || buffer.charAt (i) == 'o' || buffer.charAt (i) == 'u')
  buffer= buffer + buffer.charAt(i);
  else
  buffer= buffer + "-";
  
}
return buffer;
}



public void main () throws Exception
{
System.out.println ( "Welcome to Hangman! Today's theme is fruits!" );
Hangman obj= new Hangman();
obj.repository();
obj.fruitName();
obj.countLetters();
int triesnumber= num + 4;
obj.createBuffer();
System.out.println ( "/t" + buffer );
while (triesnumber>0)
{

obj.takeGuess();
System.out.println ("You guessed" + guess);
System.out.println ("Tries left " + triesnumber + "out of " + (num+4));
obj.searchGuess();
System.out.println ( "/t" + buffer);
obj.counter();
System.out.println ("You guessed " + counter + " out of " + num + " letters.");

}}}

Okay, here is the final program. Everything's working individually but is not working when i call everything inside main and execute the main function :(

This will be the final help I will ask for. Thanks for everything you have done :) If you do give a code please explain it too, like you've always done.

So basically Strings point to a heap of data stored elsewhere and contain only a pointer to this heap? This'll help me for sure!

Yes, a good summary. At some point you'll be interested in knowing that the "heap" and the "stack" are actually areas of memory which the machine handles quite differently, but for the moment, this will get you a good long way.

Now, for the other question, as I say, it illustrates this point in a different way, which is worth seeing even if it seems trivial.
So below I've attached the code that I wrote. It produces one line of output. Look it over and try to determine what that line will be, and then run it and see if you were right.

I don't yet know what getters and setters are coz i am learning java by myself. it will be started in school a year late. If you could tell me what getter/setters are, maybe i'll be able to understand the snippet of code at the end of your post.

There's no better sort of ignorance than that of someone going ahead and trying to learn something. In the best case, it is a continuously increasing ignorance, because everything you learn (that is worth learning) opens you up to multiple areas of things yet to learn, and this is beautiful.

So: getters and setters are the usual terms for methods within a class which get or set the value of a field. More stuffy books will use the terms "accessors" and "mutators" but "getters and setters" are pretty effective words.
You've probably seen these in code you've looked at. A getter typically has the form

public String getName()
{
  return name;
}

where name is a String variable of the class. Another class that needs to know the name of this object can call this like so:

String thatObjectName = thatObject.getName();

and then make use of the String as it likes.

Getters can be more complex, if need be. You might have a getter for a derived value, something implicit in values held in memory but not actually calculated until needed. For this, your getter would actually include the calculation, and return the result. For example if you had a Triangle class and wanted to return a boolean value "isIsoceles", you might either set a variable when the class is constructed, depending on whether the triangle has two equal sides, and return that as a simple getter, or you might instead incorporate that check in the getter itself, so the object doesn't know whether it's iscoceles or not until you ask it - and it won't know afterwards, either! This would be useful, for example, if the Triangle is changing its dimensions, or it might be useful if "isIsoceles" is just one of a number of triangular characteristics that you want to be able to check, but you don't want to set them all up in the constructor - "isRight", "isAcute", "isObtuse", "pointsUpward", whatever. As the number of such features increases, it becomes likely that calculating these on demand would be more efficient than checking them all when the class is initialized, if you assume that only some of them will be checked only occasionally. Of course, in that case, you might set a variable once you've checked it, so you don't have to check it again, but then you have to have another variable to tell you whether the answer is known, and you also have to worry about whether anything's changed since that was known. So that sort of thing can get complex, as your requirements grow more complex.
Yes, I'm giving you far more information than you need. I know that. I think you can use it, though.

A setter is the converse of a getter, it sets the value of a field. Simplest form will be something like

public void setName (String newName)
{
  name = newName;
}

Again, suppose that name is a field of the class at hand, and it's a String. This method sets the value of that field to whatever String happens to come as an argument to this method. This is not exactly how I would write it, typically I would write

public void setName (String name)
{
  this.name = name;
}

but explaining that would take me further afield than I want to go.
So the simplest setter just assigns a value to a field of the class: it tells the class what a certain value should be. Setters often do some sort of validation:

public void setName (String name)
{
  if (name.equalsIgnoreCase("Fido")
    System.out.println("I don't like that name");
  else 
    this.name = name;
}

You might even be kind enough to return a boolean - false if the validation failed, or true if the name was successfully set. This, however, is not standard, and you should make note of it if you offer this feature.

So, returning to the question I posed in the last post, here's the code for Foo.java as I wrote it. Again: what will it do? Why do you think so? And then: what did it do? Why do you think it did that?

public class Foo
{

   private int value;


   public Foo()
   {
   }

   public static void main(String[] args)
   {
      Foo a = new Foo();
      a.setValue(17);
      Foo b = new Foo();
      b = a;
      b.setValue(13);  
      System.out.println("The value of a is " + a.getValue());
   }

   public void setValue(int i)
   {
      value = i;
   }

   public int getValue()
   {
      return value;
   }

}
import java.io.*;
import java.util.Random;


class Hangman
{

String str;
int num;
char guess;
int counter, triesnumber;

String buffer;

Hangman()
{
guess='-';
str="";
num=0;
counter=0; triesnumber=0;
buffer="";
}


public String repository ()
{
  Random generator = new Random();
  String[] array  = { "apple", "apricot","orange", "pear", "plum", "peach",  "watermelon",
                      "banana", "guava", "litchi", "mango", "lemon", "melon", "pineapple",
                      "cherry","strawberry", "grapes", "kiwi", "blueberry", "pomegranate",
                      "figg", "sugarcane", "cucumber", "sapodilla", "pear", "olive",
                      "mulberry", "blackberry"};
  int rnd = generator.nextInt(array.length);
  return array[rnd];
}



public String fruitName ()
{
  str = repository();
  return str;
}



public int countLetters () throws Exception
{
  num = str.length();
  return num;
}


public void createBuffer ()  throws Exception
{
 buffer="";
 int i=0;
  for (i=1; i<=num; i++)
  {
      buffer = buffer + "-";
    }
}
  


public void takeGuess () throws IOException
{
  int done= 1;
  DataInputStream input = new DataInputStream ( System.in );
  while (done == 1)
  {
  guess='-';
  System.out.println ("Enter an alphabet or type in 'hint' for a hint!");
  String temp = input.readLine();
  
  
    if (temp.length()==1)
  {
      guess=temp.charAt (0);
      if ((guess >= 'a' && guess <= 'z') || (guess >='A' && guess <='Z'))
      {
          System.out.println ();
          done = 0;
        }
      else
      {
          System.out.println ("Special Symbols or numbers are not accepted.");
        }
    }
    
    
    else
  {
      if (temp.equalsIgnoreCase("hint"))
      {System.out.println (giveHint());
        done = 0;}
        
      else
      {System.out.println ("No multi-character words are accepted except 'hint'");}
  }
}


done = 1;
triesnumber--;
}



public void searchGuess () throws Exception
{ String buffer2="";
  int j=0;
  for(j=0; j<num; j++)
{
  if (guess == str.charAt(j))
  buffer2=buffer2+str.charAt(j);
  else
  buffer2=buffer2+buffer.charAt(j);
}
buffer=buffer2;
}



public void counter()
{
int i=0; counter = num;
for (i=0;i<num;i++)
{
  if (buffer.charAt (i) == '-')
  counter--;
}
}



public String giveHint()
{
int i=0; 
String rep="";

for(int j=0; j<num; j++)
{
  if (str.charAt (j) == 'a' || str.charAt (j) == 'i' || str.charAt (j) == 'e' || str.charAt (j) == 'o' || str.charAt (j) == 'u')
  rep=rep+str.charAt(j);
  else
  rep=rep+buffer.charAt(j);
}

buffer=rep;
return buffer;
}



public void main () throws Exception
{
System.out.println ( "Welcome to Hangman! Today's theme is fruits!" );
Hangman obj= new Hangman();
//obj.repository();
obj.fruitName();
obj.countLetters();
obj.triesnumber= obj.num + 4;
obj.createBuffer();
System.out.println ( "" + obj.buffer );
obj.counter();
while (obj.counter!=obj.num)
{

obj.takeGuess();
System.out.println ("You guessed " + obj.guess);
System.out.println ("Tries left " + obj.triesnumber + " out of " + (obj.num+4));
obj.searchGuess();
System.out.println (obj.buffer);
obj.counter();
System.out.println ("You guessed " + obj.counter + " out of " + obj.num + " letters.");
if (obj.num== obj.counter)
System.out.println ( "Congrats. You win. Now go and have some fruits like maybe ");
System.out.println ();

}}}

I revised this over and over during 4 hrs. or so and now it works. You are pretty knowledgeable about java! :)

commented: Solved your own problems with only hints towards the solution: good work. +2

This will be the final help I will ask for.

I hope not - presumably you'll keep trying to do new stuff, and running into stuff you don't know.
Looks like it's working now... good job. Carry on.

Thanks for all new info and getting me to understand the concept of each one! :) Can I reply back to this thread to ask you some more things I 'run into'..? ;)

Better probably to mark this one solved - and you did most of the solving, good work! - and ask your new questions in a new thread. That way people can figure out what you're asking, since presumably your new questions won't be about hangman :)

It will return 13. I think so. I will run it after you give a confirmation. At first b's value would be pointing where a is pointing. So they are pointing to the same place. But when value of b is 'changed', the value of a also changes because they are pointing to the same 'heap'. Pls. correct me if i'm not!

Yeah maybe. :/ You're a nice guy. Thanks for all the help.

It will return 13. I think so. I will run it after you give a confirmation. At first b's value would be pointing where a is pointing. So they are pointing to the same place. But when value of b is 'changed', the value of a also changes because they are pointing to the same 'heap'. Pls. correct me if i'm not!

Exactly right - both the result and the reasoning. As I've written that main method, a and b are different names for the same object. This can be quite useful, you'll see later on when you get to things like linked lists, and it can also lead to odd bugs if you're not aware of it.
So what do you do if you want a new Foo object that starts out with the same value as a, but can be set independently of a? There are (at least) two good answers. One does not involve a change to Foo, the other does.

remove static.... for one.
Let me think of the other. :)

maybe use final keyword... not sure.

Maybe you'd like to correct me. ;)

I'm not sure exactly what you mean by those. The only static in the Foo class is the one required for main to be the main method - can't remove that, unless you have another class running it, and that wouldn't change the matter.

What I was thinking was this. If you just want a "Foo" which has to start with the same value as another (and you don't know that value at compile time - say it's dependent on user input) - then the simplest thing would be something like this:

Foo a = new Foo();
      a.setValue(17);
      Foo b = new Foo();
      b.setValue(a.getValue());

This makes a new object, and assigns it the value that a contains. Later on, you can change b or a, and the other will remain as it is.


If you're doing this more often, you might make a method in Foo that returns a Foo object with the same value:

public Foo duplicateMe()
{
  Foo newFoo = new Foo();   // :)
  newFoo.setValue(value);
  return newFoo;
}

now I can call this from outside the class: Foo b = a.duplicateMe(); and it'll do the same thing as the above lines. Why go to the trouble? Well, suppose Foo has a lot more data in it, or suppose some of Foo's data is private and doesn't provide getters. This way I can make available to you (the user of the class) a facility for copying the object which I can promise you does the job correctly (doesn't miss any data) and doesn't require me to write getters for all of my fields - and it's also easier to use, when the body of data goes large.

There are some more ideas lurking just behind this one, of course, but I think this might be a good place to leave it for the moment.

Thanks. I was a bit confused with that. What exactly is static by the way? :)

You do ask the easy questions, don't you? :)
The simple answer:
Static means that the method or the variable it modifies pertains to the class, and not to an object of that class. Static classes and methods don't require that a class be instantiated in order to be used. An static method is accessed by the name of the class - Math.abs() , for example - where trying to access an instance method in this way is an error.


More details:

A "normal" variable (an instance field) belongs to an object. When you create an object, by calling "new Foo()", you reserve an area on the heap for that object and its data. Each Foo object has its own data - remember, we had a Foo "a" and Foo "b" - and its methods act on that data. a cannot change b's data, and b cannot change a's.
Static variables, on the other hand, are shared by all members of the class, and can be read or changed by any object of the class, or by static methods of that class.

Instance methods ("normal" methods) can work on the data of the object they're in, and on static variables of the class they belong to. Static methods can work only on static data, data that belongs to the class as a whole, and they can only call static methods. (obviously, if a static method could call an instance method, then you'd have to know which object's instance of the method was being called, which presents some problems)

One static method that you've probably seen is Integer.parseInt(). This method takes a String as an argument and it attempts to convert that to a numeric representation of its contents. Here we have a method which is useful to have around, and it doesn't depend on any particular data of any particular Integer object, so it might as well be static. If it were an instance method, you'd have to make a new Integer with some spurious value that you don't care about in order to get this functionality.
One could imagine implementing this differently: overloading Integer's constructor so it could take a String, and then forcing the user to create a new Integer object for each String they wanted to convert, but that would create an unnecessary object, which is a drain on resources, so the static solution is the correct one. Java.math is also full of static constants and methods, for the same reason.

You're probably also familiar with some static constants if you've played with the Swing classes at all. Throughout the Swing classes you find that classes take parameters formally as ints, but those ints are always referred to by static constants with appropriate names. So you might find the following method in the javadoc for JTabbedPane:

setTabPlacement

public void setTabPlacement(int tabPlacement)

Sets the tab placement for this tabbedpane. Possible values are:

* JTabbedPane.TOP
* JTabbedPane.BOTTOM
* JTabbedPane.LEFT
* JTabbedPane.RIGHT

The default value, if not set, is SwingConstants.TOP.

Parameters:
tabPlacement - the placement for the tabs relative to the content

The method signature says it takes an int, but you'll see it called as public void setTabPlacement(JTabbedPane.TOP); - you're not likely to ever see the literal number, because it would be confusing unless you happened to know the constants associated with every class in the Swing hierarchy.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.