Declaring variables in loops.

I am wondering about how the compiler deals with variables that are declared within the loop they appear in. Obviously if you have a:
while (loop == true);  {
int var;
// do something that involeves var...The suggestion is that it allocates an int with every loop iteration?
If I declare my variables outside of the context in which I use them, then they persist throughout code that doesn't need them.
Surely the compiler is smarter than that?

If I declare my variables outside of the contextin
which I use them, then they persist throughoutcode
that doesn't need them.The same goes for the variables declared in a loop.No it doesn't.
If I write this:
public class test
     public static void main(String[] args)
          for (int x = 0; x < 255; x++) {
               int y = 12;
               System.out.print(x + ", ");
          System.out.println("\n" + y + x);
}The compiler throws two errors because the lower println statement has never heard of either x or y.
Just declare the variables in the scope block closest
to where they are needed. You're worrying about
things that need not concern you.Oh, it does concern me though. I want my programs to be as neat as clean as possible and I also want to learn to be the best programmer I can: I'm not here to just leap on a gravy train! : )
See, I do want to format my files in the manner you suggest, with variable declared in the scope in which they used, but how do I make adjustments to them later: I want to do this from the top of my file.
If anybody has the answer I'll give them four more Duke dollars! : )

Similar Messages

  • Declaring Variable in Web dynpro ABAP

    Hi all
    I want to know how to declare variables globally and how to use internal tables from one method to another method without declaring each and every time in methods?
    Please suggest me to do this
    Appreciated your solution
    Regards
    Indiranjithn

    Hi
    This code in onselct method. For example
    DATA lt_node_am_detl1 TYPE wd_this->Elements_node_am_detl1.
    logic to move the data to internal table.
    lo_nd_node_am_detl1->bind_table(  lt_node_am_detl1 ).
    Now the filterd data in internal table and
    I declared this internal table in componentcontroller attributes tab like
    lt_node_am_detl1  and Elements_node_am_detl1 (Associate column ) and i tick the pulic check box.
    i am using another method onclick() .
    As you said the internal table declaration is not required if declared already in componentcontroller attributes tab .
    data wa_itab like line of lt_node_am_detl1 .
    Loop at lt_node_am_detl1 to wa_itab.
    endloop.
    while debugging i am not getting data in internal table .. Should I declared correctly in componentcontroller attributes tab .
    Tlhanks
    Indiranjithn

  • Can I declare variables in Reports from SQL Query

    Hi
    I have a Report from SQL Query published as a portlet on a page among other reports. In the query report I am using the fuction WWCTX_API.GET_USER at quite a few places to filter the data returned to the user. Can I assingn the user id to a variable at some level & replace the fuction WWCTX_API.GET_USER with the variable in all the places.
    For eg:
    usr varchar2(25);
    usr:= PORTAL30.WWCTX_API.GET_USER;
    select USER_ID, USER_LVL, BUSINESS_ID, BRANCH_ID from crs_user where user_id=usr;
    can i declare variable and assign the value like the above at any level(Report or Page Level) to the acces the variale in queries.
    Thanks in advance

    I have found that you can't use a * in a dynamic page.
    Try this:
    <ORACLE>
    DECLARE
    usr varchar2(25):=PORTAL30.WWCTX_API.GET_USER;
    BEGIN
    for c in
    (SELECT <column_name> <alias> FROM PORTALWORK.CRS_USER WHERE USER_ID=usr)
    Loop
    htp.p(c.<alias>);
    END;
    </ORACLE>
    You can also add table tags for column formating:
    <table>
    <tr><td>column 1</td></tr><tr><td nowrap>
    <ORACLE>
    DECLARE
    usr varchar2(25):=PORTAL30.WWCTX_API.GET_USER;
    BEGIN
    for c in
    (SELECT <column_name> <alias> FROM PORTALWORK.CRS_USER WHERE USER_ID=usr)
    Loop
    htp.p(c.<alias>);
    END;
    </ORACLE>
    </td></tr></table>
    Martin

  • Hello...Java is supporting mutiple datatypes declarations in for loop

    hello,
    is it possible to declare more than one data types in a for loop...i think java is supporting multiple declarations in for loop..am i right
    class check
         public static void main(String[] args)
              for(int i=10,float k=10;i<5;i++)
                   System.out.println("Hello World!"+i);
    regards,
    j.mouli

    Hi,
    no, that doesn't work because java unlike c++ does not
    have the comma operator ",". So you need to declare
    the 2nd variable in the body of the loopNot strictly correct - its true that it won't work in this case, but false that Java doesn't recognise the comma.
    If your two variables were of the same type you could use something like
    for (int i = 0, k = 10; i < k; i++)
    However, the initialisation must take place in a single statement, so you can't use multiple types

  • "Dynamic Declaration/Variable"

    Hi,
    first sorry for my bad english :)
    I have a Problem with Forms Builder 6
    I want to know if it possible to set dynamic declarations inside a loop
    loop_i := 1;
    WHILE loop_i < 10 LOOP
    go_item('GERAET' || to_char(loop_i) || '.Beginn'); --Geraet1.Beginn to Geraet10.Beginn... this works without problems
    if (':GERAET'||to_char(loop_i)||'.Beginn') is null then
    :GERAET || to_char(loop_i) || .Beginn := ('01-JAN-1234'); -- here is my problem
    END LOOP;
    My Problem is in this Line :GERAET || to_char(loop_i) || .Beginn :=
    I cant fill fields dynamic like this. Is there any way to fill Geraet1.Beginn to Geraet10.Beginn with this Loop? I dont know the syntax for declarations with " : " and a dynamic variable
    i hope you understand what i mean :)

    Use the Name_In() and Copy() built-ins (see the online doc)
    Francois

  • What happens to dynamically declared variables when I'm not using them?

    Hello, I'm making a game using Flash Pro cc. But I wonder what happens to aTile, which is dynamically declared MovieClip variable through a loop. And each aTile gets the 2 EventListener's.
    for(var i:Number=0; i<pVector.length;i++){
        var aTile:ATile=new ATile();
        aTile.x=pVector[i].x;
        aTile.y=pVector[i].y;
        aTile.gotoAndStop(Math.ceil(Math.random()*Color));
        nVector.push(aTile);
        Spr.addChild(aTile);
        aTile.addEventListener(MouseEvent.CLICK,Clicked,false,0,true);
        aTile.addEventListener(Event.COMPLETE, stop,false,0,true);
         // the current function ends here. what happens to aTile now ?? Is it going to be garbage collected? By the way, this piece of code runs whenever a player starts a new level of my game. And I don't make use of the aTile variable in other functions. I use only the nVector variable. And does declaring a dynamic variable in a loop mean a multiple of them are created? For example, if I loop the piece of code above 5 times, does it mean 5 aTile variables are created? Or each time you declare
    var aTile:ATile=new ATile(); again, does it replace the 'old' aTile with the 'new' aTile and therefore only 1 aTile exists after the loop????

    I feel there is a gap in understanding of using variables by reference vs. by value. You should look it up.
    1. new instructs Flash to create a distinct instance that per se has absolutely nothing to do with aTile variable.
    2. REFERENCE to this new instance is assigned to variable aTile. aTile var is a temporary pointer to instance.
    3. It does not replace old tile - it replaces reference.
    4. If reference to the instance is not stored elsewhere - upon exiting of function this instance will be gced.
    5. By creating another reference to the instance you prevent it from GC. One of the ways you preserve instance is by adding it to display list when using addChild.
    You can look at this this way (it is a lame example but still it illustrates parts of the concept)
    Say you have
    1. basket;
    2. basket is small and can hold only one apple;
    3. table;
    4. an apple;
    5. apple can be placed into the basket or table;
    6. dog who love apples.
    7. Dog is trained not to take apples from baskets but table but is free to eat apples that are on the ground.
    So, once apple is in the basket or on the table - it is safe.
    If you move these entities into the realm of AS3, basket and table become declared variables, apple an instance and dog garbage collector.
    What this example demonstrates is that apple exists independently of basket or table. You can put apple to the basket OR on the table OR you can put apple into basket and place basket onto the table.
    1. Find apple instance (if you know whether apple is in the basket, on the table or in the basket on the table)
    2. Prevent dog from eating apple.
    3. Allow dog to eat it (destroy it when garbage collector kicks in) by assuring that apple is in neither basket or on the table.

  • How to declare variables in standard text  - so10 t.code

    Hello Friends,
             How to declare variables in standard text  - so10 t.code? Your response will be appreciated much.
    Thanks
    Sri

    For Script & Smartform  Text - &VAR&

  • How to declare variable in the scipt

    data is coming from standard program .
    rf140-stida key entry date.
    bsik-bldat posting date
    i want to display difference between  rf140-stida and bsik-bldat in scipt form it will give number of days.
    how can i declare variables for this.
    how to write code in my form.

    Hi
    U need to create a routine to calculate the difference:
    /: DEFINE &DELTA& = SPACE
    /: PERFORM <FORM NAME> IN PROGRAM <PROGRAN NAME>
    /: USING &RF140-STIDA&
    /: USING &BSIK-BLDAT&
    /: CHANGING &DELTA&
    &DELTA&
    The routine has to be defined in your Z-PROGRAM and to have these interface:
    FORM <FORM NAME>  TABLES IN_TAB_EM     STRUCTURE ITCSY
                                                       OUT_TAB_EM STRUCTURE ITCSY.
      DATA: DELTA TYPE I.
      DATA: DATE1 LIKE SY-DATUM,
                 DATE2 LIKE SY-DATUM.
    * ---> Rembember the date has the ouput format, so it has to be converted in the
    * input format
      READ TABLE  IN_TAB_EM WITH KEY NAME = 'RF140-STIDA'.
      IF SY-SUBRC = 0.
         DATE1(4)     = IN_TAB_EM-VALUE+6(4).
         DATE1+4(2) = IN_TAB_EM-VALUE+3(2).
         DATE1+6(2) = IN_TAB_EM-VALUE(2). 
      ENDIF.
      READ TABLE  IN_TAB_EM WITH KEY NAME = 'BSIK-BLDAT'.
      IF SY-SUBRC = 0.
         DATE2(4)     = IN_TAB_EM-VALUE+6(4).
         DATE2+4(2) = IN_TAB_EM-VALUE+3(2).
         DATE2+6(2) = IN_TAB_EM-VALUE(2). 
      ENDIF.
      DELTA = DATE1 - DATE2.
      READ TABLE  OUT_TAB_EM WITH KEY NAME = 'DELTA'.
      IF SY-SUBRC = 0.
         WRITE DELTA TO OUT_TAB_EM-VALUE.
         MODIFY OUT_TAB_EM INDEX SY-TABIX.
      ENDIF.
    ENDFORM.
    Max

  • Declare variables in an MDX query

    Is it possible to declare variables in an MDX query like transact sql? something like this:
    DECLARE @date1 date
    DECLARE @month1 int
    set @date1 = '12-12-2012'
    set @month1=DATEPART(m, @date1)-1
    select @date1 as dt1, @mesreferencia as mt1

    Hi ,
      In MDX , you will not be able to put variables in MDX. But Query scoped calculated measures can be used for such cases. The equivalent MDX for the above is
    WITH MEMBER [MEASURES].Dt
    As
    CDATE('12-12-2012')
    MEMBER MEASURES.DTPart
    As
    DATEPART("M", MEASURES.Dt)-1
    SELECT {MEASURES.Dt,MEASURES.DTPart} ON 0
    FROM [Adventure Works]
    Best Regards Sorna

  • Declare variables in function module

    hi gurus,
    i am making a function module in which i need to make some performs so as to do code reusability. but for that i need to declare variable globally. As i am working wth function modules for the fisrt time. can anyone please help me with that. i dnt want these variables in improt or export parameters.
    regards
    vibhor

    hi vibhor,
    there is a tab "display object list" on the top of the sap screen when u r in dat function module. press that.
    on the left side of ur screen there will complete lists of object used in fm. in includes there will a top include, declare all the variables u need globally in that top include. u can also create more includes for different performs if u want for modularizing ur program..
    regards
    palak

  • Can we declare variable dynamic

    Hi ,
    Can we declare variables dynamically.
    [ java uses this feature in Garbage Collection.]
    Thanks ,
    Adi

    but jvm uses this dynamic decalration in Garbage
    Collection.
    then can't we use the same.I'm not sure I understand what you mean? Do you mean that objects are dynamically created at runtime? Yes they are but the variables in the class definitions were all declared at compile time.

  • Declaring variable

    private var _history:Vector.<BitmapData>;
    can any1 plz explain me this format of declaring variable specially ".<BitmapData>" part....
    Thanx..

    A Vector is a special kind of array than can only hold one 'type' of data. So in your example, the array _history will only hold BitmapData objects. This makes the access of the array much faster. Contrast this with _myArray:Array that might contain a mixture of object types as in:
    _myBitmap:Bitmap
    _myMovieClip:MovieClip
    _myArray = new Array();
    _myArray.push(_myBitmap);
    _myArray.push(_myMovieClip;
    If you pushed _myMovieClip into your _history Vevctor, you would get an error at run time since _myMovieClip is not a BitmapData object.
    You can see more here:  http://help.adobe.com/en_US/AS3LCR/Flash_10.0/Vector.html

  • "Reset" declared variables to initialized state?

    Hiya!
    This might sound like a very stupid question, but I have not figured out a way to do this. I am working on a "personal information manager", where users can enter a date in a lovely swing textfield, it get's parsed to Integer and a GregorianCalendar is created with it. Once I created the Calendar, the TextFields are emptied again, but of course the Integer instance variables are still declared with the old values. This leads to the fact that a user could click "add date" again and a date is created without entering any number at all.
    My question:
    Is it possible to set declared variables back to the state they had when initialized? They should be "empty"...
    I can`t set them null...
    Thanks for your help, it's much appreciated!

    The only type of variable where "empty" has any meaning is for an empty string: "". Otherwise there is no empty. Objects are by default initialized to null, numeric primitives to zero, and I think chars to '' but I could be mistaken about that one - I never use chars. So if you're using Integers, they could either be null, or an Integer - nothing else.

  • Declare Variable in Smartforms from BT and EPF tables

    Hi All,
    I am developing a smartform to display the payslip of employees.
    In my smartform I need to use fields from the BT table and EPF Table.
    I need to declare variables for the same fields in smartform.
    How can this be achieved.
    Any pointers or suggestions would be helpful.
    Thanks,
    Saher

    Hi
    Please search with the search term smartforms and u will get many threads which will answer your question.
    In  general, in form interface of smartform we declare the tables whose values are passed from the print program.
    IN global definitions, we declare the variables we use in the smartform.
    Regards,
    Vishwa.

  • Declare Variable Data Types

    From my understanding, there is no need to declare variables
    data type like String, Number, Array for it to function. For
    example:
    var abc:String = "abcde";
    var abc:Number = 1234;
    var abc:Array = new Array();
    We can write it in easier way and it is still working.
    abc = "abcde";
    abc = 1234;
    abc = new Array();
    So, what is the purpose and benefit to declare the variable
    specific data type?

    i mean that as3 (= actionscript 3) requires variable typing
    in most situations or the flash compiler will throw an error.
    and no, failing to use strict typing won't cause any
    debugging problems.
    there's also some "feeling" that strict typing enhances code
    efficiency, but i haven't seen anything convincing on this.

Maybe you are looking for

  • Remote for Apple TV

    I lost my Apple TV remote and now my iPad will not work as a remote. It's telling me to turn on home sharing from my Apple TV.. But I can't without remote. Help

  • How to find out if a user has a deferred task

    In my WF, I will add a deferred task to a user. If that user already has a deferred task then i want to skip it. How do we find out if a user already has a deferred task? Thanks

  • Excel import to numbers- date format issue?

    importing excel to numbers means my date format goes to a 5-digit number. I've ensured that the Excel cells are correctly formatted as dates but it keeps happening. Any ideas?

  • Collapsible Panel within another Collapsible Panel HEIGHT ISSUE

    Having an issue with the height of a collapsible panel that has another collapsible panel within it not adjusting. I am using Dreamweaver CS5. When I try the fix of changing line 431 in .js  (where you change "px" to "auto" where it says this.content

  • Airport Extreme Base Station Dual Band has WiFi problems.

    I can only connect my Droid X to the wifi network of my Apple Airport Extreme?  I have an Ipad and another computer with a wifi dongle but none of them will connect.  Only ethernet connected computers and my DroidX works. Any suggestions?