About variable initialization

Hi,
I would like to know the difference between the following two initializations :
Initializing the object inside the constructor and outside the constructor..
class Test {
FooObj obj ;
public Test() {
obj = new FooObj();
and
class Test {
FooObj obj = new FooObj();
public Test() {
Can you pl. let me know..
Thanks
Devi..

class One {
    private ArrayList data;
    public One()
        data = new ArrayList();
class Two {
    private ArrayList data = new ArrayList();
    public Two()
bytecodes:
class playground.One extends java.lang.Object {
    public playground.One();
Method playground.One()
   0 aload_0
   1 invokespecial #1 <Method java.lang.Object()>
   4 aload_0
   5 new #2 <Class java.util.ArrayList>
   8 dup
   9 invokespecial #3 <Method java.util.ArrayList()>
  12 putfield #4 <Field java.util.ArrayList data>
  15 return
class playground.Two extends java.lang.Object {
    public playground.Two();
Method playground.Two()
   0 aload_0
   1 invokespecial #1 <Method java.lang.Object()>
   4 aload_0
   5 new #2 <Class java.util.ArrayList>
   8 dup
   9 invokespecial #3 <Method java.util.ArrayList()>
  12 putfield #4 <Field java.util.ArrayList data>
  15 returnSo it looks equivalent to me. I prefer to initialize outside of the constructor unless arguments are needed to create the instance.

Similar Messages

  • Variable initialization

    Hello guys,
    Is there anybody know how and when java checks for variable initialization?For example if we change a value, assume a without initializing it we get variable a might not have been initialized.I wish to know how java checks that the variable is already assigned or not.
    int a;
    a++;//How java checks this
    regards,
    Haddock

    Rules is:
    To variables of instance - It's default value attribute automatically if not initialize with value.
    To local variable (methods for example) - It's default value in initialization has been MUST attributed
    Instance variables has a folliwing default value:
    class A{
    int i; //default value is 0
    char c; //default value is '\u0000'
    byte b; //default value is 0
    short s; //default value is 0
    long l; //default value is 0
    float f; //default value is 0.0
    double d; //default value is 0.0
    boolean bl; //default value is false
    String str; //Object is always null
    int x[]; // null. It's Object's array
    int x[5]; // 5 times default value 0.
    void testInitializeValue(){
    int x; // Compiler error; This variable has been initialized
    if(x == 5){
    return;
    Ok..Thanks!!

  • Documentation about variable types & their processing in i_step = 1, 2 etc.

    Hello experts,
    is there any documentation about variable types and their processing in i_step = 1, 2 etc.? I know there is note 492504 "Dependent customer exit-type variables", but I don't understand, whether a variable which is NOT "Ready for input" will be processed in i_step = 1 or not  (quote of SAP library: "i_step = 1: Call takes place directly before variable entry."). I experienced coincidentally, that some variables not "Ready for input" will be processed there and some not.
    Furthermore it is an error, isn't it? Why has a variable without input possibility to be processed before input? Is this really the case?
    Confused, any hints are welcomed!
    Regards M.L.

    for I_STEP = 1
    Call before the variable screen .
    for I_STEP = 2
    Call after variable entry. This step is only started up when the same variable is not input ready and could not be filled at I_STEP=1.
    for I_STEP = 3
    In this call, you can check the values of the variables. Triggering an exception (RAISE) causes the variable screen to appear once more. Afterwards, I_STEP=2 is also called again.
    for I_STEP = 0
    The enhancement is not called from the variable screen. The call can come from the authorization check or from the Monitor.
    There is a good HOW to Guide which explains the importance of I_STEP :
    http://service.sap.com/~form/sapnet?_SHORTKEY=00200797470000078090&_SCENARIO=01100035870000000112&_OBJECT=011000358700002762582003E
    Another from SDN:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/events/bw-and-portals-05/five%20ways%20to%20enhance%20sap%20bi%20backend%20functionality%20using%20abap.pdf

  • Message variable initialization

    Hello,
    We had this ridiculous situation a while ago where out service instances create their variables with multiple nodes.
    For example if we have xsd looking like this:
    <element name="Response">
    <complexType>
    <sequence>
    <element name="Result">
    <simpleType>
    <restriction base="string">
    <enumeration value="OK"/>
    <enumeration value="ERR"/>
    </restriction>
    </simpleType>
    </element>
    <element name="Comment" minOccurs="0" type="string"/>
    </sequence>
    </complexType>
    </element>
    In BPEL we have message variable which part is this "Response" element. Everything is fine till the moment we start getting initial variable looking like this:
    <outputVariable>
    <part name="payload" >
    <Response>
    <Result/>
    <Result/>
    <Result/>
    <Result/>
    <Result/>
    <Result/>
    </Response>
    </part>
    </outputVariable>
    Of course we have no reason for this, no logs, no info and so on. Any idea anyone?
    Everything is normal concerning the BPEL, no errors are raised till the moment we need to populate the variable. The process is working correctly but we cannot return result to the caller.
    WL version: 10.3.5.0
    SOA version: 11.1.1.5.0
    BPEL version: 2.0
    Best regards.

    could you please send your test case to our support team? this doesn't look right. bpel engine would initialize the variable based on the xpath usage in to-spec expressions. you can try turning of variable initialization for that particular component using bpel.config.initializeVariables to false. and go with literal xml variable initiation. [http://docs.oasis-open.org/wsbpel/2.0/OS/wsbpel-v2.0-OS.html#SA00038]
    http://docs.oracle.com/cd/E28271_01/dev.1111/e10224/bp_manipdoc.htm#BABHDFBJ
    here is the sample for that property
    in composite.xml, find the component, under that component add this property, and re-deploy with your literal variable init.
    <property name="bpel.config.initializeVariables">false</property>

  • Class variable initialization

    I have noticed that class variable initialization occurs AFTER the constructor is called.
    Why is this, and is this intentional?
    It has caused strange behaviour in my SE java applications I am porting to MIDP.
    Thanks
    - Adam

    Hi,
    Error 1:
    The problem only arises if you use the unassigned variable:
    int i;
    int y = i; // Use of unassigned variable here
    you can just assign a value to i to solve this:
    int i = 0;
    int y = i; // Use of unassigned variable here
    Error 2 and 3 have to do with static and non-static, not with the initialization per se. This is how it works:
    static members (e.g. fields) can be accessed using this syntax: <Classname>.<FieldName>, e.g:
    public static class Helpers
    public static int SomeDataValue { get; set; }
    class Program
    static void Main(string[] args)
    Helpers.SomeDataValue = 22;
    On the other hand, non-static members are accessed like this: <instance>.<fieldname>. So you always need an instance of a class to access the field:
    public class Order
    public int OrderNumber { get; set; }
    class Program
    static void Main(string[] args)
    Order o = new Order();
    o.OrderNumber = 12;
    Rgds MM

  • About static variable initialization

    Here is an exercise where you have to guess the output :-)
    public class MyClass{
        private static int x = getValue();
        private static int y = 5;
        private static int getValue(){
            System.out.print("Running getValue ");
            return y;
        public static void main(String[] args){
            System.out.println(x);
    }This code outputs "Running getValue 0" I don't understand why?

    because class initialisation will call getValue() before it initialises 7 to 5, thus setting x to the value y has before being initialised which is 0.
    What this tells you is that you should never program rubbish like that, and in general not rely on the value of uninitialised members.

  • Inheritance - instance variable initialization

    Hi all.
    I have a question regarding inherited instance variables.
    class Animal {
       int weight;
       int age = 10;
    class Dog extends Animal {
       String name;
    class Test {
       public static void main(String[] args) {
          new Dog();
    }This is just an arbitrary code example.
    When new Dog() is invoked, I understand that it's instance variable "name" is give the default
    type value of null before Dog's default constructor's call to super() is invoked.But Im a little perplexed about
    Animals instance variables. I assume that like Dog, Animals instance variables are given their default type values
    of 0 & 0 respectively, before Animals invocation of super(); What im unclear about is that at the point that weight and age are given their default type values, are Dog's inherited weight and age variables set to 0 aswell at that exact moment? Or are Dog's inherited weight and age variables only assigned their values after Animals constructor fully completes because initialization values are only assigned to a classes instance variables after it's call to super().
    Many thanks & best regards.

    Boeing-737 wrote:
    calvino_ind wrote:
    Boeing-737 wrote:
    newark wrote:
    why not throw in some print statements and find out?Super() or this() have to be the very first statement in a constructor..
    Also you cannot access any instance variables until after super or this.
    :-S
    Kind regardsbut if you add the "print" statement in animal constructor, you can easily see what happened to the attributes of Dog ; that s the trick to print "before" super()You can never add a print before super(). It's a rule of thumb, super() and this() must always be the first statements
    in a constructor, whether added implicitly by the compiler or not. In this case there are 2 default constructors (inserted by the compiler), each with a super() invocation. Even if i added them myself and tried to print before super(), the compiler would complain.
    Thanks for the help & regards.you didn't understand what i meant ; take a look at that:
    class Animal {
       int weight;
       int age = 10;
       public Animal() {
           Dog thisAsADog = (Dog) this;
          System.out.println(thisAsADog.name);
          System.out.println(thisAsADog.x);
    class Dog extends Animal {
       String name;
       int x = 10;
    public class Test {
       public static void main(String[] args) {
          new Dog();
    }this way you will know what really does happen

  • [OT] surprising instance variable initialization exception behavior

    No real question here. Just something that caught me quite off guard. I thought I understood the object instantiation process pretty well, but there's clearly at least one significant gap in my knowledge.
    Not surprisingly, the following gives "Error:Error:line (4)unreported exception java.lang.Exception; must be caught or declared to be thrown" for the new WTF2() line.
    public class WTF1 {
      private final WTF2 wtf2 = new WTF2();
      WTF1() /* throws Exception */ {}
    class WTF2 {
      WTF2() throws Exception {}
    }Quite surprisingly (to me at least) if we uncomment "throws Exception" in the WTF1() c'tor declaration, the compiler is happy.
    Reading [JLS 12.5 Creation of New Class Instances|http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.5], I can see that executing the instance initializers is step 4 of "the indicated constructor is processed to initialize the new object using the following procedure", so I guess I can see how executing the initializer can be considered "part of" executing the c'tor, and hence covered by its catch block. It just looks a little weird, and I always thought that the initializer executed before the c'tor, and had to catch checked exceptions.
    Now that I've learned something, I'm ready to count this day as a win and head to the pub. :-)

    BIJ001 wrote:
    wtf2 is an instance variable, so (the appropriate copy) must be initialized in (every) constructor.Eh? No.
    It's final, so therefore it must have it's value set by every normal completion of every ctor. But that's irrelevant to what I'm looking at. I'm talking about the fact that the declaration/initialization line complains or doesn't based on the throws clause of the c'tor.
    I see now why it works that way, but I just thought the initializer execution was "outside of" the c'tor execution. I thought that if new WTF2() could throw a checked exception, I'd have to do something like we do for static initializers:
    private final WTF2 wtf2;
      try {
        wtf2 = new WTF2();
      catch (Exception e) {
        throw some unchecked exception
    }As it turns out, the initializer is executed "inside" the c'tor in a way I didn't expect.

  • Variable initialization error

    import java.io.*;
    import java.util.*;
    import java.sql.*;
    public class ReadCSVFile
    public void StatementQuery(String Version , String Doctype_id)
    String docfamilyid,docfamilyid_upd;
    String sqlstr = "select DOCFAMILYID_ID from master table where doctypeid=\""+Doctype_id+"\"";
    public static void main(String[] args)
    ReadCSVFile obj = new ReadCSVFile();
    String str,doctype=null,version=null,doctype_id=null;
         int i=0;
         String prevdoctype,prevdoctype_id;
    try
    BufferedReader in = new BufferedReader(new FileReader("RecordsNet_DocType_List1.csv"));
    while ((str = in.readLine()) != null)
    String s[] = str.split(",");//splitting string based on ','
    if (s[1]!=null)
         doctype_id=s[1];
              if (s[5]!=null)
    doctype=s[5].trim();
    if (s[8]!=null)
    version=s[8];
    if (s[1].length()==0 && s[5].length()==0)
         System.out.println("Another version for "+ prevdoctype_id);
    if ( doctype.equalsIgnoreCase("Statement")) {
              obj.StatementQuery(version,doctype_id);
              prevdoctype_id=doctype_id;
         if ( doctype.equalsIgnoreCase("Report Class A")) {
                        //System.out.println("Report Class A"+ i + doctype);
                        prevdoctype_id=doctype_id;
         if ( doctype.equalsIgnoreCase("Report Class B")) {
                        //System.out.println("Report Class B"+ i + doctype);
                        prevdoctype_id=doctype_id;
         if ( doctype.equalsIgnoreCase("Report Class D")) {
                                  //System.out.println(doctype);
                                  prevdoctype_id=doctype_id;
         if ( doctype.equalsIgnoreCase("Trade Confirm")) {
                                  //System.out.println("Trade Confirm"+ i + doctype);
                   prevdoctype_id=doctype_id;
    in.close();
    catch (IOException e)
    }//class main end
    }// class ReadCSVFile end
    error is
    variable prevdoctype_id might not have been initialized
    if i initialize it then it get's initialized everytime..but when some parameters are blank in a file i just want to resuse the value stored in variable prevdoctype_id

    if i initialize it then it get's initialized everytime.You only need to initialize it one time outside of the while loop for example by setting it to null then the variable is initialized and it will not be overwritte each time.
    btw. the
    if (s[X]!=null)seems to be wrong.
    a) array indices are 0 based. i.e. the first index is 0
    b) split returns an array of Strings based on the regular expression
    so will split return a one element array for the String "token 1" containing ["token 1"]
    a three element array for the String "token 1, token 2, token 3", containing ["token 1", "token 2", "token 3"]
    You should replace your
    if (s[X]!=null) {
    }by
    if (s.length > X) {
    }

  • Row-Wise Session Variable Initialization Block (Max Rows)

    Hi, we have a problem with Row-Wise Session Variable.
    We'll try to implemented the security with a External Query and a Row-Wise Initialization Block. But when we'll try to open the Web Obiee and the rows of result of the query is more than 3000 rows, the browser is broken. The access is very slowly.
    When the result of Query to Row-Wise Variable is more than 3000 rows and we'll try to open the Web Obiee, we have to close NQServer.EXE process of Obiee Server.
    Is there a best practise or a limit rows in the Row-Wise Initialization Block?.
    Thanks.

    You're Right, the people can't be in 3000 groups.
    Is possible I don't explain my problem correctly.
    We use this Row-Wise Variable for implement Data Level Security. .
    For Example :
    I have a fact table with Offices and Office's Sales.
    And each Obiee User can see many Offices according to their level of security.
    I want filter the fact table using a external SQL table implemented in a Session Row-Wise Variable and a User can have X Offices (In the worst case, 3000 Offices).

  • Multiple variable initialization using arrays

    Hi,
    In my program I want to initialize some 20 odd variables(all of the same type) to the same value having their names as Input1, Input 2 .. Input 20. Want I want to do is to use an array to do this rather than writing the 20 variables one after the other. Is there any way to do so ?
    Please help.
    Thanx in advance,
    Gaurav

    Hi Again,
    I am sorry for framing the question wrongly. What i want exactly is this :
    I want to create a variable no. of arrays (the number of arrays will be inputed by the user). I want to initialize them ,something like this
    int Input1 [] = new int [400];
    int Input2 [] = new int [400];
    After this initialization I will then fill these with some info. from a file and then use it in my program.
    So I want to use a for loop or some other loop so that I can achieve this.
    Please help,
    Thanks
    Gaurav

  • PartnerLink Input Variable initialization error for xsd:any datatype

    I have a web service which use the xsd:any for the message type( segment of the wsdl given below):
    - <message name="post_ps_apg_services0Request">
    <part name="fa_form" type="**xsd:any**" />
    </message>
    <portType name="ps_services_wsPortType">
    - <operation name="post_ps_apg_services">
    <input name="post_ps_apg_services0Request" message="tns:post_ps_apg_services0Request" />
    <output name="post_ps_apg_services0Response" message="tns:post_ps_apg_services0Response" />
    </operation>
    <binding name="ps_services_wsBinding" type="tns:ps_services_wsPortType">
    <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
    - <operation name="post_ps_apg_services">
    <soap:operation soapAction="" style="rpc" />
    - <input name="post_ps_apg_services0Request">
    <soap:body use="literal" namespace="ps_services_ws" />
    </input>
    - <output name="post_ps_apg_services0Response">
    <soap:body use="literal" namespace="ps_services_ws" />
    </output>
    </operation>
    <service name="ps_services_ws">
    - <port name="ps_services_wsPort" binding="tns:ps_services_wsBinding">
    <soap:address location="http://spider.apollogrp.edu:4400/sst/runtime.asvc/ps_services" />
    </port>
    </service>
    I have created a Partnerlink Invoke_ps_apg_services with Input Variable 'Invoke_ps_apg_services_post_ps_apg_services_InputVariable'.
    During Compilation of the process I get the following exception:
    Error: Couldn't initialize variable.
    Error occurred while initializing BPEL variable "Invoke_ps_apg_services_post_ps_apg_services_InputVariable" at line 51, the schema processor could not find type "{http://www.w3.org/2001/XMLSchema}any" for part "fa_form", in the following schemas:
    Schema 0 ---> namespace=http://edu.apollogrp.ws.ps_services/Ips_services_ws.xsd
    location=file:/C:/BPELProjects/FAPP/FAPP_PS_Service/bpel/PostFAFormsPSSchema.xsd.__OAUX_GENXSD_.TOP.XSD
    Schema 1 ---> namespace=http://xmlns.oracle.com/pcbpel/adapter/jms/
    location=file:/C:/BPELProjects/FAPP/FAPP_PS_Service/bpel/jmsAdapterInboundHeader.wsdl.__OAUX_GENXSD_.TOP.XSD
    Schema 2 ---> namespace=null
    location=file:/C:/BPELProjects/FAPP/FAPP_PS_Service/bpel/FAPPService.wsdl.__OAUX_GENXSD_.TOP.XSD
    Please make sure that the type "{http://www.w3.org/2001/XMLSchema}any" is valid in your wsdl.
    Has anyone have seen this error ? What is the fix/workaround ?
    Thanks in advance

    The "any" type is not defined in the standard http://www.w3.org/2001/XMLSchema namespace. Try changing the type name to "anyType" and it should not give that error anymore.
    The valid types defined under that namespace are located at [http://www.w3.org/TR/xmlschema-2/#built-in-datatypes|http://www.w3.org/TR/xmlschema-2/#built-in-datatypes].

  • About variables in scripts

    what type of variables used in scripts to out put data

    Hi
    See the script symbols
    A variable in SAPscript is called a symbol. There are the following types.
    • System symbol (e.g. the number of the current page)
    • Standard symbol (usable in any document)
    • Program symbol (value from the print program)
    • Text symbol (“local variable”)
    The value of a symbol is text for using within SAPscript code and is represented by the symbol-name enclosed by ampersands. On seeing the tell-tale ampersands in SAPscript code, you sometimes need to figure out the symbol type.
    goto any PAGEWINDOW's Text elements in Script (SE71)
    from the Menu-> INSERT-> Symbols
    you find all symbols here
    System symbols
    System symbols in a SAPscript form are comparable to system fields like SY-UZEIT in an ABAP program, and include these. The graphical editor offers three types of system symbol.
    1. General system symbols
    See the table TTSXY. PAGE is the most widely used. The list given in our BC460 training manuals is out of date.
    2. SAPscript system symbols
    See the dictionary structure SAPSCRIPT. SAPSCRIPT-FORMPAGES is the most widely used.
    3. ABAP system symbols
    For the ABAP system field SY-UNAME, say, the symbol is SYST-UNAME. [SYST is the dictionary structure for ABAP system fields.]
    Sample code:
    User: &SYST-UNAME&
    Page &PAGE& of &SAPSCRIPT-FORMPAGES(C3)&
    Standard symbols
    Standard symbols are maintained centrally (in the table TTDTG via transaction SE75) for use in any document. Menu path:
    Tools
    Form Printout
    Administration
    Settings
    Some standard symbols are SAP-standard and others are custom. Curiously, table TTDTG is cross-client although SAPscript forms are not.
    The value of a standard symbol has to be defined for each language used. This gives a way to make a single SAPscript form multi-lingual.
    We can take advantage to an extent of the central maintenance, though there is no guarantee that the available standard symbols will used in every appropriate context.
    Standard symbols complicate searching a SAPscript form, since text like ‘Charity registration 211581’ may be hiding in a standard symbol.
    Text symbols
    A text symbol is declared and assigned to within the SAPscript code, and so obviously applies only to the current document. The command DEFINE is used, requiring /: in the tag column, as in the following examples.
    /: DEFINE &COMP_NAME& = ‘University of Warwick’
    /: DEFINE &WS_RATE& = &TAX_SUMM_C&
    SCRIPT COMMANDS
    ADDRESS : Formatting of Address
    BOTTOM, ENDBOTTOM : Define Footer text in a window
    BOX, POSITION, SIZE : Boxes, Lines and Shading
    CASE, ENDCASE : Case Distinction
    DEFINE : Value assignment to text symbols
    HEX, ENDHEX : Hexadecimal values
    IF, ENDIF : Conditional text output
    INCLUDE : Include other texts
    NEW-PAGE : Explicit forms feed
    NEW-WINDOW : Next window main
    PRINT-CONTROL : Insert print control character
    PROTECT...ENDPROTECT : Protect from page break
    RESET : Initialize outline paragraphs
    SET COUNTRY : Country-specific formating
    SET DATE MASK : Formating of date fields
    SET SIGN : Position of +/- sign
    SET TIME MASK : Formating of time fields
    STYLE : Change style
    SUMMING : Summing variables
    TOP : Set header text in window MAIN
    <b>Reward points for useful Answers</b>
    Regards
    Anji

  • Question about variable names

    k, so I have a for() loop that I want to take the value of String fs1 through String fs21 and add them in that order to a String fs. So, my question is, can you do this in a loop? you can do it in PHP, and that's what I'm accustom to.
    this is kinda what I want to make
    String fs = "";
    String fs1 = "foo";
    String fs21 = "bar";
    for(int i = 0; i<22;i++)
         fs+= (the variable "fs" plus the number of "i", so like fs1, fs2, fs3. . . fs21);
    System.out.println(fs);

    I think you want to use and array and be careful about using += that way.
    StringBuffer buffer = new StringBuffer();
    String[] fs = new String[2];
    String fs[0] = "foo";
    String fs[1] = "bar";
    for(int i = 0; i<22;i++)
         buffer.append(fs);
    return buffer.toString();

  • Question about variable declaration

    Hi all,
    I have a (in fact, two) question(s) about the declaration of variables inside of time-critical code, like render loops or similars.
    Does it really matter to use
    for (int k=0; k<1000; k++)
         for (int l=0; l<1000; l++)instead of
    int k;
    int l;
    for (k=0; k<1000; k++)
         for (l=0; l<1000; l++)concerning the speed of the app? What about doing this with non-basic types -> Objects, like to say Strings ?
    And are there any resources where I can find out more about that and other things like that ?
    Uhm, now it became three q's... Sorry to bother you ;-)
    Skippy

    whoo, maybe I got something totally wrong here.
    Does this mean that
    Image blah;
    for (int i=0; i<100; i++) blah = getImage("test"+i+".gif");will clean up a lot, because there are non-referenced Images and Strings?
    Hmm, anyone told me that
    for (int i = 0; i<100; i++)
    String test = "test"+i;
    System.out.println(test);
    }is disastrous code.
    Damn, ever thought to be a good Java programmer, but every day I get new thoughts I cannot solve these days...
    grmph
    Skippy

Maybe you are looking for