String in Java : charAt Function use - java

Reversing a string can be done by concatenating the Original String through a reverse loop (from str.length-1->0)
but why is this not Working Correctly :
by adding the character by character from last positon to the 0th position:
int i = 0;
while(i<originalStr.length())
{
strRev.charAt(i)=originalStr.charAt(str.length()-1-i);
i++;
}

Strings are immutable in Java. You cannot edit them.
If you want to reverse a String for training purpose, you can create a char[], manipulate it then instantiate a String from the char[].
If you want to reverse a String for professional purpose, you can do it like this :
String reverse = new StringBuilder(originalStr).reverse().toString();

strRev.charAt(i) // use to Retrieve what value at Index. Not to Set the Character to the Index.
All we know that String is a immutable class in Java. Each time if you try to modify any String Object it will Create a new one.
eg :- String abc = "Vikrant"; //Create a String Object with "Vikrant"
abc += "Kashyap"; //Create again a new String Object with "VikrantKashyap"
// and refer to abc again to the new Object.
//"Vikrant" Will Removed by gc after executing this statement.
Better to Use StringBuffer or StringBuilder to perform reverse Operation. The only Difference between these two class is
A) StringBuffer is a Thread Safe (Synchronized). A little slow because each time need to check Thread Lock.
B) StringBuider is not Thread Safe. So, It gives you much faster Result Because it is Not Synchronized.
There are Several Third Party Jars which provides you a Features like Reverse and Many more String base Manipulation Methods
import org.apache.commons.lang.StringUtils; //Import Statement
String reversed = StringUtils.reverse(words);

In your test method, best practice is to use triple A pattern:
Arrange all necessary preconditions and inputs.
Act on the object or method under test.
Assert that the expected results have occurred.
#Test
public void test() {
String input = "abc";
String result = Util.reverse(input);
assertEquals("cba", result);
}

Related

Difference between String and String Builder (not about concatination) [duplicate]

This question already has answers here:
String, StringBuffer, and StringBuilder
(12 answers)
Closed 7 years ago.
Yes i have read all material on internet regarding their difference.and that difference is totally based on concatenation performance of both.My question is that in the below code which technique is better.
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("test");
System.out.println(str.toString());
str = new StringBuilder("Hi ");
System.out.println(str.toString());
}
}
here is string demo
public class StringDemo {
static String str="";
public static void main(String[] args) {
str = "test";
System.out.println(str);
str ="Hi";
System.out.println(str);
}
}
My assumptions are since strings are immutable so when we assign "Hi" to str "test " also remain in memory(two objects of string created "Hi" and "test" ).where as in case of string builder when we give value "Hi" "test" is removed.so we have one object in case of string builder. So i concluded that we should use string builder in these cases. Correct me if i am being childish here .
You are right, String is immutable. Means you cannot add things to its memory content directly, meaning you'll need additional memory to access it. However, your application here doesn't seems to be memory intensive, hence you can just use String directly.
In your case an ordinary String is better. You should use StringBuilder in large for loops where you are adding a lot of stuff to a string.
The thing is that a String is imutable and when you assign a variable to a string, java looks in what you can imagine a table of already created ones. If there is one with the same content, you get a reference to that String. However, whenever you are chaining the content of the String, a new object is created and hence a slower performance in large loops.
With the StringBuilder that is not the case, it is mutable, which means that you can modify it's objects and there will be no new objects created, instead it will just resize itself when it needs to.
Yep, when you join more string or you create a string there is a String Builder hided behind it.
For simple string there is no difference in performance but you should use the String Builder if u need join (or add) more strings togheter.
This is very basic thing. you should use 'String' not 'StringBuilder' in your case.

Multiple string method chained in single code

I am working on this bit of code
public class SimpleStringTest {
public static void main(String args[])
{
String ints="123456789";
System.out.println(ints.concat("0").substring(ints.indexOf("2"),ints.indexOf("0")));
}
As per as my knowledge on java "When the multiple methods are chained on a single code statement, the methods execute from left to right" Then, Why is this bit of code throwing StringIndexOutOfBondsException?
Thanks in advance,
GPAR
Because Strings are immutable.
By invoking concat, you are not modifying ints, you are creating a new String.
Therefore by the time you invoke ints.indexOf("0"), ints is still equal to its former value and the indexOf invocation returns -1, which in turn will be the outer bound of your substring.
Try a counter-example with a mutable CharSequence such as StringBuilder:
StringBuilder ints = new StringBuilder("123456789");
System.out.println(ints.append("0").substring(ints.indexOf("2"),ints.indexOf("0")));
Output
23456789
Because ints.indexOf("0") is applied on the original String ints (not the one you concatenate).
Since there is no "0" indexOf("0") returns -1 and which throws the exception.
Your code is equivalent to this:
String ints="123456789";
int indexOne = ints.indexOf("2");
int indexTwo = ints.indexOf("0");
System.out.println(ints.concat("0").substring(indexOne, indexTwo));

Convert .toBinaryString into its complement

I do not know why I am getting an error at the yy.charAt(i) assignments. It says... Variable Expected... Not value.
static int subtract(int x,int y)
{
String yy=Integer.toBinaryString(y);
System.out.println(yy);
for(int i=0;i<yy.length();i++)
{
if(yy.charAt(i)==1)
{
yy.charAt(i)=0;
}
else
{
yy.charAt(i)
}
}
int t=Integer.parseInt(yy);
return(t);
}
You can't assign values to a string's index position, strings are immutable in Java. This will never work:
yy.charAt(i)=0;
If you need to modify a string, transform it to a char[] (using the toCharArray() method), modify the array and then build a new string from that array, using the String(char[]) constructor.
Alternatively, you could use a StringBuilder to modify the characters before returning a new string.
Use a StringBuilder instead.
The code would be almost identical to what you have now, except for these changes:
StringBuilder yy = new StringBuilder(Integer.toBinaryString(y));
...
yy.setChatAt(i, '0');
I think there are a few things that are not clear to you.
I think you mean the character '0' not the value 0.
The lines else { yy.charAt(i); } have absolutely no effect. You can simply omit them.
Strings are immutable in Java (i.e. they cannot be modified in place).
Even if they were, you're syntax is wrong. Something of the form class_name.method_name() is a call to a method of a class. It returns a value that you can store, it is not the same as a variable and trying to assign to a method call makes no sense at all.
To modify Strings in Java, the best way is probably to use a StringBuilder. You create a new StringBuilder using your String, make the necessary changes on that and then convert it back into a String.
So this would look something like this:
StringBuilder builder = new StringBuilder(yy); // StringBuilder from yy.
// rest of your code here
builder.setCharAt(i, '0');
// more code
yy = StringBuilder.toString(); // convert it back to a String.
Notice that even in a StringBuilder you have to call the appropriate method and pass in the value that you want to assign to it.

Converting an array list to a single string

I am working on a section of code for an assignment I am doing atm, and I am completely stuck with 1 little bit.
I need to convert the contents of an array list into a string, or the form of a string, which will be able to be imput into toString() in order for it to be printed to the screen.
public String toString(){
String full;
full = (this.name + this.address + "\n" + "Student Number = " + this.studentId);
for (int i = 0; i < cs.size(); i++) {
full.append(cs[i]);
return full;
The piece of above code is where i attempt to combine 3 varaibles and the contents of an array list into a single string with formatting.
Unfortunatly it creates an error "The type of the expression must be an array type but it resolved to ArrayList"
Thanks for any help.
Jake
cs is array list, so you have to do get operation, not [] (which is for array access)
It should be like:
full.append(cs.get(i));
Not
full.append(cs[i]);
EDIT: As assylis said, full should be StringBuilder not just String, because String doesn't support append() method.
StringBuilder full = new StringBuilder();
Apache Commons StringUtils has different varieties of join() methods that mean you don't have to write this yourself. You can specify the separator and even the prefix/suffix.
I would recommend you look at Apache Commons, not just for this but for lots of other useful stuff.
You are attempting to access an ArrayList as though it is a primitive array (using the square brackets around the index). Try using the get(int index) method instead.
i.e.,
cs.get(i);
You cannot index an ArrayList like an array, you need the get(index) method. Even better, use the enhanced for loop, since it's not recommended to index over a list, as the implementation may change to LinkedList.
I also suggest using a StringBuilder for efficiency:
public String toString() {
StringBuilder full = new StringBuilder();
full.append(this.name);
full.append(this.address);
full.append("\n");
full.append("Student Number = ");
full.append(this.studentId);
for (String s: cs)
full.append(s);
return full.toString();
}
Just use
"cs.get(i)" in place of "cs[i]".
as cs is an ArrayList not an Array.
and also use
full = full + cs.get(i); and not full.append(cs.get(i));
as String type dont have a append method.
Just a note, since you don't put any spacers between each element of the ArrayList it might be unreadable. Consider using Guava's Joiner class.
So instead of
for (...)
s.append(y);
if would be
a.append(Joiner.on(" ").join(yourList));
The Joiner is also more efficient than the for loop since it uses a StringBuilder internally.

Removing Backing Array From Strings

I want to get the first 4 characters of a string to compare with another string. However, when I do something like
String shortString;
shortString = longString.subString(0,3);
It takes along longString's backing array and makes it impossible to compare easily.
I've also tried converting longString into a character array and inserting each character but I always seem to end up with long string. The Android Development documents say to use the String constructor to remove the backing array but it doesn't seem to work for me either.
String shortString = new String(longString.subString(0,3));
Any suggestions would be appreciated!
First, it's string.substring() not .subString().
Second, what do you mean "impossible to compare easily"? You can compare strings with .equals() easily.
public static void main(String[] args) {
String longString = "abcdefghijklmn";
String shortString = longString.substring(0, 3);
System.out.println(shortString.equals(longString));
}
this code prints false, as it should.
Update:
If you call .substring() so that it produces string of the same length as original string (e.g. "abc".substring(0,2)) than it will return reference to the same string. So, .equals() in this case will return true.
How would you want to compare? There's built in method for simple comparison:
longString.subString(0, 3).compareTo(anotherString);
Alternatively, since String is a CharSequence, something like:
for (int i=0; i<4; i++){
if (anotherString.charAt(i) != shortString.charAt(i)) return false;
}
would work as well.
Finally, every String is constructed in backing Array, there's no way to deny it, and longString.subString(0,3) would always (except index out of bound) return a String with a 4-element Char Array.
In the event that you actually need to get rid of the backing array the following will work:
String newString = StringBuilder(oldString).toString();
This might be necessary, for example, if you are parsing strings and creating substrings and you might need to do this:
String newString = StringBuilder(oldString.substring(start,end).toString();
This creates a truly new string with a zero offset and independent backing array. Otherwise, you maintain the same backing array which, in rare cases might cause a problem for the heap because it can never be garbage collected.

Categories