Format String to Integer in java - java

I am facing the below problem:
I will be getting values similar or of greater length compared to temp value :
public class NumberFormat {
public static void main(String arg[]){
Integer numValue = null;
String temp="5474151538110135";
numValue=Integer
.parseInt(temp.trim());
System.out.println("--> "+numValue);
}
}
Please provide a solution.
Exception in thread "main" java.lang.NumberFormatException: For input string: "5474151538110135"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:60)
at java.lang.Integer.parseInt(Integer.java:473)
at java.lang.Integer.parseInt(Integer.java:511)
at com.filetransfer.August.NumberFormat.main(NumberFormat.java:10)

5474151538110135 is greater than Integer.MAX_VALUE. Use Long.parseLong instead or BigInteger if the input number is likely to grow significantly
Long numValue = Long.parseLong(temp.trim());

Probably beacuse the value is larger than max int value which is 2147483647.
System.out.println(Integer.MAX_VALUE);
You should parse it to Long which max value is 9223372036854775807.
System.out.println(Long.MAX_VALUE);
like this
Long numValue = null;
String temp="5474151538110135";
numValue=Long
.parseLong(temp.trim());

I would recommend use BigInteger for avoiding errors
Advantage of BigInteger Class
Integer is a wrapper of the primitive type int.The wrapper classes are basically used in cases where you want to treat the primitive as an object for ex-trying to pass an int value in a method that would take only a type of Object in such a case you would want to wrap primitive int value in the wrapper Integer which is of type Object. To know specific advantages of Integer I would suggest you to take a look at the Integer api provided by Sun.
Now coming to the BigInteger, you would use it in calculations which deal with very large numbers.The use of BigIntegers is in Security where typically it is used for keys specifications.For more info on BigIntegers take a look at the following link http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html
I hope the info helped you.

Related

Delete value for previously assigned int field [duplicate]

Can an int be null in Java?
For example:
int data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.
I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.
Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.
int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
No. Only object references can be null, not primitives.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.
The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
Along with all above answer i would like to add this point too.
For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.
So by default we have,
int a=0;
and not
int a=null;
Same with other primitive types and hence null is only used for objects and not for primitive types.
The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:
Integer data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.
int data = check(Node root);
// do something
Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.
To learn more about autoboxing, check this Sun guide.
instead of declaring as int i declare it as Integer i then we can do i=null;
Integer i;
i=null;
Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so
public int getHeight(String name){
if(map.containsKey(name)){
return map.get(name);
}else{
return -1;
}
}
No, but int[] can be.
int[] hayhay = null; //: allowed (int[] is reference type)
int hayno = null; //: error (int is primitive type)
//: Message: incompatible types:
//: <null> cannot be converted to int
As #Glen mentioned in a comment, you basically have two ways around this:
use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.
Data Type / Default Value (for fields)
int ------------------ 0
long ---------------- 0L
float ---------------- 0.0f
double ------------- 0.0d
char --------------- '\u0000'
String --------------- null
boolean ------------ false
Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:
new Integer(null);
I'm no expert, but I do believe that the null equivalent for an int is 0.
For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.
In some situations, this may be of use.

How to cast to Number from String in java without knowing which number type is present in the String?

I am writing a compiler, that reads from an input file, parses it and creates various kind of tokens. Further, in parsing, upon getting a NumLitToken , I retrieve its's number value stored as String and want to save it as a Number for further stages of transformations.
I am not aware whether the String contains int/ float / long / double etc. so i am using NumberFormat.getInstance().parse(x) method and expecting appropriate casted value, but i don't know why i am not getting a cast to Integer for int values.
Also, if there is any other way better to cast to Number from String, please enlighten me about it.
A small extract:
import java.text.*;
public class Main
{
public static void main(String[] args) throws ParseException{
String x = "100";
Number o = NumberFormat.getInstance().parse(x);
System.out.println(o.getClass().toString());
if(o instanceof Integer){
System.out.println("int");
}
}
}
Output:
class java.lang.Long
UPDATE : Turns out, the method only returns long or double. What to do to get appropriate cast to Number ? Is there a better way rather than trying to cast for every number type?
Because the docs say so:
Returns a Long is possible, otherwise a Double
Simple as that.
If you're just trying to parse an int, int x = Integer.parseInt("500"); does the job!
As mentioned in a different answer it is how it works.
If you want to a function that returns the most appropriate type depending its size the apache-commons NumberUtils.createNumber will do that for you.

Why does this print exception?

String bob2 = "3";
System.out.println((int)bob2);
I'm unsure of why this causes an exception. Can anyone explain? Pretty sure because of the int on String type, but want to make sure.
Yes you are right its because of typecasting. If u need to convert String to int use below code
Integer.parseInt("3");
You are correct.
You can't just cast a string to an int.
You should convert it using Integer.parseInt()
Use this
Integer.valueOf("3");
or
Integer.parseInt("3");
In Java whenever you are trying to change type of an entity to another, both the types should have some relation. Like if you are trying to caste a sub class object to super class, it will work smoothly. But if you try to compare a Person object with a Lion object, that comparison is meaning less, the same is the logic in casting. We cannot cast a Person object to Lion object.
In your code bob is String type and you are trying to cast it to int and in Java both String and Integer is not having any relation. That's why Java is throwing Exception, Class Cast Exception I guess, this is raised when different types of objects are compared.
But the parseInt(String arg) method in Integer class gives an option to convert numeric String to Integer, given that the argument is a qualified Integer as per Java standards.
Example :-
String numericString = "1234";
int numberConverted = Integer.parseInt(numericString);
System.out.println(numberConverted);
You can also try these which will tell you the precautions before using this method
int numberConverted = Integer.parseInt("1234r");
int numberConverted = Integer.parseInt("1234.56");
int numberConverted = Integer.parseInt("11111111111111111111111111111");
You can't cast String to Integer. Change:
System.out.println((int)bob2);
to:
System.out.println(Integer.parseInt(bob2));
It will create an Integer value from the String provided with bob2 variable. You can also create a reference to int variable like this if you want to store primitive int instead of Integer:
int intBob2 = Integer.parseInt(bob2);

why it always giving call integer parameter method not short parameter method

This is my code:
public class Test
{
public static void main(String arg[]) {
new Test().method1(5);
}
public void method1(int b) { // integer method
System.out.println("integer ");
}
public void method1(short a) { // short method
System.out.println("short");
}
}
I am running this class, and it gives me result of integer. Why it is not giving short?
Because the literal 5 is by default understood as an int. If you want to call the method1(short a) method, you need to explicitly do a cast:
new Test().method1((short) 5);
The literal 5 has type int, that's why the method that expects an int is called.
new Test().method1((short)5) would call the method that expects a short.
Default type of Java integer literals is int thats why integer method is getting invoked.
you have to apply type conversion because you are willing to call a function which receives short.
try calling with:(short)5
It's because, as noted in the other answers, a 5 on its own denotes an int. You can denote a long by appending an L, so 5L would be treated as a long. If you want a byte or a short then you have to cast explicitly.
It may be that you have a good reason for wanting a method that takes a short, but please bear in mind that this is quite rare. Certainly you would not want to be doing this for performance reasons. Java uses a 32-bit int by default because pretty much every processor out there can work natively with 32-bit integers. You will probably find that a short will operate more slowly than an int.
(Of course, if you're doing specifically 16-bit arithmetic, then you might still need to use a short.)

Java Autoboxing through a method

Let's say that I have a class:
class A {
private Integer i;
public int getI() {
return i;
}
// Setter, etc.
}
and I write:
A a = // initializer
Integer b = a.getI();
how many Integers will there be? My naive reading about autoboxing/unboxing leads me to believe that the answer is 2, but if getI() were:
public Integer getI();
then the answer would be 1.
You are absolutely correct, with one caveat: the answer to the first part depends on the value of Integer i.
In the first scenario, one Integer is created in the constructor, and the other one is created when boxing the int coming from getI()
In the second scenario, there needs to be no boxing, so there's only one Integer object.
Note: if the value of the Integer i is small (more precisely, between -128 and 127, inclusive), autoboxing will produce the same Integer through interning.
Correct....ish
It's theoretically possible the Compiler/JIT/JVM/etc could optimise out the autoboxing but I've no idea if it actually would.
It's also possible the same Integer object would be re-used. For example Integer.valueOf(2) is guaranteed to give you the same Integer object every time you call it and re-use the same object. This is only guaranteed for values in the range -128 to +127 inclusive though, it may happen outside that range but should not be relied upon.

Categories