Is not true check, in Java?

KonradN

Super-Moderator
Mitarbeiter
And a != true won't work?
That also works, but a != true is much longer than !a and it is also like normal language: Imagine a variable boolean glasIsEmpty. Do you say:
  • If not glas is empty then ....
  • if glas is empty is false then ...

So when we write code, we try to write easily readable code (so you can simply read code out loud and it should make sense) and also avoid complexity that is not required.

So in short: Yes, that works but is is simply uncommon and the shorter expression is prefered.
 

KonradN

Super-Moderator
Mitarbeiter
Ty. And why not if (!Boolean.TRUE.equals(isActive))? This will handle null vals correctly as well.

When you have Boolean reference which can be null, then this is of course a valid solution.

But that only makes sense, if you have a value that can be null. And often this is avoided in clean code. Possibilities can be:
  • If you have to handle such values, then you could use Optionals instead of null (or generate it with Optional.ofNullable).
  • if true / false are not enough and you have more states, you could use an enum

As you see: You have a lot of different possibilities. You simply have to choose one (which maybe must be accepted by others, too)
 

Anon0

Mitglied
I think clean code is important above all else, not so much external acceptance... Would you prefer int instead of the three-valued bool? Do you prefer null or the Optional concept? Lots of questions for possibly the wrong audience.
 

KonradN

Super-Moderator
Mitarbeiter
Sollten wir nicht einmal ins Deutsche wechseln? Wir sind hier in einem deutschsprachigen Forum ....



"external acceptance" - that should be defined. Acceptance is a crucial part of professional software development and can be found in multiple areas as design discussions, code reviews, ...

int for multiple, defined values: When you have a fixed list of defined values: enum should be a good fit.

Regarding null or Optional: Optional is not an replacement for null or so. You just have to evaluate the situation.

When you give values to others (e.g. a result of a method), then Optional is great because you make sure, that the other developer does not create an NPE.
But inside your internal code: When you handle null (and maybe use some tools that check your code), then it is safe and there is no need to create additional instances.

So in short maybe something like
  • Method results / API Design -> Optional
  • Fields, Parameters -> no Optional
 

Oneixee5

Top Contributor
In professional Java development, writing if (a != true) is considered redundant and "unclean." Here are the reasons why:

Redundancy (Double Logic)
An if statement always expects an expression that evaluates to either true or false.
  • If a is already a boolean variable, it already represents a truth value.
  • By writing (a != true), you are asking the computer to evaluate a, compare it to true, and then generate a new boolean.
It is the linguistic equivalent of saying, "If it is true that it is raining..." instead of simply saying, "If it is raining..."

SyntaxMental TranslationQuality
if (a != true)"If a is not equal to true..."Cluttered
if (a == false)"If a is equal to false..."Clearer, but still wordy
if (!a)"If not a..."Clean & Standard

The criticism of Boolean.TRUE.equals(isActive) is that it sometimes silently masks a bug. If isActive is null because a database query failed or a mapper missed a field, treating it as false might lead to hard-to-find logic errors. Sometimes, you want the code to crash (NPE) so you know exactly where the data is missing.

Here is how you would use Optional to handle your Boolean safely:
Instead of checking for null, you wrap the Boolean object. This forces you to think about the "else" case (what happens if the value is missing).
Java:
Boolean isActive = fetchStatus(); // Could be true, false, or null

// "If it's null, treat it as false"
boolean status = Optional.ofNullable(isActive).orElse(false);

if (status) {
    // Logic for true
}

If you just want to execute a piece of code only if the value is present and 'true', you can chain methods:
Java:
Optional.ofNullable(isActive)
    .filter(Boolean::booleanValue)
    .ifPresent(this::doSomething);

Why use Optionals over Boolean.TRUE.equals()?
Intent: It tells other developers: "Warning! This value might be missing."

Chaining: You can map the value to something else (e.g., if true, return "Active", if false or null, return "Inactive").

No more null: If your method returns Optional<Boolean>, the caller is forced to handle the empty case, which prevents bugs before they happen.
 
Zuletzt bearbeitet:

Oneixee5

Top Contributor
Instead of guessing what true, false, or null means, you define exactly what states exist:
Java:
public enum AccountStatus {
    ACTIVE,
    INACTIVE,
    PENDING_VERIFICATION // This is the "third" value that null often tries to hide
}

Why this is better than Boolean or int:
FeatureBoolean (with null)int (0, 1, 2)Enum
Readabilitynull is confusingWhat is 2?PENDING_VERIFICATION
Type SafetyHighLow (any number fits)Highest
ScalabilityStuck at 3 statesHard to manageEasy to add SUSPENDED

Java:
public void handleStatus(@NonNull AccountStatus status) {
    // If status is null, this will throw an NPE immediately,
    // which is often better than hiding a bug.
    switch (status) {
        case ACTIVE -> sendWelcomeEmail();
        case INACTIVE -> disableAccess();
        case PENDING_VERIFICATION -> notifySupport();
        // No 'default' needed if all enum values are covered!
    }
}
 
Zuletzt bearbeitet:

Anon0

Mitglied
Sollten wir nicht einmal ins Deutsche wechseln? Wir sind hier in einem deutschsprachigen Forum ....
We can. On the other hand, your question in the other thread was also asked in English.

int for multiple, defined values: When you have a fixed list of defined values: enum should be a good fit.

Regarding null or Optional: Optional is not an replacement for null or so. You just have to evaluate the situation.
In my humble opinion, Optional does not solve any problems when trying to avoid null values. You simply cannot completely do without null values. One alternative would be Exceptions, but handling "invalid" return values in valid conditions via Exceptions (program control flow via Exceptions) is not good design.

In practice, Optional does not eliminate null-related issues in Java; it merely shifts them.

First, null is a fundamental part of Java's type system. An Optional itself is a reference type and can therefore also be null. As a result, Optional cannot fully remove the presence of null from a program.

Second, Optional does not reliably prevent runtime errors. Calling Optional.get() on an empty value leads to a NoSuchElementException, which is conceptually no better than a NullPointerException. The error is not avoided; it is simply renamed.

Third, null often represents a valid and meaningful state rather than an error. In many APIs, a missing value is a normal outcome (e.g., "entity not found"). Using exceptions to signal such conditions is poor design, as exceptions should represent exceptional situations, not normal control flow.

Fourth, Optional frequently increases code complexity. Simple and explicit null checks are often more readable, easier to debug, and better integrated with existing frameworks than long chains of map, filter, and orElse.

Finally, even the Java designers intended Optional mainly as a communication tool for return values, not as a universal replacement for null. It is explicitly discouraged for fields, parameters, or serialization-heavy code.

Conclusion: Optional does not solve the null problem; it only wraps it. Since null is unavoidable and often semantically valid, classic Java design with explicit null handling remains one of the most practical and robust approaches.

Zusammenfassend: Vermeiden Sie nach Möglichkeit auch in Ihrem eigenen API-Design die Verwendung von Optional.
 

Oneixee5

Top Contributor
Der Trend geht eindeutig zur Vermeidung von null, @see JSpecify oder auch JSR-305. Optional ist nur ein erster Schritt in Richtung Null-Sicherheit und kann viele Probleme vermeiden. Lesbarkeit und Komplexität sind auch subjektive Wahrnehmungen. Ein Einsteiger sieht die Verwendung von null vermutlich ganz anders, als lesbar und verständlich. Fehler im Zusammenhang mit Nullreferenzen dürften zu den häufigsten Programmierfehlern zur Laufzeit gehören. Tony Hoare, der Erfinder der Nullreferenz, entschuldigte sich 2009 öffentlich für seinen "Billion-Dollar Mistake", die Einführung der Null-Referenz in ALGOL W. In modernen Sprachen wie Swift, Kotlin oder Rust ist die Zuweisung von "nil" bzw. "null" standardmäßig nicht erlaubt.
 

KonradN

Super-Moderator
Mitarbeiter
We can. On the other hand, your question in the other thread was also asked in English.
Die Frage ist: Wieso stellst Du in einem deutschsprachigen Forum eine Frage auf Englisch und bleibst so sehr dabei? Und nur weil wir generell versuchen hilfreich zu sein und daher auch auf Englisch antworten wenn die Frage auf Englisch gestellt wurde, ändert nichts daran, dass hier die Hauptsprache Deutsch sein sollte. Ich wundere mich, wieso das überhaupt eine Frage ist, die diskutiert werden sollte...

Und es ist doch ok, wenn Du eine Meinung hast. Nur wenn Du eine Meinung hast: Wieso fragst Du dann erst nach? Daher stellt sich mit gerade die Frage, was hier Deine Absicht ist Tobias (Davon gehe ich zumindest gerade aus).

Aber spielen wir das Spiel einmal mit:

First, null is a fundamental part of Java's type system. An Optional itself is a reference type and can therefore also be null. As a result, Optional cannot fully remove the presence of null from a program.
Ein Optional sollte niemals null sein. Selbst einfache statische Codeanalyse-Tools werfen eine mögliche null Zuweisung als Fehler. Daher ist das kein Argument, das zieht.

Second, Optional does not reliably prevent runtime errors. Calling Optional.get() on an empty value leads to a NoSuchElementException, which is conceptually no better than a NullPointerException. The error is not avoided; it is simply renamed.
Ja, aber auch hier gilt: Das fangen Tools zur Codeanalyse sauber ab. Und im Gegenzug gibt es sehr schöne fluent Aufbauten, die eben den Check im Code vereinfachen / lesbarer machen.

Third, null often represents a valid and meaningful state rather than an error. In many APIs, a missing value is a normal outcome (e.g., "entity not found"). Using exceptions to signal such conditions is poor design, as exceptions should represent exceptional situations, not normal control flow.
Ja, eine Exception zu werfen ist keine gute Idee. Aber das besagt ja nichts bezüglich Optional.empty aus.

Fourth, Optional frequently increases code complexity. Simple and explicit null checks are often more readable, easier to debug, and better integrated with existing frameworks than long chains of map, filter, and orElse.
Das sehe ich eben nicht so. Ich sehe den Umgang mit Optional oft als deutlich besser lesbarer an.

Finally, even the Java designers intended Optional mainly as a communication tool for return values, not as a universal replacement for null. It is explicitly discouraged for fields, parameters, or serialization-heavy code.
Das ist entspricht doch auch meiner Aussage:
Optional is not an replacement for null or so.

Zusammenfassend: Vermeiden Sie nach Möglichkeit auch in Ihrem eigenen API-Design die Verwendung von Optional.
Den kann ich nicht mehr folgen. Das würde ja besagen, die Entwickler haben da der Java Library etwas gegeben, was schlicht nicht verwendet werden sollte. Und doch wird es innerhalb der Java Library verwendet, z.B. bei Stream (findAny, findFirst, min, max, ....)

Noch einmal ganz deutlich: Du darfst Deine Meinung haben und ich habe keine Intention, diese ändern zu wollen.

Wenn man das Thema etwas vertiefen will: Joshua Bloch hat in Effective Java, 3rd Edition in Item 55 auch relativ ausführlich etwas zu Optionals geschrieben.
 

Anon0

Mitglied
Ein Optional sollte niemals null sein. Selbst einfache statische Codeanalyse-Tools werfen eine mögliche null Zuweisung als Fehler. Daher ist das kein Argument, das zieht.
Vielleicht erst einmal den ganzen Text lesen, bevor man versuchen will, andere zu belehren. Deine Meinung ist mir ~ schnurz. ;)

Und Vielleicht sollte sich @Oneixee5 mal auf Java beziehen, in der sie ja selbsternannte Expertin ist.

Du siehst, eine solche Diskussion macht an dieser Stelle eigentlich keinen Sinn mehr.

Alles Gute
 

mihe7

Top Contributor
Finally, even the Java designers intended Optional mainly as a communication tool for return values, not as a universal replacement for null. It is explicitly discouraged for fields, parameters, or serialization-heavy code.
True. Optional is not just an arbitrary wrapper for references, but a paradigm. When applied consistently, Optional eleminates the need for null return values. We do the same for multi-valued return values by using collections: instead of returning null, we return an empty collection.
 

KonradN

Super-Moderator
Mitarbeiter
Ich bin irritiert... entweder hier ist ein Fehler, den alle übersehen haben, oder es wird ein Java-Feature verwendet, das ich noch nicht kenne.

Da wird doch einfach nur der Wert von var geflippt... das Ergebnis ist doch nicht zwangsweise notTrue, oder?
Da wurde lediglich eine Bedingung von den Klammern der if Anweisung davor gezogen um das dann sozusagen zu benennen. Das ist ein Weg, um etwas lesbarer zu gestalten. Die Alternative wäre, den Check in eine Methode zu verlagern. Der Name sollte also nicht ausdrücken: "Hier ist immer true drin" (Was man einfach direkt ausdrücken würde) sondern "Irgendwas, was in var drin steckt is not true".

Also das Beispiel ist aus meiner Sicht in so fern schlecht, als das
a) keine sinnvollen Namen Verwendung gefunden haben (Das ist aber ohne Kontext einfach nicht sinnvoll machbar.
b) das Beispiel ist für dieses Refactoring einfach schlecht. Von !var zu notVar liefert nicht wirklich eine höhere Lesbarkeit, den beides wird gleich gelesen. Was anderes ist, wenn man komplexe Überprüfungen hat, dann kann sowas sinn machen weil da halt nicht nur irgendwas steht von wegen a && b && !c sondern du hast da eine Dokumentation .... wenn das also abprüft, ob ein gegebener Code die CleanCode Anforderungen erfüllt, dann hast Du nur ein var isCleanCode = a && b && !c und schon muss man nicht mehr prüfen: Was war das noch einmal?

ABER: Darum ging es hier weniger. (Unter dem Strich ging es auch nur darum, dass unserem Tobias langweilig war und er Bespassung gesucht hat)
 

Hobbes

Aktives Mitglied
Da wurde lediglich eine Bedingung von den Klammern der if Anweisung davor gezogen um das dann sozusagen zu benennen. Das ist ein Weg, um etwas lesbarer zu gestalten. Die Alternative wäre, den Check in eine Methode zu verlagern. Der Name sollte also nicht ausdrücken: "Hier ist immer true drin" (Was man einfach direkt ausdrücken würde) sondern "Irgendwas, was in var drin steckt is not true".
Genau das hatte mich irritiert. isNotTrue klang für mich nach Konstante. Der Name notVar wäre für mich deutlich verständlicher gewesen. Und idealerweise hätte es im Beitrag oberhalb des ersten Beispiels gestanden, um noch mehr Kontext zu geben.
 

fsendel

Neues Mitglied
Hello Anon0,
in my opinion is the best way for this to use libary "Boolutils" from Apache.
With Maven you can bind it inside the pom like:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version> <!-- Oder aktuelle Version -->
</dependency>
Then can ou use it: BooleanUtils.isNotTrue(var), this expression is false for var=true only, all other cases (var is null, not a boolean..) are true.
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
V Beginner question with check true value??? Java Basics - Anfänger-Themen 3
C my_table.setRowSelectionAllowed(true) funktioniert nicht; Java Basics - Anfänger-Themen 0
K Warum zeigt dieser reguläre Ausdruck true an? Java Basics - Anfänger-Themen 1
I String Expression mit Java validieren (true / false) Java Basics - Anfänger-Themen 34
F boolean stellt sich auf true Java Basics - Anfänger-Themen 15
W Stackabarbeitung - Wozu dient das "True" ? Java Basics - Anfänger-Themen 1
A Alle true Werte eines boolean Arrays herausfiltern Java Basics - Anfänger-Themen 19
T Invertierung !(false/true) Java Basics - Anfänger-Themen 11
H Koordinateneingabe im 2D Array soll true/false zurückgeben Java Basics - Anfänger-Themen 5
I Methoden List.contains() beim 2. Element = true Java Basics - Anfänger-Themen 1
D Warum nicht true wenn Array leer ist? Java Basics - Anfänger-Themen 8
N Zwei Strings mit "==" vergleichen warum TRUE Java Basics - Anfänger-Themen 2
M Wie gebe ich true or false aus? Java Basics - Anfänger-Themen 9
D Break Sprungmarken Problem einer While True in While True Java Basics - Anfänger-Themen 6
D Zwei Strings sind gleich bei if aber nicht true Java Basics - Anfänger-Themen 2
G Boolschen Ausdruck true machen Java Basics - Anfänger-Themen 2
M Erste Schritte while boolean=false läuft nur bei true??? Java Basics - Anfänger-Themen 23
H if-Abfrage, ungleich und falscher true Wert? Java Basics - Anfänger-Themen 11
J Array Muster mit true und false Java Basics - Anfänger-Themen 6
S If-Anweisunng ist IMMER true Java Basics - Anfänger-Themen 2
DStrohma Operatoren Kleiner-Zeichen in Größer-Zeichen ändern wenn boolen true? Java Basics - Anfänger-Themen 6
C ActionEvent mit CheckBox (true und false) Java Basics - Anfänger-Themen 6
U if true, "deaktiviere" Methoden der Klasse Java Basics - Anfänger-Themen 9
R Hashset.add(Array) liefert immer true? Java Basics - Anfänger-Themen 23
W Methoden Ausgabe true wenn nur Ziffern <= 1 vorhanden Java Basics - Anfänger-Themen 9
W Methoden "Fröhliche Zahl" true | false Java Basics - Anfänger-Themen 14
D Frage zu true false in Schleifen Java Basics - Anfänger-Themen 8
feardorcha boolean array false - true - Abfrage Java Basics - Anfänger-Themen 10
J Variablen Boolean true "übersetzen" in String Java Basics - Anfänger-Themen 10
S Variablen Prüfen, ob einer von vielen boolean true ist Java Basics - Anfänger-Themen 8
3 Collections containsKey() liefert false obwohl equals() true liefert Java Basics - Anfänger-Themen 6
S JTextArea mit LineWrap true viel zu groß! Java Basics - Anfänger-Themen 2
H while(true){} Java Basics - Anfänger-Themen 26
M isHidden() von java.io.File liefert immer true in Windows Java Basics - Anfänger-Themen 3
I wie definiere ich ja oder nein für true or false Java Basics - Anfänger-Themen 7
D setAlwaysOnTop(true); toFront(); - bringt alles nichts Java Basics - Anfänger-Themen 5
C warum liefert equals kein TRUE Java Basics - Anfänger-Themen 12
M true und false treiben mich ins Grab! Java Basics - Anfänger-Themen 5
algorismi Ausführungszeit Vergleich == true Java Basics - Anfänger-Themen 8
D "true" -> Boolean wird false?! Java Basics - Anfänger-Themen 6
D Array zufällig mit 1 oder 0 oder mit true oder false füllen Java Basics - Anfänger-Themen 5
S Elemente einer Liste mit true / false Werten Java Basics - Anfänger-Themen 3
C File.canWrite() immer true? Java Basics - Anfänger-Themen 12
K Frage zu "-Djava.awt.headless=true" und deploy in Java Basics - Anfänger-Themen 4
S if anweisung wird ausgeführt egal ob bedingung true o. false Java Basics - Anfänger-Themen 2
G while (true) ? wodurch wird diese Schleife beendet? Java Basics - Anfänger-Themen 6
O true false Java Basics - Anfänger-Themen 5
B JavaFilter true rückgabe Java Basics - Anfänger-Themen 23
K Primzahl//immer true Java Basics - Anfänger-Themen 7
M Swing Anwendung - boolean schaltet automatisch auf true Java Basics - Anfänger-Themen 2
G Fenster.setVisible(true); true -> false Zwischenwert? Java Basics - Anfänger-Themen 11
A Übungsaufgabe lösen - Problem mit true und false Java Basics - Anfänger-Themen 6
G setVisible(true) <--> toFront() Java Basics - Anfänger-Themen 3
M Per Button einer Funktion true oder false übermitteln? Java Basics - Anfänger-Themen 4
M if(b){ b=false}else{b=true} Java Basics - Anfänger-Themen 4
K public boolean contains (Object obj) > true or false Java Basics - Anfänger-Themen 16
M Problem beim ändern von Komponenten während Visible(true) Java Basics - Anfänger-Themen 4
S Problem mit setEnabled(true) Java Basics - Anfänger-Themen 3
C Shiften.euqals("bahnhof") == true; Java Basics - Anfänger-Themen 4
G Problem mit setVisible(true) Java Basics - Anfänger-Themen 10
E Check Java Basics - Anfänger-Themen 25
F Check ob ein Programm installiert ist Java Basics - Anfänger-Themen 4
C Check ob eine HashMap schon existiert Java Basics - Anfänger-Themen 16
R Check Box mit Array Java Basics - Anfänger-Themen 21
timbeau Javax.Mail: Check this out Java Basics - Anfänger-Themen 10
JTeacher Check your skills Java Basics - Anfänger-Themen 8
B de-Domain Whois-Check? Java Basics - Anfänger-Themen 9
Dit_ "Check for Updates" Funktion Java Basics - Anfänger-Themen 10
I Primzahlen check, String prüfen lassen. Java Basics - Anfänger-Themen 6
A Die Werte der ersten beiden markierten Check-Boxen registrieren Java Basics - Anfänger-Themen 11
Developer_X Wie kann man Check Boxes checken? Java Basics - Anfänger-Themen 10
G check-funktion mit java schreiben! Java Basics - Anfänger-Themen 3
Sam Tophy Einfache Möglichkeit PDF in Java (Swing) anzuzeigen? Java Basics - Anfänger-Themen 1
J PDF-Datei in Java anzeigen Java Basics - Anfänger-Themen 14
D Java 32Bit Java Basics - Anfänger-Themen 45
M Java Programm/Schnittstelle aus unter Ordner in übergeordnetes java programmein binden Java Basics - Anfänger-Themen 2
divorcelawyerseo1 How to accurately calculate the number of days between two dates in Java? Java Basics - Anfänger-Themen 32
J Java.exe mit seltsamen Verhalten Java Basics - Anfänger-Themen 5
M HelloWorld.txt nach HelloWorld.java in Win11 funktioniert nicht Java Basics - Anfänger-Themen 4
Sniper1000 Java lässt sich auf älterem Win 7 nicht mehr installieren Java Basics - Anfänger-Themen 34
J Probleme mit drucken aus Java Java Basics - Anfänger-Themen 3
Gokul Java chart library suggestion for web application? Java Basics - Anfänger-Themen 2
D wie kann ich gcc aus einer .java datei heraus aufrufen? Java Basics - Anfänger-Themen 2
S Text Formatierung in Java Java Basics - Anfänger-Themen 2
B Erste Schritte yaml parsen in Java Java Basics - Anfänger-Themen 19
C Methoden Umlaute in Java Java Basics - Anfänger-Themen 18
W Java-PRogramm liest als EXE-File Nicht USB, jedoch aus NetBeans Java Basics - Anfänger-Themen 45
W Methoden java map ersatz für c++map Java Basics - Anfänger-Themen 3
M Erste Schritte Java Primzahltester Java Basics - Anfänger-Themen 4
A csv Reader für Java? Java Basics - Anfänger-Themen 27
K Java - Enums Java Basics - Anfänger-Themen 30
tomzen Java Unterstützung für exel dateien installieren. Java Basics - Anfänger-Themen 2
Rookar java.lang.NoClassDefFoundError: org/json/JSONException Java Basics - Anfänger-Themen 2
Rookar Mit Button andere java öffnen Java Basics - Anfänger-Themen 4
F Java Object to Hashmap ? Java Basics - Anfänger-Themen 6
I Backend in Java und Ansicht von Dateien in statische HTML Seiten? Java Basics - Anfänger-Themen 15
R Input/Output Verwendung des Euro-Zeichens in Java Java Basics - Anfänger-Themen 7
I Push Nachrichten von JAVA EE App an Mobile App Java Basics - Anfänger-Themen 3
H .java Dateien in Eclipse einbinden und ausführen Java Basics - Anfänger-Themen 1
onlyxlia Schlüsselworte Was meint man mit "einen Typ" in Java erstellen? Java Basics - Anfänger-Themen 2

Ähnliche Java Themen


Oben