evaluating variable int/string - java

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

Related

Concatenation of Boolean and Int

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"));

I thought you couldn't mix types in an array (Java)

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.

Why my code is giving NumberFormatException?

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

Java printing a String containing an integer

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

Why is string comparison failing in my code?

I have an array in containing numbers that represent cable sizes (1, 1.5, 2.5, etc), stored as strings.
In my program, the array is loaded into a spinner, which is working fine.
However, when the item is selected and stored in a variable, I want to check what string was selected, and set another numerical variable to 2.5 so I can do a calculation later in the program.
I tried the following:
if (conductorSize = "1" ) {conCsa = 1;}
else if (conductorSize = "1.5") {conCsa = 1.5;}
conductorSize being the variable holding the selected string, and conCsa being the variable
set to a numerical variable for calculation.
The compiler says that I cannot convert a string to boolean. What's happening?
If you are doing string comparisons, use .equals()
Example taken from here:
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT <<<<<<<<<<<<< Use this.
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
As Ed S. points out you are using the assignment operator. However since you are comparing a String you need to use the equals method.
if ("1".equals(conductorSize)) {conCsa = 1;}
else if ("1.5".equals(conductorSize)) {conCsa = 1.5;}
Alternatively, you could just create a new float from your String:
float conCsa;
try {
conCsa = Float.parseFloat(conductorSize);
}catch(NumberFormatException e){
conCsa = 0.0f; //set to a default value
}
It looks like what you're trying to do might better be expressed in this way:
conCsa = Double.parseDouble(conductorSize);
In general you need to use the .equals() method.
If performance is extremely important and you are comparing against string literals, take a look at String.intern(). It'll allow you to do super-fast == comparisons and avoid a full character-by-character scan as in .equals().
Performance would have to be really, really important though, to justify such a non-standard approach.
When you have cable sizes which are constants, you need to use Enums , which will help you in reducing no of if condition comparisons.

Categories