Strange Code Sample without method name

I have come across this code sample in a test. I answered that, it gives compile errors, coz theres a block of code without any method name, which prints "nothing".
But I tried to compile and run it, which put me in surprise. It compiled and executed. I did not understand how it worked and whats the concept behind this.
Can anyone dig into details or share knowledge if already know this.
Heres the code:
public class Test1
     public static void main(String args[]){
          new Test1();
          System.out.println("main...");
          new Test1("2222");
     Test1(){
          System.out.println("in constr 1");
     Test1(String s){
          System.out.println("in constr 2 :" + s);
          System.out.println("nothing...");
     static{
          System.out.println("static...");
}

>      {
          System.out.println("nothing...");
     static{
          System.out.println("static...");
     }Those are initializer blocks; The static block is executed when the
class has been loaded; the first block is executed just before a
constructor for that class is called.
kind regards,
Jos

Similar Messages

  • Where will i get the method code and method name in Bpc

    Dear Experts,
    Thanks for watching this thread at the time of creating Consolidation methods they have
    NEW
    HOLDING
    GLOBAL
    PROPORTIONAL
    EQUITY
    lEAVING (END OF THE YEAR)
    LEAVING(DURING THE YEAR)
    Where will i get the method Code and method name.
    Can you please guide me.
    Regards,
    Srinivasan.

    The consolidation methods types you have listed are the standard ones  provided by BPC for Consolidation Method types.
    You can set the Consolidation Methods in the BPC Administration Console under Business Rules Library -> Consolidation Methods.
    There you can see some defaults - you can remove these and set your own if you prefer.
    You should read the BPC340 Training guide.

  • How to sort a list of strings, without methods and stuff just simple code?

    Hi
    How to sort a list of strings, without methods and stuff just simple code?
    Thanks in adavance!!

    Without methods? How are you going to all the sort code? What is the point of code?
    Collections.sort(List) will sort strings or anything that implements the Comparable interface, or you can use the sort method that takes a Comparator implemenation.
    If you want "just code", you could either get the Collections class souce and follow it to the code. But otherwise, there isn't one set of code. There are various sorting algorithms with advantages and disadvantages. Maybe you'd be better off searching for sorting algorithms and if you understand them, it should be simple to write Java implementations of them.

  • Code will not compile when changing method name in related class

    Hello all! I'm wondering if anyone can help a second-time poster. I have a class called Transcription which holds the artist name and song title of a guitar transcription. Transcription has a method toString() which returns a String containing the artist name and title. I have a class GuitarMag which holds a vector of Transcription objects, and has a method WriteGuitarMag() which returns a String containing, among other things, the toString() method for each Transcription in the transcriptions vector. I wanted to change the method name in Transcription to writeTranscription() for consistency, but when I refer to that method in WriteGuitarMag(), GuitarMag gives an error to the effect that the writeTranscription() method does not exist.
    This works fine:
        //Transcription object
        public String toString(){
            return "" + artistName + "\t\t" +  songName;
        //GuitarMag object
        public String WriteGuitarMag() {
            StringBuffer tmp1 = new StringBuffer();
            //find out how many components are in the vector
            int transCount = this.transcriptions.size();
            StringBuffer tmp = new StringBuffer("Name: " + this.getMagName() + "\n" +
                   "Cover: " + this.getCoverDesc() + "\n" +
                   "Date: " + this.getMagDate() + "\n" +
                   "Transcriptions:" + "\n");
            for (int i = 0; i < transCount; i++) {
                tmp1.append(this.transcriptions.elementAt(i).toString() + "\n");
            tmp.append(tmp1);
            return tmp.toString();
        }But this does not:
        //Transcription object
        public String writeTranscription(){
            return "" + artistName + "\t\t" +  songName;
        //GuitarMag object
        public String WriteGuitarMag() {
            StringBuffer tmp1 = new StringBuffer();
            //find out how many components are in the vector
            int transCount = this.transcriptions.size();
            StringBuffer tmp = new StringBuffer("Name: " + this.getMagName() + "\n" +
                   "Cover: " + this.getCoverDesc() + "\n" +
                   "Date: " + this.getMagDate() + "\n" +
                   "Transcriptions:" + "\n");
            for (int i = 0; i < transCount; i++) {
                tmp1.append(this.transcriptions.elementAt(i).writeTranscription() + "\n");
            tmp.append(tmp1);
            return tmp.toString();
        }Any thoughts or feelings about this?

    Thanks for your reply. Yes, I compiled the Transcription class first, and then the GuitarMag class, so it shouldn't have been a problem. In thinking about it more today, I'm wondering if I need to cast the vector component to a Transcription object first. Because all objects have the toString() method, it works without casting, but if I rename the method it doesn't?

  • Junit : How can I get the method name (say testMyAddress) that failed

    My code is below
              TestSuite masterSuite = new TestSuite(testClass);
              TestResult result = new TestResult();
              masterSuite.run(result);
                   Enumeration errors = result.errors();
                   while (errors.hasMoreElements())
                        TestFailure error = (TestFailure)errors.nextElement();
                        Test test = error.failedTest();
    /*will give me the class name but how can I get the method that threw the exception.
    I can get fName (that contains the method name) field to get the method,but being private I cannot hold of the field.
    Wondering if there is any easy way to get the method name that threw exception,without writing unneccessary code
                        Class c1 = test.getClass();
    thx
    m

    getting all methods is no good!
    My test class looks like this
    MyTestClass{
    testGoodData(){
    asserttrue(.....);
    testBadData(){
    asserttrue(.....);
    testNullData(){
    asserttrue(.....);
    someHelperMethod(){
    thx
    m

  • Code sample of sendRedirect using Web Dynpro NetWeaver 6.4

    Hi ALL,
      I’m building a Web Dynpro application under Netweaver Developer Studio 6.4 and I need to redirect to another URL while the client click on a button. 
      I know it should be something like request.getServletResponse(true).sendRedirect("myURL");
    But I’m not sure how to get the request, or the response in order to apply the sendRedirect method.
      Do you have any code sample or Web documentation I could use to redirect my Web Dynpro application?
    Best regards,

    Hello Jean-François,
    To navigate to http://www.yahoo.com you have 2 options:
    1) Call
    WDClientUser.forceLogoffClientUser("http://www.yahoo.com");
    2) Define Outbound plug with name Url in interface view, mark it as exit, define parameter Url with type String. Add usage of interface view in your view and add something like this in action handler:
    wdThis.wdGet...InterfaceViewController().wdFirePlugUrl("http://www.yahoo.com");
    Best regards, Maksim Rashchynski.

  • Using oc4j to generate interfaces from wsdl produced improper method names

    The method names that were produced from the opperations in my WSDL, generated an interface file with incorrect method names. The name went from "DoTest" in the wsdl to "doTest" in the Interface file.
    I double checked and all the cases are correct in the wsdl.
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- edited with XMLSpy v2005 rel. 3 U (http://www.altova.com) by John Reynolds (MedPlus) -->
    <definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:y="http://localhost/TestService" targetNamespace="http://localhost/TestService">
         <types>
              <xs:schema targetNamespace="http://localhost/TestService" xmlns="http://www.w3.org/2001/XMLSchema">
                   <xs:element name="Tresult" type="xs:string"/>
                   <xs:element name="Tname" type="xs:string"/>
                   <xs:element name="Tfault" type="xs:string"/>
              </xs:schema>
         </types>
         <message name="DoTestResponse">
              <part name="Result" element="y:Tresult"/>
         </message>
         <message name="DoTestRequest">
              <part name="Name" element="y:Tname"/>
         </message>
         <message name="DoTestFault">
              <part name="ExceptionDetail" element="y:Tfault"/>
         </message>
         <portType name="TestService">
              <operation name="DoTest">
                   <input message="y:DoTestRequest"/>
                   <output message="y:DoTestResponse"/>
                   <fault name="DoTestException" message="y:DoTestFault"/>
              </operation>
         </portType>
         <binding name="TestService" type="y:TestService">
              <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
              <operation name="DoTest">
                   <soap:operation soapAction="urn:#DoTest" style="document"/>
                   <input>
                        <soap:body use="literal"/>
                   </input>
                   <output>
                        <soap:body use="literal"/>
                   </output>
                   <fault name="DoTestException">
                        <soap:fault name="DoTestException" use="literal"/>
                   </fault>
              </operation>
         </binding>
         <service name="TestServiceSoap">
              <port name="TestService" binding="y:TestService">
                   <soap:address location="http://localhost/TestService"/>
              </port>
         </service>
    </definitions>

    Obviously one could rename the operation to that standard, but that doesn't exactly strike me as being anything other that a work around for a bug.
    WSDL provides a contract in which multiple languages have to conform to a set of interfaces, and it's not exactly good to have a tool, just a assume the contract for an interface is wrong.
    I could argue that I'm only doing Java on the front end and .Net on the client side and that they don't neccessarily follow the Java convention, nor should be constrained by it.
    I do agree with you that they probably just followed the convention when writing to code generator and just happened to pick up the convention. They just need to fix it now.

  • How to convert a String variable as class name and method name?

    i have two classes
    class Student
    public String insertStudent(String sname)
    { return("Student has been inserted ");     }
    class Teacher
    public String execute(String methodName, String className)
    {  //return statement of the method 'insertStudent' in the class 'Student'; }
    }Now, i have a class with the main method. Here, i would like to call the method *'insertStudent'* of class *'Student'*
    using the method *'execute'* of class *'Teacher',* passing the method-name and the class-name (viz. insertStudent, Student) as the
    String parameter.
    Can anyone please help me out. Thanks
    regards,
    chinglai

    You should have just added that as a comment on your [initial posting|http://forums.sun.com/thread.jspa?threadID=5334953] instead of starting a new thread.
    Now, i have a class with the main method. Here, i would like to call the method 'insertStudent' of class 'Student'using the method 'execute' of class 'Teacher', passing the method-name and the class-name (viz. insertStudent, Student) as the
    String parameter.
    Why oh why? What do you want to achieve?
    Let me tell you: there is a way to do what you try to do, but it's not recommended and should be used only very sparingly. Especially not in anything like your code, that resembles normal business logic (as opposed to an application framework such as Spring, for example).
    Can you explain what exactly you want to do with that? Why should a Teacher be able to call any random method ony any other class. And what good would that do?

  • How to read the source code of class method

    Hi,
    I want to read the source code of a method which is in a BAdi implementation.
    I used SEO_METHOD_GET_SOURCE function module where I passed interface name as class and method name.
    But I didn't get the source code. Is there any other function module of method to read the source code.
    Thanks and regards,
    Venkat.

    Hi Venkat,
      You can still use the Function Module SEO_METHOD_GET_SOURCE with a small change in the parameter passing. It should be:
    Paramaters:
    MTDKEY-CLSNAME : <Implementaion Classname>
    MTDKEY-CPDNAME: <Interfacename~methodname>
    STATE : 'A' for active or 'I' for inactive
    For example:
    MTDKEY-CLSNAME :ZCL_IM_PLM_AUDIT_ALV_GRID
    MTDKEY-CPDNAME: IF_EX_PLM_AUDIT_ALV_GRID~ON_USER_COMMAND
    STATE: A
    After executing you will get the source code in the form of string in the 'SOURCE' parameter.
    Hope this helps you.
    Regards,
    Swarna Munukoti

  • Failed to parse method name:

    Hi,
    I've the following environment:
    - Sun Solaris
    - WL 61 without service pack
    - jdk 1.3.1
    I wrote a simple Session Bean and make it IIOP enabled.
    For the Java-Corba client I use an IDL which describes
    the interfaces of the remote and home interface of the
    Session Bean.
    Everything works fine, that means I get the WL's NameService,
    home and the remote object. If I call a method of the remote
    object I got the following message:
    <Info> <IIOPEndPoint> <failed to parse method name: foundUnkownSubscriber>
    I found something in you newsgroup and you said the we should
    use SP2. Where can I get this SP2?
    Regards
    Andre Genser

    Andy Piper <[email protected]> wrote:
    "Andre Genser" <[email protected]> writes:
    I've the following environment:
    - Sun Solaris
    - WL 61 without service pack
    - jdk 1.3.1
    I wrote a simple Session Bean and make it IIOP enabled.
    For the Java-Corba client I use an IDL which describes
    the interfaces of the remote and home interface of the
    Session Bean.
    Everything works fine, that means I get the WL's NameService,
    home and the remote object. If I call a method of the remote
    object I got the following message:
    <Info> <IIOPEndPoint> <failed to parse method name: foundUnkownSubscriber>Are you sure you are spelling correctly? Seems like this should be
    foundUnknownSubscriber.
    andy
    -- Sorry Andy, it was the name but I didn't solved the problem. Now I got the following
    exception:
    <Apr 16, 2002 8:47:29 AM CEST> <Warning> <Dispatcher> <Error thrown by rmi server:
    'weblogic.rmi.cluster.ClusterableServerRef@111 - jvmid: '-5101001595216439928S:10.2.9.70:[8045,8045,9045,9045,8045,9045,-1]:agenser8045:myserver',
    oid: '273', implementation: '[BaseEJBObject] home: prototype.CallBackBean_w4a7u3_HomeImpl@29bced''
    java.lang.OutOfMemoryError
    <<no stack trace available>>
    >
    <Apr 16, 2002 8:47:29 AM CEST> <Error> <Kernel> <ExecuteRequest failed
    java.lang.OutOfMemoryError
    <<no stack trace available>>
    >
    What is wrong in my solution? Here is my simple IDL-File:
    module prototype{
         exception CallBackException {
         interface CallBack {
              void foundUnknownSubscriber( in string MSISDN) raises(CallBackException);
         interface CallBackFactory {
              CallBack create();
    Thanks.
    Andre

  • Get the method name

    hi
    can anyone know how to get the name of method from its catch block.
    For example
    i have a class called Hello.java
    and inside that a method called display();
    and i have a written the code inside a try catch block.so when an exception occurs i want to create a log file
    i got the class name using this.getClass().getSimpleName()
    so is there any way to get the method name , where the catch is written. (here in example i should get it as "display")
    plz help me
    im in great need.
    hope u understood my doubt.
    rgds

    Use a logging framework, and name the loggers well & use meaningful messages?
    Or create a Throwable, [fill in|http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html#fillInStackTrace()] the stack trace, get the required StackTraceElement and [get the method|http://java.sun.com/javase/6/docs/api/java/lang/StackTraceElement.html#getMethodName()] from this.

  • TelemetryClient.TrackException Does Not Include Method Name Or Call Stack (Windows Store App)

    We are attempting to use Application Insights (v0.12.0-build17386) for our Windows Store App.  When we use TelemetryClient.TrackException, no details appear in the azure portal.  The Failed Method is "Could Not Parse" and the Call Stack
    is empty. If we click on the "..." it gives more details but still no method name or call stack information to help us determine where the exception was thrown.  Is this by design, not implemented, or did we miss something obvious?  The
    code is very simple:
    public static void LogException(Exception exception)
    TelemetryClient telemetryClient = new TelemetryClient();
    telemetryClient.TrackException(exception);

    This is a known limitation of this version. It is in the backlog to fix. Note though that 0.13 is out already and fix should be included in the next version (0.14)
    Anastasia

  • Looking up invoking method name

    Hi,
    first the code:
    class Test{
      test1(){
        OtherClass otherObject = new OtherClass();
        otherObject.method()
    test2(){
        OtherClass otherObject = new OtherClass();
        otherObject.method()
    }the question: is it possible for me to receive the name "test1" or "test2" of the Test class when the "method" method gets invoked?
    like:
    class OtherClass{
      method(){
        //if the method name is "test1" do this
       //else do that
    }It&acute;s not possible for me the provide parameters. Does the jre provide me such information somehow?
    Thanks in advance for answers.

    No. You could do something like:
    Throwable t = new Throwable();
    t.fillInStackTrace();
    StackTraceElement[] stack = t.getStackTrace();
    String invokingClass = stack.length < 2 ? null : stack[1].getClassName();
    String invokingMethod = stack.length < 2 ? null : stack[1].getMethodName();- Saish

  • How to know method name dynamically with sender or EventArgs object

    Hello All,
    I am working in ASP.NET. I wanna log method name in log file whenever that method is executed. e.g.
    protected void Page_Load(object sender, EventArgs e)
    Trace.Log("Page_Load start");
    Trace.Log("Page_Load end");
    protected void Method2(object sender, EventArgs e)
    Trace.Log("Method2 start");
    Trace.Log("Method2 end");
    Trace.Log() is use to log my string in log files at D:\. Now, here I have hard coded Method name in Trace.Log(). But, now I want to fetch method name via c# code. Can we achieve it via sender or EventArgs object?
    Please assist.
    Thanks, Chintan

    Hello Chintan,
    You can get class name through reflection as it gets STATIC info about the component.
    However, to get the line number of an exception, which is a run time parameter, you cannot use reflection.
    I actually have not tried this before but, given it did not work for you in the web part class, you may try the below code in your *.ascx.cs user control used by your visual web part.
    //To Retrieve class name use this line:
    string className = this.GetType().FullName;
    // To retrieve other parameters including line number
    try
    TestFunction();
    catch (Exception ex)
    StackTrace st = new StackTrace(ex, true);
    StackFrame[] frames = st.GetFrames();
    // Iterate over the frames extracting the information you need
    foreach (StackFrame frame in frames)
    string stkFrame = string.Format("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber());
    For more info, please refer to this
    post.
    THosE wHo doN'T apPreCiATe LiFe, DOn't DeSerVe iT

  • Variable/method names standardizing

    Hi All,
    The problem we've got here is that same things are named in slightly different way by different developers or development groups.
    Typical example:
    'id' property. accessors could be named like: 'getID' or 'getId'.
    Or even better example: term 'Work List' implementation of which has nothing to do with Java List. So, property could be named as 'worklist' or 'workList' with similar names for accessors.
    I think, this problem is slightly outside of coding standards scope. And as project is very massive ~300000 lines of code, there are a lot of different terms named like in example above.
    Has anyone come across such problem before?
    I suspect, solution would be to keep a kind of variable/method names library.
    Are there any better solutions?
    Thanks in advance
    Andrei

    I think, this problem is slightly outside of coding
    standards scope. It is, and I'm glad it is because the "people" who make the standards that we do have end up creating dumb, inconsistent stuff as it is. Better they don't get too granular.
    Has anyone come across such problem before?Every day
    I suspect, solution would be to keep a kind of
    variable/method names library.
    Are there any better solutions?How you name stuff is a matter of opinion. I personally don't care if you do someID or someId or even someid, what kills me is stuff like someid and someid. But again, it's all what you're used to.

Maybe you are looking for

  • Date variable in watermark

    I'm generating .pdf as an output option from a DITA environment, and want to set up a .pdf watermark (Acrobat Pro X) to add the current date each time I update the content. I don't mind doing this as a separate step, until I've had time to grapple wi

  • How do I set up 2 itunes account on my MacBook Air?

    I'm looking at purchasing a second iPad for my husband and have the 2 iPads download from itunes from the same computer.  Can anyone help me set that up?

  • Screen tapping problems in iOS 5.0.1 on iPad 1

    After the update to ios 5.0.1 on our ipad1, some websites doe not function properluy. When tapping text windows, the cursor appears above the window and not in the window itself. Some buttons of the website I tried do not work. Does anyone know of th

  • Open Firefox pdf downloads in acrobat

    My downloaded pdfs are storing in Downloads and I want them to auto open in Acrobat. Can anyone tell me how to do that?

  • Using the Gradient tool to change button text

    I have had a request to change the text on a number of buttons on the website that I am maintaining. I thought it would be a simple case of cropping the text, editing this using the background colour and then pasting back in. The background colour, h