Unquantifying an integer - java

Is it possible to create an int variable with no value, then quantify it in my code, and then "unquantify" it so that it no longer has a value?
Example:
class Test {
int integer;
public static void main (String[] args) {
integer = 1;
...
//do stuff
...
integer = null; //Does this line set integer's value to nothing?
// I want to be able to reset the value of integer back to what it was when I defined it (the value was nothing, it had no value)
}
}
EDIT: grammar

You cannot assign null to a primitive type.
You could use the Integer object like this:
Integer i = null;
If you have an int as classmember and you access it inside a method the value of the int will be 0.
Also you have to make your variable static to access it in your main.

As an alternative to null you might like to look at the Optional class that was added in Java 8. It is useful for declaring variables that may or may not have a value:
Optional<Integer> value = Optional.empty();
value = Optional.of(4);
value.ifPresent(n -> method(n));
If used well it can make the code handling optional values much more obvious and transparent than using null.

Related

Why when you set an ArrayList, there is no need to return a value?

I am new to java and I was writing some code to practice, but there is something that I am confused about. I have the following code:
public class test {
public static void main(String[]args) {
int n = 0;
ArrayList<String> fruits = new ArrayList();
setList(fruits);
n =setInt(9);
// get the values from fruits
for (String value: fruits) {
print(value);
}
}
public static void setList( ArrayList list) {
list.add("pear");
list.add("apple");
list.add("pear");
}
public static int setInt(int number) {
number = 3;
return number;
}
}
My question is why in order to set my Arraylist() there is no need to return the any value, but in order to set my int I need to return something.If run this code it prints all the values in my list, but I expected not to print anything because In my method setList I do not return any value. If I did not return any value with my setInt, the value of n would not change, and that makes sense to me.
Thank you.
There are different ways to that params get passed in functions. The usuall way that most beginners start with is pass by value. The other way is pass by reference. In passing by reference, the object itself is pass in, not a copy as is with pass by value. That means any changes will affect the param and remain, even after it is called. All objects in java are passed by reference, only primitives are passed by value. Thus, is why you don't have to return when using arraylist object.
Edit: Actually, I've made an error. What is actually occuring is that a copy of the reference itself is being passed by value. Take a look at this.
Everything in Java is Pass by Value.

Java initialize variable with null or not?

I was wondering whether I should initialize class members in java with an initial value and then change that value to some other given value in the constructor, or should I avoid doing such a thing?
code example
public class Test {
private int value = 5;
public Test(int value) {
this.value = value;
}
}
If not specified,:
primitive bytes, shorts, ints, longs, floats and doubles are initialized to 0
booleans are initialized to false
Objects are initialized to null
If we are talking about class fields than all unset variables of
primitive types are set to
0 (numeric ones like int, long, double...)
\u0000 (char)
false (boolean).
object types like String, Integer, or AnyOtherClass are set to null
so actually it doesn't matter if you set it explicitly, because
private int x;
private Integer y;
is equivalent of
private int x = 0;
private Integer y = null;
Java give value class variables, I mean they are initialized by JVM and you can use them. But you must to search their default values to use them correctly.
On the other hand, JVM does not initialize the local variables which is created in methods. So if you create any variable on methods you have to assign them to a value before use them.
A not initialized int is always 0 on heap. It can't never be null. Mind: within a method it must be initialized, not only declared.
First, you cannot initialize an int value with null. The default value of an int is zero, but initializing it in both the field declaration and the constructor is pointless. Assuming the compiler does not omit the field initializer completely, it effectively compiles to this:
public class Test {
private int value;
public Test(int value) {
this.value = /* field initializer value */;
this.value = value;
}
}
Unless you want to initialize a field with a non-default value (non-zero, non-null), there is generally no reason to add an initializer. This is especially true if the initializer is redundant, as is the case above. The default value for a field is the "zeroed out" value of the field type, e.g., 0 for numeric types, false for a boolean, and null for objects. Note that there is an exception with respect to fields: final fields must have an initializer if they are not assigned exactly once in every constructor; final fields have no implicit default value.
Now, it may be necessary to initialize method variables to guarantee they have a value by the time they are read, as variables do not have a default/implied initializer as fields do. Whether an explicit initializer is necessary depends on the control flow of your method.

Advance for reference variables?

I am trying to understand the difference between Object with primitive variables when using them as parameters in a method.
There are some examples using reference variables:
public class Test1 {
public static void main(String[] args) {
int[] value = {1};
modify(value);
System.out.println(value[0]);
}
public static void modify(int[] v) {
v[0] = 5;
}
}
result: 5
public class Test2 {
public static void main(String agrs[]) {
Integer j = new Integer(1);
refer(j);
System.out.println(j.intValue());
}
public static void refer(Integer i) {
i = new Integer(2);
System.out.println(i.intValue());
}
}
result: 2 | 1
So what is different in here?
In java array is primitive type.and Integer is Object type.
For primitives it is pass by value the actual value (e.g. 3)
For Objects you pass by value the reference to the object.
In first example,
you are changing value in array.
while in other example ,
you are changing reference of i to other memory location where object value is 2.
when returning back to main function, as you are not returning value. its reference scope limited to "refer" method only.
Recall that the array references are passed by value. The array itself is an object, and that's not passed at all (That means that if you pass an array as an argument, your'e actually passing its memory address location).
In modify() method, you're assigning 5 to the first place in the array, hence, changing the array's value. So when you print the result, you get: 5 because the value has been changed.
In the second case, you're creating a new Object of type Integer locally. i will have the same value when you exit the method refer(). Inside it you print 2, then you print i, which is 1 and hence change doesn't reflect.
v[0] = 5, is like saying Get 0th element of current v's reference and make it 5.
i = new Integer(2), is like saying change i to 2's Integer object reference
In one case you are changing the internal values via the reference and in latter you are changing the reference itself.
The difference here is that they are different.
In your first example you are passing the argument to another method, which is modifying one of its elements, which is visible at the caller. In the second case you are assigning the variable to a new value, which isn't visible at the caller, because Java has pass-by-value semantics.
NB 'Primary variable' has no meaning in Java.
I don't know what the word 'advance' in your title has to do with anything.

Java variable value initialisation

I am a beginner in Java, struggling to understand the following problem with variable initialisation, would appreciate an expert help.
Given the code from an exam:
public class SimpleCalc {
public int value;
public void calculate() { value += 7; }
}
AND
public class MultiCalc extends SimpleCalc {
public void calculate() { value -= 3; }
public void calculate(int multiplier) {
calculate();
super.calculate();
value *= multiplier;
}
public static void main (String[] args) {
MultiCalc calculator = new MultiCalc ();
calculator.calculate(2);
System.out.println(calculator.value);
}
}
My understanding is that this needs to throw a runtime exception since variable "value" never gets an actual preliminary value assigned to it (public int value;). But, the code works and behaves as if the variable "value" is assigned 0 (same as public int value=0;). Could someone explain please why does this happen? Many thanks
. But, the code works and behaves as if the variable "value" is
assigned 0 (same as public int value=0;).
instance variables in java get default values. i.e, int get 0 as default value, float get 0.0 and so on. thus if you don't initialize, they get default values.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
My understanding is that this needs to throw a runtime exception since variable "value" never gets an actual preliminary value assigned to it (public int value;).
Failing to initialise a variable which must be initialised is checked by the compiler and is a compile time error.
Runtime errors are thrown at Runtime. i.e. when you run a program which has been successfully compiled. The only runtime error you will get from failing to set a value is a NullPointerException (for accessing a null reference), or rarely an ArithmeticException if you divide by an integer which is zero.
final fields and local variables must be initialised, but non final fields will value their default value.
Primitive types in Java always get assigned a default value. For an int this is always 0.
If you were to use a Integer object (rather than int) you would see a null pointer exception being thrown if it wasn't initialised.
This kind of initializations happen for instance variables, in java. The variable 'value' is an instance variable which exists in each of the object of that class. Instance variables of data type int have default value 0 assigned to it. Different data types(of instance variables) have different default values.
Example

Changing boolean value in class function in java

Can we modify a Boolean value in class function in java, something like this wont work as the change is local to function. How can we make the following change passed variable reflect outside the method call?
public void changeboolean(Boolean b)
{
if( somecondition )
{
b=true;
}
else
{
b=false;
}
}
EDIT
The code could be like this:
public String changeboolean(Boolean b,int show)
{
if( somecondition )
{
b=true;
show=1;
return "verify again";
}
else
{
b=false;
show=2;
return "Logout";
}
show=3;
return verifed;
}
I'm searching for something like this
b.setvalue(true);
Is it possible?
Can we modify a Boolean value in class function in java
No, Boolean is immutable, like all the wrappers for the primitive types.
Options:
Return a boolean from your method (best choice)
Create a mutable equivalent of Boolean which allows you to set the embedded value. You would then need to modify the value within the instance that the parameter refers to - changing the value of the parameter to refer to a different instance wouldn't help you, because arguments are always passed by value in Java. That value is either a primitive value or a reference, but it's still passed by value. Changing the value of a parameter never changes the caller's variable.
Use a boolean[] with a single element as the wrapper type
Use AtomicBoolean as the wrapper type
Boolean is immutable, like all the wrappers for the primitive types.
Soln:
Trying using MutableBoolean of apacheCommon
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/mutable/MutableBoolean.html

Categories

Resources