Does static methods need to be synchrnized ?

Hi All,
I have some class (static) methods in my program running on Server-A, which call a service running on Server-B over HTTP. My program is accessed by different client threads which pass values for my class method's parameters, and my class method will return the value that it got from the service returned by Server-B.
In such scenarion, which of the following options is better, and if you have any other option that suits well to this situation, please suggest:
option 1: synchronize the static methods.
option 2: modfiy the class methods to instance methods.
option 3: leave it as it is, there is no problem.
thanks,
darbha.

It looks you have to synchronize the static method (option 1).
Only one client thread may use the HTTP connection at a time.

Similar Messages

  • Should I use a static method or an instance method?

    Just a simple function to look at a HashMap and tell how many non-null entries.
    This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
    Does this have to be an instance method? Or is it perfectly fine to use a static method?
    public static int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    OR
    public int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    }

    TPD Opitz-Consulting com wrote:
    The question is the other way around: Is there a good reason to make the method static?
    Ususally the answer is: no.The question is: does this method need state? Yes -> method of a class with that state. No -> static.
    The good thing of having this method statig is that it meight decrese memory foot pring but unless you're facing memory related problem you should not think about that.I doubt there is any difference between the memory foot print of a static or not method.
    I'm not shure if this method beeing static maks problems in multithreaded environments like the one you're aiming at. But I do know that an immutable object is always thread save.Does the method use shared state (data)? No -> no multi threaded problems.
    Can the parameters be modified by different threads? Yes, if multiple threads modified the parameter map, but nothing you can do about it here (no way to force the calling thread to lock on whatever you lock on).
    So my answer to your question is: yes, it should be non static.The method should be static since it uses no state.
    It is thread-safe when only the calling thread can modify the passed map (using a synchronized or ConcurrentHashMap is not enough, since you don't call a single atomic method on the map).
    // Better use Map instead of HashMap
    // We don't care about the generic type, but that does not mean we should use a raw type
    public static int countNonNullEntries(Map<?, ?> map) {
      // whether to accept null map or not, no need for explicit exception
      // since next statement throw NPE anyway
      Collection<?> values = map.values();
      // note your method is called countNonNull, not countNull!
      // (original code it would need to by if(null != mapValue) notNullsCounter++;
      return values.size() - java.util.Collections.frequency(values, null);
    }

  • Declaring static methods.

    I have some questions about declaring a method as static. If I first write a paragraph about my understanding so far, followed by a code snippet hopefully somebody can help me out.
    It is my understanding (limited) that only one class is loaded by the classloader. When creating an object, all its parameters are stored, but each object does not have its own copy of the methods its class defines, each method. If a method is declared as static then you do not have to create an instance of this class to call this method.
    Code
    /** Get table of codes.
          * @return <code>Hashtable</code> populated with clinical code values.
        public Hashtable getCodeHashtable(HttpServletRequest request) {
            Hashtable htResults = new Hashtable();
            try {
                SpParameter[] spOut = {
                    new SpParameter(OracleTypes.CURSOR, 0)//po_cur_data
                 HOUtils utils = new HOUtils();
                UtilDBquery db = utils.getUtilDBquery(request);
                htResults = db.runGeneralStoredProcedureThrowsExceptions(null, spOut, SP_CodeList, null, true, true);
            } catch (Exception e){
                 e.printStackTrace();
            return htResults;
    Questions
    1) If each object does not carry around its own copy of the methods associated with its class, how does the jvm know which object is calling a method?
    2) In the above code snippet, if I were to make the method static would this have implications if 2 people were to browse to the same page on the app server and run this method at the same time?
    Thanks for any replies.

    1) If each object does not carry around its own copy of the methods
    associated with its class, how does the jvm know which object is
    calling a method?Each object stores one single pointer to its class description. The class
    description contains all the methods (also the static ones). This is a bit
    of a simplification but basically that's all there is to it. When you call
    a method, the address of the method is looked up in that class description
    and it's invoked. For non static methods there's a hidden parameter,
    called 'this' so the method always 'knows' which object it (the method)
    is invoked on. For static methods that hidden parameter simply isn't
    present.
    2) In the above code snippet, if I were to make the method static
    would this have implications if 2 people were to browse to the same
    page on the app server and run this method at the same time?Who knows? This all depends whether or not the method (static or not)
    is reentrant, i.e. does the method have side effects? Does the method
    needs to be synchronized?
    kind regards,
    Jos

  • Non-static method getContentPane() cannot be referenced from a static conte

    From this line I'm getting an error
    Container bmC = getContentPane();
    - non-static method getContentPane() cannot be referenced from a static context
    Aprecciate solution,
    thx

    The reason this is happening is that you can't call non-static methods from a static method. Non-static methods need an instance in order to be called. Static methods are not associated with an instance.

  • Why do we need private static method or member class

    Dear java gurus,
    I have a question about the use of private and static key words together in a method or inner class.
    If we want to hide the method, private is enough. a private static method is sure not intended to be called outside the class. So the only usage I could see is that this private static method is to be called by another static method. For inner class, I see the definition of Entry inner class in java.util.Hashtable, it is static private. I don't know why not just define it as private. Could the static key word do anything better.
    Could anybody help me to clear this.
    Thanks,

    What don't you get? Private does one thing, andstatic does >something completely different.
    If you want to listen to music, installing an airconditioner doesn't help>
    Hi, if the private keyword is the airconditioner, do
    you think you could get music from the static keyword
    (it acts as the CD player) in the following codes:You're making no sense and you're trying to stretch the analogy too far.
    Private does one thing. If you want that thing, use private.
    Static does something completely different and unrelated. If you want that thing, use static.
    If you want both things, use private static.
    What do you not understand? How can you claim that you understand that they are different, and then ask, "Why do we need static if we have private"? That question makes no sense if you actually do understand that they're different.

  • Need Urgent Help with static methods!!!!

    If I have a static method to which a variable is being passed...for example
    static String doSomething(String str)
    //..doSomething with str and return
    If the method is invoked a second time by a separate entity when it is already in use by one entity(!!!not entity beans) .... will this lead to the second invocation overwriting str while the method is already in use and thus corrupting the variable that the method was passed from the first entity?

    It's also a common misunderstanding about parameters. The method does not receive a variable as its parameter, it receives a reference to an object. And inside the method, the parameter acts just the same as a local variable would. So if two threads call the method (static or not), each thread has its own copy of the parameter.

  • I really need abstract static methods in abstract class

    Hello all.. I have a problem,
    I seem to really need abstract static methods.. but they are not supported.. but I think the JVM should implement them.. i just need them!
    Or can someone else explain me how to do this without abstract static methods:
    abstract class A {
    abstract static Y getY();
    static X getX() {
        // this methods uses getY, for example:
        y=getY();
       return new X(y); // or whatever
    class B extends A {
    static Y getY() { return YofB; }
    class C extends A {
    static Y getY() { return YofC; }
    // code that actually uses the classes above:
    // these are static calls
    B.getX();
    A.getX();I know this wont compile. How should i do it to implement the same?

    Damn i posted this in the wrong thread.. anyways.
    Yes offcourse i understand abstract and static
    But i have a problem where the only solution is to use them both.
    I think it is theoretically possible ot implement a JVM with support for abstract static methods.
    In fact it is a design decision to not support abstract static methods.. thats why i am asking this question.. how could you implemented this otherwise?
    There is an ugly soluition i think: using Aspect Oriented Programming with for example AspectJ.. but that solution is really ugly. So anyone has an OO solution?

  • NEED HELP WITH USING STATIC METHOD - PLEASE RESPOND ASAP!

    I am trying to set a value on a class using a static method. I have defined a servlet attribute (let's call it myAttribute) on my webserver. I have a serlvet (let's call it myServlet) that has an init() method. I have modified this init() method to retrieve the attribute value (myAttribute). I need to make this attribute value accessible in another class (let's call it myOtherClass), so my question revolves around not knowing how to set this attribute value on my other class using a static method (let's call it setMyStuff()). I want to be able to make a call to the static method setMyStuff() with the value of my servlet attribute. I dont know enough about static member variables and methods. I need to know what to do in my init() method. I need to know what else I need to do in myServlet and also what all I need in the other class as well. I feel like a lot of my problems revolve around not knowing the proper syntax as well.
    Please reply soon!!! Thanks in advance.

    class a
    private static String aa = "";
    public static setVar (String var)
    aa = var;
    class b
    public void init()
    a.aa = "try";
    public static void main(String b[])
    b myB = new b ();
    b.init();
    hope this help;
    bye _drag                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Need some explanations regarding static Method

    Hello,
    I have a code where a class has a static method access by other classes. This not working as I thought and I would like to understand why.
    Here below is the code.
    Here is a class having the static method "test"
    package test;
    public class StaticTest {
        public StaticTest() {
        public static void test (int i){
        while (i < 1000){
            System.out.println("i = " + i );
            i++;
    }Here is the code of another class (Thread) using this static method. This Thread can be initialized with an integrer value that will be passed to the static Method.
    package test;
    public class ThreadTester extends Thread {
        int x;
        public ThreadTester(int i) {
            x=i;
        public void run(){
            StaticTest.test(x);
    }Here is the code starting 2 Thread running in parallel and both are then calling the static method.
    //start 2 thread accessing the static method.
          ThreadTester test1 = new ThreadTester(0);
          ThreadTester test2 = new ThreadTester(200);
          test1.start();
          test2.start();
    ...As the second thread is started with a bigger value I thought that we would only have seen few printouts from the first thread starting by 0 and then printouts starting by 200.
    Here is what I thought regarding the result:
    i = 0
    i = 1
    i = 2
    i = 3
    i = 200 --> startup of the second thread, x in static method is overriden (at least this is what I thought!)
    i = 201
    i = 202
    i = 203
    i = 204
    i = 205
    i = 206
    i = 207
    i = 208
    i = 209
    But the real result is:
    i = 0
    i = 1
    i = 2
    i = 3
    i = 4
    i = 5
    i = 200
    i = 6
    i = 201
    i = 202
    i = 203
    i = 204
    i = 205
    i = 206
    i = 7
    i = 207
    i = 208
    i = 209
    i = 8
    It seems that there is 2 instances running in parallel. I thought that it would'nt be the case with the word "Static".
    Also I don't understand the result because if I use JBuilder in Optimizer mode I can see that there is only one instance of StaticTest object.
    Can anyone here explain me how is that possible?
    Thanks in advance for your help.
    Regards,
    Alain.

    >
    thread test1 creates its own stack and starts incrementing �i� starting at values 0. However, in the middle of incrementing, it gets kicked out by the OS (or JVM) into a �blocked� state to allow other threads to run. BUT before leaving the running state, test1 saves the stack state including the value of �i�.
    >
    Ok, now I understand, but then I have another question.
    What is the difference between the code shown in my first post and the following where we create 2 instances of StaticTest class (which is not static in this case for sure).
    How to decide (while coding) if it is better to use difference instances of class or not?
    package test;
    public class StaticTest {
        public StaticTest() {
        public void test (int i){ //Not static anymore
        while (i < 1000){
            System.out.println("i = " + i );
            i++;
    }We create new instance in the Thread.
    package test;
    public class ThreadTester extends Thread {
        int x;
        public ThreadTester(int i) {
            x=i;
        public void run(){
    StaticTest newInstance = new StaticTest(); //Create a new instance
            newInstance .test(x);
    }Alain

  • Using HttpServletRequest object to share variables between static methods.

    Does anyone know of the overhead/performance implications of using the HttpServletRequest object to share variables between a static method and the calling code?
    First, let me explain why I am doing it.
    I have some pagination code that I would like to share across multiple servlets. So I pulled the pagination code out, and created a static method that these servlets could all use for their pagination.
    public class Pagination {
         public static void setPagination (HttpServletRequest request, Config conf, int totalRows) {
              int page = 0;
              if (request.getParameter("page") != null) {
                   page = new Integer(request.getParameter("page")).intValue();
              int articlesPerPage = conf.getArticlesPerPage();
              int pageBoundary = conf.getPageBoundary();
                int numOfPages = totalRows / articlesPerPage;  
                // Checks if the page variable is empty (not set)
                if (page == 0 || (page > numOfPages && (totalRows % articlesPerPage) == 0 && page < numOfPages + 1)) {    
                 page = 1;  // If it is empty, we're on page 1
              // Ex: (2 * 25) - 25 = 25 <- data starts at 25
             int startRow = page * articlesPerPage - (articlesPerPage);
             int endRow = startRow + (articlesPerPage);           
             // Set array of page numbers.
             int minDisplayPage = page - pageBoundary;
             if (minDisplayPage < 1) {
                  minDisplayPage = 1;     
             int maxDisplayPage = page + pageBoundary;
             if (maxDisplayPage > numOfPages) {
                  maxDisplayPage = numOfPages;     
             int arraySize = (maxDisplayPage - minDisplayPage) + 1;
             // Check if there is a remainder page (partially filled page).
             if ((totalRows % articlesPerPage) != 0) arraySize++;
             // Set array to correct size.
             int[] pages = new int[arraySize];
             // Fill the array.
             for (int i = 1; i <= pages.length; i++) {
                  pages[i - 1] = i;
             // Set pageNext and pagePrev variables.
             if (page != 1) {
                  int pagePrev = page - 1;
                  request.setAttribute("pagePrev", pagePrev);
             if ((totalRows - (articlesPerPage * page)) > 0) {
                 int pageNext = page + 1;
                 request.setAttribute("pageNext", pageNext);
             // These will be used by calling code for SQL query.
             request.setAttribute("startRow", startRow);
             request.setAttribute("endRow", endRow);
             // These will be used in JSP page.
             request.setAttribute("totalRows", totalRows);
             request.setAttribute("numOfPages", numOfPages);
             request.setAttribute("page", page);
             request.setAttribute("pages", pages);          
    }I need two parameters from this method (startrow and endrow) so I can perform my SQL queries. Since this is a multithreaded app, I do not want to use class variables that I will later retrieve through methods.
    So my solution was to just set the two parameters in the request and grab them later with the calling code like this:
    // Set pagination
    Pagination.setPagination(request, conf, tl.getTotalRows());
    // Grab variables set into request by static method
    int startRow = new Integer(request.getAttribute("startRow").toString());
    int endRow = new Integer(request.getAttribute("endRow").toString());
    // Use startRow and endRow for SQL query below...Does anyone see any problem with this from a resource/performance standpoint? Any idea on what the overhead is in using the HttpServletRequest object like this to pass variables around?
    Thanks for any thoughts.

    You could either
    - create instance vars in both controllers and set them accordingly to point to the same object (from the App Delegate) OR
    - create an instance variable on the App Delegate and access it from within the view controllers
    Hope this helps!

  • Help with writing a static method in my test case class inside blue j

    I have this method that I have to test. below is the method I need to test and what I have to create inside my test case file to test it Im having big time problems getting going. Any help is appreciated.
    public String introduceSurprise ( String first, String last ) {
    int d1 = dieOne.getFace();
    Die.roll();
    if (d1 %4 == 2){
    return Emcee.introduce(first);
    else {
    return this.introduceSpy (first,last);
    So how do write tests to verify that every fourth call really does give a randomized answer? Write a static method showTests which
    creates an EmCee,
    calls introduceSurprise three times (doing nothing with the result (!)),
    and then calls it a fourth time, printing the result to the console window.
    Write this code inside your test class TestEmCee, not inside EmCee!

    hammer wrote:
    So how do write tests to verify that every fourth call really does give a randomized answer? Write a static method showTests which
    creates an EmCee,
    calls introduceSurprise three times (doing nothing with the result (!)),
    and then calls it a fourth time, printing the result to the console window.
    Write this code inside your test class TestEmCee, not inside EmCee!Those instructions couldn't be anymore straightforward. Make a class called TestEmCee. Have it create an EmCee object. Call introduceSurprise on that object 3 times. Then print the results of calling it a 4th time.

  • How to get the current class name in static method?

    Hi,
    I'd like to get the current class name in a static method. This class is intended to be extended. So I would expect that the subclass need not to override this method and at the runtime, the method can get the subclass name.
    getClass() doesn't work, because it is not a static method.
    I would suggest Java to make getClass() static. It makes sense.
    But in the mean time, does anybody give an idea to work around it?
    Thank you,
    Bill

    Why not create an instance in a static method and use getClass() of the instance?
    public class Test {
       public static Class getClassName() {
          return new Test().getClass();

  • Non-static method/object cannot be referenced from a static context...?????

    What does this mean. I know about static, but I don't understand why I get this so many times.
    I try to do something pretty normal and this is what I get a lot of times. I mean: the main() method should be static right? Then what good is the main() method if you cannot let it do stuff for you like this:
    public class Test extends JFrame
        public Test
            setSize( 100, 100 );
            show();
    public static main( String args[] )
        Test window = new Test();
        draw();
    public void draw()
        blablabla whatever I want to do, a lot of times I can't.....
    }Why is this, what is the reason for Java to forbid this and what can I do about it?

    Your draw() method, since it isn't defined as static is considered by Java to be part of your Test object; hence, it can only be invoked in the context of an existing instance of your object. In other words, any Java program that wanted to use your draw() method would have to create an instance of your Test class using something likemyTest = new Test()Your main method, however, is something different. Since you want to execute your class as a program, the Java run-time environment needs to have standard starting point. This starting point is the main method. The problem is that the main method must be static, because the run-time environment cannot be expected to know beforehand the correct way to create an instance of your class so that non-static methods can be invoked. The drawback is that your main method can only directly access methods that are defined as static.
    There are two possible solutions to this problem, and which of the two you want to use depends on the object-oriented nature of your program.
    On the one hand, if your draw() method is closely tied to the object itself, if the draw() method is actually drawing your object or a part of it, it should be left as an instance method, and you should simpy use the instance of the object you created in your main method:public static main( String args[] )
        Test window = new Test();
        // maybe some code to generate something to draw???
        window.draw();
    }This is what I think you are trying to do.
    On the other hand, if your draw() method was some kind of universal method that didn't depend in any way on the current configuration of your instance, you could simply define draw() as static at which point your main method (or a method in an external class) could invoke it directly, without a corresponding instance. But if you did that, the draw() method itself would only be able to access static variables and methods.
    Doug

  • Non-static method close() cannot be referenced from a static context

    Friends,
    I am having a little help with some static and not static issues.
    I created a JMenuBar, it's in the file: SlideViewMenu.java
    One of the operations is File->Close and another is File->Exit.
    The listener is in the SlideViewMenu.java file. The listener needs to reference two non-static methods within SlideView.java.
    Here's some of the code:
    SlideViewMenu.java
    public class SlideViewMenu {
        public JMenuBar createMenuBar() {
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
         // All the menu stuff works fine and is taken care of here.
       // Listener for Menu
       class MenuActionListener implements ActionListener {
         public void actionPerformed (ActionEvent actionEvent) {
              String selection = (String)actionEvent.getActionCommand();
             if (selection.equals("Close"))
              SlideViewFrame.close();
             else  SlideViewFrame.exit();
    }SlideView.java
    // Driver class
    public class SlideView {
         public static void main(String[] args) {
              ExitableJFrame f = new SlideViewFrame("SlideView");
                    // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame {
            // some things here, work fine.
         private SlideViewMenu menuBar = new SlideViewMenu();
         public SlideViewFrame(String title) {
         // Set title, layout, and background color
         super(title);
         setJMenuBar(menuBar.createMenuBar());
            // Stuff here works fine.
         // Handles doing stuff once the file has been selected
         public void setFileName(File fullFileName, String simpleName) {
            // Stuff here works fine.     
         // File->Close. clean up everything.
         public void close() {
              setTitle("SlideView");
              textArea.setText("");
              scrollBar.setVisible(false);
              textArea.setVisible(false);
              statsPanel.setVisible(false);
         // File->Exit.     
         public void exit() {
              System.exit(0);
    }The error I'm getting is:
    SlideViewMenu.java:50: non-static method close() cannot be referenced from a static context
    I don't get it?
    Thanks for all help.

    Making close() and exit() static would not solve the problem because close() requires access to nonstatic member variables/functions.
    Fortunately, that is not necessary. The real reason you are having a problem is that you don't have any way in your listener to access the main frame window, which is what the listener trying to control. You made a stab at gaining access by prefixing the function with the class name, but, as the compiler has informed you, that is only valid for static methods. If you think about it, you should see the sense in that, because, what if you had a number of frames and you executed className.close()? Which one would you close? All of them?
    Fortunately, there is an easy way out that ties the listener to the frame.
    SlideViewMenu.java:public class SlideViewMenu
      // Here's where we keep the link to the parent.
      private SlideViewFrame parentFrame;
      // Here's where we link to the parent.
      public JMenuBar createMenuBar(SlideViewFrame linkParentFrame)
        parentFrame = linkParentFrame;
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
        // All the menu stuff works fine and is taken care of here.
      // Listener for Menu --- It is assumed that this is a non-static nested
      // class in SlideViewMenu. All SlideViewMenu variables are accessible from
      // here. If this is not the case, simply add a similar member variable
      //  to this class, initialize it with a constructor parameter, and
      // pass the SlideViewMenu parentFrame when the listener is
      // constructed.
      class MenuActionListener implements ActionListener
        public void actionPerformed (ActionEvent actionEvent)
          String selection = (String)actionEvent.getActionCommand();
          // Use parentFrame instead of class name.
          if (selection.equals("Close"))
              parentFrame.close();
            else
              parentFrame.exit();
    }SlideView.java// Driver class
    public class SlideView
      public static void main(String[] args)
        ExitableJFrame f = new SlideViewFrame("SlideView");
        // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame
      // some things here, work fine.
      private SlideViewMenu menuBar = new SlideViewMenu();
      public SlideViewFrame(String title)
        // Set title, layout, and background color
        super(title);
        //Here's where we set up the link.
        setJMenuBar(menuBar.createMenuBar(this));
      // Stuff here works fine.
      // Handles doing stuff once the file has been selected
      public void setFileName(File fullFileName, String simpleName)
        // Stuff here works fine.     
      // File->Close. clean up everything.
      public void close()
        setTitle("SlideView");
        textArea.setText("");
        scrollBar.setVisible(false);
        textArea.setVisible(false);
        statsPanel.setVisible(false);
      // File->Exit.
      public void exit()
        System.exit(0);
    }

  • Abstract static methods

    Hello,
    I've written an abstract class, called AbstractNetworkParticipant. I've also written two sub classes that extend this class. I'm in the process of writing a Viewer class that I'm intending to parameterized with some subclass of AbstractNetworkParticipant,
    public class Viewer<T extends AbstractNetworkParticipant> I would like to include a couple of static methods that return Strings for Labeling information to a particular subclass in the Viewer.
    So for example, if I have NetworkUser and NetworkAdministrator, both of which extend AbstractNetworkParticipant, I would like to set the text of a JLabel labeling the participant's name to "User Name", or "Administrator Name" depending on the type of participant being viewed.
    I would like the method that returns these strings to be static, so that I don't have to have an instance of the current subclass when I initializes the JLabel. An abstract method cannot be static. I attempted to make a non-abstract static method in the abstract class,
      public static getDescriptor() {
         return "Participant";
      }and then override it in each sub class to a more descriptive string (User, or Administrator). However, when I reference the method, it always invokes the method defined in the abstract parent class, rather than in the subclass, whichever it may be.
    Can anyone suggest a solution. Should I just forget about the method being static? Is there a better way to implement a solution to this problem?
    Thanks
    Edited by: paulwooten on Mar 27, 2009 9:58 AM

    paulwooten wrote:
    The whole point of my original post was in order to learn something about Java that I'm not particularly familiar with. I was having a difficult time articulating the problem precisely, so I tried to draw an analogy between C++ and Java. It turns out I was mistaken in the way C++ works. Fortunately I described my problem adequately enough to both 1. be corrected about how virtual functions actually work in C++, and 2. get advice on how to approach the problem in Java. I never claimed I was a C++ expert, or that I was asking a question about C++. I was just trying to explain my problem as precisely as possible.
    I don't mean to disrespect, but your post, and slimy's aren't nearly as constructive as all the other posts that actually addressed my question; either to me personally, or to anyone else who has a similar question and may happen to read this thread. It's not like I dumped a bunch of C++ code here and begged someone to translate it for me. I asked a question, to the best of my ability, several other forum members replied (without giving me a mini lecture on how to learn Java), and now the problem is resolved.Sorry for the confusion. I wasn't complaining about your post. My post wasn't directed at you at all. It's fine to know C++, and to ask how to do something similar in Java. As you said, that wasn't even how you asked your original question. You asked a legitimate question to learn Java, a few people made suggestions, you made a comparison to C++, and people corrected your understanding both of C++ and Java. That's all well and good, and it's a fair way to learn. I see no problem with any of that.
    What exactly does "learn Java properly" mean? Read the tutorials and pretend like no other programming languages exist?I was referring to slimy's post where he talked about "knowing C++ properly if you use it as an input to Java". The point of my post was supposed to be that "you can know C++ properly, but +you shouldn't always use that as your input to Java+". A very simple example I've seen of what I meant by "non-proper" Java code, in real [but +bad+ ] Java code at a real company is for String comparison:
    String abc = "abc";
    String xyz = "xyz";
    String another = "xyz";
    if (abc.compareTo(xyz) != 0) { // Not "proper" Java
       doSomething();
    if (xyz.compareTo(another) == 0) { // Not "proper" Java
       doSomethingElse()
    }To me, that looks like someone who copied their C++ knowledge (or, at least, C knowledge) to the extreme. In C, the only function to test equality of two C "strings"--i.e., "null-terminated char arrays" is 'strcmp', and you test equality of the strcmp result to 0 to determine whether two "null-terminated char arrays" represent the same thing:
    char abc [] = "abc";
    char xyz [] = "xyz";
    char another [] = "xyz";
    if (strcmp(abc, xyz)) { // could include explicit != 0, but not needed in C
       doSomething();
    if (!strcmp(xyz, another)) { // anything non-zero is true in C, so !0 is true
       doSomethingElse();
    }"compareTo" sounds like "strcmp", and the comparison to 0 is the same in my above examples.
    But, in Java, there is a real "equals" method for Strings, and it should be used:
    String abc = "abc";
    String xyz = "xyz";
    String another = "xyz";
    if (!abc.equals(xyz)) { // "proper" Java
       doSomething();
    if (xyz.equals(another)) { // "proper" Java
       doSomethingElse()
    }I would argue that using "compareTo" to test equality of Strings in Java is "non-proper" Java, and using "equals" to test equality of Strings in Java is "proper" Java. That was my definition of "learning Java properly".
    I certainly don't think anyone learning Java needs to pretend that no other programming languages exist--it is fine to know other languages, and to look for the similarities (and differences). However, someone learning Java (or any other language new to them) does need to know that things don't work the same in all languages, so, if they base all of their knowledge by trying to get Java to work exactly the same as C++ (or whatever previous language they knew), their Java will not be "proper" Java. There are often multiple ways to do things "properly" in Java, but copying a C++ program verbatim into Java syntax is not necessarily going to result in the best Java code that you could have. When doing the translation from another language to Java (I realize that isn't your goal, but for some people, that is the goal), you need to be sure that your Java code follows Java rules and standards, and not just assume that the architecture of your Java code should be the same as the architecture of your code in the original language.
    I hope that clarifies my intentions. As I said, I wasn't directing my previous comment to you. I think your question and learning approach are absolutely fine.

Maybe you are looking for