I have a code in which I need to divide an integer by a very big number e.g. 12345678912. I used long but it still gives error as The literal 12345678912 of type int is out of range.
Code for example:
public static void main(String[] args) {
//rest of the code
long x = 12345678912; //<--error is in this statement
System.out.println(y/x); //<---y is an integer which is having some value in rest of the code.
}
I know that the maximum value that an unsigned long can hold is 2^(64)-1. But then, I want to know, how to achieve this in Java? Is there any way to achieve it directly, or I need to implement any algorithm?
Java Language Specification
An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).
You need to tell that the data type is long by appending literal l or L
long x = 12345678912L;
Related
final long b = 123123;
final long c = 123123*123123*123123;
long d = b*b*b;
System.out.println(c);
System.out.println(d);
output :
-162426261
1866455185461867
In the case of the first printout, it seems that overflow occurs because Java treats it as an integer rather than a long one, but why is it not calculated as an integer in the second case? I thought that if I put final in front of long and make it a constant, it would be calculated in compile time, so I thought that the second and first output sentences should have the same result, but I want to know why I was wrong.
Because numeric literals without a decimal point in Java treated as int, variable c gets initialized with an overflown result of int multiplication.
Conversely, variable d is assigned to a result of multiplication that is done on long values (because b is of type long).
Basically you have:
long c = int * int * int; // multiply `int` numbers and then promote an overflown result into `long`
long d = long * long * long;
I thought that if I put final in front of long and make it a constant, it would be calculated in compile time
Variables b and c are compile-time constants, because they are primitive, marked as final, assigned at the moment of declaration and initialized with constant expressions. All accuracies of these variables in the code would be replaced with their values. But it doesn't change how the value of c is calculated.
Variable d isn't a compile-time constant because it has no final modifier. But this fact also has no effect on the way how its value is calculated.
Since your value of c won't contain decimal points, it will be treated as an int. To solve this just add "L"(L stands for long)
final long c = 123123L*123123L*123123L;
public class MyClass {
public static void main(String args[]) {
final long b = 123123;
final long c = 123123L*123123L*123123L;
long d = b*b*b;
System.out.println(c);
System.out.println(d);
}
}
Output
1866455185461867
1866455185461867
Is long allowed inside of for loop in java? If yes, why does eclipse shows an error while putting a long value, If no, what is the maximum value that can be used inside a for loop as iterator?
Yes it is allowed. This works just fine
for(long l=0;l<Long.MAX_VALUE;l++){
System.out.println(l);
}
It is allowed, look:
for (long lng = 1L; lng < Long.MAX_VALUE; lng++) {
// your code
}
To see max long value that you can assign, you can use:
System.out.println(Long.MAX_VALUE);
Notice that I put L after literal 1 (it's 1L) when assigning value to long, to avoid error when trying to assign value exceeding Integer range (this error would occur when if you tried to assign value greater than Integer.MAX_VALUE to variable of type long without using long literal (this literal is upper- or lowercase 'L' character after digits, without 'L' it's integer literal and compiler checks that this number is currently out of int range).
When for 1 in my example this L was redundant, for numbers greater than Integer.MAX_VALUE it's necessary.
Without any code I can only guess, but I assume you're trying to use a value that's too big to fit into an int literal where you want a long.
For example:
for(long x = 0; x < 9876543210; x++) {
...
}
This code will produce The literal 9876543210 of type int is out of range because although you defined x to be of type long, the literal you're using here is interpreted as int and is therefore too big.
To fix this, you need to explicitly tell the compiler, that you mean a long literal by appending a l or L to the value (upper-case L is preferred, because you can better tell it apart from a 1):
for(long x = 0; x < 9876543210L; x++) {
... ^- notice the 'L'
}
This question already has answers here:
Using the letter L in long variable declaration
(2 answers)
Closed 5 years ago.
What's the difference between the following?
long var1 = 2147483647L;
long var2 = 2147483648;
(or any primitive variable declaration)
Does it have any performance issue with or without L? Is it mandatory?
In the first case you are assigning a long literal to a long variable (the L or l suffix indicates long type).
In the second case you are assigning an int literal (that's the default type when no suffix is supplied) to a long variable (which causes an automatic type cast from int to long), which means you are restricted to the range from Integer.MIN_VALUE to Integer.MAX_VALUE (-2147483648 to 2147483647).
That's the reason why
long var2 = 2147483648;
doesn't pass compilation (2147483648 is larger than Integer.MAX_VALUE).
On the other hand
long var2 = 2147483648L;
would pass compilation.
For easy understanding each of the type have range in java.
By default every digit you entered in java is either byte or short or integer.
short s = 32767;
byte b = 127;
int i = 2147483647;
So if you assign anything except from their range you'll get compilation error.
int i = 2147483648; //compilation error.
Type range
And when you write long longNumber = 2147483647;
though it falls in long range but internally java treat it as
long l = (int) 2147483647;
you wont get any errors.
But if we assign beyond the range of integer like
longNumber = 2147483648; we will get compilation error as
long o = (int) 2147483648;
here java will try to convert the 2147483648 to int but it is not in int range so widening error is thrown.
To indicate java that the number what we have written is beyond the integer range just append l or L to the end of the number.
so java will wide his range till long and convert it as
long o = (long) 2147483648;
By default every floating point or digit with floating points (.) are size of double. So when you write some digits with (.) java treat as a double and it must be in double range.
As we know the float range is smaller then double.
so when you write
float f = 3.14;
though it falls in double range but internally java treat this assignment as
float f = (double) 3.14;
here you are assigning the double to float narrowing which is not correct.
so either you have to convert the expression like that
float f = (float)3.14;
or
float f = 3.14f; // tell jvm to assign this in float range by appending **f** or **F**
If we don't mention the L with the value then value is considered to be int value.
It type casts the int to long automatically.
This question already has answers here:
Converting Chars to Ints in Java
(2 answers)
Closed 8 years ago.
Here is my code but I am not getting how int getValue() method accepting char type as return value. How is it working? could any body please explain me how this method is working?
public class CharToInteger {
private static Scanner input;
public static int getValue(char character){
return character;
}
public static void main(String[] args) {
input = new Scanner(System.in);
System.out.println("Enter a character to get value of it:");
String inputString=(String) input.next();
char inputCharacter=inputString.charAt(0);
System.out.println(getValue(inputCharacter));
}
}
Thanks in advance :)
public static int getValue(char character){
return character;//<-- unicode value is being returned, e.g. char 0 -> int 48
// char ranges from 0 - 65535
}
From JSL:
5.1.4. Widening and Narrowing Primitive Conversion
The following conversion combines both widening and narrowing
primitive conversions:
byte to char
First, the byte is converted to an int via widening primitive
conversion (§5.1.2), and then the resulting int is converted to a char
by narrowing primitive conversion (§5.1.3).
see more:
OK, so first things first:
This is a widening primitive type conversion, so this is legal. You can:
int foo() { return 'a' /* character constant */ };
long foo() { return 3; /* int constant */ }
But you CANNOT DO:
char foo() { return 1; /* int constant */ }
int foo() { return 1L; /* long constant */ }
Second: what it returns is NOT THE ASCII CODE AT ALL. Java does Unicode.
It just happens that when Java was created, Unicode only defined code points fitting 16 bits; hence char was created as a 2 byte, unsigned primitive type (it is the only unsigned primitive type in Java) matching the then-called UCS-2 character coding (a 1 to 1 mapping between the coding and code points).
However, afterwards Unicode went "wide" and code points outside the BMP (ie, greater than U+FFFF) appeared; since then UCS-2 became UTF-16, and code points outside the BMP require two chars for one code point (a leading surrogate and a trailing surrogate; in previous Unicode versions, and in the Java API, those were called resp. high and low surrogate). A char is therefore now a UTF-16 code unit.
It is still true, however, that for code points in the BMP, the char value exactly matches the code point.
Now, in order to "fix" your program to accurately display the "character value", ie the code point, for each possible entry, you would do that (Java 8):
public static void main(String[] args) {
final Scanner input = new Scanner(System.in);
System.out.println("Enter a character to get value of it:");
String inputString = input.next();
// Print -1 on an empty input
final OptionalInt codepoint = inputString.codePoints().findFirst();
System.out.println(codepoint.isPresent() ? codepoint.get() : -1);
}
This will also handle code points outside the BMP.
char is effectively an unsigned 16-bit integer type in Java.
Like other integer types, you can perform an assignment conversion from an integer constant to any integer type so long as it's in the appropriate range.
And it is legal to ,
public static int getValue(char character){
return character;
}
This is because char in java is 2 bytes and int is 4 bytes. So it is a widening conversion, which happens implicitly in Java. The return value is the ASCII value on the input character.
Char is UTF-16 code representation - read it as 2-byte integral value. int is 4-byte integral value. Java can implicitly cast smaller sized integrals to larger ones - char to int, int to long, because conversion this way doesn't lead to precision or data loss.
The vice versa way doesn't work - you cannot implicitly convert int to char and long to int, because int has a much wider range of possible values than char.
Put simply, Java is willing to implicitly convert a char to an int.
It will convert it to a 16-bit Unicode value.
If the input were 'A' you will get '65' as your output.
It's arguable (by me!) that characters and integers are sufficiently different that the language shouldn't be so sloppy as from time to time it can lead to surprise behaviour.
If you want chapter and verse look at Sec 5.1.2 here:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
the below code gives me -1894967296 as result but this is not expected. What is exactly happening? I can't figure it out. The result has to be 2400000000 as per my calculator :(
import java.util.List;
import java.util.ArrayList;
public class Calculate{
public static void main(String []args){
int result = 1;
List<Integer> integer = new ArrayList<Integer>();
integer.add(100);
integer.add(200);
integer.add(300);
integer.add(400);
for (Integer value : integer) {
result *= value;
}
System.out.println(result);
}
}
When I debug, it works correctly till the third iteration.
Update:
As per the answers, the int primitive type range has been exceeded but what will happen to the int variable? It will be defaulted to some value?
The largest number Java can store in an int is 2^31 - 2147483648
2400000000 is larger than that so "wraps around".
You need to use a 64 bit data type such as long.
2400000000 is too large to store in an int. It would be more appropriate to use a long which has a minimum value of -2^63 and maximum value of 2^63 - 1 which your number is well within the range of.
more info here
The expected result 2400000000 > Integer.MAX_VALUE. So, use long instead of int to store result.
Use BigInteger instead of int because the int is limited
Java doc:
int: By default, the int data type is a 32-bit signed two's complement integer, which has a > minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
That's what most programmer call Pillage. You shouldn't save a long value inside a small variable, don't expect an Int to save a value 2^31+.
For what you want to do there's a long