Why can't i do this?
I understand that concatenation of a int and a string or with boolean,(true or false) is possible, but not an addition of boolean with an int.
What exactly happens when u add a int with a boolean? Why does it show an error?
System.out.println(a.length() + a.startsWith("a"));
i also understand that the work around for this code is
System.out.println(""+a.length() + a.startsWith("a"));
which uses concatenation.
Because the + operation has different functions.
In the first example you try Number + Boolean. And this doesn't make sense, so the compiler gives an error.
In the second example you try String + Number (which is allow as String - concentation and returns a String). Afterwards you try String + boolean (which is also allowed)
What exactly happens when u add a int with a boolean? Why does it show an error?
Because the + operator is not defined for those operands.
Use the Boolean.toString() static method to get a string representation of the Boolean value:
Boolean.toString(a.startsWith("a"));
Related
This is more of theory question. I have this piece of code:
String[] contacts = new String[10];
for (int x = 0; x < contacts.length; x++)
{
contacts[x] = "Person" + x;
System.out.println(contacts[x]);
}
I understand that arrays can only have one type but I have concatenated the variable x (which is an int) on to the end of the String and stored this into an array.
However when I try to do this int based array it doesn't like it which makes sense because you can't mix types in an array that is declared to be holding int variables.
Im confused because you can add Boolean as well to the end of the statement.
contacts[x] = "Person" + x + false
As long as the array starts with a String you can get away with it.
Is this because the String in an object itself?
I'm really sorry if this is an obvious question. I believe this is related to this question but it doesn't quite answer it to my satisfaction Multiple type array
You're not adding multiple types into the array. Like in the following statement, any + operator that follows a string will concatenate the next variable as if it were parsed to a call to toString().
contacts[x] = "Person" + x + false
So the above is the same as;
contacts[x] = "Person" + Objects.toString(x) + Objects.toString(false)
Note that in the above the variables x and the value false are auto-boxed.
Further reading;
Autoboxing and Unboxing - Official Tutorial
How does the String class override the + operator?
That's because if the first element is a string, then it calls toString() on x and it calls toString() on the boolean variable. So you'll just get Person1false, Person2false and so on. And they are all String.
Print them out, you'll see.
int x = 20;
double d = 3.1416;
String s ="H";
those are my variables and I have to give the type the next lines evaluate to.
d/x + "";
is evaluating to double variable type (0.15708), is that correct?
You'd be right if we didn't have that pesky "" at the end!
Add "" to the end of something like this makes it into a String. It can actually be a handy shortcut - instead of having to use something like String.valueOf(), you could just do 4/2 + "", which makes it into a string.
To reiterate,
d/x would be a double, since you are adding a floating point.
But a double + "" = String.
I hope that helps. Good luck :)
You are wrong.
d/x + ""; is a String. This happens because when you are using the + operator, if any of the 2 sides is a String, then string concatenation happens and of course the result is a String.
By the way you can check that indeed it is a String by using the getClass() method. Note that if you remove the "" and use the getClass() you will get an error. This happens because d/x is a double, i.e a primitive type, so it can't use the method getClass(). In your example:
System.out.println((d/x + "").getClass()); will return java.lang.String
I have code like this :
int [] arrayOfImages = new int[namesOfSubjectsColorCode.size()];
int y = 0;
for (int x = 0 ; x<namesOfSubjectsColorCode.size();x++) {
nameOfColorCode = namesOfSubjectsColorCode.get(x);
String str = "com" + "." + "nyurals" + "." + "R" + "." + "drawable" + "." + nameOfColorCode;
arrayOfImages[y] = Integer.parseInt(str);
// Integer.parseInt(str);
y++;
}
Here, I have created integer array. Then, I have created string and by using Integer.parseInt() I want to convert it to int so that, my array of integer should generate dynamically. It is giving NumberFormatException.
Please suggest to me a solution for this.
There is no way for this String to be reasonably turned into an int.
String str = "com" + "." + "nyurals" + "." + "R" + "." + "drawable" + "." + nameOfColorCode;
Something like this would be expected:
String str = "1";
Its obvious that it gives you NumberFormatException. Look at your code :
Your str variable contains String which cant parse into Integer value.
Argument for Integer.parseInt() is invalid, you can't pass it string like "com.nyurals.." etc
From the docs:
public static int parseInt(String s)
throws NumberFormatException
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
And that's exactly what you're getting: NumberFormatException.
EDIT:
You probably want to do something like this:
nameOfColorCode = namesOfSubjectsColorCode.get(x);
String str = "" + nameOfColorCode;
int resourceId = this.getResources().getIdentifier(str, "drawable", this.getPackageName());
arrayOfImages[y] = resourceId;
y++;
If you want to get the int (id) of a resource than you should use
Resources res = activity.getResources();
res.getIdentifier("name","resourceType",activty.getPackageName());
change the name with actual name and resourceType with actual resource type (drawable,color,etc);
As others wrote you don't have an int in your string, it's just an int and not a reference to resoruce
You can access the constants you're trying to reference via http://docs.oracle.com/javase/tutorial/reflect/ but you really don't want to do that.
You'd be better served putting the int's in some form of map of which you can then select some kind of subset dependent on changing information
Integer.parseInt() expects to be given an integer of some sort, not a string of the format com.nyurals.R.drawable.<<nameOfColorCode>>.
Generally, in Android, you would access the variables directly with something like:
R.drawable.SomeName
rather than trying to decode (or, in your case, directly using) the string to get a value.
For example, the following code gets the surface view based on an ID:
SurfaceView sv = (SurfaceView)findViewById(R.id.PfrRightAntiView);
If you do need to dynamically extract a resource based on a string known only at runtime, look into Resources.getIdentifier(), an example of which can be found here.
As per this article, that method may not be the fastest. It may be better to use the reflection method as shown in that link.
May your str returns null so Integer.parseInt(null) return number format exception
I have a doubt which follows.
public static void main(String[] args) throws IOException{
int number=1;
System.out.println("M"+number+1);
}
Output: M11
But I want to get it printed M2 instead of M11. I couldn't number++ as the variable is involved with a for loop, which gives me different result if I do so and couldn't print it using another print statement, as the output format changes.
Requesting you to help me how to print it properly.
Try this:
System.out.printf("M%d%n", number+1);
Where %n is a newline
Add a bracket around your sum, to enforce the sum to happen first. That way, your bracket having the highest precedence will be evaluated first, and then the concatenation will take place.
System.out.println("M"+(number+1));
It has to do with the precedence order in which java concatenates the String,
Basically Java is saying
"M"+number = "M1"
"M1"+1 = "M11"
You can overload the precedence just like you do with maths
"M"+(number+1)
This now reads
"M"+(number+1) = "M"+(1+1) = "M"+2 = "M2"
Try
System.out.println("M"+(number+1));
Try this:
System.out.println("M"+(number+1));
A cleaner way to separate data from invariants:
int number=1;
System.out.printf("M%d%n",number+1);
System.out.println("M"+number+1);
Here You are using + as a concatanation Operator as Its in the println() method.
To use + to do sum, You need to Give it high Precedence which You can do with covering it with brackets as Shown Below:
System.out.println("M"+(number+1));
System.out.println("M"+number+1);
String concatination in java works this way:
if the first operand is of type String and you use + operator, it concatinates the next operand and the result would be a String.
try
System.out.println("M"+(number+1));
In this case as the () paranthesis have the highest precedence the things inside the brackets would be evaluated first. then the resulting int value would be concatenated with the String literal resultingin a string "M2"
If you perform + operation after a string, it takes it as concatenation:
"d" + 1 + 1 // = d11
Whereas if you do the vice versa + is taken as addition:
1 + 1 + "d" // = 2d
I'm having a minor issue with Java String comparisons.
I've written a class which takes in a String and parses it into a custom tree type. I've written a toString class which then converts this tree back to a String again. As part of my unit tests I'm just checking that the String generated by the toString method is the same as the String that was parsed in the first place.
Here is my simple test with a few printouts so that we can see whats going on.
final String exp1 = "(a|b)";
final String exp2 = "((a|b)|c)";
final Node tree1 = Reader.parseExpression2(exp1);
final Node tree2 = Reader.parseExpression2(exp2);
final String t1 = tree1.toString();
final String t2 = tree2.toString();
System.out.println(":" + exp1 + ":" + t1 + ":");
System.out.println(":" + exp2 + ":" + t2 + ":");
System.out.println(exp1.compareToIgnoreCase(t1));
System.out.println(exp2.compareToIgnoreCase(t2));
System.out.println(exp1.equals(t1));
System.out.println(exp2.equals(t2));
Has the following output; (NB ":" - are used as delineators so I can ensure theres no extra whitespace)
:(a|b):(a|b):
:((a|b)|c):((a|b)|c):
-1
-1
false
false
Based on manually comparing the strings exp1 and exp2 to t1 and t2 respectively, they are exactly the same. But for some reason Java is insisting they are different.
This isn't the obvious mistake of using == instead of .equals() but I'm stumped as to why two seemingly identical strings are different. Any help would be much appreciated :)
Does one of your strings have a null character within it? These might not be visible when you use System.out.println(...).
For example, consider this class:
public class StringComparison {
public static void main(String[] args) {
String s = "a|b";
String t = "a|b\0";
System.out.println(":" + s + ":" + t + ":");
System.out.println(s.equals(t));
}
}
When I ran this on Linux it gave me the following output:
:a|b:a|b:
false
(I also ran it on Windows, but the null character showed up as a space.)
Well, it certainly looks okay. What I would do would be to iterate over both strings using charAt to compare every single character with the equivalent in the other string. This will, at a minimum, hopefully tell you the offending character.
Also output everything else you can find out about both strings, such as the length.
It could be that one of the characters, while looking the same, may be some other Unicode doppelganger :-)
You may also want to capture that output and do a detailed binary dump on it, such as loading it up into gvim and using the hex conversion tool, or executing od -xcb (if available) on the captured output. There may be an obvious difference when you get down to the binary examination level.
I have some suggestions
Copy each output and paste in Notepad (or any similar editor), then
copy them again and do something like this
System.out.println("(a|b)".compareToIgnoreCase("(a|b)"));
Print out the integer representation of each character. If it is a weird unicode, the int representation will be different.
Also what version of JDK are you using?