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'
}
Related
So this the line with the precision error fault;
A[i]= m % 3;
m is long
A is int[];
And my error is
error: possible loss of precision
A[i]= m % 3.
required int
found long.
How can I have error when the only potential answers are 0,1,2?
Isn't there another way than declaring A as long[]?
It's a potentially big array so I don't want that (in fact I would even prefer for A to be short[])
Also I tried error: A[i]= m % 3L , but same result.
The compiler doesn't look at the result, it looks at the type. The type of m%3 is long, and you are trying to put it into an int.
So, the compiler is angry, because potentially, the value stored in a longis bigger than the one you can store into an int.
In order to remove the problem, you have to cast the result back into an int:
A[i] = (int) (m % 3);
However, you can do this because you know the result is 0,1 or 2. If you do not know the value of the long you are casting, you may have an integer overflow:
public static void main(String[] args) {
long l = Integer.MAX_VALUE + 1L;
System.out.println(l);
// 2147483648
System.out.println((int)l);
// -2147483648
}
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;
I have this question that has completely stumped me.
I have to create a variable that equals Integer.MAX_VALUE... (in Java)
// The answer must contain balanced parentesis
public class Exercise{
public static void main(String [] arg){
[???]
assert (Integer.MAX_VALUE==i);
}
}
The challenge is that the source code cannot contain the words "Integer", "Float", "Double" or any digits (0 - 9).
Here's a succinct method:
int ONE = "x".length();
int i = -ONE >>> ONE; //unsigned shift
This works because the max integer value in binary is all ones, except the top (sign) bit, which is zero. But -1 in twos compliment binary is all ones, so by bit shifting -1 one bit to the right, you get the max value.
11111111111111111111111111111111 // -1 in twos compliment
01111111111111111111111111111111 // max int (2147483647)
As others have said.
int i = Integer.MAX_VALUE;
is what you want.
Integer.MAX_VALUE, is a "static constant" inside of the "wrapper class" Integer that is simply the max value. Many classes have static constants in them that are helpful.
Here's a solution:
int ONE = "X".length();
int max = ONE;
while (max < max + ONE) {
max = max + ONE;
}
or lots of variants.
(The trick you were missing is how to "create" an integer value without using a numeric literal or a number wrapper class. Once you have created ONE, the rest is simple ...)
A bit late, but here goes:
int two = "xx".length();
int thirtyone = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".length();
System.out.println(Math.pow(two, thirtyone)-1);
How did I go? :p
I do like that bitshift one though...
The issue is that the answer cannot contain: "Integer", "Float", "Double", and digits (0 - 9)
There are other things in Java which can be represented as an Integer, for example a char:
char aCharacter = 'a';
int asInt = (int) aCharacter;
System.out.println(asInt); //Output: 97
You can also add chars together in this manner:
char aCharacter = 'a';
char anotherCharacter = 'b';
int sumOfCharacters = aCharacter + anotherCharacter;
System.out.println(sumOfCharacters); //Output: 195
With this information, you should be able to work out how to get to 2147483647on your own.
OK, so an Integer can only take certain values. This is from MIN_VALUE to MAX_VALUE where the minimum value is negative.
If you increase an integer past this upper bound the value will wrap around and become the lowest value possible. e.g. MAX_VALUE+1 = MIN_VALUE.
Equally, if you decrease an integer past the lower bound it will wrap around and become the largest possible value. e.g. MIN_VALUE-1 = MAX_VALUE.
Therefore a simple program that instantiates an int, decrements it until it wraps around and returns that value should give you the same value as Integer.MAX_VALUE
public static void main(String [] arg) {
int i = -1
while (i<0) {
i--;
}
System.out.println(i);
}
public class Three {
public static void main(String[] args) {
Three obj = new Three();
obj.function(600851475143);
}
private Long function(long i) {
Stack<Long> stack = new Stack<Long>();
for (long j = 2; j <= i; j++) {
if (i % j == 0) {
stack.push(j);
}
}
return stack.pop();
}
}
When the code above is run, it produces an error on the line obj.function(600851475143);. Why?
600851475143 cannot be represented as a 32-bit integer (type int). It can be represented as a 64-bit integer (type long). long literals in Java end with an "L": 600851475143L
Append suffix L: 23423429L.
By default, java interpret all numeral literals as 32-bit integer values. If you want to explicitely specify that this is something bigger then 32-bit integer you should use suffix L for long values.
You need to use a long literal:
obj.function(600851475143l); // note the "l" at the end
But I would expect that function to run out of memory (or time) ...
The java compiler tries to interpret 600851475143 as a constant value of type int by default. This causes an error since 600851475143 can not be represented with an int.
To tell the compiler that you want the number interpretet as a long you have to add either l or L after it. Your number should then look like this 600851475143L.
Since some Fonts make it hard to distinguish "1" and lower case "l" from each other you should always use the upper case "L".
You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html).
This has nothing to do with function. Try using a long integer literal instead (as suggested in the other answers).
At compile time the number "600851475143" is represented in 32-bit integer, try long literal instead at the end of your number to get over from this problem.
Apart from all the other answers, what you can do is :
long l = Long.parseLong("600851475143");
for example :
obj.function(Long.parseLong("600851475143"));
Or, you can declare input number as long, and then let it do the code tango :D ...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
long n = in.nextLong();
for (long i = 2; i <= n; i++) {
while (n % i == 0) {
System.out.print(", " + i);
n /= i;
}
}
}
I have an array of ints ie. [1,2,3,4,5] . Each row corresponds to decimal value, so 5 is 1's, 4 is 10's, 3 is 100's which gives value of 12345 that I calculate and store as long.
This is the function :
public long valueOf(int[]x) {
int multiplier = 1;
value = 0;
for (int i=x.length-1; i >=0; i--) {
value += x[i]*multiplier;
multiplier *= 10;
}
return value;
}
Now I would like to check if value of other int[] does not exceed long before I will calculate its value with valueOf(). How to check it ?
Should I use table.length or maybe convert it to String and send to
public Long(String s) ?
Or maybe just add exception to throw in the valueOf() function ?
I hope you know that this is a horrible way to store large integers: just use BigInteger.
But if you really want to check for exceeding some value, just make sure the length of the array is less than or equal to 19. Then you could compare each cell individually with the value in Long.MAX_VALUE. Or you could just use BigInteger.
Short answer: All longs fit in 18 digits. So if you know that there are no leading zeros, then just check x.length<=18. If you might have leading zeros, you'll have to loop through the array to count how many and adjust accordingly.
A flaw to this is that some 19-digit numbers are valid longs, namely those less than, I believe it comes to, 9223372036854775807. So if you wanted to be truly precise, you'd have to say length>19 is bad, length<19 is good, length==19 you'd have to check digit-by-digit. Depending on what you're up to, rejecting a subset of numbers that would really work might be acceptable.
As others have implied, the bigger question is: Why are you doing this? If this is some sort of data conversion where you're getting numbers as a string of digits from some external source and need to convert this to a long, cool. If you're trying to create a class to handle numbers bigger than will fit in a long, what you're doing is both inefficient and unnecessary. Inefficient because you could pack much more than one decimal digit into an int, and doing so would give all sorts of storage and performance improvements. Unnecessary because BigInteger already does this. Why not just use BigInteger?
Of course if it's a homework problem, that's a different story.
Are you guaranteed that every value of x will be nonnegative?
If so, you could do this:
public long valueOf(int[]x) {
int multiplier = 1;
long value = 0; // Note that you need the type here, which you did not have
for (int i=x.length-1; i >=0; i--) {
next_val = x[i]*multiplier;
if (Long.MAX_LONG - next_val < value) {
// Error-handling code here, however you
// want to handle this case.
} else {
value += next_val
}
multiplier *= 10;
}
return value;
}
Of course, BigInteger would make this much simpler. But I don't know what your problem specs are.