convert from boolean to byte in java - java

I need to set byte value as method parameter. I have boolean variable isGenerated, that determines the logic to be executed within this method. But I can pass directly boolean as byte parameter this is not allowed and can't be cast in java. So the solution I have now looks like this:
myObj.setIsVisible(isGenerated ? (byte)1 : (byte)0);
But it seems odd for me. Maybe some better solution exists to do this?

your solution is correct.
if you like you may avoid one cast by doing it the following way:
myObj.setIsVisible((byte) (isGenerated ? 1 : 0 ));
additionally you should consider one of the following changes to your implementation:
change your method to something like setVisiblityState(byte state) if you need to consider more than 2 possible states
change your method to setIsVisible(boolean value) if your method does what it's looking like

You can use this solution. I found it on this very useful page
boolean vIn = true;
byte vOut = (byte)(vIn?1:0);

It is not odd. It is OK.
The odd is that you need to transform typed boolean value to not self explainable byte. However sometimes we have to do this when working with legacy APIs.
BTW if you want to save memory you can use 1 bit instead of byte, so you can group several boolean flags together while using bit for each boolean value. But this technique is relevant for huge amounts of data only when saving several bytes can be significant.

Related

Why using default trash value for string is wrong?

tl;dr;
Why using
string myVariable = "someInitialValueDifferentThanUserValue99999999999";
as default value is wrong?
explanation of situation:
I had a discussion with a colleague at my workplace.
He proposed to use some trash value as default in order to differentiate it from user value.
An easy example it would be like this:
string myVariable = "someInitialValueDifferentThanUserValue99999999999";
...
if(myVariable == "someInitialValueDifferentThanUserValue99999999999")
{
...
}
This is quite obvious and intuitive for me that this is wrong.
But I could not give a nice argument for this, beyond that:
this is not professional.
there is a slight chance that someone would input the same value.
Once I read that if you have such a situation your architecture or programming habits are wrong.
edit:
Thank you for the answers. I found a solution that satisfied me, so I share with the others:
It is good to make a bool guard value that indicates if the initialization of a specific object has been accomplished.
And based on this private bool variable I can deduce if I play with a string that is default empty value "" from my mechanism (that is during initialization) or empty value from the user.
For me, this is a more elegant way.
Optional
Optional can be used.
Returns an empty Optional instance. No value is present for this Optional.
API Note:
Though it may be tempting to do so, avoid testing if an object is empty by comparing with == against instances returned by Option.empty(). There is no guarantee that it is a singleton. Instead, use isPresent().
Ref: Optional
Custom escape sequence shared by server and client
Define default value
When the user enter's the default value, escape the user value
Use a marker character
Always define the first character as the marker character
Take decision based on this character and strip this character for any actual comparison
Define clear boundaries for the check as propagating this character across multiple abstractions can lead to code maintenance issues.
Small elaboration on "It's not professional":
It's often a bad idea, because
it wastes memory when not a constant (at least in Java - of course, unless you're working with very limited space that's negligible).
Even as constant it may introduce ambiguity once you have more classes, packages or projects ("Was it NO_INPUT, INPUT_NOT_PROVIDED, INPUT_NONE?")
usually it's a sign that there will be no standardized scope-bound Defined_Marker_Character in the Project Documentation like suggested in the other answers
it introduces ambiguity for how to deal with deciding if an input has been provided or not
In the end you will either have a lot of varying NO_INPUT constants in different classes or end up with a self-made SthUtility class that defines one constant SthUtility.NO_INPUT and a static method boolean SthUtility.isInputEmpty(...) that compares a given input against that constant, which basically is reinventing Optional. And you will be copy-pasting that one class into every of your projects.
There is really no need as you can do the following as of Java 11 which was four releases ago.
String value = "";
// true only if length == 0
if (value.isEmpty()) {
System.out.println("Value is empty");
}
String value = " ";
// true if empty or contains only white space
if (value.isBlank()) {
System.out.println("Value is blank");
}
And I prefer to limit uses of such strings that can be searched in the class file that might possibly lead to exploitation of the code.

use if or set value in java and kotlin

I need to compare these 2 codes for CPU and RAM usage. who is better?
enableValidation is a Boolean variable and need to set false.
I have 2 ways:
1. use if
2. set false direct
which one is better?
way 1:
if (enableValidation) {
enableValidation = false;
}
way 2:
enableValidation = false;
As far as CPU/RAM usage, there is almost no difference between these two mentioned code approaches. While approach one is checking for a redundant condition. Both code means at this point enableValidation has to be false, no matter what is the situation.
So code readability perspective, better to assign it to false directly.
java and kotlin will be translated to byte codes so you can view byte code and detect wich one is larger code than other
as i know from c++ , the way 2 is better but here the resource usage is about nothing !
dont realy care about it

How do I use ArrayList<Integer>#contains when I only have a BigInteger?

I am pulling data values from a database that returns a List of <Integer>. However, I would like to see if the List contains my BigInteger. Is there a simple way to do this?
I currently have the following code in Java:
ArrayList<Integer> arr = new ArrayList<Integer>() {{add(new Integer(29415));}};
boolean contains = arr.contains(29415); // true
boolean contains2 = arr.contains(new BigInteger("29415")); // false
I'm not sure on an efficient way to do this?
The correct answer will be returned by evaluation of the following:
val != null
&& BigInteger.valueOf(Integer.MIN_VALUE).compareTo(val) < 0
&& BigInteger.valueOf(Integer.MAX_VALUE).compareTo(val) > 0
&& list.contains(val.intValue())
This will correctly solve the question of whether the BigInteger you have is "contained" within the List<Integer>. Note that here we only downcast where necessary. If the val is outside the range of Integer values there is no need to downcast as we know that the value cannot be within the list.
A more relevant question is whether you should actually be using a List<BigInteger> in place of a List<Integer> but that is a different question and not part of the answer to your explicit question
While arshajii provides a solution which works, i would vote against it.
You should never downcast values. You are running in danger of your program producing larger values which translate to invalid values when downcasted. This kind of bug will be super nasty to troubleshoot months later.
If your code works with BigInteger, then you should convert all values from the database into BigInteger. This is an upcast where you cannot loose values.
Overall I would value correctness over efficiency. If at all, I would reconsider your usage of BigInteger (maybe long is fine?) but because you have it, I assume you have a reason for it.
In Java List.contains() uses the equals() method internally and because BigInteger.equals(Integer) returns false, your List.contains() also returns false. Either use the an List<BigInteger> or extract the Int value from BigInteger (as arshajii explained!). Of course, if you really want to search effectively, you should think of a binary search (in a sorted list) or of another data structure like Map.
You can try using BigInteger#intValue():
arr.contains(myBigInteger.intValue())
Note, however, that if myBigInteger is too big to fit into an int, then only the lower 32 bits will be returned (as described in the linked docs). Therefore, you might want to check if myBigInteger is less than or equal to Integer.MAX_VALUE before checking for containment.

Is there a way to change the internal radix of Java code?

If I want to write a program that deals almost exclusively with, say, base 8 math, is there a way to change the source code or JVM to perform all calculations with this radix without having to explicitly change it on every integer reference?
For example, instead of...
private static final int RADIX = 8;
// ... then, elsewhere ...
System.out.println(Integer.toString(3 + 7, RADIX));
... I could just do ...
System.out.println(3 + 7);
... and have it print the same result of 12? Is there some environment variable or in-code setting I can apply? Or is this simply not possible?
This may seem arcane or a "why in the world would you want to do this" scenario, but if you can imagine having to perform a large number of non-trivial calculations under a different base, then you can see how it would become extremely tedious extremely fast to have to keep manually converting numbers to the appropriate radix.
No, there is no feature like that.
A number is a number no matter what base you're talking about, the radix only comes in when converting to/from strings. If you have to do this all of the time, then create some utility methods that do the work, and always call them. Alternatively, write your own Integer-like class that handles the fromString/toString bit.
public final class OctalInteger extends Number implements Comparable<OctalInteger> {
// Basically a copy of Integer.java, but changes the methods dealing with Strings
}
No.
Also, why would you want that? Imagine how many pieces of code you would break that run in the same JVM - no one coding libraries would expect the default radix to suddenly change.
Your use of a constant is the right way to go.
You can't change default radix. But you can easily write your own print and println procedures which would print integers in octal base.

Reflection, hashtable or methods for performance?

I'm trying to write a Java program to decode and encode Ogg streams. I've got a decoder working but I didn't like the fact that I had duplicate code so I started writing something like that:
Decoder oggDecoder = new Decoder(
new StringDecoder( "Ogg" ),
new IntDecoder( "something" )//, ...
);
I wrote encoders and decoders for some "types" and then use them to build the whole thing.
But then I don't know how to store the result. I have 3 options I know:
- keep the data in an array of bytes and provide a get( String name ) and set( String name, Object value ) methods that will work directly on the bytes.
- use a dictionary.
- use a class and use reflection to set the properties.
I'm not that much into performance and if it's slow I don't really care as long as it's fast enough to read music. Meaning that I know writing the functions myself would make it faster but I want to write just one function working for all the properties.
So what do you think would be the fastest way of doing this?
Another way to ask this question would be:
Given a set of field names as an array of String, what is the most appropriate data structure to store the corresponding values that got decoded from a byte stream:
- keep them as byte
- store them in a dictionary
- store them in a class using reflexion
Thanks in advance for your answer.
KISS - just use a HashMap<String, byte[]>. No reflection needed.
Update
I don't think I understood at first what you want, but now I think what you are looking for is a hetergeneous map structure.
Here's a question that might be of more use to you.

Categories