What is boolean data type in java

Тип boolean

— Привет, Амиго. Хочу рассказать тебе о новом типе данных. Это тип boolean . Переменные этого типа могут принимать всего два значения – true (истина/правда) и false (ложь).

— Этот тип неявно используется во многих местах. Так же, как и результат любого сложения – число, то и результат любого сравнения – истина или ложь – тип boolean . Примеры:

if (a > b) System.out.println(a);
boolean m = (a > b); if (m) System.out.println(a);
boolean m = (a > b); if (m == true) System.out.println(a);
boolean m = (a > b); if (m) System.out.println(a);
public boolean isALessThanB (int a, int b)
public boolean isALessThanB (int a, int b) < boolean m = (a < b); if (m) return true; else return false; >
public boolean isALessThanB (int a, int b) < boolean m = (a < b); return m; >
public boolean isALessThanB (int a, int b) 

Давай используем цикл for, чтобы вывести на экран прямоугольный треугольник из восьмёрок со сторонами (катетами) 10 и 10. То есть в первой строке должна быть одна 8, начиная слева, во второй — две и т.д. Пример вывода на экран: 8

— А что мне делать, если я хочу записать, выражение 0

— Ну, выражений, которые включают три оператора, в Java нет, поэтому тут нужно воспользоваться такой конструкцией: (0

— Подожди, сейчас все объясню. В Java есть три логических оператора: AND (и), OR (или) и NOT (не). С помощью них можно строить условия различной сложности. Эти операторы можно применять только к выражению, имеющему тип boolean . Т.е. (a+1) AND (3) написать нельзя, а (a>1)AND (a<3) – можно.

— Оператор NOT – унарный – его действие распространяется только на выражение справа от него. Он больше похож на знак «минус» перед отрицательным числом, чем на знак умножить

— С переменными типа boolean (логический тип) можно выполнять различные операции.

Читайте также:  Цвет ссылок

— Вот сейчас мы их и рассмотрим:

Логический oператор Обозначение в Java Выражение Результат
AND (и) && true && true true
true && false false
false && true false
false && false false
OR (или) || true || true true
true || false true
false || true true
false || false false
NOT(не) ! ! true false
! false true
Распространённые комбинации и выражения m && !m false
m || !m true
! (a && b) !a || !b
! (a || b) !a && !b

— А можно побольше примеров?

— Реши пока немного задачек.

Источник

What is boolean data type in java

The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean . In addition, this class provides many methods for converting a boolean to a String and a String to a boolean , as well as other constants and methods useful when dealing with a boolean .

Field Summary

Constructor Summary

Allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string «true» .

Method Summary

Returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.

Returns true if and only if the system property named by the argument exists and is equal to the string «true» .

Methods inherited from class java.lang.Object

Field Detail

TRUE

FALSE

TYPE

Constructor Detail

Boolean

public Boolean(boolean value)

Allocates a Boolean object representing the value argument. Note: It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory valueOf(boolean) is generally a better choice. It is likely to yield significantly better space and time performance.

Boolean

Allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string «true» . Otherwise, allocate a Boolean object representing the value false . Examples: new Boolean(«True») produces a Boolean object that represents true .
new Boolean(«yes») produces a Boolean object that represents false .

Method Detail

parseBoolean

Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string «true» . Example: Boolean.parseBoolean(«True») returns true .
Example: Boolean.parseBoolean(«yes») returns false .

Читайте также:  border-style

booleanValue

public boolean booleanValue()

valueOf

Returns a Boolean instance representing the specified boolean value. If the specified boolean value is true , this method returns Boolean.TRUE ; if it is false , this method returns Boolean.FALSE . If a new Boolean instance is not required, this method should generally be used in preference to the constructor Boolean(boolean) , as this method is likely to yield significantly better space and time performance.

valueOf

Returns a Boolean with a value represented by the specified string. The Boolean returned represents a true value if the string argument is not null and is equal, ignoring case, to the string «true» .

toString

Returns a String object representing the specified boolean. If the specified boolean is true , then the string «true» will be returned, otherwise the string «false» will be returned.

toString

Returns a String object representing this Boolean’s value. If this object represents the value true , a string equal to «true» is returned. Otherwise, a string equal to «false» is returned.

hashCode

hashCode

public static int hashCode(boolean value)

equals

Returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.

getBoolean

Returns true if and only if the system property named by the argument exists and is equal to the string «true» . (Beginning with version 1.0.2 of the Java TM platform, the test of this string is case insensitive.) A system property is accessible through getProperty , a method defined by the System class. If there is no property with the specified name, or if the specified name is empty or null, then false is returned.

compareTo

compare

public static int compare(boolean x, boolean y)
Boolean.valueOf(x).compareTo(Boolean.valueOf(y))

logicalAnd

public static boolean logicalAnd(boolean a, boolean b)

logicalOr

public static boolean logicalOr(boolean a, boolean b)

logicalXor

public static boolean logicalXor(boolean a, boolean b)

Источник

Java Booleans

Very often, in programming, you will need a data type that can only have one of two values, like:

Читайте также:  Python pet projects ideas

For this, Java has a boolean data type, which can store true or false values.

Boolean Values

A boolean type is declared with the boolean keyword and can only take the values true or false :

Example

boolean isJavaFun = true; boolean isFishTasty = false; System.out.println(isJavaFun); // Outputs true System.out.println(isFishTasty); // Outputs false 

However, it is more common to return boolean values from boolean expressions, for conditional testing (see below).

Boolean Expression

A Boolean expression returns a boolean value: true or false .

This is useful to build logic, and find answers.

For example, you can use a comparison operator, such as the greater than ( > ) operator, to find out if an expression (or a variable) is true or false:

Example

int x = 10; int y = 9; System.out.println(x > y); // returns true, because 10 is higher than 9 

Example

System.out.println(10 > 9); // returns true, because 10 is higher than 9 

In the examples below, we use the equal to ( == ) operator to evaluate an expression:

Example

int x = 10; System.out.println(x == 10); // returns true, because the value of x is equal to 10 

Example

System.out.println(10 == 15); // returns false, because 10 is not equal to 15 

Real Life Example

Let’s think of a «real life example» where we need to find out if a person is old enough to vote.

In the example below, we use the >= comparison operator to find out if the age ( 25 ) is greater than OR equal to the voting age limit, which is set to 18 :

Example

int myAge = 25; int votingAge = 18; System.out.println(myAge >= votingAge);

Cool, right? An even better approach (since we are on a roll now), would be to wrap the code above in an if. else statement, so we can perform different actions depending on the result:

Example

Output «Old enough to vote!» if myAge is greater than or equal to 18 . Otherwise output «Not old enough to vote.»:

int myAge = 25; int votingAge = 18; if (myAge >= votingAge) < System.out.println("Old enough to vote!"); >else

Booleans are the basis for all Java comparisons and conditions.

You will learn more about conditions ( if. else ) in the next chapter.

Источник

Оцените статью