Beginner Java Question about Integer.parseInt() and casting - java

so when casting like in the statement below :-
int randomNumber=(int) (Math.random()*5)
it causes the random no. generated to get converted into an int..
Also there's this method I just came across Integer.parseInt() which does the same !
i.e return an integer
Why two different ways to make a value an int ?
Also I made a search and it says parseInt() takes string as an argument.. So does this mean that parseInt() is ONLY to convert String into integer ?
What about this casting then (int) ?? Can we use this to convert a string to an int too ?
sorry if it sounds like a dumb question..I am just confused and trying to understand
Help ?

Integer.parseInt does not do the same thing as a cast.
Let's take a look at your first example:
int randomNumber=(int) (Math.random()*5)
Math.random returns a double, and when you multiply a double by an int Java considers the result to be a double. Thus the expression Math.random()*5 has a type of double. What you're trying to do is assign that value to a variable of type int. By default Java will not allow you to assign a double value to a variable of type int without your explicitly telling the compiler that it's ok to do so. Basically you can think of casting a double to an int as telling the compiler, "I know this int variable can't hold the decimal part of this double value, but that's ok, just truncate it."
Now take a look at the conversion of a String to an int:
int value = Integer.parseInt("5");
The string "5" is not immediately convertible to an integer. Unlike doubles, which by definition can be converted to an integer by dropping the decimal part, Strings can't be easily or consistently converted to an int. "5", "042", and "1,000" all have integer representations, but something like "Hello, World!" does not. Because of this there is no first order language feature for converting a String to an int. Instead, you use a method to parse the String and return the value.
So to answer all your questions:
Why two different ways to make a value an int ?
You have to take into account what the type of the value you are converting is. If you're converting a primitive to an int you can use a cast, if you're converting an Object you'll need to use some sort of conversion method specific to that type.
Also I made a search and it says parseInt() takes string as an argument.. So does this mean that parseInt() is ONLY to convert String into integer ?
Correct. You cannot pass any other type to the parseInt method or you will get a compiler error.
What about this casting then (int) ?? Can we use this to convert a string to an int too ?
No, casting to int will only work for primitive values, and in Java a String is not a primitive.

In your example, you are casting a floating-point number to an int. Integer.parseInt(), however, reads an integer value from a String.

You can only cast between compatible types (I'd link to the JLS but that might be too much for a beginner question).
Casting is basically just taking a value and saying, "Hey, this thing that was a double? Now it's an int. So there."
You can't do that with a string because it isn't anything like an int. You have to instead parse an int out of it, which is actually a lot harder than it sounds. Fortunately, it's already implemented for you so you don't have to worry about how it works.

Casting can only convert from one numeric type to another. Interpreting a string (aka parsing) needs to be done with a method call.

Let's start from the top.
int randomNumber=(int) (Math.random()*5);
Yes, this does indeed give a random integer between 0 and 4, but this is very much not the proper way of doing this. You see, if you forget a parenthesis, i.e. you type
int notSoRandomNumber=(int) Math.random()*5;
you'll always get 0 because casting has higher precedence than multiplication. That is to say the result of Math.random() is first coerced into an integer, which will always be 0 and then it's multiplied by 5, which is still 0.
I'd favour using java.util.Random for generating random integers. q.v. http://java.sun.com/javase/6/docs/api/java/util/Random.html#nextInt(int).
Casting can only be done between "compatible types". For primitive types and their wrappers (i.e. int, Integer, long, Long, &c.) you can always cast between them with the caveat that some conversions lose information. e.g. when casting a long to an int, the long may contain a number larger than Integer.MAX_VALUE]. This kind of casting Java basically got from C++ which it in turn got from C.
As for casting objects, it's actually simpler. Simply ask "is this object, o, an X?" If so then (X) o makes sense and has static type X. If o is not an X and you try to cast anyway, you'll get a ClassCastException signifying that o's dynamic (runtime) type is not compatible with X. This will probably make a lot more sense later when you get the difference between the static and the dynamic (runtime) type of objects.

Following code convert String to int without any methods
public class MyStringToNumber {
public static int convert_String_To_Number(String numStr){
char ch[] = numStr.toCharArray();
int sum = 0;
//get ascii value for zero
int zeroAscii = (int)'0'; // '0'=48 zeroAscii=48
for(int i=0;i<ch.length;i++){
int tmpAscii = (int)ch[i]; // for 0 ch[i]=3,3=51, tempAscii=51
// (0*10)+(51-48)
// 0 +3
// 3
// sum=3
// for 1 ch[i]=2,2=50, tempAscii=50
sum = (sum*10)+(tmpAscii-zeroAscii); // 0 +(51-48)=3 sum=3
// (3*10)=30+(50-48)
// 30 + 2
// sum=32
// for 2 ch[i]=5, 5=53 tempAscii=53
// (32*10)+(53-48)
// 320 + 5
// 325
// sum=325
// for 3 ch[i]=6,6=54, tempAscii=54
// (325*10)+(54-48)
// 3250 +6
// 3256
// sum=3256
}
return sum;
}
public static void main(String a[]){
System.out.println("\"3256\" == "+convert_String_To_Number("3256"));
}
}
Output "3256" --> 3256

Parse() method is available is many formats, Integer class having the method ParseInt() which is a static method, we to call this method by Integer.ParseInt()
Similarly Double class having ParseDouble()and we call it as Double.ParseDouble().
The more Generic way is XXXX.ParseXXXX()
The main use of this Method is to convert any Object into a Primitive.
And here you can raise a question why we need to convert into Primitives?
The answer is, we know that primitives are stored in stack area and objects are stored in Heap area, and you doesn't want to waste the Heap Memory and you can convert an Object into a Primitive.
And the other thing, while accessing any Object there may be Overhead.
It is better to use as a Primitive.

Related

Default data type of the constants printed in System.out.print();

System.out.println(2147483647 + 1); //prints -2147483648
I know 2147483647 is the max value of integer data type. My question is why is this result calculated for Integer type, and why was it not considered for Long or double?
Because...
System.out.println(127+1); //prints 128
here why is 127 not considered for Byte data type, resulting in the result to be -128?
Fundmentally, you seem to not fully understand literals. A number without a decimal point or suffix is always an int, regardless of it's magnitude. This can be further complicated by implicit widening when assigning to larger primitive datatypes (e.g. int may be implicitly widened to long).
So now we know that your two literals are ints. int + int is always int. It doesn't matter whether the result will overflow or not.
If you know or suspect that the constants will exceed the range of int, add the suffix L (i.e. 2147483647L and 1L) to explicitly declare that these are longs. long + long = long, so the result will not overflow in this case.
println is overloaded with several inputs, your paramters are of type int so method will be called
public void print(int i) {
write(String.valueOf(i));
}
Every number in java sorce code is by default an integer. If you like to have an other type like long, you need to extend your number with an 'L' (e.g. 23409L) or you have to cast it. Only at initialization from a variable the compiler make the cast for you.
In many cases you can give byte or short also to methodes, even if they request for an integer parameter. But this only works because of java's conversions and promotions mechanism.
Because of all this functionalities some programmer mess up with the real data types they have at one point of the code.
For more infos visit the oracle documentation:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

Why can't results of arithmetic expressions including int and long variables be assigned back to int variable?

I know that numeric literals in Java are by default of the type int.
So the 5 in the following example actually is an int as long as I don't write an 'L' behind it. So why can't I assign the result of a*b back to an int variable, if 5 and 7 are both of the type int?
long a = 5;
int b = 7;
int c = a * b;
I do not understand why Java has problems seeing something like this as long:
long a = 345236577970;
but still performs a typecast if the expression includes a long variable, even though its type is actually int. Super basic beginner question, sorry.
Your reasoning is that 5 and 7 (both int) are assigned to variables which are then multiplied so the result should be an int. The flaw in this reasoning is that your code is not multiplying 5 and 7, but a and b. Once constants are assigned to these variables it's irrelevant what the type of the constant is: the only thing that matters is the type of the variable. In this case the types are long and int so the result is a long.
Simple options to convert to int is to cast or to use Math.toIntExact
Before the computation is done, there's no way to know what the result will be (which seems obvious but sometimes needs to be said out loud). It could be a result that could fit in an int, but it might not be -- it could be a long. So the language is designed to require that the result be of a type that could fit the largest possible range of results.
If you want to stuff the final result back into an int, you can certainly cast it into an int variable, but you do open yourself up to the risk that the result might not fit in there.

Cannot cast double as int

I'm having a problem in my script where it says I can't convert a double to an integer...
Here's the where the error is noted in the bat:
cm.getPlayer().yellowMessage("You have gained " +
getJQ.getCurrentMap() + " JQ points!");
The error is off of the method getCurrentMap(), which is here...
public int getCurrentMap() {
return maps.get((level - 1));
}
Level is an integer that is incremented every time the player advances a level. What I don't understand is how I'm receiving that error. When I print out the List<Integer> maps, I get a list of numbers. I don't see what's wrong.
Here is how I declare it:
private int level = 0;
Image of Error:
Code:
Code - Look at the methods getCurrentMap and the declaration of maps in the file. Ignore everything else.
Source Code: As you can see level is declared as an int, and getCurrentMap() only details with integers. There main lines that deal with this error are lines 29-32, and lines 59-61, where I push an array with a random value.
If level is a double then the result is a double as well. Java won't convert it to an integer because that would lose information. So you have to make it explicit:
return maps.get((int) (level - 1));
If level (or any other int) is retrieved from JavaScript, the code will not even be executed however. You are assigning a double from JavaScript to an int, so it never even reaches your Java code. Accept a double from JavaScript, then convert it to an integer by casting using (int).
You may want to use Math.ceil first - or another rounding method - if you want to round up instead of down.
If you want to create an integer from a double, use a function like Math.ceil or Math.round. Otherwise it is ambiguous how the conversion should be done.
JavaScript doesn't have integers, everything is a floating point value. So somewhere you have some floating point value you're getting from JavaScript that you're trying to treat as an integer. Where this happens is unclear from your question.
Casting something to a class that it isn't a subclass of will fail; Double and Integer are both subclasses of Number, you can cast a Double to a Number but not to an Integer. If you have a double value you want to convert to an integer, you could call a conversion method on the object wrapper for Double:
new java.lang.Double(10.001D).intValue();
which returns the integer part and discards any fractional part.

why casting double to int is possible but casting double to String is not possible?

I convert other type to String by String.valueOf() like following:
String s = String.valueOf(2.5);
i also convert double to int by casting like following:
int i = (int) 2.5 ;
i want casting double to String like following:
String s = (String) 2.5;
but i give following error:
Cannot cast from double to String
why casting double to int is possible but casting double to String is not possible?
Casting from one primitive type to another is standard, well understood and supported in machine code. I.e. Java just gives you the syntax to produce the appropriate machine code.
Even C language had support for this.
Converting to objects is different as it requires you to call a library and even though C++ has operator overloading to support such conversions, it is not a cast as such. C and Java do not support implicit conversion like this.
BTW The simplest way to convert to a String is to use the following.
primitive p = ...
String s = "" + p;
This is not efficient as it uses a StringBuilder, however it's not efficient to create a String either so it's only not as bad, rather than being very good. btw I have libraries to turn primitives to/from text without creating objects.
However, I use this because it is more efficient for the developer and I waiting for a profiler to tell me this is not good enough in which case I wouldn't use String.valueOf() either.
double a = 44;
String b = String.valueOf(a);
double and int are both numeric types, thus they can be converted by casting.
String is not a numeric type.
According to Java specifications, you need to convert the primitive type first:
Any type may be converted to type String by string conversion.
A value x of primitive type T is first converted to a reference value
as if by giving it as an argument to an appropriate class instance
creation expression (ยง15.9):
If T is boolean, then use new Boolean(x).
If T is char, then use new Character(x).
If T is byte, short, or int, then use new Integer(x).
If T is long, then use new Long(x).
If T is float, then use new Float(x).
If T is double, then use new Double(x).
This reference value is then converted to type String by string
conversion.
Then
(...) the conversion is performed as if by an invocation of the toString
method of the referenced object with no arguments; but if the result
of invoking the toString method is null, then the string "null" is
used instead
See 5.1.11. String Conversion in http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
#Samiey Mehdi : I will give u what happens when U Type Cast From one format to another ..
Example
Double a = 2.5; // consider it
step 1:first machine will convert this number into binary format ..
double a =(0000 0000 0010.0101);
step 2:when your type casting it into int .. first it will remove decimals.. lets make the binary into (0000 0000 0010)
step 3: it will truncate it into 32 bit after it is completely fallen into int range then it will print the value. int range( -2,147,483,648 to 2,147,483,647)
it will print now
Note: if the value of the non decimal is more than range of type cast it will lose the data or digit (shrinks it)and prints the remaining value
But In Case of String Format .. Step two fails .. it cant able to convert the value of binary digit into string range [bcos string don't have any range]. so it will print incompatible types [compile time error].................

What does a 'int' in parenthesis mean when giving a value to an int?

Here's an example I have.
public int getDelta()
{
long time = getTime();
int delta = (int) (time - lastFrame);
lastFrame = time;
return delta;
}
In the fourth line, there's an "(int)". What does it mean?
This code is just an example I found with it; I'm not looking for a specific answer to the code I posted. What the (int) even does, generally. I've seen it done with (byte) too.
It means you're casting a long into an int. See: http://en.wikipedia.org/wiki/Type_conversion
You can't just say
int delta = (time - lastFrame);
Because time and lastFrame are longs (I'm assuming lastFrame is, at least). Therefore you must convert the type (cast) the result of that subtraction into an integer value.
When you cast with (int), you discard any fraction number after the floating point. For example:
System.out.println((int) 15.5); // prints 15
That is cast to the primitive data type int. It will try casting the result produced by the calculation (which would be a long type in this case)into a primitive int (Integer) type.
So, if you had a result of 16.253353 from that line (as an example), the cast would return just 16, since int doesn't deal with decimal places, only whole numbers.
It's a conversion operator. It converts (time - lastFrame) to an integer.
As both time and lastFrame are long ints, there is no need for rounding.
If you had either a float or a double, the difference there might have been rounded down.
In your case it just uses a smaller data type: int, rather than long.
(typename) value or variable is called casting. It tells Java to treat the value as the type stipulated in the cast. Sometimes it's necessary because a method already written returns a type that's too big - you need an int and the method returns a long. Sometimes its used to cast a superclass to a subclass so that methods in the subclass can be called. If you cast primitives to other types make sure the size of the variable is "big" enough to hold the value or you'll get wierd overflow values. If you cast an object to a different type you have make sure the object is the correct type or you'll get a ClassCastException, for example - casting a String to a Date won't work because they're not in the same class hierarchy.
This cast are used to ensure that result will be returned in a int value. In this case, time is a long value (probably int64) to use getTime() function. But for delta you need to casto it to a int (int32) value. This cast can loose values.
Stating the data type in parenthesis makes the compiler perform an explicit cast to that type.
It can be done with any type/object. For instance:
MyObject myobject = (MyObject) MyArray[0];
In your code I believe it will define your resulting variable as an int and not date.

Categories