• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Bear Bibeault
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • salvin francis
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Jj Roberts

Return Type

 
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a Dan Chisholm question on Return Type, but I fail to understand the answer given for it.
Code :
class JSC201 {
static byte m1() {
final char c = '\u0001';
return c; // 1
}
static byte m3(final char c) {return c;} // 2
public static void main(String[] args) {
char c = '\u0003';
System.out.print(""+m1()+m3(c));
}}
The answer is:
Complile-time error occurs at 2, the reason being, char c is not a compile-time constant, whereas1 works fine, because here c is a complile-time constant.
My question
In the following expression in the above code
static byte m3(final char c) {return c;}
We declare c as final, in the expression,
m3(final char c),
thus making it a compile time constant, than to it gives a compile-time error,why is it so ?.
 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,


static byte m3(final char c) {return c;}


c here is a constant but not a compile time constant. The Compiler does not know what the value of c will be when you compile it; you may well pass a value like the following later somewhere in your code.

Which will definitely not fit in a byte variable when m3 tries to return that value
Thanks,
Sindhur.
 
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I change it to this

I don't get any error. So the problem is not in the final keyword but in type mismatch.

HTH,
B.
 
Hey, I'm supposed to be the guide! Wait up! No fair! You have the tiny ad!
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic