Final vs const

What is the difference between final keyword and const keyword.
as per my knowledge,
1. final - that doesnt change
2. const - same as final?
where the const keyword is used in java

Sun's tutorial "Nuts and Bolts" has a list of
keywords
http://java.sun.com/docs/books/tutorial/java/nutsandbo
lts/_keywords.html
Check out what it says about const.I checked that, but it lists only keywords, not
explainingNo its clearly mentioned there that const keyword is not used. See the * symbol and what is written about that symbol at the bottom

Similar Messages

  • 'private static final String' constants vs inline constants

    Other than source code readability and maintainability, is there any runtime benefit from declaring String constants as 'private static final' in your code? Does this effect the way the String is stored in memory in the constant pool?
    Thanks, Kevin

    I guess my question really is, is this String declared inline:
    System.out.println("some constant");treated any different internally in memory at runtime compared with this:
    System.out.println(SOME_CONSTANT);
    private static final String SOME_CONSTANT = "some constant";Since both Strings end up in the Constant Pool, how is declaring it 'static final' of any benefit in terms of performance?

  • Imposing constraints - final & (const?)

    Hi
    i'm looking to impose a unique identifier on a class (for an inventory system) and according to a previous exam question there are two ways of applying such a constraint.
    I had thought it was final or const but on further research i understand that const is reserved but not used. I'm confident that final is one of the ways..
    Any ideas? Greatly appreciated

    Hi
    i'm looking to impose a unique identifier on a class
    (for an inventory system) and according to a previous
    exam question there are two ways of applying such a
    constraint.
    Can you please expand upon what it is that you are looking for? For example do you really mean class or do you mean instance? And what do you mean by "impose"?

  • Getting constants from .h files in Java

    Hi all,
    if we have a .h file with a number of constants that we wish to use in some Java source code, is it possible to get these values without having to redefine them in Java?
    I'm thinking along the lines of using JNI to read the file and get the values and using them when needed.
    E.g.
    in a .h file I have
    const int A_CONST = 0;
    const int B_CONST = 1;and I want to have a Java source file which can do something like;
    System.out.println("the value is "+A_CONST);Is this possible or would I have to read the file as ordinary text?
    Regards,
    John

    $ cat a.c
    #define const private final static
    const int A_CONST = 0;
    const int B_CONST = 1;$ gcc -E -P a.c
    private final static int A_CONST = 0;
    private final static int B_CONST = 1;

  • How do I pass local final variable value to global variable.

    Hi,
    In my code, I need to pass the local final string varibale value to the global variable for further usage. I know final is constant and inside the braces it can't be modified or assigned to other. Help needed in this regard or how do I re-modify the code according to my requirement i.e assigning the final string variable value to the outside of that block.I need the value of final String variable to be available in the process method outside of the specified block.
    class HostConnection{
    public module process(){
         HostKeyVerification hkv = new HostKeyVerification() {
              public boolean verifyHost(String hostname,SshPublicKey key) {
    final String keyfingerprint = key.getFingerprint();               return true;
    Thanks
    Sri                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    SriRaj wrote:
    It seems to be by-default all varibales in the inner calss method are Final.This is not true. Try this:
    class SomeClass {
      public void method() {
        Runnable runnable = new Runnable() {
           public void run() {
              int i = 0;  // new inner-class variable
              i = i + 1;
              System.out.println(i);  //prints "1"
    }But you obviously can't do this:
    class SomeClass {
      public void method() {
        Runnable runnable = new Runnable() {
           public void run() {
              int i = 0;  // new inner-class variable
              i = i + 1;
              System.out.println(i);  //prints "1"
        System.out.println(i); //compiler error: "i" is undefined
    }Because you are declaring i in an inner class. If you want to access the value of i outside that inner class, you'd have to do this:
    class SomeClass {
      private int i;
      public void method() {
        Runnable runnable = new Runnable() {
           public void run() {
              int i = 0;  // new inner-class variable
              i = i + 1;
              System.out.println(i);  //prints "1"
              SomeClass.this.i = i;
        System.out.println(i); //no compiler error
    }If this doesn't answer your question, please try to post an actual question, along with your real code, and any compiler errors you are getting, word for word.

  • Related with Final Keyword...

    Hi,
    I written the following code to iterate over an array :
    for(final int i:arr)
    System.out.println(i);
    }

    jschell wrote:
    I really doubt that the compiler doesn't erase the final part.
    It is a compile time rather than run time check.Runtime as well, it seems.
    public class Final {
      public static final int i = 999;
    public class FinalChanger {
      public static void main(String[] args) {
        Final.i = 123;
        System.out.println(Final.i);
    }1) Compile both without the final keyword in Final.java
    2) Put final into Final.java, and recompile.
    3) Run javac -cp . FinalChanger
    Exception in thread "main" java.lang.IllegalAccessError
            at FinalChanger.main(FinalChanger.java:3)
    :; javap -s -c -verbose -classpath . Final
    Compiled from "Final.java"
    public class Final extends java.lang.Object
      SourceFile: "Final.java"
      minor version: 0
      major version: 50
      Constant pool:
    const #1 = Method       #3.#14; //  java/lang/Object."<init>":()V
    const #2 = class        #15;    //  Final
    const #3 = class        #16;    //  java/lang/Object
    const #4 = Asciz        i;
    const #5 = Asciz        I;
    const #6 = Asciz        ConstantValue;
    const #7 = int  999;
    const #8 = Asciz        <init>;
    const #9 = Asciz        ()V;
    const #10 = Asciz       Code;
    const #11 = Asciz       LineNumberTable;
    const #12 = Asciz       SourceFile;
    const #13 = Asciz       Final.java;
    const #14 = NameAndType #8:#9;//  "<init>":()V
    const #15 = Asciz       Final;
    const #16 = Asciz       java/lang/Object;
    public static final int i;
      Signature: I
      Constant value: int 999
    public Final();
      Signature: ()V
      Code:
       Stack=1, Locals=1, Args_size=1
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   return
      LineNumberTable:
       line 1: 0
    :; javac -version
    javac 1.6.0_06
    :; java -version
    java version "1.6.0_06"
    Java(TM) SE Runtime Environment (build 1.6.0_06-b02)
    Java HotSpot(TM) Client VM (build 10.0-b22, mixed mode)

  • Static final buffer passed into FilterOutputStream.write(byte[])

    Greetings,
    My team is using a custom subclass of FilterOutputStream to XOR some bytes with a key before writing them to an underlying OutputStream. We have never had problems with it until we started testing with Java 1.4.x -- where we noticed that some optimizations had been made to GZIPOutputStream to write the GZIP header out at once using a static final buffer to hold the header.
    The problem seems to be that this header, although marked as static final, can still be changed when it is passed to our custom FilterOutputStream's write(byte[] b) method. For speed, we are XORing the bytes in place in the byte[] and then writing it directly back out. So every time we write the header with the same key, the static final byte[] that holds the header in GZIPOutputStream changes from its XORed to cleartext equivalent, and back.
    My question is this: should this be considered a bug in the SDK, or a bug in our code? Maybe I'm looking in the wrong place, but I can't find any documentation that specifies what can and can't be done with a byte[] that is passed into the write(byte[]) method of an OutputStream.
    Any input is appreciated.
    Regards,
    Mike Pontillo

    Mike,
    Need some code here to clarify. Are you saying that
    the original final static (constant) changes?
    You've got to be careful when you talk about passing a
    byte[], which can't be done, of course. You are
    passing a reference to a byte[]. Using the reference,
    the bytes can be copied. There aren't any restrictions
    on what can be done to the copy.
    and also, if you have final array, then only that arrays'
    reference is final, but the content of array may change
    as well as when that array wasn't static.Yes, I understand this. Thank you for your replies. FilterOutputStream.write(byte[]) of course takes a reference to a byte[]. We are overloading this to be something like:
    public void write(byte[] b) {
       for(int i = 0 ; i < b.length ; i++) {
          b[i] = foo(b);
    out.write(b);
    i.e. we modify the array inside the method rather than making a copy and writing out the copy.
    This hasn't been a problem until Java 1.4.x -- now GZIPOutputStream passes a private static final byte[] (reference of course) into write(byte[]) in OutputStream. So when our overloaded write(byte[]) method gets called in FilterOutputStream and code similar to the above runs, the private static final reference to a byte[] is overwritten in the java.util.zip.GZIPOutputStream class. This was a change sometime between 1.3 and 1.4, I believe. From the J2SDK 1.4.1_02 source:
         * Writes GZIP member header.
        private final static byte[] header = {
            (byte) GZIP_MAGIC,                // Magic number (short)
            (byte)(GZIP_MAGIC >> 8),          // Magic number (short)
            Deflater.DEFLATED,                // Compression method (CM)
            0,                                // Flags (FLG)
            0,                                // Modification time MTIME (int)
            0,                                // Modification time MTIME (int)
            0,                                // Modification time MTIME (int)
            0,                                // Modification time MTIME (int)
            0,                                // Extra flags (XFLG)
            0                                 // Operating system (OS)
        private void writeHeader() throws IOException {
            out.write(header);
        }As you can see, they are passing a private static final reference to a byte array into somebody's untrusted method (ours). =)
    Due to this issue we have to change our code so that it makes a copy of these bytes rather than changing them in the method. Now I'm wondering if this should be considered a bug in Java or not -- does changing bytes like this violate the general contract of an Input/Output stream? It at least seems like a bad idea for encapsulation purposes since anyone can change these bytes in the GZIPOutputStream class. We had previously assumed that if they were writing these bytes to an output stream they didn't care about them any more, which is the case 99.9% of the time in our experience.

  • PI 7.1 Adapter Module - meaning of VERSION_ID and serialVersionUID?

    Hi!
    I am currently developing my first PI Adapter Module. In SAP sample coding GetHostName I find the following declarations and I ask me what's the meaning and/or purpose of these declarations:
    public static final String VERSION_ID = "$Id://tc/aii/30_REL/src/_adapters/_sample/java/user/module/GetHostName.java#1 $";
    satic final long serialVersionUID = 7435850550539048631L;
    And additionally how I have to declare these two variables for my adapter module ... This comes true especially for VERSION_ID, because serialVersionUID can be generated by NWDS using quick fix feature. It then declares such a variable ...
    Thanxs for any hint in advance!
    Regards,
    Volker

    Hi Pavel,
    public - this is the visibility modifier (it means that the body method can be call by any outside method)
    static - the method is a static instance of the class. Not sure what exactly it does though.
    final indicates that the value of the variable won't change - in other words, a variable who's value can't be modified after it is declared.
    Use public final static String when you want to create a String that belongs to the class (no instance necessary to use it), and that won't change, for instance when you want to define a Stringconstant that will be available to all instances of the class, and to other objects using the class, depending on the access modifier:
    public final static String MY_CONSTANT = "SomeValue";  // ... in some other code, possibly in another object, use the constant: if (input.equals(MyClass.MY_CONSTANT)
    All the variables are implicitly public static final in a Java Interface.
    Is it a good coding practice to use public static final in constant variable although it is declared inside an Interface.
    For example :
    public interface TestInterface{  public static final String EX_CONSTANT = "ABC"; public static final int EX_INT_CONSTANT = 5; public static final double EX_DOUBLE = "5.0"; public static final Integer EX_INTEGER = 10;  }
    Refer below links
    http://scn.sap.com/community/pi-and-soa-middleware/blog/2012/09/24/setting-queue-dynamically-using-adapter-module
    http://f0j00fec.benxbrain.com/en(bD1lbiZjPTAwMQ==)/index.do?onInputProcessing(brai_object_thread)&001_threadid=89626&001_boardtype=01&sysid=PI1&pgmid=R3TR&object=DTEL&obj_name=VERSION_ID&child_param=
    Hope it will helpful..
    Regards
    Bhargava krishna

  • Create tab seperated file on application server

    Hi all
    I need to create a file with Tab separation. I have a solution on a 4.7 system as shown below. But this does not work on a 4.6 system as the class does not exist.
    How can I do this on a 4.6 system?
    Thank you four your reply.
    Herbert
    CONSTANTS c_tab  TYPE c VALUE cl_abap_char_utilities=>horizontal_tab.
        LOOP AT t_material.
          CONCATENATE
            t_material-id
            t_material-brand
            t_material-desc
            t_material-level
            t_material-flag
         INTO w_line
            SEPARATED BY c_tab.
          TRANSFER w_line TO w_file2.
        ENDLOOP.

    do this way...
    Table to store final data
    CONSTANTS: cns_09(2) TYPE n VALUE 09,
               c_val1 TYPE c VALUE 'X'.
    DATA: g_deli(1) TYPE c.
    table to place delimiter
    DATA: BEGIN OF it_hex,
            tab TYPE x,
          END OF it_hex.
    ASSIGN g_deli TO <fs> TYPE c_val1.
    it_hex-tab = cns_09.
    <fs> = it_hex-tab.
    LOOP AT t_material.
    CONCATENATE
    t_material-id
    t_material-brand
    t_material-desc
    t_material-level
    t_material-flag
    INTO w_line
    SEPARATED BY g_deli.
    TRANSFER w_line TO w_file2.
    ENDLOOP.

  • JSTL Problem with attribute names

    (Sorry for double posting. I've asked this question on javaranch, but did not get any answer. So I hope you can help me.)
    The values I pass (request.setAttribute etc.) from my servlet to my JSP pages have often dots in their names like "my.variable" (Assume for the following that my.variable justs holds the String "hello").
    I want to use <c:out > to print the value of "my.variable". Obviously the naming scheme collides with the expression language ("my" is not an object and certainly does not have the getter getVariable). Is there a way to work around this problem?

    What? Why do you consider it a bad way? It's the only
    naming scheme I know!
    It's pretty straight forward to use the package name
    to make your attribute names unique. See either Struts
    or Java Petstore (org.apache.struts.Globals or
    com.sun.j2ee.blueprints.waf.controller.web.util.WebKeys
    as an example.Btw those Globals and WebKeys, are static finals or constants.
    this is something completely different, and if you would really look good in stead of refusing some friendly advice you'll see that indeed the packages are separated with a . and the variables are with a _
    so calm down and try to listen what we say.
    If you give to java a x.y he'll thing y is a method of x or that y is a class in the package x
    ok?
    greetings

  • 4 basic java questions..

    ok so I already learned Java last year (in grade 11), but my teacher didn't really teach anything, we learnt everything by ourselves from the API... so theres a lot of things I actually don't understand, but for now I want to ask 4 basic questions:
    1. What does static mean?
    2. Why would u "final" a constant variable? ie. If you have a variable called SIZE which is set to 5, so if u want it to be a constant, just never change its value. But what does the keyword final do to it?
    3. What's super? I see it sometimes, and my teacher showed us in the applet exampls to use super.paint(g) or somethign like that for the paint method, but I never use that because I noticed it works fine without it..
    4. Whats a question mark? I saw a game that was made in java and it had a lot of places where it had a question mark , which was part of the syntax. For example,
    int j1 = i != 0 ? i - 1 : 199;
    OR
    JUMPVEL = (fSuperSlime) ? 65 : 31;
    I really don't understand these lines...
    feel free to answer any of these questions...

    wow cool...thanks.. that question mark thing is nice
    saves a few lines..
    now, about super, so u mean u can access the parent
    class's variables?Variables, methods, constructors, if the access level is such that it's allowed.
    This will be covered in any tutorial or text though.
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.
    James Gosling's The Java Programming Language. Gosling is
    the creator of Java. It doesn't get much more authoratative than this.

  • Widening conversion bugs ?

    I dont understand .. (from A Programmer's Guide to Java Certification 3rd Edition - mughal pg 172)
    a) this work
    Integer iRef3 = (short)10; // constant in range: casting by narrowing to short,
    // widening to int, then boxing
    b) final short x = 3;
    Integer y = x;
    this work but not this.
    short x = 3;
    Integer y = x;
    The 'final' means constant expression which is used for implicit narrowing conversion. The 2nd one is not narrowing conversion so why the 2nd one didnt work?
    c) Exactly as a) but instead of Integer .. i use Long. // This doesnt work
    Long iRef3 = (short)10;
    c) This also doesnt work unless i put the final on short
    short s = 10; // narrowing (a)
    Integer iRef1 = s; // short not assignable to Integer -- error here (b)
    Since implicit conversion succeded for (a) and you dont need constant expression for widening conversion (b) .. why it doesnt work on (b).
    I thought the variable s would be widen to int and then boxing into Integer.
    Any help is appreciated
    Edited by: yapkm01 on Jul 16, 2009 9:32 PM

    A type conversion from long to float is
    commonly called a widening conversion and thus legal.
    I understand that the range of float variables
    is wider than that of long variables.
    However, a long variable can hold about 4
    billion (2^64) distinct integer values. How could
    these possibly all be represented by a float
    variable that uses only 32 bits - and thus can only
    represent 2^32 distinct values. The mantissa of a
    float variable actually uses even less bits -
    only 23.
    So, while any value of a long variable will
    fall within the range of a float variable,
    occasionally approximation should occur and
    information get lost.
    Why is then usually said that widening conversion
    doesn't lose information?Mathematically, a float's bigger. You do lose precision, though.
    What's your point?

  • Changing SIgn for Amount field

    Hi:
    We have a requirement where we need to change +/- sign on amount field in Infocube during the data loading. How this can be done?
    Thanks

    Hi Sunil,
    In the update rules, in the key figure you want, instead of assigning a source key figure from communication structure (first option), select the formula  and press create. Name your formula, and then, in the formula editor, double click your key figure so it appears in the upper part. Then press the * button. and finally press constant button and enter -1 in the text box it appears. This should do it.
    Hope it helps.
    Regards,
    Diego Lombardini

  • Initialization of the static variable

    When does it happening; Is it happening during the compilation time or when the class is loaded or when the first instance of the class is created?
    can't find it anywhere in docs

    There's one common gotcha with static fields. Compile and run this code:
    public class One {
        public static final int CONSTANT = 17;
    public class Two {
        public static void main(String[] args) {
            System.out.println(One.CONSTANT);
    }You get the output 17 -- no surprise. Now edit One.java and change that value to 42, say, and
    carefully only recompile One.java. (You may not want to do this
    in an overly helpful IDE!) When you run Two again, you will still see 17!
    To avoid this, you can use a static initializer:
    public class One {
        public static final int CONSTANT;
        static {
            CONSTANT = 42;
    }

  • Good, cheap, non-tomcat servlet container?

    Specifically, not using the Jasper jsp compiler, as it can't be counted on to recompile a changed .jsp (see http://issues.apache.org/bugzilla/show_bug.cgi?id=33453). I am frustrated with Apache software quality and (lack of)support, and searching for alternatives to Tomcat. It would also have to either work with JBoss or include an EJB stack with similar functionality to JBoss.
    I have looked at Sun Application Server, which appears to use Tomcat in its entirety, and Jetty, which uses Jasper.

    Here's a quote from Resin ML archive:
    <quote>
    From Resin users ML archive:
    Q:
    I have a general question about the most effective way to process JSP page
    updates.
    My impression of the JSP engine is that in the event of a change to the JSP
    file (changed file modification date), the JSP page is automatically
    recompiled and reloaded. This is a great feature -- it means you have the
    flexibility that is often found in interpreted languages like Perl in terms
    of not having to restart the server when changes are made.
    Unfortunately for me, that flexibility breaks down when I start including
    JavaBeans, or other Java classes into my JSP pages through the "import"
    directive. There doesn't seem to be any way to make a JSP page also
    dependent on another external class file, and to force recompilation if
    that external class file
    Here's an example...
    start of file MyJSP.jsp...
    <@ page language=java
    import="com.mycompany.MyClass,caucho.sql.db.*,java.io.*" />
    ....some JSP code mixed with HTML....
    end of file MyJSP.jsp
    For the above JSP file, the servlet engine doesn't seem to recognize that
    the JSP page is dependent on the file "com.mycompany.MyClass". If I make
    any changes to the file MyClass.java and recompile, the changes won't take
    effect until I restart the servlet engine.
    Any thoughts on how to make a JSP file explicitly dependent on another
    external file?
    I suppose you could try to use a utility like make to help manage
    dependencies, but this gets ugly -- especially for compiled JSP page
    servlet classes which are temporary anyways. Any suggestions for a solution
    to this problem?
    ----- Bryan Bunch
    A:
    You don't actually need to recompile the JSP pages, you just need them
    reloaded. JSP pages are just like any other Java classes; you usually can
    compile classes independently. The only case where you need the JSP pages
    recompiled is if you change 'final static' constants.
    If your classes are in the global classpath, there's nothing Resin can do. I
    don't know how you're loading your classes like com.mycompany.MyClass.
    However, you can put them in WEB-INF/classes or in a jar in WEB-INF/lib. When
    any class/jar in either changes, Resin will reload the entire application
    including any JSPs. I'm pretty sure this is what you want.
    Resin lets you add to the auto-update class path. Here's how:
    <http-server>
    <classpath id='/home/myhome/ws/classes'/>
    <classpath id='/home/myhome/ws/myjar.jar'/>
    </http-server>
    If any of the classes in /home/myhome/ws/classes changes, Resin will reload
    the application just like it reloads a JSP.
    If you're really daring, you can have Resin compile your beans for you.
    (There are a few important bugs fixed in the latest snapshot, so you would
    want to use the snapshot.) That way, you get auto-compilation and
    auto-loading of your beans when you change any Java source. This is certainly
    helpful for small test cases, but it can get confused for large projects.
    <classpath id='/home/myhome/ws/classes' source='/home/myhome/ws/src'/>
    -- Scott
    </quote>

Maybe you are looking for

  • Smart Playlist Problems (Since Ver 5)

    I have come across a problem, which I believe started when I installed Version 5. I have many SMART playlists set up that are really for my iPod usage. They are set to pick certain tracks that have not been heard in xxx amount of days, and usually se

  • Passing date range parameters in MDX Query

    Following is my mdx query SELECT NON EMPTY     [Measures].[Cache Attendees Count] ON COLUMNS, NON EMPTY     ([Cache Attendees].[Visit Id].[Visit Id].ALLMEMBERS *     [Cache Attendees].[User Id].[User Id].ALLMEMBERS *     [Cache Attendees].[Screen Nam

  • IPad Air- PDFs in Safari are black pages. How can I read them?

    I've had my iPad Air a month, and couldn't open PDFs in Safari; they appeared as black pages. I downloaded Adobe Reader from the App store, but it made no difference. The advice given here all seems to relate to Mac OS, not iOS. The iPad is my only c

  • ERPI logs folder  in 11.1.2.2

    Hi All, where  can we find ERPI 11.1.2.2 logs Thanks,

  • Creating a SP 2010 farm

    Hi, We have a staging environment which is a farm and We want to create a new production farm for share point 2010.(This farm is for Internet sites(public sites). not for Intranet as of now) Can I know how do I know how many servers do we need (i mea