General java programming question.

i have trouble knowing when something is referred to in contrast to something being copied.
in this case, the array has changed, but not the character.
public class ReturnArray2
     public static int[] getArray()
          int a[] = new int[3];
          a[0] = 2;
          a[1] = 4;
          a[2] = 6;
          return a;
     public static void mystery(int[] b, char r)
          r = 'Q';
          for(int i = 0; i < b.length; i++)
               b[i] = b[i] + 5;
          System.out.println("array b contains: ");
               for(int i = 0; i < 3; i++)
                    System.out.println(b[i] + " ");
     public static void main(String args[])
          int scores[];
          char x = 'L';
          scores = getArray();
          System.out.println("Array in main.");
          for (int i = 0; i < 3; i++)
               System.out.println(scores[i] + " ");
          mystery(scores, x);
          System.out.println("After return from mystery.");
          System.out.println("character is " + x);
          for(int i = 0; i < 3; i++)
               System.out.println(scores[i] + " ");
Array in main.
2
4
6
array b contains:
7
9
11
After return from mystery.
character is L
7
9
11
*/and in this case, why didn't the array change?
public class ReturnArray2
     public static int[] getArray()
          int a[] = new int[3];
          a[0] = 2;
          a[1] = 4;
          a[2] = 6;
          System.out.println("array in function");
          for(int i = 0; i < 3; i++)
               System.out.println(a[i] + " ");
          return a;
     public static void mystery(int[] b)
          for(int i = 0; i < b.length; i++)
               b[i] = b[i] * 2 + 5;
          int[] c = new int [3];
          c[0] = 55;
          c[1] = 44;
          c[2] = 33;
          System.out.println("array c contains: ");
          for (int i = 0; i < 3; i++)
               System.out.println(c[i] + " ");
          b = c;
          System.out.println("array b contains: ");
               for(int i = 0; i < 3; i++)
                    System.out.println(b[i] + " ");
     public static void main(String args[])
          int scores[];
          scores = getArray();
          System.out.println("Array in main.");
          for (int i = 0; i < 3; i++)
               System.out.println(scores[i] + " ");
          mystery(scores);
          System.out.println("After return from mystery.");
          for(int i = 0; i < 3; i++)
               System.out.println(scores[i] + " ");
array in function
2
4
6
Array in main.
2
4
6
array c contains:
55
44
33
array b contains:
55
44
33
After return from mystery.
9
13
17
*/

i have trouble knowing when something is referred to
in contrast to something being copied.Java has only one passing mode: pass-by-value. The value, whether it be of an int or a reference, is always copied.
in this case, the array has changed, but not the
character.A reference has a value, that value is either null or the address of an Object. The value of scores is the address of the array returned by getArray(). When you pass scores to mystery() the value of scores is copied to a new reference called b on the local stack frame. The value of b is the same as the value of scores, but they are two different references. However, since the value is the same they both contain the same address which is the address of the array. When you modify the array you are modifying the array at the address that b has as it's value. Since scores has that same address as it's value, in other words they both point to the same array, you will see it modified in both places. When you passed the char the value (L) was copied to the local stack frame. Your copy r now has the value L. Modifying r modifies the value at r, which is independent of the value at x.
So, with the char you changed the value at the address. With the reference you changed the value at the address the reference contained as it's value.
and in this case, why didn't the array change?You didn't modify the array, you simply printed it's contents concatenated with an empty String.

Similar Messages

  • Java Programming Questions

    I have taken a couple class in Java programming in just regular programming with GUI/console. I am looking to further my programming skills and wonder what course I need to take to become a java programmer for companies. I am confused on all this language in Java and there does not seem to be any reference to explain exactly what these technologies are. Example is.....What is J2EE? What is .JSP? Are they the same things? What environment is most commonly used in jobs? What about Java certifications?

    Here's the path tree to become a Java Programmer from Sun Microsystems:
    http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getlppage?page_id=212&path=SJPF
    There are other paths like Web Development and Databasing, so click around if you're interested in those. I think for a standard Java Programming job you will want the "Java Programming for Professionals - Sun Certified Java Programmer".
    However, most Jobs are specialized and require skills like JSP Development or Java Enterprise. Look around at a job search site and see what types of skills Java jobs are asking for.
    I've noticed, for example, that Java web jobs generally require: PHP, HTML, JSP, XML, SQL, etc.

  • Java Programming Question

    Hi,Everybody:
    I have a question about Java programming. If I want to write a java class code called if.java like below, how should I do to make it pass the java compiler and make it work. I know the words "if" and "for" are reserved words. I just try to figure it out that is it possible??? Do I need to create my own java compiler or recompiler?
    public class if
    public if() { }
    public static for test()
    return new for();
    public class for
    public for() { System.out.println("for class constructor"); }
    }

    I don't think you can bypass the compiler's rejection of this. There is little point to naming the classes after keywords. Not sure if it's case sensitive though, so maybe "If" or "For"? Otherwise, try "if_" or "for_"

  • Accessing oracle DB from a java program - question for oracle driver

    Hi,
    I have Oracle 10 G under vista on my desktop. I am trying to write a simple java program to access/update database tables. I saw in one of oracle example to import 2 packages - namely --- import oracle.jdbc.driver.*; import oracle.sql.*;
    Where do I find these 2 packages. Also I read some documentation to download drivers. I would like to use 2 drivers, the thin driver and the OCI driver. Can someone tell me where I can find these drivers and where do I copy these two drivers - so javac and java command can recognize it.
    I will greatly appreciate the help. Julia
    My program is as follows
    (It was working few years ago but things have changed now and I have Vista because my old machine died):
    import java.sql.*; // JDBC package
    //import com.inet.tds.JDBCRowSet;
    import java.util.*;
    import oracle.jdbc.driver.*;
    import oracle.sql.*;
    public class HomeDB
    run as follows:
    C:\Documents and Settings\MMM>cd \jj
    C:\john>set CLASSPATH=.;c:\oracle9i\classes12;%CLASSPATH%
    C:\john>javac HomeDB.java
    C:\john>java HomeDB
    King: 24000.0
    Kochhar: 17000.0
    De Haan: 17000.0
    Hunold: 9000.0
    Ernst: 6000.0
    Austin: 4800.0
    public static void main(String[] argv)throws SQLException
    Connection conn=null;
    try // may throw a SQLException
    conn = getConnection();
    doQuery (conn);
    catch (SQLException e)
    System.err.println(e.getErrorCode() + ": " + e.getMessage());
    finally // make sure the connection is closed
    if (conn != null) try {conn.close();} catch (SQLException e) {};
    //out.close(); // close PrintWriter stream
    private static Connection getConnection() throws SQLException
    String username = "scott";
    String password = "tiger";
    String url = "jdbc:oracle:thin:@localhost:1521:newora";
    // "jdbc:oracle:thin:@localhost:1521:COCKYJOB";
    Connection conn = null;
    String driver = "oracle.jdbc.driver.OracleDriver";
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    } catch ( ClassNotFoundException cnfex ) {
    System.err.println(
    "Failed to load JDBC/ODBC driver." );
    cnfex.printStackTrace();
    }catch (Exception e){
    e.printStackTrace();
    //DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
    conn = java.sql.DriverManager.getConnection(url,username,password);
    conn.setAutoCommit(false);
    return conn;
    private static void doQuery (Connection c) throws SQLException
    // statement to be executed
    String query = "SELECT ename, job, mgr FROM EMP";
    Statement st = null;
    ResultSet rs = null;
    try // make sure the close statements are executed (in the finally block)
    // create the statement
    st = c.createStatement();
    // execute the query
    rs = st.executeQuery(query);
    // process results
    while (rs.next())
    // get the employee last name
    String eName = rs.getString("ename");
    String eJob = rs.getString("job");
    String eMgr = rs.getString("mgr");
    System.out.println("Emp Name:" + eName +
    "Job: " + eJob +
    "MGR: " + eMgr);
    finally // make sure the close statements are executed
    // close the result set if it exists
    if (rs != null) try {rs.close();} catch (Exception e) {};
    // close the statement if it exists
    if (st != null) try {st.close();} catch (Exception e) {};
    Edited by: user455788 on Dec 19, 2008 9:13 PM

    You can download the drivers from http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html.
    Note that oracle.jdbc.driver is desupported after 10.2, http://forums.oracle.com/forums/ann.jspa?annID=201, so you might want to consider using a DataSource to provide Connections.
    E.G.
    {message:id=2819114}

  • Java program question

    how would i write a java program that takes as input the distance of the commute in miles, the automobiles fuel consumption rate in miles per gallon, and the price of a gallon of gas. this program should then after output the cost of the commute.

    how would i write a java program that takes as input
    the distance of the commute in miles, the automobiles
    fuel consumption rate in miles per gallon, and the
    price of a gallon of gas. this program should then
    after output the cost of the commute.The same way anyone else would do it.

  • General Game Programming Questions

    Hey All,
    I'm a reformed C# / VB.Net MMOPG game programmer who want's to take a crack at making MMORPG's using Java. Mainly because I'm tired of paying the big $$$ for M$'s products when I'm finding Java has a nice assortment of high quality RAD tools and the such for next to nothing, if not free. The only free IDE's for the .Net platform at the moment is a still too early in beta (buggy) to be productive with. Anyways after buying a couple of Java books and knocking them out in a week's time, I'm feeling pretty confident about making Java work for me. I do however have a few questions that the books I purchased failed to answer so here they are..
    Is it possible to compile Java applications (game clients in my case) in a stand alone executable form? I would like a install system where users can just install my game client without them having to worry about having the latest versions of Java ,etc, ie.. I want it to be a easy one click install application.. Does Java offer this? That was another thing that turns me off about the .Net platform, many people don't want to take the time to install the .Net runtime just to check out my game applications...
    I was wondering how Java handles Images, Does Java package up all your images into a .Jar file? A game client can have 100's of sprite sheets, mesh's, skins, etc, ie.. Say I were too make a Applet game client, how would java handle all the images? Would the players download the images while the applet loads?
    Well thats really all I wanted to know.... Thanks In Advanced...

    If you do a search on the forums for "java exe" or something similar, you will probably find about a billion posts asking and answering the same question. The answer is yes, but you will of course make the game windows dependent. Also I think the executable turns out to be quite large and doesn't work without its quircks... a better approach is to install the java runtime with the install of your game. User would never even notice.
    As far as how java handles images, for an applet the images will be downloaded with the applet, but will not be loaded until called upon in the program. You can package all the images into a jar file, or you can just leave them in a directory/directories, although packaging them into one jar would be faster due to downloading only one file and compression.

  • Table Entry Insert - Java Programming Question

    I design table input/output interface with adding / deleting entry function. Table data will be saved in AbstractList by BAPI.
    In Controller implementation tab, I created "input" under WD_init()
       Bapi_Entrysheet_Create_Input <b>input</b> = new Bapi_Entrysheet_Create_Input();
       wdContext.nodeBapi_Entrysheet_Create_Input().bind(<b>input</b>);
       <b>input</b>.setEntrysheetheader(new Bapiessrc());
    In view action function, I need "input" as.
    input.addEntrysheetservices(new Bapiesllc());
    My question is how I can let view class know "input".
    Thanks.
    Message was edited by: li dong
    Message was edited by: li dong

    Hi li dong,
    You need to establish context mapping between view and controller. Open view, select "Properties" tab, In "Required Controllers" section press "Add" and add your controller. Create model node in view (Bapi_Entrysheet_Create_Input) and click "Edit context mapping" in context menu for node. Establish context mapping. Than you can call
    wdContext.nodeBapi_Entrysheet_Create_Input().modeObject().addEntrysheetservices(new Bapiesllc());
    from view.
    Best regards, Maksim Rashchynski.

  • Java Programming Language questions...???

    Hi everybody....
    Can I post here my questions about Java Programming Language....or only to to the relevant Sun's forum....http://forum.java.sun.com/index.jspa???
    My greetings,
    Simon

    Simon,
    sure, the worst thing that could happen is that people point you to the SUN forum. Usually this forum answers general Java questions.
    Frank

  • General java sound capability questions

    im trying to get a handle on the basics of what i can do with sound in java. ive read a lot of pages but there are still some ambiguities.
    what i want to do ideally is have an applet that takes sound from the client microphone and records the sound file on a server. so:
    if this were an applet, would it require me to first save the sound file locally (and therefore sign the applet?) or can the sound be saved in memory somehow without creating a "file" per se - then moved to the server? if it could be done does it require JMF?
    i read that an applet cannot convert the file format client-side. does that mean the file would have to be uploaded in an uncompressed format?
    a java webstart app is also acceptable for my purposes. can someone advise if that is the best way to go?
    can a web start app do the following:
    - connect to a database (on the server)?
    - record / compress / upload a sound?
    if so, i guess java web start is the way to go... if you know any good resources for any of these issues please let me know... thanks!

    BamaColtsFan wrote:
    Hey Gang,
    I know that the general rule here is to try your code first then ask why it doesn't work but my questions right now are more conceptual than anything else. I know a little (very little, really) about Java and some of it's capabilities. I've been thinking about possibly converting a MS Access Utility that I use into a Java program. The MS Access version can be a little unstable and I think by moving to Java, I can eliminate that problem. But, I want to be sure that Java can do everything I need it to do before I spend a lot of time only to find I can't get there from here. These are my initial questions:
    1. I have to run several reports from a large Oracle system. Currently, I export the data as Excel files and link the Access database to them. Using Java, will I be able to export as text files (daily) and have the program read the text and treat it like a database file? The short answer is NO. The more lengthy answer is yes, but you can attach to Excel spreadsheets through ODBC (JDBC/ODBC Bridge) and use them as a database the same way Access did.
    2. Part of the output of the Access database feeds MS Word mail-merge documents that are used to send e-mail messages. Will Java format and send e-mail via Outlook? NO, but you can send mail with the Java Mail API.
    3. The second half of the output is an Excel Workbook with re-formatted and cleaned report data from the original files. Can Java dynamically pass information to Excel and create the various worksheets necessary to display the data the way management wants to see it? NO
    Now having said all of that, there is the Java interface through OpenOffice, which will support MS-Office documents. The MS Office products are Windoz specific, and as such, there are some 3rd party Classes out there that will interface to them, but not directly from Sun's standard API.

  • Java programming language main method question?

    Hello everyone I am quite new to the Java programming language and I have a question here concerning my main method. As you can see I am calling 4 others methods with my main method. What does the null mean after I call the method? I really don't understand is significance, what else could go there besides null?
    public static void main(String[] args)
              int cansPerPack = 6;
              System.out.println(cansPerPack);
              int cansPerCrate = 4* cansPerPack;
              System.out.println(cansPerCrate);
              have_fun(null);
              user_input(null);
              more_java(null);
              string_work(null);
         }Edited by: phantomswordsmen on Jul 25, 2010 4:29 PM

    phantomswordsmen wrote:
    ..As you can see I am calling 4 others methods with my main method. 'Your' main method? Your questions indicate that you did not write the code, who did?
    ..What does the null mean after I call the method?.. 'null' is being passed as an argument to the method, so there is no 'after the method' about it.
    ..I really don't understand is significance, what else could go there besides null? That would depend on the method signatures that are not shown in the code snippet posted. This is one of many reasons that I recommend people to post an SSCCE *(<- link).*
    BTW - method names like have_fun() do not follow the common nomenclature, and are not good code for a newbie to study. The code should be put to the pointy end of your sword.

  • Java Programming Competition Sample Questions

    Hi,
    I am interested in participating the Java Programming Competition in my University. For pratice can you point me to some website with sample questions or any question u have in mind.
    Thanks
    Satish

    I was thinking of putting up on-forum competitions, winner gets dukes etc.
    Someone find an empty forum and we can get on it.

  • Question about Java programming development

    There are five phases in java program development. They are: edit -> compile -> load -> verify -> execute
    However, every time I develops program. I only experience phase 1, phase 2 and phase 5. I always miss phase 3 and 4. When do the class loader and bytecode verifier work? How do they work?
    Second question, how the legitimate programs can execute automatically without typing command java to invoke the interpreter?

    lighthero wrote:
    I still have some questions.
    1. I want to run the program just like the commercial software such as Adobe and MS Office.(just double click to run the program.) How do I execute a java program without typing command java every time?Create an executable JAR: [http://java.sun.com/docs/books/tutorial/deployment/jar/index.html]
    >
    2. How does the JIT compiler work?[http://www.google.ca/search?q=Java+JIT]

  • General Java questions

    1) A program written in Java is supposed to be multi-platform. However, I notice alot of programs I've seen written in Java are distributed to specific systems using different file extensions. The Windows version usually uses the .exe extension and I'm wondering how come they don't use the default .class extension? One major company is Borland for their JBuilder. They had a Windows version long before a Linux version even though I hear it was created in Java.
    2) Is there a free install program for Java or are the only ones commercial products?
    3) Is there a personal database available for Java that will work on all platforms? In my Internet Programming with Java class we used mySQL but I don't want to use a server database let alone one that will require a seperate install.
    4) Is there a free multi-platform IDE for Java (not counting just a text editor)?
    5) Can you universally access a system with Java? Ex. If I wanted to load an application with Java in Linux and Windows do I need to write two seperate routines on how to do this or does Java have a built in function? If I wanted to delete a file is this written universally the same?

    1) A program written in Java is supposed to be
    multi-platform. However, I notice alot of programs
    I've seen written in Java are distributed to specific
    systems using different file extensions. The Windows
    version usually uses the .exe extension and I'm
    wondering how come they don't use the default .class
    extension? One major company is Borland for their
    JBuilder. They had a Windows version long before a
    Linux version even though I hear it was created in
    Java.Java programs are packaged (wrapped) to allow invocation using a .exe extension. It is not mandatory, nor is it a function provided within the native Java libraries. Standard Java is packaged in .jar files that allow execution within a Windows (or other) environment. Environmental setup is necessary to allow the O/S to find the Java libraries. This is a simple process that includes additions to the PATH and CLASSPATH environment variables.
    2) Is there a free install program for Java or are the
    only ones commercial products? I believe installAnywhere has a stripped down version of an installer that you can use for free. They also have a pay-per version that provides more extensive functionality.
    3) Is there a personal database available for Java
    that will work on all platforms? In my Internet
    Programming with Java class we used mySQL but I don't
    want to use a server database let alone one that will
    require a seperate install.There are several Java embeddable SQL compliant databases including Cloudscape and Pointbase. These are written and deployed as Java libraries, and can run within the same JVM as your application or in a seperate JVM on the same machine, or on a seperate machine with IP connectivity. I'm sure there are more, these are just two that I have used. I don't know that there are any free implementations of embeddable databases for Java (but just wait awhile, things change all the time).
    4) Is there a free multi-platform IDE for Java (not
    counting just a text editor)?For personal use, there is Borland JBuilder personal that can be downloaded and used for free. I personally use Sun ONE Studio CE (formerly Forte for Java) which is also free but uses a lot of resources, so be sure you have an adeqaute workstation to run it on. Again, I'm sure there are others, these are just the ones I have had success with.
    5) Can you universally access a system with Java? Ex.
    If I wanted to load an application with Java in Linux
    and Windows do I need to write two seperate routines
    on how to do this or does Java have a built in
    function? If I wanted to delete a file is this
    written universally the same?I'm a little unclear on your question, but you can invoke a seperate process (application) from Java using the O/S native interface through a Java function call. A seperate method is probably not necessary for each O/S, just different parameters passed to the exec function.
    File I/O and file manipulation can be done using Java, and does not have to be O/S specific (but you have that option if you want to).

  • Need help with Java programming installation question

    Sorry for my lack of knowledge about Java programming, but:....
    A while back I thought I had updated my Java Runtime Environment programming. But I now apparently have two programs installed, perhaps through my not handling the installation properly. Those are:
    J2SE Runtime Environment 5.0 update 5.0 (a 118MB file)
    and:
    Java 2 Runtime Environment, SE v 1.4.2_05 (a 108MB file)
    Do I need both of these installed? If not, which should I uninstall?
    Or, should I just leave it alone, and not worry about it?
    Yeah, I don't have much in the way of technical knowledge...
    Any help or advice would be appreciated. Thank you.
    Bob VanHorst

    Thanks for the feedback. I think I'll do just that. Once in a while I have a problem with Java not bringing up a webcam shot, but when that happens, it seems to be more website based than a general condition.

  • Running a java program a set number of times

    This is a general question. Is it possible to make a java program run only 5 times for the sake of arguement.
    Basically I want to write a program that will give the user some flexibility when it will actually run another Java program, but I only want them to be able to say "not now' for a set number of times. When the last time comes the other program will launch. I was initially thinking of the Do Whilw loop, but this needs to work when the program is restarted.
    Program starts, it has 5 times it will run before it does something else(doesn't really matter now I think). User takes option "Not Now" and the program ends, but warns the user this will run 4 more times before you will need to do something.
    This process will repeat until the user takes the option "Ok install now" or the time limit expires and the install occurs anyway. Can someone point me in the right direction.

    ok I see so it's like one those programs that you download for free on the internet and they give you a set amount times to use it before you have to pay for it. but in this case when the number of times you use it equals 5 (or when the user clicks ok) a different java app will open automatically.
    My first thought would be to Write a Serialized object to disk using objectOutputStream that stores the number of times the application has been opened. and each time the program runs it checks for the serialized object and then you can do something like what I posted before. of course if were worried about security the user could always look for the object and erase it, if so then I guess we would have to come up with another plan of attack
    Hope this helps

Maybe you are looking for

  • Mini DisplayPort to VGA Adapter problems

    I connected my Apple Pro to my HD TV to watch streamed movies on my computer using the TV as a monitor. I was advised to purchase a Mini DisplayPort to VGA Adapter and all the connections fit. The first time I connected it was no problem. I watched t

  • How to get a photo from video footage

    I would like to know how you can take a photo out of video footage please, in the old I Movie it was possible but can't figure it out for the new I Movie. Hope it is still possible!

  • 1-Pass or 2-Pass??

    I asked this question in the AME forum earlier and have received no comments, so I thought I would try here as well. I'm just curious what others have experienced. As an experiment I used a 30 second AVCHD clip that had a few effects added and encode

  • Install on Desktop ad laptop

    Good afternoon, I'm sorry if this question has already been asked but I couldn't find the answer. I use CS4 web premium on my desktop PC but I wonder if I can install it on my laptop with the same serials ? That would be useful for me to have it inst

  • MacPro and MacBook Pro network setup

    I hope someone can help me. Basically, I am trying to build a setup connecting my MacPro and MacBook Pro over a network sharing my DSL internet connection and one printer. I currently have a Netgear DSL Router connected to my MacPro and need to add w