number « Integer « Java Data Type Q&A

1. String to Int in java - Likely bad data, need to avoid exceptions

Seeing as Java doesn't have nullable types, nor does it have a TryParse(), how do you handle input validation without throwing an exceptions? The usual way:

String userdata = /*value from gui*/
int val;

2. Integer with leading zeroes

when i write

i get
why it works that way?

3. Find out number of bits needed to represent a positive integer in binary?

This is probably pretty basic, but to save me an hour or so of grief can anyone tell me how you can work out the number of bits required to represent ...

4. Large Numbers in Java

How would i go about doing calculations with extremely large numbers in Java? i have tried long but that maxes out at 9223372036854775807, and when using an integer it does not ...

5. Way to get number of digits in an int?

Is there a neater way for getting the length of an int as this?

int length = String.valueOf(1000).length();

6. How to do an Integer.parseInt() for a decimal number?

The Java code is as follows:

String s = "0.01";
int i = Integer.parseInt(s);
However this is throwing a NumberFormatException... What could be going wrong?

7. hex to int number format exception in java

I am getting a number format exception when trying to do it

int temp = Integer.parseInt("C050005C",16);
if I reduce one of the digits in the hex number it converts but not otherwise. why ...

8. How to round *down* integers in Java?

I'd like to round integers down to their nearest 1000 in Java. So for example:

  • 13,623 rounds to 13,000
  • 18,999 rounds to 18,000
  • etc

9. Check if int is between two numbers

Why can't do you this if you try to find out whether an int is between to numbers:

if(10 < x < 20)
Instead of it, you'll have to do
if(10<x && x<20)
which seems ...

10. How might I count the number of int members defined for a Java class?

I have a class that stores a large number of int member variables, each defined as follows:

public final static int int1 = int1value;
public final static int int2 = int2value;
public final static ...

11. In java is it possible to pack a integer number that is expected not to be negative & be final (not overflow) into a short?

"Unsigned int" into a short and back. Is this possible? How to do it if so? Grrrr. I forgot how signed numbers are implemented. The question makes no sense. Thanks anyway. I ...

12. Convert integer to equivalent number of blank spaces

I was wondering what the easiest way is to convert an integer to the equivalent number of blank spaces. I need it for the spaces between nodes when printing a binary ...

13. Checking if an int is prime more efficiently

I recently was part of a small java programming competition at my school. My partner and I have just finished our first pure oop class and most of the questions were ...

14. how to work with other base numbers in java?

Guys if the int c=10001; which is a binary value.If i want to process it like multiplying it by 10 how to do that?

15. Number for each enum item?

Is it possible to define something like this in java? C# code:

public enum Character
    A = 1,

    B = 2,

    C = 4,


16. How to get the separate digits of an int number?

I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0. How ...

17. What's the right way to represent phone numbers?

I'm having trouble representing a mobile number in one of my applications. I was wondering if there is an Integer class that will allow you to store such a number starting with ...

18. How to convert a string of numbers into integers?

I want to convert a string of 5 numbers separated by commas into integers and store them into an array.

// person class
public class Person {
    private String ...

19. Random number generator that generates integers for Java

I want to generate some random integers in Java, but this according to some distribution laws. More specific:

  • I want to generate some random integers for gaussian distribution. I found out only generators ...

20. JXL GetFormula() returns formula to string OK, but with .0 to every integers numbers

I'm using this piece of code to get a Cell formula with JXL :

FormulaCell c=null;
String f="";
try {
    c  = (FormulaCell) mySheet.getCell(C,R);
} catch (Exception e) {e.printStackTrace();}
try {

21. How can I convert an int number from decimal to binary?

How can I convert an int number from decimal to binary . for example int x=10; radix 10 how can i make another integer has the binary representation of x such as: int y=1010 radix ...

22. How can I do operations on big numbers that can't be stored in one variable

In Java, I would like to be able to do operations on really big integers (that can't be stored in a long), how can I do that? What is the best way ...

23. Does Java have mutable types for Integer, Float, Double, Long?

I am in a situation where I want to use mutable versions of things like Integer. Do I have to use these classes (below) or does Java have something built in?

24. Java Round up Any Number

I cant seem to find the answer im looking for regarding a simple question. How to round up any number to the nearest int? I.e. whether the number is 0.2, 0.7, 0.2222, 0.4324, ...

25. Why is Java offended by my use of Long.parseLong(String s, int radix) with this long binary number?

I have the following code: Why does Java think that this is not a valid long.

public void testOffendingBinaryString() {
  String offendingString = "1000000000000000000010101000000000000000000000000000000000000000";
  assertEquals(64, offendingString.length());
  Long.parseLong(offendingString, 2);

26. Why does this not result in 1000?

Possible Duplicate:
Java problem-Whats the reason behind and what will be probable output
long milli=24*60*60*1000;
long micro=24*60*60*1000*1000;
long result=micro/milli;
The result should be 1000 but its not. Why does ...

27. Java - Convert number to string

Given a number:

int number = 1234;
Which would be the "best" way to convert this to a string:
String stringNumber = "1234";
Thanks in advance!
I have tried searching (googling) for an answer but no ...

28. Converting a character to an integer if the character is already a number in java

I'm trying to read a string's character to get the numeric value. String cardNumber =;

  int currentIndex = cardNumber.length() - 1;
  while (currentIndex >= 0)


29. Very Large Numbers in Java Without using java.math.BigInteger

How would I go about doing arithmetic, + - / * % !, with arbitrarily large integers without using java.math.BigInteger? For instance, the factorial of 90 returns 0 in Java. I would ...

30. Integer.parseInt() doesn't parse large negative numbers

Why is NumberFormatException is thrown when i try Integer.parseInt("80000010", 16)?? That IS a 32-bit number, which is the size of java's int. EDIT: The best part is this...

int z = 0x80000010;
System.err.println("equal to ...

31. Checking if a number is an Integer in java

Is there any method or quick way to check whether a number is an Integer ( belongs to Z field) in java I thought of maybe subtracting it from the rounded number, ...

32. Convert a raw negative rgb int value back to a 3 number rgb value

Ok so I'm working on a program that takes in an image, isolates a block of pixels into an array, and then gets each individual rgb value for each pixel in ...

33. Java long Numbers Help

So at the top of my code I declared the variable private long counter; And when I try to give it a number that's really long it gives an error, Im trying to ...

34. Long vs Integer, long vs int, what to use and when?

Sometimes I see API's using long or Long or int or Integer, and I can't figure how the decision is made for that? When should I choose what?

35. How do I truncate a java integer to fit/exand to a given number of bytes?

I am designing an archive format(Just for fun) in Java using this template-

First 4 bytes: Number of files in the archive
Next 4 bytes: Number of bytes in the filename
Next N bytes: ...

36. Integer (number) to String

Here is my simple question We can convert integer, float, double to String like String s = "" + i; so why do we need String s = Integer.toString(i); ? just requirements ...

37. Given a number n and two integers p1,p2 determine if the bits in position p1 and p2 are the same or not. Positions p1,p2 and 1 based

I've been doing some little code quizes just to catch back up on my coding after graduating but this one got my stump. Here's the question: Given a number n and two ...

38. Problem with adding sorted number Strings to a SortedSet in Java

I created a my own SortedSet here is the code for adding something to the array. (I know there are better and simpler ways to do this than an Array but ...

39. Check for recurring numbers in a int[] Java

I want to be able to tell if a any number in an int[] appears 3 or more times? How can I do this? Would be awesome to have method

boolean hasTriples(int[] numbers) ...

40. What exactly does Double mean in java?

I'm extremely new to Java and just wanted to confirm what Double is? Is it similar to Float or Int? Any help would be appreciated. I also sometimes see the uppercase ...

41. How do I fix wrong numbers produced by integer overflow?

I had a bug that caused an integer overflow, resulting in wrong (negative) timestamps being written to the database. The code is fixed already, but I want to fix the wrong ...

42. How to convert string numbers into comma seperated integers in java?

Can any one give me some predefined methods or user defined methods to convert string numbers(example : 123455) to comma separated integer value (example : 1,23,455). Thanks in advance, sathish

43. Append two Integers, each representing a nibble, to a hexadec. number

I write the bitstream for a JPEG Encoder, I'm facing this problem: I built Pairs for the AC Cosinus Coefficients (after Quantization) in an int[]array. Each Pair: (Number of Zeros/ Category of ...

44. Number of digits and which digits it is in integer

Example int i=185; Then I want to get that 'i' contains 3 digits and those digits are 1,8, and 5.

45. Display first n digits of a number in Java

I am having difficulty of creating a method to display first n digits of a number when 'n' is determined by the user. For example, user inputs an integer '1234567' and ...

46. String.valueOf(i) vs "" + i or i + ""

I usually use "" + i for convenient. But compare about perfomance myself, I thought String.valueOf(i) will be faster. Is it right? Which one should I use? UPDATE: I've read your answers, ...

47. multiplication of two ints overflowing to result in a negative number

Consider this snippet from the Java language specification.

class Test {
public static void main(String[] args) {
int i = 1000000;
System.out.println(i * i);
long l = i;
System.out.println(l * l);
The output is
Why is the result ...

48. Check if a number is a double or an int

I am trying to beautify a program by displaying 1.2 if it is 1.2 and 1 if it is 1 problem is I have stored the numbers into the arraylist as ...

49. How can I place numbers at the end of an int (not summing)?

I'm busy with making an expression tree for school, I've already build the part in which the tree is being made and printing the result of the arithmetic expression also works.

50. How to write Numeric Unsigned, four bytes integer using the Apache Commons libs?

I have to write in a buffer some integer values. But in the API is specified that the number is Integer, Numeric Unsigned and must have at maximum 4 bytes . How ...

51. Variables craziness, rounding number (int,double etc.)

This is mine code, not fully finished, and sorry for Polish language but it's easy to get it. So, this is about vet, 4 variables are for price per visitor: 1. ...

52. Getting the wrong number when converting from byte[] to int

I am trying to convert an int to a byte[] and back again, but I think I am doing something wrong along the way. My code is basically:

byte[] array = new ...

55. Problem with using selectionSort on number input, says cannot be applied to int

Hello everyone I am new here, so I hope I don't get a "fine" of 10 posts if this question is not proper for this forum anyway, here is my problem. I am new to java, thus still very confused on classes methods interfaces etc etc but trying to learn it all.. I have in one folder a selectionSort I wrote ...

56. Need Help With returning some int numbers.

I am doing a hw assignment and I am stuck. I have 3 files: RollingDice2(has the main method) PairOfDice Die So this is what my problem is it has to roll some dies and find some numbers so like how I have it now RollingDice rolls 2 dices and finds the sum but how the RollingDice gets it roll it must ...

58. Cast number with comma as Integer.

You should separate out how you STORE it from how you DISPLAY it. a number does not have commas in it. If you want to store something with commas in it, then you're not storing a number, you're storing a string. If you want to store a string, then don't consider it as a number.

60. Number of occurrences in a int[ ]

I'm having a little trouble as to taking two int []'s and if there are two elements that are the same, skipping over them. In the end I need the program to print out the elements that don't have any duplicates at all. For instance: int [] a = {4, 5, 5} int [] b = {6, 6, 3} The program ...

61. how to convert String number to int

62. Program to read integers until a specific number?

Hello! I have a problem. I want to make a program that reads all the integers that are typed in and when a certain integer is typed in (lets say 0) it stops and then adds them all toghether. I was thinking of a while and for loop. And to place the integers to an array. But how do i add ...

64. Help with initialize int variable without assigning a number?

Hello! I wonder if it is possible to initialize a variable without giving it an value? The part of my program I'm having trouble with: Java Code: //*The program will ask for 10 ints, when 10 ints have been taken in from //input the software will print the 2 biggest and the 2 smallest int. I've got it //to work if ...

65. Extracting individual numbers from a long integer

public class DigitExtractor { private static int intNumber; public DigitExtractor(int anInteger) { intNumber = anInteger; String number = String.valueOf(intNumber); char charNumber = number.charAt(4); int x = number.charAt(3); int x1 = number.charAt(2); int x2 = number.charAt(1); int x3 = number.charAt(0); } public static String nextDigit() { I dont understand if I return one number is only gives me that number. Even if ...

66. converting a given positive integer m to a positional number system in base n

Write a Java method to convert a given positive integer m to a positional number system in base n (n is in between 2 and 36). The result is a string consisting of digits and lowercase latin letters if needed. public static String toSysString (int m, int n) Example: toSysString (14, 4) == "32"

67. What is the correct way of getting a random Integer number?

It should work pretty fast. How do you know that it's slow? Do you use a profiler? Also, do you try to create a new rand object on each loop of the for loop, or do you create one rand object before the for loop and use the same object inside of the loop? Please do the latter, not the former. ...

68. Method to convert a rational number from 'int' to 'Double'.

class Rational{ int num; int denom; int swap; public Rational(){ this.num = 0; this.denom = 0; } public Rational(int num, int denom){ this.num = num; this.denom = denom; } public Rational (int swap){ this.swap = swap; } public static void printRational (Rational r){ System.out.println (r.num + "/" + r.denom + " " + "i"); System.out.println ((r.num / r.denom) + " " ...

69. Sentinel Values that reads telephone numbers as integers

sentinel value? It looks like you are trying to parse the string. There is no built in method for this (that I know of) so you will have to write your own. Depending on what you know about the format of the string, you might want to use the String methods split(), or substring() to start with. (A telephone "number" ...

70. Converting string of numbers to ints

while(go==true) { int[] info = new int[69]; System.out.print("Enter username: "); username = reader.nextLine(); //use "Hellfire010" if you're going to try this out try{ URL score = new URL("" + username); BufferedReader in = new BufferedReader(new InputStreamReader(score.openStream())); String inputLine, ScoreList = ""; while ((inputLine = in.readLine()) != null) { ScoreList = (ScoreList + inputLine); } System.out.println(ScoreList); in.close(); }catch (IOException e) { System.err.println("Caught ...

71. Add number to an Integer variable

72. converting string number int o percentage

73. help... how to separate the integer number..?

public class test { public static void main(String args[]) { int n = 23121888; int part1 = n / 1000000; int part2 = (n % 1000000 - y)/10000; int part3 = n % 10000; System.out.println("Part 1 : " + part1 + "\nPart2 : " + part2 + "\nPart3 : " + part3); } }

74. Specifying a number inside an int

I know you use charAt( ); for specifying a specific char in a string. What is the code to specify an int inside an int which is more than one digit long EG: four digit int int = 1234 how do i say intAt(0); the number (int) at position 0 within the initial int I want to specify each one individually ...

75. print integer numbers in Specfic Format

Shame on both of you. I recommend getting these books. Introduction to Java Programming (Y. Daniel Llang) Absolute Java Two of the best that i have seen. First Step Into Java - Dev Shed. This one to me at first seemed quite good. But then it started to feel like it was trying to teach Java to a 5th grader. The ...

76. Number of occurrences in a int[ ]

77. return true if an integer is an even number

79. NumberFormatException when using Integer.decode with hex numbers

I've tried using a string such as "-0xdeadbeef" or "+0xdeadbeef" with the same results. Is not the natural size of an Integer object 32 bits? So the max is 0xFFFFFFFF. my example of 0xdeadbeef is well within this. I'm not sure how the run time system is seeing it as a negative number?? Still stuck!! Mike

80. To write numbers ,in specific, integer data from java to a C program

Both methods work fine if there is a single write that is ,when i use a print(int) or write(int) of PrintWriter OR writeInt(int) of DataOutputStream to write one integer data it works fine..the same is causing problems when i do three consecutive writes into the socket using either of the methods.. any help would be of great help for my project:) ...

83. I need to strip down a long number to indidual integers.

If you are just told to strip it down into digits but not told to do anything with the digits then you don't need to keep the digits in integer variables. Just print them out as you get them. If you were not told an order in which you need to print them, print them in any order that makes the ...

85. If int is no Number - error. How to? Easy help please.

Thank you gentlemen, but what you wrote did not solve my problem ... I am so new in java that it may be easyer for me to walk on hands... Can i solve this problem lets say in one command? Somehow? Could you please give me some example? Because i think i may learn it best on hand of an example ...

86. complex number, an integer power

Hi, new to the site, looking for a few answers and i stumbled on a few forums. Most people give good advice, but there are a few that are annoying. If someone posts on these forums, its assumed they've 'googled' for an answer, as that would be the fastest way to resolve something. The purpose of these posts is to get ...

88. Picking some numbers randomly from a pool of integers :-)

Hello! I want a code to select randomly let's say 3 numbers from a pool of numbers like (1,2,4,7,8,34) which have evenly distributed probabilities. How this can be done? I have found only how to pick a number randomly from a range of integers, but this is not my case, as I don't want the possibility of a number being selected ...

89. Returns the integer part of a real number

Hello, I need to know an integer value as part of a real number, like this: double a = 0; double x = 0; x = 1500.00; a = (x / 1000); now "a" must be equal to 1. Pascal has a function INT (a = INT(x/1000)), and what about java ? Thanks for help, guido

90. hw to achieve the nxt int number???

here is my jsp code.... dont know hw to proceed nxt.... <%@ taglib uri="/WEB-INF/pagination.tld" prefix="pagination-tag"%> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="java.util.*" %> <%@ page import="com.INFO.*" %> <%@ page import="com.DAO.*" %> ...

91. String to Int. Words to numbers

92. new Integer(((Number)formatter.parseObject(string)).intValue())

DecimalFormat df = new DecimalFormat("#.###"); NumberFormatter format = new NumberFormatter(df); n the above code i have to convert decimal number to integer, how the below code will fit to it or any other way new Integer(((Number)formatter.parseObject(string)).intVal ue()) What kind of drugs are you taking currently? What kind of decimal format do you expect from an number with no decimals? The sentence ...

93. Get number of integer digits from BigDecimal

Number classes don't 'store this internal radix'. They use it in the code, as e.g. % 10 or / 10 or & 0xff or >>> 8. In the latter cases you can see that it is impossible to claim that the radix (256) is 'stored' anywhere at all. However as noted BigDecimal uses binary internally, much to my surprise. Doesn't alter ...