convert Integer to int - java

I have an Integer value of variable as below:
Integer programNumber= ........
I took the program number as Integer type. However in my other class, I want to check whether this variable, programNumber, equals variable which is the type of int.
To sum up, I want to convert the variable of the of Integer to int primitive value.
I used programno.intValue() but it doesn't work.
Thanks in advance.
I have a two class, BasvuruKisi and Program. the code snippet is below:
BasvuruKisi bsvkisi = (BasvuruKisi) (this.getHibernateTemplate().find("from BasvuruKisi bsv where bsv.basvuruNo=?", basvuruNumaralari.get(i))).get(0);
if (bsvkisi != null) {
int yetkiVarmi = 0;
Integer programno= bsvkisi.getProgramId();
List array =
this.getHibernateTemplate().find("from Program p where p.id=?", programno.intValue());
but
this.getHibernateTemplate().find("from Program p where p.id=?", programno.intValue());
this one doesn't work. return firstly, no table or view is available despite available and then returns null pointer exception.
thanks

The variable name in the initialization block says programNumber, but the variable in the method call is programno. Which is it?
Using the wrong variable name shouldn't give you a null pointer exception, unless you have another variable named programno defined somewhere.
Whatever the variable name is, make sure you initialize it before you get the intValue.

Validate programNumber is null or not?
If the value is null, it throws Exception.
Integer programNumber= null;
System.out.println(programNumber.intValue());

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.

Recursive method for binary tree node couting

Ok, so i have to create a recursive method for counting the nodes in a tree, and i did this (variable names are in portuguese, sorry):
public int contaNos(Arvbin r) {
Integer cardinalidade = 0;
contaNosPrivado(r, cardinalidade);
return cardinalidade;
}
private void contaNosPrivado(Arvbin r, Integer cardinalidade) {
if (r==null) {
return;
}
cardinalidade=cardinalidade+1;
contaNosPrivado(r.esq, cardinalidade);
contaNosPrivado(r.dir, cardinalidade);
return;
}
Arvbin is the binary tree, esq and dir are the left and right references to the tree's branches.
I thought this would work, but for some reason when i try to run it, it returns 0. I've usen a little bit of debugging and i think the issue is that when the methods finish and come back to the original non-recursive one, the cardinalidade variable is set to 0. I'm not sure if it's because autoboxing is messing with my Integer and turning it into an int, and then when i call the method it passes a copy of the value instead of the reference to the existing object, and i don't know how to fix it. If anyone could help, i'd greatly appreciate it
The problem is that wrapper classes are immutable in Java. cardinalidade is just a parameter of contaNosPrivado here and, unfortunately, cannot act as an argument like other object type parameters can, i.e. this local reference cannot change inner fields of the object that initial reference refers. Any change to it affects it only the way it affects any primitive local variable.
What exactly happens inside your contaNosPrivado:
On invocation, it is indeed supplied a reference to an Integer object. This reference is assigned to a local variable named
cardinalidade.
In this line:
cardinalidade=cardinalidade+1;
this object is first unboxed to a primitive int variable, this variable is incremented afterwards, and
finally the result is reboxed into a new Integer object which is
then assigned to cardinalidade. There is no way to 'increment'
original object, even if you use the increment operator:
cardinalidade++;
Any further processing applies to the newly created Integer object and doesn't affect the reference passed to contaNosPrivado.
To achieve your goals, use something like this instead:
static int contaNosPrivado(Arvbin r) {
if (r == null)
return 1;
else
return contaNosPrivado(r.esc) + contaNosPrivado(r.dir);
}
As #John McClane has pointed out, you can't pass an Integer argument by reference, only by value.
But there's also no need for a private helper method, you can just simplify it all to a single method:
public int countLeaves( BinaryTreeNode n )
{
return n == null? 0 : ( countLeaves( n.rightLeaf ) + countLeaves( n.leftLeaf ) );
}
Or (excuse my poor Portugese):
public int contaNos( Arvbin r )
{
return r == null? 0 : ( contaNos( r.esq ) + contaNos( r.dir ) );
}

How to compare List count against single integer value?

I am trying to matching total number of records but not able to do it because my one totalcount strong in list type variable and another is getting store in single integer variable.
My Code :
`Base.getdriver().get(Js_constants.DashboardURL);
List<WebElement> totaljobs = Base.getdriver().findElements(By.className(Js_constants.TopsJobsactualtotal));
System.out.println(totaljobs.size()); //OUTPUT 30
//Integer.parseInt(totaljobs); //THIS IS NOT WORKING..WHY?
String Topjobscount = Base.getdriver().findElement(By.xpath(Js_constants.Topsjobscount)).getText();
System.out.println(Topjobscount); //OUTPUT 30
Integer.parseInt(Topjobscount);
//HERE IT IS NOT SUPPORTING CONDITION LIKE THIS.
if(Topjobscount == (totaljobs.size()))
{
System.out.println("Jobs & Count are matching");
Reporter.log("Jobs & Count are matching");
}
else
{
System.out.println("Jobs & Count are matching");
Reporter.log("Jobs & Count are not matching");
}
}`
I am using selenium webdriver & Java. I want to compare both variable count but issue is it does not allow me to convert list type variable to integer.
Topjobscount varibale is a string and you are trying to compare it with an int value.
Calling Integer.parseInt(Topjobscount) wont convert your string to int.You have to assign the value returned by Integer.parseInt(Topjobscount) to an int value and then compare.
Try this.
int x = Integer.parseInt(Topjobscount);
if(x == (totaljobs.size()))
Remember to catch NumberFormatException
Integer.parseInt() documentation states that
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer.
So you need to save that returned value into Integer variable and use that variable.
int count = Integer.parseInt(Topjobscount);
if(count == (totaljobs.size()))
Java is strictly a types language. That means following.
You can not supply anything into a method, it has to be strictly in the same object hierarchy. It results a compile time error if trying to supply wrong type of value as a parameter.
E.g. in your code List<WebElement> totaljobs clearly says type of object totaljobs is List.
Where in Integer.parseInt() takes a parameter type of String. So you can not supply a List type of value where string is expected.
rather you can pass size of list by converting it in string as shown following.
String.valueOf(totaljobs.size());
will return a string representation of size of the list.
However you can convert this string value back to integer by calling Integer.parseInt(String.valueOf(totaljobs.size()));
But above does not make any sense as size() method of List, returns an integer value.
Topjobscount is a String value which can not be compared to int value without converting it to integer.
So you can correct (Topjobscount == (totaljobs.size())) by converting String into integer. As given below.
if (Integer.parseInt(Topjobscount) == totaljobs.size())
Hope this helps.

JNA: Pointer to char**

I own the next C function:
int fillWithNames(const char*** names, int *n);
which I convert to java using JNA proceeding like this:
public interface PlayersLibrary extends Library {
PlayersLibrary INSTANCE = (PlayersLibrary) Native.loadLibrary("player", PlayersLibrary.class);
int fillWithNames(PointerByReference names, IntByReference n);
}
How could I print the Strings that this method returns in names?
I want to do something like this:
PlayersLibrary.INSTANCE.fillWithNames(names, n);
Pointer first = names.getValue(); // char**
String a = first.getPointer(0).getValue() // char*
System.out.println(a);
but in this case, names.getValue() returns null and I donĀ“t know what to do
What can I do to solve this problem?
Use names.getValue().getStringArray(0, n.getValue()]).
I'm inferring that the n parameter is telling the callee how many names to fill in. getStringArray() will convert consecutive pointer values in memory into strings until it encounters a NULL value; if your callee doesn't terminate with a NULL pointer you'll need to explicitly tell it how many pointers to read (ostensibly the n parameter in the call to fillWithNames()).
EDIT
So the length does indeed come back in the n parameter. If the callee writes a zero to that parameter, then it's telling you it has no names (which would by why you get a null back in the other parameter).
Class PointerByReference
Represents a reference to a pointer to native data. In C notation, void**.
Also, see SO: PointerByReference not returning value.

Java declaration confusion for datatypes

I have a doubt about null assigning to variable in Java. In my program I have assigned null to String variable as String str_variable = null;. For the learning purpose i assigned null integer variable as int int_variable = null; It shows error Add cast with Integer. So that rewrite the above int declaration as Integer int_variable = null;. This does not shows errors. I do not know the reason of these two kind of declaration.
Please the difference between to me.
String str_variable = null;
int int_variable = null; // error.
Integer int_variable1 = null; // no error.
String and Integer are both classes, in a way they are not native data types that is why it is always okay for you to set null as an initial value, however for int you must always initialize it with a number, one good way to find out their appropriate initialization value is to create variables outside your main(), example String var1; int var2; then use System.out.println(var1); System.out.println(var2); within the main()
to see what was placed as an initial value when you run the program.
int is a primitive, Integer is a class.
See http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
int is a primitive type, Integer is a wrapper class type extending Object class. Non-referencing objects can be null but primitives cannot. That's why you get an error message saying you need casting.
You can use a line like int num = (Integer) null;, this is how casting is done, however you will get NullPointerException when you try to use num anywhere in your code since a non-referencing(null) Integer object doesn't hold / wrap a primitive value.

Categories