• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

final keyword on variables

 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Test8{
public static void main(String a[]){
byte b = 1;
char c = 2;
short s = 3;
int i = 4;

c = b; // 1
s = b; // 2
i = b; //3
s = c * b; //4
}
}
Which of the following are correct?
Error at 1
Error at 4

but here....

public class Test9{
public static void main(String a[]){
final byte b = 1;
char c = 2;
short s = 3;
int i = 4;

c = b; // 1
s = b; // 2
i = b; //3
s = c * b; //4
}
}
which of the following are correct?
error at 4.

can someone explain me the use of final here???
 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


from the JLS 4.12.4:

"We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (�15.28) a constant variable."



Note that if you leave off the initializer (= 1) you have a blank final, which is different.


final byte b = 1;



b is now a constant expression with a value known at compile time.

so, at 1 in the second example, it's exactly the same as putting "c = 1;"
at 4, you have a type mismatch error because of c.

but consider:


In this case, both c and b are known compile time constants.
 
arivu mathi
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks for your reply Peter....
can u throw some more light on what is the difference between c=b in both examples?
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
5.2 Assignment Conversion may also help you.
reply
    Bookmark Topic Watch Topic
  • New Topic