Sunday, May 29, 2016

Java Operators

We have five types of operators:
·        Arithmetic Operators
·        Assignment Operators
·        Logical Operators
·        Relational Operators
·        Bitwise Operators
Arithmetic Operators:
These operators are used for any type of mathematical operation or calculations like traditional mathematics. Below is list of them. 
S No
Operators
Description
Example
1
+
Addition
int a=10;
int b = 20;
int sum = a+b;

This will give you 30.
2
-
Subtraction
int a=10;
int b = 20;
int sum = a-b;

This will give you -20.
3
*
Multiplication
int a=10;
int b = 20;
int sum = a*b;

This will give you 200.
4
/
Division
int a=10;
int b = 20;
int sum = a/b;

This will give you 0.5.
5
%
Modulus
int a=20;
int b = 35;
int sum = a%b;

This will give you 15.
6
++
Increment
int a=10;
int increment = a++;

This will give you 11.
7
--
Decrement
int a=10;
int increment = a--;

This will give you 9.




The Assignment Operators:
Always keep in mind that these types of operators always use with = equals to sign. Below is the list.
S NO
Operators
Description
Example
1
=
Simple assignment operator, Assigns values from right side operands to left side operand.
C = A + B will assign value of
 A + B into C
2
+=

Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand.
C += A is equivalent to
 C = C + A
3
-=

Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand.
C -= A is equivalent to
 C = C - A
4
*=

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand.
C *= A is equivalent to C = C * A
5
/=

Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand.
C /= A is equivalent to C = C / A
6
%=

Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand.
C %= A is equivalent to C = C % A
7
<<=

Left shift AND assignment operator.
C <<= 2 is same as C = C << 2
8
>>=

Right shift AND assignment operator.
C >>= 2 is same as C = C >> 2
9
&=
Bitwise AND assignment operator.
C &= 2 is same as C = C & 2
10
^=

Bitwise exclusive OR and assignment operator.
 C ^= 2 is same as C = C ^ 2
11
|=

Bitwise inclusive OR and assignment operator.
C |= 2 is same as C = C | 2




The Logical Operators:
The following table lists the logical operators:
Assume Boolean variables A holds true and variable B holds false.
S No.
Operators
Description
Example
1
&& (logical and)
Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
(A && B) is false.
2
|| (logical or)

Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.
(A || B) is true.
3
! (logical not)

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(A && B) is true.




The Relational Operators:
There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20:
S NO
Operators
Description
Example
1
== (equal to)

Checks if the values of two operands are equal or not, if yes then condition becomes true.
 (A == B) is not true.
2
!= (not equal to)

Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
(A != B) is true.
3
> (greater than)
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
4
< (less than)

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
5
>= (greater than or equal to)

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
6
<= (less than or equal to)

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.




The Bitwise Operators:
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 63; and b = 13.
S No
Operators
Description
Example
1
& (bitwise and)

Binary AND Operator copies a bit to the result if it exists in both operands.
(A & B) will give 12 which is 0000 1100
2
| (bitwise or)

Binary OR Operator copies a bit if it exists in either operand.
(A | B) will give 61 which is 0011 1101
3
^ (bitwise XOR)

Binary XOR Operator copies the bit if it is set in one operand but not both.
(A ^ B) will give 49 which is 0011 0001
4
~ (bitwise compliment)

Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.
(~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.
5
<< (left shift)

Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand
A << 2 will give 240 which is 1111 0000
6
>> (right shift)

Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
 A >> 2 will give 15 which is 1111
7
>>> (zero fill right shift)

Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.
A >>>2 will give 15 which is 0000 1111

Thursday, February 25, 2016

How to read a file from directory?


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderClass {

public static void main(String[] args) {

//Create BufferedReader Class
BufferedReader bufferReader = null;

try {

//Declare varibale for line number 
String lineNumber;

//Opening the file
bufferReader = new BufferedReader(new FileReader("C:\\file_to_read.txt"));

//Print all rows of file till last row
while ((lineNumber = bufferReader.readLine()) != null) {
System.out.println(lineNumber);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//Closing bufferReader object
if (bufferReader != null)
{
bufferReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

}
}

Wednesday, January 27, 2016

Static Method Vs Instance Method

                                                         http://www.try2catch.in

Static Method: These methods are not belongs to class rather than object or instance and always call by the reference of class name. Class/Static method never calls instance methods and variables.

class TryCatch {

// Class/Static method implementation
public static int doSum(int a, int b) {

int sum = a + b;

return sum;

}

public static void main(String[] args) {

// Calling class/static method in same class.
doSum(2, 5);
}

}




public class TryCatchMain {

public static void main(String[] args) {

// Calling class/static method in other class.
TryCatch.doSum(2, 5);

}
}

Instance Method: These methods are part of instance or object and always calls by using refrence of same class. Instance methods can call a class/static method or valriable.


class TryCatch {

int i = 0;

//Class/Static method implementation
public static int doSum(int a, int b) {

int sum = a + b;

return sum;

}

public static void main(String[] args) {

//Calling class/static method in same class.
doSum(2, 5);
}

//Instance method implementation
public int doSum(int a, int b, int c) {

//Calling class/static method in instance method.
doSum(2, 5);

int sum = a + b;

return sum;

}
}



Tuesday, November 24, 2015

Singleton Class


Singleton class is that for which, we can create only one or single instance of the class through the life cycle of program. In other words, we are restricting user to create multiple instance.

For example, we don’t want to create connection object if it is already created. We should make our connection class as singleton class.

Below is code snippet, how to make singleton class.





/*Singleton Class*/
class TryCatch {

       private static TryCatch singleton = new TryCatch();

       /*Constructor is private because we don’t want to create object outside of the class*/
       private TryCatch() {

              System.out.println("In private constructor…");
       }

       /* Static 'instance' method */
       public static TryCatch getInstance() {
              return singleton;
       }
}



/*Main Class*/
public class TryCatchMain {

       public static void main(String[] args) {
             
             
              TryCatch object = TryCatch.getInstance();

       }

}


Sunday, November 15, 2015

New and Best Features of Java 8


Get a new tool set for easily performing common operations.

I've been giving a presentation called "Java 8 in Anger." No, it's not that the most recent release of Java has me particularly enraged; in anger is (apparently) a British phrase meaning "in practice" or "in the real world."



The aim of the talk is to demo, with live code, how to use some of the Java SE 8 features such as lambda expressions and the Stream API to solve some of the coding problems you might come across in your day job as a developer.

For more details click on Feature of Java 8.


Friday, November 13, 2015

What is Thread


Thread is a flow of execution and a program in itself. Each thread has its own job to perform. We can create a thread by using two things:

1)  Extending Thread class &
2)  Implementing Runnable interface.





Here is one more class i.e. ThreadGroup. This class is use to group number of threads as per their behavior. This class is helpful, if we want to change behavior of multiple threads of same group at once.

Thread class has multiple methods to implement required job. But, in case of Runnable interface, it has only run() method.

We should implement runnable interface because by extending thread class we will never extends other classes if required.



Each thread has some property, which are

1)  Name: By setting name, we can identify the thread by its name. By default name is Thread0, Thread1…

2)  Priority: By setting name, we can set the execution chance priority. We can set from 1 to 10. By default priority is normal i.e. 5.

3)  Group: We cannot set group of threads. It is automatically set by JVM. We can only get group name of thread.


Thread class implements Runnable interface.


Wednesday, November 4, 2015

Thread States






1)      New/Born:  When we create object of thread class, it is in new or born state.

2)      Runnable/Ready: After creating object, when we call start() method of thread class, it comes into runnable or ready state.

3)      Running: When thread scheduler will assign or allocate processor while calling run() method to thread then it comes into running state.

4)      Dead: After completion of job assigned to thread, when we call stop() method then it comes to dead state.

5)      Yield: It means, we want back to Runnable/Ready state. For this, we need to call static method of Thread class yield().

6)      Blocked: When we call join() method, that’s mean we want to block till the joined thread will complete its job or till the time not get finished or not get interrupted.

7)      Sleep: When we call sleep() method, thread will exists into sleeping state.

8)      Waiting: While calling wait() method, thread comes into waiting state. It will come to ready state only if we call notify() or notifyAll() method.


9)      Suspended: While calling suspend() method, thread comes into suspend state. It will come to ready state only if we call resume() method


Transient Keyword


To understand transient keyword, we must know the concept of serialization. In serialization, Java object represented as a sequence of bytes with data and its type. Object has been written into a file.

Now to declare any object serialized, we must implement Serializable interface and declare the object as transient. Any of the transient variables never is serialized. In the below example, we declare String middleName as transient.



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class TryCatchData implements Serializable {
       private String firstName;
       private transient String middleName;
       private String lastName;

       public TryCatchData(String firstName, String middleName, String lastName) {
              this.firstName = firstName;
              this.middleName = middleName;
              this.lastName = lastName;
       }

       public String toString() {
              StringBuilder builder = new StringBuilder();
              builder.append("First Name : ");
              builder.append(this.firstName);
              builder.append(" Middle Name : ");
              builder.append(this.middleName);
              builder.append(" Last Name : ");
              builder.append(this.lastName);
              return builder.toString();
       }
}



public class TryCatch {
       public static void main(String args[]) throws Exception {
              TryCatchData writeData = new TryCatchData("Try", "2", "Catch");
              ObjectOutputStream outStream = new ObjectOutputStream(new FileOutputStream("TryCatchData"));
              outStream.writeObject(writeData);
              outStream.close();

              ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("TryCatchData"));
              TryCatchData readData = (TryCatchData) inputStream.readObject();
              System.out.println(readData);
       }
}

Output: First Name : Try Middle Name : null Last Name : Catch


Tuesday, November 3, 2015

Volatile Keyword

Volatile is a modifier keyword. Volatile can be use with only variables not with class or method names. When a variable declared as volatile it means, the value of the variable should be taken from main memory of its stack not from cached thread-locally. A variable value will be modified by different threads. This keyword has to declare in synchronized block.



public class TryCatch {

       private static volatile int volatileVariable = 0;

       public static void main(String[] args) {
              new Listener().start();
              new Maker().start();
       }

       static class Listener extends Thread {
              @Override
              public void run() {
                     int LocalVariable = volatileVariable;
                     while (LocalVariable < 5) {
                           if (LocalVariable != volatileVariable) {
                                  System.out.println("Got Change for volatileVariable : " + volatileVariable);
                                  LocalVariable = volatileVariable;
                           }
                     }
              }
       }



       static class Maker extends Thread {
              @Override
              public void run() {

                    int localVariable = volatileVariable;
                     while (volatileVariable < 5) {
                           System.out.println("Incrementing volatileVariable to " + (localVariable + 1));
                           volatileVariable = ++localVariable;
                           try {
                                  Thread.sleep(1000);
                           } catch (InterruptedException e) {
                                  e.printStackTrace();
                           }
                     }
              }
       }

}