21

in C# when I want to know if an object is an instance of a particular type or not, I can use "is" operator:

String foo = "hi :)"
if (foo is String) ...

how can I do it in java? (I know I can use try statement, any other way?)

Ganesh R.
  • 4,337
  • 3
  • 30
  • 46
user2136334
  • 648
  • 7
  • 16

6 Answers6

26

Java equivalent:

String foo = "hi :)"
if (foo instanceof String)
rocketboy
  • 9,573
  • 2
  • 34
  • 36
  • 1
    `is` in C# can assign the value to a new instance. `instanceof` seems that only checks for type equality. – ageroh May 21 '21 at 08:01
12

You'd use instanceof - that's the equivalent of is in C#. Note that there's no equivalent of as.

See the JLS section 15.20.2 for more details of instanceof, but it's basically the same as is:

// Note: no point in using instanceof if foo is declared to be String!
Object foo = "hello";
if (foo instanceof String)
{
    ...
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

instanceof is the java equivalent to the C# is operator.

William Morrison
  • 10,953
  • 2
  • 31
  • 48
6

Try something like this:-

String foo = "hi :)"
if (foo instanceof String)
{
 ......
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
5
if (foo instanceof String)

I believe is what you're looking for

jongusmoe
  • 676
  • 4
  • 16
4

In java you can use "instanceof" instead of "is"

String foo = "hi :)"
if (foo instanceof String) 
Marseld
  • 174
  • 5