Saturday, 16 December 2017

Write a java program to reverse a string or line using recursion.

public class Reverse {
public static void main(String[] args) {
String rev="Hello here is reverse using recursion";
revrec(rev);
//System.out.println(rev);
System.out.println(revrec(rev));
}

static String revrec(String rev) 
                 {
 
                 String reverse ="";
// TODO Auto-generated method stub
if(rev.length() == 1){
return rev;
}
else
{
 
reverse += rev.charAt(rev.length()-1)+revrec(rev.substring(0, rev.length()-1));
 
return reverse;
                 }
}
   

}

Thursday, 12 January 2017

Write a program to create deadlock between two threads.

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other to release a lock.

Code:
package com.javakickoff
public class MyDeadlockClass {

 String str1 = "Oracle";
 String str2 = "MySQL";
 
 Thread trd1 = new Thread("My Thread 1"){
  public void run(){
  while(true){
     synchronized(str1){
        synchronized(str2){
           System.out.println(str1 + str2);
     }
    }
   }
  }
 };
 
 Thread trd2 = new Thread("My Thread 2"){
  public void run(){
  while(true){
     synchronized(str2){
        synchronized(str1){
           System.out.println(str2 + str1);
     }
    }
   }
  }
 };
 
 public static void main(String a[]){
  MyDeadlockClass mdl = new MyDeadlockClass();
  mdl.trd1.start();
  mdl.trd2.start();
 }
}

How to call stored procedure in Hibernate

MySQL store procedure

Here’s a MySQL store procedure, which accept a stock code parameter and return the related stock data.


DELIMITER $$
CREATE PROCEDURE `GetStocks`(int_stockcode varchar(20))
BEGIN
   SELECT * FROM stock where stock_code = int_stockcode;
   END $$

DELIMITER ; 
In MySQL, you can simple call it with a call keyword : 
CALL GetStocks('7277');

Hibernate call store procedure

In Hibernate, there are three approaches to call a database store procedure.

1. Native SQL – createSQLQuery

You can use createSQLQuery() to call a store procedure directly.
 Query query = session.createSQLQuery(
 "CALL GetStocks(:stockCode)")
 .addEntity(Stock.class)
 .setParameter("stockCode", "7277");

List result = query.list();
for(int i=0; i<result.size(); i++){
 Stock stock = (Stock)result.get(i);
 System.out.println(stock.getStockCode());
} 

2. NamedNativeQuery in annotation

Declare your store procedure inside the @NamedNativeQueries annotation.
 //Stock.java 
...  
@NamedNativeQueries({ 
 @NamedNativeQuery( 
 name = "callStockStoreProcedure", 
 query = "CALL GetStocks(:stockCode)", 
 resultClass = Stock.class ) }) 

@Entity  
@Table(name = "stock") 
public class Stock implements java.io.Serializable {

Call it with getNamedQuery().
Query query = session.getNamedQuery("callStockStoreProcedure")
 .setParameter("stockCode", "7277");
List result = query.list();
for(int i=0; i<result.size(); i++){
 Stock stock = (Stock)result.get(i);
 System.out.println(stock.getStockCode());
} 

3. sql-query in XML mapping file 

Declare your store procedure inside the "sql-query" tag. 

<!-- Stock.hbm.xml --> 

...

<hibernate-mapping>
    <class name="com.mkyong.common.Stock" table="stock" ...>
        <id name="stockId" type="java.lang.Integer">
            <column name="STOCK_ID" />
            <generator class="identity" />
        </id>
        <property name="stockCode" type="string">
            <column name="STOCK_CODE" length="10" 
        not-null="true" unique="true" />
        </property>
        ...
    </class>

    <sql-query name="callStockStoreProcedure">
 <return alias="stock" class="com.mkyong.common.Stock"/>
 <![CDATA[CALL GetStocks(:stockCode)]]>
    </sql-query>

</hibernate-mapping> 
Call it with getNamedQuery().
Query query = session.getNamedQuery("callStockStoreProcedure")
 .setParameter("stockCode", "7277");
List result = query.list();
for(int i=0; i<result.size(); i++){
 Stock stock = (Stock)result.get(i);
 System.out.println(stock.getStockC

Why multiple inheritance is not supported in java?

First of all try to understand what is diamond problem?

Consider the below diagram which shows multiple inheritance as Class D extends both Class B & C. Now lets say we have a method in class A and Class B & C overrides that method in their own way. Now problem comes here – 

Assume, method hello() is overridden in Class B and C.

Class D is extending both B & C, so now if Class D wants to use the same method i.e. hello(), which method would be called ? the overridden method hello() of B or or C ?.  Because of this ambiguity java doesn’t support multiple inheritance.

Also, multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity. Also java avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn't provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.

However, you can achieve multiple inheritance in Java using interfaces. Assume in above diagram B and C is interface not a class, then class D can implement the method hello() and this will be common implementation in class D.

interface B
{
   public void hello();
}
interface C
{
   public void hello();
}
class D implements B, C
{
   public void hello()
   {
       System.out.println(" Multiple inheritance example using interfaces");
   }
}

Saturday, 8 August 2015

Program to print even and odd numbers using two threads

package JavaBuzz.Threadmania;

class PrintEvenNumbersTask implements Runnable {

private Object lock;

public PrintEvenNumbersTask(Object lock) {
    this.lock = lock;
}

@Override
public void run() {
    synchronized (lock) {
        for (int i = 0; i <= 10; i += 2) {

            lock.notify();

            System.out.println("Even : "+i);

            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        lock.notify(); // not required if thread1 gains lock first
    }
}

}


class PrintOddNumbersTask implements Runnable {

private Object lock;

public PrintOddNumbersTask(Object lock) {
    this.lock = lock;
}

@Override
public void run() {
    synchronized (lock) {
        for (int i = 1; i < 10; i += 2) {

            lock.notify();

            System.out.println("Odd : "+i);

            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        lock.notify();
    }
}

}



public class EvenOddThreads {

public static void main(String[] args) {

    Object lock = new Object();

    PrintEvenNumbersTask printEvenNumberstask = new PrintEvenNumbersTask(lock);
    PrintOddNumbersTask printOddNumberstask = new PrintOddNumbersTask(lock);

    Thread thread1 = new Thread(printEvenNumberstask);
    Thread thread2 = new Thread(printOddNumberstask);

    thread2.start();
    thread1.start();

}

}

Output : 

Odd : 1
Even : 0
Odd : 3
Even : 2
Odd : 5
Even : 4
Odd : 7
Even : 6
Odd : 9
Even : 8
Even : 10

Friday, 7 August 2015

Writing your own custom exception in Java

1. Custom defined exception in Java


package exception.custom;

public class MyException extends Exception {

public MyException(String message)
{
super(message);
}

}

Analysis of the above code

"MyException" is our exception class name. It can be any name.
Mandatory thing to be done is our class extends "Exception" class to provide exception feature to you class. 
"Now we define a constructor of my class. This constructer takes a "String" argument. We call super class' constructor(super class here is "Exception class") and pass this string to it. Now Java creates a new Exception with the message passed in the input String

2. How to make use of the custom defined exception

Using Try/Catch block

package exception.custom;

public class CustomException {

/**
* @param args
* @throws MyException 
*/
public static void main(String[] args) {
try{
for (int i = 0; i <10; i++) {
System.out.println(i);

if(i==5){
throw new MyException("My Exception Occurred");
}
}
}

catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Ouput:

0
1
2
3
4
5
exception.custom.MyException: My Exception Occurred
at exception.custom.CustomException.main(CustomException.java:15)

Using Throws

package exception.custom;

public class CustomException {

/**
* @param args
* @throws MyException 
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
for (int i = 0; i <=10; i++) {
System.out.println(i);
if(i==5){
throw new MyException("My Exception Occurred");
}
}
}
}

Ouput:

0
1
2
3
4
5
Exception in thread "main" exception.custom.MyException: My Exception Occurred
at exception.custom.CustomException.main(CustomException.java:16)

Thursday, 23 July 2015

Does Java pass by reference or by value?

Java is always pass-by-value. The difficult thing to understand is that Java passes objects as references and those references are passed by value.


Everything is passed by value in Java.  Objects are not passed by reference in Java. Let’s be a little bit more specific here: objects are passed by reference – meaning that a reference/memory address is passed when an object is assigned to another – BUT (and this is what’s important) that reference is actually passed by value. The reference is passed by value because a copy of the reference value is created and passed into the other object.


Example of pass by value in Java

Suppose we have a method that is named “getvalue” and it expects an integer to be passed to it:
public void getvalue (int var)
{
  var = var + 5;
}
Note that the “var” variable has 5 added to it. Now, suppose that we have some code which calls the method getvalue:
public static void main(String [] args)
{
  int passing = 4;

  getvalue (passing);
 
  System.out.println("The value of passing is: " + passing);
}
Java will just create a copy of the “passing” variable and that copy is what gets passed to the getvalue method – and not the original variable stored in the “main” method. This is why whatever happens to “var” inside the getvalue method does not affect the “passing” variable inside the main method.

How does pass by value working here?

Java basically creates another integer variable with the value of 4, and passes that to the “getvalue” method. That is why it is called “pass by value” – because the value of 4 is what is being passed to the “getvalue” method, not a reference to the “passing” variable.