Simple Java Array Question

// This is how I was taught to make a simple array. You have to define the size first.
String [] test1 = new String[4];
test1[0] = "1";
test1[1] = "2";
test1[2] = "3";
test1[3] = "4";
out.println(test1[0]);
out.println(test1[1]);
out.println(test1[2]);
out.println(test1[3]);
//If the size is not defined in this second example, why does it still work?
String [] test2 = {"1","2","3","4"};
out.println(test2[0]);
out.println(test2[1]);
out.println(test2[2]);
out.println(test2[3]);
They both produce the same results.

// This is how I was taught to make a simple array.
You have to define the size first.
String [] test1 = new String[4];
test1[0] = "1";
test1[1] = "2";
test1[2] = "3";
test1[3] = "4";
out.println(test1[0]);
out.println(test1[1]);
out.println(test1[2]);
out.println(test1[3]);
//If the size is not defined in this second example,
why does it still work?
String [] test2 = {"1","2","3","4"};
out.println(test2[0]);
out.println(test2[1]);
out.println(test2[2]);
out.println(test2[3]);
They both produce the same results.Umm..the size is just as well defined in your second as in your first...it is a four element array.
The second way is akin to the first...also
String[] s = new String[]{"Hello","I","contain","five","elements"};
System.out.println(s[5]); Will compile..you will get a run-time ArrayIndexOutOfBoundsException (it is a 5 element array, 0-4, but java will not assume that the variable s is not changed between those two lines of code)..
Array index/boundary checking is done at run-time, not compile-time.
In fact:
String[] s;
//let's say up in the program
//and
public void printS(int i)
System.out.println(s);
Will also compile...and if something else happens to set s as a 10 element String array:
printS(9);would work
~David

Similar Messages

  • Simple Java Coding Question

    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    My first thought was that they meant to look at the position in the array one less (or more) than i (j). But that doesn't seem to be the case. A is an array of Strings, if that matters...
    Thanks for you help.

    muiajc wrote:
    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    It mean increase/decrease the int i/j by 1. This is done before it gets you the value of a[]. for example if i=5 and you said a[--i] it is really a[4] and i is now equal to 4;

  • Simple Java EJB question.

    When it comes to EJB v3 Remote and Local interfaces,
    (With JBoss EJB Container Software in mind, for this question,)
    -Does the Remote interface for the EJB include method signatures from the Bean class
    -that are to be seen
    -that are to be hidden?
    -Does the Local interface for the EJB include method signatures from the Bean class
    -that are to be seen
    -that are to be hidden?
    Which is which for
    -EJB 2.1 ?
    -EJB 3.x ?
    - is EJB 3.x reverse compatible in that it allows use of the javax.ejb.* interfaces,
    and would accept a EJB 2.1 approach, or does it force one to use Annotations
    exclusively?
    Edited by: Zac1234 on Jul 21, 2010 5:21 PM

    muiajc wrote:
    I know this is a simple question, but I can't search for the answer to this because it involves syntax that Google and the like don't seem to search for..
    I am trying to figure out some Java code that I have found. I would like to know what:
    a[--i] and a[++j] mean.
    It mean increase/decrease the int i/j by 1. This is done before it gets you the value of a[]. for example if i=5 and you said a[--i] it is really a[4] and i is now equal to 4;

  • Plzzz write prog to this simple java threads question

    Write a program in C to create four processes. The original processes creates
    two children before it prints out "PARENT". The children processes print
    "CHILD1" and "CHILD2" respectively. The first child process creates a child
    process that prints out "GRANDCHILD".
    Note: The output must be guaranteed to print out in the following order each
    time it is executed:
    GRANDCHILD
    CHILD2
    CHILD1
    PARENT
    a. Write the program using C or C++ and forks to create the children processes.
    b. Write a second program using Java and Threads for the children processes.
    The output statements for CHILD1, CHILD2 and GRANDCHILD must come from print
    statements in the run method of the thread.

    Most people here will not do your homework for you. If you post a reasonable question that shows you've made some effort, and what the results of that effort were, and provides details about what parts you're having trouble with, then somebody will probably provide guidance so that [you can complete the work.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Simple Java SDK question for server group assignment

    I have a snippet of code below in which I am trying to apply the setProcessingServerGroup() and setProcessingServerGroupChoice() methods to my report object. My question should be relatively simple: I believe I need to cast(?) my iObject report object to iProcessingServerGroupInfo per the API in order to use the setProcessingServerGroup() and setProcessingServerGroupChoice() methods, but I'm not sure how to do so.
    Can someone please advise how to cast my iObject to iProcessingServerGroupInfo?
    Thanks in advance...
    Code:
    IInfoObject iObject = (IInfoObject) childReports.get(i); 
    int sgID_view = Integer.parseInt(serverGroupID_view);
    int sgPref_view = Integer.parseInt(serverGroupPref_view);
    !!!!!  CONVERSION / CAST NEEDED HERE !!!!!
    iProcessingServerGroupInfo.setProcessingServerGroup(sgID_view);
    iProcessingServerGroupInfo.setProcessingServerGroupChoice(sgPref_view);

    To followup, I've been able to cast to IShedulingInfo in order to use the setServerGroup() and setServerGroupChoice() methods successfully:
    IInfoObject iObject = (IInfoObject) iObjects.get(i);    
    ISchedulingInfo iSchedulingInfo = iObject.getSchedulingInfo();
    iSchedulingInfo.setServerGroup(427);
    iSchedulingInfo.setServerGroupChoice(2);
    But I don't know how to perform the cast to be able to access the setProcessingServerGroup(), sterProcessingServerGroupChoice() methods.
    Any help appreciated.
    Thanks!

  • Simple java architecture question

    This should be a simple question to answer but I haven't been able to find a good answer.
    I have an application that establishes a network connection with a server and registers event listeners on that connection.
    What I want to do is find a way without a busy-wait/while loop to keep the main() thread running so that the listeners can do their job.
    Here is a sample of what I've got:
    public static void main(String[] args)
    SomeConnection conn1 = null;
    try
    conn1 = new SomeConnection("someaddress");
    TrafficManager tm = conn1.getTraffictManager();
    TrafficHandler th = tm.createTraffichandler(new MessageListener()
                        public void processMessage(Message message)
                             System.out.println("Received: " + message.toString());
         catch (Exception e)
              e.printStackTrace(System.out);
         conn1.disconnect();
    The problem is that the application doesn't stay running to respond to traffic coming across the connection.
    Any guidance would be appreciated.
    Thanks

    Well, what is the job of the MessageListener if it isn't to listen for messages? And apparently it isn't doing that because your application terminates.
    Bear in mind that I don't have any idea how any of those four classes work, or even how they are supposed to work. So let me just quote this line from the API documentation of the Thread class which says when your application will terminate:
    "All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method."
    That must be the case in your application.

  • Simple Java Sound Question...

    Can I draw waveforms while capturing data? If yes, how. If no, why.
    Thanks. I need the answer ASAP, please help.

    Hi nfactorial,
    Can I draw waveforms while capturing data?If you would like to do that in Java you would need to know about how to use the Java language in general and especially about the Java Sound and Java2D APIs.
    If yes, how.It would be too much to explain to answer such a general question. A general answer is, you need to use the Java Sound API to capture the data for which a waveform should be drawn. The Sound API delivers data as a stream of bytes typically encoded in pulse coded modulation (PCM) format. The data stream has digital samples each representing a level of sound pressure for a certain point in time. The stream of samples in the amplitude/time domain need to be transformed to a spectrum of samples in the amplitude/frequency domain, i.e. a number of PCM samples need to be mapped to the frequencies that should be displayed. This is done with the fast fourier transformation algorithm. Each set of amplitude/frequency values can then be displayed as a waveform by using some line drawing logic. The entire process would need to run constantly, i.e. as bytes are received from the sound data stream transformation and drawing is triggered.
    Related readings:
    Java Tutorial
    http://java.sun.com/docs/books/tutorial/
    Java Sound Documentation
    http://java.sun.com/j2se/1.5.0/docs/guide/sound/index.html
    Java Sound API Programmer's Guide
    http://java.sun.com/j2se/1.5.0/docs/guide/sound/programmer_guide/contents.html
    Java Sound Resources
    http.//www.jsresources.org
    Java 2D Graphics Tutorial
    http://java.sun.com/docs/books/tutorial/2d/index.html
    Wikipedia on fast fourier transformation
    http://en.wikipedia.org/wiki/Fast_fourier_transform
    HTH
    Ulrich

  • Simple java pgm - question

    Hallo,
    to the following pgm I had question:
    static void printPrimes (int max) (= wavy bracket;
    boolean(should be angular brackets) sieve = new booolean (angular br max+1
    angular br)
    int i,j;
    for (i=2; i = max;i++)sieve(angluarbr i angular br)= true
    i= 2
    while (i= <= max;) (=wavy bracket Out.println (i+ " "); // is prime
    for (j=i; j <= j+i) sieve(angular br j angularb.) = false;
    while (i <= maxAmpersandAmpersand !sieve (angular br angular br)I++;
    ) wavy br ) wavy br.
    I hope this is still kind of readable.
    Q's are:
    after the first "for" there is a new i=2, which seems to staty at 2 all the time; the following while does not change this value ( the beginning for i++ does not change this) and so seems to print 2 at all times (??)
    then the inner loop seems to count up all the doubbles of the new prime number and thrwoes it out as false at the end of it;
    the i values (increased with i++ seemsto refere at all times to the unit numbers and only indirect to the un it values, which are written/ assigned to it (??)
    I seem to wonder how the pgm can print out anythings else the 2's.
    I would appreciate any help to that.
    ml
    griz

    I hope this is still kind of readable.No, it's not. http://forum.java.sun.com/help.jspa?sec=formatting
    Why are you omitting the braces and brackets? And why don't you type "program"? Aren't we worth the additional time it takes?
    Q's are:
    after the first "for" there is a new i=2, which
    seems to staty at 2 all the time; the following
    while does not change this value Why should it? You don't tell it to.
    ( the beginning for
    i++ does not change this)It does. It just gets re-set to 2 after the for loop-
    and so seems to print 2 at
    all times (??)Yeah. What else?
    then the inner loop seems to count up all the
    doubbles of the new prime number and thrwoes it out
    as false at the end of it; That part is definitely unreadable.

  • Simple conditional array question

    Hi -
    I need to create an array, but how big it is depends on some other influences. Here's a simplified version:
    if (dataRequest.equals("elves")){
    String[] arrayLoader={"tinky","winky","pinky","stinky"};
    } else if (dataRequest.equals("reindeer")){
    String[] arrayLoader={"dasher","dancer","rudolph"};
    } else if (dataRequest.equals("villians")){
    String[] arrayLoader={"snowmiser","heatmiser"};
    out.println(arrayLoader.length);When I run this, I get "arrayLoader.length cannot be resolved to a type", but if I put the arrayLoader.length statement within each of the conditional parts, a length is returned. For some reason, the value seems to be "forgotten" by the time I leave the conditional part of the code.
    What am I missing?

    Variables only exist within the block they are declared in. So each of those String arrays only has scope within its own curly braces.
    What you want is an ArrayList.
    http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html
    It's an array that is automatically sized as you add members to it.

  • Simple Java regex question

    I have a file with set of Name:Value pairs
    e.g
    Action1:fail
    Action2:pass
    Action3:fred
    Using regex package I Want to get value of Name "Action1"
    I have tried diff things but I cannot figure out how I can do it. I can find Action1: is present or not but dont know how I can get value associated with it.
    I have tried:
    Pattern pattern = Pattern.compile("Action1");
    CharSequence charSequence = CharSequenceFromFile(fileName); // method retuning charsq from a file
    Matcher matcher = pattern.matcher(charSequence);
    if(matcher.find()){
         int start = matcher.end(0);
         System.out.println("matcher.group(0)"+ matcher.group(0));
    how I can get value associated with specific tag?
    thanks
    anmol

    read the data from the text file on a line basis and you can do:
    String line //get this somehow
    String[] keyPair = line.split(":")g
    System.out.println(keyPair[0]); //your name
    System.out.println(keyPair[1]); //your valueor if you've got the text file in one big string:
    String pattern = "(\\a*):(\\a*)$"; //{alpha}:{alpha}newline //?
    //then
    //do some things with match objects
    //look in the API at java.util.regex

  • Problem with getNodeValue() - simple Java XPath question

    I am trying to extract the node values from a XML file:
    <root>
      <frame>
         <boxes>
           <box>
              <spec>22</spec>
              <spec>2222</spec>
           </box>
           <box>
              <spec id="BA" value="short"/>
              <spec id="BB" value="thin"/>
              <spec id="BC" value="black"/>
              <spec id="BD" value="full"/>
              <spec id="BE" value="7"/>
              <spec id="BF" value="deactive"/>
           </box>                
         </boxes>
         <circles>
           <circle id="CA" value="blue"/>
           <circle id="CB" value="green"/>
         </circles>
      </frame>
    </root>I use this code:
             XPathFactory factory = XPathFactory.newInstance();
             XPath xpath = factory.newXPath();
             XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec");            
             Object result = xPathExpression.evaluate(doc, XPathConstants.NODESET);
             NodeList nodes = (NodeList) result;
             for (int i = 0; i < nodes.getLength(); i++) {
                 System.out.println(nodes.item(i).getNodeValue());
             }But only:
    null
    null
    null
    null
    null
    null
    null
    null
    get printed. I would have assumed:
    22
    2222
    null
    null
    null
    null
    null
    null
    since the two first spec nodes contains the above numbers. Any ideas?

    change this:
    XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec");to this:
    XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec/text()");Need to xpath all the way down to the text of the node.
    You could use
    System.out.println(nodes.item(i).getTextContent());with your current xpath but if the spec node has children, these will also be included in the output.

  • Efficiency Question: Simple Java DC vs Used WD Component

    Hello guys,
    The scenario is - I want to call a function that returns a FileInputStream object so I can process it on my WD view. I can think of two approaches - one is to simply write a simple Java DC that does so and just use it as a used DC so I can call the functionality from there. Or create another WD DC that exposes the value (as binary) via component interface.
    I'm leaning on the simple Java DC approach - its easier to create. But I'm just curious on what would be the Pro-side (if there's any) if I use the WD Component interface approach? Is there a plus for the efficiency? (Though I doubt) Or is it just a 'best/recommended practice' approach?
    Thanks!
    Regards,
    Jan

    Hi Jan
    >one is to simply write a simple Java DC that does so and just use it as a used DC so I can call the functionality from there
    Implemented Java  API for the purpose mentioned in your question is the right way, I think. The Java API can be even located in the same WebDynpro DC as your WebDynpro components. There is not strongly necessity to put it into separate Java DC.
    >Or create another WD DC that exposes the value (as binary) via component interface
    You should not do this because in general WD components' purpose is UI, not API. Implementing WD component without any UI, but with some component interface has very-very restricted use cases. Such WD component shall only be a choice in the cases when the API is WebDynpro based and if you have to strongly use WebDynpro Runtime API in order to implement your own API.
    If your API does not require WebDynpro Runtime API invocations or anything else related to WebDynpro then your choice is simple Java API.
    >But I'm just curious on what would be the Pro-side (if there's any) if I use the WD Component interface approach? Is there a plus for the efficiency?
    No. Performance will be better in simple Java API then in WebDynpro component interface. The reason is the API will not pass thought heavy WebDynpro engine.
    BR, Siarhei

  • [JNI Beginner] GC of Java arrays returned by the native code

    Hello all,
    I am beginning with JNI, to integrate a C library that pilots an industrial equipment, into a java UI. This library enables to exchange various proprietary PDUs (protocol data units), with the equipment, up and down (request/replies). Both requests and replies are arrays of bytes (+char*+).
    "Request" byte arrays are constructed by Java code, which passes them to the JNI code that glues with the lib. "Reply" byte arrays are returned to the Java code, which analyzes them.
    The "return reply" part is very similar to this [tutorial example|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html] , which returns bytes read from a file. However there's something I don't understand with regard to garbage collection of the returned byte array:
    - in this stock example, the C code creates a Java byte array fills it, and simply returns it (example code stripped to highlight only the parts relevant to my question):
        jByteArray=(*env)->NewByteArray(env, size);
        (*env)->SetByteArrayRegion(env, jByteArray, 0, size, (jbyte *)sourceBytes);
        return (jByteArray);What will happen to this Java array (jByteArray) with regard to garbage collection?
    - if it's no more referenced (the example Java code just systemouts it and forgets it), will it be eligible to GC?
    - if it is referenced by a Java variable (in my case, I plan to keep a reference to several replies as the business logic requires to analyze several of them together), do regular Java language GC rules apply, and prevent eligibility of the array to GC as long as it's referenced?
    That may sound obvious, but what mixes me up is that the same tutorial describes memory issues in subsequent chapters: spécifically, the section on "passing arrays states that:
    [in the example] the array is returned to the calling Java language method, which in turn, garbage collects the reference to the array when it is no longer usedThis seems to answer "yes" to both my questions above :o) But it goes on:
    The array can be explicitly freed with the following call:
    {code} (*env)-> ReleaseByteArrayElements(env, jByteArray, (jbyte *)sourceBytes, 0);{code}Under what circumstances would one need to explicitly free jByteArray when it's about to be returned to the Java calling method? Or does this sentence apply to completely different situations (such as, when the array is +not+ returned as is to a Java method)?
    The tutorial's next section has a much-expected +memory issues+ paragraph, from which I quote:
    By default, JNI uses local references when creating objects inside a native method. This means when the method returns, the references are eligible to be garbage collected.I assume this means, +unless the references are assigned, in the Java code, to a Java variable+, right?
    If you want an object to persist across native method calls, use a global reference instead. A global reference is created from a local reference by calling NewGlobalReference on the the local reference.I assume this enables the C code to maintain a global reference to a java object even if it's not referenced anymore from the Java variables, right?
    I also checked the [JNI specification|http://download-llnw.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp1242] , but this didn't clear the doubt completely:
    *Global and Local References*
    The JNI divides object references used by the native code into two categories: local and global references. Local references are valid for the duration of a native method call, and are automatically freed after the native method returns. Global references remain valid until they are explicitly freed.
    Objects are passed to native methods as local references. All Java objects returned by JNI functions are local references. The JNI allows the programmer to create global references from local references. JNI functions that expect Java objects accept both global and local references. A native method may return a local or global reference to the VM as its resultAgain I assume the intent is that Global references are meant for objects that have to survive across native calls, regardless of whether they are referenced by Java code. But what worries me is that combining both sentences end up in +All Java objects returned by JNI functions are local references (...) and are automatically freed after the native method returns.+.
    Could you clarify how to make sure that my Java byte arrays, be they allocated in C code, behave consistently with a Java array allocated in Java code (I'm familiar already with GC of "regular" Java objects)?
    Thanks in advance, and best regards,
    J.

    jduprez wrote:
    Hello all,
    I am beginning with JNI, to integrate a C library that pilots an industrial equipment, into a java UI. This library enables to exchange various proprietary PDUs (protocol data units), with the equipment, up and down (request/replies). Both requests and replies are arrays of bytes (+char*+).
    "Request" byte arrays are constructed by Java code, which passes them to the JNI code that glues with the lib. "Reply" byte arrays are returned to the Java code, which analyzes them.
    The "return reply" part is very similar to this [tutorial example|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html] , which returns bytes read from a file. However there's something I don't understand with regard to garbage collection of the returned byte array:
    - in this stock example, the C code creates a Java byte array fills it, and simply returns it (example code stripped to highlight only the parts relevant to my question):
        jByteArray=(*env)->NewByteArray(env, size);
    (*env)->SetByteArrayRegion(env, jByteArray, 0, size, (jbyte *)sourceBytes);
    return (jByteArray);What will happen to this Java array (jByteArray) with regard to garbage collection?It will be collected when it is no longer referenced.
    The fact that you created it in jni doesn't change that.
    The array can be explicitly freed with the following call:
    (*env)-> ReleaseByteArrayElements(env, jByteArray, (jbyte *)sourceBytes, 0);Under what circumstances would one need to explicitly free jByteArray when it's about to be returned to the Java calling method? Or does this sentence apply to completely different situations (such as, when the array is not returned as is to a Java method)?
    Per what the tutorial says it is either poorly worded or just wrong.
    An array which has been properly initialized it a just a java object. Thus it can be freed like any other object.
    Per your original question that does not concern you because you return it.
    In terms of why you need to explicitly free local references.
    [http://download-llnw.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp16785]
    The tutorial's next section has a much-expected memory issues paragraph, from which I quote:
    By default, JNI uses local references when creating objects inside a native method. This means when the method returns, the references are eligible to be garbage collected.I assume this means, unless the references are assigned, in the Java code, to a Java variable, right?As stated it is not precise.
    The created objects are tracked by the VM. When they are eligible to be collected they are.
    If you create a local reference and do NOTHING that creates an active reference elsewhere then when the executing thread returns to the VM then the local references are eligible to be collected.
    >
    If you want an object to persist across native method calls, use a global reference instead. A global reference is created from a local reference by calling NewGlobalReference on the the local reference.That is not precise. The scope is the executing thread. You can pass a local reference to another method without problem.
    I assume this enables the C code to maintain a global reference to a java object even if it's not referenced anymore from the Java variables, right?
    It enables access to it to be insured across multiple threads in terms of execution scope. Normally you should not use them.

  • Manipulating java array object in an oracle procedure

    hi there,
    i have a java store procedure that returns an array of filenames, and i have an oracle stored procedure that will for each filename returned in the java array object, open that file do some processing and load the data into database tables, now my question is, would an oracle 9i varray object be compatible with a java array, or should i pass in a pl/sql table to store the filnames returned?
    i really am stuck at this point and need help !!!!
    Thanx

    Wole,
    Have you searched the code samples available at the Technet Web site? Could you not find a relevant one?
    Have you tried searching the Ask Tom Web site?
    Good Luck,
    Avi.

  • Can we call a simple java application from ESB

    Please let me know how this can be done by using a ESB. The application jar exists on the host server. How we can pass parameters etc and receive results from this application.
    Any help will be greatly appreciated.
    Prakash

    Not sure if I completely understand your question, but you can certainly try following ways:
    - call your java application via WSIF. ESB with JAVA wsif is available in 10.1.3.3.1 only (it is not supported in 10.1.3.3 very well).
    - you will have to include this jar file in server.xml or bpel/system/classes so that it is available to the SOA jvm.
    - You mentioned it is simple java application, but if your java API has complex (object) input and output, you will need some work
    HTH,
    Chintan

Maybe you are looking for