1

I have seen this code:

Integer statusCode = (Integer)

Strange, this is first time I see this syntax. Can anyone explain this?

Why there is no semicolon at the end of the line?

What does it mean if you put a Type or Class in parentheses?

What is it's benefit to use it like that?

Edit: Some answers mentioned that either the code is incomplete or gives a compile time error but I have tried it it works! Actual code is from this page:https://www.tutorialspoint.com/servlets/servlets-exception-handling.htm

ramazan polat
  • 7,111
  • 1
  • 48
  • 76
  • 5
    Type in parentheses is used for casting. However, the statement is incomplete. Maybe a multi-liner, which would explain the missing semicolon. – jp-jee Oct 03 '16 at 11:24
  • I am pretty sure that it doesn't have a semicolon. Actual code is here:https://www.tutorialspoint.com/servlets/servlets-exception-handling.htm – ramazan polat Oct 03 '16 at 20:18
  • 2
    Like others have guessed, the code you link to has `Integer statusCode = (Integer) NEWLINE request.getAttribute("javax.servlet.error.status_code");`, i.e., it's split over 2 lines. Java sees that as if it was on one line. So it takes the result of `request.getAttribute(...)`, casts that to `Integer`, and assigns it to the `statusCode` variable. – Robert Oct 03 '16 at 20:45

2 Answers2

2

Indeed, syntax that you have mentioned will cause an compile time error. However, what you have mentioned is an example of type casting but it do require a value that will be converted using type casting.

for example:-

Integer val = (Integer) 2;
deepansh2323
  • 261
  • 1
  • 8
  • Unfortunately it does NOT cause an error, it works. Check here:Check this page:https://www.tutorialspoint.com/servlets/servlets-exception-handling.htm Copy-pasted the code and it actually works without any error. – ramazan polat Oct 03 '16 at 20:24
  • 1
    Link you have mentioned contains syntax for Type casting in multi-liner. See next line, it do contain complete statement. Cheers !! – deepansh2323 Oct 06 '16 at 06:46
  • Just realized that. – ramazan polat Oct 07 '16 at 08:09
1

This code is not valid and will cause an error.

A type or class in parentheses is used for casting a object:

Object o = "str";
String str = (String)o;

Example from: https://stackoverflow.com/a/5289493/4585226

A benefit of casting is that you can use it as the type/class you are casting it to. Like in the example showed in this answer.You can use the object as a string now.

Community
  • 1
  • 1
476rick
  • 2,764
  • 4
  • 29
  • 49
  • Check this page:https://www.tutorialspoint.com/servlets/servlets-exception-handling.htm Copy-pasted the code and it actually works without any error. – ramazan polat Oct 03 '16 at 20:23