I have 3 options:
Declare double member and later when I have to pass String use member + "".
Declare double member and later when I have to pass String use Double.toString(member).
Declare Double member = 0.0 and later when I have to pass String use member.toString().
My opinions:
The shortest one. However, member + "" will be converted to new StringBuilder().append(member).append("").toString(), which seems not elegant.
In Double.toString(member) I don't like that it doesn't start from the word member, which is the most important. We only need to convert it. It's better if member is in the beginning, because I pay most attention to the beginning of word. Quick glance and I know "ah, ok I'm passing member". And with Double.toString(member) my very first concentration goes to "ah, ok... a Double, we are doing toString... of a member! Ah ok".
member.toString() looks fine and it can be typed even faster then + "", because of autocompletion in Eclipse. However, objects are much slower then primitives. Reference.
What is the best option? Maybe there are some other options?
The best all-round approach, which will work for anything, is:
String s = String.valueOf(x);
Here x can be a primitive or an object, which (importantly) may be null.
Edit:
The hackaliciuos way is:
X + "";
Although note that this is not very efficient, because it compiles to:
new StringBuilder().append(x).append("").toString();
And the call to .append(x) invokes String.valueOf(x) anyway.
Note that arrays need special treatment:
String s = Arrays.toString(array);
Related
I am currently using
Double a = 0.00;
for(condition)
//Do things
String result = "" + a;
Would using
String result = a.toString();
Provide any real benefit compared to what I have now. Does this just help the compiler or are there any differences between the two methods?
The first version - String result = "" + a under the hood is the same as String result = "" + a.toString();. Whenever there is a concatenation of String + Object the toString method is called.
What is the best practice here? What looks better for you. I'd probably go with the first version.
If you're concerned about the performance of both - String result = a.toString(); on paper will be faster because you don't need to create / get an empty String just to create a new one. However, as with many things in Java, something like that most likely gets optimized by JIT compiler anyway so I wouldn't worry about it too much. Even if it doesn't you shouldn't worry about optimization prematurely - if your code runs slowly then usually there is something else wrong with it that is much bigger than that.
I think second option is better because concatenation of strings cost much more memory.Since Strings are immutable objects in the first way your memory is wasting for store a Double object + two String Objects .
But in the second option it only create one new String object only .So in your memory there will only be one Double object + one String Object.
I am new to learning Java and was explained that every variable needs to be declared. Why do I not need to do this in two steps?
int a = Integer.parseInt(console.readLine("How old are you? "));
console.printf("a: %d", a);
You don't need to declare a variable, but when you do so, you must specify a type (or a super type of what is on the right hand side).
The return value of console.readLine("How old are you? ") is a String and printf can take that as a parameter, so there is no missing type information.
Nothing stops you from writing it in one line, i.e.
console.printf("a: %d", Integer.parseInt(console.readLine("How old are you? ")));
This will work without any problem. Writing it in one line becomes a question of preference / readability and whether you want to do anything with the variable before you print it...
As to your comment, you can check in documentation that console.readLine() returns String.
I try to get a better understanding of Strings. I am basically making a program that requires a lot of strings. However, a lot of the strings are very, very similar and merely require a different word at the end of the string.
E.g.
String one = "I went to the store and bought milk"
String two = "I went to the store and bought eggs"
String three = "I went to the store and bought cheese"
So my question is, what approach would be best suited to take when dealing with strings? Would concatenating 2 strings together have any benefits over just having static strings in, say for example, performance or memory management?
E.g.
String one = "I went to the store and bought "
String two = "milk"
String three = "cheese"
String four = one + two
String five = one + three
I am just trying to figure out the most optimal way of dealing with all these strings. (If it helps to put a number of strings I am using, I currently have 50 but the number could surplus a huge amount)
As spooky has said the main concern with the code is readability. Unless you are working on a program for a phone you do not need to manage your resources. That being said, it really doesn't matter whether you create a lot of Strings that stand alone or concatenate a base String with the small piece that varies. You won't really notice better performance either way.
You may set the opening sentence in a string like this
String openingSentence = "I went to the store and bought";
and alternate defining each word alone, by defining one array of strings like the following ::
String[] thingsToBeBought = { "milk", "water", "cheese" .... };
then you can do foreach loop and concatenate each element in the array with the opening sentence.
In Java, if you concatenate two Strings (e.g. using '+') a new String is created, so the old memory needs to be garbage collected. If you want to concatenate strings, the correct way to do this is to use a StringBuilder or StringBuffer.
Given your comment about these strings really being URLs, you probably want to have a StringBuilder/StringBuffer that is the URL base, and then append the suffixes as needed.
Performance wise final static strings are always better as they are generated during compile time. Something like this
final static String s = "static string";
Non static strings and strings concatenated as shown in the other example are generated at runtime. So even though performance will hardly matter for such a small thing, The second example is not as good as the first one performance wise as in your code :
// not as good performance wise since they are generated at runtime
String four = one + two
String five = one + three
Since you are going to use this string as URL, I would recommend to use StringJoiner (in case your are using JAVA 8). It will be as efficient as StringBuilder (will not create a new string every time you perform concatenation) and will automatically add "/" between strings.
StringJoiner myJoiner = new StringJoiner("/")
There will be no discernable difference in performance, so the manner in which you go about this is more a matter of preference. I would likely declare the first part of the sentence as a String and store the individual purchase items in an array.
Example:
String action = "I went to the store and bought ";
String [] items = {"milk", "eggs", "cheese"};
for (int x = 0; x< items.length; x++){
System.out.println(action + items[x]);
}
Whether you declare every possible String or separate Strings to be concatenated isn't going to have any measurable impact on memory or performance in the example you give. In the extreme case of declaring truly large numbers of String literals, Java's native hash table of interned Strings will use more memory if you declare every possible String, because the table's cached values will be longer.
If you are concatenating more than 2 Strings using the + operator, you will be creating extra String objects to be GC'd. For example if you have Strings a = "1" and b = "2", and do String s = "s" + a + b;, Java will first create the String "s1" and then concatenate it to form a second String "s12". Avoid the intermediate String by using something like StringBuilder. (This wouldn't apply to compile-time declarations, but it would to runtime concatenations.)
If you happen to be formatting a String rather than simply concatenating, use a MessageFormat or String.format(). It's prettier and avoids the intermediate Strings created when using the + operator. So something like, String urlBase = "http://host/res?a=%s&b=%s"; String url = String.format(urlBase, a, b); where a and b are the query parameter String values.
I have a cookie value like SESSIONID_TEST=4CEC1E0609F127DD7EB87DD438B2CA50.jap-test-lad-14; path=/
Now i want to replace only 14(which is dynamic value) with different number for example 19.
So I want the cookie value to be and also remove "; path=/" and text "SESSIONID_TEST="
4CEC1E0609F127DD7EB87DD438B2CA50.jap-test-lad-19
Let me know
much appreciated
Can't you use this?
cookie.replace("14; path=/", "19");
use String.replace(). It takes two arguments. The first one is the old string you want to change and the second is what you want to change it to.
cookie = cookie.replace("14; path=/", "19")
will make cookie = SESSIONID_TEST=4CEC1E0609F127DD7EB87DD438B2CA50.jap-test-lad-19
Be careful though
String x = "101010";
x.replace("1", "2");
System.out.println(x);
Will print "101010" because strings are immutable. You have to make a new string or call
x = x.replace()
https://docs.oracle.com/javase/tutorial/java/data/strings.html
"The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation."
EDIT:
Since "14" changes you can use slicing instead of String.replace(). Assuming "14" will always be in the same spot and always be the same length use this instead:cookie = cookie[0 : (len(cookie) - 10)] + "19" Also remember to replace "sessionid_test" with an empty string.
Convert it to a String and put it in a variable str and then use the following code snippet -
str.replace("14", "19")
str.replace("; path=/" , "");
str.replace("SESSIONID_TEST=", "");
Thanks
I've read that in Java an object of type String can't change. But int and char variables can. Why is it? Can you give me an example?
Thank you.
(I am a newer -_- )
As bzabhi said, strings are immutable in Java. This means that a string object will never change. This does not mean you can not change string variables, just that you cannot change the underlying memory representation of the string. for an example:
String str = "Hello";
str += " World!";
Following the execution of these lines, str will point to a new string in memory. The original "Hello" string still exists in memory, but most likely it will not be there for long. Assuming that there are no extenuating circumstances, nothing will be pointing at the original string, so it will be garbage collected.
I guess the best way to put this would be to say that when line 2 of the example executes, a new string in memory is created from the concatenation of the original string and the string being added to it. The str variable, which is just a reference to a memory location, is then changed to point at the new variable that was just created.
I am not particularly knowledgeable on the point, but, as I understand it, this is what happens with all "non-primitive" values. Anything that at some point derives from Object follows these rules. Primitive values, such as ints, bools, chars, floats and doubles allow the actual value in memory to be changed. So, from this:
int num = 5;
num += 2;
the actual value in memory changes. Rather than creating a new object and changing the reference, this code sample will simply change the value in memory for the num variable.
As for why this is true, it is simply a design decision by the makers of Java. I'm sure someone will comment on why this was made, but that isn't something I know.
int and char can't change either. As with strings, you can put a different value into the same variable, but an integer itself doesn't change. 3 will always be 3; you can't modify it to be 4.
String is an immutable type (the value inside of it cannot change). The same is true for all primitive types (boolean, byte, char, short, int, long, float, and double).
int x;
String s;
x = 1;
x = 2;
s = "hello";
s = "world";
x++; // x = x + 1;
x--; // x = x - 1;
As you can see, in no case can you alter the constant value (1, 2, "hello", "world") but you can alter where they are pointing (if you warp your mind a bit and say that an int variable points at a constant int value).
I'm not sure that it is possible to show (by example) that Strings cannot change. But you can confirm this by reading the description section of Javadoc for the String class, then reading the methods section and noting that there are no methods that can change a String.
EDIT: There are many reasons why Strings are designed to be immutable in Java. The most important reason is that immutable Strings are easier to use correctly than mutable ones. And if you do need the mutable equivalent of a String for some reason, you can use the StringBuilder (or StringBuffer) class.
It's also worthwhile to note that since strings are immutable, that if they are passed into a method, they can't be modified inside of the method and then have those changes seen outside of the method scope.
public void changeIt(String s) {
// I can't do anything to s here that changes the value
// original string object passed into this method
}
public void changeIt(SomeObject o) {
// if SomeObject is mutable, I can do things to it that will
// be visible outside of this method call
}
This little article can probably explain it better than I can: http://www.jchq.net/tutorial/09_02Tut.htm
Strings are immutable in java. Nevertheless, you can still append or prepend values to strings. By values, I mean primitive data types or other strings.
However, a StringBuffer is mutable, i.e. it can be changed in memory (a new memory block doesn't have to be allocated), which makes it quite efficient. Also, consider the following example:
StringBuffer mystringbuffer = new StringBuffer(5000);
for (int i = 0; i<=1000; i++)
{
mystringbuffer.append ( 'Number ' + i + '\n');
}
System.out.print (mystringbuffer);
Rather than creating one thousand strings, we create a single object (mystringbuffer), which can expand in length. We can also set a recommended starting size (in this case, 5000 bytes), which means that the buffer doesn't have to be continually requesting memory when a new string is appended to it.
While a StringBuffer won't improve efficiency in every situation, if your application uses strings that grow in length, it would be efficient. Code can also be clearer with StringBuffers, because the append method saves you from having to use long assignment statements.