String object creations in java - java

Q.1. How many Objectes are created in the below example?
ex.
String s1="isaq";
String s2="isaq";
String s3="isaq";
if answer is 1 or 3 ,explain me why?

When we try to create a String Object JVM first checks the String constant pool,if string doesn't exist in the pool then it will creates a new String Object isaq and reference maintained in the pool.The Variable S1 also refer the same String Object.
String s1="isaq";
Above statement create one String Object in String pool.
Now you are doing the
String s2="isaq";
Above statement won't create any String Object in String pool and S2 refers the same object as S1.Because JVM will check the Pool and it found String object is already present.
To Validate it you can compare String reference using equality operator(==). to check whether they are referring the same String Object or not.

Related

How many String objects'll be created and what would be the string values of those objects? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How many java objects generated by this code? and why?
I am very confused in the following
String s1 = new String("Java");
String s2 = new String("Java");
How many objects are created here?
String s1 = new String("Java");
String s2 = new String("Ruby");
How many objects are created here?
String s1 = new String("Java");
String s2 = "Java";
How many objects are created here?
String s1 = "Java";
String s2 = "Java";
How many objects are created here?
Your first part of code:
2 objects are created.
If "Java" is not present in String Pool, a string is created and added there.
Your 2nd part of code:
2 objects are created and if neither "Java" nor "Ruby" are present in String Pool, both strings are created and added to it.
Your 3rd part of code:
one object created. and same condition is executed to add to String Pool.
Your 4th part of code:
Only one object created, if "Java" not present in String Pool. else no new object created.
String s1 = new String("Java");
String s2 = new String("Java");
It will create 2 objects in heap.
String s1 = new String("Java");
String s2 = new String("Ruby");
This will create 2 objects in heap.
String s1 = new String("Java");
String s2 = "Java";
This will create one object in heap for first line.
For second line, it will check whether "Java" exists in string pool or not.If exists, it wont create a new string.It will return the reference to already existing string in pool
String s1 = "Java";
String s2 = "Java";
First line will check whether "Java" exists in string pool or not.If exists, it wont create a new string.It will return the reference to already existing string in pool.
Second line will get the reference to already created string.So no new objects if "Java" exists or maximum one object

Does string lose mutability if a new instance is created [duplicate]

This question already has answers here:
Is "new String()" immutable as well?
(15 answers)
Closed 7 years ago.
I know Strings are immutable in nature. But I have a question.
String a = new String("abc");
If we create a string like above instead of a literal, then isn't it not immutable any more since it is created as a new object? Please clarify. Thanks.
No. It doesn't. A java String is always immutable irrespective of how it is created.
Actually using new to create Strings is redundant and should be avoided in 99 percent of the cases (unless you are doing some micro-bench marking)
Immutable means an instance cannot be modified once it is created. When you look at all the methods of String, none of them actually modifies the original String passed to it. They either return the same String or create a new one.
This is a mutable object:
class Person {
private name;
Person(String name) { this.name = name; }
void setName(String name) { this.name = name; }
}
Because you can change its state after it has been created:
Person john = new Person("John");
john.setName("Fred"); //oops, John's name is not John any more...
On the other hand, once you have created a String there is no method that allows you to change the value of that string.
String john = "John";
john.setValue("Fred"); //No, that's not possible...
That does not prevent you from creating new Strings with similar or different values of course.
Your String is immutable as String is always immutable (view The Java Language Specification)
The difference between String a = "abc"; and String a = new String("abc"); is not the mutability, is the use of the String pool. When you do
String a = "abc";
you are using the Java String pool (See String intern)
And when you do
String a = new String("abc");
you are not using the String pool.
The String pool stores different String instances, that's why when you create two different objects using the pool, the references are the same.
In both cases anyways, you cannot change the state of your String instance (String is immutable).
Creating Strings using new can be avoided almost always.

Java use String value as Variable

I have a method with a Parameter Country. This Parameter only Contains an abbreviation of the Country. In the method i want to print the full name of the Country without switch case or something, but with predefined Strings
final String VA="Vatikan";
String country="VA";
system.out.println(country);
//Is it possible that it Prints Vatikan now?
//I know not with that code but is there a possibillity to do that.
No, but you could use a map to acheve the result you want. Specifically, to return the full name of the abbreviated country name:
String va="Vatikan";
String country="VA";
Map<String, String> abbreviationMap = new HashMap<String, String>();
abbreviationMap.put(country, va);
System.out.println(abbreviationMap.get(country)); //prints "Vatikan"
This will assign it properly:
final String VA="Vatikan";
String country=VA;
System.out.println(country);
The String variable country will be pointed to whatever the variable VA is pointed to; because VA cannot change (it's final), country will point to "Vatikan".
What you are doing is that assigning a string "VA" to country, but you want to treat it as a variable, so remove the quotes("").
final String VA="Vatikan";
String country=VA;
System.out.println(country);

String can't be cast to an Integer and Integer can't be cast to a String

The getHttpPort method returns an Object type derived from a JSON data query. The value of the Object could be a blank string or an Integer value. To be on the safe side I thought I could represent it as a String like this:
String port = (String)getHttpPort(param);
But this sometimes generates the error:
Integer cannot be cast to a String.
So I tried this:
String port = ((Integer)getHttpPort(param).toString();
But now I get the reverse error:
String cannot be cast to an Integer.
What's the proper way to represent the returned result of the getHttpPort method as a String?
Did you try
String port = getHttpPort(param).toString();
?
toString() is present in every class in Java. So change this
String port = ((Integer)getHttpPort(param).toString();
to
String port = getHttpPort(param).toString();
Now, this will work for the scenarios where toString() is implemented .

Do I need to do something special to use the replace method with symbols?

Here's some code
private String replaceToEncrypt(String password) {
password.replace('A','#');
password.replace('E','=');
password.replace('I','!');
password.replace('J','?');
password.replace('O','*');
password.replace('P','#');
password.replace('R','&');
password.replace('S','$');
}
Using print statements its seems that nothing happens because ABCDEFGHIJKLMNOPQRSTUVWXYZ
before this method is ABCDEFGHIJKLMNOPQRSTUVWXYZ after
Thanks
You have to re-assign the result of each replacement, for example:
password = password.replace('A','#');
This is because all Strings in Java are immutable, and any operation that modifies a String what really does is return a new String with the modifications, the original String is kept unchanged.
replace() according to the Java 7 API:
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
So in your code you need to reassign to password the new String:
password = password.replace('A','#');
//etc...

Categories

Resources