Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Wednesday, 14 January 2015

What is Association, Aggregation, Composition, Abstraction, Generalization and Dependency ?

These terms signify the relationships between classes. These are the building blocks of object oriented programming  and very basic stuff. But still for some, these terms look like Latin and Greek. Just wanted to refresh these terms and explain in simpler terms.

Association:

Association is a relationship between two objects. In other words,association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects.

Note: Aggregation is a special form of association.Composition is a special form of aggregation.



For Example:  A Student and a Faculty are having an association.

Aggregation:

Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them.Direction between them specified which object contains the other object. Aggregation is also called a “Has-a”
relationship.

For Example: A class contains students. A student cannot exist without a class There exists composition between class and students.


Composition: 

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.



For Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.


Abstraction:

Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.

For Example: A wire frame model of a car.

Generalization:

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specialization to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can
relate this term very well. Generalization is also called a “Is-a” relationship.

For Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.


Dependency:

Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.


For Example:  Relationship between shape and circle is dependency.

Saturday, 3 January 2015

What is Serialization and Deserialization in Java

Serialization: 
Serialization  is a mechanism where an object can be represented as a sequence of bytes that includes the object's  data as well as information about the object's type and the types of data stored in it
provide a mechanism to write the state of and class objects in file in a sequence  of bytes.After a
serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes  that represent the object and its data can be used to recreate the object in memory.

Note: Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:
Syntex:

public final void writeObject(Object x) throwsIOException

The above method serializes an Object and sends it to the output stream.Similarly, the ObjectInputStream class contains the following method for deserializing an object:
Syntex:

public final Object readObject() throwsIOException, ClassNotFoundException

This method retrieves the next Object out of the stream and deserializes it.The return value is Object, so you will need to cast it to its  appropriate data type.

To demonstrate how serialization works in Java below is the Example of it.

Serializing an Object:

The ObjectOutputStream class is used to serialize an Object. The below SerializableExample program instantiates an Employee object and serializes it into employee.ser file.

save as  Employee.java
public class Employee implements Serializable
{
public int id;
public String name;
public String address;
public float salary;
public transient String PAN;
Employee(int id,String name,String address,float salary,String PAN)
 {
this.id=id;
this.name=name;
this.address=address;
this.salary=salary;
this.PAN=PAN;
 }
}

Note:For a class to be serialized successfully, two conditions must be met:

>1. The class must implement the java.io.Serializable interface.
>2. All of the fields in the class must be serializable. If a field is not serializable, it must be marked           transient.

If you want to know that  a Java Standard Class is serializable or not, check the documentation for that class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not.

Note:  By using  javap tool  you can check that a class is serializable or not with cmd (command prompt).

save as  SerializableExample.java

import java.io.*;
public class SerializableExample {
public static void main(String []args) {
Employee e =new Employee(111,"Vishwa","Gurgaon", 28000,"8086PQSE");
try {
FileOutputStream fileOut = new FileOutputStream("D:\\employee.ser");
ObjectOutputStream out= new ObjectOutputStream(fileOut);
out.writeObject(e);
System.out.println("successfully objects serialized ");
out.close();
fileOut.close();
}
catch(IOException ex) {
ex.printStackTrace();
  }
  }
}

Output: successfully objects serialized 

When this  program executed, a file named employee.ser in the D directory is created in the present working directory.The program does not generate any output.

Note: When serializing an object to a file,the standard convention in Java is to give the file
as  .ser extension.


Deserilization:  It is vice-versa(opposite) process of Serilization.In this concept we construct object from the serialized file.

Deserilizing an Object:

The ObjectInputStream class is used to deserialize an Object. The following DeserializableExample program instantiates an Employee object and deserializes it from employee.ser file.

Save as DeserializableExample.java

import java.io.*;
public class DeserializableExample {
public static void main(String []args) {
Employee e =null;
try {
FileInputStream fileIn = new FileInputStream("D:\\employee.ser");
ObjectInputStream in=new ObjectInputStream(fileIn);
e =(Employee)in.readObject();
in.close();
fileIn.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
catch(ClassNotFoundException c) {
System.out.println("Employeeclassnot found");
c.printStackTrace();
}
System.out.println("Deserialized Employee objects...");
System.out.println("ID: "+ e.id);
System.out.println("Name: "+ e.name);
System.out.println("Address: "+ e.address);
System.out.println("Salary: "+ e.salary);
System.out.println("PAN: "+ e.PAN);
 }
 }

 Ouput:
 ID: 111
 Name: Vihswa
 Address: Gurgaon
 Salary: 28000
 PAN: null

Here are some important points to be noted:

>1. The try/catch block tries to catch a ClassNotFoundException, which is declared by the                  readObject() method. For a JVM to be able to deserialize  an object, it must be able to find the            bytecode for that class.  If the JVM can't find a class during the deserialization of an object,  it            throws a  ClassNotFoundException.
>2.  Notice that the return value of readObject() is cast to an Employee reference.
>3.  The value of the PAN field was 8086PQSE when the object was serialized, but because that         field(PAN) is transient variable,so this value was not sent  to the output stream.The PAN field of the deserialized Employee object is null.(if PAN variable's type is int then output will be 0 default value)








Saturday, 27 December 2014

What is Array in Java ?

Array in Java:

Normally, array is a collection of similar type of elements that have contagious memory location. In java, array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed number elements in an array.
Array is index based object, first element of the array is stored at 0 index.

Advantage of using Array:

Randomly access: We can get any data located at any index position.
Code Optimization: It makes the code optimized because we can retrive data easily on index basis and sorting is also easy.

Disadvantage of using Array:


Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime.
To solve this problem, collection framework comes in  java.

Types of Array:

There are two types of array

>1.Single Dimensional Array
>2.Multidimensional Array

Single Dimensional Array:

Syntax to Declare an Array in java

dataType[] avariableName; (or)
dataType []avariableName; (or)
dataType avariableName[]

Note: You can declair array in any one of the above 3 ways.
For Example: 

int[] age;
String []name;
float price[];

Instantiation of an Array in java:

avariableName=new datatype[size];

For Example:

int[] age=new int[10];
Here age is array of type int of size 10.

Example of single dimensional java array:

simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.

class Test{
public static void main(String []args){
int age[]=new int[6];   //declaration and instantiation of array
age[0]=15;  //initialization
age[1]=25;
age[2]=30;
age[3]=40;
age[4]=20;
age[5]=10;

for(int i=0;i<age.length;i++)  // here length is the property of array
System.out.println(age[i]);
  }
}

Output: 15
                25
                30
                40
                20
                10

Note: Indexing of array start from 0 to (size-1). i.e.  0 to 5 (6-1)

Declaration, Instantiation and Initialization of Java Array all together:

int age[]={12,20,10,25}; //declaration, instantiation and initialization

For Example:

class Test{
public static void main(String []args){
int age[]={12,20,10,25};  //declaration, instantiation and initialization

for(int i=0;i<age.length;i++)
System.out.println(age[i]);
  }
}

Ouput: 12
               20
               10
               25

Multidimensional array:

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in java;

dataType[][] variableName; (or)
dataType [][]variableName; (or)
dataType variableName[][]; (or)
dataType []variableName[];

Note: All the above are the right syntext to declair multidimensional array.

Example to initantiate Multidimensional Array in java:

int[][] age=new int[4][3]; // 4 row and 5 column

Example to initialize Multidimensional Array in java:

age[0][0]=1;
age[0][1]=2;
age[0][2]=3;
age[1][0]=4;
age[1][1]=5;
age[1][2]=6;
age[2][0]=7;
age[2][1]=8;
arr[2][2]=9;
age[3][0]=10;
age[3][1]=11;
arr[3][2]=12;

Example of Multidimensional java array:

class Test{
public static void main(String []args){
//declaring and initializing 2D array
int age[][]={ {1,2,3},{4,5,6},{7,8,9},{10,11,12} };

for(int x=0;i<4;x++){
for(int y=0;j<3;y++){
System.out.print(age[x][y]+" ");
    }
System.out.println();
    }
   }
}

Output: 1  2  3
              4  5  6 
              7  8  9
             10 11 12

Passing Java Array in the method:

We can pass the array in the method so that we can reuse the same logic on any array.
simple example to get maximum number of an array using method.

class Test{
static void max(int []arr){
int max=arr[0];

for(int i=1;i<arr.length;i++)
  {
if(max<arr[i])
    max=arr[i];
  }

System.out.println(max);
 }

public static void main(String []args){
int age[]={1,7,2,4};
max(age);   //passing array in the method
    }
}

Output: 7
     



Thursday, 25 December 2014

What is StringBuilder Class ?


The StringBuilder class is used to created mutable (modifiable) string.The StringBuilder class is same as StringBuilder class except that it is non-synchronized. It is available since JDK1.5.

Note: StringBuilder class is not a thread-safe means multiple threads can access it simultaneously. So a proper order while acccessing by multiple thread is not maintain.

Commonly used Constructors of StringBuilder class:

>1. StringBuilder(): creates an empty string buffer with the initial capacity of 16.
>2. StringBuilder(String str): creates a string buffer with the specified string.
>3. StringBuilder(int capacity): creates an empty string buffer with the specified capacity as length.


Commonly used methods of StringBuider class:



>1. public synchronized StringBuilder append(String s): is used to append the specified string              with this string. The append() method is overloaded like append(char), append(boolean),                      append(int), append(float), append(double) etc.
>2. public synchronized StringBuilder insert(int offset, String s): is used to insert the specified            string with this string at the specified position. The insert() method is overloaded like
      insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
>3. public synchronized StringBuilder replace(int startIndex, int endIndex, String str): is used         to replace the string from specified startIndex and endIndex.
>4. public synchronized StringBuilderdelete(int startIndex, int endIndex): is used to delete the
      string from specified startIndex and endIndex.
>5. public synchronized StringBuilder reverse(): is used to reverse the string.
>6. public int capacity(): is used to return the current capacity.
>7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least              equal to the given minimum.
>8. public char charAt(int index): is used to return the character at the specified position.
>9. public int length(): is used to return the length of the string i.e. total number of characters.
>10. public String substring(int beginIndex): is used to return the substring from the specified
       beginIndex.
>11. public String substring(int beginIndex, int endIndex): is used to return the substring from the
     specified beginIndex and endIndex.

An example of StringBuilder class by append() method:

The append() method concatenates the given argument with this string.

class Test{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("vishwa ");
sb.append("welcome");
System.out.println(sb);
   }
}

Output: vishwa welcome

Example of insert() method of StringBuilder class:

The insert() method inserts the given string with this string at the given position.

class Test{
public static void main(String []args){
StringBuilder sb=new StringBuilder("vishwa ");
sb.insert(2,"hello");
System.out.println(sb);
   }
}

Output: vihelloshwa

Example of replace() method of StringBuilder class:

The replace() method replaces the given string from the specified beginIndex(inclusive) and endIndex(exclusive).

class Test{
public static void main(String []args){
StringBuilder sb=new StringBuilder("vishwa");
sb.replace(1,4,"hello");
System.out.println(sb);
   }
}

Output:vhellowa



Example of delete() method of StringBuilder class:

The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.

class Test{
public static void main(String []args){
StringBuilder sb=new StringBuilder("vishwa");
sb.delete(1,4);
System.out.println(sb);
  }
}


Output: vwa

Example of reverse() method of StringBuilder class:

The reverse() method of StringBuilder class reverses the current string.

class Test{
public static void main(String []args){
StringBuilder sb=new StringBuilder("vishwa");
sb.reverse();
System.out.println(sb);
   }
}

Output: awhsiv

Example of capacity() method of StringBuilder class:

The capacity() method of StringBuilder class returns the current capacity of the buffer.The default capacity of the buffer is 16.
If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your  current capacity is 16, it will be (16*2)+2=34.

class Test{
public static void main(String []args){

StringBuildersb=new StringBuilder();
System.out.println(sb.capacity());
sb.append("vishwa");
System.out.println(sb.capacity());
sb.append("my name is vishwa");
System.out.println(sb.capacity());
   }
}

Output:  16  (by default)
                16
                34

What is StringBuffer class ?


The StringBuffer class is used to created mutable (modifiable) string.The StringBuffer class is same as String except it is mutable i.e. it can be changed.

Note: StringBuffer class is thread-safe means multiple threads cannot access it simultaneously.So it is safe and will result in a proper order whiling acccessing by multiple thread.

Commonly used Constructors of StringBuffer class:

>1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
>2. StringBuffer(String str): creates a string buffer with the specified string.
>3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.


Commonly used methods of StringBuffer class:



>1. public synchronized StringBuffer append(String s): is used to append the specified string with      this string. The append() method is overloaded like append(char), append(boolean), append(int),
      append(float), append(double) etc.
>2. public synchronized StringBuffer insert(int offset, String s): is used to insert the specified              string with this string at the specified position. The insert() method is overloaded like
      insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
>3. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to
      replace the string from specified startIndex and endIndex.
>4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the
      string from specified startIndex and endIndex.
>5. public synchronized StringBuffer reverse(): is used to reverse the string.
>6. public int capacity(): is used to return the current capacity.
>7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least              equal to the given minimum.
>8. public char charAt(int index): is used to return the character at the specified position.
>9. public int length(): is used to return the length of the string i.e. total number of characters.
>10. public String substring(int beginIndex): is used to return the substring from the specified
       beginIndex.
>11. public String substring(int beginIndex, int endIndex): is used to return the substring from the
     specified beginIndex and endIndex.

Que) What is mutable string ?

Ans: A string that can be modified or changed is known as mutable string. StringBuffer and                        StringBuilder classes are used for creating mutable string.

An example of StringBuffer class by append() method:

The append() method concatenates the given argument with this string.

class Test{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("vishwa ");
sb.append("welcome");
System.out.println(sb);
   }
}

Output: vishwa welcome

Example of insert() method of StringBuffer class:

The insert() method inserts the given string with this string at the given position.

class Test{
public static void main(String []args){
StringBuffer sb=new StringBuffer("vishwa ");
sb.insert(2,"hello");
System.out.println(sb);
   }
}

Output: vihelloshwa

Example of replace() method of StringBuffer class:

The replace() method replaces the given string from the specified beginIndex(inclusive) and endIndex(exclusive).

class Test{
public static void main(String []args){
StringBuffer sb=new StringBuffer("vishwa");
sb.replace(1,4,"hello");
System.out.println(sb);
   }
}

Output:vhellowa



Example of delete() method of StringBuffer class:

The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.

class Test{
public static void main(String []args){
StringBuffer sb=new StringBuffer("vishwa");
sb.delete(1,4);
System.out.println(sb);
  }
}


Output: vwa

Example of reverse() method of StringBuffer class:

The reverse() method of StringBuilder class reverses the current string.

class Test{
public static void main(String []args){
StringBuffer sb=new StringBuffer("vishwa");
sb.reverse();
System.out.println(sb);
   }
}

Output: awhsiv

Example of capacity() method of StringBuffer class:

The capacity() method of StringBuffer class returns the current capacity of the buffer.The default capacity of the buffer is 16.
If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your  current capacity is 16, it will be (16*2)+2=34.

class Test{
public static void main(String []args){

StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());
sb.append("vishwa");
System.out.println(sb.capacity());
sb.append("my name is vishwa");
System.out.println(sb.capacity());
   }
}

Output:  16  (by default)
                16
                34


Wednesday, 24 December 2014

What is String class or String Handling in java

String Handling:

String Handling provides a lot of concepts that can be performed on a string such as concatinating string, comparing string, substring etc.In java, string is basically an immutable object.Immutable means unmodifiable object.

String:

Normally string is a sequence of characters. But in java, string is an object. String class is used to create string object.

In Java you can create String By two Ways:

>1. By string literal
>2. By new keyword

By string literal:

In string literal you can create string object by double quote.

For Example:

String name="vishwa";
String company="TCS";
String college="KEC";

Note:Actually JVM create string literal object in a memory area known as string constant pool which is a part of heap memory area.
each time when you create a string object by string literal first JVM check string constant pool for that string if present in the string
constant pool then JVM will not create new object it return  reference of that  old object.if it dose not present in the string constant pool
then it create new object and place in the string constant poll area.

For Example:

String name="vishwa";
String ename="vishwa";

Here no new object will be created only one object is created in string constant pool and both name and ename reference variable refer to that  vishwa(single object) in the memory.

Why java uses concept of string literal ?

To make Java more memory efficient (because no new objects are created if it exists already in string constant pool area).


By new keyword:

String name=new String("vishwa");

In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "vishwa" will be placed in the string constant  pool.The variable name will refer to the object in Heap(nonpool).

As you know String is an immutable Object so here immutable means.....

In Java immutable means unmodifiable object.

For Exampale: 

class Test{
public static void main(String []args){
String name="vishwa";
name.concat(" roop ");
System.out.println(name);
   }
}

Output: vishwa

As you can see in the above example that two objects are created but no reference variable refers to"vishwa roop".But if we explicitely assign it to the reference variable, it will refer to "vishwa roop" object.

For example:

class Test{
public static void main(String []args){
String name="vishwa";
name=name.concat(" roop");
System.out.println(name);
  }
}

Output: vishwa roop

Que) Why string objects are immutable in java ?

Ans: Because java uses the concept of string literal.Suppose there are 10 reference variables,all referes to one object "vishwa".If one reference  variable changes the value of the object,it will be affected to all the others reference variables.That is why string objects are immutable in java
so that now can change the value once created.


String Concatenation:

In Java you can concat string objects by two ways:

>1. By + (string concatenation) operator
>2. By concat() method


>1. By + (string concatenation) operator:

String concatenation operator is used to add strings.
For Example:

class Test{
public static void main(String []args){
String name="vishwa"+" roop";
System.out.println(name);
  }
}

Output: vishwa roop

Note: String concatenation operator produces a new string by appending the second operand onto the end of the first operand.The string concatenation  operator can concat not only string but primitive values also.

For Example:

class Test{
public static void main(String args[]){

String name=10+20+"vishwa"+30+40;
System.out.println(name);
  }
}

Output: 30vishwa3040

Note:If either operand is a string, the resulting operation will be string concatenation. If both operands are numbers, the operator will perform an addition.

>2. By concat() method:

concat() method concatenates the specified string to the end of current string.

Syntax: public String concat(String another){  }

class Test{
public static void main(String []args){
String name="vishwa ";
String lname="roop";
String fname=name.concat(lname);
System.out.println(fname);
  }
}

Output: vishwa roop 


String comparison:

There are three ways to compare String objects:

>1. By equals() method
>2. By = = operator
>3. By compareTo() method

>1. By equals() method:

equals() method compares the original content of the string.It compares values of string for equality.String class provides two methods:

public boolean equals(Object another) { } compares this string to the specified object.
public boolean equalsIgnoreCase(String another){ } compares this String to another String,
ignoring case.

For Exampale no.1 :

class Test{
public static void main(String [] args){
String name="vishwa";
String name1="vishwa";
String name3=new String("vishwa");
String name4="roop";
System.out.println(name.equals(name1));
System.out.println(name1.equals(name2));
System.out.println(name3.equals(name4));
   }
}

Output: true
              true
              true
              false

For Example no.2

class Test{
public static void main(String []args){
String name="vishwa";
String cname="VISHWA";
System.out.println(name.equals(name));
System.out.println(name.equalsIgnoreCase(cname));
   }
}


Output: false
               true

>2. By == operator:

The = = operator compares references(means memory address of the object in the heap )  not values.

For Example:  

class Test{
public static void main(String []args){

String name="vishwa";
String name1="vishwa";
String name2=new String("vishwa");
System.out.println(name==name1);
System.out.println(name1=name2);
  }
}


Output: true
              false

>3. By compareTo() method:

compareTo() method compares values and returns an int  which tells the difference between ASCII value of the character value is equal,less or greater than. Suppose name and name1 are two string variables.If:

Suppose s1 and s2 are two string variables.If:

name == name1  then 0
name > name1 then positive value
name < name1 then negative value

For Exampale:

class Test{
public static void main(String args[]){
String name="vishwa";
String name1="vishwa";
String name2="roop";
System.out.println(name.compareTo(name1));
System.out.println(name.compareTo(name2));
System.out.println(name2.compareTo(name));
  }
}

Output: 0
                4
              -4


Commonaly used methods of String class:

>1.public boolean equals(Object obj)-----------------------> Compares this string to the specified object.
>2.public boolean equalsIgnoreCase(String another)--------->Compares this String to another String, ignoring case.
>3.public String concat(String str)------------------------>Concatenates the specified string to the end of this string.
>4.public int compareTo(String str)------------------------> Compares two strings and returns int
>5.public int compareToIgnoreCase(String str)-------------->Compares two strings, ignoring case differences.
>6.public String substring(int beginIndex)------------------> Returns a new string that is a substring of this string.
>7.public String substring(int beginIndex,int endIndex)----->Returns a new string that is a substring of this string.
>8.public String toUpperCase()------------------------------> Converts all of the characters in this String to upper case
>9.public String toLowerCase()------------------------------> Converts all of the characters in this String to lower case.
>10.public String trim()------------------------------------>Returns a copy of the string, with leading and trailing whitespace omitted.
>11.public boolean startsWith(String prefix)----------------> Tests if this string starts with the specified prefix.
>12.public boolean endsWith(String suffix)------------------> Tests if this string ends with the specified suffix.
>13.public char charAt(int index)---------------------------> Returns the char value at the specified index.
>14.public int length()-------------------------------------> Returns the length of this string.
>15.public String intern()----------------------------------> Returns a canonical representation for the string object.


Some  example of the above methods:

toUpperCase() and toLowerCase() method:

class Test{
public static void main(String []args){
String name="vishwa";
System.out.println(name.toLowerCase());
System.out.println(name.toUpperCase());
System.out.println(name);
  }
}


Output: vishwa
                VISHWA
                 vishwa


trim() method:

class Test{
public static void main(String []args){
String name=" vishwa ";
System.out.println(name);
System.out.println(name.trim());
   }
}

Output:  vishwa
                 vishwa


startsWith() and endsWith() method:

class Test{
public static void main(String []args){
String name="vishwa";
System.out.println(name.startsWith("vi"));
System.out.println(name.startsWith("wa"));
  }
}

Output: true
                 true


charAt() and length() method:

class Test{
public static void main(String []args){
String name="vishwa";//012345(index)
System.out.println(name.charAt(1));
System.out.println(name.charAt(5));

System.out.println("length is =="+name.length());
    }
}

Output: i
                a
 length is ==6

intern() method:

A pool of strings,initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned.  Otherwise, this String object is added to the pool and a reference to this String object is returned.

For Exampale:

class Test{
public static void main(String args[]){
String name=new String("vishwa");
String name1=name.intern();
System.out.println(name1);
  }
}

Output: vishwa



toString() method of String class:

If you want to represent any object as a string, toString() method is used. The toString() method returns the string representation of  the object. If you print any object, java compiler internally invokes the toString() method on that object.So overriding the toString()  method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Advantage of the toString() method:

By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.

Problem without toString() method:

class Employee{
int eid;
String ename;
String company;
Employee(int eid, String ename, String company){
this.eid=eid;
this.ename=ename;
this.company=company;
}
public static void main(String args[]){

Employee e1=new Employee(111,"vishwa","gorakhpur");
Employee e2=new Employee(222,"Virat","delhi");
System.out.println(e1);
System.out.println(e2);
  }
}

Output: Employee@19821f
                Employee@addbf1


As you can see in the above example, printing e1 and e2 prints the hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand  it with the example given below:

Understanding the actual use of toString() method:

class Employee{
int eid;
String ename;
String company;
Employee(int eid, String ename, String company){
this.eid=eid;
this.ename=ename;
this.company=company;
}
public String toString()
 {
return eid+" "+ename+' "+company;
 }
public static void main(String args[]){

Employee e1=new Employee(111,"vishwa","gorakhpur");
Employee e2=new Employee(222,"Virat","delhi");
System.out.println(e1);
System.out.println(e2);
  }
}

Output: 111 vishwa gorakhpur
                222 virat delhi




substring method of String class:

You can get substring from the given String object by one of the two methods:

>1.public String substring(int startIndex):   This method returns new String object containing the
 substring of the given string from specified startIndex (inclusive).
>2.public String substring(int startIndex,int endIndex): This method returns new String object
 containing the substring of the given string from specified startIndex to endIndex.

In case of string:
startIndex: starts from index 0(inclusive).
endIndex: starts from index 1(exclusive).

For Example:

class Test{
public static void main(String args[]){
          Sachin Tendulkar
String s="vishwa roop";
System.out.println(s.substring(5));
System.out.println(s.substring(0,5));
   }
}

Output: roop
              vishwa



How to create Immutable class in Java ?


There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes  and String class is immutable. We can also create immutable class by creating final class that have final data members.

For Example:

In this example, we have created a final class named Student. It have one final datamember, a parameterized constructor and getter method.

public final class Student{
final String rollno;
public Student(String rollno){
this.rollno=rollno;
}
public String getRollno(){
return rollno;
  }
}


The above class is immutable because:

The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
The class is final so we cannot create the subclass.There is no setter methods i.e. we have no option to change the value of the instance variable. These points makes this class as immutable class.










Sunday, 21 December 2014

What is legacy classes in Java ?

Legacy Elements:

Before Collection Framework, defined several classes and interface that provide method for storing objects. When Collection framework were added in J2SE 1.2, the original classes were reengineered(included) to support the collection interface. These classes are also known as Legacy classes.All legacy claases and interface were redesign by JDK 5 to support Generics.

The following are the legacy classes defined by java.util package.

1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector

There is only one legacy interface called Enumeration.

Note: All the legacy classes are syncronized.

Enumeration interface:

1. Enumeration interface defines method to enumerate through collection of object.
2. This interface is suspended by Iterator interface.
3. However some legacy classes such as Vector and Properties defines several method in which
    Enumeration interface is used.
4. It specifies the following two methods

   boolean hasMoreElements()
   Object nextElement()

Vector class:

1. Vector is similar to ArrayList which represents a dynamic array.
2. The only difference between Vector and ArrayList is that Vector is synchronised while Array is           not.
3. Vector class has following four constructor

Vector()
Vector(int size)
Vector(int size, int incr)
Vector(Collection< ? extends E> c)

Vector defines several legacy method.
Lets see some important legacy method define by Vector class.

addElement()--> add element to the Vector
elementAt()---> return the element at specified index
elements()----> return an enumeration of element in vector
firstElement()-> return first element in the Vector
lastElement()--> return last element in the Vector
removeAllElement()--> remove all element of the Vector

Example of Vector:

import java.util.*;
public class Test
{
public static void main(String []args)
{
Vector v1 = new Vector();
v1.add(40);
v1.add(50);
v1.add(60);
v1.add(70);
v1.add(80);
v1.add(90);

Enumeration en = ve.elements();
while(en.hasMoreElements())
    {
System.out.println(en.nextElement());
     }
  }
}

Output: 
40
50
60
70
80
90

Hashtable class:

1. Like HashMap, Hashtable also stores key/value pair in hashtable. However neither keys nor values       can be null.
2. There is one more difference between HashMap and Hashtable that is Hashtable is synchronized           while  HashMap is not.
3. Hashtable has following four constructor

Hashtable()
Hashtable(int size)
Hashtable(int size, float fillratio)
Hashtable(Map< ? extends K, ? extends V> m)

Example of Hashtable;

import java.util.*;
class HashTableExample
{
public static void main(String []args)
{
Hashtable< String,Integer> ht = new Hashtable< String,Integer>();
ht.put("a",new Integer(400));
ht.put("b",new Integer(300));
ht.put("c",new Integer(200));
ht.put("d",new Integer(100));

Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
     {
Map.Entry m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+" "+itr.getValue());
     }
  }
}

Output: 
a 400
b 300
c 200
d 100

Properties class:

1. Properties class extends Hashtable class.
2. It is used to maintain list of value in which both key and value are String
3. Properties class define two constructor

    Properties()
    Properties(Properties default)
4. One advantage of Properties over Hashtable is that we can specify a default property that will be         useful when no value is associated with a certain key.


Example of Properties class;

import java.util.*;
public class Test
{
public static void main(String []args)
{
Properties p = new Properties();
Properties p = new Properties();
p.put("Java", "James Ghosling");
p.put("C++", "Bjarne Stroustrup");
p.put("C", "Dennis Ritchie");
p.put("C#", "Microsoft Inc.");

Set set = p.keySet();
for(Object ob: set)
     {
System.out.println(ob+" was created by "+ p.getProperty((String)ob) );
    }
  }
}

Output: 
Java was created by James Ghosling
C++ was created by Bjarne Stroustrup
C was created by Dennis Ritchie
C# was created by Microsoft Inc

Saturday, 20 December 2014

What is javac, java, javap and javadoc commands in java ?

javac:

javac is command or tool which is used to compile java file.It also known as java compiler(javac).
It phisically exists in the system at java installed folder.

In my system its location is :  C:\Program Files\Java\jdk1.6.0_21\bin
Under this bin folder you can see as javac.exe  that  is javac compiler.

To compile any java file we use it as: javac (java file name).java

java:

java  is also a command or tool just like javac but it is used to run a java file.
It phisically exists in the system at java installed folder.

In my system its location is :  C:\Program Files\Java\jdk1.6.0_21\bin
Under this bin folder you can see as java.exe  that  is java tool.

To run any java file we use it as: java (java class name)

javap:

javap is also a command or tool(important).It is used to see the structure of any pre defined or
user defined class.(means to see how many methods, variables, constants,constructor etc in a class)
It phisically exists in the system at java installed folder.

In my system its location is :  C:\Program Files\Java\jdk1.6.0_21\bin
Under this bin folder you can see as javap.exe  that  is javap tool.

For Example:

If you want to see what is the structure of Object class or System class then follow below commands.

To use it type this command at cmd: javap  java.lang.Object
and then press enter button

Systex to run this command: javap full_package_name.Class_Name
i.e. javap java.lang.System

Note: By using command  this you can also see your owned creted class structure.

javadoc:

javadoc  is also a command or tool which is used to create API documents of usered defined class.
It is java documentation command.In the java file, we must use the documentation comment /**..... */ to post information for the class, method, constructor, fields etc.
It phisically exists in the system at java installed folder.

In my system its location is :  C:\Program Files\Java\jdk1.6.0_21\bin
Under this bin folder you can see as javadoc.exe  that  is java API documentation command.

For Example :

package com.vishwa;
/** This class is a user-defined class that contains one methods square.*/
public class Test{

/** The cube method prints cube of the given number */

public static void cube(int x)  {  
System.out.println(x*x);  
      }
}
If you want to make API documents of any usered defined(own) class then by using javadoc command you can make.

To use it type this command at cmd:  javadoc class_name.java  (as javadoc Test.java)

and then press enter button.Now you see at the same location where your this class_name java file is there at that place many .html files, .css and package-list  file created.

i.e. javadoc Test.java (here Test.java is a java file for which I want to make API documents)

Note: These are the main java tools or commands used mainly in java programming.

If any doubts about these tools or any concepts then please feel free to asked me.
You can comments on my post or asked any query  I will try my best to  clear your doubts.
And if any errors or suggestions please feel free to tell me.

What is static import in java

static import:

static import  is slightly different from normal  import.If we uses static import then we can access static data members of that class without qualify with that class name.

For Example:

import static java.lang.System.*;
public class Test
{
public static void main(String []args)
{
int age=25;
String name="vishwa";
out.println(age);
out.println(name);
  }
}

Output: 25
                vishwa

Friday, 19 December 2014

What is Runtime Polymorphism in java


Runtime Polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time.
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.

Example of Runtime Polymorphism:

In this example,we are creating two classes Car and Honda. Honda class extends Car class and
overrides its runing() method.We are calling the runing method by the reference variable of
Parent class. Since it refers to the subclass object and subclass method overrides the Parent
class method, subclass method is invoked at runtime. Since it is determined by the compiler,
which method will be invoked at runtime, so it is known as runtime polymorphism.

class Car{
void runing(){System.out.println("running");}
}
class Honda extends car{
void runing(){
System.out.println("car is running ");
}
public static void main(String []args){
Honda h = new Car();
h.runing();
  }
}

Output: car is running

Runtime Polymorphism with data member

Method is overriden not the datamembers,so runtime polymorphism can't be achieved by data members.
In the example given below, both the classes have a datamember speed, we are accessing the
datamember by the reference variable of Parent class which refers to the subclass object. Since we are
accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.

Note: Runtime polymorphism can't be achieved by data members.

class Car {
int speed=50;
}
class Honda extends Car{

int speed=80;
public static void main(String []args){
Car c=new Honda();
System.out.println(c.speed);
   }
}

Output: 50

What is Polymorphism in java ?


In java polymorphism makes from two words, poly means 'multiple' and morphism means 'form' 
polymorphism means  'multiple form'.

For Example:  overloding and overriding.

Que: What is rurtime polymorphism ?

Ans: Click on link to see  Rurtime Polymorphism 

What is Clone() method ( Object Cloning ) in java ?

The clone() method :

The object cloning is a way to create exact copy of an object.For this purpose, clone() method of Object class is used to clone(exact copy) an object.The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create.If we don't implement Cloneable interface, clone() method gives CloneNotSupportedException.  The clone() method is defined in the Object class.

Syntax of the clone() method is as follows:

protected Object clone() throws CloneNotSupportedException

Que: Why use clone() method ?

Ans: The clone() saves the extra processing task for creating the exact copy of an object.
 If we perform it by using the new keyword, it will take a lot of processing to be performed
that is why we use object cloning.

Example of clone() method (Object cloning):

class Employee implements Cloneable{
int eid ;
String ename;
Student(int eid,String ename){
this.eid=eid;
this.ename=ename;
  }
public Object clone()  throws CloneNotSupportedException{

return super.clone();
}
public static void main(String []args){

try{
Employee e1=new Employee(111,"vishwa");
Employee e2=(Employee)e1.clone();
System.out.println(e1.rollno+" "+e1.name);
System.out.println(e2.rollno+" "+e2.name);
  }
catch(CloneNotSupportedException c)  {     }
  }
}

Output: 111 vishwa
                111 vishwa

What is Command-Line argument in java


The command-line argument is an argument passed at the time of running the java program.
The argument can be received in the program and used as an input. So, it provides an convenient way to check out the behaviour of the program on different values. You can pass any numbers of arguments fromthe command prompt.

Example of command-line argument:

In this example,we are receiving only one argument and dispalying it. For running this program, you must pass at least one argument from the command prompt.

class Test{
public static void main(String []args){
System.out.println("first argument is: "+args[0]);
  }
}

To compile by :  javac Test.java
To run  :  java Test roop

Output: roop



Example of command-line arguments that prints all the values:

In below example,we are printing all the arguments passed from the command-line.For this purpose,we have traversed the array (args) of main method using for loop.

class Test{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
        {
System.out.println(args[i]);
           }
   }
}


To compile : javac Test.java
To run: java Test my name roop and age is 25 and

Output: my
                name
                roop
                and
                age
                is
               25
               and

What is Encapsulation in java


Encapsulation  is a process of wrapping(binding) code(objects) and data(variables) together
into a single unit.It is a way to achieve data hiding.

For Example: class is a collection of objects, methods and variables so class is an example of Encapsulation in java.( i.e.package,inteface etc).

Simple example of Encapsulation: 

Student.java

package com;
public class Student{
private string name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name
  }
}

Test.java

package vishwa;
class Test
public static void main(String []args){
Student s=new Student();
s.setname("Roop");
System.out.println(s.getName());
  }
}

Output: Roop 

What is call by value and call by referance in java


There is only call by value possible in java, not call by reference.If we call a method passing a value, it is known as call by value.


Example of call by value :

In case of call by value original value is not changed.  Let's  see a  example of it:

class Test{
int num=10;
void modify(int num){

num=num+20; //changes will be in the local variable only
}
public static void main(String []args){
Test t=new Test();
System.out.println("modify value is: "+t.num);
t.modify(40);
System.out.println("modify value is: "+t.num);
  }
}

Output:before modify value is:10
               after modify value is :60


Another Example of call by value :

In case of call by reference original value is changed if we made changes in the called method. If we pass object in place of any primitive value, original value will be changed. In this example we are passing object as a value. Let's take a simple example:

class Test{
int num=100;
void modify(Student st){

st.num=st.num+100; //changes will be in the instance variable
}
public static void main(String []args){
Test t =new Test();
System.out.println("before modify value is: "+t.num);
t.change(t);   //passing object
System.out.println("after modify value is: "+t.num);
   }
}

Output: before modify value is:100
                after modify value is :200

What is access modifiers and access specifiers in java

Access Modifiers:

There are two types of modifiers access modifier and non-access modifier.
These  access modifiers specifies accessibility (scope) of a datamember, method,constructor or class. So this is also know as access specifiers.

These are 4 types:

>1. private
>2. default
>3. protected
>4. public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc.
Here, we will see only access modifiers.

>1. private:

The private access modifier is accessible only within the class.

Example of private access modifer(variable,method):

In this example,we have created two classes Test and Student.Test class contains private
data member and private method.We are accessing these private members from outside the class,
so there is compile time error.

class Test{
private int data=20 ;
private void run(){   System.out.println("hello private");}
  }
public class Student{

public static void main(String []args){
Student st=new Student();
System.out.println(st.data);
st.run();
    }
}

Output: compile time error

private constructor:

If you make any class constructor as private, you cannot create the instance of that class
from outside that class.

Example of private constructor:

class Test{
private Test(){}   //private constructor
void run(){  System.out.println("hello private constructor");}
}
public class Student{

public static void main(String []args){
Student st=new Student();
    }
}

Output: compile time error

Note: A class cannot be private or protected except nested class.


>2. default:

If you don't use any modifier,it is treated as default modifier bydefault.The default modifier is accessible only within the package.

Example of default access modifier:

In this example, we have created two packages com and vishwa.We are accessing the Test class from
outside its package,since Test class is not public,so it cannot be accessed from outside the package

Test.java

package com;
class Test{
void run(){
System.out.println("test running");
  }
}


Student.java

package vishwa;
import pack.*;
class Student{

public static void main(String []args){
Test t = new Test();
t.run();
   }
}

Output: compile time error

In the above example,the scope of class Test and its method run() is default so it cannot be accessed
from outside the package.

>3. protected:

The protected access modifier is accessible within package and outside the package by only through
inheritance. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

Example of protected access modifier:

In this example, we have created the two packages com and vishwa.The Test class of com package is
public, so can be accessed from outside the package.But run method of this package is declared as
protected,so it can be accessed from outside the class only through inheritance.

Test.java

package com;
public class Test{
protected void run(){
System.out.println("test running");
  }
}

Student.java

package vishwa;
import com.*;
class Student extends Test{

public static void main(String []args){
Student st = new Student();
st.run();
    }
}

Output: test running


>4. public:

The public access modifier is accessible everywhere.It has the maximum scope among all other modifiers.

Example of public access modifier:

Test.java

package com;
public class Test{
public void run(){
System.out.println("testing");
   }
}


Student.java

package vishwa;
import com.*;
class Student{

public static void main(String []args){
Student st = new Student();
st.run();
   }
}

Output: testing


Note: If you are overriding any method, overriden method (declared in subclass) must not be         more restrictive.

For Example:

class Test{
protected void run() {
System.out.println("testing");}
}
public class Simple extends A{
void run(){System.out.println("testing ");}

public static void main(String []args){
Student st=new Student();
st.run();
   }
}

Output: compile time error

Note: Because the default modifier is more restrictive than protected.That is why  compile time error comes here.




What is static and dynamic binding in java

Binding in Java:

Connecting a method call(calling nethod) to a method body(of that calling method)  is called binding.

It can be of two types:

>1.static binding (early binding).
>2.dynamic binding (late binding).

What is type in Java ?

>1.variables have a type

For example:int age=26;  here age variable is a type of int.

>2.References have a type

For example:

class Test{
public static void main(String []args){
Dog d1;
    }
}

Here d1 is a type of  Dog.

>3.Objects have a type

An object is an instance of particular java class,but it is also an instance of its superclass.

For example:

class Person {  }
class Student extends Person{

public static void main(String []args){
Student s1=new Student();
  }
}

Here s1 is an instance of Student class,but it is also an instance of Person.

>1. static binding:

When type of the object is determined at compiled time(by the compiler), it is known as static binding. If there is any private, final or static method in a class,it is static binding.

Example of static binding:

class Test{
private void run()  { System.out.println("test is running");}

public static void main(String []args){
Test t1=new Test();
t1.run();
  }
}


>2.dynamic binding:

When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding:

class Person{
void run()  { System.out.println("person is running");}
}
class Studet extends Person{
void run()  {  System.out.println("student is playing");}

public static void main(String []args){
Person p=new Student();
p.play();
   }
}

Output:  student is playing

Note:In the above example object type cannot be determined by the compiler,because the instance of Dog is also an instance of Animal.So compiler doesn't know its type,  only its base type.  



What is interface in java


An interface is a blueprint of a class. It has static constants and abstract methods.The interface is a mechanism to achieve abstraction injava.There can be only abstract methods in the interface.
It is used to achieve fully abstraction and multiple inheritance in Java.

Why use Interface?

There are mainly three reasons to use interface. They are given below.

>1.It is used to achieve fully abstraction.
>2.By interface,we can support the functionality of multiple inheritance.
>3.It can be used to achieve loose coupling.

Note:The java compiler converts methods of interface as public and abstract, data members as public,final and static bydefault.

Example of Interface:

Befor compilation code (Bike.java) is:

interface Bike {
int speed=60;
void run();
  }

After compilation code (Bike.class)  is:

interface Bike {
 public static final int speed=60;
 public abstract run();

}


Simple Example of Interface:

In this exmple,Bike interface have only one method,its implemenation is  provided in the Test class.

interface Bike{
void run();
}
class Test implements Bike
{
public void print(){ System.out.println("Hello"); }

public static void main(String []args){
Test t = new Test();
t.run();
  }
}

Output: Hello

How Multiple Inheritance is supported by interface ?

Exampel:

interface Bike{
void run();
}
interface Car{
void speed();
}
class Test implements Bike, Car {

public void run() { System.out.println("Running..."); }
public void speed()  { System.out.println("Speeding..."); }

public static void main(String []args){
Test t = new Test();
t.run();
t.speed();
  }
}

Output:Running...
              Speeding...

Note: In the above example there is two interface Bike and Car and has two method.If we want   access those two methods we can easily implements both interfaceand use both method.But         it is only  possible in interface case.
 If these two methods are in two different class then we can't access both methods
 because we can't extends two class so this senario is possible by interface
 thats why we say Multiple Inheritance is achieved by Interfacce.


Note: We can implements two or more interface but we can't extends more than one class.


Another Example of Multiple Inheritance by Interface:

interface Bike{
void run();
  }
interface Car{
void run();
}
class Test implements Bike,car{
public void run() { System.out.println("Running...");}

public static void main(String []args){
Test t = new Test();
t.run();
   }
}

Output: Running...

Note: As you can see in the above example,Bike and car interface have same methods but its
implementation is provided by class Test, so there is no ambiguity.

Note: A class implements interface but One interface extends another interface also.

interface Bike{
void run();
}
interface Car extends Bike{
void speed();
}
class Test implements Car{
public void run()  {System.out.println("running"); }
public void speed()   {System.out.println("speeding"); }

public static void main(String []args){
Test t= new Test();
t.run();
t.speed();
  }
}

Output:running
                speeding


What is marker or tagged interface ?

An interface that have no member is known as marker or tagged interface.For example: Serializable,
Cloneable, Remote etc.They are used to provide some essential information to the JVM so that JVM may perform some useful operation.

Note: An interface can have another interface i.e. known as nested interface.We will learn it
in detail in the nested classes post. 

For example:

interface Bike{
void run();

interface runningCar{
void running();
  }
}


Note:A Interface which has only one method is known as Functional Interface. For example Runnable Interface has only one method as public void run().







What is instanceof Operator in java ?


The  instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface) and it return Boolean value

The instanceof operator is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that have null value, it returns false.

Simple example of instanceof operator:

Let's see the simple example of instance operator where it tests the current class.

class Test{

public static void main(String []args){
Test t=new Test();
System.out.println(t instanceof Test);
  }
}

Output: true

An object of subclass type is also a type of parent class.For example, if Person extends Student then object of Person can be reffered by either Person or Student class.

Another example of instanceof operator:

class Person{ }
class Student extends Person  {  //Student inherits Person

public static void main(String []args){
Student s=new Student();
System.out.println(s instanceof Person);
  }
}

Output: true

instanceof operator with a variable that have null value:

If we apply instanceof operator with a variable that have null value, it ruturns false.
Let's see the example given below where we apply instanceof operator with the variable that
have null value.

For example:

class Person{
public static void main(String []args){
Person p=null;
System.out.println(p  instanceof  Person);
  }
}

Output: false



Thursday, 18 December 2014

What is Operators in java ?

Operators in java:

Operator is a special symbol that is used to perform operations.

Precedence of Operators:

Operators:                                              Precedence:

postfix                                                           exp++

prefix & uniary                                           ++exp,--exp,+exp,-exp,~,!

multiplicative                                             * / %

additive                                                      +,-

shift                                                           << >> >>>

relational                                                  <  >  <=  >=  instanceof

equality                                                     == !=

bitwise AND                                            &

bitwise exclusive OR                               ^

bitwise inclusive OR                                |

logical AND                                         &&

logical OR                                               ||

ternary                                                   ?  :

assignment                                          = += -= *= /= %= &= ^= |= <<= >>= >>>=