How to assign to String[] from StringBuffer in a loop?

Hi all,
public class Test {
public String[] getSJ() 
        String[]    jg;
        String[]    jig;
        String[]    tg;
        String[]    result;
        Date startTime;
        StringBuffer buf = new StringBuffer();
        int i;
        int j;
        int k = -1;
jg = {"g1", "g2"};
for( i=0; i < jg.length; i++ )
         jig = {"1", "2", "3"};
         for( j=0; i < jig.length; j++, k++ )
               buf.append( jg[i] ).append( ":" );                                      
               buf.append( jig[j] ).append( ":" );   
               buf.append( Date() );    
               result[k] = buf.toString();
               buf = null;
}I want to add to result string array by assigning from buf which is StringBuffer in a loop. But what happens after buf = null??
Will the added String be gone?
Or should I just do:
buf = "";
and continue with the loop and the string objects will be preserved? But isn't result just an array of references?
Many thanks,

I am not sure I understand correctly. Here is a test program (in real program I call APIs from a library which returns String[] for jg and for jig, i.e they are changing in the loop in runtime.
I tried to put together test program:
import java.util.*;
public class Test {
     public void Test() {
public String[] getSJ()
        String[] jg = {"g1", "g2"};
        String[] jig = {"1", "2", "3"};
        String[]    result = new String[50];
        StringBuffer buf = new StringBuffer();
        int i;
        int j;
        int k = 0;
for( i=0; i < jg.length; i++ )
         for( j=0; i < jig.length; j++, k++ )
               buf.append( jg[i] )
                  .append( ":" )
                  .append( jig[j] )
                  .append( ":" )
                  .append( new Date() );
               result[k] = buf.toString();
               buf = null;
   return result;
public static void main( String[] args ) {
    Test   t = new Test();
    String[] res = t.getSJ();
    for( int i=0; i<res.length; i++ ) {
     System.out.println( res[i] );
}but when I run it fails in this statement:
buf.append( jg[i] )
                  .append( ":" )
                  .append( jig[j] )
                  .append( ":" )
                  .append( new Date() );Exception in thread main
java.lang.NullPointerException
java.lang.String[] Test.getSJ()
Test.java:24
void Test.main(java.lang.String[])
Test.java:38
Wierd!?
And if I change to:
buf.setLength(0);
then it fails with this error:
Exception in thread main
java.lang.ArrayIndexOutOfBoundsException: 3
        java.lang.String[] Test.getSJ()
                Test.java:24
        void Test.main(java.lang.String[])
                Test.java:38Also, I would like not to have to allocate like in:
String[] result = new String[50];
because I do not know how many different Strings in array will be returned by API. Is it possible to dynamically adjust
String[] result
somehow?
Many thanks,

Similar Messages

  • How to read a string from file & assign the val to a variable in batch file

    Hi,
    How to read a string from a file and assign the value to a variable then return the value to the screen in windows batch file?
    Any suggestions?
    thanks.

    Unless this is a homework question then I don't see the purpose of doing this, but....
    You should be looking a the supplied package utl_file to get the string out of the file, dbms_output to display the string and then google windows batch/command files calling sqlplus to execute your program.
    Andre

  • How to convert a string from upper case to lower case in FOX formula

    Hi Experts,
    How to convert a string from upper case to lower case in FOX formula?
    Thanks,
    Cheers!!!
    PANKAJ

    The last result.append( c ) should be:
    result.append( Character.toLowerCase(c) );

  • How to convert a string from lower case to upper case withour using transla

    Hi all,
    how to convert a string from lower case to upper case withour using translate,
    Thanks in Advance,
    Reddy

    Refer to this related thread
    Re: hi guys this very urgent please help

  • How to transfer a string from sub sequence to main sequence

    Hi,
    How to transfer a string from sub sequence to main sequence, My main sequence has included a sub sequence, the sub sequence is return a string value after running done, I need to get this string value from sub sequence to main sequence, I check the defined that look like seem the two
    sequence have themself local variable,but I don't know how to defined a globe variable to cover main sequence and sub sequence like VC++'s Main App ,Please kindly help me,thanks in advance...

    Hi,
    I hope this small example will help you.
    Regards
    Ray Farmer
    Regards
    Ray Farmer
    Attachments:
    Sequence File1.seq ‏36 KB

  • How to search a string from the database?

    how to search a string from the database? starting with some character

    If you're trying to do this in a SELECT, you can use the LIKE verb in your WHERE clause.
    Here's an Example
      SELECT obj_name FROM tadir
        INTO prog
        WHERE pgmid = 'R3TR'
          AND object = 'PROG'
          AND obj_name LIKE 'Z%'.
    In this case it will select every row that obj_name starts with Z. 
    If you wanted to find every row that the field obj_name contains say... 'WIN'  you use LIKE '%WIN%'.
    Edited by: Paul Chapman on Apr 22, 2008 12:32 PM

  • How to build a String from Date?

    How to build a String from class Date?
    How to get the year, month, day, hour ... from a Date object.

    Ok to build a string use this function in java.util.Date
    toString()
    TO get year, date, etc u can use the following functions
    getYear()
    getDate()
    This link might help u more
    http://java.sun.com/products/jdk/1.1/docs/api/java.util.Date.html

  • How to write a string a stringbuffer to a text file or read a file?

    I need create a text file if the file is not exist, if exist, I have to append a string or stringbuffer to the file. Basically I am using java server page for our web application. I need send user input into a text file. I am uploading my JSP into a server, and run JSP from server. I wonder if I want to create a file, where this file goes, and how can I specify the path of the file?
    I used: BufferedReader br = new BufferedReader( new FileReader("report.txt"));
    The file report.txt could not be found.
    Please help me, thank you so much

    Try
    File file = new File("report.txt");
    out.println("File name: "+file.getAbsolutePath());in your jsp page, then you will see where it would be placed it you created it.
    You can specify the full path like this:
    File wFile = new File("c:\\temp\\report.txt"); // for windows
    File uFile = new File("/tmp/report.txt"); // for unix/linux
    // or
    File file = new File(myPath, "report.txt"); // where myPath is the path where you want to place report.txt.You can either use a File object or String object in the FileReader constructor..
    If you just want to know if the file exits, then use a file object and call exists() on it, returns true if the file already exist. If you want to create the file if it doesn't exit and append a string, then you don't need to check if it exist first. Just do it like this:
    PrintStream ps = new PrintStream(new FileOutputStream("report.txt", true), true);
    // again you could use a file object instead of a string with the file name
    ps.println("Add this line");
    ps.close();If the file doesn't exist, it will create it for you. The second argument in FileOutputStream means "append", and the second argument in PrintStream means "autoflush" every time you use the println methods (or add a newline '\n').

  • How to put a string from one Frame to another Frame?

    Dear all,
    How can I put a String from one Frame to another Frame?
    When the application started, the Frame 'WindowX' will be displayed. After you press the 'openButton', a whole new Frame (inputFrame) will be shown. In this Frame )(inputFrame) you can write a String in a TextField. After pressing the okButton, this String will be sent to the first Frame 'WindowX'.
    But does anyone know how to realize the sending part?
    I've tested this code on Win98 SE and JDK1.2.2.
    Hope someone can help me. Thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    public class WindowX extends Frame implements ActionListener, WindowListener
         private Button openButton;
         private TextField resultField;
         public static void main(String [] args)
              WindowX wx = new WindowX();
              wx.setSize(300,100);
              wx.setVisible(true);
         public WindowX()
              setLayout(new FlowLayout());
              openButton=new Button("open");
              add(openButton);
              openButton.addActionListener(this);
              resultField=new TextField(10);
              add(resultField);
              resultField.addActionListener(this);
              addWindowListener(this);     
         public void actionPerformed(ActionEvent evt)
              if (evt.getSource()==openButton)
                   inputFrame ip=new inputFrame();
                   ip.setSize(200,80);
                   ip.show();
         public void place(String theString) //this doesn't work
              resultField.setText(theString);
         public void windowClosing(WindowEvent event)
              System.exit(0);
         public void windowIconi......
    class inputFrame extends Frame implements ActionListener,WindowListener
         String theString = "";
         Button okButton;
         TextField inputField;
         WindowX myWX=new WindowX();   //??
         public inputFrame()
              setLayout(new FlowLayout());
              inputField=new TextField(10);
              add(inputField);
              inputField.addActionListener(this);
              okButton=new Button("OK");
              add(okButton);
              okButton.addActionListener(this);     
              addWindowListener(this);     
         public static void main(String[] args)
              Frame f = new Frame();
              f.show();
         public void actionPerformed(ActionEvent evt)
              if (evt.getSource()==okButton)
                   theString=inputField.getText();
                   myWX.place(theString);   //??
                   dispose();
        public void windowClosing(WindowEvent e) {
        dispose();
        public void windowIconi......
    }

    Thanks for your reply!
    But I got an other problem:
    I can't refer to the object (wx) made from the main Frame 'WindowX', because it's initialized in 'public static void main(String [] args)'...
    Hope you can help me again... Thanks!
    import java.awt.*;
    import java.awt.event.*;
    public class WindowX extends Frame implements ActionListener, WindowListener
         private Button openButton;
         private TextField resultField;
         public static void main(String [] args)
              WindowX wx = new WindowX();   //!!
              wx.setSize(300,100);
              wx.setVisible(true);
         public WindowX()
              setLayout(new FlowLayout());
              openButton=new Button("open");
              add(openButton);
              openButton.addActionListener(this);
              resultField=new TextField(10);
              add(resultField);
              resultField.addActionListener(this);
              addWindowListener(this);     
         public void actionPerformed(ActionEvent evt)
              if (evt.getSource()==openButton)
                   inputFrame ip=new inputFrame(wx);
                   ip.setSize(200,80);
                   ip.show();
         public void place(String theString)
              resultField.setText(theString);
         public void windowClosing(WindowEvent event)
              System.exit(0);
         public void windowIconi....
    class inputFrame extends Frame implements ActionListener,WindowListener
         String theString = "";
         Button okButton;
         TextField inputField;
         WindowX parent;
         public inputFrame(WindowX parent)
              setLayout(new FlowLayout());
              this.parent=parent;
              inputField=new TextField(10);
              add(inputField);
              inputField.addActionListener(this);
              okButton=new Button("OK");
              add(okButton);
              okButton.addActionListener(this);     
              addWindowListener(this);     
         public static void main(String[] args)
              Frame f = new Frame();
              f.show();
         public void actionPerformed(ActionEvent evt)
              if (evt.getSource()==okButton)
                   theString=inputField.getText();
                   parent.place(theString);
                   dispose();
        public void windowClosing(WindowEvent e) {
        dispose();
        public void windowIconi..........
    }          

  • How can i pass string from C++ DLL to Java via JNI?

    Hi everybody. I made a DLL with Borland C++. I must pass a string from this dll to Java via JNI.Namely i define a string variable in C++ DLL and i send this variable's value to Java via JNI.
    I can pass integers but i couldnt Strings. . How can i do this? is there any sample?

    Hi,
    So your function should be private static native String get_text();
    (It's often a good idea to make native methods private since when you change signatures you generally have to change java wrapper methods only).
    I know nothing about C++ strings but I'm pretty sure that you can convert it to char*, so
    do :
    char* szMyString = myString.toChar*();
    Then return from native with JNU_NewStringPlatform(env, szMyString)
    (see my 1st answer for JNU_NewStringPlatform() description).
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to create XML string from BPM Business Object?

    Hello,
    I have a business object in my BPM project and I need to transform it in a XML string:
    From:
    Business Object: Customer
    Properties:          Name, Age
    To:
    "<Customer><Name>Robert</Name><Age>17</Age></Customer>"
    How can I do this?
    Thanks.

    Hello,
    I have a business object in my BPM project and I need to transform it in a XML string:
    From:
    Business Object: Customer
    Properties:          Name, Age
    To:
    "<Customer><Name>Robert</Name><Age>17</Age></Customer>"
    How can I do this?
    Thanks.

  • How to pass a string from a servlet to client side

    hi,
    i would like to generate a string from a servlet and pass it to the client side. the client will receive the string by using request.getParameter(). How should i implement this system? Could anybody give me some hint?
    Best Regards,
    Henry

    Greetings,
    hi,
    i would like to generate a string from a servlet and
    pass it to the client side. the client will receive
    the string by using request.getParameter(). HowAre you referring to the instance of (Http)ServletRequest the 'request' object being passed to the "client"? What is the "client" in this case? If you mean a "traditional" client communicating over (or by tunneling through...) HTTP then no can do. The (Http)ServletRequest object is generated by the web container (a.k.a. "servlet engine"), not by the client, and it is not serializable so there is no way to pass it back to the client...
    should i implement this system? Could anybody give me
    some hint?It depends again on "what is the 'client' in this case?"
    Best Regards,
    HenryRegards,
    Tony "Vee Schade" Cook

  • How to save the string from JTextFied to database?

    can i know how to save the data from JTextFied to databse. Is it using update?

    The most straightforward way would be something like:
    String myKey=myKeyField.getText();
    String foo=fooField.getText();
    String sql="update mytable set foo='"+foo+"' where mykey='"+myKey+"'";
    connection.createStatement().executeUpdate(sql);
    This example assumes that the input fields cannot possibly contain quotes or the string won't be built correctly. Which by the way brings up a question I'd be interested in hearing others answer: What do you do about this? Sometimes I use PreparedStatement which handles that problem, other times I write my own little function to escape the string properly.
    You can also read the record into a ResultSet and use ResultSet.update(). I'm mostly using mySql and I found that in mySql ResultSet.update just creates a SQL update statement like I did above and executes it, so the only real advantage would be if you find the syntax more convenient. Perhaps other database drivers do something different that would give other pros and cons.

  • How can I get String from Bytes

    I want to get String from array of bytes but i have some trouble from byte that it's lager more than 128. How can I do ???
    Please hepl me. Thanks very much.

    This program is only to show you what the relationships are between unsigned byte, signed byte, character, and binary values. Because of the constraints that Java has, the program code is not especially clean. Run the program and see if it helps. As has been said, the character output is dependent on the encoding in use.
    Here is a sample of some of its output:
    Unsigned byte= 189 Signed byte= -67 Character= � Binary= 10111101
    Unsigned byte= 190 Signed byte= -66 Character= � Binary= 10111110
    Unsigned byte= 191 Signed byte= -65 Character= � Binary= 10111111
    Unsigned byte= 192 Signed byte= -64 Character= � Binary= 11000000
    Unsigned byte= 244 Signed byte= -12 Character= � Binary= 11110100
    Unsigned byte= 245 Signed byte= -11 Character= � Binary= 11110101
    Unsigned byte= 246 Signed byte= -10 Character= � Binary= 11110110
    public class ATest {
        public static void main(String[] args) {
            int in;
            byte by;
            String bin;
            char chr;
            for(in=0; in<256; in++) {
                // create a byte whose binary value is equal to the;
                // integer loop counter;
                by = (byte)in;
                // mask off sign extension [that I don't agree with!] and;
                // cast the resultant 8 bits to a char;
                chr = (char)(by & 0x00ff);
                // since there's no Byte.toInteger, must cast to int to get;
                // binary string and then delete unwanted portion of string;
                if(in<128) {
                    bin = Integer.toBinaryString((int)by);
                } else {
                    bin = Integer.toBinaryString((int)by).substring(24);
                // print everything;
                System.out.println(
                    "Unsigned byte= "+in+
                    " Signed byte= "+by+
                    " Character= "+chr+
                    " Binary= "+bin);
    }

  • How to send a string from sender to receiver side using java

    I am doing a project on Digital Signature.I have already done with the GUI using java swing.
    Now i want to send a string from the sender side to the receiver side on the click of a button using socket programming.
    Please can anybody provide me with the code as early as possible.

    http://catb.org/~esr/faqs/smart-questions.html

Maybe you are looking for

  • Ipod Nano 7 won't show in my itunes but will on other computers.

    My ipod nano (7th gen) was working fine on my Lenovo (windows 7) laptop for 3 weeks. Then yesterday, itunes told me I needed to restore my ipod which I did. Since then it will not show in my itunes. The Apple store couldn't figure it out. The device

  • How do I uninstall Mavericks and go back to Mountain Lion

    Any ideas? Can't find it on App Store anymore.

  • Ideal System?

    I am a longtime Premiere user, now working with CS3 - almost exclusively SD, but moving gradually to HDV. My Dell XPS was powerful at purchase - Pentium 4 3.2 GHz, 4gb RAM, 23" 1920 x 1200 monitor, 2 external & 2 internal HDs. Also added an 800 Firew

  • Why won't my airplay work?!

    I am running ios7 on a 5s with an up to date 2nd gen apple tv I have both phone and Apple TV set on the same wifi network And airplay is set to ON but when I try play a song or video the airplay icon simply just doesn't appear I have searched high an

  • Multi org

    Hi, i am going through multi org manual and i have some queries on it. 1. can i have a inventory org that belong to more than one operating unit(if inventory org and operating unit belong to the same set of books). 2. I am assuming that multiple set