Unit2 Java
Unit2 Java
There are multiple types of operators in Java all are mentioned below:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
Output
– : Subtraction a + b = 13
class test { a - b = 7
// Main Function a * b = 30
public static void main (String[] args) {
a / b = 3
// Arithmetic operators a % b = 1
int a = 10;
int b = 3;
}
}
2. Unary Operators
Unary operators need only one operand. They are used to increment and decrement value.
++: Increment operator, used for incrementing the value by 1. There are two varieties of increment
operators.
Post-Increment: Value is first used for computing the result and then incremented.
Pre-Increment: Value is incremented first, and then the result is computed.
– –: Decrement operator, used for decrementing the value by 1. There are two varieties of
decrement operators.
Post-decrement: Value is first used for computing the result and then decremented.
Pre-Decrement: The value is decremented first, and then the result is computed.
// Uniary Operators
import java.io.*;
// Driver Class
class GFG {
// main function
// Integer declared
int a = 10;
int b = 10;
Output
Postincrement : 10
Preincrement : 12
// Using uniary operators
Postdecrement : 10
System.out.println("Postincrement : " + (a++)); Predecrement : 8
System.out.println("Preincrement : " + (++a));
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left associatively, i.e. value
given on the right-hand side of the operator is assigned to the variable on the left, and therefore right-hand
side value must be declared before using it or should be a constant.
The general format of the assignment operator is:
Variable = value;
In many cases, the assignment operator can be combined with other operators to build a shorter
version of the statement called a Compound Statement. For example, instead of a = a+5, we can
write a += 5.
+=, for adding the left operand with the right operand and then assigning it to the variable on the
left.
-=, for subtracting the right operand from the left operand and then assigning it to the variable on
the left.
*=, for multiplying the left operand with the right operand and then assigning it to the variable on
the left.
/=, for dividing the left operand by the right operand and then assigning it to the variable on the
left.
%=, for assigning the modulo of the left operand by the right operand and then assigning it to the
variable on the left.
import java.io.*;
4. Relational Operators
These operators are used to check for relations like equality, greater than, and less than. They return
boolean results after the comparison and are extensively used in looping statements as well as
conditional if-else statements. The general format is,
import java.io.*;
// Driver Class
Output
class test { a > b: true
// main function
public static void main(String[] args) a < b: false
{
// Comparison operators a >= b: true
int a = 10;
int b = 3;
a <= b: false
int c = 5; a == c: false
System.out.println("a > b: " + (a > b)); a != c: true
System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations, i.e., a function similar
to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is
not evaluated if the first one is false, i.e., it has a short-circuiting effect. Used extensively to test for
several conditions for making a decision. Java also has “Logical NOT”, which returns true when the
condition is false and vice-versa,
Conditional operators are:
&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-versa
import java.io.*;
// Driver Class
class test {
Output
// Main Function x && y: false
public static void main (String[] args) {
// Logical operators x || y: true
boolean x = true;
boolean y = false; !x: false
6. Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has three operands and hence the
name Ternary.
class operators {
public static void main(String[] args)
{
int a = 20, b = 10, result;
import java.io.*;
OUTPUT
// Driver class
class test {
// main function
d & e: 4
public static void main(String[] args)
{ d | e: 5
// Bitwise operators
int d = 4; d ^ e: 1
int e = 5;
System.out.println("d & e: " + (d & e)); ~d: -5
System.out.println("d | e: " + (d | e));
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d));
}
}
The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in Java.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
If (condition) {
//code to be executed
}
//Java Program to demonstate the use of if statement.
public class IfExample { Output:
public static void main(String[] args) { Age is greater than 18
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
class IfElseExample {
public static void main(String[] args) {
Output:
//defining a variable
int number=13; odd number
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
} }
The if-else-if ladder statement executes one condition from multiple statements.
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
Output:
System.out.println("B grade");
} C grade
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
The nested if statement represents the if block within another if block. Here, the inner if block condition
executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:
Output:
Example 2:
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper
types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
In other words, the switch statement tests the equality of a variable against multiple values.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Example:
SwitchExample.java
SwitchVowelExample.java
case 'A':
class SwitchVowelExample {
System.out.println("Vowel"); break;
public static void main(String[] args) {
case 'E':
char ch='O';
System.out.println("Vowel"); break;
switch(ch)
case 'I':
{
System.out.println("Vowel"); break;
case 'a':
case 'O':
System.out.println("Vowel"); break;
System.out.println("Vowel"); break;
case 'e':
case 'U':
System.out.println("Vowel"); break;
System.out.println("Vowel"); break;
case 'i':
default:
System.out.println("Vowel"); break;
System.out.println("Consonant");
case 'o':
} } }
System.out.println("Vowel"); break;
case 'u': Output:
System.out.println("Vowel"); break;
Vowel
Loops in Java
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is
recommended to use for loop.
Java provides three types of Conditional statements this second type is loop statement.
While loop: A while loop is a control flow statement that allows code to be executed repeatedly based on
a given Boolean condition. The while loop can be thought of as a repeating if statement.
While loop starts with the checking of Boolean condition. If it evaluated to true, then the loop
body statements are executed otherwise first statement following the loop is executed. For this
reason it is also called Entry control loop.
Once the condition is evaluated to true, the statements in the loop body are executed. Normally
the statements contain an update value for the variable being processed for the next iteration.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
Syntax :
while (boolean condition)
{
loop statements...
}
Import java.io.*;
class test {
public static void main (String[] args) {
int i=0;
while (i<=10)
{
System.out.println(i);
i++;
}
}
}
for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.
class test {
public static void main (String[] args) {
for (int i=0;i<=10;i++)
{
System.out.println(i);
}
}
}
Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.
Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It
is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
Statement execution: Once the condition is evaluated to true, the statements in the loop body are
executed.
Increment/ Decrement: It is used for updating the variable for next iteration.
Loop termination: When the condition becomes false, the loop terminates marking the end of its life
cycle.
Do while: do while loop is similar to while loop with only difference that it checks for condition after
executing the statements, and therefore is an example of Exit Control Loop.
Syntax:
do
{
statements..
}
while (condition);
Example program
class test {
public static void main (String[] args) {
int i=0;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
do while loop starts with the execution of the statement(s). There is no checking of any condition
for the first time.
After the execution of the statements, and update of the variable value, the condition is checked
for true or false value. If it is evaluated to true, next iteration of loop starts.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
It is important to note that the do-while loop will execute its statements at least once before any
condition is checked, and therefore is an example of exit control loop.
Write a program to input a number by the user and check number is prime number or not.
Import java.io.Scanner;
class test {
public static void main (String args[]) {
Scanner obj = new Scanner (System.in);
System.out.print(“Enter the number”);
int n = obj.nextInt();
int pr=0;
for (i=2;i<n;i++)
{
if(n%i == 0)
pr++;
}
if(pr==0)
System.out.print(“Number is prime”);
else
System.out.print(“Number is prime”);
}
}
while do-while
Variable in condition is initialized before the variable may be initialized before or within the
execution of loop. loop.
while loop is entry controlled loop. do-while loop is exit controlled loop.