Sunday 15 June 2014

What is encapsulation?

Encapsulation :  It is a process by which wrapping code and data into a single unit.

Example : A java bean is a best example of heighly encapsulated class where any instance variable declared as private and these private variable can access through public method.

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


//save as EmpTest.java  
package com.pky.com;  
class EmpTest{  
public static void main(String[] args){  
Employee e=new Employee();  
e.setName("Pradeep Yadav");  
System.out.println(s.getName());  
}  
}

Output :
Pradeep Yadav

Advantage of Encapsulation :

* you can make the class read-only or write-only.
 you can control over the data

Using yield() and join() in threading in java

Use of yield() : yield() is used in threading to allow another thread to execute which have same priority and itself switch running to runnable state.

Example :

package mypkg;

public class YieldDemo {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread p = new Producer();
Thread c = new Consumer();
p.setPriority(Thread.MIN_PRIORITY);
c.setPriority(Thread.MAX_PRIORITY);
p.start();
c.start();
}
}

class Producer extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("I am producer :" + i);
Thread.yield();
}
}
}

class Consumer extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {

System.out.println("I am consumer :" + i);
Thread.yield();
}
}


}


Use of join() : This method is used to current thread execute completely without any intrrupt. When it execute completely then control give other thread for execution.

Example :

Fetch any number of heighest salary from table in mysql

You can fetch any number of heighest salary from table in mysql using following query -

select * from emp order by salary desc limit 0,1;

In above query emp is a table, salary is a column so when we change limit value like 0 or 1 or 2 it will be fetch heighest, second heighest, and third heighest and so on. Each red color word is a keword in mysql.

How to delete duplicate value from table in mysql?

Here is a siple query to delete duplicate value from table :

DELETE e1 FROM employee e1, employee e2 WHERE e1.name = e2.name AND e1.id > e2.id;