A basic question about static variables and methods

What would be the effects if I declare lots of static variables and static methods in my class?
Would my program run faster?
Would the class take more memory spaces? (If so, how do I estimate an appropriate number of variabls and methods to be declared static?)
Thank you @_@

when you declare a static var the var isn't created for every instance of the class, it just "live" in the class
when you declare a static method is the same, so if you have:
class MyClass
static int myMethod()
//Method work
you dont need to have a instance of the class to call myMethod, you can do such things like this.
int value = Myclass.myMethod();
if myMethod isn't static you can't do this.. so, if
class MyClass
int myMethod()
//Method work
you CAN'T call
int value = MyClass.myMethod();
instead, you have to write
MyClass m;
m = new MyClass();
value = m.myMethod();

Similar Messages

  • Static and non-static variables and methods

    Hi all,
    There's an excellent thread that outlines very clearly the differences between static and non-static:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=374018
    But I have to admit, that it still hasn't helped me solve my problem. There's obviously something I haven't yet grasped and if anyone could make it clear to me I would be most grateful.
    Bascially, I've got a servlet that instatiates a message system (ie starts it running), or, according to the action passed to it from the form, stops the message system, queries its status (ie finds out if its actually running or not) and, from time to time, writes the message system's progress to the browser.
    My skeleton code then looks like this:
    public class IMS extends HttpServlet
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            doPost(request, response);
       public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          //get the various parameters...
             if (user.equalsIgnoreCase(username) && pass.equalsIgnoreCase(password))
                if(action.equalsIgnoreCase("start"))
                    try
                        IMSRequest imsRequest = new IMSRequest();
                        imsRequest.startIMS(response);
                    catch(IOException ex)
                    catch(ClassNotFoundException ex)
                else if(action.equalsIgnoreCase("stop"))
                    try
                        StopIMS stopIMS = new StopIMS();
                        stopIMS.stop(response);
                    catch(IOException ex)
                 else if(action.equalsIgnoreCase("status"))
                    try
                        ViewStatus status = new ViewStatus();
                        status.view(response);
                    catch(IOException ex)
             else
                response.sendRedirect ("/IMS/wrongPassword.html");
    public class IMSRequest
    //a whole load of other variables   
      public  PrintWriter    out;
        public  int                 messageNumber;
        public  int                 n;
        public  boolean         status = false;  //surely this is a static variable?
        public  String            messageData = ""; // and perhaps this too?
        public IMSRequest()
        public void startIMS(HttpServletResponse response) throws IOException, ClassNotFoundException
            try
                response.setContentType("text/html");
                out = response.getWriter();
                for(n = 1 ; ; n++ )
                    getMessageInstance();
                    File file = new File("/Users/damian/Desktop/Test/stop_IMS");
                    if (n == 1 && file.exists())
                        file.delete();
                    else if (file.exists())
                        throw new ServletException();
                    try
                        databaseConnect();
                   catch (ClassNotFoundException e)
    //here I start to get compile problems, saying I can't access non-static methods from inside a static method               
                   out.println(FrontPage.displayHeader()); 
                    out.println("</BODY>\n</HTML>");
                    out.close();
                    Thread.sleep(1000);
            catch (Exception e)
        }OK, so, specifially, my problem is this:
    Do I assume that when I instantiate the object imsRequest thus;
    IMSRequest imsRequest = new IMSRequest();
    imsRequest.startIMS(response); I am no longer in a static method? That's what I thought. But the problem is that, in the class, IMSRequest I start to get compile problems saying that I can't access non-static variables from a static method, and so on and so on.
    I know I can cheat by changing these to static variables, but there are some specific variables that just shouldn't be static. It seems that something has escaped me. Can anyone point out what it is?
    Many thanks for your time and I will gladly post more code/explain my problem in more detail, if it helps you to explain it to me.
    Damian

    Can I just ask you one more question though?Okay, but I warn you: it's 1:00 a.m., I've been doing almost nothing but Java for about 18 hours, and I don't do servlets, so don't take any of this as gospel.
    If, however, from another class (FrontPage for
    example), I call ((new.IMSRequest().writeHTML) or
    something like that, then I'm creating a new instance
    of IMSRequest (right?)That's what new does, yes.
    and therefore I am never going
    to see the information I need from my original
    IMSRequest instance. Am I right on this?I don't know. That's up to you. What do you do with the existing IMS request when you create the new FrontPage? Is there another reference to it somewhere? I don't know enough about your design or the goal of your software to really answer.
    On the other hand, IMSRequest is designed to run
    continuously (prehaps for hours), so I don't really
    want to just print out a continuous stream of stuff to
    the browser. How can I though, every so often, call
    the status of this instance of this servlet?One possibility is to pass the existing IMSRequest to the FrontPage and have it use that one, rather than creating its own. Or is that not what you're asking? Again, I don't have enough details (or maybe just not enough functioning brain cells) to see how it all fits together.
    One thing that puzzles me here: It seems to me that FP uses IMSReq, but IMSReq also uses FP. Is that the case? Those two way dependencies can make things ugly in a hurry, and are often a sign of bad design. It may be perfectly valid for what you're doing, but you may want to look at it closely and see if there's a better way.

  • Question about session variables and binding

    Hi All,
    I'm a newbie with Application Express. I've gone through several tutorials and a book, and now I'm actually getting started with apex. My first adventure is a tiny little form, where all you do is fill it out and it sends an email. Pretty simple.
    And, i have it working just fine - but I have a question about something I don't quite understand. Basically, I am generating the email text in a page process. And some of the form fields work fine if i reference them as *:ACCT_NAME*, but some give me the dreaded "not all variables bound" error. For the ones that give me the error, I can reference them like V('ACCT_NAME').
    So, as a newbie, I'm a little confused. When is it appropriate to use the V function, and when it is appropriate to use binding? Why would one of the fields work with binding but not another from the same form?
    Thanks for any clarification you can offer,
    Lisa

    Lisa,
    A bind variable is a place holder variable available in an environment.It is used quite frequently(outside Apex Context) in SQL and PLSQL scripts and especially in Dynamic SQL statements.Many times using a bind variable gives better performance. In the Apex environment,page items and many other variables related to the session are available as bind variables and hence their value can be referred in SQL,PLSQL contexts as :VARIABLE_NAME.
    Now V() function is an apex specific function which returns the value of an apex session variable outside the apex environment. So as Machaan pointed out, it is used in
    procedures and triggers that gets called from within an apex session. This is required since the bind variables themselves are not directly available in the SQL environment but their values from the corresponding session can be accessed by this apex built-in function.
    The length of any Bind variable name is limited to 30 characters, this is a limitation inherited from Oracle SQL itself and hence session variables(page or application items) whose name has a length which exceeds 30 characters cannot be used as the :ITEM_NAME format. In such cases you would have to use the v() method again. This might be happening in your case.

  • Basic questions about connection sharing and radio mode

    I just got TC and have a couple of basic questions.
    At home I have a D-Link ADSL modem/router (no wifi) plugged into the wall, and would like TC to provide wifi. I've connected the WAN port to some LAN port of the router and everything works fine. The intented usage of the setup is wifi-only. Would you recommend TC to do DHCP/NAT? Or is Bridge mode better? In the latter case I don't fully understand who's routing the wifi network (though it actually works).
    Second question is about radio mode. My wife has an iBook G4 that is not capable of talking 801.11n, so I selected the n mode compatible with b/g. In that mode my black MacBook will still be able to talk 801.11n with TC? The iBook has very low usage, it is fine that computer uses 801.11g for TC, but I'd like the MacBook to go full-speed. (If that's not possible I'd ponder purchasing an 801.11n adaptor of some sort for the iBook.)

    Would you recommend TC to do DHCP/NAT? Or is Bridge mode better?
    It doesn't matter.
    In the latter case I don't fully understand who's routing the wifi network (though it actually works).
    The D-Link modem/router.
    In that mode my black MacBook will still be able to talk 801.11n with TC?
    Yes. It will only suffer lower bandwidth if the iBook G4 is actively connected.

  • Some basic questions about foriegn key , and relationships.

    Hi
    Thank you for reading my post
    I read some documents about foreugn key and tables relation ships.
    but i still can not understnad some stuff.
    1-when we have a foreign key , we have two tables that we want to relate them together
    in a way that one of ? table columns forced to be a value from ?? table column.
    what is name of those two tables , i saw , child-parent , ..... which confuse me.
    can some one please tell me correct name of those two tables ?
    2-some times we need some kind of master details relation like :
    one-to-many : i this case MANY table will have a column to point a record in ONE table , can this relation be a foreign key relation ?
    3-we can achieve many-to-many relation only by using a helper table to host both tables primary keys in a record to relate them together.
    can you point me to some resources that help me to find answers to this questions ?
    or explain them to me ?
    thank you for your time.

    These are critical database basics that you need to understand. I would seriously recommend getting some study in, because proper relational database design relies on the basic principle of data and relationships and a process called normalization.
    In reality, you only really need one gigantic table to host data. It would include everything you would want to know about something - let's take a sales order for example. You would have to record the customer's name, address, etc. along with every item they ordered, etc. You would have a HUGE table full of data that appeared over and over and over again. This is bad design for two basic reasons: it is difficult to query, and it is very easy to have minor mistakes like capitalization or alternate spellings that prevent things from matching up properly. For example, let's say Bob orders 40 widgets and 40 digits. In our hypothetical table, we could put it in as Bob - 40 widgets and Robert - 40 digits. See how confusing this can get even in a simple example? And let's say you wanted to correct all of Robert's orders to say Bob and you found out there were 40 orders from "Robert" How would you know which ones to change?
    The process of normalization helps to reduce the chance for these types of errors in addition to creating a good basis for indexes. You normalize the data by creating sets of parent/child tables with a "key" value to match them. In our hypothetical situation, you could create a table for orders and a table for customers. In the customers table you give all the detail for the customer in one place, and you assign each customer a unique number or ID. In the orders table we add the customer ID (NOT the name) and we ensure that we are getting the customer we want, in addition to saving a lot of space and eliminating redundancy. In our example, the customers table is the "parent" table and the orders table is the "child" table. The child table references the unique entries in the parent table via that id. That reference is referred to as a foreign key. The foreign key in the child table points back to the original and complete record in the parent table and eliminates the redundancy of keeping all that extra data for every order. Foreign keys in child tables always refer to a primary/unique key in the parent field.
    That help?

  • Best Practice:  Using a static variables and methods vs singleton pattern

    Just curious, since when anything, within a class, is denoted as static it typically will be stored in main memory as a class property(method, variables, etc). Is it a good practice to be doing this all the time or is the singleton pattern a better choice. Please explain why. Thanks.

    I wouldnot make anything other than the constants and the instance itself static. And I cant think of a reason wjy one would.

  • Basic questions about Bigdata, NOSQL and Hadoop

    Hi,
    I've basic questions related to Bigdata. (I've googled it but still wants to confirm with experts)
    Please correct me if I am wrong on below.
    1) As far as I know big data is collection of unstructured data. Even we can store relational data as well.
    2) NOSQL is an Oracle product to handle bigdata (un structured data and relational data as well)
    3) Hadoop is the only one frame work which is avilable in market to manage the bigdata.
    What are the other database systems we have in the market to manage the bigdata.
    Cheers,
    Suri

    Hi Suri,
    1)  "Big Data" does not have a crystal clear, black and white definition. 
    It is generally characterized as being the processing and management of an amount and type of data that makes a specific workload on that data slow and/or expensive.
    Most commonly, Big Data involves processing and management of unstructured data of large volume and the typical technology used to store/process it is Hadoop, However, on occasion a NoSQL database will also deal with unstructured data.
    Big Data is also seen often in the form of simple, semi-structured data of both large volume and/or large velocity and the typical technology used to store/process it is a NoSQL database.  However, on occasion Hadoop will also deal with semi-structured data of large volume.
    In some cases, Big Data is seen in the form of highly connected data that will be manipulated by advanced algorithms that will need to touch a lot of the data and the typical technology used to store/process it is a Graph type of NoSQL database.
    2)  NoSQL is a category of database technologies most often dealing with the issues as outlined in bullet 2 above.   The Oracle NoSQL Database is oracle's product in the NoSQL category of database technologies.   It does NOT store relational data.   When using NoSQL relations between the data must be managed within the application code.
    3)  Hadoop and NoSQL booth manage Big Data, but different aspects as discussed in (1) above.   Hadoop is a batch based, slow processing data technology, but the "slow" is relative because it can process very large amounts of data, so minutes is commonly seen as fast.   NoSQL is a near real-time data processing technology and typically deals with Big Data where access times are in the single digit millisecond range.
    Hope this helps,
    -Robert

  • Question about shared variables and report generator

    I have a project with about 200-250 shared variables and at every 12 hours i want to make a report containing information about some boolean and double front panel variables linked to the shared variables... Now, i've tried with both the "Write Trace to SpreadSheet File" function from DSC->History and with different functions from NI Report Generation Toolkit. My problem is this: i would like to get my xls file to contain just the timestamps when my shared variable changed value. As it is, the number of rows in the file depends, obviously, on the sampling interval given as input. As an example, in 12 hours, my shared variable would change value maybe 5-6 times. Thus i would like my xls file to contain just 5-6 rows with those 5-6 changes. If i set the sampling interval to say, a matter of seconds, that would mean too much unneeded information in my xls file. Instead, if i set it to let's say 15 minutes, i would probably lose the moment the shared variable changed value. Is there a way for me to achieve my desired functionality with functions from DSC or Report Generation Toolkit? Thanks in advance, Sabin 

    Hi Mike and thanks for the reply. Actually, my first idea was exactly this: in an event case structure, whenever my variable changed value, i would retain the relevant data in an array and then at the 12 hour period write all of it in a report. However, my boss deeemed it memory unefficient and compelled me to use only one function. Thus my predicament... If you have more advice on this new info, i would be grateful... Cheers, sabin

  • Basic question about Java, UNIX and OAS

    Hi,
    Can I create an appication that contains GUI components like testbox and textfields etc...and then load/import it into OAS?
    Can I again, create such an GUI application and then load it UNIX platform and run it?
    The reason I asked because I did create an application which has a frame, a panel and couples of buttons, text fields then ftp it to Unix Solaris, when I ran it with jre command, I got the following message:
    java.lang.NoClassDefFoundError: Javax/Swing/UIManager at cms.CMSApp.main(compiled code) Exception in thread main
    Please anyone help me to clarify this, I don;t if we can do such things but I did not do it the right way? or we cannot do it at all. Thanks for your help
    Minh

    I'm not sure I understand where OAS fits in here.. Is this an applet?
    In any case, it sounds like the JDK version you are using is 1.1.x, and swingall.jar is not in the classpath.
    If it's an applet, then you need to edit the HTML file and add in swingall.jar.
    If it's an application, you need to edit the CLASSPATH environment variable and append the full path to swingall.jar
    (note: in Java2 (JDK 1.2, 1.3) swingall.jar is no longer seperate, it is part of the runtime classes of java, so you don't have to add anything to the classpath)
    Take Care,
    Rob
    null

  • [JS] Basic question about event listeners and event handlers

    I am very new to the whole topic of event listeners and event handlers.  I'd run the test for the following problem myself, but I don't know where to start, and I just want to know if it's impossible -- that is, if I'm misunderstanding what event listeners and event handlers do.
    Say I have an InDesign document with a text frame that is linked to an InCopy story.  Can I use an "afterImport" event listener on the text frame to perform some action any time the link to the InCopy story gets updated?  And will the event handler have access to both the story that is imported, and the pathname of the InCopy file?
    Thanks.

    Thank you, Kasyan.
    Both of those are good solutions.
    We are currently using InDesign CS4 and InCopy CS5.  I'm hoping to get them to purchase the whole CS5 suite soon, since I'd like to start writing scripts for InDesign CS5 as soon as possible, as long as I'm going to have to be doing it in the not too distant future anyway.  The greater variety of event handlers sounds like it might be something that is crucial to the project I'm working on, so that adds to the argument for getting CS5.
    Thanks again.  You have no idea how helpful this is.  I made some promises to my boss yesterday that I later realized were  based on assumptions of mine about the InDesign/InCopy system that didn't make any sense, and I was going  to have to retract my promises.  But after reading your response I think I can still deliver, in a slightly different way that I had been thinking before.
    Richard

  • Basic Questions about JSF, Login and Session

    Hi,
    I try to implement a login/logout function on my jsf-website. I create one <form> with Login and Pass to enter. My AuthenticBean(sessionbean) checks login and pass. If Login is "ok" the login and pass will set in the authenticBean (min. value of login and pass = 2).
    Now I check protected .jsf files (files who need a login) if in the AuthenticBean the login.equals("") or pass.equals(""). If so, the user is not logged in.
    Is this a safe method or should I choose a better way to have secure login/logout functions. Perhaps its better to create a userSessionBean after a succeful login and check it with HttpServletRequest rq.getSession().getAttribute(userSessionBean)?
    I am confused a little bit and I hope you'll help me:)
    Thnx Alex

    Implement a javax.servlet.Filter and indeed use the attributes of the HttpSession.

  • Basic questions about word spacing and vertical alignment with CSS

    I'm sill very new to Dreamweaver and web page designing. I've
    read the entire manual SC3, one book, and starting another but I
    have almost 0 practice.
    Q1. so far I haven't been able to produce the effect of the
    Word Spacing property. I tried all kinds of tests and I don't know
    in what scenario this effect will show. Can someone give me a
    simple example that shows the effect of this CSS property.
    Q2. Vertical Alignment: this works well with images inserted
    into text but I also expected this to work with text against other
    text. For example I typed TEST© and assigned a different SCC
    style to the © so that I can make it smaller and put it up
    with the Vertical Alignment property. Surprisingly this propery
    didn't produce any effect. How is htis suppose to be done?

    > This is some text. This is some text.
    You forgot to wrap your text in <p> tags so the style
    rule you created
    doesn't apply.
    Walt
    "emil emil" <[email protected]> wrote in
    message
    news:[email protected]...
    >
    quote:
    Originally posted by:
    Newsgroup User
    > i don't know about Q1. but for Q2. just delete what you
    already have for
    > the copyright symbol, and then insert the copyright
    special character.
    > there's a couple ways to do it: on the main menu at the
    top of the
    > window, go to Insert, then HTML, then Special
    Characters, and select
    > Copyright. or you can also find it in the Insert panel,
    which is below
    > the menu, under Text. ...
    >
    >
    > Thanks courtney, but that was exactly the way I created
    the © character
    > and
    > like in this text here it needs to be scaled down and
    moved up
    > independently
    > from the surrounding text. Can someone please post a
    simple code showing
    > the
    > effect of the vertical alignment of text in relation to
    surrounding text.
    >
    >
    >
    quote:
    Originally posted by:
    Newsgroup User
    > Q1
    >
    > <html>
    > <head>
    > <style type="text/css">
    > p
    > {
    > word-spacing: 30px
    > }
    > </style>
    > </head>
    > <body>
    >
    > <p>
    > This is some text. This is some text.
    > </p>
    >
    > </body>
    > </html>
    >
    >
    > Thank you Ken, your code works but not the code
    generated from
    > Dreamweaver
    > when I type in the Design View and assing CSS style to
    the p tag. Does
    > Dreamweaver have trouble generating properly working
    HTML or I'm missing
    > something here? Here is the code that Dreamweaver
    generates and the word
    > spacing doesn't work with it.
    >
    > <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Transitional//EN"
    > "
    http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    > <html xmlns="
    http://www.w3.org/1999/xhtml">
    > <head>
    > <meta http-equiv="Content-Type" content="text/html;
    charset=utf-8" />
    > <title>Untitled Document</title>
    > <style type="text/css">
    > <!--
    > p {
    > word-spacing: 50em;
    > }
    > -->
    > </style>
    > </head>
    >
    > <body>
    > This is some text. This is some text.
    > </body>
    > </html>
    >
    >
    >

  • Basic questions about downloading updates and smartnet licensing

    I have been trying to get a definitive answer to these questions by browsing around cisco.com, but so far no luck.
    1. I manage an ASA5510 for which there is no current smartnet contract.  It is running an outdated code version (8.2) of the Security Plus license.  Is it allowable to download the 8.4 image and upgrade the ASA as long as I stay within the Security Plus license, or would there be a fee?
    2. Same question in general for routers without smartnet: If I have a router running old v12.x code is is permissible to upgrade to 15.x code as long as the featureset remains the same?
    3. If I were to purchase a new ASA feature license (e.g. SSL VPN 50 users) and then install it on this ASA, would the license be recoverable if the ASA were to become unusable because of a hardware failure?
    Help on any of these questions would be greatly appreciated.  All doc I have found so far either seems either contradictory or ambiguous.
    Thanks,
    -Mathew

    Answer 1:
    If you do not have a SMARTnet agreement for the device that you support, you will be unable to download updates for that device. You will need to have a CCO login with an active SMARTnet agreement for that device.
    Answer 2:
    Same answer to question 1 applies to routers. You will be unable to download updates if that device does not have an active SMARTnet agreement.
    Answer 3:
    If you add a feature, like updating the user license, you will be unable to transfer it to a new unit. This is because the license is bound to the device serial number. The new device will have a different serial number.
    Just to mention also, If you add a feature and have an active agreement, you will need to purchase a new agreement to cover that feature. The original agreement only covers the original device. If it goes bad and needs replacing, you will receive a replacement like the original. It will not contain the added license and you will be unable to install the license on the replacement unit because the license is bound to the serial number. The replacement will have a different serial number.
    Sent from Cisco Technical Support iPad App

  • Very basic questions about JSP server and plug-in.

    Hi all,
    I am wondering what are other ways to make use of the JSP script on a server running normal Apache without changing it to Tomcat. Is there a plug-in version of JSP for Apache that will enable JSP? I am looking for something like PHP plug-in, which is quite generic. They even have a php.exe that OHTTP (a great shareware Win32 web server) can call to run PHP. Is there such thing along this line with JSP on Win32 or Linux? Thanks!

    You need a jsp/servlet engine, and in effect, Tomcat is the "plug-in" you described. Tomcat has basic web server functionality built in, so it can run stand-alone, but it's most commonly used with a robust web server like Apache. You don't have to "change it" to Tomcat - you just configure Apache to forward specific urls (anything ending in *.jsp, for example) to Tomcat.

  • Simple question about environment variables and setting the class path???

    ok I have been trying for a few months now ontrying to set the class path..
    I work with windows vista..
    on the environment variables user variables,
    I have the name of the variable as class
    and the value as C:\Program Files\Java\jdk1.6.0_04\bin;.
    where javac is...
    on the system variables I have
    its name as class
    and the value as C:\Program Files\Java\jdk1.6.0_04\bin;.
    why is this not reading javac

    The PATH environment variable should have as an entry the directory containing your javac executable. The CLASSPATH should have have entries which define your library directories and entries which are your jar file libraries. In the early days, probably the only CLATHPATH entry you will need will be a '.' to indicate the current directory.
    The Java tutorial covers ALL of this.

Maybe you are looking for