Java : Array items null and int values - java

I have an array with type Object. Then I assign it's values to null. But later I want to assign int values on null cells. Is that possible?
In these lines:
Queue[y]=new Int;
Queue[y]=num;
I am trying create an object Int type, in the null cell. But I get this error:
error: '(' or '[' expected
Queue[y]=new Int;
private Object Queue[];
public PriorityQueue(int capacity){
this.capacity=capacity;
Queue= new Object [capacity];
for(int i=0;i<=Queue.length;i++) {
Queue[i]=null;
}
}
public boolean insert(int num){
if (y<capacity){
Queue[y]=new Int;
Queue[y]=num;
y++;
return true;
}
else{
y++;
return false;
}
}

(I don't know what class you mean by Int - perhaps you mean java.lang.Integer, but perhaps you mean some custom class. It's not totally relevant to the answer, however)
You always need a parameter list when you invoke a constructor, even if it is empty:
new Int()
Or, if you mean to create an array, you need to specify the number of elements:
new Int[10]
However, you don't need the first assignment:
Queue[y]=new Int();
Queue[y]=num;
The second line overwrites the value in the first line, so it's actually just creating an object and then immediately discarding it.
You could simply write:
Queue[y]=num;
Note that this isn't actually assigning an int to an Object array element: due to autoboxing, the compiler automatically converts this to:
Queue[y]=Integer.valueOf(num);
so an instance of Integer is being added to the array. However, this conversion isn't something that you need to do yourself.

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.

Can we not initialize reference array in Trie constructor

In this Trie implementation, children array elements are assigned null value individually using a for loop.
TrieNode(){
isEndOfWord = false;
for (int i = 0; i < ALPHABET_SIZE; i++)
children[i] = null;
}
However, by default, when we create an array of reference types in Java, all entries will have default value as null which is:
TrieNode[] children = new TrieNode[ALPHABET_SIZE];
The above step assigns default values of children array entries as null.
Is it required to have null assignment once again in the for loop inside that TrieNode constructor?
No it's not required - for each class variable, instance variable, or array component Java will always assign reasonable default value (like 0 for int or null for Object) - you can read more here
However notice that for local variables it's not guaranteed
The compiler will assign a reasonable default value for fields of the above types; for local variables, a default value is never assigned.
and that's why you are forced to initialize it manually
public void f() {
String s;
System.out.println(s); // will cause Error: java: variable s might not have been initialized
}

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 ) );
}

java method to change the value of an array to null

public void setData(double[] d) {
if (d == null) {
data = new double[0];
} else {
data = new double[d.length];
for (int i = 0; i < d.length; i++)
data[i] = d[i];
}
}
this method in my code is used to set the data of an array. I am also required to write a method called reset() that changes a given array to have a null value. Also, we are practicing overloading in this lab. There are four versions of setData() (double, int, float, long). Since a double array is used internally by the Stat class to store the values, do I only have to make one reset() method of type double?(I think I only need one...) Finally, please give me some hints as to going about this reset business because everything I have tried has failed miserably and usually consists of statements such as
"setData(double[] null)" which return errors.
Everything in java is pass by value; even references are passed by value. So by passing an array through a method, you can change the contents of the array, but you cannot change what the array points to. Now, if you are inside a class and happen to pass an instance member that you already have access to by virtue of being in the class, you will be able to set the array to null.
If you always want to be able to change what an array points to, then simply have a function which returns an array (instead of being void), and assign that returned value to the array of interest.
Because java is pass by value, you can't reassign a variable passed as a parameter to a method, and expect to see that change reflected outside.
What you can do, is put the array in some sort of wrapper class like this:
class ArrayReference<T> {
T[] array; // T would be either Double, or Long, or Integer, or whatever
}
and then:
void setData(ArrayReference<Double> myReference) {
myReference.array = null;
}
I'm not sure if I understood your question, but is it that what you want?
public class Stat {
private double[] data;
public void reset() {
data = null;
}
public void setData(double[] d) {
data = (d == null) ? new double[0] : Arrays.copyOf(d, d.length);
}
}

returning arrays in java?

In my program I am trying to return the prevScore[i] and the prevScoreName[i]. However, both return statements have errors stating that they're incompatible types (required int[], found int). I feel like it may be how I defined them in the main project (first 2 lines below). Any help would be appreciated.
prevScore = scoreChange (prevScore, score);
prevScoreName = nameChange (prevScoreName, newName);
public static int[] scoreChange (int prevScore[], int score)
{
for (i=1; i<prevScore.length;i++){
prevScore[i] = score;
}
return prevScore[i];
}
public static String[] nameChange (String prevScoreName[], String newName)
{
for (i=1; i<prevScoreName.length;i++){
prevScoreName[i] = newName;
}
return prevScoreName[i];
}
If you want to return just one item from each function, change the return types to int and String (not int[] and String[]). If you want to return whole arrays, then change the return statements to return prevScore; and return prevScoreName; (without the [i]).
Note that there's no need to return the whole array - the caller already has a reference to it. Just change the return types to void, delete the return statements, and get rid of the assignments in front of your calls.
You are not returning the arrays:
return prevScoreName[i]; // Returns the String at index 'i'
return prevScore[i]; // Returns the integer at index 'i'
If you want to return actual arrays, you need to lose the [i]:
return prevScoreName; // Returns the array
return prevScore; // Returns the array
Additionally, there is no need to even return anything:
prevScore = scoreChange (prevScore, score);
prevScoreName = nameChange (prevScoreName, newName);
You are modifying the contents of these arrays with the function calls.
It seems like you maybe don't understand arrays.
When you say
public static int[] you are making reference to an entire array. (not all of its contents, but rather you are pointing to the space in memory where the array lives.)
When you say
public static int you are referring to just one integer.
In your method, you declared your return type as int[], which meant you were returning an entire array of integers. But your return statement was trying to return prevScore[i], which is a single integer, that just happens to be contained in the array. It would have been the same if you had wrote:
int var = prevScore[i];
return var;
Its easier to see that you are returning an integer in this example.
An array of integers is not the same as an integer, so your compiler didn't know what to do when you tried to send back a single integer when it was expecting to see an array of integers.

Categories