Is it possible to remember state in Java functions?

I'm trying to graduate from C to Java, largely skipping C++ in the process. Both for fun, and as a learning experience, I'm converting a C program I wrote almost 7 years ago to Java, which computes sunrise & sunset given one's latitude and longitude (downloadable as http://alumni.caltech.edu/~tfly/sun.zip ).
A technique I sometimes used in C programs was to have a "first_time" variable in a function. If that function was being executed for the "first time," it would know to perform this or that initialization of various variables. Such a variable would be declared as "static" within the function (it would retain its state from one function call to the next). Often, I would do this simply as a matter of efficiency- to avoid having to do the same calculation over and over again:
/* Return the angle swept out since the Perihelion passage, "days_elapsed" ago.
double orbit(days_elapsed)
double days_elapsed;
     double x, y, cos_rads, radians;
     static char first_time = 1;
     static char *eccentricity = "\r\nEccentricity = 0.12345678";
     static double ecc, ecc_const, sqrt_const;
     if (first_time)
          first_time = 0;
          ecc = (double) APHELION_DIST / (double) AU_DISTANCE - 1;
          sprintf(eccentricity, "\r\nEccentricity = %.8f", ecc);
          output(eccentricity);
          sqrt_const = sqrt(1 - pow(ecc, 2));
          ecc_const = 2 * PI / SIDEREAL_YEAR;
...An obvious work-around (kluge) in Java would be to have class variables first_time_x specific to each function x that might want to know whether or not it's being called for the first time since the program was started.
My question has more to do with philosophy and program design. Is this a significant flaw in Java, or am I simply using a feature of C that lets me take the easy way out of a fundamental design problem?

Java doesn't have a concept of C-style static variables. You are supposed to remember things like this in object data members. Rather than use a counting integer, use "boolean initialized = false;" and assign it to true in your method with:
if (initialized == false) {
initialized = true;
Look at it this way, in C you'll have a separate variable for each function, all with different names. All you are doing in Java is moving that variable to the next wider scope - object level instead of method level.
If your functions form some kind of logical hierarchy, you can place the boolean initializer in the base class along with a method to perform the if() check. Then the only thing that changes is the implementation of the function in the derived classes. If you do it right, the polymorphic features of Java will call the right methods for the respective objects and you won't have to worry about a thing.
You said you skipped C++, so if some of this OOP terminology is too foreign, drop me a line at [email protected] and we can discuss it at length and I can save on the phone bills :-)

Similar Messages

  • XSLT using Java function from graphical mapping (RFClookup)

    Hi,
    I was wondering if it is possible to use the standard Java functions of the graphical mapping (RFCLookup, Datetrans, ...) or from my own UDF inside an xslt mapping. Does anyone have every tried this or is an example available ?
    Regards Bernd

    Hi Bernd,
    here you can find an example how to use RFC lookup from an XSLT Mapping:
    http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/05a3d62e-0a01-0010-14bc-adc8efd4ee14?quicklink=index&overridelayout=true
    Is this what you're looking for?
    Regards,
    Gábor

  • Is it possible to pass blob from java to PL/SQL ?

    Hi, I try to bind a PL/SQL function who return a blob to a java class :
    Signature of java method :
        public static Blob getBLOB(int aId, String aJDBC) {Create PL/SQL function :
    create or replace function aa_java(myPiId in number,myPiJDBC in varchar2) return blob
    as language java
    name 'zip.ReadBLOB.getBLOB(int,java.lang.String) return java.sql.Blob';
    /In java code, my blob has the right size (150 Ko) but in PL/SQL, size = 0 !!!
    Any ideas ?

A: Is it possible to pass blob from java to PL/SQL ?

Thank you, but I think I have a Java problem...
Here is my code :
package zip;
import java.sql.*;
import oracle.jdbc.OracleDriver;
import oracle.sql.BLOB;
public class ReadBLOB {
    public static BLOB getBLOB(int aId, String aJDBC) {
        BLOB vBlob = null;
        try {
            DriverManager.registerDriver(new OracleDriver());
            Connection connection = DriverManager.getConnection(
                aJDBC,
            PreparedStatement stat = connection
                .prepareStatement("select image from aa_blob where id="+aId);
            ResultSet rs = stat.executeQuery();
            if (rs.next()) {
                vBlob = (BLOB) rs.getBlob(1);
                System.out.println("Taille 1 : "+vBlob.length());
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        return vBlob;
    public static void main(String[] args) throws Exception {
        BLOB vBlob = getBLOB(1, "jdbc:oracle:thin:@vdn-ceg5:1521:DEV5");
        System.out.println("Taille 2 : "+vBlob.getLength());
}When I run the main method, I have :
Taille 1 : 150260
Taille 2 : 86
!!!!????!!!!????

Thank you, but I think I have a Java problem...
Here is my code :
package zip;
import java.sql.*;
import oracle.jdbc.OracleDriver;
import oracle.sql.BLOB;
public class ReadBLOB {
    public static BLOB getBLOB(int aId, String aJDBC) {
        BLOB vBlob = null;
        try {
            DriverManager.registerDriver(new OracleDriver());
            Connection connection = DriverManager.getConnection(
                aJDBC,
            PreparedStatement stat = connection
                .prepareStatement("select image from aa_blob where id="+aId);
            ResultSet rs = stat.executeQuery();
            if (rs.next()) {
                vBlob = (BLOB) rs.getBlob(1);
                System.out.println("Taille 1 : "+vBlob.length());
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        return vBlob;
    public static void main(String[] args) throws Exception {
        BLOB vBlob = getBLOB(1, "jdbc:oracle:thin:@vdn-ceg5:1521:DEV5");
        System.out.println("Taille 2 : "+vBlob.getLength());
}When I run the main method, I have :
Taille 1 : 150260
Taille 2 : 86
!!!!????!!!!????

  • Is is possible to create Socket using Java Stored Procedures/Function(Ora)?

    Hello Friends,
    Is is possible to create Socket using Java Stored Procedures/Function in Oracle?
    OR
    How I can send a message from oracle to Java Desktop Application which is working like server program?
    Please Guide !!

    J3Ganesh wrote:
    Hello Friends,
    Is is possible to create Socket using Java Stored Procedures/Function in Oracle?No, Oracle was very careful to take that feature out of the JDK provided in Oracle 10/11, but you can buy that feature back for, if I remember correctly, about 5000 dollars. (I actually raised a service request on this and then told my rep what I thought about the answer I received--some thing along the line of money grubbing so and so....)
    How I can send a message from oracle to Java Desktop Application which is working like server program?You can make a table and poll it from time to time from the Java side and write and commit what ever you want to the table. I do not know any way to send a signal from Oracle DB an external Java application--Java or PL/SQL stored procedure.

  • How to Dynamically construct the conditional IF statement in java

    Is there a way to dynamically construct a conditional IF statement in java?
    For example:
    Suppose i have a 2D array like:
    Array[the actual values to search for][the column number in the table to perform the search on].
    e.g.
    Array {
                 {"x"} , {1},  
                 {"y"} , {2},  
                 {"z"} , {3},  
    }How can i construct the if statement like:
    Looping over table rows (tableRow) {
        Looping over array {
            IF ( {"x"}. equals( tableModel.getValueAt( tableRow, {1})   &&
                   {"y"}. equals( tableModel.getValueAt( tableRow, {2})   &&
                   {"z"}. equals( tableModel.getValueAt( tableRow, {3})  )              
            return true;
    }The array can grow or shrink based on the values in it so therefore IF statement will grow or shrink. How can i achieve it?
    If not then how can i achieve this?

    My understanding (feeble at best) is that a sieries of && elements will be evaluated in order until the first false value is encountered. So, in an "if a && b && c" statement where b is false c will never be evaluated and the conditional executable will not run. Is that what you mean?
    Yes, logical expressions will not evaluate unnecessary operands. So you can safely write the following, for instance, without getting an error,
    if ((anArray != null) && (anArray.length > 0)) { ... }because the second operand of the '&&' will never be evaluated if 'anArray' is null.
    Also, is there a difference between & and &&?
    & is a bitwise operator, && is a boolean operator.

  • Is there an equivalent statement in Java for this PL/SQL stmt?

    Hi,
    I want to know if there is an equivalent statement
    in java for this PL/SQL statement:
    IF strTok IN('COM-1','COM-2','COM-3') Then
    /* Do Something */
    End If;
    I tried using : // This is giving me errors..
    if (strTok.equals(("COM-1") || ("COM-2") || ("COM-3") ) )
    /* Do Something */
    The above Java code is giving me errors.
    Any Help to reduce the number of steps for comparison
    is appreciated.
    thanks in adv
    Sharath

    Something like
    if (strTok.equals("COM-1") ||
        strTok.equals("COM-2") ||
        strTok.equals("COM-3") )Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Is there a goto statement in java??

    is ther a goto statement in java
    if yes how is it
    and if no wat we use instead of it , if we want to redirect to control flow??
    thanking you
    rose!!!

    But he did not say it with three exclamation
    points!!!
    yes, I'm trying to restrict my usage of the exclamation mark as part of my attempts to be more even tempered (which aren't succeeding that well, but I may just need more practice).

  • How to execute a SELECT statement  in java??

    Hello !!
    In my java program , i need to delete a record of number X, so
    i accept the number X from the keyboard
    Then before deleting it
    i want the program to show me the name, age of the record which has the number X
    How to do this

    hello kylas
    actually i didnt get why this program example?? wats
    its executing ??? Look at reply #3 in your other thread:
    http://forum.java.sun.com/thread.jspa?threadID=713289&messageID=4126346
    Notice the similarity? You've now asked "How to delete a record in Java" and "how to execute a select statement in java". You may have noticed that, aside from the SQL and the call to execute and executeUpdate (for delete) it's the same code. This is because you don't so much do these things in Java, you do them in SQL. The Java code simply asks the Driver to execute whatever SQL you write. So, I really hope your next post isn't "how do I execute an UPDATE statement in Java".
    Good Luck
    Lee

  • INSERT statement in Java and MS Access

    Hi all,
    can anyone please tell me how to insert data to an MS Access table using JSP i tried INSERT statement of java but it is getting errors saying INSERT statement is wrong. I have no idea about MS access insert statement. i am totally tired of this. Please someone help me.

    Hello,
    MS Sql can cause problems where it goes off standard, however I dont think insert is any different.
    INSERT INTO table_name (column1, column2) VALUES (variable1, variable2)
    Make sure your table and column names are exactly right, Java is case sensitive, so make sure the case is correct also.
    The other common error is if you have a required field in the database that is not populated by your program, so, if for instance there was a column3 in the table for the above example, which was a required field, the sql would fail as there is no data being entered for column3.

  • Is it possible to Integrate dos with Java to create a sample compiler?

    Is it possible to Integrate dos with Java to create a sample compiler, or do I have to write the compiler from scratch? In theory, I would like to have users enter sample code in a java text field, hit a java button that would compile/run the code, by calling a dos command prompt that would run it, and display any error messages back to the java text field. Does anyone know if this is possible? Any help would be greatly appreciated.
    Tflav23

    There is a Compiler class you might be able to use also:
    C:\jdk1.3.1_01\docs\api\java\lang\Compiler.html
    So perhaps there is no need to create a process to compile code. But I don't know if you can get information about compiler errors.

  • Using java function in select statement

    Hi,
    I am trying to use java function in select statement.
    public class ClassA{
         private static String MyConst = "foo";
         public static String functionA(){
              return MyConst;
    in my query I have:
    select
         ClassA.functionA() AS id,
         groupId AS newID,
    from
         myChannel[now]
    ClassA is part of the application (no need to import).
    I get and error of Invalid Expression on ClassA.functionA().
    I also tried to declare the function in the processor element:
    <wlevs:processor id="proc">
         <wlevs:function function-name="A" exec-methode="functionA">
              <bean class="mtPackage.ClassA"/>
         </wlevs:function>
    <wlevs:processor>
    but then I get a different error in the processor XML file:  "An InvocationTargetException was encoutered while attemting to register the user defind function A. The message was null"
    What am I missing here?

    Hi,
    From the above description, you have tried two manners to call method functionA() in the user defined  class ClassA. One uses java cartridge manner directly and the other try to use user defined function manner.
    For the java cartridge manner, the following CQL query should work if the ClassA is really included in the OEP app. I have done similar test before, it works.
    select
         ClassA.functionA() AS id,
         groupId AS newID,
    from
         myChannel[now]
    For user defined function manner, I think two things you need to change:
    1. Need to declare the function in the EPN assembly file(under META-INF/spring/), not component configuration file(under META-INF/wlevs/). The following is an example:
    <wlevs:processor id="proc">
         <wlevs:function function-name="A" exec-methode="functionA">
              <bean class="mtPackage.ClassA"/>
         </wlevs:function>
    </wlevs:processor>
    2. Call the user defined function in the CQL query in the component configuration file under processor. For example:
    select A() from myChannel
    Regards,
    XiYing

  • Convert SQL statements to JAVA Code ?

    Using SQL queries Can I convert SQL statements to JAVA Code ?
    Edited by: user11238895 on Jun 7, 2009 10:54 PM
    Edited by: user11238895 on Jun 7, 2009 11:12 PM

    Me very new to Oracle.
    can we convert SQL Queries to JAVA Code using simple built in SQL queries ?
    Which SWISS SQL Tool does [Converting SQL Queries to JAVA Code]

  • Is it possible to login into the Java instance without password's input, using only my Windows workstation authorization?

    Dear Sirs,
    I try to do an authorization to my NW 7.3 Java instance through my Windows domain authorization.
    I done:
    1) Create connection to LDAP-server and tested it.
    2) Add windows domain certificate to TrustedCAs
    3) Configure SPnego
    Now, I can to login in my NW7.3 Java instance with my windows password, but however I must to input password when I open NW7.3 Java homepage.
    Is it possible to login into the Java instance without password's input, using my windows workstation login/password?
    What I have to do for that?
    I use Windows XP on my workstation and IE 8.0.6 & Chrome 38.0.2125.
    Best regards,
    Alexey Lugovskoy

    Please check
    Using Kerberos Authentication on SAP NetWeaver AS Java - User Authentication and Single Sign-On - SAP Library (NW7.3)
    Using Kerberos Authentication for Single Sign-On - User Authentication and Single Sign-On - SAP Library (NW7.0)

  • How to isolate the Sql Statement from Java Code

    Hi
    I Need to know that can we segregate the Sql Statements and convert them to Stored Procedures so as to isolate the Sql statements from Java Code.
    So i have one static web page which uses four select Statements so what i want is to create a stored procedure encapsulating these queries. So that the Java Web Developer will simply call the Stored Procedure instead of using four different SQL Statements.
    Suppose the developer has these four Statements
    Select ename,empno,sal,job from emp;
    select empno,ename,mgr from emp;
    select deptno,dname from dept;
    select emp.ename,emp.empno,emp.deptno,dept,dname fromemp,dept;
    So can i encapsulate these four Sql Statements in one Procedure and the Web developer can call the Store procedure and dont need to write the Sql Statements in his code.
    Can Anybody guide me how to write this Stored type of Store procedure.
    Thanks

    http://www.google.com/search?q=java+windows+registry
    Next time, search yourself. It might be beyond your belief, but you're really, really not the first person to wonder about this.

  • Is it possible to use WMI in Java

    hi,
    Is it possible to use WMI in java.We can use C# code to fetch Windows information using WMI,but is it possible to do the same in Java?

    One easy solution is to generate a vbscript, launch it and capture the output.
    Example at [http://www.rgagnon.com/javadetails/java-0580.html]
    ok, it's ugly but unless you want to go with JNI then it's worth a look.
    Bye.
    RG.

  • Maybe you are looking for

    • Bbm doesn't work ...

      hi, i was using a pay as you go sim, but now im using a pay monthly sim, and now my bbm has stopped working. What do i do?? And who do i contact to sort it out??

    • Newbie needs colour replacement advice

      I'm still feeling my way along with PS and would appreciate some help with what is probably a very straightforward issue: I'm planning to do some giclee prints involving scans of original watercolour paintings of botanical subjects. Because of the na

    • Basic question about multiple AP's and channel selection

      I have approximately 10 AP's (Aironet 1240G) which are to be deployed one of my office floors. We looked at a floor diagram and made sure that we ordered enough of them to completely saturate the floor with wireless coverage. There are some AP's whic

    • Deleting files/ offline question

      hey guys i just filled up my hard drive with footage...i need to take it off because im gonna start using an external hardive and i need more space. i was wondering...... if i delete the capture scratch, the project, and everything thing else...will

    • Process Chain Missing variant REMOVED

      every time i go to RSPC and open any process chain i got a message " Varaint &0000000000526 does not exist" , when i click more help Variant &0000000000526 does not exist Message no. DB612 Diagnosis You selected variant &0000000000526 for program RSP