Initialize a string to null or ""

String s;
When we declare a variable with type String, we need to initialize it. Or we will get compile error "variable s might not have been initialized"
My question is which way we should do?
1) String s = null;
2) String s = "";
Or it really depends on our application needs?

In Java, the null reference is a value that indicates that the reference does not point to an object. You have to decide what semantics to give that value. If you want null to indicate that the value hasn't been set, you need an object to indicate that the value has been set to "blank".
In the case of a String, you could make a special String object:
public final BLANK_VALUE = new String();
and then use == to test for this object. Often, however, the empty String "" is used to indicate the value has been set to "blank".
But let me also state that if you are only trying to avoid "variable might not have been initialized" then you are basically not coding the right way
e.g
String s;
if (true)
s="VOW";
}this way you would get the error but then in this case rather than initializing and then putting in another value later a better practice would be
String s;
if (true)
s="VOW";
else
s="HELP"; //now you wouldnot get the error.

Similar Messages

  • JDBC Receiver does not convert empty string to NULL

    Hello experts,
    I am facing a problem with an INSERT statement to ORACLE DB where some of the fields are empty, for example:
    - <STATEMENT_VLP_CONT_DETAILS>
    - <TABLE_VLP_CONT_DETAILS ACTION="INSERT">
      <TABLE>VLP_CONT_DETAILS</TABLE>
    - <ACCESS>
      <VLP_HDR_ID>43</VLP_HDR_ID>
      <VLP_CONT_LINE_ID>1</VLP_CONT_LINE_ID>
      <QUANTITY>1</QUANTITY>
      <OWNER>CBHU</OWNER>
      <SERIAL_NO>3372739</SERIAL_NO>
      <CONT_ISO_CODE>2300</CONT_ISO_CODE>
      <WEIGHT>6.44</WEIGHT>
      <POL>ILASH</POL>
      <POD>FRFOS</POD>
      <FD>FRFOS</FD>
      <OPER_CODE>COS</OPER_CODE>
      <CUR_STOW_LOC>150102</CUR_STOW_LOC>
      <PRV_STOW_LOC />
      <HAZARDOUS>N</HAZARDOUS>
    In the JDBC Receiver comm channel I selected: Interpretation of Empty String Values = NULL Value.
    It seems the empty strings are not converted to NULL values as can be seen in the reflected SQL statement in RWB:
    INSERT INTO  VLP_CONT_DETAILS (VLP_HDR_ID, VLP_CONT_LINE_ID, QUANTITY, OWNER, SERIAL_NO, CONT_ISO_CODE, WEIGHT, POL, POD, FD, OPER_CODE, CUR_STOW_LOC, PRV_STOW_LOC, HAZARDOUS, EMPTY, REFER, OOG, HAZARD_IMDG, TEMP_SET, TEMP_MIN, TEMP_MAX, FRONT_OVL, REAR_OVL, RIGHT_OVW, LEFT_OVW, OVERHEIGHT, COMMODITY, BOOKING_REF, ALLOTMENT, YARD_LOC, LD_SEQ_CRANEID, LD_SEQ_NUMBER, LD_STATUS, STACKABLE, OPT_PORT_CODE1, OPT_PORT_CODE2, OPT_PORT_CODE3) VALUES (44, 1, 1, CBHU, 3372739 , 2300,  6.44, ILASH, FRFOS, FRFOS, COS,   150102,         , N, N, N, N,      ,      ,      ,      ,    ,    ,    ,    ,    ,     ,             ,    ,           ,    ,    0,    64, N,      ,      ,      )
    So, I am getting the following error:
    Could not execute statement for table/stored proc. "VLP_CONT_DETAILS" (structure "STATEMENT_VLP_CONT_DETAILS") due to java.sql.SQLException: ORA-00936: missing expression
    Help would be appreciated.

    Hi Effi,
    There is a mismatch in the field and thier value.
    Here field id 37
    VLP_HDR_ID, VLP_CONT_LINE_ID, QUANTITY, OWNER, SERIAL_NO, CONT_ISO_CODE, WEIGHT, POL, POD, FD, OPER_CODE, CUR_STOW_LOC, PRV_STOW_LOC, HAZARDOUS, EMPTY, REFER, OOG, HAZARD_IMDG, TEMP_SET, TEMP_MIN, TEMP_MAX, FRONT_OVL, REAR_OVL, RIGHT_OVW, LEFT_OVW, OVERHEIGHT, COMMODITY, BOOKING_REF, ALLOTMENT, YARD_LOC, LD_SEQ_CRANEID, LD_SEQ_NUMBER, LD_STATUS, STACKABLE, OPT_PORT_CODE1, OPT_PORT_CODE2, OPT_PORT_CODE3
    And value is 35
    44, 1, 1, CBHU, 3372739 , 2300, 6.44, ILASH, FRFOS, FRFOS, COS, 150102, , N, N, N, N, , , , , , , , , , , , , , , 0, 64, N, , ,
    Give empty values for nuil fields so that they can be made NULL by jdbc adapter
    Regards
    Suraj

  • String value null in the XI mapping

    Hi folks,
    is it possible to create in the XI mapping for a string the value <b>null</b> and not an empty string like "". It is necessarily for the Webservice over the soap adapter.
    Thanks for answers
    Johann

    Johann,
    Make sure the min. occurance of the target node is 0. If you do not map the field it will not throw an error. It will throw an error only if the min occurance is equal to or greater than 1.
    @Shabz,
    I guess Mapping to a string constant "null" is not the same as null. Pls correct me if I am wrong.
    Regards,
    Jai Shankr

  • How to check empty string and null? Assign same value to multiple variables

    Hi,
    1.
    How do I check for empty string and null?
    in_value IN VARCHAR2
    2. Also how do I assign same value to multiple variables?
    var_one NUMBER := 0;
    var_two NUMBER := 0;
    var_one := var_two := 0; --- Gives an error
    Thanks

    MichaelS wrote:
    Not always: Beware of CHAR's:
    Bug 727361: ZERO-LENGTH STRING DOES NOT RETURN NULL WHEN USED WITH CHAR DATA TYPE IN PL/SQL:
    SQL> declare
      2    l_str1   char (10) := '';
      3    l_str2   char (10) := null;
      4  begin
      5  
      6    if l_str1 is null
      7    then
      8      dbms_output.put_line ('oh STR1 is null');
      9    elsif l_str1 is not null
    10    then
    11      dbms_output.put_line ('oh STR1 is NOT null');
    12    end if;
    13  
    14    if l_str2 is null
    15    then
    16      dbms_output.put_line ('oh STR2 is null');
    17    elsif l_str2 is not null
    18    then
    19      dbms_output.put_line ('oh STR2 is NOT null');
    20    end if;
    21  end;
    22  /
    oh STR1 is NOT null
    oh STR2 is null
    PL/SQL procedure successfully completed.
    SQL> alter session set events '10932 trace name context forever, level 16384';
    Session altered.
    SQL> declare
      2    l_str1   char (10) := '';
      3    l_str2   char (10) := null;
      4  begin
      5  
      6    if l_str1 is null
      7    then
      8      dbms_output.put_line ('oh STR1 is null');
      9    elsif l_str1 is not null
    10    then
    11      dbms_output.put_line ('oh STR1 is NOT null');
    12    end if;
    13  
    14    if l_str2 is null
    15    then
    16      dbms_output.put_line ('oh STR2 is null');
    17    elsif l_str2 is not null
    18    then
    19      dbms_output.put_line ('oh STR2 is NOT null');
    20    end if;
    21  end;
    22  /
    oh STR1 is null
    oh STR2 is null
    PL/SQL procedure successfully completed.
    SQL> SY.

  • Empty string and NULL value

    Hi,
    Does oracle treat empty string as NULL.
    If it is so,Can we force db to treat both as different things.
    Thanx

    11g.DBA wrote:
    Hi,
    Does oracle treat empty string as NULL.Yes.
    If it is so,Can we force db to treat both as different things.No.
    Please read in SQL Reference:
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements005.htm#SQLRF3003

  • ORACLE treats empty Strings as NULL, Any workaround?

    Hi,
    ORACLE treats empty Strings as NULL.
    I am writing, rather modifying Java code to make it work with both SQLServer and Oracle. Since our code is already working for SQLServer, now I have the problem in porting to Oracle wherever I have empty strings. I used to insert empty strings into coulumns in SQLServers, the same SQLs give errors in SQL Server.
    Any workaround on the DB end or in JDBC for this?
    Thanks in advance,
    Suresh
    [email protected]

    jschell wrote:
    nichele wrote:
    jwenting wrote:
    If NULL really is different in your context from an empty string you're going to have to define some sequence of characters as indicating an empty string.yes, this is what i need to implement.Sounds like a flawed design then.
    I'm wondering what's the best approach in order to avoid to change all my application isolating this behavior somewhere (wrapping the jdbc driver for instance).That doesn't make much sense to me. You should already have a database layer. You change the database layer. If you don't have a database layer then that means you have another design flaw. And in that case I would really not be the one that needs to maintain that code base.I thought a bit about the value of your answer...but i didn't find it ....sorry but i don't like who replies on forum just to say bad design/bad choice etc...if you have any kind of suggestion you are welcome, otherwise you can spend your time in doing something else instead of reply to this thread.

  • What is the difference between string != null and null !=string ?

    Hi,
    what is the difference between string != null and null != string ?
    which is the best option ?
    Thanks
    user8729783

    Like you've presented it, nothing.  There is no difference and neither is the "better option".

  • Set whole Query string to null or ""

    Good morning!
    Is there a way to set the whole query string to null or ""?
    so that request.getQueryString() = "" ?
    I've been trying something like this
    String body = "";
    request.setAttribute(???, body);
    what would go in the ???
    thanks,
    Alex

    Thats not good. I'm having a problem when the session times out. When a person times out , the system forwards them to the login screen. When they login, they are authenticated by siteminder and the last action they requested is sent (whatever is in the querystring) The querystring tries to go to our controllerservlet (in the querystring), and bypasses the login servlet! I figured if you set toe querystring to "", it would have to go to the loginservlet

  • Mapbuilder.jar: cannot initialize Look and Feel: null

    When I try to start mapbuilder using java -jar mapbuilder.jar it crashes:
    cannot initialize look and feel: null
    error: java.lang.NullPointerException
    Running under 64 bit Linux in a VNC session.
    Anyone else seen this?
    JAVA_HOME is set.

    Try to use a java32 bit version (minimum jre 1.5 or later) and to give the complete path, I don't know a lot of Linux.
    Cheers
    Nico
    Edited by: gerardnico on Aug 26, 2009 10:26 PM Add jre 1.5 or later

  • How to declare and initialize a STRING ARRAY (assign strings to array elements)

    How to declare and initialize a STRING ARRAY (assign desired strings to elements of an array, for example "abc", "def", "ghi", "jkl", etc.) in LabVIEW? I saw a "string array" block in help, but could not find it in the function palette. Does a spreadsheet string have to be in a file (or can it be in a string constant block)? Thank you.

    Hi,
    you can do it in several ways:
    1. Direct way: Create string array control on front panel and type strings in its elements
    2. Programmatically 1: Create string array indicator (or local variable of control), right click on it in block diagram, select "Create constant" from drop down menu. The array constant will appear. Now type values in this constant's strings
    3. Programmatically 1: Use "Build array", "Replace array subset", "Insert into array" or "Initialize array" functions from "Functions->Array" palette.
    And of course you can combine all of these methods.
    Good luck.
    Oleg Chutko.

  • Possible to initialize a String as empty?

    So, in the following code i initialize result with null because i want it to be empty. However when i run the driver for the method, i get the first proper character followed by null for output. For instance "snull" is my output. Any ideas why this is occuring? public class Cipher {
    String words;
    String result;
    String enc;
    String ke;
    String mes;     
    public Cipher(String en, String k, String me) {
         words = null;
         result = null;
         enc = en;
         ke = k;
         mes = me;
    public String encipher(String encode, String key, String message) {
    if (message.length() > 0 && message.charAt(0) == encode.charAt(0)) {
         String temp;
         temp = (key.charAt(0) + this.encipher(encode, key, message.substring(1, message.length())));
         this.result = temp;
         else if(message.length() > 0 && encode.length() > 1 && key.length() > 1) {
         this.encipher(encode.substring(1, encode.length()), key.substring(1, key.length()), message);
         return this.result;
    }

    String s = ""; // empty string

  • Distinguishing between empty string and null values

    hi all,
    I am using an ODBC connection to connect my java app to database using JDBCODBC driver. I have 2 columns 'aColumn' and 'bColumn' in my table, both allow null values. I have one row in it, which has null value in aColumn and empty string in bColumn. I retrieve this row's data and assign it to 2 columns : 'aColumnVar' and 'bColumnVar' respectively. I find out that both 'aColumnVar' and 'bColumnVar' variables has null values (although bColumnVar should has an empty string as its value). Now my ODBC connection Data Source has the option "Use ANSI nulls, paddings, and warnings" ON. I turn it off and try again. This time both 'aColumnVar' and 'bColumnVar' variables has empty string as values (although aColumnVar should has null as its value).
    How can I make sure that i can get the data exactly as it is in the database in my variables?
    Thanks

    there is a wasNull() method on ResultSet. After you
    have obtained the value of a column e.g. by calling a
    method like getString you can call wasNull and if it
    returns true then the value on the database is null.
    Check the java docs, it might explain it better
    http://java.sun.com/j2se/1.4.1/docs/api/java/sql/Result
    et.html#wasNull()I am using MS SQL Server 7.0 under Windows NT 4.0 with JDK 1.2. My ODBC connection Data Source has to have the option "Use ANSI nulls, paddings, and warnings" ON.
    I try the wasNull() method but it is doing the same thing i.e. telling me that a column is null when in database it is null (right); and a column is null when in database it is an empty string (wrong). I suspect it is something to do with the JDBC-ODBC driver I am using.

  • Is empty string and Null same?

    create table x
    (empid number);
    Table created.
    insert into x values ('');
    1 row created.
    insert into x values (null);
    1 row created.
    SQL> set null <<>>
    SQL> select * from x;
         EMPID
    <<>>
    <<>>So i can safely change an Insert statement like
    insert into x values ('');to
    insert into x values (null);Right?

    michaels2 wrote:
    char pads with spaces to the length of the data itemdon't think so - at least not on my 11.2.0.1.0Good. Oracle finally fixed it. Before 11.2 it was pretty much as ajallen noted:
    Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production
    PL/SQL Release 11.1.0.6.0 - Production
    CORE    11.1.0.6.0      Production
    TNS for 32-bit Windows: Version 11.1.0.6.0 - Production
    NLSRTL Version 11.1.0.6.0 - Production
    SET SERVEROUTPUT ON
    DECLARE
        flag CHAR(2);
        PROCEDURE check_null (p_flag IN CHAR)
        IS
        BEGIN
          IF p_flag = '  '
            THEN
              dbms_output.put_line ('flag is equal to ''  ''');
            ELSIF p_flag IS NULL
              THEN
                dbms_output.put_line ('flag is null');
            ELSE
              dbms_output.put_line ('other');
          END IF;
        END;
    BEGIN
        flag := '';
        check_null (flag);
        flag := NULL;
        check_null (flag);
    END;
    flag is equal to '  '
    flag is null
    PL/SQL procedure successfully completed.
    alter session set events '10932 trace name context forever, level 16384';
    DECLARE
        flag CHAR(2);
        PROCEDURE check_null (p_flag IN CHAR)
        IS
        BEGIN
          IF p_flag = '  '
            THEN
              dbms_output.put_line ('flag is equal to ''  ''');
            ELSIF p_flag IS NULL
              THEN
                dbms_output.put_line ('flag is null');
            ELSE
              dbms_output.put_line ('other');
          END IF;
        END;
    BEGIN
        flag := '';
        check_null (flag);
        flag := NULL;
        check_null (flag);
    END;
    flag is null
    flag is null
    PL/SQL procedure successfully completed.
    SQL>
    Bug 727361: ZERO-LENGTH STRING DOES NOT RETURN NULL WHEN USED WITH CHAR DATA TYPE IN PL/SQL
    SY.

  • Varchar2, empty strings and NULL

    Hi all,
    When inserting an empty string into a column of type varchar2 - is a NULL value stored in the column by the database? I've seen conflicting reports, and I know that the SQL 1992 spec specifies that empty strings not be treated as a NULL value, but that Oracle has traditionally treated zero length strings stored in a varchar2 column as NULL.
    So, is there a way to store an empty string in a varchar2 column as an empty string and not a NULL value?
    TIA,
    Seth

    It can be even more complicated or annoying than NULL not equal to ASCII NULL.
    example:
    create table test_null
    (fld1 varchar2(10),
    fld2 varchar2(10),
    fld3 varchar2(20));
    insert into test_null values (chr(0),null, 'chr(0) and null');
    insert into test_null values (null, null, 'null and null');
    insert into test_null values ('', chr(0), ''''' and chr(0)');
    insert into test_null values ('', null, ''''' and null');
    select * from test_null;
    FLD1       FLD2       FLD3
                          chr(0) and null
                          null and null
                          '' and chr(0)
                          '' and null
      1  DECLARE
      2  BEGIN
      3   for c1 in (select fld1, fld2, fld3 from test_null) loop
      4      if c1.fld1 = c1.fld2 then
      5         dbms_output.put_line(c1.fld3||' Are equal'||
      6                '  Length fld1 = '||to_char(length(c1.fld1))||
      7                ' Length fld2 = '||to_char(length(c1.fld2)));
      8      else
      9         dbms_output.put_line(c1.fld3||' Are NOT equal'||
    10                '  Length fld1 = '||to_char(length(c1.fld1))||
    11                ' Length fld2 = '||to_char(length(c1.fld2)));
    12      end if;
    13      dbms_output.put_line(' ');
    14   end loop;
    15*  END;
    SQL> /
    chr(0) and null Are NOT equal  Length fld1 = 1 Length fld2 =
    null and null Are NOT equal  Length fld1 =  Length fld2 =
    '' and chr(0) Are NOT equal  Length fld1 =  Length fld2 = 1
    '' and null Are NOT equal  Length fld1 =  Length fld2 =
    PL/SQL procedure successfully completed.

  • Report is showing "null" string for null values.

    hi ,
    I am new to BI Publisher and creating a report in BI Publisher. In the result set for null values, report is printing as "null". I checked the query , it gives blank (empty value) data for null values. But in report it is coming as "null" value (string "null"). I require to show the report as blank data for null values. Can you please help me to find solution for this ?.
    Thank you very much in advance.
    Regards
    Gayathri.

    it shouldnt happen like that
    try these
    <?xdoxslt:ifelse(ADDRESS3!='',ADDRESS3,'')?>
    or
    <?xdoxslt:ifelse(ADDRESS3!='null',ADDRESS3,'')?>
    if those didnt work send me your template and xml to my email i can try that at my side .
    Email [email protected]

Maybe you are looking for

  • Use of Logical Database in function module

    Hello Experts, Is there a way of using logical database and Get enent inside a function module. I am trying to create a RFC for HR module and need this badly. Any help would be highly appriciated. Thanks, Gregory fernando

  • Links in mouseover images to change with the images

    I have created a page with mouseovers on page headings that affect the main page image -- mouseover image 1 and the main image changes, mouseover image 2 and the main image changes again etc. I have set the mouseovers not to revert on mouseout, so th

  • 2012 MacBook Pro running extremely slowly with constant color wheel

    I have a 2012 MacBrook Pro and yesterday it randomly began to function extremely slowly and has almost a constant color wheel. This does not just happen when on the internet, but happens with any function of my computer. Even the typing is lagging. T

  • Mi router WRT54GC isn't working - Please urgent help

    Hi all, I've bought this router on February and suddenly it has left working. I've tried to upgrade the firmware but the power led is now in orange (not blinking)...... Did I broke the router? How can I fix it? Thanks for you help! Killi

  • Software Inventory - Unknown Install Location

    Hello, Running the SCCM Asset Intelligence report 'Installed Software on a specific computer (Report 02E)' shows a number of software titles with 'Unknown' in the 'Installed Location' column. I have asked the user of a particular device to check a sa