Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
public class StringDemo
{
public static void main(String [] args)
{
String s = "Sachin";
s.concat(" Tendulkar");
s.toLowerCase();
System.out.print(s);
}
}
This example giving output as : Sachin
then how many objects have been created?
The answer is: an indeterminate number.
on the face of it, the two operations on s each create a single String object,
two more String objects are created at load time to represent the literals,
objects may be created when print is called: internally to the System.out PrintWriter and the stream stack that it wraps,
each String object may (or may not) have a distinct char[] object inside it,
it is possible that the operations on s could be optimized away, since they actually have no effect on the output of the program (!!),
when the application is called, it will be passed a String[] argument, potentially populated with multiple String, and (finally),
an arbitrary number of objects will be created during JVM bootstrapping and class loading ... prior to the application starting.
So, depending on what objects you count, how you count them, and the other assumptions that you make, the answer could be some number from zero to a very large number of objects.
Note: the normal quiz answer for this would be "2 Strings are created", but as you can see the answer is a lot more complicated than that.
Note 2: the concat and toLowerCase methods do NOT create strings in the string pool. In fact, the only String operation that puts strings into the pool is intern. (It is easy to verify this experimentally, or by reading the Java class library source code.)
String in java is a immutable type.
s.concat(" Tendulkar");
s.toLowerCase();
these 2 lines return 2 distinct strings and doesn't affect the original string.
In java String is considered as immutable which means that it cannot be changed once its created, so if you count how many you have, on the first line you declared the first one, when you did s.concat("SE 6") you created a new object, and finally s.toLowerCase() created the 3rd object, therefore 3 string objects are created.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am a beginner. Why isEmpty() is defined an error in my question.
I trim and split a string array:
String[] items = s.trim().split("[ !,?.\\_'#]+");
I want to print
int i = (items.isEmpty()) ? 0 : items.length;
but isEmpty shows an error.
Arrays don't have isEmpty method. You need to check it yourself with items.length == 0.
Also, be aware that items is never empty:
If the expression does not match any part of the input then the resulting array has just one element, namely this string.
String[] items is known as an array and is one of the most simple data structures in Java. There are more complicated and handy data structures like ArrayList, HashMap, etc.
The isEmpty() is a method which has been declared in the List Interface, so all the Java classes that implemented this interface have their implementation of isEmpty method. (String[] is not an implementation of List)
Note: split method always returns a non-empty array, so it is useless to to have a method like isEmpty. You can just check the length of returned value, items.length == 0
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
String s = "world";
StringBuilder str = new StringBuilder(s);
str.deleteCharAt(0);
System.out.println(s);
this code outputs the following result : world , what am i doing wrong ? why is the first character of string not being deleted ?
The Issue with the StringBuilder and your code is that it does not exactly what you think it does.
A StringBuilder may take any CharSequence as a constructor argument but it will not alter the passed value directly. String in particular are immutable. Anyway StringBuilders do not alter the Object directly. They buffer the characters in a char[] which isn't immutable anymore.
To get the buffered value (and your new "altered" String) you have to call the toString() method of the StringBuilder since it will create a new String based on the interally stored buffer.
But since it System.out.println() implicitly calls the toString() method it is not needed here.
System.out.println(str);
you must put the value of your StringBuilder back to your string.
s = str.toString();
You are printing s, and s has not been changed. When you construct str using s, a copy of s is made. Told in a different way, the reference to each character in s and str is not the same, so even after your deletion in str, s stays the same.
Modify
System.out.println(s);
to
System.out.println(str.toString());
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
public class Book
{
String bookName;
public static void main(String[] args)
{
Book Object = new Book();
Object.bookName = "Network Technology Design";
System.out.println("The book named", Object.bookName);
}
}
As you see, the
System.out.println("The book named", Object.bookName);
is wrong,but if I do that
System.out.println(Object.bookName);
No any error, why?
You need to concatenate the Strings with a "+", because System.out.println() only takes one parameter.
You have to do it like this:
System.out.println("The book named " + Object.bookName);
If you see the PrintStream class,then you can find that there are no such method println which accepts 2 arguments.
So
System.out.println("The book named", Object.bookName); is wrong and System.out.println(Object.bookName); is right
System.out.println expected String, and you try to pass additional paramters. As menthioned in comments, use string concatenation or foramt function
System.out.println(String.format("The book named %s", Object.bookName))
System.out.println() takes only one parameter - Any primitive data type or Object type. Need to make it one argument by concatenating or combining..!
PrintStream class overloadingprintln() method depending on arguments type it call the method and it have only one argument or no argument.
like println(), println(String x), println(int x) etc
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have a little/huge problem with String comparison in Java, I want to compare two Strings and .equals([...]) does not give me the correct result.
I also tried the following: ==, .compareTo([...]), .trim(), .equalsIgnoreCase([...]), creating a Collator with default Locale and using [collator].compare.
(All fail to work)
The first String comes from an already created object (the content of the string is from a database), the second String comes from a newly created object (but has been passed to a method), the content of this String is from the same database.
I am pretty clueless what to do now, the last thing I'd try is to convert it to some number (i.e. hex).
I already tried to write both Strings to console and manually look for differences, but there is none...
Code is this:
public static Lagerplatz hinzufuegen(Lagerplatz lagerplatz) {
boolean neu = true;
if (lagerplaetze.isEmpty()) {
lagerplaetze.add(lagerplatz);
System.out.println(lagerplatz.getBezeichnung() + " erstmalig hinzugefügt!");
}
for (int i = 0; i < lagerplaetze.size(); i++) {
System.out.println("'" + lagerplatz.getBezeichnung() + "'" + " - " + "'"
+ lagerplaetze.get(i).getBezeichnung() + "'");
if (lagerplatz.getBezeichnung().equalsIgnoreCase(lagerplaetze.get(i).getBezeichnung())) {
neu = false;
}
}
if (neu) {
lagerplaetze.add(lagerplatz);
System.out.println(lagerplatz.getBezeichnung() + " hinzugefügt!");
}
return lagerplatz;
}
The if-part with (lagerplaetze.isEmpty()) does work, after the first one is added it should check if the Lagerplatz (at least the name of it) is already in the lagerplaetze-ArrayList, if so then don't add, if not add.
Stepping through it revealed that the objects are correctly referenced...
Thanks very much in advance, and sorry if this question has been answered already but I can't find a helping answer under all these questions...
EDIT1: Normalizing does not help in this case, "umlaute" (german ä, ö or ü) are not causing the problem...
Converting the String to a byte[] and converting this byte-array to String like:
(Arrays.toString(lagerplatz.getBezeichnung().getBytes()).equalsIgnoreCase(
Arrays.toString(lagerplaetze.get(i).getBezeichnung().getBytes())))
and then comparing it does also not solve the problem, the bytes of the two strings are exactly the same: '[72, 55, 48]' - '[72, 55, 48]'
EDIT2: The problem is not with the String comparison, it is because the variables of the class "Lagerplatz" are static, they were replaced each time the loop is entered...
Maybe delete this question?
The only time two strings that look exactly the same but equals() does not result in true is when the unicode composition is different.
For example one can compose the A umlaut (Ä) with a single character: \u00C4
Or with a combination of the A character and the dots (the dieresis character ¨): \u0041\u0308
In essence, you are using two unicode characters for one letter. Because equals() compares characters, the form with dieresis is not equals to the form without.
To overcome this problem, one must decompose each string to a canonical form before comparison.
In Java one can create such a canonical form like this:
java.text.Normalizer.normalize("Your String", java.text.Normalizer.Form.NFD);
Once normalized, equals() will work as expected.
Obviously, since you didn't provide any data, this answer may or may not match your problem.
In any case, you might want to normalize all Strings in some form and then use a Set as data structure, not a list.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I know it's a simple question but really want to see if there's another way to do it instead of using ArrayList to hold all the values. And if that's necessary, what should be the design of the java class.
Say I would need 5 list of values read from 5 files. Previously I just used 5 ArrayList to store the 5 list of values.
public class Values{
ArrayList<String> o1 = new ArrayList<String>();
ArrayList<String> o2 = new ArrayList<String>();
ArrayList<String> o3 = new ArrayList<String>();
...
public void readFromFile(ArrayList<String> listName, String filePath){
/*read file contents into list*/
}
But my problem is, each may contain more than 2000 string values. Is this an appropriate way to do so? If so, what would be a better design of it?
I think you will be fine with using ArrayLists for such a task. I have processed a large dataset of Tweets (aka Twitter Streaming data) to the tune of 5 GB and 1.5 million individual tweets. It wasn't an issue.
You can always increase your heap size if you have problems. Do realize that unless you really need to create and store so many ArrayLists, you can always clear them after intermediate processing.
java -Xms2048M -Xmx4096M YourProgramName
I think this should give you an idea of how you should design your program. The idea here is to add, process, remove. For my case, I just parsed, manipulated a tweet, cleared and moved on.
Given that you really need to have that data in memory, there is nothing wrong with ArrayList to accomplish that. 5 files with 2000 strings of a length of 80 characters are 5*2000*80*2 bytes of character data + some overhead for the 10000 String objects + 5 ArrayList objects, in total you will use less than 1.7 MB of memory for that. Not a big deal.
You should change the declaration and use List instead of ArrayList, like this:
List<String> o1 = new ArrayList<String>();
In this way you can use for example a LinkedList instead of the ArrayList without changing to much of your code. But as long as you don't have any specific reason to use something else, go ahead and use the ArrayList, it is the simplest solution.
KISS.
Unless a different solution enhances testability, maintainability, clarity and simplicity of what you're trying to accomplish, go with what you have. Writing good, clean code is much more important at the outset than writing highly optimized, fast performing code. Clean code is code that's easy to optimize later anyway.