Аккаунт Войти / Регистрация
Тема
Размер текста
Conditional operators in Java

Conditional operators in Java

Java — Conditional Operators

Visual article with examples: if / else / logic / ternary operator / switch

In brief — conditional operators allow the program to make decisions: to execute one piece of code or another depending on the expression. Below are compact explanations and examples that you can copy and run in your environment.

The main idea: "if the condition is true — do one, otherwise — do the other." This is how programs become smarter.

1) Simple if / else

Check equality and output the result.


// example: simple if/else
int a = 1;
if (a == 1) {
    System.out.println("Условие выполняется: a == 1");
} else {
    System.out.println("Условие не выполняется");
}
    

Output when a = 1: Condition is met: a == 1

2) else if — chain of checks

When you need to check several options one after another.


int a = 2;
if (a == 1) {
    System.out.println("a == 1");
} else if (a == 2) {
    System.out.println("a == 2");
} else {
    System.out.println("none of the options");
}
    

Tip: the order is important — the first matching if/else if "absorbs" the execution.

3) Comparison Operators and Negation

  • != — not equal
  • >, < — greater / less
  • >=, <= — greater/less or equal
  • ! — logical "not" for boolean expressions

int a = 3;
if (a != 2) {
    System.out.println("a не равно 2");
}
if (a > 2) {
    System.out.println("a больше 2");
}
    

4) Logical operators: && (AND) and || (OR)

Composite conditions.


int a = 3, b = 1;
// logical AND: both conditions must be true
if (a == 3 && b == 1) {
    System.out.println("both conditions are true");
}
// logical OR: it’s enough for at least one to be true
if (a == 2 || b == 1) {
    System.out.println("at least one is true");
}
    

5) Ternary Operator — Compact, but Cautious

Shortened form of if/else. Good for simple assignments, but beginners are better off reading the regular if.


int a = 3, b = 1;
int c = (b == 1) ? (a + 1) : (a - 1);
System.out.println(c);
    

If b == 1, then c = a + 1, otherwise c = a - 1.

6) switch — when there are many discrete options

Easy to read, especially with many integer/string cases. Don't forget break.


int a = 5;
switch (a) {
    case 1:
        System.out.println("a == 1");
        break;
    case 2:
        System.out.println("a == 2");
        break;
    case 3:
        System.out.println("a == 3");
        break;
    default:
        System.out.println("Condition not met");
}
    

7) A small cheat sheet for debugging

  • To understand why it doesn't enter the condition — print the values of the variables before checking.
  • Check types: comparison == for references (objects) — is not the same as for primitives.
  • The ternary operator is good in one line — but do not make complex logic in it.

Test — How well did you understand the lesson?

Оставить комментарий

Мой канал в социальных сетях
Отправляя email, вы принимаете условия политики конфиденциальности

Полезные статьи:

Pointers, functions, and execution control in Go vs Java | Types - Language
Series: Go for Java Developers — analyzing pointer, closures, defer, panic/recover In this article, we will analyze how Go manages the state and lifecycle of functions. A feature of Go is the ease of…
Multithreading in Go and Java: types of tasks and solution patterns
Multithreading is not just about "starting a million threads and letting them calculate". It is the art of efficiently using CPU and memory resources, safely processing data, and properly distributing…
Java under the Microscope: Stack, Heap, and GC using Code Examples
Diagram - Java Memory Model - Heap / Non-Heap / Stack Heap (memory for objects) Creates objects via new. Young Generation: Eden + Survivor. Old Generation: objects that have survived several GC c…

Новые статьи:

Concurrency is not about “starting many threads”. It’s about agreements between them. Imagine a restaurant kitchen: — cooks (threads / goroutines) — orders (tasks) — and the main question: how do th…
When HashMap starts killing production: the engineering story of ConcurrentHashMap
Imagine a typical production service. 32 CPU hundreds of threads configuration / session / rate limits cache tens of thousands of operations per second And somewhere inside — a regular Map. At first…
Zero Allocation in Java: what it is and why it matters
Zero Allocation — is an approach to writing code in which no unnecessary objects are created in heap memory during runtime. The main idea: fewer objects → less GC → higher stability and performance. …