Java/Operators

From Meshplex

Jump to: navigation, search
Image:Java_programming.jpg
Introduction to Java
Overview of Java
How to Setup Java on your PC
Data Types, Variables,and Arrays
Operators
Packages, Classes, and Interfaces
Java Program
Modifiers
Control Statements
Exception Handling
Object Oriented Programming
Wrappers
Strings
Math
Arrays
Random Numbers
Date and Time
Regular Expressions
Java Collections
Generics
Java Thread and Multithreading
Java IO and file Handling
Java Network Programming
RMI
Image, Audio, Video
GUI
Applets
Internationalization
JDBC
Java and XML
Java provides a rich operator environment. Most of its operators can be divided into the following four groups: assignment, arithmetic, relational, and logical. Java also defines some additional operators that handle certain special situations.
Assignment Operators
The assignment statements has the following syntax:

<variable> = <expression>

The destination variable and the source expression must be type compatible. The destination variable must also have been declared. Since variable can store either primitive data values or object references, <expression> evaluates to either a primitive data value or an object reference. When assigning a value to a primitive , size matters. Be sure you know when implicit casting will occur, when explicit casting is necessary, and when truncation might occur.

Assigning primitive value


int a, b;
a = 2;     // 2 is assigned to variable a
b = 5;     // 5 is assigned to variable b

Assigning references


Home home1 = new Home();  // new object created
Home home2 = home1;       // assigning the reference of home1 in home2

In the above example home1 and home2 points to the same reference. Any change made to attribute in home2, same change will be reflected in the attribute of home1 also. But interesting thing is that if you assign null value to home2 it will be applied only on home2 and not on home1. home1 will still be holding the reference and home2 will be nullified.

Compound Assignment Operators


+=, -=, *=, and /=

examples

int i;
i += 5; // it is equal to i = i + 5

int a;
a -= 5; // it is equal to i = i - 5

int b;
b *= 5  // it is equal to i = i * 5

int c;
c /= 5  // it is equal to i = i / 5

Arithmetic Operators
The arithmetic operators are used to construct mathematical expressions as in algrebra. Their operands are of numeric type.

+ addition            // i = i + 1

- subtraction         // i = i - 1

* multiplication      // i = i * 1

/ division            // i = i / 1. This operator only returns the quotient.

% remainder operator  // i = i % 1. This operator returns the remainder 
                      // value after division.

++ increment operator // i++ . It increments the value by one.

-- decrement operator // i-- . It decrements the value by one.

If you have any doubt about the usage of division operator and remainder operator then please try the below code and see the results.

Code for division operator

public DivisionExample {
 
  public static void main(String args[]) {
 
    int a = 6;
    System.out.println(a / 4);
 
  }
}

Code for remainder operator

public RemainderOpertor {
 
  public static void main(String args[]) {
 
    int a = 6;
    System.out.println(a % 4);
 
  }
}

In Java, + operator is also used for String concatenation. Like an example given below

public StringConcatenation {
 
  public static void main(String[] args) {
 
    String firstName = "FirstName";
    String lastName = "LastName";
    String name = firstName + " " + lastName;
 
    System.out.println("Name is " + name);
  }
}
Relational Operators
Java has six relational operators
<    Less than sign   

<=   Less than or equal to sign

>    Greater than sign

=>   Greater than or equal to sign

==   Equal to sign

!=   Not equal to sign

Less than sign is used to check whether the value of the first variable is less than the value of the second variable.

public LessThanExample {
 
  public static void main(String args[]) {
 
    int a = 5; 
    int b = 10;
 
    if(a < b) {
 
      System.out.println("a is less than b");
    }
  }
}

Less than or equal to sign is used to check whether the value of the first variable is less than or equal to the value of the second variable.

public LessThanEqualExample {
 
  public static void main(String args[]) {
 
    int a = 10; 
    int b = 10;
 
    if(a <= b) {
 
      System.out.println("a is less than or equal to b");
    }
  }
}

Greater than sign is used to check whether the value of the first variable is greater than the value of the second variable.

public GreaterThanExample {
 
  public static void main(String args[]) {
 
    int a = 10; 
    int b = 5;
 
    if(a > b) {
 
      System.out.println("a is greater than b");
    }
  }
}

Greater than or equal to sign is used to check whether the value of the first variable is greater than or equal to the value of the second variable.

public GreaterThanEqualExample {
 
  public static void main(String args[]) {
 
    int a = 10; 
    int b = 10;
 
    if(a => b) {
 
      System.out.println("a is greater than or equal to b");
    }
  }
}

Equal to sign is used to check whether the value of the first variable is equal to the value of the second variable.

public EqualToExample {
 
  public static void main(String args[]) {
 
    int a = 10; 
    int b = 10;
 
    if(a == b) {
 
      System.out.println("a is equal to b");
    }
  }
}

Not equal to sign is used to check whether the value of the first variable is not equal to the value of the second variable.

public NotEqualExample {
 
  public static void main(String args[]) {
 
    int a = 10; 
    int b = 5;
 
    if(a != b) {
 
      System.out.println("a is not equal to b");
    }
  }
}
Logical Operators

These logical operators work only on boolean operands. Their return values are always boolean.

?:  Ternary if-then-else

&   Logical AND

&&  Short-circuit AND

|   Logical OR 

||  Short-circuit OR

^   Logical XOR 

==  Equal to

!=  Not equal to

!   Logical unary NOT

Now we will see the usage of these operators.

?: Ternary if-then-else

public class TernaryOperatorExample {
 
	public static void main(String[] args) {
 
		char ans = 'y';
 
		// (?) condition is checked 
		// (:) value is returned based on the condition. If
		// it is true then the first expression is returned
		// otherwise the second one.
		String value = ans == 'y' ? "IT'S YES" : "OH NO!!!";
		System.out.println(value);
	}
}

& Logical AND

public class ANDOperatorExample {
 
	public static void main(String[] args) {
 
		char ans = 'y';
		int count = 1;
 
		if(ans == 'y' & count == 0) {
			System.out.println("Count is Zero.");
		}
 
                if(ans == 'y' & count == 1) {
			System.out.println("Count is One.");
		}
 
                if(ans == 'y' & count == 2) {
			System.out.println("Count is Two.");
		}
	}
}

&& Short-circuit AND

public class ShortCircuitANDOperatorExample {
 
	public static void main(String[] args) {
 
		int hour = 9;
		int minute = 30;
 
		// short circuit AND operator is differnt from
		// normal AND operator. If happens like this that
		// the when first condition is checked and if it
		// is true then only it checks for the second condition
		// that is on the other side of the &&.
		if (hour == getHour() && minute == getMinute()) {
 
			System.out.println("It is 10:30");
		}
 
	}
 
	public static int getHour() {
		System.out.println("Return Hour");
		return 10;
	}
 
	public static int getMinute() {
		System.out.println("Return Minute");
		return 30;
	}
}

Logical OR

public class ORExample {
 
	public static void main(String[] args) {
 
		int x = 10;
		if(x == 5 | x ==10) {
			System.out.println("Value of x can be divided by 10");
		}
	}
}

Short-circuit OR

public class ShortCircuitORExample {
 
	public static void main(String[] args) {
 
		int hour = 10;
		int minute = 30;
 
		// if the first condition is true then it will not
		// check for the second condition. But if the first
		// condition is false then it will check for second
		// condition. In case of OR either one of the conditions
		// should be true.
		if(hour == getHour() || minute == getMinute()) {
			System.out.println("Correct time of display this message");
		}
	}
 
	public static int getHour() {
		System.out.println("returning hour");
		return 10;
	}
 
	public static int getMinute() {
		System.out.println("returning minute");
		return 30;
	}
}

Logical XOR

public class XORExample {
 
	public static void main(String[] args) {
 
		int a = 1;
		int b = 2;
 
		int c = 3;
		int d = 4;
 
		// XOR will return true only if the conditions
		// are mutually exclusive.
		System.out.println(a == 1 ^ b == 2); // both the conditions are true
		System.out.println(c == 4 ^ d == 3); // both the conditions are false
		System.out.println(c == 4 ^ d == 4); // only second condition is true
	}
}

Equal to

public class EqualToExample {
 
	public static void main(String[] args) {
 
		char ans = 'y';
 
		if(ans == 'y') {
			System.out.println("It is YES.");
		}
	}
}

Not equal to

public class NotEqualToExample {
 
	public static void main(String[] args) {
 
		int value = 4;
		if (value != 10) {
			System.out.println("Value is not equal to 10");
		}
	}
}

Logical unary NOT

public class UnaryNotExample {
 
	public static void main(String[] args) {
 
		boolean flag = false;
 
		// Here the value of the flag is false. But if block
		// is only executed when the condition is true. So
		// in cases we can use Unary Not (!). This negates the
		// boolean value of the flag. If the value of flag is 
		// false and used with Unary Not then it will return
		// true and vice-versa.
		if(!flag) {
			System.out.println("Hello world.");
		}
	}
}
Previous Next
Personal tools