Final static array declaration

Hi,
I recently discovered i can do this
  protected static final float[] COLOR_BUTTON_FRAME_OUTLINE = { 0.5f, 0.5f, 0.5f };rather than
  protected static final float[] COLOR_BUTTON_FRAME_OUTLINE = new float[] { 0.5f, 0.5f, 0.5f };is there a difference or is it just a shortcut?

just so you now, it only works when the variable is declared and defined simultaneously. I.E.
int[] a = { 0, 1, 2 };works, but
int[] a = whatever;
a = { 0, 1, 2 }; // redefine adoes not. For that you must do
int[] a = whatever;
a = new int[] { 0, 1, 2 }; // redefine a

Similar Messages

  • URGENT: Declaring Static Array after runtime

    Hi All
    Hope you can help me with this problem. I need to create a static array that can be used by other classes. I have declared the object in the beginning of the class, but I can only know the size after executing a method that is in that class.
    When I then try to create the object I get a NullPointerException when I run the program.
    THUS, how do I create a static array if I only know the size after the class is running?
    Hope you can help me
    COMLINK

    Are you suggesting that the following doesn't work for you?
    class MyClass{
        static String[] myStaticArray;
        public MyClass(){
        static void setArraySize(int size){
            myStaticArray = new String[size];
    }or are you trying to access the myStaticArray variable before you have set it to an actual array (i.e. using newString[size])?
    If the later, then you may need to use lazy initialization and access the array through a static getMyArray() function that tests for null, then populates the myStaticArray variable properly before returning it.
    - K

  • Methodology Question: Initializing Static Arrays

    After almost gnawing my arm off in frustration, I finally stumbled onto how to go about initializing and populating a static array that's outside of my Class's constructor (by placing it inside of a static block). My problem is, I just don't understand why I needed to do it that way. My code started out as such:
    public class Parameter {
         private static appEnvironmentBean[] appEnvironment = new appEnvironmentBean[8];
         appEnvironment[0].setMachineIP("192.168.1.100")
    }and this kept throwing an error " ']' expected at line ###"
    so I changed it to this:
    public class Parameter {
         private static appEnvironmentBean[] appEnvironment = new appEnvironmentBean[8];
         static {
         appEnvironment[0].setMachineIP("192.168.1.100")
    }and it worked. Now my problem is, I'm assigning a literal, and I declared the Bean array as static, so the way I see it, there was no reason to throw assignments to the array inside of a static block. I'll take it as a "That's just the way it is" thing, but if someone out there could explain the reasoning behind having to put my assignments inside of a static block, it would really be appreciated.
    Thanks!

    Because if you didn't put it inside a static block you'd be attempting to execute code outside of a method which is illegal except for initialization.
    I think you could do it this way:
    private static appEnvironmentBean[] appEnvironment = {
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100"),
      new appEnvironmentBean().setMachineIP("192.168.1.100") };it depends on whether setMachineIP returns an appEnvironmentBean.

  • Array declaration problems

    hi
    i am having problems with my array declarations
    import java.io.*;
    public class bubbleSort4{
      public static void main (String []args) throws IOException{
        BufferedReader input=new BufferedReader (new FileReader("numbers.txt"));
        for (int blah=0; blah<0; blah+=1 ){
        int array1[];
        array1[blah]=Integer.parseInt(input.readLine());
        }//end of for
        input.close();
        bubbleSort4(array1);
      }//end of main
    public static void bubbleSort4(int[] array1) {
      int newLowest = 0;            // index of first comparison
        int newHighest = array1.length-1;  // index of last comparison
        while (newLowest < newHighest) {
            int highest = newHighest;
            int lowest  = newLowest;
            newLowest = array1.length;    // start higher than any legal index
            for (int i=lowest; i<highest; i++) {
                if (array1[i] > array1[i+1]) {
                   // exchange elements
                   int temp = array1; array1[i] = array1[i+1]; array1[i+1] = temp;
    if (i<newLowest) {
    newLowest = i-1;
    if (newLowest < 0) {
    newLowest = 0;
    }//end of if
    } else if (i>newHighest) {
    newHighest = i+1;
    }//end of else if
    }//end of if
    }//end of for
    }//end of while
    }//end method bubbleSort4
    }//end of class
    i get the error where i call the bubbleSort4 method with the array1 in brakets, it says that it doesnt recognize the variable. i know thats because i declared it in the for loop, but when i declare the array outside the for loop, it says that it was not initialized when i use it in the for loop. a vicious cycle. lol. so please, someone help....

    int array1[];you must initilize the array1
    example :
    int [] array1 = null;or
    int [] array1 = new int [10];
    for (int blah=0; blah<0; blah+=1 ){the codes will never go into the above for loop since
    blah always >= 0;

  • Accessing a Static Array in one CAP file from another CAP in same project

    Hi all,
    I have been developing a banking application on JavaCard. So the size of the applet has grown size able and have now split the file to multiple CAP files. I have been using NXP JCOP plugin in Eclipse for development. Below are the steps done
    a.) I have created multiple packages under the same project where one project has all the variable which are public static final and don't reference any other class. Also this package does not extend Applet. So it finally generates to a CAP file.
    b.) Another package which imports the above package and also extend Applet is the one which has all the UI and logic related to the project. The applet uses the static array defined in the another package to show the menu on phone.
    Now the problem is that when the code come to point for fetching the menu data, i have some thing like menu.length . But when the code comes to this point in debugger i get a
    +6F 00    Status: No precise diagnosis.+
    To cross check i put a watch on the menu variable and found that it has all the data required for showing the menu (which is of 32 byes). So now i am perplexed on why this length is giving this problem. Am i doing some thing wrong. Below is the Snip of the larger code
    This code is the package which has all the constants..
    package constantsPack;
    import javacard.framework.APDU;
    import javacard.framework.ISO7816;
    import javacard.framework.JCSystem;
    import javacard.framework.Util;
    public class ConstantsApplet {
    //menu array decleration
    public static final byte[] MAIN_SETUP_MENU = {
                       (byte) 0x81,  ConstantsApplet.CMD_DTL_LENGTH, ConstantsApplet.CMD_NUMBER, ConstantsApplet.MAIN_CMD_SET_UP_MENU, (byte) 0x00,
                       (byte) 0x82, (byte) 0x02, ConstantsApplet.DEVICEID_SIM, ConstantsApplet.DEVICEID_ME,
                       (byte) 0x85, (byte) 0x08 ,'A','B', 'C',' ','A','p','p','s',
                       (byte) 0x8F, (byte) 0x0D, ConstantsApplet.SB_MENU, 'A','b','c','d','e','f','g',' ','B','a','n','k',
    // other constants.
    }This is the package which has the applet and which uses the variables of the above package
    package myPkgLib;
    import constantsPack.*;
    import javacard.framework.APDU;
    import javacard.framework.Applet;
    import javacard.framework.ISO7816;
    import javacard.framework.ISOException;
    import javacard.framework.OwnerPIN;
    import javacard.framework.Util;
    import javacard.framework.JCSystem;
    public class myApplet extends Applet{
    // other code
    fetch(ConstantsApplet.MAIN_SETUP_MENU.length);
    }Any help regarding this would be very helpful...
    Regards
    Prakash
    Edited by: prakash on Apr 18, 2012 11:57 PM

    Hi lexdabear,
    I tried putting a function inside the library package where the static array is present, but the results are the same... Also by try catch . what exception you want to catch... i see Exception has just .equal function... Tried with ExternalException also but does not seem to enter it..
    Attaching the source code compilable in eclipse below ..
    package constantsPack;
    public class ConstantsApplet {
         public static final byte[] MAIN_SETUP_MENU = {
              (byte) 0x81, (byte) 0x03, (byte) 0x01, (byte) 0x25, (byte) 0x00,
              (byte) 0x82, (byte) 0x02, (byte) 0x81, (byte) 0x82,
              (byte) 0x85, (byte) 0x08 ,'A','B', 'C',' ','A','p','p','s',
              (byte) 0x8F, (byte) 0x0D,  0x0F, 't','e','s','t','a','p','p',' ','B','a','n','k',
              public ConstantsApplet ()
    }The applet code where the above static array is used..
    package smilePkgLib;
    import constantsPack.*;
    import javacard.framework.APDU;
    import javacard.framework.Applet;
    import javacard.framework.ISOException;
    import javacard.framework.Util;
    public class BLApplet extends Applet{
         short fetchcode =0;
         public static void install(byte[] bArray, short bOffset, byte bLength) {
              // GP-compliant JavaCard applet registration
              new smilePkgLib.BLApplet().register(bArray,
                        (short) (bOffset + 1), bArray[bOffset]);
         private BLApplet(){
              // put init code
          * The main method.
         public void process(APDU apdu) throws ISOException {
              if (selectingApplet()) {
                   return;
              byte choosenMenuItem = 0;
              byte[] buf = apdu.getBuffer();
              byte bytesRead =(byte)(apdu.setIncomingAndReceive());
              fetchList(ConstantsApplet.MAIN_SETUP_MENU , (byte)0x00);
         private void fetchList(byte[] list, byte command){
              shouldFetch(list);
          * Overloaded method to fetch the MENUs only.     
          * @param menu
         private void shouldFetch(byte[] menu) {
              shouldFetch((byte)menu.length);
         private void shouldFetch(byte len) {
                   fetchcode = Util.makeShort((byte) 0x91, (byte) (len));          
    }The JCOP script to run the above project
    /select |DefaultApplet
    # Terminal Profile
    /send A0100000133B67FF7F1F020F0B4100000000869804000000 Have the eclipse loadable project but dont know how to put here...
    Regards
    prakash.

  • Memory allocation when using multiple instances of a static array.

    Hi,
    I have question regarding the amount of memory allocated using multiple instances of a class that has declared a static array, e.g.:
    package staticTest;
    import javacard.framework.*;
    public class StaticClass
         static byte[] staticArray;
         public StaticClass()
              staticArray = new byte[100];
    /* Another class */
    package statictest;
    import javacard.framework.*;
    public class MyApplet extends javacard.framework.Applet
         StaticClass staticLibA, staticLibB;
         public MyApplet()
              /* Here we use two instances */
              staticLibA = new StaticClass();          
              staticLibB = new StaticClass();
         public static void install(byte[] bArray, short bOffset, byte bLength)
              (new MyApplet()).register(bArray, (short)(bOffset + 1), bArray[bOffset]);
         public void process(APDU apdu)
              byte[] buf = apdu.getBuffer();
              switch(buf[ISO7816.OFFSET_INS])
    }When downloading and installing this applet on a gemXpresso 211 PKis (that has a ' Get free EEPROM memory' function) the card reports that the amount of memory is increased by a approx 100 bytes every time a new staticLibX is added in the MyApplet constructor. Is this correct? If yes, can someone explain to me how to declare a static array that only allocates memory once and are being shared by the instances.
    Best regards,
    Jonas N

    Hi!
    I have another issue about static variable. The following is my sample code:
    ========================================
    package com.Test01;
    import javacard.framework.*;
    import javacard.security.*;
    import javacardx.crypto.Cipher;
    public class Test01 extends Applet {
         OwnerPIN Pin;
         static DESKey[] keys;
    protected Test01(byte[] buffer, short offset, byte length) {     
    keys = new DESKey[4];
    length = 0;
    while (length < 4) {
         keys[length] = (DESKey)KeyBuilder.buildKey((byte)3, (short)0x80, false);
         length = (byte)(length + 1);
    public static void install(byte buffer[], short offset, byte length) {     
    new Test01(buffer, offset, length);
    ===========================================================
    If there are two instances, A and B, created in the package.
    My issue:
    1. Are keys[0]~ keys [3] kept while B is deleted?
    2. Does each instance have itsown object while "keys[length] = (DESKey)KeyBuilder.buildKey((byte)3, (short)0x80, false);"?
    3. follow item 2, if A and B share the same object, is the object kept while B is deleted?
    Thank you
    Best regards,
    kantie

  • Using a static variable declared in an applet in another class

    Hi guys,
    I created an applet and i want to use one of the static variables declared in teh applet class in another class i have. however i get an error when i try to do that...
    in my Return2 class i try to call the variable infoPanel (declared as a static JPanel in myApplet...myApplet is set up like so:
    public class myApplet extends JApplet implements ActionListener, ListSelectionListener
    here are some of the lines causing a problem in the Return2 class:
    myApplet.infoPanel.removeAll();
    myApplet.infoPanel.add(functionForm2.smgframeold);
    myApplet.infoPanel.validate();
    myApplet.infoPanel.repaint();
    here are some of the errors i get
    dummy/Return2.java [211:1] package myApplet does not exist
    myApplet.infoPanel.removeAll();
    ^
    dummy/Return2.java [212:1] package myApplet does not exist
    myApplet.infoPanel.add(functionForm2.smgframeold);
    ^
    dummy/Return2.java [213:1] package myApplet does not exist
    myApplet.infoPanel.validate();
    ^
    dummy/Return2.java [214:1] package myApplet does not exist
    myApplet.infoPanel.repaint();
    ^
    please help! thanks :)

    I don't declare any packages though....i think it just doesn't recognize myApplet for some reason..
    other errors i got compiling are:
    dummy/Return2.java [82:1] cannot resolve symbol
    symbol : variable myApplet
    location: class Return2
    updateDesc.setString(3, myApplet.staticName);
    I Don't get why i'm getting this error cuase they worked fine when myApplet was a standalone application, not an applet.
    myApplet is in the same folder as Return2 and it compiles properly.

  • String Array declaration with multiple lines

    I have an array declaration with several indexes where it covers multiple lines.
    Please advise if this is the best way to declare an array declaration with multiple lines:
    String cityString = "San Diego, Oakland, London, New York, Dublin," +
    "Dallas, Milan";
    String city[] = cityString.split(",");

    String[] city = {"San Diego", "Oakland", "London",
    "New York", "Dublin", "Dallas", "Toronto"};You can use indentation and line breaks as you like, as usual in Java.

  • Discussion: private final static vs public final static

    take following class variable:public final static int constant = 1;Is there any harm in making this variable public if it's not used (and never will be) in any other class?
    Under the same assumption Is there any point in making this variable static?
    tx for your input

    Is there any harm in making this variablepublic
    if it's not used (and never will
    be) in any other class?Harm? No. Use? Neither.I suppose it makes no difference at all concerning
    runtime performance?
    Under the same assumption Is there any point inmaking this variable
    static?If the creation of the constant is costly, for
    instance. A logger is private final static most of
    the time.Same here, does making a variable final or static
    have any influence on runtime performance?No. And for 'expensive' operations (say, parsing a XML configuration file, which only needs to occur once), making a variable static will improve performance.
    - Saish

  • How to javadoc "public final static int"?

    How can we create "Field Summary" HTML document for "public final static int" variables?
    This question is probably same as the below question.
    http://forums.java.sun.com/thread.jsp?forum=41&thread=72832
    p.s.
    The below document indicates CENTER, NORTH, ...
    How an we achieve it to document "public final static" variables?
    http://java.sun.com/products/jdk/1.2/docs/api/index.html

    No, 1.3 does not have the static constant values exposed to the Doclet API,
    and so that information is not available to any doclets to place in the
    generated documentation.
    BTW, based on feedback from a developer, we changed the format from:
    public static final int NORTH = 0
    to
    public static final int NORTH
    See: Constant values
    where the "Constant values" link takes them to a summary page that
    lists all of the values. This helps discourage users from mistakenly
    seeing and using the value instead of the constant.
    -Doug Kramer
    Javadoc team

  • About array declaration

    Welcom evry body,
    as mentioned in the java langage specification this array declaration is right:
    String[] aas = { "array", "of", "String", };see: [http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html]
    My question is: what is the reason to allow the coma after the last array element?

    jmeist wrote:
    My question is: what is the reason to allow the coma after the last array element?Lazyness, usually.
    For one, you can easily expand an array defined such as this:
    String[] strings = {
      "aString",
      "anotherOne",
      "athirdOne",
    }You don't have to remember to treat the last line in a special way. Also, tools can create such code easier than if you required the last line to be different.

  • Final static method

    I have a class as follows that I instantiate in another program by:
    CalcsLin calcsLin=new CalcsLin();
    and use like:
    r=calcsLin.tunits(r,2,4);
    We obviously need "final static" on conv[ ], but I have not used it on tunits().
    My questions are: What does "final static" do on tunits()?
    Is it good to use it?
    And does each usage still get its own separate copy of "f" and "i"?
    public class CalcsLin {
      final static double conv[] = {  12.0,  30.0, 24.0, 60.0, 60.0, 100.0 };  //example numbers only
      final static double tunits(double r, int levfr, int levto) {
        double f=1.0;
        if(levfr<=levto) {
          for(int i=levfr;i<=levto-1;i++)f=f*conv; r=r*f;
    } else {
    for(int i=levto;i<=levfr-1;i++)f=f*conv[i]; r=r/f;
    } return(r);

    Have you read the links I posted?
    Static means that that method is part of the class, and not part of an object of that class.
    Both will work, but first is preferred:
    CalcsLin.tunits(1,2,3);
    c = new CalcsLin();
    c.tunits(1,2,3);And yes, it will work if you left static out, but I think it's in the right place there.
    Besides that I realized too late that I only answered the first question, here are the other answers.
    2nd: It is good to use it if (and only if) it makes sense. For example the [Math-class|http://java.sun.com/javase/6/docs/api/java/lang/Math.html]: the value of log(42) does not rely on any instance of the Math-class (if it was possible to instantiate this class) but is always the same equation, in those cases static functions are usefull. To make a static-method final isn't very usefull because the best way to call a static method is with it's class-name (thus CalcsLin.tunits(1,2,3); and not c = new CalcsLin(); c.log(1,2,3)).
    3rd: Yes, every call of the method will have it's own 'instance' of f and i.

  • Array Declaration - SCJP - WHY?

    class MWC212 {
      public static void main(String[] args) {
        int[] a1[],a2[];  // 1
        int []a3,[]a4;    // 2
        int []a5,a6[];    // 3
        int[] a7,a8[];    // 4
    }}A compile-time error is generated at which line?
    a.      1
    b.      2
    c.      3
    d.      4
    e.      None of the above
    Answer: b
    An array variable is declared by placing brackets after the identifier or after the type name. A compile-time error occurs at the line marked 2, because the brackets appearing before the identifier for array variable a4 are not associated with the type or the identifier.
    When you type something like this:
    String a,b;You are declaring that a and b are Strings
    Its perfect to declare an array like the code below
    int[] b[];
    int[][] b;
    int b[][];When you type
    int []a3,[]a4;is it not equal like
    int[]a3;
    int[]a4;Why?

    Read up on the correct declaration syntax. It's either
    int[] anArray or
    int anArray[]
    For some reason, the compiler doesn't care too much about spaces and allows
    int []anarray. Still, the angular brackets belong to int in this case.
    int []a, []b would be like writing
    int[] a, [] b - there's the type declaration missing in this case.
    Why? Because someone said so.

  • Constants:  "final static" vs. "final"

    In a GUI object, I have some class constants that are only used internally. Example 1:
    private final int PREFERRED_WIDTH = MainWin.MAX_WINDOW_WIDTH;
    private final int PREFERRED_HEIGHT = 50;Example 2:
    private final JButton helpButton = new JButton("Help");
    private final JButton closeButton = new JButton("Close");
    private final JLabel clearanceLabel = createClearanceLabel();Should the members in EX1, EX2 be static??
    These items are members of a GUI object, and there is only 1 instance of this GUI object during application runtime.
    The nature of my question is about the best practices of when to use the "static" modifier for private class constants.
    Thank you
    Message was edited by:
    PatrickFinnigan

    and "static" as sparingly as possible -- Disagreement here. First, of course, use it when
    appropriate. Second, though, my customers coding
    guidelines urge to use static for all methods that
    aren't accessing non-static members; there might be a
    reason for that although I don't know. But it's
    basically no problem declaring those as static.I can see the logic of declaring them static if they don't access anything instance-level; at least it makes it more obvious what it's doing. I suppose you might want to keep it non-static if you think that at some point the implementation will change and you don't want users of the API locked into a way of calling it which won't work, but such thinking can be dangerous.
    On a related note, a bad design choice I sometimes see is an excessive use of objects in which there is absolutely no state being maintained; the code in question doesn't need to be non-static at all. Making things objects when they don't have to be can make things too complicated.
    On the other hand, when you're doing object-oriented programming and you find that you're never creating objects, then something is seriously wrong.
    I think the best rule of thumb is: keep a clear understanding of what's an object, what isn't, and why; keep objects and non-objects clearly built as such, don't make things that are basically static utility methods into objects just because you can; and if you find that you're throwing the keyword "static" around a lot, then it's a red flag that you've probably got something wrong in your design.

  • Loading the final static variables at run time.. Please help

    Hello, fellow developers & Gurus,
    Please help me figure out the best way to do this:
    I need to load all my constants at run time. These are the public static final instance variables. The variables values are in the DataBase. How do I go about loading them.

    Your original question was diffeent, but your further posts show what you really want to do:
    1) all constants in 1 class
    2) available readonly for other classes
    3) updatable during runtime by changing in the database
    Did I understand you right?
    Then smiths' approach solves point 2):
    Instead, make the variables available through a method
    call - that way you avoid the whole final variable
    versus read-only attributes problem.
    //GLOBAL VARIABLES EXPOSED AS PUBLIC PROPERTIES
    public final class GlobalProperties
    public static int getTableSize();
    public static int getRowSize();
    Each "constant" should be a private static variable, and these methods simply return their values.
    The variables are initialized in a static initializer by accessing the db. Ok.
    You habe a table with one row containing as columns all the constants.
    A method readConstants() does a "select constant1, constant2, ... from const_table" and sets all the variables.
    The static initializer calls this method.
    Right?
    Ok, then you simply call readConstants() everytime you want to synchronize with the actual content of const_table.
    Was it this?

Maybe you are looking for