• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

What is the difference between declaring a String variable and assigning a blank value to a variable

 
Greenhorn
Posts: 18
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is the difference between

just declaring a variable

assigning variable nothing



according to my knowledge the latter one assign null
but i didn't get the former one (String j)
 
Greenhorn
Posts: 1
  • Likes 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can use jshell to do some quick tests, when you want to test some basic concepts in Java. If you don't initialise a string, it will be null by default. The "" empty string isn't equal to null. They are totally different.

jshell> String j;
j ==> null

jshell> System.out.println(j);
null

jshell> String k="";
k ==> ""

jshell> Objects.equals(j,k);
$5 ==> false
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Likes 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String j;

this gives you a label "j" you could stick onto a box, but no actual box.  If you say "hey, tell me about j", you get an error because there is nothing there.

String j = ""

This gives you a label "j" and a box to stick it on, but the box is empty.  if you say "hey, tell me about j", you are told "this is an empty box"

String j = "fred"

This gives you a label "j", and a box that has "fred" inside it.  if you say "hey, tell me about j", you are told "this is a box with 'fred' inside it".

 
Marshal
Posts: 79151
377
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch

Steven Toxoto wrote:You can use jshell to do some quick tests . . . If you don't initialise a string, it will be null by default.

JShell is useful, very useful, but I can't remember whether plain simple variables are treated as fields would be or as local variables would be. I think it treats them like fields, in which case all uninitialised variables of reference type default to null.
Uninitialised local variables of any type are treated as undefined and cannot be used until they have been definitely assigned to. Otherwise the compiler will block their use.
 
Rancher
Posts: 1093
29
Netbeans IDE Oracle MySQL Database Tomcat Server C++ Java
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
my understanding is that

gives you a reference variable ready to be pointed to a container; but references NULL to start.

give you a reference variable pointing to a container that is empty.  since Stings in Java are immutable, may not be changed, then if you consequently say:

in the first, the reference variable's reference would be set to the string "hello world".  in the second that same would happen, but also that empty container would be orphaned and eligible for garbage collection.  in the first, there is no container to be orphaned or collected.

Pratik Kandalgaonkar wrote:What is the difference between

just declaring a variable

assigning variable nothing



according to my knowledge the latter one assign null
but i didn't get the former one (String j)

 
Pratik Kandalgaonkar
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for all the replies they are relly helpful!!
i'll look into JShell, thanks for the recommendation
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Les Morgan wrote:my understanding is that

gives you a reference variable ready to be pointed to a container; but references NULL to start.


True only if the declaration is an instance variable. Local variables do not have a default initial value, not even null.
 
Saloon Keeper
Posts: 27752
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nitpick: You can't "reference" null. Null means there there is literally nothing to reference at all. It's a value, but not a reference, unlike actual objects where the value you assign is a reference to that object.


Junilu Lacar wrote:
True only if the declaration is an instance variable. Local variables do not have a default initial value, not even null.


I've seen that assertion, but I don't believe it. That was a VERY big problem in C - local variables would have a value equal to whatever garbage was currently on the stack, which affected repeatability and thus reliability. In Java, as far as I am aware, every variable is initialized to either null (if an object reference) or zero if a numeric/character variable. Java, after all, was designed to remedy as many of the common C/C++ faults as it could.

On the other hand, I'm fairly sure that the present-day Java compilers are all smart enough to detect variables that were never given a value before being read and scream bloody murder about it. As in, refuse to compile. So you could claim that there's no default initial value, but since such a situation is not valid code, there's more than just variables not getting assigned at that point.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Chapter 16 of the JLS goes to some length explaining "definitely assigned" and "definitely unassigned".  They also mention a "blank" local variable.

https://docs.oracle.com/javase/specs/jls/se14/html/jls-16.html

 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Holloway wrote:. . . That was a VERY big problem in C - local variables would have a value equal to whatever garbage was currently on the stack . . . the present-day Java compilers are all smart enough to detect variables that were never given a value before being read and scream bloody murder about it. . . . .

I am 99% sure that is the explanation of why newly‑declared local variables must be definitely assigned to before they can be used, otherwise they fail to compile. It's all in the JLS link Junilu gave you:-

That JLS section wrote:. . . For every access of a local variable or blank final field x, x must be definitely assigned before the access, or a compile-time error occurs. . . .

That has been the situation for as long as I can remember.
 
Tim Holloway
Saloon Keeper
Posts: 27752
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:That has been the situation for as long as I can remember.


It has been long enough that I don't remember noticing it as a new thing. But I do have a recollection of a time where the pre-initialisation of everything was a major selling point for Java.

We're used to very capable compilers these days with extensive optimisations, JIT code generation and advanced analysis. But for many decades, if a compiler could take syntactically valid code and convert it into something executable that was considered to be enough. IBM did an optimising version of their PL/I language compiler back in the 1970s and charged extra for it.

Realise that for many, many years, even the largest systems had perhaps 16 KILObytes of RAM available for a compiler to run in and 5 MEGAbyte disks were not uncommon. An IBM 3330 disk drive had 200MB capacity and that was top-of-the-line back when I was in school and couldn't get access to PL/I because it required 1MB of DASD space and unless I could gather up enough people to demand a course in PL/1 they couldn't spare that much.

Today, I can run PL/I under an IBM System/370 emulator at the same time I run it under a PR1ME computer emulator in a back corner of my Linux box.

In short, early compilers ran as very linear processes, loading an overlay into RAM to handle one particular phase such as lexical scanning or parsing, then replacing that overlay with another one and typically there'd be 5 or more phases.

The first SERIOUSLY optimising compiler I ever saw was IBM's Pascal/VS somewhere around the early 1980s. Linux burst forth in the 1990s and adopted the gcc compiler, which was not bound by the old hardware constraints and had serious optimisation built into it. Java was also showing up then, but the early generations spent a lot of time on its security and repeatability features. Detailed code analysis had to wait for the basics to settle in - and the even more powerful post-millenial processors.

In short, as I said, I think that Java has always ensured definite values for all variables. It's just that these days it ensures them at compile time, rather than by simply zapping the stack frame to all zeroes.


 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To be honest, I don't see how any of that matters. It's like arguing with someone who says "You need gas in your tank if you want to start your car" by saying "Technically, there's always a residual amount of gas in the tank because so and so reason" which might be literally correct but still the car won't start because essentially, there is no gas.
 
Tim Holloway
Saloon Keeper
Posts: 27752
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think most people would see a difference between "won't run reliably", "runs predictably" and "won't run because it won't even compile".
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
On my own it's more about memory utilization;
1- Declaring String j;  creates a reference variable in the stack that points to null (nothing)
2- Declaring String j= "" ; creates a reference variable j in the stack, that points to an object with value ""   from the string pool, if not exist it will be created and added to the string pool.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
BT: welcome to the Ranch

As we said before, the first declaration has different behaviour depending on where it is declared.
 
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From my experience of you don't initialize the string and later on you want to use it , the compiler(with Eclipse) show an error and ask you to initialized it and will offer you a fix and your string will becomes : String j = null;
or you can do it yourself like this String  j= "";
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Fred Masen wrote:. . . you don't initialize the string and later on you want to use it , the compiler(with Eclipse) show an error . . .

In Java®, that applies to local variables, not usually to fields or method parameters. Non‑final fields have default values, so a field would default to null.

String j = null;
. . . String  j= "";

You do realise those two initialisations are very different from each other?
 
Fred Masen
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yep
String j = ";  has a length 0
String j = null; is NULL

I usually initialized myself that way I avoid all the crappy NullPointerException errors
but if I let Eclipse fix it it will initialized as NULL then if you try to use and work with the String like equals etc.. it will throw  a NullPointerException error because I believe it has not yet been allocated space in memory.
But if I don't to manipulate the String and just want to use it that way :
String name = null;
Scanner keyboard = new Scanner(System.in);
System.out.println(" What is your name ? ");
name = keyboard.nextLine();
Then NULL is perfectly fine to use it.

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Declaring a string variable may or may not be initialized,but assigning a blank value to a variable is initialized and can be modified later.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When declaring a string like thisString = ""; you initialize it. You will find that you will need to initialize the string if you are planning to assign it a value within a loop or if statement later. Whereas simply declaring it like thisString will not allow you to re-assign it within that context.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
BJ BV: welcome to the Ranch

Sorry for the wrong initials last week.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please explain more, BJ BV. What you said probably applies only to local variables, but a local vaiable can be definitely assigned to if every path of execution includes assignment before use. It will be necessary for an if to be accompanied by a plain else, forr example.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For java and scala. Declaration is we are defining the fields but they are abstract, which means they do not have any value or implement attached to them. This in turn means that no storage is provided to that variable and currently it is a logical entity. However when a variable is defined in the later case, storage is provided to it and now it becomes a physical entity
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
VSK: welcome to the Ranch

Is what you said correct for Scala? I am afraid it isn't correct for Java®.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thé answer is in your question. It is declaration/definition vs. assignment.

it’s:

char *myString;

vs.

myString=“whatever”;

The first statement declares the existence of the variable myString. The second statement assigns it a value. The first statement must happen before the second, though the time span between the two can be shortened a tad:

char *myString=“whatever”;
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Fred Masen wrote:Yep
String j = ";  has a length 0
String j = null; is NULL

I usually initialized myself that way I avoid all the crappy NullPointerException errors

The error is that the memory has not been filled with a “real” reference to an object. The exception is the result of that error.

. . . it will throw  a NullPointerException . . . it has not yet been allocated space in memory.

No, the space for a field or an array element is allocated immediately.

. . .Then NULL is perfectly fine to use it.

Not NULL, please, but null.
Note I added code tags when I quoted your post, and removed some whitespace. Doesn't it look better now, but please use spaces for indenting, not tabs.
I am afraid that isn't the best way to declare an initialise that variable. It is better to declare it as late as possible, like this:-You didn't use the null anywhere. All you did was replace it with a “real” reference to an object.
If you are declaring local variables, it is probably better to use var:-
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Declaring a String variable means specifying its type and name without assigning a value, while assigning a blank value initializes it with an empty string.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Eden Wheeler - Welcome to the Ranch!
 
reply
    Bookmark Topic Watch Topic
  • New Topic