50264

java string with new operator and a literal

Suppose we create a String s as below

String s = new String("Java");

so this above declaration will create a new object as the new operator is encountered.

Suppose in the same program if we declare a new String s1 as below :

String s1 = "Java";

Will this create a new object or will it point to the old object with Java as it is already created with new operator above.

Answer1:

Well, the second line won't create a new object, because you've already used the same string constant in the first line - but s1 and s will still refer to different objects.

The reason the second line won't create a new object is that string constant are pooled - if you use the same string constant multiple times, they're all resolved to the same string. There still has to be a String object allocated at some point, of course - but there'll only be one object for all uses. For example, consider this code:

int x = 0; for (int i = 0; i < 1000000; i++) { String text = "Foo"; x += text.length(); }

This will not create a million strings - the value of text will be the same on every iteration of the loop, referring to the same object each time.

But if you deliberately create a new String, that will definitely create a new object - just based on the data in the existing one. So for example:

String a = new String("test"); String b = new String("test"); String x = "test"; String y = "test"; // Deliberately using == rather than equals, to check reference equality System.out.println(a == b); // false System.out.println(a == x); // false System.out.println(x == y); // true

Or to put it another way, the first four lines above are broadly equivalent to:

String literal = "test"; String a = new String(literal); String b = new String(literal); String x = literal; String y = literal;

Answer2:

String myString = new String("Java");

creates two objects.

String myString = "Java";

creates one object.

Answer3:

In order to create a new object we use <strong>new</strong> keyword, Object cannot be created without using new.

As per the declaration in the first instance a new Object is created but in the second instance you are only declaring a variable with a value.

So its not an Object.

Answer4:

<strong>String s1="foo";</strong> literal will be created in StringPool.

<strong>String s2="foo";</strong> this time it will check "foo" literal is already available in StringPool or not as now it exist so s2 will refer the same literal as s1.

<strong>String s3=new String("foo");</strong> "foo" literal will be created in StringPool first then through string arg constructor String Object will be created i.e "foo" in the heap due to object creation through new operator then s3 will refer it.

Answer5:

When you create a String with literal (e.g. String str = "Hello";) the Object is not created in Heap it will be available in StringPool only, however when you create a String using 'new' operator (e.g. String str = new String("Hello")) then the Object in StringPool is created along with one more object in Heap. So we are creating two objects unnecessarily. So string creating with literal is preferred way.

Recommend

  • Sysprocesses table - will it help me debug connection pooling issues?
  • Is it safe to use HttpClientFactory?
  • Grails - Getting data from a different datasource and saving it in my Grails database
  • Reference cursor gets lost in XMLType.createxml
  • Function arguments VBA
  • G1 Collector not doing full GC
  • Pass nested C++ vector as built-in style multi-dimensional array
  • Program crashes when run outside IDE
  • Google Player Game Service Error: Can't build the sample game
  • Subversion reverting resolved file
  • composer dependency stating in doesn't have php-xsl
  • Wrapping text in spinner android
  • Django model for a Postgres view
  • How to retrieve information from antrun back to maven?
  • Position: fixed nav does not stay fixed
  • Atlas images wrong size on iPad iOS 9
  • Meteor helpers not available in Angular template
  • Extracting HTML between tags
  • Repeat a vertical line on every page in Report Builder / SSRS
  • Android screen density dpi vs ppi
  • NetLogo BehaviorSpace - Measure runs using reporters
  • Bug in WPF DataGrid
  • Validaiting emails with Net.Mail MailAddress
  • MySQL WHERE-condition in procedure ignored
  • ActionScript 2 vs ActionScript 3 performance
  • Build own AppleScript numerical error handling
  • Web-crawler for facebook in python
  • Rearranging Cells in UITableView Bug & Saving Changes
  • trying to dynamically update Highchart column chart but series undefined
  • Benchmarking RAM performance - UWP and C#
  • Acquiring multiple attributes from .xml file in c#
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • How can I remove ASP.NET Designer.cs files?
  • Sorting a 2D array using the second column C++
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • UserPrincipal.Current returns apppool on IIS