How Can a String Be Initialized Using " "

How can a string be initialized using ?

Java String is Special

The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the call stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces.

For performance reason, Java's String is designed to be in between a primitive and a class.

For example

String s1 = "Hello";              // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object

Sample Image

Note: String literals are stored in a common pool. This facilitates the sharing of storage for strings with the same contents to conserve storage. String objects allocated via the new operator are stored in the heap, and there is no sharing of storage for the same contents.

String initialization in Java

What is the difference between 1. and 2.? If I consider str1 as a pointer variable, what it stores is a particular memory address that is never used by the JVM or OS?

If these are fields in a class, there's no difference, since the default value for a field of a reference type (such as String) is already null.

If these are local variables (i.e. variables declared in a method) str1 will not be initialized to anything, while str2 will be initialized to null. The difference here is that a local variable can't be used until it has been initialized, so (as you seem to have discovered) you can't print str1, but you can print str2.

Is there a difference between 4. and 5.?

No, not semantically. You'll get slightly different byte code though.

When I print str1 and str2 directly by System.out.println(str1) and System.out.println(str2), for str1, I can't even pass the compilation. For str2, compilation is OK and I get "null" and the output in the console window. Why?

This seems to indicate that these are local variables. Local variables needs to be initialized before they are used.

I would like to know more about "null". Since str2 (reference variable) is like a pointer variable, there should be something (0/1 bits) in it (in the memory occupied by this pointer variable). As it is initialized as null, is it all-0-bits or the bytecode of null is all-zero?

This has already been asked (and answered):

  • How is null represented in memory in java
  • What exactly is null in Java memory

Another question is that if I call the method toString() on str2 by str2.toString(), I got a NullPointer Error at runtime. So it is JVM that checks if the reference variable is null?

Yes.

How can JVM know that it is null? JVM checks the bits in str2?

Yes.

Java: how to initialize String[]?

You need to initialize errorSoon, as indicated by the error message, you have only declared it.

String[] errorSoon;                   // <--declared statement
String[] errorSoon = new String[100]; // <--initialized statement

You need to initialize the array so it can allocate the correct memory storage for the String elements before you can start setting the index.

If you only declare the array (as you did) there is no memory allocated for the String elements, but only a reference handle to errorSoon, and will throw an error when you try to initialize a variable at any index.

As a side note, you could also initialize the String array inside braces, { } as so,

String[] errorSoon = {"Hello", "World"};

which is equivalent to

String[] errorSoon = new String[2];
errorSoon[0] = "Hello";
errorSoon[1] = "World";

Is it necessary to initialize a string in c++?

If by "string", you mean char*, then yes, they should be (even must be, or at least is it strongly recommended) initialized, like any other variable by the way.

If by "string", you mean std::string, then they are initialized to empty string ("") automatically by default (default constructor).

std::string str;
std::cout << str; // will print nothing (empty string) for sure
char* str2;
std::cout << str2; // will most likely print garbage or even crash

Why can you initialize a string pointer as a string literal, but not as an array?

Why can you initialize a string pointer as a string literal, but not as an array?

Because {'a', 'b', 'c', '\0'} is not an array; it is a list of values to put in the thing being initialized.

The syntax {'a', 'b', 'c', '\0'} does not stand for an array in C. People see it being used to initialize arrays, but, when used in that way, it is just a list of values. It could also be used to initialize a structure, because it is just listing values to put into the thing being initialized. It is not, by itself, an array.

In char *word2 = {'a', 'b', 'c', '\0'};, it does not make sense to initialize word2 with the values 'a', 'b', 'c', and '\0'. It is just one pointer and should be initialized with one value. Giving a list of four values to initialize one thing does not make sense.

In char *word2 = "abc";, "abc" is not a list of values. It is a string literal. A string literal defines a static array that is filled with the characters of the string. And then the string literal is automatically converted to a pointer to its first element, and it is this pointer that is used to initialize word2.

So char *word2 = "abc"; does two things: The string literal defines an array, and the initialization sets word2 to point to the first element of that array. In contrast, in char *word2 = {'a', 'b', 'c', '\0'};, there is nothing to define an array; the list of values is just a list of values.

Comparing this to array initializations, in char word2[] = {'a', 'b', 'c', '\0'};, the array is initialized with a list of values, which is fine. However, in char word1[] = "abc";, something special happens. C 2018 6.7.9 14 says we can initialize an array of character type with a string literal, and the characters of the string will be used to initialize the elements of the array.

When do I need to initialize a String?

It's because monthString is a local variable and there's a path you can take where it's not initialized and you're still trying to use it.

That's just not allowed in Java. I think the reason is it's an easy way for Java to prevent you from making a mistake. It forces you to acknowledge that you haven't set monthString to anything yet but you're still trying to use it. 9 times out of 10, that's an mistake on the developers part, so Java won't let you do it.

One way to fix it is to set monthString to something in your default:. You can also initialize it to null, as @Eran said.

A question about initializing a newly created empty string in Java

this is the object being constructed. the empty string represented by the literal “” is an already existing string object, which is separate from the object being constructed. value is a private field on String. The code assigns the pre-existing empty string value to the new object’s value. There is no circularity here.

It is a bit weird that an object can see another object’s private members, this is allowed inside a class definition as long as the other object has the same type. Usually you see this in equals methods.

Literal syntax for String is coded into the compiler. Different JVM languages allow different literal syntaxes for different kinds of objects, the syntax is part of the language. Groovy, Clojure, and Scala all have very different literal syntaxes for various things. Rules for literals are spelled out in https://docs.oracle.com/javase/specs/jls/se16/html/jls-3.html#jls-3.10.5

How to initialize a string?

Java can't guarantee that car will ever become initialized. You don't have a guaranteed case (else) in your if statement that assigns car.

Initialize it to some value, such as an empty string.

String car = "";

Does a class string always gets initialized to empty?

In both cases, the default string constructor will be called. The default constructor for the std::string class will always initialize it to an empty string.



Related Topics



Leave a reply



Submit