[Go to site: main page, start]

0% found this document useful (0 votes)
9 views64 pages

Java Variable Types and Operators Guide

The document provides an overview of Java programming concepts, focusing on variable naming conventions, types of variables, and operators including arithmetic, bitwise, relational, and logical operators. It explains the rules for valid variable names, the scope and lifetime of different variable types, and demonstrates the use of operators through code examples. Additionally, it highlights the advantages of short-circuit logical operators in terms of efficiency and error prevention.

Uploaded by

4ptjn6xnmm
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)
9 views64 pages

Java Variable Types and Operators Guide

The document provides an overview of Java programming concepts, focusing on variable naming conventions, types of variables, and operators including arithmetic, bitwise, relational, and logical operators. It explains the rules for valid variable names, the scope and lifetime of different variable types, and demonstrates the use of operators through code examples. Additionally, it highlights the advantages of short-circuit logical operators in terms of efficiency and error prevention.

Uploaded by

4ptjn6xnmm
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

CS6308- Java Programming

V P Jayachitra
Assistant Professor
Department of Computer Technology
MIT Campus
Anna University
public class Variables {
Variables public static void main(String[] args) {
// Valid variable names
• A variable is a storage location used to // Valid: starts with a letter, only contains letters & digits
hold data values that can be modified int userAge = 70;
and accessed during the execution of a // Valid: starts with an underscore, contains letters
program. String _userName = “James Gosling";
// Valid: contains a dollar sign, starts with a letter
• Allowed Characters: double annualSalary$ = 10000000.50;
• Letters: Uppercase (A-Z) and lowercase (a-z)
// Invalid variable names (cause errors)
• Digits: (0-9), but not as the first character /*
int 1stVariable = 100; // Invalid: starts with a digit
• Underscores: (_) String user-age = "Alice"; // Invalid: contains a hyphen
double @salary = 199.99; // Invalid: contains @ symbol
boolean user Name = true; // Invalid: contains a space
• Dollar Sign: ($), though its use is generally */
discouraged for regular variable names
}
}
•Starting Character: Variable names must start with a letter (A-Z or a-z) or an underscore (_)
•Subsequent Characters: After the first character, variable names can include letters, digits, underscores, and
dollar signs.
•Case Sensitivity: Java is case-sensitive(myVariable, MyVariable, and MYVARIABLE are different variables)
•Reserved Words: Variable names cannot be Java reserved keywords.
Variable types
In Java programming the main types of variables are local, instance, class and parameters.
Local Variables Instance Variables Class Variables or Parameters
or Non-static fields Static Variables
Scope: Declared inside Declared within a class Declared with the static Declared in
methods, but outside methods. keyword within a class. method or
constructors, or constructor
blocks. definitions.
Lifetime: Exist only during the Exist as long as the Exist for the duration of Exist only during
execution of the object of the class the program and are the execution of
method or block exists. shared among all the method or
where they are instances of the class. constructor
declared.
Initialization: Must be initialized Automatically initialized Automatically initialized Initialized with
before use. to default values if not to default values if not the values passed
explicitly initialized. explicitly initialized. to the method or
constructor when
it is called.
public class Variable { public static void main(String[] args) { obj1
// Class variable (static variable) // Create two instances of Variable ######
static int classVariable; // Default value: 0 Variable obj1 = new Variable(10); Class Variable: 100
// Instance variable Variable obj2 = new Variable(20); Instance Variable: 10
int instanceVariable; // Default value: 0 // Modify the class variable Local Variable: 20
// Constructor with parameter [Link] = 100; obj2
public Variable(int instanceVariable) { // instance variables ######
// Initialize instance variable via constructor parameter [Link]("obj1"); Class Variable: 100
[Link] = instanceVariable; [Link]("######"); Instance Variable: 20
} [Link](); Local Variable: 20
public void method() { [Link]("obj2"); ######
// Local variable [Link]("######"); Class Variable : 100
int localVariable = 20; // must be initialized before use [Link](); obj1: 10
[Link]("Class Variable: " + classVariable); // class variable obj2: 20
[Link]("Instance Variable:" + instanceVariable); [Link]("######");
[Link]("Local Variable: " + localVariable); [Link]("Class Variable:" +[Link]);
} // instance variables from each object
[Link]("obj1: " + [Link]);
[Link]("obj2: " + [Link]);
}
}
Operators

• Java provides a rich operator environment.


• Most of its operators can be divided into the following four groups:
• Arithmetic
• Bitwise
• Relational
• Logical
Arithmetic Operators
• The operands of the arithmetic operators must be of a numeric type.
• Cannot use them on boolean types, but you can use them
on char types, since the char type in Java is, essentially, a subset
of int.
• Integer Division: Result is an integer. Any fractional part is discarded.
• Floating-Point Division: Retain fractional results.
OPERATOR Description
+ , -, *, /,% Addition, subtraction, multiplication,
division, modulus
+, - Unary plus, unary minus
++, -- Increment, Decrement
+= , -=, *=, /=,%= Addition assignment, subtraction
assignment, multiplication assignment,
division assignment, modulus assignment
The Bitwise Operators
• Java defines several bitwise operators that can be applied to the
integer types: long, int, short, char, and byte.
• These operators act upon the individual bits of their operands.

OPERATOR Description
~ Bitwise unary NOT
&, |, ^ Bitwise AND, OR, EXCLUSIVE OR
>>, <<, >>> Shift Right, Shift Left, Shift Right with zero fill
&=, |=, ^= Bitwise AND assignment, Bitwise OR assignment,
Bitwise Exclusive OR assignment
>>=, <<=, >>>= Shift Right Assignment, Shift Left Assignment, Shift
Right with zero fill Assignment
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5; // binary: 0101
int b = 3; // binary: 0011
// Bitwise Operators
[Link]("Bitwise AND: " + (a & b)); // 1 (binary 0001) Bitwise AND: 1
[Link]("Bitwise OR: " + (a | b)); // 7 (binary 0111) Bitwise OR: 7
[Link]("Bitwise XOR: " + (a ^ b)); // 6 (binary 0110) Bitwise XOR: 6
[Link]("Bitwise Complement: " + (~a)); // -6 (binary 11111010) Bitwise Complement: -6
// Bitwise Assignment Operators Bitwise AND Assignment: 1
a &= b; Bitwise OR Assignment: 7
[Link]("Bitwise AND Assignment: " + a); // 1 Bitwise XOR Assignment: 6
a = 5; // Resetting Left Shift: 12
a |= b; Right Shift: 3
[Link]("Bitwise OR Assignment: " + a); // 7 Unsigned Right Shift: 3
a = 5; // Resetting Unsigned Right Shift of -5: 2147483642
a ^= b;
[Link]("Bitwise XOR Assignment: " + a); // 6
// Shift Operators
[Link]("Left Shift: " + (a << 1)); // 12 (binary 1100)
[Link]("Right Shift: " + (a >> 1)); // 3 (binary 0011)
[Link]("Unsigned Right Shift: " + (a >>> 1)); // 3 (binary 0011)
// Negative number example for unsigned right shift
int negNum = -5;
[Link]("Unsigned Right Shift of -5: " + (negNum >>> 1)); }}
class BitLogic {
public static void main(String args[]) {
String binary[] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" };
int a = 3;
int b = 6;
int or = a | b;
int and = a & b; a = 0011
int xor = a ^ b; b = 0110
int xnor = (~a & b) | (a & ~b); (a|b) or= 0111
int not = ~a & 0x0f; (a&b) and= 0010
(a^b) xor = 0101
[Link](" a = " + binary[a]); (~a&b|a&~b)xnor = 0101
[Link](" b = " + binary[b]); ~a = 1100
[Link](" (a|b) or= " + binary[or]);
[Link](" (a&b) and= " + binary[and]);
[Link](" (a^b) xor = " + binary[xor]);
[Link](" (~a&b|a&~b)xnor = " + binary[xnor]);
[Link](" ~a = " + binary[not]);
}
}
Relational Operators
• The relational operators determine the relationship that one operand has
to the other. Specifically, they determine equality and ordering. outcome of
these operations is a boolean value.
• only integer, floating-point, and character operands may be compared to
see which is greater or less than the other.
int done;
//... if(done == 0)... // This is Java-style.
if(!done)... // Valid in C/C++ if(done != 0)...
if(done)... // but not in Java.

• The reason is that Java does not define true and false in the same way as
C/C++. In C/C++, true is any nonzero value and false is zero.
• In Java, true and false are nonnumeric values that do not relate to zero or
nonzero. Therefore, to test for zero or nonzero, you must explicitly employ
one or more of the relational operators.
Boolean Logical Operators
• The Boolean logical operators shown here operate only
on boolean operands. All of the binary logical operators combine
two boolean values to form a resultant boolean value.

OPERATOR Description
!, &, |, ^ Logical Unary NOT, Logical AND, Logical OR, Logical XOR
&=, |=, ^= Logical AND assignment, Logial OR assignment, Logical
XOR assignment
||, && Short-circuit OR, short-circuit AND
==, != Equal To, Not Equal To
?: Ternary(If Then Else)
Boolean Logical Operators
// Demonstrate the boolean logical operators.
• The logical Boolean class BooleanLogic {
operators, &, |, and ^, public static void main(String args[]) {
boolean a = true;
operate on boolean values boolean b = false;
The logical ! operator boolean c = a | b; a = true
b = false
inverts the Boolean state: boolean d = a & b;
a|b = true
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b); a&b = false
a^b = true
!true==false boolean g = !a;
!a&b|a&!b = true
[Link](" a = " + a);
!false == true. [Link](" b = " + b); !a = false
[Link](" a|b = " + c);
[Link](" a&b = " + d);
[Link](" a^b = " + e);
[Link]("!a&b|a&!b = " + f);
[Link](" !a = " + g);
}
}
Short-Circuit Logical Operators
Short-Circuit OR (||): Short-Circuit AND (&&):
• Evaluates the right-hand operand
• Evaluates the right-hand operand only if the left-hand operand is
only if the left-hand operand is
true.
false
• Prevent unnecessary computations • Avoid operations that could cause
or avoid errors (e.g., check if an errors or be inefficient if the result
object is null before accessing its is already determined by the left-
methods). hand operand.

Advantages of Short-Circuit Operators:


Efficiency: Reduces computational overhead by avoiding unnecessary evaluations.
Error Prevention: Avoids runtime errors or exceptions (e.g., NullPointerException) by ensuring certain conditions are met
before executing potentially risky code.
public class ShortCircuitEffects {
private static int globalCounter = 0;
public static void main(String[] args) {
boolean condition1 = false;
boolean condition2 = true;
// Using short-circuit AND
if (condition1 && performSideEffect()) {
[Link]("Condition met with AND");
} else {
[Link]("Condition not met with AND"); Condition not met with AND
} Condition met with OR
// Using short-circuit OR Global Counter: 1
if (condition2 || performSideEffect()) {
[Link]("Condition met with OR");
} else {
[Link]("Condition not met with OR");
}
[Link]("Global Counter: " + globalCounter);
}
private static boolean performSideEffect() {
globalCounter++;
[Link]("Side effect executed");
return true;
}}
public class ShortCircuitExample { Avoids Unintended State Changes
private static int globalCounter = 0; If the right-hand side of a logical expression (&& or
||) has side effects, and the left-hand side of the
public static void main(String[] args) { expression already determines the result, the right-
boolean conditionA = false; hand side might not be executed.
boolean conditionB = false;
This avoids unintended changes or operations
// Using short-circuit OR (||)
if (conditionA || performSideEffect()) { Side effect executed
[Link]("Condition met with OR"); Condition met with OR
} else { Global Counter: 1
[Link]("Condition not met with OR");
}
If conditionA is true, performSideEffect() is not called
// Print the final value of globalCounter due to short-circuit evaluation.
[Link]("Global Counter: " + globalCounter); This prevents the global variable globalCounter from
} being incremented if it's not necessary

private static boolean performSideEffect() {


// Side effect: modifying a global variable
globalCounter++;
[Link]("Side effect executed");
return true;
}}
public class ShortCircuitExample {
public static void main(String[] args) { Avoids expensive computation
boolean isValid = true; Short-circuit evaluation can enhance performance by
avoiding expensive or time-consuming operations
// Using short-circuit AND (&&) when the result of the expression is already known.
if (isValid && expensiveComputation()) {
[Link]("Condition met with AND"); short-circuit AND (&&) avoid an expensive
} else { computation when it is not necessary.
[Link]("Condition not met with AND");
}
}
If isValid were false, the expensiveComputation()
private static boolean expensiveComputation() { method would not be called at all, which is a key
// Simulate an expensive computation benefit of using short-circuit logical operators; the
[Link]("Expensive computation started..."); output is
try {
Condition not met with AND
[Link](1000); // 1 second delay
} catch (InterruptedException e) {
[Link]();
}
[Link]("Expensive computation finished.");
return false; Expensive computation started...
} Expensive computation finished.
} Condition not met with AND
public class ShortCircuitExample {
public class ShortCircuitExample {
public static void main(String[] args) {
public static void main(String[] args) {
String str = null;
String str = null;
// Using short-circuit AND (&&) to avoid
// Using short-circuit AND (&&) to avoid NullPointerException
NullPointerException
if (str != null && [Link]() > 5) {
if (str != null || [Link]() > 5) {
[Link]("String is longer than 5 characters");
[Link]("String is longer than 5 characters");
} else {
} else {
[Link]("String is null or not longer than 5
[Link]("String is null or not longer than 5
characters");
characters");
}
}
}
} Exception in thread "main"
} String is null or not longer than 5 characters } [Link]: Cannot invoke
"[Link]()" because "str" is null
at
[Link]([Link])

Avoid Exceptions:
Short-circuit operators can prevent exceptions by ensuring that
the second operand is only evaluated if necessary.
The Assignment Operator

• The assignment operator is the single equal sign, =. The assignment


operator works in Java much as it does in any other computer
language. It has this general form:
• var = expression;
• Here, the type of var must be compatible with the type of expression.
• int x, y, z;

x = y = z = 100; // set x, y, and z to 100


The ? Operator
• Java includes a special ternary (three-way) operator that can replace certain types of if-
then-else statements.

• This operator is the ?. It can seem somewhat confusing at first, but the ? can be used
very effectively once mastered. The ? has this general form:
condition ? expression1 : expression2
• condition: An expression that evaluates to a boolean value.
• expression1: Evaluated and returned if condition is true.
• expression2: Evaluated and returned if condition is false

• The result of the ? operation is that of the expression evaluated. Both expression2 and
expression3 are required to return the same (or compatible) type, which can’t be void.

• Here is an example of the way that the ? is employed:


ratio = denom == 0 ? 0 : num / denom;
The ?: Operator

public class TernaryExample {


public static void main(String[] args) {
int i1 = 10; // Example 1
int i2 = -10; // Example 2

int absValue1 = (i1 < 0) ? -i1 : i1;


int absValue2 = (i2 < 0) ? -i2 : i2;

[Link]("Absolute value of " + i1 + " is " + absValue1);


[Link]("Absolute value of " + i2 + " is " + absValue2);
}
} Absolute value of 10 is 10
Absolute value of -10 is 10
Operator Precedence

• In Java, operators have a specific order of precedence, determining


how expressions are evaluated.
• The order of precedence from highest to lowest is as follows.
• Although [ ], ( ), and . are technically separators, they also function as
operators with the highest precedence when used for array access,
method calls, and field access.
• Binary Operations: Evaluated from left to right.
• Assignment Operators: Evaluated from right to left
Operator Precedence
Highest
++ (postfix) -- (postfix)
++ (prefix) -- (prefix) ~ ! + (unary) -(unary) (Type-cast)
* / %
+ -
>> << >>>
> >= < <= instanceof
== !=
&
^
|
&&
||
?:
->
= op= (+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, and >>>=)
Lowest
public class OperatorPrecedence { [Link]("\nMultiplication, division, and modulus:");
public static void main(String[] args) { // Multiplication and division have same precedence
int a = 5; [Link]("a * b / c = " + (a * b / c));
int b = 10; // Parentheses change the order
int c = 2; [Link]("a * (b / c) = " + (a * (b / c)));
// Postfix and prefix operators // Modulus has same precedence as multiplication
[Link](a++ + " " + a); [Link]("a * b % c = " + (a * b % c));
// Prefix increment // Addition and subtraction
[Link](++b + " " + b); [Link]("\nAddition and subtraction:");
// Unary operators // Left to right evaluation
[Link]("\nUnary operators:"); [Link]("a + b - c = " + (a + b - c));
[Link]("Bitwise complement of 5: " + ~a); // precedence across rows
[Link]("Logical NOT of true: " + !true); [Link]("\n different precedence levels:");
[Link]("Unary plus: " + +a); // Prefix increment, then multiplication, then addition
[Link]("Unary minus: " + -a); [Link]("++a * b + c = " + (++a * b + c));
// Type casting // Multiplication before addition
[Link]("\nType casting:"); [Link]("a + b * c = " + (a + b * c));
[Link]("Int to double: " + (double)a); // Parentheses change the order
[Link]("(a + b) * c = " + ((a + b) * c));
}
}
56
11 11

Unary operators:
Bitwise complement of 5: -7
Logical NOT of true: false
Unary plus: 6
Unary minus: -6

Type casting:
Int to double: 6.0

Multiplication, division, and modulus:


a * (b / c) = 30
a*b%c=0

Addition and subtraction:


a + b - c = 15

different precedence levels:


++a * b + c = 79
a + b * c = 29
(a + b) * c = 36
public class OperatorPrecedence {
public static void main(String[] args) {
int a = 5; 56
int b = 10; 11 11
int c = 2;
// Postfix and prefix operators Unary operators:
[Link](a++ + " " + a); Bitwise complement of 5: -7
// Prefix increment Logical NOT of true: false
[Link](++b + " " + b); Unary plus: 6
// Unary operators Unary minus: -6
[Link]("\nUnary operators:");
[Link]("Bitwise complement of 5: " + ~a); Type casting:
[Link]("Logical NOT of true: " + !true); Int to double: 6.0
[Link]("Unary plus: " + +a);
[Link]("Unary minus: " + -a);
// Type casting
[Link]("\nType casting:");
[Link]("Int to double: " + (double)a);
// Multiplication, division, and modulus
[Link]("\nMultiplication, division, and modulus:");
Multiplication, division, and modulus:
// Multiplication and division have same precedence
a * (b / c) = 30
[Link]("a * b / c = " + (a * b / c));
a*b%c=0
// Parentheses change the order
[Link]("a * (b / c) = " + (a * (b / c)));
Addition and subtraction:
// Modulus has same precedence as multiplication
a + b - c = 15
[Link]("a * b % c = " + (a * b % c));
// Addition and subtraction
different precedence levels:
[Link]("\nAddition and subtraction:");
++a * b + c = 79
// Left to right evaluation
a + b * c = 29
[Link]("a + b - c = " + (a + b - c));
(a + b) * c = 36
// Demonstrating precedence across rows
[Link]("\n different precedence levels:");
// Prefix increment, then multiplication, then addition
[Link]("++a * b + c = " + (++a * b + c));
// Multiplication before addition
[Link]("a + b * c = " + (a + b * c));
// Parentheses change the order
[Link]("(a + b) * c = " + ((a + b) * c));
}
}
Control statements
• To cause the flow of execution to advance and branch based on
changes to the state of a program.
• Java’s program control statements can be put into the following
categories:
• Selection
• Iteration
• Jump
Control statements
• Selection statements:
• To choose different paths of execution based upon the outcome of an
expression or the state of a variable.
• Iteration statements:
• To enable program execution to repeat one or more
• Jump statements:
• To allow your program to execute in a nonlinear fashion.
Java’s Selection Statements
• To control the flow of your program’s execution based upon
conditions known only during run time.
• Java supports two selection statements:
• if and switch.
Java’s Selection Statements
• If statement
• The if statement is Java’s conditional branch statement.
• Used to route program execution through two different paths.
if (condition)
statement1;
else
statement2; Nested If
• Here, each statement may be a single statement, or a compound if(condition)
statement enclosed in curly braces (that is, a block). statement;
• The condition is any expression that returns a boolean value. else if(condition)
• The else clause is optional. statement;
else if(condition)
• The if statements are executed from the top down. As soon as one of statement;
the conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the ladder is bypassed. .
.
• The final else acts as a default condition; that is, if all other conditional .
tests fail, then the last else statement is performed.
else
• If there is no final else and all other conditions are false, then no action statement;
will take place.
Selection statement: If statement
// Third example
class ConditionalExamples { int month = 4; // April
public static void main(String args[]) { String season;
// First example if (month == 12 || month == 1 || month == 2)
int bytesAvailable = 10; // Example value season = "Winter";
int n = 5; // Example value else if (month == 3 || month == 4 || month == 5)
if (bytesAvailable > 0) { season = "Spring";
ProcessData(); else if (month == 6 || month == 7 || month == 8)
bytesAvailable -= n; season = "Summer";
} else { else if (month == 9 || month == 10 || month == 11)
waitForMoreData(); season = "Autumn";
bytesAvailable = n; else
} season = "Bogus Month";
// Second example [Link]("April is in the " + season + "."); }
boolean dataAvailable = true; private static void ProcessData() {
if (dataAvailable) [Link]("Processing data..."); }
ProcessData(); private static void waitForMoreData() {
else [Link]("Waiting for more data...");
waitForMoreData(); }
}
Selection statement: Switch switch(expression){
case value1:
• The switch statement is Java’s multiway branch statement. //statement
• It provides an easy way to dispatch execution to different parts of break;
your code based on the value of an expression. case value2:
//statement
• A better alternative than a large series of if-else-if statements. break;
• Expression must resolve to type byte, short, int, char, String or an .
enumeration. .
.
• Duplicate case values are not allowed. The type of each value must case valueN:
be compatible with the type of expression. //statement
• The expression is evaluated once. break;
default:
• The break statement is used to exit the switch statement. //statement
Without break, the program continues to the next case. break;
• If no cases match, the default block is executed (if it exists). }
• Switch can handle byte, short, char, int, String, enum primitive
data types and Wrapper classes (Integer, Byte, Short, Character)
class SwitchExample { switch (i) {
public static void main(String args[]) { // Example with int
byte b = 1; short s = 100; char c = 'A’; int i = 10; case 10:
switch (b) {// Example with byte [Link]("Int value is 10");
case 1: break;
[Link]("Byte value is 1"); default:
break; [Link]("Int value is neither 10 nor 20");
default: break; }
[Link]("Byte value is neither 1 nor 2"); // Example with String
break; } String str = "hello";
switch (s) {// Example with short switch (str) {
case 100: case "hello":
[Link]("Short value is 100"); [Link]("String is 'hello'");
break; break;
default: case “java":
[Link]("Short value is neither 100 nor 200"); [Link]("JamesGosling");
break; } break;
switch (c) {// Example with char default:
case 'A': [Link]("neither 'hello' nor 'JamesGosling'");
[Link]("Char value is A"); break; }
break;
default:
[Link]("Char value is neither A nor B");
break;
}
// Example with enum
Day day = [Link];
switch (day) {
case MONDAY: Byte value is 1
[Link]("It's Monday"); Short value is 100
break; Char value is A
case TUESDAY: Int value is 10
[Link]("It's Tuesday"); String is 'hello'
break; It's Monday
default:
[Link]("It's neither Monday nor Tuesday");
break;
}
}

// Enum type for the days of the week


enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY, SUNDAY
}
} }
case 1: statement in the inner switch does not conflict with the case 1: statement in the outer switch.

class NestedSwitch {
class NestedSwitch { public static void main(String[] args) {
int mode = 2, option = 1;
public static void main(String[] args) {
int mode = 2, option = 1; switch (mode) {
case 1:
switch (mode) { switch (option) {
case 1 -> switch (option) { case 1: [Link]("Mode 1, Option 1"); break;
case 1 -> [Link]("Mode 1, Option 1"); case 2: [Link]("Mode 1, Option 2"); break;
case 2 -> [Link]("Mode 1, Option 2"); case 3: [Link]("Mode 1, Option 3"); break;
case 3 -> [Link]("Mode 1, Option 3"); }
break;
};
case 2:
case 2 -> switch (option) { switch (option) {
case 1 -> [Link]("Mode 2, Option 1"); case 1: [Link]("Mode 2, Option 1"); break;
case 2 -> [Link]("Mode 2, Option 2"); case 2: [Link]("Mode 2, Option 2"); break;
case 3 -> [Link]("Mode 2, Option 3"); case 3: [Link]("Mode 2, Option 3"); break;
}; }
} break;
} }
}
}
}
case '-':
Selection statement: Switch result = num1 - num2;
import [Link]; [Link]("%.2f - %.2f = %.2f", num1, num2, result);
break;
public class SimpleCalculator { case '*':
public static void main(String[] args) { result = num1 * num2;
Scanner scanner = new Scanner([Link]); [Link]("%.2f * %.2f = %.2f", num1, num2, result);
double num1, num2, result; break;
char operation; case '/':
[Link]("Simple Calculator"); if (num2 != 0) {
[Link]("Enter first number:"); result = num1 / num2;
num1 = [Link](); [Link]("%.2f / %.2f = %.2f", num1, num2, result);
[Link]("Enter an operation (+, -, *, /):"); } else {
operation = [Link]().charAt(0); [Link]("Error: Division by zero!"); }
[Link]("Enter second number:"); break;
num2 = [Link](); default:
switch (operation) { [Link]("Error: Invalid operation!");
case '+': } } } Simple Calculator Simple Calculator
result = num1 + num2; Enter first number: Enter first number:
[Link]("%.2f + %.2f = %.2f", num1, num2, result); 10 10
break; Enter an operation (+, -, *, /): Enter an operation (+, -, *, /):
# *
Enter second number: Enter second number:
2 2
Error: Invalid operation! 10.00 * 2.00 = 20.00
Selection statement: Switch
• Three important features of the switch statement to note:

• The switch differs from the if in that switch can only test for equality, whereas if
can evaluate any type of Boolean expression. That is, the switch looks only for a
match between the value of the expression and one of its case constants.

• No two case constants in the same switch can have identical values. Of course, a
switch statement and an enclosing outer switch can have case constants in
common.

• A switch statement is usually more efficient than a set of nested ifs in terms of
execution speed and code clarity, particularly when there are many cases to
evaluate
Selection statement: switch vs if
• To select among a large group of values, a switch statement will run
much faster than the equivalent logic coded using a sequence of if-
elses.
• The compiler can do this because it knows that the case constants are
all the same type and simply must be compared for equality with
the switch expression.
• The compiler has no such knowledge of a long list of if expressions.
Iteration Statements:
• Java’s iteration statements are
• for,
• while, and
• do-while.
• These statements are commonly call loops.
• A loop repeatedly executes the same set of instructions until a
termination condition is met.
Iteration statement: While
• The while loop is Java’s most fundamental loop statement. It repeats a
statement or block while its controlling expression is true.
while(condition) {
// body of loop
}

• The condition can be any Boolean expression.


• The body of the loop will be executed as long as the conditional expression
is true.
• When condition becomes false, control passes to the next line of code
immediately following the loop.
• The curly braces are unnecessary if only a single statement is being
repeated.
class NoBody { class SimpleWhileLoop {
public static void main(String[] args) { public static void main(String[] args) {
int i, j; int count = 1; // Initialize the counter
while (count <= 5) {
i = 100; [Link]("Count is: " + count);
j = 200; count++; // Increment the counter
}
// Find midpoint between i and j }
while (++i < --j); // no body in this loop }

[Link]("Midpoint is " + i);


}
}
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Midpoint is 150
Iteration statement: do-while
• Each iteration of the do-while loop first executes the body of the loop
and then evaluates the conditional expression.

• If this expression is true, the loop will repeat. Otherwise, the loop
terminates.

• Java’s loops, condition must be a Boolean expression.


do {
// body of loop
} while (condition);
import [Link];
// validate user input

class DoWhileLoopExample {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int number;
do {
[Link]("Please enter a number between 1 and 10: ");
number = [Link]();

if (number < 1 || number > 10) {


[Link]("Invalid input. Try again.");
}
} while (number < 1 || number > 10);
Please enter a number between 1 and 10: 5
You entered: 5
[Link]("You entered: " + number);
} Please enter a number between 1 and 10: 11
} Invalid input. Try again.
Iteration statement: While vs do While
• While loop
• The conditional expression controlling a while loop is initially false, then the
body of the loop will not be executed at all.
• Do while loop
• Execute the body of a loop at least once, even if the conditional expression is
false to begin with.
• To test the termination expression at the end of the loop rather than at the
beginning.
• The do-while loop always executes its body at least once.
Iteration statement:for
• There are two forms of the for loop.
• for loop
• Requires manual management of the index and loop bounds.
• Indexing required for(initialization; condition; increment){
• Read and Write access // body of the loop
}

• for each loop


• iterates directly over elements in arrays or collections
• No indexing required
• Read-only access for (Type element : Array or collection) {
// body of the loop
}
for(initialization; condition; increment){
// body of the loop
Iteration statement: for }

• First, the initialization portion of the loop is executed only once when
the loop starts.
• Next, Boolean expression condition is evaluated.
• If this expression is true, then the body of the loop is executed.
• If it is false, the loop terminates.
• Next, the iteration portion of the loop is executed.
• The loop then iterates, first evaluating the conditional expression,
then executing the body of the loop, and then executing the iteration
expression with each pass. This process repeats until the controlling
expression is false.
Iteration statement:for
• There are two forms of the for loop.
• for loop
String[] javaDevelopers = {"James", "Patrick", "Mike"};
for (int i = 0; i < [Link]; i++) {
[Link](javaDevelopers[i]);
}

• for each loop


String[] javaDevelopers = {"James", "Patrick", "Mike"};
for (String name : javaDevelopers) {
[Link](name);
}
Basic for Loop For loop with variable declared inside:

class VariableInsideForLoop {
class BasicForLoop { public static void main(String[] args) {
public static void main(String[] args) { // Print Fibonacci sequence up to 100
// Print squares of numbers from 1 to 5 int prev = 0;
for (int i = 1; i <= 5; i++) { [Link]("Fibonacci sequence: ");
[Link]("Square of " + i + " is " + for (int current = 1; current <= 100; ) {
(i * i)); [Link](current + " ");
} int next = prev + current;
} prev = current;
} current = next;
}
Square of 1 is 1 }
Square of 2 is 4 }
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
Fibonacci sequence: 1 1 2 3 5 8 13 21 34 55 89
For loop with some parts empty:
class EmptyPartsForLoop {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
For loop with boolean condition: int index = 0;
class BooleanConditionForLoop {
public static void main(String[] args) { for (; index < [Link];) {
int sum = 10; [Link]("Element at index " + index + ": " +
boolean reachedTarget = false; numbers[index]);
int num ; index++;
for ( num=1; !reachedTarget; num++) { }
sum += num; } Element at index 0: 1
if (sum > 100) { } Element at index 1: 2
reachedTarget = true; Element at index 2: 3
} Element at index 3: 4
} Element at index 4: 5
[Link]("Sum exceeded 100 after adding " + num+ " numbers"); }
}

Sum exceeded 100 after adding 14 numbers


class EmptyPartsForLoop {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int index = 0; Element at index 0: 1
Boolean complete=false; Element at index 1: 2
for (; !complete;) { Element at index 2: 3
[Link]("Element at index " + index + ": " + numbers[index]); Element at index 3: 4
if(index==4) complete=true; Element at index 4: 5
index++;
} An infinite loop. This loop will run forever
} because there is no condition under which it
} will terminate.
class InfiniteForLoop { class InfiniteWhileLoop {
public static void main(String[] args) { public static void main(String[] args) {
int counter = 0; int counter = 0;
for (;;) { while (true) {
[Link]("This is iteration " + (++counter)); [Link]("This is iteration " + (++counter));
if (counter == 5) { if (counter == 5) {
[Link]("Breaking out of the infinite loop"); [Link]("Breaking out of the infinite loop")
break; break;
} }
} }
} }
}
An infinite loop. This loop will run forever because there is no condition under which it will terminate.
for (;;) { while (true) {
// code // code
if (/* condition */) { if (/* condition */) {
break; // Exit loop based on a condition break; // Exit loop based on a condition
} }
} }
class InfiniteForLoop { class InfiniteWhileLoop {
public static void main(String[] args) { public static void main(String[] args) {
int counter = 0; int counter = 0;
for (;;) { while (true) {
[Link]("This is iteration " + (++counter)); [Link]("This is iteration " + (++counter));
if (counter == 5) { if (counter == 5) {
[Link]("Breaking out of the infinite loop"); [Link]("Breaking out of the infinite loop");
break; break;
} }
} This is iteration 1 } This is iteration 1
} This is iteration 2 } This is iteration 2
} This is iteration 3 } This is iteration 3
This is iteration 4 This is iteration 4
This is iteration 5 This is iteration 5
Breaking out of the infinite loop Breaking out of the infinite loop
For loop with multiple variables:
To allow two or more variables to control a for loop, Java permits you to include multiple statements in both
the initialization and iteration portions of the for. Each statement is separated from the next by a comma.

class MultipleVariablesForLoop {
public static void main(String[] args) {
// Print a countdown with days and hours
for (int days = 3, hours = 0; days >= 0; days--, hours += 6) {
[Link]("Time remaining: " + days + " days and " + hours + " hours");
}
}
}

Time remaining: 3 days and 0 hours


Time remaining: 2 days and 6 hours
Time remaining: 1 days and 12 hours
Time remaining: 0 days and 18 hours
Iteration statement: For-Each version of the
for loop
• A for-each style loop is designed to cycle through a collection of
objects, such as an array, in strictly sequential fashion, from start to
finish.
//The general form of the for-each
for(type itr-var : collection)
statement-block

• type specifies the type


• itr-var specifies the name of an iteration variable that will receive the
elements from a collection, one at a time, from beginning to end.
Basic for-each loop:

// Basic for-each style loop


class ForEachExample {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Cherry", "Date", "berry"};
int totalLength = 0;
// for-each style to display and sum the length of fruit names
for (String fruit : fruits) {
[Link]("Fruit name: " + fruit);
totalLength += [Link]();
}
[Link]("Total length of all fruit names: " + totalLength);
}
}
Fruit name: Apple
Fruit name: Banana
Fruit name: Cherry
Fruit name: Date
Fruit name: berry
Total length of all fruit names: 26
For-each loop with break

class ForEachWithBreak {
public static void main(String[] args) {
double[] prices = {10.99, 5.49, 15.99, 20.00, 7.99, 30.50};
double budget = 40.00;
double totalSpent = 0;
// for-each to sum prices until budget is exceeded
for (double price : prices) {
[Link]("Checking item priced at: $" + price);
if (totalSpent + price > budget) {
break; // Stop if adding this item would exceed the budget
}
totalSpent += price;
}
[Link]("Total spent within budget: $" + totalSpent);
}
}
Checking item priced at: $10.99
Checking item priced at: $5.49
Checking item priced at: $15.99
Checking item priced at: $20.0
Total spent within budget: $32.47
For-each loop with 2D

class ForEachWith2D {
public static void main(String[] args) {
String[][] schedule = {
{"Monday", "Math", "History"},
{"Tuesday", "Science", "English"},
{"Wednesday", "Art", "Music"}
};

// Use for-each to display the schedule


for (String[] day : schedule) {
for (String subject : day) {
[Link](subject + "\t");
}
[Link]();
}
}
Monday Math History
}
Tuesday Science English
Wednesday Art Music
Using type inference in for loops

class TypeInferenceInFor {
public static void main(String[] args) {
[Link]("Powers of 2: ");
for (var i = 1; i <= 128; i *= 2) {
[Link](i + " ");
}
[Link]();

var temperatures = new double[] {98.6, 100.4, 97.3, 99.1, 98.8};


[Link]("Temperatures: ");
for (var temp : temperatures) {
[Link]("%.1f°F ", temp);
}
[Link]();
}
}

Powers of 2: 1 2 4 8 16 32 64 128
Temperatures: 98.6°F 100.4°F 97.3°F 99.1°F 98.8°F
Jump Statements

• Java supports three jump statements:


• break,
• continue, and
• return.
• These statements transfer control to another part of your program.
Break
• Force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
• When a break statement is encountered inside a loop, the loop is
terminated and program control resumes at the next statement
following the loop. i: 0
i: 1
// Using break to exit a loop. i: 2
class BreakLoop { i: 3
public static void main(String args[]) { i: 4
for(int i=0; i<100; i++) { i: 5
if(i == 10) break; // terminate loop if i is 10 i: 6
[Link]("i: " + i); i: 7
} i: 8
[Link]("Loop complete."); i: 9
} Loop complete..
}
// Using break to exit from nested loops
Using break as labels class BreakLoop4 {
public static void main(String args[]) {
// Using break as a form of goto. outer: for(int i=0; i<10; i++) {
class Break { [Link]("outer loop " + i + ": ");
public static void main(String args[]) { for(int j=0; j<20; j++) {
boolean t = true; if(j == 10) break outer; // exit inner and outer loops
[Link](j + " ");
one: { }
two: { [Link]("I won’t execute");
three: { }
[Link]("I am executable in three block."); [Link]("Outer Loops complete.");
if(t) break three; // break out of three block }
[Link]("I won't execute"); }
}
[Link]("I am executable at block two");
if(t) break two; // break out of two block outer loop 0: 0 1 2 3 4 5 6 7 8 9 Outer Loops complete.
}
[Link]("This is at block one.");
}
} I am executable in three block.
} I am executable at block two
This is at block one.
Using break as labels
// This program contains an error.
class BreakWithErr {
public static void main(String args[]) {
one: for(int i=0; i<10; i++) {
[Link]("Pass " + i + ": ");
}

for(int j=0; j<10; j++) {


if(j == 10) break one; // error- one is not in this scope
[Link](j + " ");
}
}
}

java: undefined label: one


Using continue

• In while and do-while loops, a continue statement causes control to


be transferred directly to the conditional expression that controls the
loop.
• In a for loop, control goes first to the iteration portion of
the for statement and then to the conditional expression.
• For all three loops, any intermediate code is bypassed.
// Usage continue with a label.
// Usage of continue. class ContinueLabel {
class Continue { public static void main(String args[]) {
public static void main(String args[]) { outer: for (int i=0; i<10; i++) {
for(int i=0; i<10; i++) { for(int j=0; j<10; j++) {
[Link](i + " "); if(j > i) {
if (i%2 == 0) continue; [Link]();
[Link](""); continue outer;
} }
} }
} [Link](" " + (i + j));
}
[Link](); }
}
01 0
23 12
45 234
67 3456
89 45678
5 6 7 8 9 10
6 7 8 9 10 11 12
7 8 9 10 11 12 13 14
8 9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16 17 18
jump statement:Return
• The return statement is used to explicitly return from a method.
• That is, it causes program control to transfer back to the caller of the
method. As such, it is categorized as a
// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
I will execute.
[Link](" I will execute.");

if(t) return; // returning to caller

[Link](“I won't execute.");


}
}

You might also like