Question about string array?

Hello,
When passing Stting arrays to a function, is there anyto test if the array is emply?
void testFucntion(String[] test){
}

Or test the array is null.
if (test == null || test.length == 0)

Similar Messages

  • Question about C array initialization

    I understand that the statement
    char string[] = "chars";
    initializes string[5] to 0 ('\000'). My question is does the statement
    char *strings[] = { "string1", "string2", "string3" };
    initialize strings[3] to (void *) 0, i.e. NULL? I can't find the answer to this question in the ansi standard. GCC seems to tack on a NULL pointer at the end (even with the -ansi and -pedantic-errors flags), which is really convenient for finding the boundary, but I'm not sure whether it's a GCC thing or an official C thing. I see where the standard talks about terminating char arrays initialized by a string literal with a null byte, but it doesn't talk about the analogous case with arrays of pointers.
    Last edited by nbtrap (2012-06-25 03:18:20)

    nbtrap wrote:
    Not necessarily. A declaration like:
    char arr[3] = "str";
    doesn't get null-terminated.
    It doesn't get null-terminated because you don't leave enough room in the array for the null character. "char arr[3]" can only contain 3 characters, the same way that "char arr[2] = "str" will only contain 2. The second example generates a warning whereas the first does not, but only because it is very common to work with non-null-terminated strings.
    nbtrap wrote:
    And besides, my point is that initializing strings[3] *would* make sense for the same reason that intializing
    char foo[] = "bar";
    with a terminating null byte *does* make sense.
    I know that arrays of pointers are not the same. My questions assumes that much. The fact of the matter is, however, GCC terminates pointer arrays of unknown size with a null pointer, and my question is simply "is this an ansi C thing or a GCC thing?".
    In fact, it seems that GCC terminates all arrays of unknown size that are explicitly initialized with the appropriate number of null bytes. For example:
    struct tag { int i; char c; char *str; } tags[] = {
    { 1, 'a', "string1" },
    { 2, 'b', "string2" },
    { 3, 'c', "string3" }
    initializes tags[3] to sizeof (struct tag) null bytes. Try it for yourself.
    I get the following:
    test.c
    #include <stdio.h>
    int
    main(int argc, char * * argv)
    int i;
    char *strings[] = { "string1", NULL, "string3"};
    for (i=0;i<5;i++)
    printf("strings[%d]: %s\n", i, strings[i]);
    return 0;
    output
    strings[0]: string1
    strings[1]: (null)
    strings[2]: string3
    Segmentation fault
    test2.c
    #include <stdio.h>
    #include <string.h>
    int
    main(int argc, char * * argv)
    int i;
    struct tag {int i; char c; char *str;};
    struct tag null;
    memset(&null, 0, sizeof(struct tag));
    struct tag tags[] =
    { 1, 'a', "string1" },
    // { 2, 'b', "string2" },
    null,
    { 3, 'c', "string3" }
    for (i=0;i<5;i++)
    printf(
    "tags[%d]: (%p) %1d %c %s\n",
    i, tags + i, tags[i].i, tags[i].c, tags[i].str
    return 0;
    output
    tags[0]: (0x7fffd2df4e80) 1 a string1
    tags[1]: (0x7fffd2df4e90) 0 (null)
    tags[2]: (0x7fffd2df4ea0) 3 c string3
    tags[3]: (0x7fffd2df4eb0) 0 (null)
    Segmentation fault
    The above behavior appears to conflict.
    Given that string constants in C are defined as null-terminated, i.e. "str" is equivalent to "{'s', 't', 'r', '\0'}", the assignment 'arr[] = "str"' explicitly includes a null terminator. The other examples above do not include such a terminator. Even if it would be convenient sometimes, the standard should adopt a minimally invasive approach. It's easy to add a NULL at the end of an array declaration, but impossible to remove an extra element from such a declaration.
    This may be informative too:
    test3.c
    #include <stdio.h>
    #include <string.h>
    int
    main(int argc, char * * argv)
    char str[] = "test";
    char *strings[] = {"string1", NULL, "string3"};
    struct tag {int i; char c; char *str;};
    struct tag null;
    memset(&null, 0, sizeof(struct tag));
    struct tag tags[] =
    { 1, 'a', "string1" },
    // { 2, 'b', "string2" },
    null,
    { 3, 'c', "string3" }
    printf(
    "str\n size: %lu\n length: %lu\n"
    "strings\n size: %lu\n length: %lu\n"
    "tags\n size: %lu\n length: %lu\n",
    sizeof(str), sizeof(str)/sizeof(char),
    sizeof(strings), sizeof(strings)/sizeof(char *),
    sizeof(tags), sizeof(tags)/sizeof(struct tag)
    return 0;
    output
    str
    size: 5
    length: 5
    strings
    size: 24
    length: 3
    tags
    size: 48
    length: 3
    The string length (actual number of chars in array) is reported as 5 ('t', 'e', 's', 't', '\0'), which is expected. The array of strings and tags are both reported as 3, even though you can access a null value after the last initialized index of the tags array. If that null value was really supposed to be there, it should be accounted for using sizeof, just as the null character is in the string.
    Maybe the ultimate null element of the tags array is some artefact of memory alignment.

  • Question about string manipulation

    Hello, I am practicing with Java and trying to learn it, and have a quick question. I am trying to get the count on a string of numbers for after a decimal point. the numbers are generated as the result of a math, so I can't use index, since the location of the decimal changes based on the number imputed. I want to figure this out on my own, but have hit a wall here, i've spent the past few hours trying every string command I can think of, and haven't figured it out yet, anyone mind pointing me in the right direction for which string to use? Thanks in advance for any help you can provide!

    Is this what you want?
    public class Fallen{
      public static void main(String[] args){
        String number = "123.45678";
        String frac = number.substring(number.indexOf('.') + 1);
        System.out.println(frac + " length=" + frac.length());
        frac = number.replaceFirst("^.+\\.", "");
        System.out.println(frac + " length=" + frac.length());
    }

  • Question about Java Array Primative Type.

    Say I create an Array of type Integer, like this:
    Integer [] myArray = new Integer[10];
    I now have an Integer array, 10 cells big.
    However, I have now learned that I can do the following:
    String [] [] [] stringArray = new String [3][3][3];
    I can create higher dimensional arrays!
    Is there any limit to the degree/dimension such an array may be,
    and does the Array class presently support any methods, like getDimension,
    to check the number of indices on an array where the number of indicies/dimensions
    are a priori unknown?

    And as far as I know, their is not limit to the depth of the arrays as long as you stay within the memory boundaries.In practice the depth is limited by the range of a Java 'int', because the array descriptor in the .class file is a String starting with the appropriate number of [ characters.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Question about an Array of objects

    I'm writing a program that is supposed to store a String and a double in an array of CustomerBill objects. I just want to know if I am doing it correctly. Heres my code:
    public static CustomerBill[] getCustomerData()
             //Local variables
             int numCust;     //The number of customers being processed
             double amt;
             String customer;        
          //Ask for the number of customers to be processed.
             System.out.print("How many customers are to be processed? ");
             numCust = Integer.parseInt(keyboard.nextLine());
             CustomerBill[] array = new CustomerBill[numCust];
             //Ask user to enter the data.
             System.out.println("\nPlease enter customer data when prompted.");
             System.out.println("Enter customer's last name, then first name.");
          //Get the customer data from user.
             for (int i = 0; i < array.length; i++)
               array[i] = new CustomerBill();
               System.out.print("\nCustomer name:  ");
               customer = keyboard.nextLine();       
               array.setName(customer);
    System.out.print("Total bill amount: ");
    amt = Double.parseDouble(keyboard.nextLine());
    array[i].setAmount(amt);
    System.out.println();
    return array;

    Write a test() method that:
    (1) Gets an array of CustomerBills using getCustomerData()
    (2) In a for-loop print out each of the CustomerBills. It will help if
    CustomerBill has a toString() method but, in any case you should be
    able to see that the aray contains the right number of nonnull elements.
    Then write a main() method that calls the test() method.
    [Edit] And then run it! You may need to do this a few times and check
    what happens with "crazy" data.

  • Question about using arrays

    I have a web page written with combination of Front Page and Java is included. I have 4 drop down boxes which work in sequence. select an item in the first, it then asks you to select in the second box, then 3rd then in the final 4th box. This was set up using arrays. My question is how can i put a hyperlink to the items in the last drop down box? I want the last selection to go to a URL. can you tell me what code i need to use and where to insert it? I assume it has to go into the array somewhere. Thanks, Tom

    selection to go to a URL. can you tell me what code
    i need to use and where to insert it? Not without you clarifying your question and showing the relevant bits of your code, and possibly not even then.
    When you post code, please use[code] and [/code] tags as described in Formatting tips on the message entry page. It makes it much easier to read.
    I assume it
    has to go into the array somewhere. I assume it doesn't, because code doesn't go into arrays.

  • Question about String constant pool

    Is there is any function available to find how many Sring literal in String Constant pool

    Well, there's stuff like BCEL.
    But it may not do what you want.
    Why do you want to find out what's in the constant pool?

  • Easy question about String

    Hi!
    I have a string in a variable. how can I check if the String is composed just by numbers?
    thank you very much!

    Use the following method from Integer API
    parseInt
    public static int parseInt(String s)
                        throws NumberFormatExceptionParses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002d') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.If it throws NumberFormatException its alphanumeric else its numeric. You would however have to remove any spaces or commas etc. since they are not mumeric either

  • Question about sorting arrays

    Hi,
    I have posted information from an one-dimensional array on to a list widget. When a user selects an item in the list(index value = 3), presses the delete button, the item would be removed. Likewise, the element of the array at index value 3 would also be removed (or set to null?).
    The trouble I am having is, how would you move up the elements that are subsequent to the element index value 3? For example, moving element index value 4 up to 3, 5 up to 4, 6 up to 5....etc.?
    Here is my code:
    public void delete()
    list.delItem(list.getSelectedIndex());
    student[list.getSelectedIndex()]=null;
    Thanks alot!!

    It's usually faster to use System.arraycopy() to close up the "hole" when removing something from an array: public void delete() {
        int index = list.getSelectedIndex() ;
        list.delItem(index) ;
        // if not removing last item... close up hole...
        if (index < (student.length-1)) {
            System.arraycopy(student, index+1, student, index, student.length - 1 - index) ;
        // clear out space made empty at end of array
        student[student.length-1] = null ; // or whatever represents 'empty' in your student[]

  • A question about String.hashCode()

    Why the implementation of hashCode() for String class using 31 as a base?

    Why the implementation of hashCode() for String class
    using 31 as a base?I think it's a magic number. It has been found to produce a reasonably even distribution over the int range.

  • A question about string.trim()

    I got a fragment of code as follows:
    String s = "abcd ";
    boolean a = (s.trim()=="abcd");
    boolean b = (s =="abcd ");
    Why a is false, b is true?

    The reason why the below code has true assigned to be is quite easy to explain:
    String s = "abcd";
    String y = "abcd";
    boolean b = (s == y);
    ...The String class has a "Pool" of strings. When you use String literals; the compiler automatically checks if it is in the String pool already and if it exists; a reference to that String is returned; if not a new entry in the pool is added and then you get a reference to that. This is only true for Stirng literals and String created using the intern() method.
    If you compile this code you will see that the strings are not equal:
    public static void main(String args[])
      String s = "abcd";
      String y = args[0];
      boolean b = (s == y);
      System.out.println(b);
    }This is because the "abcd" is in the String pool when your program starts; but because the value "abcd" passed in (is not created in the pool automaticlaly). Therefor they are two different String objects.
    This code block shows that you can add Strings to the pool. The intern() method checks to see if the String is in the pool already and if it is it will return you a reference to it; if not it will create one and then return it.
    public static void main(String args[])
      String s = "abcd ";
      String y = args[0].intern();
      boolean b = (s == y);
      System.out.println(b);
    }- Chris

  • Question about the Arrays utility

    Can I use the util.Arrays library to sort multi dimentional arrays? I dont see methods for that in the documentation, so I am guessing no.

    Yes it is. what kind of a comparetor would I need to set up for an int[][] array which I wish to sort in descending order according to the second dimension?
    Also, can you copy an array without using a for loop? I know that doing a = b (where a and b are both arrays of the same type) just passes a a referene to b.

  • Question about Object Arrays

    I am getting compile time error of missing ']' on the second line
        dvdData[] data = new dvdData[4];
        data[0] = new dvdData("Casablanca", "Warner Brothers", "1942");
        data[1] = new dvdData("Citizen Kane", "RKO Pictures", "1941");
        data[2] = new dvdData("Singin' in the Rain", "MGM", "1952");
        data[3] = new dvdData("The Wizard of Oz", "MGM", "1939");the object dvdData is being declared correctly with 3 strings as constructors, can anyone tell me why it is doing this? I will post complete code if nessecary.

    Hi,
    I don't see any problem - check out my code :-
    package project1;
    public class DVDData
        String str1 = null;
        String str2 = null;
        String str3 = null;
        public DVDData(String str1,String str2,String str3)
            this.str1=str1;
            this.str2=str2;
            this.str3=str3;
        public String toString()
            return str1 + " : " +    str2 + " : " + str3;
        public static void main(String[] args)
            DVDData[] data = new DVDData[4];
            data[0] = new DVDData("Casablanca", "Warner Brothers", "1942");
            data[1] = new DVDData("Citizen Kane", "RKO Pictures", "1941");
            data[2] = new DVDData("Singin' in the Rain", "MGM", "1952");
            data[3] = new DVDData("The Wizard of Oz", "MGM", "1939");
            System.out.println(data[0]);
            System.out.println(data[1]);
            System.out.println(data[2]);
            System.out.println(data[3]);
    }I get the correct output :-
    Casablanca : Warner Brothers : 1942
    Citizen Kane : RKO Pictures : 1941
    Singin' in the Rain : MGM : 1952
    The Wizard of Oz : MGM : 1939How are you comipling this ?
    Regards,
    Sandeep

  • Question about string constant in Hex display format

    how to get a plus of 2 string constant which is display in Hex display like attahced, for example I have string "28" and "5D" in Labview which has been in Hex format, the plus of this 2 string should be "85" in Hex. pls help on this, thanks
    Attachments:
    1.jpg ‏21 KB

    This'll work, too.  I'm afraid of casting types...
    Jm
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice
    Attachments:
    hex.png ‏2 KB
    hex.vi ‏7 KB

  • Question about String initialization~~~

    String a = "sss";
    String b = "sss";
    the result of a==b is true .
    String a = new String("sss");
    String b = new String("sss");
    however , the result of a==b is false .
    why? the operator "==" compares WHAT of two object ??
    thanks , ;[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    == compare the reference of the object
    String s1 = new String("sss") creates a new String object at location xxxxxx, while
    String s2 = new String("sss") creates a new String object at location yyyyy.
    therefor xxxxxxx != yyyyyyyy
    by location..the memory address
    String s3 = "sss"; // java create a new String object "sss" at location zzzzzzzz and assign the reference to s3
    String s4 = "sss"; // java assign the reference (location zzzzzzzz) to s4
    so s3 == s4....
    noticed only one String object is created...s3 and s4 holds the reference to the 1st String created..though it is not clearly shown in th ecode...it actually look something like this
    String temp = new String("sss");
    String s3 = temp;
    String s4 = temp;

Maybe you are looking for

  • Umstieg von Win auf mac mit cs6

    Ein freundliches Hallo an die Mitarbeiter von Adobe, vor etwa einem Jahr habe ich eine Win CS6 Studentenversion erworben und nutze sie täglich tatkräftig für meine Projekte. Inzwischen die Zeit reif für einen neuen Rechner. Dabei denke ich über einen

  • Creation of customer with contact person detials using BAPI

    Hi,  What is the standard BAPI for creating customer.  I need to create the customer with contact person details, what BAPI i can use for this, i was trying with 'BAPI_CUSTOMER_CREATEFROMDATA1' by populating structure personal data and copy reference

  • I don't know what I did but recently bookmarked is at the bottom of the bookmark page How do I get it back on top

    <i>Locking duplicate thread.<br>Please continue here: [[/questions/1020571]]</i> I somehow accidentally got the recently bookmarked on the bottom of the page. How do I get it back to the top of the bookmarks list? I tried the about;config method and

  • Workflow from BS

    Hi, I am invoking an existing workflow from a new Business Service. However, when I am using toggle points to debug the Script I noticed that the code after I invoke the workflow never gets executed. Is there a way I can debug the workflow as soon as

  • Records shown in Who's who search result

    Hi Experts I have one requirement regarding the search results of Who's who in employee search on ESS. My client want that in the search results of Who's Who, only active employees of the company will be displayed. In other words employees with inact