Newbie Q'n -- Calling class methods without instantiation

Hello All,
I would like to know how is it possible to call methods within a class without instatiating the class.
For instance consider the following statement:
String x = Integer.toString(10);
Here there we are calling the toString() function of "Integer" class without instantiating it. How is it possible?? How does the JVM call the toString() function when there is no Integer object defined in my program?? Can the same functionality achieved for user created classes ??
Can anyone explain ??
If this appears as a trivial question, please forgive me.
Thanks in advance,
Arun

String x = Integer.toString(10);
Here there we are calling the toString() function of
"Integer" class without instantiating it. How is it
possible?? How does the JVM call the toString()
function when there is no Integer object defined in my
program?? Can the same functionality achieved for user
created classes ?? It isn't possible, and its not happening in your example either:
toString() is an instance method. toString(int) and toString(int, int) are class (static) methods.
You might see documentation referring to a toString (notice no "()" at the end) method. When you do, it should usually be clear from the context which particular method is being referred to.
Such confusion might well have been avoided if the original API designers had thought to call the methods something different (perhaps format?), but they didn't (in fact, toString(int) seems rather pointless).

Similar Messages

  • Does calling class methods from bean and JSP cause collision?

    Hi,
    Please look at the class below:
    public class X
    // no member variable
    public X() {}
    // pay attention to static keyword
    public static int getY()
    Think a bean (say BeanZ) that make calls to getY() method without initializing the class X (like this: X.getY() )
    And think many users having "page scope" in JSP make call to BeanZ or directly calls it from JSP.
    I'm wondering if any collision occurs because of STATIC method? Should I use "SYNCHRONIZED" keyword with it? If so, what about Math.cos() which also is a non synchronized static method ? Shouldn't I use Math.cos() (and the other static methods) in JSP or bean?
    Thank you for your help.
    Ali Sadik

    Hi,
    Thank you for your quick answer. Think my class like this:
    public class X
    // no member variable
    public X() {}
    // pay attention to static keyword
    public static int[] getY(int a, int[] b)
    // i know there is no need for the extra array.
    // just for example ;)
    int[] ret = new int[b.length];
    for(int i = 0; i < b.length; i++)
    ret[i] = a * b;
    return ret;
    Does it the type of class that you've mentioned ? It makes calculation to produce dynamic result. Shouldn't I use it as static ? If your answer is yes, what about Math.cos()? Doesn't it have dynamic calculation?
    Thanks a lot.

  • Newbie: How to call a method when a JFrame closed ?

    Hya,
    how I can call a method to perform some operations when the JFrame's close(x) button is pressed?
    thanks in advance

    try this
    (change System.exit(0) if you don't want to close the app)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      public Testing()
        setLocation(300,200);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);//<---------
        setSize(300,200);
        addWindowListener(new WindowAdapter(){//<-----------
          public void windowClosing(WindowEvent we){
            someMethod();
            System.exit(0);}});
      public void someMethod()
        JOptionPane.showMessageDialog(this,"Closing...");
      public static void main(String[] args){new Testing().setVisible(true);}
    }

  • Calling varargs method without varargs parameter.

    Hello
    I really appreciate your help on clarifying the following problem.
    1) I have method signature as
    public User validateUser(User usr, boolean isLogin,Object...args)
    2) When I call this method as
    obj.validateUser(usrObject,true);
    In windows environment, the method implementation specified in 1) is called and no issues.
    But, when the same code is deployed on linux, I get the following error
    java.lang.NoSuchMethodError: com.mysubpackage.dao.myobject.*validateUser(Lcom/startf orce/system/User;Z)Lcom/startforce/system/User;*
    Please let me know, if there is any known incompatibility issue out there between windows and linux.
    Thanks
    Muthu

    Hi Jverd
    You are right! I think I worked too much and got lost somewhere, to prove me wrong I wrote the following test class and ran on both linux and windows and produced the same result (as it should). -:) Thanks all of you for responding.
    public class VarArgsTest {
          * @param args
         public static void main(String[] args) {
               VarArgsTest test = new VarArgsTest();
               System.out.println("\nCalling varArgs with two parameter as test.printVarArgs(\"I am Param1 Value\", \"I am Param2 value\")");
               test.printVarArgs("I am Param1 Value", "I am Param2 value");
               System.out.println("Calling varArgs with three parameter as test.printVarArgs(\"I am Param1 Value\", \"I am Param2 value\", \"I am Param3 value\")");
               test.printVarArgs("I am Param1 Value", "I am Param2 value","I am Param2 value");
         public void printVarArgs(String param1, String param2, Object...objects) {
              System.out.println("\nparam1 = "+param1+"\nparam2 = "+param2);
              System.out.println();
              System.out.println(" param3 [Object...objects] length = "+objects.length);
              System.out.println();
              if(objects.length > 0)
                   System.out.println("Param 3 is not empty and its first value is  = "+objects[0]);
              else
                   System.out.println("Param 3 is  empty and nothing to display, it is an empty array ");
    Output
    Calling varArgs with two parameter as test.printVarArgs("I am Param1 Value", "I am Param2 value")
    param1 = I am Param1 Value
    param2 = I am Param2 value
    param3 [Object...objects] length = 0
    Param 3 is empty and nothing to display, it is an empty array
    Calling varArgs with three parameter as test.printVarArgs("I am Param1 Value", "I am Param2 value", "I am Param3 value")
    param1 = I am Param1 Value
    param2 = I am Param2 value
    param3 [Object...objects] length = 1
    Param 3 is not empty and its first value is = I am Param2 value
    Edited by: Startup_Muthu on Mar 12, 2008 11:41 AM
    Edited by: Startup_Muthu on Mar 12, 2008 11:43 AM

  • Calling class method

    Hi,
    In classical report we click on the pattern and write the funciton module name there to get the import and export parameter of the fucntion.
    Can somebody tell me how to call the class method in the program with the parameters coming automatically .
    Thanks

    hi Arvind,
    Click on pattern.
    Choose ABAP object pattern radio button and press enter.
    You have four radio button-the first one call method is for your requirement.
    Enter the object instance name, class name and method name and press enter.
    You will get the call method for this instance of the class.
    Hope this helps.
    Regards,
    Richa

  • Calling class methods from jsp

    hi - this seems like it should be painfully obvious but I am missing something somewhere and can't seem to get it to work.
    The end result I am looking for is to be able to call a method similar to how I would do it in PHP or ASP.
    To do this I have writte the following class (just as an example) and combpiled it to /WEB-INF/classes/com/example/util/Echo.class:
    package com.example.util;
    class Echo
    public static void main(String[] args)
    System.out.println(args[0]);
    I then have a sample JSP that I attempt to use this in that looks like:
    <%@ page import="com.example.util.Echo" %>
    <%
    RDmail("I'm using my Echo class.");
    %>
    My expectation would be that when I run this page in a browser, I see the text "I'm using my Echo class." printed out on the page. Instead I get the following error:
    An error occurred at line: 1 in the jsp file: /classtest.jsp
    Generated servlet error:
    [javac] Compiling 1 source file
    /var/tomcat4/work/Standalone/localhost/raindance/classtest_jsp.java:47: cannot resolve symbol
    symbol : method Echo (java.lang.String)
    location: class org.apache.jsp.classtest_jsp
    Echo("I'm using my Echo class");
    ^
    1 error
    What am I doing wrong?

    Umm... I'm not entirely sure what you're attempting to do, but it looks like there's some discrepancy between your error message and your code...
    RDmail("I'm using my Echo class."); in your code
    and
    Echo("I'm using my Echo class"); in your error message.
    Is this just a cut/paste error?
    Also, the main() method is only called from a command line, and will not be run when you instantiate your bean in a JSP. If you want to have your String printed out when you create a new object, you should put the print statement in the constructor. Which would then be called when you created a new object..
    Echo e = new Echo("I'm using my Echo class");
    Or, you could create a static method inside Echo.java that prints out the statement.
    Finally, your System.out most likely will not print to your browser, but probably to a standard log, or perhaps a command window.

  • Error calling class methods CL_GUI_FRONTEND_SERVICES

    Hi all,
    I have a requirement in BAPI (integrating solman to portal) to download file from app. server to local directory. I used the below FM to get temp directory of presntation server.
    CALL METHOD CL_GUI_FRONTEND_SERVICES=>GET_TEMP_DIRECTORY
       CHANGING
         TEMP_DIR             =  LV_TEMP_DIR
       EXCEPTIONS
         CNTL_ERROR           = 1
         ERROR_NO_GUI         = 2
         NOT_SUPPORTED_BY_GUI = 3
         others               = 4.
       CALL METHOD cl_gui_cfw=>flush.
    It works fine in R3, but when i called it from portal it shows Access not possible using 'NULL' object reference with a short dump .
    st22 shows
    Error in ABAP application program.
    The current ABAP program "CL_GUI_FRONTEND_SERVICES======CP" had to be
    terminated because one of the
    statements could not be executed.
    This is probably due to an error in the ABAP program.
    An exception occurred. This exception is dealt with in more detail belo
    . The exception, which is assigned to the class 'CX_SY_REF_IS_INITIAL',
    neither
    caught nor passed along using a RAISING clause, in the procedure
    "GET_TEMP_DIRECTORY" "(METHOD)"
    Since the caller of the procedure could not have expected this exceptio
    to occur, the running program was terminated.
    The reason for the exception is:
    Attempt to access a component using 'NULL' object reference (points
    to nothing).
    An object reference must point to an object (an instance of a class)
    before you can use it to access components (variable:
    "CL_GUI_FRONTEND_SERVICES=>HANDLE").
    Either the reference has not yet been set, or it has been reset to
    'NULL' by a CLEAR statement.
    When i put external break point and the dump comes during execution of CALL METHOD cl_gui_cfw=>flush.
    Is it not possible to use CL_GUI_FRONTEND_SERVICES in RFC ??.
    thanks and regards
    Jijo

    [CL_GUI_FRONTEND_SERVICES|https://www.sdn.sap.com/irj/sdn/advancedsearch?cat=sdn_all&query=cl_gui_frontend_services+portal&adv=false&sortby=cm_rnd_rankvalue] needs a SAPGUI, so it is not possible to use it in RFC, BSP or other portal.
    Regards

  • How call native method without code modification

    "How to access third party's C API from Java Using JNI without modifying the C code"

    Unfortunately, the only way I know of doing this is to use a pass-through DLL that you write. Logically it
    looks like this:
    Java App (written by you)
    |
    v
    Java native methods (written by you)
    |
    v
    JNI DLL (written by you)
    |
    v
    3rd party DLL
    It adds a little bit of overhead, but it's not too big of a deal. Check out the JNI tutorial on how to write this.
    Bryan

  • Calling class methods from listSelectionListener

    Hi,
    I have a GUI class which containt a few Jlist. I also have two listSelectionListener classes. How do I reach methods in the GUI class from the listSelection classes. Can I pass a reference of GUI to them somehow?
    Karl XII

    For the benefit of future readers, the answer is yes, either in your listSelectionListener constructor, or a listSelectionListener method you implement. In either case, just set a listSelectionListener member variable (added by you) to the desired value.

  • Call a methode without opening the main view

    Hi,
    I have a function that calls a web dynpro application. The handledefault methode of the window from this web dynproapplication searches for a url of a picture and opens it with my browser.
    This works well.
    But there are two windows open: my picture and the empty web dynpro main view.
    How can I stop this? I just want the window with my picture.
    Thanks,
    Martina.

    Hi Manigandaan,
    I deleted  the empty main view from the webdynpro window.
    But the result is always the same:
    1 empty window and
    1 window with my url
    this is the code in the handledefault (after the data declaration):
    DATA lo_window_manager TYPE REF TO   if_wd_window_manager.
       DATA lo_api_component  TYPE REF TO   if_wd_component.
       DATA lo_window         TYPE REF TO   if_wd_window.
       DATA ld_url            TYPE          string.
       lo_api_component  = wd_comp_controller->wd_get_api( ).
       lo_window_manager = lo_api_component->get_window_manager( ).
    ld_url = lv_doclink.
      data lo_api_controller type ref to if_wd_view_controller.
      data lo_window_ctlr TYPE REF TO if_wd_window_controller.
      lo_api_controller = wd_this->wd_get_api( ).
      lo_window_ctlr = lo_api_controller->GET_EMBEDDING_WINDOW_CTLR( ).
    * get the control for window to be closed
      lo_window = lo_window_ctlr->get_window( ).
    * this will close the window
      lo_window->close( delete_window = abap_true ).
    if the ld_url is i.e. 'http://www.google.com' I get one browser window with google and another
    browser window which is empty. The URL of this empty browser window is the url with which
    i called the web dynpro application. But I don't need this window, how can I avoid this?
    Thank you very much!!!
    Martina

  • Calling a method within an application?

    Hi I'm a student taking an intro Java class and right now I have to develop and application that prompts for someone to input a character of the alphabet and it will display the corresponding number on a telephone that it is listed under. The main method gets the input from the user and we are required to retrieve the corresponding digit to the character from a separate method using either a switch statement or a nested if-then-else statement to determine what the digit is. I'm having trouble calling that method in the main class which is another requirement. any suggestions?
    public class Hmwk08
         * Main driver begins program execution.
         * @param args program arguments
        public static void main(String[] args) throws Exception
            char letter;
            char ch;
            int relatesTo;
            PrintStream win = new PrintStream(System.out);
            Scanner in = new Scanner(System.in);
            String newLine = System.getProperty("line.separator");
            win.println("Given a letter of the alphabet, this program" + newLine
                        + "will tell you the corresponding digit on a" + newLine
                        + "telephone keypad.");
            win.println();
            win.print("Enter a letter: ");
            letter = in.nextLine().charAt(0);
            letter = Character.toUpperCase(letter);
         * Get the digit on a telephone keypad that corresponds
         * to the specified character. If the character is neither
         * a letter nor a digit, this method will retun the
         * asterisk character: '*'
         * @param letter the specified character
         * @return the corresponding digit
        private static char getPhoneDigit(char letter)
            char digit;
            digit = '*';
            if(letter == 'A' || letter == 'B' || letter == 'C')
                digit = '1';
            return digit;
    }

    Your method is static so you can call your method without creating a Hmwk08 object.
    char result = getPhoneDigit(letter);Would suffice in your main method
    Mel

  • In webdynpro ,Passing field symbols as values to class methods

    Hi
    Please tell me the ways of accessing database in webdynpro abap(not directly). I am calling Class method for accessing database. As currently I am directly accessing database in my webdynpro application. I have created a class and method for the same.
    In my method I want to use select statement which will return table with values to webdynpro application. So for select statement(Calling Method) I need to use my field symbol values as where in clause .
    Could anyone please help with example code?
    Thanks,
    Ujjwal

    data: in_line type ref to data.
    CREATE DATA in_line LIKE LINE OF <dyn_tab>.
      ASSIGN in_line->* TO <dyn_wa>.
    You can create a data reference and assign it to a field symbol and change the values. direclty passing field symbols is not possible.
    Abhi

  • Automatically detect the caller class!

    Guys,
    I have a simple but "sounds-like-general-and-interesting" doubt..
    I have a class 'A' and another class 'B'. I have a method in 'A' called 'a' calling a method in class 'B' (which is 'b').
    suppose the control is inside the method 'b' of the class 'B'.
    Now, the doubt is
    how can I find out that it was class 'A' who called the method 'b' of class 'B' from within the method 'b'?
    the scenario is a simpe loging scenario where the class 'B' is a Logger class and I want to automatically detect the class calling this component from within this component so that it can be logged too.
    Hope my problem is clear. Thankx in advance for the replies.. am stuck and confused too.. and hop there's a solution for this
    regards
    Manesh

    mgumbs is right - typically a Logger class will accept a context (Object) to indicate where the message has come from. Sometimes people pass in "this", sometimes they pass in "this.class" or sometimes they'll log on behalf of another class. It's pretty much the same solution - if it's needed you should supply it.
    One method made possible in J2SDK-1.4 is using a stack trace to find out what the calling class/method is. Perhaps the only way to do that would be to throw a new Exception and get hold of its stack trace elements. I suspect that this would add significant overhead, though, and I certainly wouldn't recommend it!

  • How to call a instance method without creating the instance of a class

    class ...EXCH_PRD_VERT_NN_MODEL definition
    public section.
      methods CONSTRUCTOR
        importing
          value(I_ALV_RECORDS) type ..../EXCH_VBEL_TT_ALV
          value(I_HEADER) type EDIDC .
      methods QUERY
        importing
          I_IDEX type FLAG
          i_..........
        returning
          value(R_RESULTS) type .../EXCH_VBEL_TT_ALV .
    Both methods are instance methods.
    But in my program i cannot created instance of the class unless i get the results from Query.
    I proposed that Query must be static, and once we get results we can create object of the class by pasing the result table which we get from method query.
    But i must not change the method Query to a static method.
    Is there any way out other than making method Query as static ?
    Regards.

    You can't execute any instance method without creating instance of the class.
    In your scenario, if you don't want to process your method of your class, you can check the instance has been created or not.
    Like:
    IF IT_QUERY IS NOT INITIAL.
      CRATE OBJECT O_QUERY EXPORTING......
    ENDIF.
    IF O_QUERY IS NOT INITIAL.
    CALL METHOD O_QUERY->QUERY EXPORTING....
    ENDIF.
    Regards,
    Naimesh Patel

  • Can we call a static method without mentioning the class name

    public class Stuff {
         public static final int MY_CONSTANT = 5;
         public static int doStuff(int x){ return (x++)*x;}
    import xcom.Stuff.*;
    import java.lang.System.out;
    class User {
       public static void main(String[] args){
       new User().go();
       void go(){out.println(doStuff(MY_CONSTANT));}
    }Will the above code compile?
    can be call a static method without mentioning the class name?

    Yes, why do it simply?
    pksingh79 wrote:
    call a static method without mentioning the class name?For a given value of   "without mentioning the class name".
        public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws Exception {
            Class<?>[] types = new Class<?>[args.length];
            for(int i=0;i<args.length;++i) types[i] = args==null?Object.class:args[i].getClass();
    return Class.forName(className).getDeclaredMethod(methodName,types).invoke(null,args);

Maybe you are looking for

  • Problems installing Photoshop CS6 Extended

    Hello to whoever is reading this - I have a problem installing Photoshop CS6 Extended (as you can guess from the title) due to the fact that I download a pre release version of it (not the beta) And I've looked everywhere on my laptop and I still can

  • "SQL Developer" vs. "SQL Developer Data Modeler"

    Hi Everybody! I'm using SQL Developer and I miss functionalities like re-engeneering of ER Models. As far as I know this is what the "SQL Developer Data Modeler" does. So my question is: Is the "SQL Developer Data Modeler" a complete replacement for

  • I lost mouse operation all together. on my G5 DP 1.8

    I work with a logitech wireless trackball and keyboard that I've had for quite a while, say 9 months maybe 10. They have been flawless, but today, thought the keyboard is working fine, the mouse seemed a little sluggish so I decided to look at the lo

  • Save as *.jpg instead of *.JPG

    Hey People, I need some help... I have two problems in Photoshop CS5. Is there somebody with a solution. 1. When i open a RAW (.nef) file it always want to save as a .PSD file. In the past always had .jpg as standard. Is there a preference setting to

  • Forms 4.5 and oracle 8 compatibilty

    We are still working with oracle7.3.4 and forms 3. Now we are upgading to forms 4.5 and in the future we will upgrade to oracle8. I would like to know whitch vertions are compatble (oracle and developer)