Changing boolean value in class function in java - 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

Related

Optional "map" maps String to Boolean object instead of primitive boolean when using "var"

I have following problem, I'm not sure if it is IntelliJ Bug or something else.
I have static function which maps string to boolean. When I use this function in Optional.map() it maps every time to Boolean instead of boolean. Is this standard behavior of type inference?
public class MyClass {
public void myMethod() {
Optional<String> myAttribute = Optional.of("1");
final var myBoolean = myAttribute
.map(MyClass::mapStringToBoolean) //it maps to Optional<Boolean>, why not to boolean when function gives primitive back?
.orElse(false);
// "myBoolean" is Boolean instead of boolean
}
public static boolean mapStringToBoolean(String myString) {
return "1".equals(myString) || "true".equals(myString);
}
}
As said by others, there is no Optional<boolean> as Java’s Generics do not support primitive types as type arguments.
However, you’re using the wrong tool for the job. Use
final var myBoolean = myAttribute
.filter(MyClass::mapStringToBoolean)
.isPresent();
Optional<T>#orElse returns T, which cannot be a primitive. Try replacing var with boolean to force unboxing.
Primitives cannot be used as generics in Java so you are getting autoboxed. Try to declare eg List<int> to see what will happen.

Unquantifying an integer

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.

Java - Calling one method before another

Using class methods, I want to make sure that the getAverage method is always called before the setAverage method
If setAverage is called first, it should return an error.
I'm confused as to how to check if the set is called before the get.
If getAverable returns a non primitive object, you can check if the value is null.
If you return primitive value, like integer, you can use a boolean to check if the setMethod was called.
class Name {
int value;
boolean isCalled;
public int getValue() {
if(isCalled == false) {
throw new Exception();
}
else {
return value;
}
}
public void setValue(int value) {
isCalled = true;
this.value = value;
}
}
There is no direct Java support for doing this. Of course, you could implement directly in the methods some algorithm which memorize which method was executed in which order. Better way to do this is with Aspect-oriented programming.
The simplest way to do what you want is to write an Aspect which writes in a Boolean that getter was executed and allows execution of setter only in case where Boolean flag is true.
Of course, this is only a first step and would be very error prone. (Concurrency, Repetiton etc.)
(I have written such a framework during my master thesis. Of course, it was a bit more complex than just checking single sequential method invocations.)

List as output parameter in Java

I am trying to write a Java function which has List object as output parameter.
boolean myFunction(int x, in y, List myList)
{
...Do things...
myList=anotherList.subList(fromIndex, toIndex);
return true
}
Before that I call the function I declare myList as follow:
List myList=null;
Then I call the function myFunction(x,y,myList)
But when I try to manipulate myList, I find that myList is still null.
I am sure the variable "antherList" in my function code is not null and I am sure that the subList function return a non-empty List.
What is the reason, and how can pass a List as output parameter in a Java function?
Thank you very much.
Java always uses pass by value. This means that manipulating a passed variable won't affect the variable that was passed by the caller.
In order to solve your problem there are some possibilities:
Return the sublist:
List myFunction(int x, int y) { return anotherList.subList(....);}
I know that this way gets rids of your boolean return value.
Create a structure that holds the pointer to the List and.
class Reference <T>
{
public T ref;
}
boolean myFunction(int x, int y, Reference<List> listRef)
{
listRef.ref = anotherList.subList(....);
return true;
}
Create a structure that holds all the output you want the method to return:
class MyFunctionOutput
{
List list;
boolean b;
}
MyFunctionOutput myFunction(int x, int y)
{
MyFunctionOutput out = new MyFunctionOutput();
out.list = anotherList.subList(....);
out.b = true;
return out;
}
Or the most easy way: pass an initialized List instead of null and let the function add the sublist, like Attila suggested.
You cannot pass an out parameter in Java. You will either need to state the return type as the List or change the contents of the passed list:
boolean myFunction(int x, in y, List myList)
{
...Do things...
myList.clear();
myList.addAll(anotherList.subList(fromIndex, toIndex));
return true
}
Note: out-parameter means that you change the value of the variable containing the value passed to the function. In your case it would mean returning a different List object. Instead, you are returning the same List object, but with changed content.
Think of the parameter as a local copy of the passed value: any changes that replace the whole object will be lost upon the function returning. If you just change its content/state, that change will remain as you are accessing the same object as you have passed in (the local copy is made of the reference pointing to the same object)
Note: it might have been for demonstration purposes, but you should use generics to specify the object contained by the list: e.g. List<String> instead of the raw List type
References in Java are passed by value. So you can't specify an out parameter.
What you can do (however) is to mutate an object passed in. So in your example above, you can pass in an empty List, and populate it within your called method.
i.e. in the above:
myList.addAll(...);
You would likely want to assert as a precondition that the passed list is empty.
I would perhaps suggest that this isn't a very common pattern in the Java world. Because out parameters don't exist, it's not expected behaviour that arguments passed in as parameters would change, and you may be better off creating a suitable object type to return.
The myList variable is local to that function. References are passed by value, not by pointer in the Java world. As soon as you exit, it is removed from the context stack. A possible option is to not return a boolean but return the list itself. Then you can test the list for null to see if your function worked or not.
Another option is to actually create your list, then pass it to the function (non-null). Then your function need not create a new list, but simply add values to it.
A short answer- just return the new list as return value of the function:
List myFunction(int x, in y, List myList) {
...Do things...
return anotherList.subList(fromIndex, toIndex);
}
the long answer is that java copy the pointer of your object when you call a function, that mean that if you assign a new object to the method param, it wouldn't affect the original variable. so you must save the param reference if you want to change the object value.

JNI - How to modify a parameter when calling a Java method from C++?

I have a Java method something like this
public boolean ReadBool(String ValueName, Boolean Value)
{
boolean Retval = ...;
...
Value = true;
...
return bRetval;
}
that I call from native code (C++) like this:
jMethodID MethodId = pEnv->GetMethodID(ClassId, "ReadBool", "(Ljava/lang/String;Ljava/lang/Boolean;)Z");
// What goes instead of "??" ?
bool bOk = pEnv->CallBooleanMethod(myobject, MethodId, pEnv->NewStringUTF("Value1"), "??");
My intention is for the Java method to "return" a boolean value in Value. I understand that a built-in boolean will not work for this purpose. Is it possible to do this with a Boolean wrapper? How does one construct the object to pass in place of "??" ?
I have googled around, but some questions remain. For example, I suppose I could pass an object created by calling Boolean's <init> "method". But wouldn't the assignment in the Java ReadBool make Value refer to a newly created wrapper, throwing away that first object? In that case I would have called <init> for nothing. I think it should be possible to create (in the native code) something that Java sees as an object that is null and whose type is Boolean. Is that possible? Or am I on the wrong track altogether?
Booleans are immutable in Java, so you need your own wrapper class, which can be really simple though:
public class BooleanWrapper {
public boolean val;
// public is fine here imo, but you can obviously use [g|s]etters as well
}
Or if you don't want this, we can use a.. well not really pretty, but nice to know hack:
public void hack(boolean[] vals) {
vals[0] = true; // voila, now you change the value itself
}
Has some obvious drawbacks when calling (and looks strange), but if you're fine with keeping a specific parameter sequence, you can do:
public void hack(boolean.. vals) {
vals[0] = true; // voila, now you change the value itself
}
that way the caller doesn't have to use stuff like new boolean[] {};
You can obviously cheat and change the internal state of the Boolean object itself, but that will have unwanted consequences (booleans are cached ergo if you change the Boolean.TRUE instance to false internally this will give interesting results). So don't do that.

Categories

Resources