Writing functions in Java

Hi there,
I'm pretty much a newbie to Java, but have had some experience with C++. I've been trying to write functions to use within the main class but they don't seem to work properly, although I have kinda found a solution, I just don't know if it's the right solution.
example
public class test
static int ival;
public static void init(void)
ival = 55;
public static void show(void)
System.out.println(ival);
public static void main(String []args)
test.ival();
test.show();
}not sure if that should work as I am writing it off the top of my head. The thing is I need to create a modular program that doesn't use other objects in it (otherwise I would just define them and use the member functions of the class definition to do the work that I need done). In terms of C++, the code I'm used to writing is more like this:
#include <iostream>
// prototypes
void init(void);
void display(void);
// main program
void main(void)
int var1;
init();
display();
// function definitions
void init(void)
var1 = 55;
void display(void)
cout<<var1<<endl;
}Then again, now that I look at the code, I don't know if the C++ code will work properly (*sigh*)... And people wonder why I prefer using PHP - no complications...
So if anyone can help clarify this for me, I would greatly appreciate it.
Many thanks,
Garatheus

There really isn't a "main class" in Java (and I don't recall C++ enough to compare); there's just classes potentially with main methods, which can be the starting point for execution as invoked by the JVM.
Also IIRC Java's OOP model is cleaner than C++'s -- to the point which you don't have standalone functions, just methods within a class.
Although maybe I shouldn't be posting here, as I've spent the last few years trying to forget C++.

Similar Messages

  • Writing message mapping function in Java in integration repository

    Hi XI Pundits,
    I am new to XI. I was working on Message mapping in intergration repository.
    To map the source messages to target messages, we do graphical kind of mapping like drag and drop.
    There are some functions aavilable at the bottom like concatehate, trim and etc. which we use if we need to modify the source message and map to target.
    But in case we face a situation when we don't find the function which suits our requirement, I guess we need to write a new function. We can write these new function using Java only.
    Can someone throw some light on this ?
    <b>What do we do to invoke java editor in integartion reposity to write mapping function in java ?
    Can someone give an example of snippet of code ?</b>
    Thanks.

    Hi Tushar,
    Go thro this help link. You will get all info about User defined function.
    http://help.sap.com/saphelp_nw04/helpdata/en/22/e127f28b572243b4324879c6bf05a0/frameset.htm
    To get more understanding on mapping go thro this link(PDF File)
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/9202d890-0201-0010-1588-adb5e89a6638
    Hope this helps.
    regards,
    P.Venkat
    Message was edited by: Venkataramanan

  • Calling c++ function in java

    Hi,
    I would like to know how I can modify c++ program so that I can use its(c++) functions in java.
    the program is c++ ready-made and i would like to use its functions in a java package.
    i read the turiols concerning this on java.sun.com but does that mean that i have append "jni.h", "JNIEXPORT", etc to the c++ file?
    Hints shall be appreciated.
    Thanks.

    OK, thanks.I have tried the jni procedure but without success.
    Is it possible for Java talk to native code (c++) via TCP/IP.
    Please advice of any links/knowledge.
    Thanks.
    1. Strictly speaking, java does not operate on C++; it
    operates on C functions. This is more than a quibble:
    o JNI expects to call C functions, not methods of C++
    objects.
    o In fact, if you really just have functions, but they
    are compiled as C++, then you will probably have to
    declare C linkage.
    2. Functions called from java must conform to JNI
    calling conventions.
    o In general, the starting point is to define how you
    would like the object and native method to look in
    java, then run jni.h to generate the appropriate C
    header definitions, then write the C code.
    o Functions called from java must exist in shared
    libraries - on Windows, in dlls.
    o Existing C function libraries are typically accessed
    by writing a "wrapper" dll that implements the
    required java interface and then calls the existing
    library functions.
    o In fact, a wrapper could actually instantiate C++
    objects and call their methods.
    3. You might care to look up something called JACE,
    which some people claim can generate the kinds of
    wrappers discussed here.

  • Writing functions that contain scriptlets/expressions

    How do I go about writing functions in my JSP page that contain scriptlets and expressions? Also, I'd like to reference session/request/response variables from within.
    I want something like this:
    <jsp:useBean id="myObject" class="com.classes.*" scope="session" />
    <%!
    void printList()
         String str1 = myObject.getName();    <%-- reference outside object --%>
         String str2 = request.getParameter("address");  <%-- use request variable --%>
         out.println(str1 + ": " + str2); <%-- I know it's illegal to do this, but how do I print to the browser from a function? --%>
         <%= request.getParameter("zipcode") %> <%-- Also illegal (are expressions allowed?) --%>
         out.println("<A HREF=\"<% session.getAttribute("url") %>\">Click here</a>");  <%-- dynamic and static content: how do I do this? --%>
    %>I unsure as to how to carry out the above actions. My biggest problem is the last example. How do I print out HTML interspliced with dynamic content with my function?
    I'm pretty sure that nesting <% %> tags inside of <%! %> directive tags is illegal. Is writing a void function that prints out a bunch of static and dynamic data simply not possible with JSP? If so, is it necessary that I write several functions to return values which can then be printed later in the page via separate scriptlets or expressions?

    Take a look at generated servlet code and try to understand how it is working.
    request and response is available only inside some method body. So to access it in your method, you must pass it as argument.
    void printList(HttpServletRequest request, HttpServletResponse response) { ... }everything inside
    <%!
    is added to servelt code, but things inside <% %> are added to processing method body not servlet body.
    Take look at jsp and corresponding servlet:
    JSP:
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <html>
    <head><title>JSP Page</title></head>
    <body>
        <%="place 1"%>
    </body>
    </html>
    <%!
        public String aaa() {
            return "palce2";
    %>GENERATED SERVLET
    package org.apache.jsp;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.jsp.*;
    public final class test_jsp extends org.apache.jasper.runtime.HttpJspBase
        implements org.apache.jasper.runtime.JspSourceDependent {
        public String aaa() {
            return "palce2";
      private static java.util.Vector _jspx_dependants;
      public java.util.List getDependants() {
        return _jspx_dependants;
      public void _jspService(HttpServletRequest request, HttpServletResponse response)
            throws java.io.IOException, ServletException {
        JspFactory _jspxFactory = null;
        PageContext pageContext = null;
        HttpSession session = null;
        ServletContext application = null;
        ServletConfig config = null;
        JspWriter out = null;
        Object page = this;
        JspWriter _jspx_out = null;
        PageContext _jspx_page_context = null;
        try {
          _jspxFactory = JspFactory.getDefaultFactory();
          response.setContentType("text/html;charset=UTF-8");
          pageContext = _jspxFactory.getPageContext(this, request, response,
                         null, true, 8192, true);
          _jspx_page_context = pageContext;
          application = pageContext.getServletContext();
          config = pageContext.getServletConfig();
          session = pageContext.getSession();
          out = pageContext.getOut();
          _jspx_out = out;
          out.write("\n");
          out.write("\n");
          out.write("<html>\n");
          out.write("<head><title>JSP Page</title></head>\n");
          out.write("<body>\n");
          out.write("    ");
          out.print("place 1");
          out.write("\n");
          out.write("</body>\n");
          out.write("</html>\n");
          out.write("\n");
        } catch (Throwable t) {
          if (!(t instanceof SkipPageException)){
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
              out.clearBuffer();
            if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        } finally {
          if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }

  • User defined function in java for message mapping

    I wrote the following user defined function in java for message mapping and mapped vendor with this. The aim of this function is to write a error file at defined path when i send empty Vendor value from File to RFC-Function module BAPI_PO_CREATE. The "err.txt" error file is not written when i execute in TEST but the value "ERROR" is returned to destination Vendor Field.
    public String  validation(String a, Container container) {
    //write your code here
    if (a.equals("")) {
    try {
    String source = "Vendor cannot be empty";
    char buffer[] = new char[source.length()];
    source.getChars(0, source.length(), buffer, 0);
    for (int i = 0; i < buffer.length; i +=2)
       f0.write(buffer<i>);
    f0.close();
    FileWriter f1 =  new FileWriter("/10.10.0.55/sapmnt/trans/edixiin/err.txt");
    f1.write(buffer);
    f1.close();
    catch (IOException e) {}
    return "ERROR";

    Hi Senthil,
    Check these things :
    1) Whether you have permission to create a file in that directory.
    2) try giving this 
    10.10.0.55
    sapmnt
    trans
    edixiin
    err.txt
    3) Also check for permissions.
    Hope this will help you.
    Regards
    Suraj

  • Can we call java function in java script????

    hello
    please tell me can i call a java function through java script function in jsp???

    of course not. JavaScript is interpreted by the client (web browser) while the Java code in a JSP resides on the server. don't confuse the web application's architecture.
    robert

  • FM call from Variant Function in JAVA SCE

    Hello,
    I have an issue with Variant Configuration in CRM WEB UI / WebShops.
    We have created a variant function in ECC to read/pull a customer master value (KNVV table).  This is working fine in ECC & got the desired result.
    Now we need replicate the same in CRM. For this we need to create KB, Version & write a variant function in Java class in SCE. In that variant function we need to call a function module and get the customer master / Business partner value as similar to ECC process described above.
    But we see that the SAP standard is not supporting FM calls from VF in Java. i.e. we are unable to call the JCO call to a CRM function module from SCE.  The package for User defined classes "com.sap.sce.user" and the method inside it public boolean execute(fn_args args, Object obj) { ..... } has no option to make a FM call.
    Has anyone faced the similar requirement and has any resolution for this? 
    Thanks,
    Surya.

    Hi Eric,
    You sound quite familiar with the variant functions. I am also working on IPC-SCE
    variant functions for few years now.
    We have a situation where I am building some debug logs in one java variant function and want to display it to the web UI at some condition.
    Is there any object(like context etc.) that IPC server-side and Webapps share?
    I can write that log to a text file and read it from web ui ... but I wanna avoid that.
    Is there any other way you know of???
    Regards,
    Ruchika

  • How to access C/C++ functions in Java using existing .dll library

    Hi JNI Guru's,
    I am having well written API in C/C++.This C/C++ files are made into *.dll files.The api are working fine.
    I wan't access the C/C++ api functions in Java., just using System.LoadLibrary("*.dll").Is it possible.I kindly request you to suggest some examples and how to do this.
    Its Urgent !.
    Thanks and Regards,
    V K LAL

    In general you cannot simply access dlls that have already been written. The DLLs called using JNI must conform to JNI calling standards.
    This means you will probably have to write one or more "wrapper" dlls which a) provide the correct JNI interface, and b) call the existing dlls.
    There are some programs around that claim to be able to generate such wrappers. Try a google search for "wrapper", "jni", "generate".
    The JNI tutorial covers creating wrappers.

  • Calling c functions in java

    How do I call c functions from java?

    See http://java.sun.com/docs/books/tutorial/native1.1/index.html

  • Calling a SP or Function from Java receiving a geometry(MDSYS.SDO_GEOMETRY)

    Hi there,
    What I want to do is: calling a stored procedure OR function from Java with a String-variable as input and receiving a geometry (SDO_GEOMETRY).
    I’m facing currently the problem of calling a stored function on oracle 11g from Java using JPA (EclipseLink), Spring 2.5.6 returning an MDSYS.SDO_GEOMETRY object.
    I’ve tried to call a stored procedure with MDSYS.SDO_GEOMETRY as an output parameter instead, but with no success.
    The function’s signature looks like this:
    CREATE or REPLACE
    FUNCTION GET_GEO_BRD_FUNCTION(p_geo_brd_id IN VARCHAR2) RETURN MDSYS.SDO_GEOMETRY AS
    sdo_geom    MDSYS.SDO_GEOMETRY := null;
    BEGIN
    /* do some fancy stuff on the database side */
      SELECT sp_geom
        INTO sdo_geom
        FROM geo_brd WHERE id = p_geo_brd_id;
      RETURN sdo_geom;
    END;
    The calling code looks like this:
    MyClass extends JpaDaoSupport{
       /** logger */
       protected static final ILogger LOG = LogFactory.getLogger(MyClass.class);
        * {@inheritDoc}
        * @see com.example.MyClass#calculateGeometry(java.lang.String)
       @Override
       public JGeometry calculateGeometry(final String id) {
           JGeometry geometry = null;
           final JpaCallback action = new JpaCallback() {
                @Override
                public Object doInJpa(final EntityManager em) throws PersistenceException {
                   final Session session = JpaHelper.getEntityManager(em).getActiveSession();
                   final StoredFunctionCall functionCall = new StoredFunctionCall();
                   functionCall.setProcedureName("GET_GEO_BRD_FUNCTION");
                   functionCall.addNamedArgument("p_geo_brd_id");
                   functionCall.setResult("sdo_geom", Oracle.sql.STRUCT.class);
                   final ValueReadQuery query = new ValueReadQuery();
                   query.setCall(functionCall);
                   query.addArgument("p_geo_brd_id");
                   final ArrayList args = new ArrayList();
                   args.add("2e531e62-2105-4522-978a-ab8baf19e273");// hardcoded for test
                   final Object result = session.executeQuery(query, args);
                   return result;
        final STRUCT result = (STRUCT) this.getJpaTemplate().execute(action);
        try {
           geometry = JGeometry.load(result);
        } catch (final SQLException e) {
           MyClass.LOG.error("Error loading JGeometry from STRUCT.", e);
           return null;
        return geometry;
    And when I execute the query I get the following error:
    Internal Exception: java.sql.SQLException: ORA-06550: Row 1, Column 13:
    PLS-00382: expression is of wrong type
    ORA-06550: Row 1, Column 7:
    PL/SQL: Statement ignored
    Error Code: 6550
    Call: BEGIN ? := GET_GEO_BRD_FUNCTION(p_geo_brd_id=>?); END;
         bind => [=> sdo_geom, 2e531e62-2105-4522-978a-ab8baf19e273]
    Query: ValueReadQuery()
    So I thought may be let's try it with a stored procedure instead...
    The procedure looks like this:
    CREATE or REPLACE
    PROCEDURE GET_GEO_BRD_PROCEDURE(p_geo_brd_id IN VARCHAR2, sdo_geom OUT MDSYS.SDO_GEOMETRY) AS
    BEGIN
    /* do some fancy stuff on the database side */
      SELECT sp_geom
        INTO sdo_geom
        from geo_brd where id = p_geo_brd_id;
    END;
    The calling Java code in case of the stored procedure looks like this (only the content of the JPACallback has changed):
    @Override
    public Object doInJpa(final EntityManager em) throws PersistenceException {
        final Session session = JpaHelper.getEntityManager(em).getActiveSession();
        final StoredProcedureCall spCall = new StoredProcedureCall();
        spCall.setProcedureName("GET_GEO_BRD_PROCEDURE");
        spCall.addNamedArgument("p_geo_brd_id", "p_geo_brd_id", String.class);
        spCall.addNamedOutputArgument("sdo_geom", "sdo_geom", OracleTypes.STRUCT);
        final ValueReadQuery query = new ValueReadQuery();
        query.setCall(spCall);
        query.addArgument("p_geo_brd_id"); // input
        final List args = new ArrayList();
        args.add("2e531e62-2105-4522-978a-ab8baf19e273");// hardcoded for test
        final Object result = session.executeQuery(query, args);
        return result;
    And when I execute the query I get the following error:
    java.sql.SQLException: ORA-06550: Row 1, Column 13:
    PLS-00306: wrong number or types of arguments in call to 'GET_GEO_BRD_PROCEDURE'
    ORA-06550: Row 1, Column 7:
    PL/SQL: Statement ignored
    So both exceptions look quite similar.
    I guess in both cases the exception description leads to the assumption, that the wrong type for the return value / output parameter is used…
    So - how can a receive a MDSYS_SDO_GEOMETRY object from a stored procedure or stored function in Java ?
    What is wrong in the Java code?
    Thank you in advance for any suggestions!
    Yours,
    Chris
    Edited by: user3938161 on 20.12.2011 07:46
    Edited by: user3938161 on Dec 20, 2011 8:06 AM: added variable declaration of JGeometry geometry in source code

    Thanks, that did the trick! ;-)
    Here is now the code for stored procedure and function for anybody else encountering the same troubles... (be aware of the parameter order and/or naming!)
    Code for stored functions:
    final JpaCallback action = new JpaCallback() {
      @Override
      public Object doInJpa(final EntityManager em) throws PersistenceException {
         final Session session = JpaHelper.getEntityManager(em).getActiveSession();
           * Using CallableStatement for stored functions
          STRUCT st = null;
          CallableStatement cs = null;
          final DatabaseLogin login = session.getLogin();
          final Connection _conn = (Connection) login.connectToDatasource(session.getDatasourceLogin().buildAccessor(), session);
          try {
             try {
                cs = _conn.prepareCall("{? = call GET_GEO_BRD_FUNCTION(?)}");
                cs.registerOutParameter(1, OracleTypes.STRUCT, "MDSYS.SDO_GEOMETRY");
                cs.setString(2, "2e531e62-2105-4522-978a-ab8baf19e273");//TODO: hardcoded for test
                cs.execute();
             } catch (final SQLException e) {
                MyClass.LOG.error("An exception occured calling the stored procedure", e);
             if (cs != null) {
                //reading geometry from the database
                try {
                   st = (STRUCT) cs.getObject(1);
                } catch (final SQLException e) {
                   MyClass.LOG.error("An exception occured converting the query result to oracle.sql.STRUCT", e);
          } finally {
             try {
                if (_conn != null && !_conn.isClosed()) {
                    _conn.close();
             } catch (final SQLException e) {
                MyClass.LOG.error("An exception occured on closing the database connection.", e);
          return st;
    final STRUCT result = (STRUCT) this.getJpaTemplate().execute(action);
    The code for stored procedure solution:
    final JpaCallback action = new JpaCallback() {
      @Override
      public Object doInJpa(final EntityManager em) throws PersistenceException {
          final Session session = JpaHelper.getEntityManager(em).getActiveSession();
           * Using CallableStatement for stored procedure
          STRUCT st = null;
          CallableStatement cs = null;
          final DatabaseLogin login = session.getLogin();
          final Connection _conn = (Connection) login.connectToDatasource(session.getDatasourceLogin().buildAccessor(), session);
          try {
             try {
                cs = _conn.prepareCall("{call GET_GEO_BRD_PROCEDURE(?,?)}");
                cs.setString("p_geo_brd_id", "2e531e62-2105-4522-978a-ab8baf19e273");
                cs.registerOutParameter("sdo_geom", OracleTypes.STRUCT, "MDSYS.SDO_GEOMETRY");
                cs.execute();
              } catch (final SQLException e) {
                MyClass.LOG.error("An exception occured calling the stored procedure", e);
              if (cs != null) {
                //reading geometry from the database
                try {
                   st = (STRUCT) cs.getObject("sdo_geom");
                } catch (final SQLException e) {
                   MyClass.LOG.error("An exception occured converting the query result to oracle.sql.STRUCT", e);
           } finally {
              try {
                if (_conn != null && !_conn.isClosed()) {
                   _conn.close();
              } catch (final SQLException e) {
                MyClass.LOG.error("An exception occured on closing the database connection.", e);
            return st;
    final STRUCT result = (STRUCT) this.getJpaTemplate().execute(action);

  • Any Mod function in JAVA?

    I did not find 'MOD' function in the Math class. Is there any 'MOD' function in Java?
    Thanks!

    What is your MOD function?
    Does the %-operator do what you need or do you want a strict mathematical modulus that returns only positive values?

  • Please ..give me some example APDU for writing data to java card

    morning everybody .. :)
    I need some example APDUs for writing data to java card. (CLA || INS || P1 || P2 etc)..
    please..thank for your attention .. god blessing u.

    Hi,
    did you check some articles about JavaCards:
    [Understanding Java Card 2.0|http://www.javaworld.com/cgi-bin/mailto/x_java.cgi?pagetosend=/export/home/httpd/javaworld/javaworld/jw-03-1998/jw-03-javadev.html&pagename=/javaworld/jw-03-1998/jw-03-javadev.html&pageurl=http://www.javaworld.com/javaworld/jw-03-1998/jw-03-javadev.html&site=jw_core]
    [How to write a Java Card applet: A developer's guide|http://www.javaworld.com/cgi-bin/mailto/x_java.cgi?pagetosend=/export/home/httpd/javaworld/javaworld/jw-07-1999/jw-07-javacard.html&pagename=/javaworld/jw-07-1999/jw-07-javacard.html&pageurl=http://www.javaworld.com/javaworld/jw-07-1999/jw-07-javacard.html&site=jw_core]
    Hope it helps,
    Tex

  • Why static is used before any function in java

    Sir/Madem
    I'm new in java. I have just started learning java.
    please tell me
    "why static is used before any function in java??????"
    I have searched on net and in soime bokks .But i was unable toget it. what is exact reson of using static in java.

    tandm-malviya wrote:
    Sir/Madem
    I'm new in java. I have just started learning java.
    please tell me
    "why static is used before any function in java??????"
    I have searched on net and in soime bokks .But i was unable toget it. what is exact reson of using static in java.It's actually seldom used in "real" applications. static associates the method with the class instead of an instance.
    Kaj

  • The troubles with creating SQL function in Java

    Hi!
    I use Oracle 10g and connect to it from Java application. I need in creating SQL functions from Java code.
    In Java I have:
    Statement stm = null; try{     stm = dbConnection.createStatement();     stm.executeUpdate( query ); }catch(SQLException ex){     throw ex; }finally{     try{ stm.close(); }catch(Exception ex){ stm.close(); } }
    And I'm passing the next SQL function:
    create or replace function get_me return number is
    result number;
    begin
    select 5 into result from dual;
    return result;
    end;
    This code is run successful, but I can't call this funtion, because it has status Invalid
    I'm looked the next error: PLS-00103: Encountered the symbol "" when expecting one of the following: . @ % ; is authid as cluster order using external character deterministic parallel_enable pipelined aggregate
    But I don't understand, What the matter? From Oracle Enterprise Manager I can create this function without problems. So, I wrote the wong Java code. Also, I can't find my error :(
    May be, do u have the some ideas?
    Thank you very much!

    Post the whole pl/sql code please.
    To run PL/SQL from within java you'll need callablestatement.
    [here |http://www.idevelopment.info/data/Programming/java/jdbc/PLSQL_and_JDBC/CallPLSQLFunc.java] an example : http://www.idevelopment.info/data/Programming/java/jdbc/PLSQL_and_JDBC/CallPLSQLFunc.java

  • The mkdir() function in java returning false. Why?

    I am trying to create the folder archive under the following directory structure:
    E:/preweb/CATest/DL/Zipra Internal/EventCompletion/html/archive/
    using the boolean mkdir() function in java.
    Though the folder archive does not exist under html folder, still the function is returning false.
    Canm someone let me know why?

    And you have checked that by using
    File file =// E:/preweb/CATest/DL/Zipra Internal/EventCompletion/html/archive/
    Sys.out.println( file.getParentFile().exists() );

Maybe you are looking for

  • How to add vertical scrollbar to a tree region

    Hi, I have a page containing two regions. The first is a tree region displayed on the left hand side of the page. The second is form region displayed to the right of the tree, showing details relating to the selected node from the tree. How can I add

  • My itunes wont close

    it says it is still backing up my iphone but I cancelled the back up and ejected my iphone and now the backup is still cancelling without it being plugged in the computer. What should I do?

  • ABAP to asXML to XSLT to XML???

    Hi, I have a few questions concerning <b>Call Transformation</b> hopefully someone has done this before. I am attempting to convert an ABAP internal table to a particular XML layout for consumption by an external application.  There seem to be a few

  • Re:********************Utilization of MS-ACCESS in Web Dynpro for java*****

    Hi all, Can anybody tell me how to fetch records from MS-ACCESS in Web Dynpro java.

  • Keeping your servers up-to-date with patches

    Hello All, Please note that this is NOT a WSUS question. I have that installed in our environment and I know how to use it, or at least I like to think I do. I am a System Admin of a completely virtualized environment. As our company grows, more and