Pages

Monday 12 August 2019

Use of modifiers

Basic use of modifiers:

Access Modifiers(public,protected,default[package access],private)
Comparison between access modifiers

Visibility
private
default
protected
public
1.Within the same class
Yes
Yes
Yes
Yes
2.From child class of the same package
No
Yes
Yes
Yes
3.From the non-child class of the same package
No
Yes
Yes
Yes
4.From child class of outside package
No
No
Yes, But you must use child class reference only
Yes
5.From the non-child class of outside package
No
No
No
Yes


Non-Access Modifiers(transient,volatile,final,abstract,native,synchronized,static,strictfp)
Impact of final keyword:
If you use keyword final with top-level class, you can't create a subclass of this class.
Example:
  1. public final class A{}
  2. public class B extends A{} // Compiler Error.
If you use the keyword final with the method, you can't override this method.
If you use the keyword final with an instance variable, you must initialize this variable before constructor completion otherwise you will get a compiler error.
Following are the various possible places for the initialization
1.At the time of declaration 
Example:
  1.  final int a =10;
2.Inside instance block
Example:
  1. final int a;
  2. {a = 10;}
3.Inside constructor
Example:
  1. class Test{
  2. final int a;
  3. Test(){
  4. a =10;
  5. }
  6. }
If you are doing initialization other than above places you will get compiler error.
Note: Once the final variable is initialized you can't change it. 
          final instance variable become compile time constant.
If you use keyword final with static variable, you must initialize this variable before class loading completion otherwise, you will get a compiler error.
The following are the various possible places for the initialization.
1.At the time of declaration
Example:
  1.  final static int a =10;
2.Inside static block
Example:
  1. final static int a;
  2. static {a = 10;}
You can use keyword final with local variables or method parameters.
Note: The final is the only modifier that is applicable for local variables and method parameters.
abstract keyword
  • You can use the keyword abstract with top-level classes and methods only.
  • You can't use the keyword abstract with variables.
  • If you use the keyword abstract with class, you can't create an object of this class.
  • If you declare an abstract method(method without body) in a class, you must make that class abstract otherwise you will get a compiler error.
static keyword
  • It is applicable for variables, methods, and blocks
  • If you use keyword static with variables, then initialization happens only once and you can share the same copy throughout the application.
  • If you use keyword static with methods, you can't override this method.
native keyword
  • It is applicable only for methods.
  • The methods which are implemented in non-java is called native method.
transient keyword
  • It is only applicable to variables.
  • If you use keyword transient with an instance variable, this variable won't be serialized.
  • If you use keyword transient with static variables, there is no impact. Because the static variable is not part of the object.
  • If you use keyword transient with the final variable, there is no impact. Because final variables are by default eligible for serialization.
volatile keyword
  • It is only applicable to variables.
  • You can solve the visibility problem by using keyword volatile in a multithreaded environment.
synchronized keyword
  • You can use the keyword synchronized with methods and blocks only.
  • You can solve the data inconsistency problem by using the keyword synchronized in a multithreaded environment.
stricfp keyword
  • You can use keyword stricfp with classes, interfaces, and methods only.
  • To ensure that calculations using floating-point numbers are identical on all platforms.

Saturday 10 August 2019

Garbage collection

Agenda:
  • Introduction
  • The way to make an object eligible for Garbage Collection
  • The methods for requesting JVM  to run Garbage Collection
  • Finalization
  • Memory Leaks
Introduction:
  • Garbage Collection: It is a process of collecting unused objects from the memory(heap).
  • And the actor who is collecting this garbage is called Garbage Collector.
  • Garbage Collection is an automatic process, JVM will do this process with the help of the Garbage collector.
  • As a developer, you can't start the execution of Java's garbage collector. You can only request it to be started by calling
  • System.gc() or Runtime.getRuntime().gc().But calling this method doesn't guarantee when the garbage collector would start.
The way to make an object eligible for Garbage Collection.

1.Nullifying the reference variable:
If an object is no longer required then you can make eligible for Garbage Collection by assigning null
 to all its reference variable.
Studnet s1 = new Student();
Studnet s2 = new Student();
s1 = null;
s2 = null;

2. Reassign the reference variable:
If any object is no longer required then reassign all its reference variables to some other objects then the old object is by default eligible for Garbage Collection.

3.An object created inside a method:
Objects created inside a method are by default eligible for Garbage Collection once method completes.
Example 1:
  1. class Test{
  2. public static void main(String[] args){
  3. createObject();
  4. }
  5. public static void createObject(){
  6. Student s1 = new Student();
  7. Student s2 = new Student();
  8. }
  9. }
Example 2:
  1. class Test{
  2. public static void main(String[] args){
  3. Student s = createObject();
  4. }
  5. public static Student createObject(){
  6. Student s1 = new Student();
  7. Student s2 = new Student();
  8. return s1;
  9. }
  10. }

Example 3:
  1. class Test{
  2. public static void main(String[] args){
  3. createObject();
  4. }
  5. public static Student createObject(){
  6. Student s1 = new Student();
  7. Student s2 = new Student();
  8. return s1;
  9. }
Example 4:
  1. class Test{
  2. static Student s1;
  3. public static void main(String[] args){
  4. createObject();
  5. }
  6. public static void createObject(){
  7. s1 = new Student();
  8. Student s2 = new Student();
  9. }
  10. }
4. Island of Isolation:
  1. class Test{
  2. Test i;
  3. public static void main(String[] args){
  4. Test t1 = new Test();
  5. Test t2 = new Test();
  6. Test t3 = new Test();

  7. t1.i = t2;
  8. t2.i = t3;
  9. t3.i = t1;

  10. t1 = null;

  11. t2 = null;

  12. t3 = null;
  13. }
  14. }
Note: If an object doesn't have any reference then it always eligible for Garbage Collection.
Note: Even though the object having reference still it is eligible for Garbage collection sometimes.
Ex: Island of isolation, all references are internal references.

The methods for requesting JVM to run Garbage Collection:
  • Once you made an object eligible for Garbage Collection. It may not be destroyed immediately by the Garbage Collector.
  • Whenever JVM runs Garbage collection then the only objects will be destroyed by Garbage Collector.
  • You can request JVM  to run a garbage collector programmatically, but whether JVM accepts your request or not there is no guaranty. But most of the time JVM will accept our request.
The following are various ways for requesting JVM to run Garbage Collector:
By System class:
  • System class contains a static method Garbage Collection for this purpose.
  • Ex: System.gc();
By Runtime class:
  • A java application can communicate with JVM by using the Runtime object.
  • Runtime class is a singleton class present in java.lang Package.
  • You can create a Runtime objects by using the factory method getRuntime().
    E.g.: Runtime r = Runtime.getRuntime();
  • Once you got Runtime object you can call the following methods on that object.
  • freeMemory(): returns the free memory present in the heap.
  • totalMemory(): returns total memory of the heap.
  • gc(): for requesting JVM to run garbage collector.
Note: gc() method present in System class is static, whereas it is an instance method in Runtime class.
Note: Over Runtime class gc() method, System class gc() method is recommended to use.
Note: In java, it is not possible to find the size of an object and address of an object.

Finalization:
  • Just before destroying any object garbage collector always calls finalize() method to perform cleanup activities.
  • If the corresponding class contains finalize() method then it will be executed otherwise Object class finalize() method will be executed.
  • Which is declared as follows
  • protected void finalize() throws Throwable.
Case 1:
Just before destroying any object garbage collector calls finalize() method on the object which is eligible for Garbage Collection then the corresponding
class finalize() method will be executed.
For example: If the String object is eligible for Garbage Collection then the String class finalize() method is executed but not Test class finalize() method.
Example:
  1. class Test{
  2. public static void main(String[] args){
  3. String s = new String("kalawati");
  4. Test t = new Test();
  5. s = null;
  6. System.gc();
  7. System.out.println("End of main");
  8. }
  9. public void finalize(){
  10. System.out.println("Finalize() method is executed"): 
  11. }
  12. }
Case 2:
You can call finalize() method explicitly then it will be executed just like a normal method call and object won't be
destroyed. But before destroying any object Garbage Collector always calls finalize() method.
Example:
  1. class Test{

  2. public static void main(String[] args){
  3. Test t = new Test();
  4. t.finalize();
  5. t.finalize();
  6. t=null;
  7. System.gc();
  8. System.out.println("End of main");
  9. }
  10. public void finalize(){
  11. System.out.println("Finalize() method is executed"): 
  12. }
  13. }
Case 3:
  • finalize() method can be call either by the programmer or by the Garbage Collector.
  • If the programmer calls explicitly finalize() method and while executing the finalize() method if an exception is raised and uncaught then the program will be terminated abnormally.
  • If Garbage Collector calls finalize() method and while executing the finalize() method if an exception raised and uncaught then JVM simply ignores that exception and the program will be terminated normally.
Example:
  1. class Test{
  2. public static void main(String[] args){
  3. Test t = new Test();
  4. //t.finalize();
  5. t=null;
  6. System.gc();
  7. System.out.println("End of main");
  8. }
  9. public void finalize(){
  10. System.out.println("finalize() method is called");
  11. System.out.println(0/0);
  12. }
  13. }
If we are not comment line4 then programmer calling finalize() method explicitly and while executing the finalize() method
ArithmeticException raised which is uncaught hence the program terminated abnormally.
If you comment line4 the Garbage collector calls finalize() method and JVM ignores ArithmeticException and the program will be terminated normally.

Which of the following is true?
While executing finalize() method JVM ignores every exception(invalid);
While executing finalize() method JVM ignores only uncaught exception(valid);

Case 4:
On any object, GC calls finalize() method only once.
Example:
  1. class FinalizeDemo{
  2. static FinalizeDemo s;
  3. public static void main(String[] args) throws Exception{
  4. FinalizeDemo f = new FinalizeDemo();
  5. System.out.println(f.hasCode());
  6. f=null;
  7. System.gc();
  8. Thread.sleep(5000);
  9. System.out.println(s.hasCode());
  10. s=null;
  11. System.gc();
  12. Thread.sleep(5000);
  13. System.out.println("End of main method");
  14. }
  15. public void finalize(){
  16. System.out.println("finalize() method is called");
  17. s=this;
  18. }
  19. }
Memory leaks:
An object which is not using in our application and it is  not eligible for Garbage Collection such type of objects are called memory leaks.

Friday 9 August 2019

Arrays

Agenda:
  • Introduction
  • Array declaration
  • Array construction
  • Array initialization
  • Array declaration construction initialization in a single line.
  • length vs length() 
  • Anonymous arrays
  • Array element assignments
  • Array variable assignments
Introduction:
  • An array is a collection of homogeneous elements.
  • It can represent multiple values with the same name.
  • It is fixed in size. Means once you  created an array you can't change the size of the array
  • It is an object in java.
Array Declaration:
Single Dimensional array declaration
int[] a;
int a[];
int []a;

Double dimensional array declaration
int[][] a;
int [][]a;
int[]a[];
int a[][];
int a[] [];
int[] a[];

Three dimensional array declaration
int[][][] a;
int [][][]a;
int[][]a[];
int[]a[][];
int a[][][];
int a[] [][];
int a[][] [];
int a [][][];

Note: If you specify the [](dimension) before the variable this rule is applicable only for the first variable. The second variable onward you can't apply in the same declaration.
e.g int[]a,[]b;//invalid
Array construction:
  • Every array in java is an object so, you can create an object using the new operator.
     E.g.: int[] a = new int[3];
  • For every array type corresponding classes are available but these classes are part of java language and not available to the programmer level.
Points to remember:
  • You must specify the size at array creation otherwise you will get a compiler error.
    E.g.: int[] a = new int[];//compiler error.
  • It is valid to have an array with size zero in java e.g int a = new int[0];
  • You can't take array size with -ve int value, otherwise, you will get runtime exception NegativeArraySizeException
  • The allowed data types to specify array size are a byte, short, char, int only.
  • The maximum allowed array size in java is the maximum value of int size[2147483647]
Two-dimensional array creation:
  • In java, multidimensional arrays are implemented as an array of arrays approach but not matrix form.
  • The main advantage of this approach is to improve memory utilization.
Array initialization:
Whenever you are creating an array every element is initialized with default value automatically.

Declaration  and initialization of an array in a single line:
int[] a = {10,20,30,40};
int[][] a ={{10,20},{30}.{40,50}};
int[][][] a ={{{10,20},{30}},{{40,50}},{{60},{70,80},{90}}};

length vs length() method:
length:
It is the final variable applicable only for arrays.
It represents the size of the array.
length() method:
It is the final method applicable to String objects.
It returns the no of characters present in the String.
Anonymous Arrays:
  • Sometimes you can create an array without name such type of nameless arrays are called anonymous arrays.
  • At the time of anonymous array creation, we can't specify the size otherwise you will get a compiler error e.g new int[]{10};//valid, new int[3]{10,20};//invalid
  • You can give a name for anonymous array if required then it will be no longer anonymous e.g int[] a = new int[]{10,20};

Array element assignments:
Case 1: In the case of a primitive array, as array elements, any type is allowed which can be promoted to declared type.
Example 1: For the int type arrays the allowed array element types are a byte, short, char, int
Example 2:  For the float type arrays the allowed array element types are a byte, short, char, int, long, float. e.g. int[] a = new int[10]; a[0]=97;//valid, a[1]=10L;//invalid

Case 2: In the case of a Class type arrays, as array elements, you can provide either declared type objects or its child class objects.
Example:
Object[] obj = new Object[10];
obj[0] = new Object();//valid
obj[1] = new String("anu");
Number[] numbers = new Numbers[10];
numbers[0] = new Integer(10);//valid
numbers[1] = new String("kalawati");//invalid because String is not the child class of Number class.

Case 3: In the case of interface type arrays, as array elements, you can provide its implemented class objects.
Example:
Runnable[] r = new Runnable[10];
r[0] = new Thread();//valid
r[1] = new String("Amit");// invalid, because String is not implemented class of Runnable interface.
Array variable assignments:
  • Element level promotions are not applicable at the array level.
  • Example: A char value can be promoted to int type but char array can't be promoted to an int array. int[] a ={10,20}; char[] ch ={'a','d'}; int[] b =a;//valid, an int[] c = ch;//invalid C.E
  • Whenever you are assigning one array to another array internal elements won't copy just reference variables will be reassigned, so sizes are not important but types must be matched.Example: int[] a = {10,20,30,40}; int[] b ={10,20}; a=b;//valid  b=a;//valid
  • Whenever you are assigning one array to another array, dimensions must be matched, i.e in the place of a one-dimensional array, you must provide the same type only otherwise you will get a compiler error. int[][] a = new int[3][];  a[0] = new int[4][5];//invalid
  • I explained earlier that every array is an object. This means you can assign an array object to a variable of type Object. Like this:
    int[] intArray = new int[3]; Object obj = intArray; This is valid because an array of ints is an Object. Object[] obj2 = new int[3];//Invalid It will give you a compilation error because elements of the array pointed to by int array are not objects. They are ints. Therefore, you can't assign an array of ints to a variable of type array of objects. Each element of the array created using new int[2][3] is an array of ints. An array of ints is an object and therefore, an array of array of ints is an array of objects.
    Object[][] obj3 = new int[3][2];//Invalid,
    Object[] obj4 = new int[3][2];//valid
Note: Whenever you are performing array assignments the types and dimensions must be matched but sizes are not important.

Memory Representation of Arrays:
Fig -1









Fig-2

Fig-3


Next Topic: METHOD & ENCAPSULATION                                                                                                                                     
















Thursday 8 August 2019

Control flow

Agenda:
  • Selection statements
  • Iterative statements
  • Transfer statements
Selection statements:
  • if-else
  • switch
if-else:
Syntax:
  1.  if(b){// here b is boolean type
  2. // action if b is true.
  3. }else{
  4. action if b is false.
  5. }
  • The argument of the if statement must be boolean type otherwise you will get a compiler error.
  • {} curly braces are optional if you take only one statement under if, but it should not be a declarative statement.
  • e.g if(10>5)
  • int x=10;// Compiler error because it is a declarative statement.
  • if(true); is valid syntax but not useful.
switch:
If many options are available then it is not recommended to use if-else, you should go for the switch statement.
Syntax:
  1. switch(x){
  2. case 1: action1
  3. case 2: action2
  4. case 3: action3
  5. .
  6. .
  7. .
  8. default: default action
  9. }
  • {} curly braces are mandatory.
  • case and default are optional
  • Every statement inside the switch must be under some case or default. Independent statements are not allowed.
  • e.g switch(){
  • System.out.println("Hello");// It is an independent statement so, compiler error.
  • }
byte,short,int,char,Byte,Short,Integer,Character,enum,String are allowed argument for switch.
Every case label should be compile-time constant otherwise you will get a compiler error.
e.g int x=10;
switch(x){
case x: System.out.println("Hello");//compiler error because x is not compile time constant. to make it compile time constant use  final keyword.
}
final int x =10;//compile time constant
switch(x){
case x: System.out.println("Hello");
}
Switch argument and case label can be expression, but case must be constant expression.
Every case label should be within the range of switch argument types.
byte b=10;
switch(b){
case 10:System.out.println("anu");
case 100: System.out.println("ambe");
case 1000: System.out.println("amit");//compiler error, byte range is -128 to 127  but case label 1000 which is out of range
}
Duplicate case label is not allowed.

Fall through inside the switch:
  • Within the switch statement if any case is matched from that case onwards all statements will be executed until the end of the switch or break.
  • Within the switch, you can take the default anywhere.
Iterative statements:
while loop:
  • If you don't know the number of iterations in advance then you should go for a while loop.
  • The argument of the while loop must be boolean type, otherwise compiler error.
  • {} curly braces are optional and without curly braces, you can take only one statement which should not be a declarative statement(int a =10; or int a)
do-while loop:
  • If you want to execute while loop at least one then you should go for a do-while loop.
  • {} curly braces are optional and without curly braces, you can take only one statement between do and while which should not be a declarative statement(int a =10; or int a).
Syntax:
do{}while(b);// semicolon is mandatory.
Note: do while(b);//compiler error

For loop:
If you know the number of iteration in advance then you can use this.
syntax:

{} curly braces are optional and without curly braces, you can take only one statement which should not be a declarative statement(int a =10; or int a)
1.Initialization section
  • This section will be executed only once.
  • Here you can declare loop variable and you will perform initialization.
  • You can declare multiple variables but should be of the same type.
  • You can't declare the different types of variables.
  • In the initialization section, you can take any valid statement including System.out.println().
2. condition check
  • You can take any java expression but should be of the type boolean.
  • The condition expression is optional if you are not taking any expression compiler will place true.
3.Increment and decrement section:
Here you can take any java statement including System.out.println().

Enhance for loop:
  • It was introduced in java 1.5v.
  • Best suitable to retrieve the elements of arrays and collection.
  • Example:
  • int a[] ={10,20,30,40,50};
  • for(int val:a){
  • System.out.println(val);
  • }
Transfer statements
Break statement:
  • You can use break statement in the following cases.
  • Inside switch to stop fall-through.
  • Inside loops to break the loop based on some condition.
  • Inside label, blocks to break block execution based on some condition.
  • If you are using anywhere else you will get a compiler error.
Continue statement:
  • You can use continue statement to skip current iteration and continue for the next iteration.
  • You can use continue statement only inside loops otherwise you will get a compiler error.
Next Topic: ARRAYS

Wednesday 7 August 2019

Operators


Agenda:
  • Increment and Decrement operators
  • Arithmetic operators
  • String concatenation operator
  • Relational operators
  • Equality operator
  • "instanceof" operator
  • Bitwise operator
  • Short circuit operators
  • Typecast operator
  • Assignment operator
  • Ternary operator
  •  New operator
  • [] operator
Increment & Decrement operators:
Pre increment  E.g.:  y = ++x;
Pre decrement  E.g.:  y = --x;
Postincrement  E.g. : y = x++;
Postdecrement E.g.:  y = x--;
  • In Preincrement or Predecrement first value gets increased or decreased then the assignment will happen(value is used).
  • But in Postincrement or Postdecrement first assignment(value is used) will happen then value gets increased or decreased.
For example:
1.     class Test{
2.     public static void main(String[] args){
3.     int x=10;
4.     int y=20;
5.     System.out.println(x++);
6.     System.out.println(++y);
7.     int a = 10;
8.     a = a++ +a + a-- -a-- + ++a;
9.     System.out.println(a);//(10 + 11 + 11 -10 + 10 = 32)
10. }
11. }
Output:
10
21
32

Note:
  • The evaluation of expression starts from Left to Right.
  • The value assignment starts from Right to Left.
  • Increment or decrement operators only valid for variables not for constant values.
  • E.g.: 10++ // invalid
  • Nesting of increment or decrement operators is not permitted.
  • E.g.: int x=10;
    int y =++(++x)//Compiler Error(It will become constant)
  • Increment or decrement operator for final variables are not permitted. 
  • E.g.: final int x =10;
    int y = ++x;//compiler Error.
  • Increment or decrement operator is not allowed on boolean variables.
Arithmetic Operators(+,-,*,/,%):

If you apply any arithmetic operator between two variables a and b, the result type is always
max(int,type of a, type of b);

E.g.:
  • byte+byte = int
  • byte+short =int
  • byte+int = int
  • char + char = int
  • int + long = long
  • float +double = double
  • System.out.println('a'+1);//98
Infinity:
  • For Integral arithmetic(byte,short,int,long) there is no way to represent infinity or undefined results.
  • Hence, If infinity or undefined is the result then we will get ArithmeticException.
  • System.out.println(10/0);//AE
  • System.out.println(0/0);//AE
  • But for floating-point arithmetic(float, double) there is a way to represent infinity or undefined results.
  • For this Float and Double classes contains the following constants.
  • POSITIVE-INFINITY
  • NEGATIVE-INFINITY
  • NaN(Not a number)
  • Hence, If infinity or undefined results are the results we won't get any runtime exception.
E.g.:
1.     System.out.print(10/0.0);//+infinity
2.     System.out.println(10.0/0);//+infinity
3.     System.out.println(-10/0.0);//-infinity
4.     System.out.println(-10.0/0);//-infinity
5.     System.out.println(0/0.0);//NaN
6.     System.out.println(0.0/0);//NaN
7.     System.out.println(-0.0/0);//NaN
8.     System.out.println(-0/0.0);//NaN
Note:
  • ArithmeticException(AE) is a RuntimeException not compile-time exception.
  • AE is only for integral arithmetic not for floating-point arithmetic.
  • Only operators(/,%) causes AE.
String concatenation operator:
  • "+" is the only overloaded operator in java.
  • Sometimes "+" operator acts as arithmetic addition and sometimes it acts as concatenation.
  • If at least one argument is string type then "+" operator acts as concatenation.
  • If all arguments are number type then the "+" the operator acts as an additional operator.
For E.g.:
  • String a ="anu";
  • int b=10,c=20;
  • System.out.println(a+b+c);//anu1020
  • System.out.println(b+c+a);//30anu
Relational operators(>, <, >=, <=):
  • You can apply relational operators for every primitive type except boolean.
  • You can't apply relational operators for the object type.
  • You can't perform nesting of relational operators.
  • Ex: System.out.println(10<20<30);//Compiler Error.
Equality Operators(==, !=):
  • You can apply equality operators for every primitive type including boolean type also
  • You can also apply equality operators for an object reference.
  • Means, if you compare two objects reference r1,r2 using ==(double equal operator),
  • then r1==r2 return true if and only if both r1 and r2 pointing to the same object.
  • To use equality operator compulsory there should be some relationship between argument type(either parent-child or child-parent or same type),
  • otherwise, you will get a compiler error(incomparable types).
= = vs .equals():
  • = = operator compare address/location whereas .equals() compare content.
  • For E.g.:
  • String s1 = new String("anu");
  • String s2 = new String("anu");
  • System.out.println(s1==s2);//false
  • System.out.println(s1.equals(s2));//true
Instanceof operator:
  • You can use this operator to check whether the given object is of particular type or not.
  • syntax: <object reference> instanceof <class or interface name>
  • To use this operator compulsory there should be some relationship between argument type(either parent-child or child-parent or the same type), otherwise you will get a compiler error(incomparable types).
  • Whenever you are comparing parent object is child type or not by using instanceof operator then you will get false as output.
  • For any class or interface X, null instanceof X the result is always false.
Bitwise operators:
  • &(AND): If both the arguments are true then the result is true.
  • |(OR): If at least one argument is true, then the result is true.
  • ^(X-OR): If both are different arguments, the result is true.
  • System.out.println(true & false);//false
  • System.out.println(true | false);//true
  • System.out.println(true ^ false);//true
Note:
&, |, ^ : Applicable for both boolean and integral types.

Bitwise complement(~ tild operator):
  • It works with only Integral types.
  • It inverts all bits of its operand, means it convert 0 ---> 1 and 1---> 0
Trick
  • If value is +ve integer, then increase value by 1 and put negative prefix.
  • int a =10;
  • System.out.println(~a);// -11
  • If value is -ve integer, then decrease value by 1 and put positive prefix.
  • int a =-9;
  • System.out.println(~a);// 8
Boolean complement(!)  operator:
This operator is applicable only for boolean types not for integral types.
System.out.println(!false);// true

Short circuit(&&, ||) operators vs Bitwise operators(&, |)
  • In bit-wise operators both the argument should be evaluated while in short circuit operators the second argument is optional.
  • For example: 
  • r1&&r2, r2 will be evaluated if and only if r1 is true.
  • r1||r2, r2 will be evaluated if and only if r1 is false.
  • In bit-wise operator is applicable for both integral and boolean types while short circuit operator is applicable only for boolean types.
Typecast operator(primitive type-casting)
1.     Implicit typecasting.
2.     Explicit typecasting.
Implicit type casting:
  • The compiler is responsible for this typecasting.
  • Whenever you are assigning smaller data type value to the bigger data type variable this typecasting will be performed. Also known as widening or up-casting.
  • There is no loss of information in this typecasting.
  • The following are various possible implicit typecasting.
          

Explicit type casting
  • A programmer is responsible for this typecasting.
  • Whenever you are assigning bigger data type value to the smaller data type variable then explicit typecasting is required.
  • Also known as Narrowing or downcasting.
  • There may be a chance of loss of information in this typecasting.
  • Whenever you are assigning bigger data type value to the smaller data type variable by explicit typecasting the most significant bit(MSB) will be lost.
  • Whenever you are assigning floating-point data types to the integer data type by explicit typecasting the digits after the decimal the point will be lost.
  • E.g.:
  • float x =150.45f;
  • int i = (int)x;
  • System.out.println(i);//150
Assignment Operator:
Simple assignment operator:
E.g.: int x =10;
Chained assignment operator
int a,b,c,d;
a=b=c=d=20;
You can't perform chained assignment at the time of declaration.
E.g.: int a=b=c=d=20;
Compound assignment operator
  • += E.g.: int a+=1; is equivalent to int a=a+1;
  • -= E.g.: int a-=1; is equivalent to int a=a-1;
  • *= E.g.: int a*=1; is equivalent to int a=a*1;
  • /= E.g.: int a/=1; is equivalent to int a=a/1;
  • %= E.g.: int a%=1; is equivalent to int a=a%1;
  • &=
  • !=
  • ^=
  • >>=
  • >>>=
  • <<=
Conditional Operators:
  • Ternary operator(?:) is the only conditional operator in java.
  • int x = 10>20?30:40;
  • System.out.println(x);//40
  • You can perform nesting of Ternary operator.
  • int x =10>20?30:(50>10)?40:60;
  • System.out.println(x);//40
New operator:
  • You can use new operator to create an object.
  • In java, there is no delete operator for the destruction of the objects.
  • The garbage collector is responsible for destroying the objects.
[] operator:
  • You can use [] operator to declare and construct arrays.

Shift operators:
Right shift operators(>>):
  • It shifts binary bits to right.
  • e.g int a=4;int b=a>>2;
  • Here binary bits shift 2 position right and at empty place fill 0 if the number is +ve and if the number is -ve fill 1.
  • Assume the size of the int is 1 byte. So,4 will store in memory like 00000100 after shifting one position right and at empty place fill 0 (because the number is positive) It will become 00000010. Again shifting one position right it will become 00000001 and it's decimal value is 1 System.out.println(b);//1
Left shift operators(<<):
  • It shifts binary bits to left.
  • e.g int a=4; int b=a<<2;
  • Here binary bits shift 2 positions left and at empty place fill 0 either number is negative or positive.
  • Assume the size of the int is 1 byte. So,4 will store in memory like 00000100 after shifting one position left and at empty place fill 0. It will become 00001000
  • Again shifting one position left it will become 00010000 and its decimal value is 16
  • System.out.println(b);//16
Shift Right Zero Fill operator(>>>):
  • It  shifts binary bits to right and put 0 at the empty place(No matter number is +ve or -ve)
  • Its result will be always a positive number. 
  • e.g byte  a = -4;
  • int b =a>>>2;//111111111111111111111111111111(30 times 1)
  • System.out.println(b);//1073741823
Note: For shift, operator apply max(int, type of a, type of b);
E.g.: 
byte a=4;
int b=a>>2;
int c=a<<2;
int d=a>>>2;

Java operator precedence:
1.Unary operators:
[],x++,x--
++x,--x,~,!
new
2.Arithmetic operators:
*,/,%
+,-
3.Shift operators:
>>,>>>,<<
4.Comparision operators:
<,<=,>,>=,instanceof
5.Equality operators:
==,!=
6.Bitwise operators:
&,^,|
7.Short circuit operators:
&&,||
8.Conditional operators:
?:
9.Assignment operators:
+=,-=,*=,/+,%=

Next topic: CONTROL FLOW