1

I need to write a new method that checks if certain values are of the type String or not.

I have two objects and I want to be able to check if these two objects are strings, if they are to then return true, and false otherwise.

I did start off with the following method:

public boolean stringTest()
{  
    boolean aString;
}

But could not get anything to work after that, any help would be greatly appreciated!

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Joe
  • 4,877
  • 5
  • 30
  • 51
  • These two variables already are `String`'s. If you have an `Object` variable you can check, whether it is a `String` class instance via `myObj instanceof String` –  May 09 '16 at 18:19
  • I do apologise, I've misread the question. It is indeed an object that I am checking! – Joe May 09 '16 at 18:27
  • what do you mean by string? do you mean don't have numerical characters in it(and ofcourse that is not the definition of string)? – Alikbar May 09 '16 at 18:28

2 Answers2

4

You can make use of instanceof and rewrite your method

public boolean stringTest(Object any)
{  
   return any instanceof String;

}

then

stringTest(townName); // true
stringTest(new Integer()); // false
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Use instanceof:

public boolean isString(Object o) {
    return o instanceof String;
}
Zircon
  • 4,677
  • 15
  • 32