Java Variable Types and Operators Guide
Java Variable Types and Operators Guide
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
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.
Avoid Exceptions:
Short-circuit operators can prevent exceptions by ensuring that
the second operand is only evaluated if necessary.
The Assignment Operator
• 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.
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
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
}
• If this expression is true, the loop will repeat. Otherwise, the loop
terminates.
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]();
• 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]);
}
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"); }
}
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");
}
}
}
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"}
};
class TypeInferenceInFor {
public static void main(String[] args) {
[Link]("Powers of 2: ");
for (var i = 1; i <= 128; i *= 2) {
[Link](i + " ");
}
[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