0% found this document useful (0 votes)
2 views34 pages

Java Chapter 2

The document provides an overview of Java Booleans, comparison operators, and logical operators, along with examples of their usage. It also covers binary to decimal conversion, bitwise operators in Python, and various real-life applications of boolean logic in programming. Additionally, it includes information on Java strings, string manipulation methods, and examples demonstrating string operations.

Uploaded by

yaraelgendy27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views34 pages

Java Chapter 2

The document provides an overview of Java Booleans, comparison operators, and logical operators, along with examples of their usage. It also covers binary to decimal conversion, bitwise operators in Python, and various real-life applications of boolean logic in programming. Additionally, it includes information on Java strings, string manipulation methods, and examples demonstrating string operations.

Uploaded by

yaraelgendy27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Java Booleans

Java Comparison Operators


Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Java Logical Operators
Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

Returns true if one of the statements is


|| Logical or x < 5 || x < 4
true

Reverse the result, returns false if the


! Logical not !(x < 5 && x < 10)
result is true
Binary → Decimal
1 0 1 1 0 0 1 0

27=128 26=64 25=32 24=16 23=8 22=4 21 = 2 20=1

◼ Simple! Don't memorize formulas from book (makes it harder)

◼ Learn the powers of 2:

❑ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096,…

◼ Then, just add up the appropriate powers

❑ 10110010 = 128 + 32 + 16 + 2 = 178

◼ Real programmers use a calculator! We'll just have simple values in exams so you
don't need a calculator and practice the basics
AND Boolean Operator

• This operator is also called Short Circuit


Boolean AND. It gives the output as True X Y Output
only if both the operands are True. If the first
operand is False, it does not evaluate the False False False
second operand. It gives False as the output
directly.
False True False

True False False

True True Ture


Python Bitwise Operators:
AND
• print(6 & 3)

• """
• The & operator compares each bit and set
it to 1 if both are 1, otherwise it is set to 0:

• 6 = 0000000000000110
• 3 = 0000000000000011
• --------------------
• 2 = 0000000000000010
OR Boolean Operator

• This operator is also called Short Circuit Boolean


X Y Output
OR. It gives the output as True if the any of the
operands are True. If the first operand is True, False False False
this Boolean OR operator does not evaluate the
False True True
second operand. It gives the output as True
directly. True False True

True True True


Python Bitwise Operators: OR

• print(6 | 3)

• """
• The | operator compares each bit and set it to 1
if one or both is 1, otherwise it is set to 0:

• 6 = 0000000000000110
• 3 = 0000000000000011
• --------------------
• 7 = 0000000000000111
XOR

• XOR is a bitwise operator, and it stands for


X Y X&Y X|Y X^Y
"exclusive or." It performs logical operation. If
input bits are the same, then the output will be 0 0 0 0 0
false (0) else true (1). 0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
NOT Boolean Operator

• This operator gives the output as False if the input


X Output
is True. If the input is False, it gives True as the
output. So, it reverses the input.
True False

False True
Bitwise Operators: NOT

• print(~3)

• """
• The ~ operator inverts each bit (0
becomes 1 and 1 becomes 0).

• Inverted 3 becomes -4:


• 3 = 0000000000000011
Example 1: Java Booleans

public class Main {


public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);
}
}
Example 2: Java Booleans

public class Main {


public static void main(String[] args) {
int x = 10;
int y = 9;
System.out.println(x > y);
}
}
Example 3: Java Booleans

public class Main {


public static void main(String[] args) {
int x = 10;
System.out.println(x == 10);
}
}
Real Life Example

public class Main {


public static void main(String[] args) {
int myAge = 25;
int votingAge = 18;
System.out.println(myAge >= votingAge);
}
}
Real Life Example

public class Main {


public static void main(String[] args) {
int myAge = 25;
int votingAge = 18;

if (myAge >= votingAge) {


System.out.println("Old enough to vote!");
} else {
System.out.println("Not old enough to vote.");
} }}
Check if a number is even or odd using a boolean
public class EvenOddChecker {
public static void main(String[] args) {
// Predefined number
int number = 41;
// Boolean to check if the number is even
boolean isEven = (number % 2 == 0);
if (isEven) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}}}
Age and Membership-based Access Control System
public class AccessControlSystem {
public static void main(String[] args) {
// Example user data
int userAge = 22;
boolean isMember = true;
// Define access criteria
int ageThreshold = 18;
// Boolean expressions
boolean isOldEnough = userAge >= ageThreshold;
boolean hasAccess = isOldEnough && isMember;
// Decision logic using Boolean expressions
if (hasAccess) {
System.out.println("Access granted. Welcome!");
} else if (!isOldEnough) {
System.out.println("Access denied. You must be at least " + ageThreshold + " years old.");
} else if (!isMember) {
System.out.println("Access denied. You must be a member to enter.");
}}}
Boolean Algebra in Digital Circuits
public class LogicGates {
public static void main(String[] args) {
boolean A = true, B = false;

// Example circuit: (A AND B) OR (A XOR B)


boolean result = (A && B) || (A ^ B);

// Print the output


System.out.println("Circuit Output: " + result);
}
}
AI Decision System for Autonomous Vehicles
public class TrafficDecision {
public static void main(String[] args) {
String trafficLight = "red"; // You can change to "yellow" or "green"
boolean pedestrianDetected = true;
String roadCondition = "slippery"; // You can change to "clear"
// Decision-making logic
boolean shouldStop = trafficLight.equals("red") || pedestrianDetected;
boolean shouldSlowDown = trafficLight.equals("yellow") || roadCondition.equals("slippery");
// Output the decision
if (shouldStop) {
System.out.println("Car: STOP");
} else if (shouldSlowDown) {
System.out.println("Car: Slow Down");
} else {
System.out.println("Car: Keep Driving");
} }}
Boolean Logic in Cryptography
public class XorCipher {
// XOR cipher method
public static String xorCipher(String text, int key) {
StringBuilder result = new StringBuilder();
for (char c : text.toCharArray()) {
result.append((char)(c ^ key));
}
return result.toString();
}
public static void main(String[] args) {
String message = "Hello, World!";
int key = 42;
// Encrypt
String encrypted = xorCipher(message, key);
System.out.println("Encrypted: " + encrypted);
// Decrypt
String decrypted = xorCipher(encrypted, key);
System.out.println("Decrypted: " + decrypted);
}}
Security Access Control System
public class AccountAccess {
public static void main(String[] args) {
// Predefined username and password
String correctUsername = "user123";
String correctPassword = "password123";
// Hardcoded user input for username and password (simulating login attempt)
String enteredUsername = "user123";
String enteredPassword = "password123";
if (enteredUsername.equals(correctUsername) &&
enteredPassword.equals(correctPassword)) {
System.out.println("Access granted to the account.");
} else {
System.out.println("Access denied. Incorrect username or password.");
}}}
Java Strings
Java Strings

• String is the type of objects that can store the sequence of characters enclosed by double
quotes and every character is stored in 16 bits. A string acts the same as an array of
characters.
Java Strings

public class Main {


public static void main(String[] args) {
String txt = "ABCDEFG ABC";
System.out.println("The length of the txt string is: " + txt.length());
}
}
UpperCase and LowerCase methods

public class Main {


public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}
}
String Concatenation

public class Main {


public static void main(String args[]) {
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
}
}
String Concatenation

public class Main {

public static void main(String[] args) {

String firstName = "John ";

String lastName = "Doe";

System.out.println(firstName.concat(lastName));

}
String Concatenation

public class Main {


public static void main(String[] args) {
int x1 = 10;
int y1 = 20;
int z1 = x1 + y1;

String x2 = "10";
String y2 = "20";
String z2 = x2 + y2;

System.out.println(z1);
System.out.println(z2);
}}
String Comparison

public class Main {


public static void main(String[] args) {

String str1 = "hello";

String str2 = "Hello";

System.out.println(str1.equals(str2));

System.out.println(str1.equalsIgnoreCase(str2));
}}
Substring

public class Main {

public static void main(String[] args) {

String str = "Hello, World!";

String subStr = str.substring(0, 5);


System.out.println(subStr);

}}
Checking if a String Contains Another String

public class Main {

public static void main(String[] args) {

String str = "Java Programming";

System.out.println(str.contains("Java"));

System.out.println(str.contains("Python"));

}}
Trimming Whitespace

public class Main {

public static void main(String[] args) {

String str = " Hello, World! ";

System.out.println(str.trim());
}}
Replacing Characters

public class Main {

public static void main(String[] args) {

String str = "Hello, Java!";

String replacedStr = str.replace("Java", "World");

System.out.println(replacedStr);
}}

You might also like