Error at using Assignment operator in java [duplicate] - java

This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 2 years ago.
I also the error "Left Hand Side of an Assignment must be a Variable" for following line
outPutArray.charAt(i)=inputArray[i]
how to resolve this? I have tried putting braces like but of no use
(outPutArray.charAt(i))=inputArray[i]

You are trying to mutate a String object. This is not possible, String is supposed to be immutable. You have to create a new String with the changed content, use a char array instead, or something else that allows you to actually achieve what you are trying to do in the end (which is: given an input String, return an output String where one character is changed).
With that out of the way, you can't do an assignment on the return value of a function. You don't get a reference back that you can change and then some variable gets changed. You get a value back. The great Is Java "pass-by-reference" or "pass-by-value"? question is maybe a good read.

Very silly, but the format should be:
inputArray[i] = outPutArray.charAt(i);
not
outPutArray.charAt(i) = inputArray[i]
putting the function on the left hand side means you are assigning a constant integer to a integer array element. As the integer is constant, it will fail. This is why we put our variables(inputArray[i] in your case) on the left hand side and our functions on the right hand(outPutArray.charAt(i)). Hope you understand!

.charAt(i) function returns the character at position i. It does not return the reference to the character at that index.
Look at this for more details

Related

String.valueOf(someVar) vs ("" + someVar) [duplicate]

This question already has answers here:
String valueOf vs concatenation with empty string
(10 answers)
Closed 5 years ago.
I want to know the difference in two approaches. There are some old codes on which I'm working now, where they are setting primitive values to a String value by concatenating with an empty String "".
obj.setSomeString("" + primitiveVariable);
But in this link Size of empty Java String it says that If you're creating a separate empty string for each instance, then obviously that will take more memory.
So I thought of using valueOf method in String class. I checked the documentation String.valueOf() it says If the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So which one is the better way
obj.setSomeString("" + primitiveVariable);
obj.setSomeString(String.valueOf(primitiveVariable));
The above described process of is done within a List iteration which is having a size of more than 600, and is expected to increase in future.
When you do "" that is not going to create an Object. It is going to create a String literal. There is a differenc(How can a string be initialized using " "?) actually.
Coming to your actual question,
From String concatenation docs
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.
So unnecissarly you are creating StringBuilder object and then that is giving another String object.
However valueOf directly give you a String object. Just go for it.
Besides the performance, just think generally. Why you concatenating with empty string, when actually you want to convert the int to String :)
Q. So which one is the better way
A. obj.setSomeString(String.valueOf(primitiveVariable)) is usually the better way. It's neater and more domestic. This prints the value of primitiveVariable as a String, whereas the other prints it as an int value. The second way is more of a "hack," and less organized.
The other way to do it is to use Integer.toString(primitiveVariable), which is basically the same as String.valueOf.
Also look at this post and this one too

Java: Unexpected Type Error [duplicate]

This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 8 years ago.
Can someone help me understand why I'm getting an "Unexpected Type Error"?
if(s.charAt(i-1) == ' '){
String sub = s.substring(i, s.indexOf(' ')+1);
for(int j = 0; j < sub.length()/2; j++){
char temp;
temp = sub.charAt(j);
sub.charAt(j) = sub.charAt(sub.length()-1-j);
sub.charAt(sub.length()-1-j) = temp;
sub = sub+" ";
complete = complete+sub;
}
}
I'm getting the error on lines 6 and 7. I can't figure out why and I'd appreciate the help!
charAt() returns the character. It is not a left side operand aka you cannot assign a value to it.
Strings are immutable, which means you cannot change them (this seems to be your intention).
Instead: create a new String and add to that.
If this confused you, I try to elaborate a little: the assignment operator takes whatever is on the right and tries to shove it into whatever is on the left of it.
The problem here is that some things do not like it when you try to shove other things into them. You cannot put everything on the left that you want. Well, you can try:
"everything" = 5;
but this does not work, neither does this:
"everything" = 42;
Set aside what that last snippet failing implies to the universe and everything, your problem at hand is that charAt() is also one of those things that do not like it on the left side of the assignment operator.
I'm afraid there's no way to turn charAt() into one of those things that like it on the left side. A week after stranding on a deserted island without any plants but only solar powered refrigerators filled with steaks, this probably works:
vegetarian = meat;
Even though the vegetarian doesn't like it there, he'd accept his situation being on the left side of the = operator. He eats some steaks.
This does not hold true for what you are trying, though. There's no such deserted island for charAt().
In these lines you're trying to set the value of functions' return. This is illegal
sub.charAt(j) = sub.charAt(sub.length()-1-j);
sub.charAt(sub.length()-1-j) = temp;
as far as I see you're trying to change the characters of a String, but Strings are imutable objects. So you'll need to use a StringBuffer to set the values.

How does this recursion work [duplicate]

This question already has answers here:
Reversing a String with Recursion in Java
(17 answers)
Closed 8 years ago.
This piece of code reverses string parameter passed to it. I know that string is immutable. I seem not to understand what is going on. Where does it store the reversed string that it returns.
public static String reverseRecursively(String str) {
//base case to handle one char string and empty string
if (str.length() < 2) {
return str;
}
return reverseRecursively(str.substring(1)) + str.charAt(0);
}
Your reverseRecursively(str.substring(1)) + str.charAt(0) creates a new String object every time it is called.
Where does it store the reversed string that it returns.
As the method shows, it calls itself recursively. Each time it is called it would add entries to the call stack. So, read about how the call stack works if you are concerned with the magic about where these "intermediate" results are stored.
Here is a call diagram that illustrates data flow:
Vector source of the image
Each call returns a copy of string with first character placed last and rest being processed by further calls. References to these strings are stored on stack which grows with each call (more stack space is required to handle longer strings).

Obfuscation: hide hardcoded values in java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
hiding strings in Obfuscated code
I'm trying to hide a little some static Strings of my app in order to make it harder to decompile, this way like the constants like cipher algorithms names are harder to find in the obfuscated code.
I've considered things like:
String CONCAT= "concat"+"string";
String RAW_STRING= "raw_string";
String FROM_BYTES=new String("from_bytes".getBytes());
String FROM_CHARS=new String(new char[]{'f','r','o','m','_','c','h','a','r','s'});
String FROM_CHAR2=new String(new char[]{102,114,111,109,95,99,104,97,114,115,95,50});
And the last two options seems to be "darker" than the raw option but I imagine there are better ways for doing this.
How can I improve this? Thanks
For one, you shouldn't just write
String FROM_CHAR2=new String(new char[]{102,114,111,109,95,99,104,97,114,115,95,50});
It's a dead give-away that the char array is actually a String.
You can do a combination of the followings:
put your "String" in an int[] array
or even better, break your String into several int arrays
calculate/manipulate the array's values at various stage of the application, so its value will only become valid at a certain interval during a runtime, guaranteeing that it won't be deciphered at a curious glance by decompiling your code
passes the array(s) back and forth, through local variables, back to instance variables, etc, before finally converting the arrays to a single array to be passed to the String constructor
immediately set the String to null after use, just to reduce the amount of time the actual String exist at runtime
I would prefer to set the value in the static (class) initializer using an decryption algo
Something like
class ...
String CONCAT;
static {
CONCAT = uncrypt ("ahgsdhagcf");
}
where uncrypt might be really a good unencryption algo or somewhat weaker a base64 decode.
In any case you need a simple program to encode your string first.

What is the meaning of the information that I get by printing an Object in Java? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 5 years ago.
Lets say i have this code :
Integer[] a= new Integer[5];
System.Out.println(((Object)a).toString());
the output is get is
[Integer#89fbe3
what is the meaning of 89fbe3 ? is this some kind of address ? hash code? is it unique for each object? , and if so- if its a multi-threaded program , is it still unique ?
thanks !
It's the result of System.identityHashCode(Object x);
which is the default implementation of every object's hashCode()...
from the Object javadoc:
getClass().getName() + '#' + Integer.toHexString(hashCode())
The 89fbe3 is a hex version of the hash code. The [I means an array of ints (I'm surprised you get that with an Integer[], are you sure it wasn't an int[]?)
Some others:
[L<typename>;: an array of reference type "typename" (e.g. [Ljava.lang.Integer)
[J: an array of longs
[B: an array of bytes
etc.
It is the identity hash code of the object (you can think of it as the address of the object), along with some type information.
[ = array
I = Integer
I think that while technically all the answers are correct, the real answer is "NO". This number has no meaning and you can make absolutely no assumptions about it.
It's the memory address of the object which is what the default toString() implemented in the Object class does. It is also the default hashCode().

Categories

Resources