<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>tutiez - tech and java tutorials, tech news and gadgets &#187; Java</title>
	<atom:link href="http://tutiez.com/category/java/feed" rel="self" type="application/rss+xml" />
	<link>http://tutiez.com</link>
	<description>tech and java tutorials, tech news and virtualization</description>
	<lastBuildDate>Thu, 23 May 2013 16:58:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>How to find or check palindrome String in java</title>
		<link>http://tutiez.com/how-to-find-or-check-palindrome-string-in-java.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-find-or-check-palindrome-string-in-java</link>
		<comments>http://tutiez.com/how-to-find-or-check-palindrome-string-in-java.html#comments</comments>
		<pubDate>Thu, 23 May 2013 16:58:26 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://tutiez.com/?p=1262</guid>
		<description><![CDATA[Many times we asked to write a code for checking palindrome string or words in java. Questions might be different such as How would you write a code in java to test for palindromes? How to check if a string is a palindrome in java? Write Java program for checking String is palindrome or not? [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Many times we asked to write a code for checking palindrome string or words in java. Questions might be different such as How would you write a code in java to test for palindromes? How to check if a string is a palindrome in java? Write Java program for checking String is palindrome or not? Writing a java program to check palindrome String is often asked to new graduates and also in ISC students. Now lets see how we can check the String or word is palindrome or not.</p>
<h3>Java Example for checking String is palindrome String</h3>
<p>In the following example, I would like to share two methods to check the String is palindrome or not. In first method using the character array we are checking each characters from both sides, if any of the character do not matches then we are returning false. If the length is odd then checking the center letter doesn&#8217;t matter because it doesn&#8217;t need to compare.<br />
In the second method we are using reverse method from the StringBuffer to reverse the String and we are matching the String with the reversed String if both Strings are equal then this String is palindrome String. </p>
<pre class="brush:java"> 
public class StringPalindromeTest {
    
    public static void main(String[] args) {
        String testWord = "aibohphobia";//"test"
        if( istPalindromeString( testWord ) ){
            System.out.println( "testWord : "+testWord+ " is a palindrome string" );
        }else{
            System.out.println( "testWord : "+testWord+ " is not a palindrome string" );
        }
        if( isPalindromeUsingReverse( testWord ) ){
            System.out.println( "testWord : "+testWord+ " is a palindrome string" );
        }else{
            System.out.println( "testWord : "+testWord+ " is not a palindrome string" );
        }
    }
    
    public static boolean istPalindromeString( String word ){
        char[] charFromWord = word.toCharArray();// Converting String to character array
        int startLength = 0;
        int endLength = word.length() - 1; //Getting length of the string
        while ( endLength > startLength ) {
            //Checking characters from both sides
            if ( charFromWord[ startLength ] != charFromWord[ endLength ] ) { 
                return false;
            }
            ++startLength;
            --endLength;
        }
        return true;
    }
    
    public static boolean isPalindromeUsingReverse( String word ) {
        // In this method we are doing reverse of the word and checking for equality
        return word.equals(new StringBuffer().append(word).reverse().toString());
    }
}
</pre>
<p>Output :</p>
<p>testWord : aibohphobia is a palindrome string<br />
testWord : aibohphobia is a palindrome string</p>
<p>testWord : test is not a palindrome string<br />
testWord : test is not a palindrome string</p>
<div class="shr-publisher-1262"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tutiez.com/how-to-find-or-check-palindrome-string-in-java.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to find LCM of two numbers &#8211; Java Example</title>
		<link>http://tutiez.com/how-to-find-lcm-of-two-numbers-java-example.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-find-lcm-of-two-numbers-java-example</link>
		<comments>http://tutiez.com/how-to-find-lcm-of-two-numbers-java-example.html#comments</comments>
		<pubDate>Wed, 22 May 2013 18:08:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://tutiez.com/?p=1255</guid>
		<description><![CDATA[How to find LCM of two numbers &#8211; Java Example Write a program to find the LCM of two numbers in java is a popular question in ISC exam as well as in interviews of newly graduated candidates. This question basically checks your logic and knowledge of iteration, its overhead, breaking of loop etc. We [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><h2>How to find LCM of two numbers &#8211; Java Example</h2>
<p>Write a program to find the LCM of two numbers in java is a popular question in ISC exam as well as in interviews of newly graduated candidates. This question basically checks your logic and knowledge of iteration, its overhead, breaking of loop etc.</p>
<p>We all know that LCM or the least common multiple of two or more non-zero whole numbers is actually the smallest whole number that is divisible by each of the numbers. In this tutorial we will see how to calculate LCM of two numbers using java.</p>
<h3>Java example to find LCM of two numbers</h3>
<p>Following example shows how to find the LCM of the two numbers. Now lets see how we are finding LCM step by step. </p>
<p>1. We are taking two inputs from users and deciding min and max among those.<br />
2. After deciding min and max of these two numbers, we will be iterating till the min number.<br />
3. Then we are multiplying index to the max number. Then checking this value is fully divided by the min value.<br />
4. If it is divisible then we get the LCM value for it. We can stop our iteration at this point.</p>
<h3>Simple java program to find LCM of two numbers</h3>
<pre class="brush:java"> 
public class LCMTest { 
    public static void main(String[] args) { 
        try{ 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
        int num1, num2, maxNum, minNum, multiVal, lcm = 1; 
        System.out.print("Enter first number : "); 
        num1 = Integer.parseInt(br.readLine()); 
        System.out.print("Enter second number : "); 
        num2 = Integer.parseInt(br.readLine()); 
        if(num1 is greater than num2 )
        {
             maxNum=num1;
             minNum=num2;
        }
        else
        {
             maxNum=num2;
             minNum=num1;
        }

        for (int i = 1; i <= minNum; i++) { 
            multiVal = maxNum * i; // Getting multiples of the number 
            if (multiVal % minNum == 0) // Checking multiVal is divisible by minNum 
            { 
                lcm = multiVal; //Got the LCM value                 
                 break;         //breaking the loop after getting LCM  
            } 
        } 
        System.out.println("L.C.M. of "+num1+" and "+num2+" is " + lcm); 
     
    }catch(Exception es){ 
            System.out.println("es "+es.getLocalizedMessage()); 
    } 
    } 
}
</pre>
<p>Thus we have seen how to find LCM from two numbers in java.</p>
<div class="shr-publisher-1255"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tutiez.com/how-to-find-lcm-of-two-numbers-java-example.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to remove duplicate elements from ArrayList in Java</title>
		<link>http://tutiez.com/how-to-remove-duplicate-elements-from-arraylist-in-java.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-remove-duplicate-elements-from-arraylist-in-java</link>
		<comments>http://tutiez.com/how-to-remove-duplicate-elements-from-arraylist-in-java.html#comments</comments>
		<pubDate>Tue, 21 May 2013 14:43:53 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Collections]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[ArrayList]]></category>

		<guid isPermaLink="false">http://tutiez.com/?p=1252</guid>
		<description><![CDATA[How to remove duplicate elements from ArrayList in Java Many times we need to remove duplicate or repetitive elements from the ArrayList because ArrayList dont check for duplicates. We will use HashSet to remove duplicates from the ArrayList. As we all know HashSet do not store duplicates but it also do not maintain the order [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><h2>How to remove duplicate elements from ArrayList in Java</h2>
<p>Many times we need to remove duplicate or repetitive elements from the ArrayList because ArrayList dont check for duplicates. We will use HashSet to remove duplicates from the ArrayList. As we all know HashSet do not store duplicates but it also do not maintain the order of insertion. So we need to keep it in mind while using HashSet to remove duplicates from the arraylist in java. Following example  shows to delete duplicates from ArrayList </p>
<h3>Java program to delete duplicates from ArrayList using HashSet</h3>
<pre class="brush:java"> 
public static void removeDuplicates(ArrayList arList) 
 { 
 Set set = new HashSet(); 
 List tempList = new ArrayList(); 
 for (Iterator iter = arList.iterator();    iter.hasNext(); ) { 
 Object element = iter.next(); 
   if ( set.add(element) ) {  //Condition to check duplicates 
      tempList.add( element ); //Adding non duplicate elements 
    } 
    arList.clear(); //Clearing old contents 
    arList.addAll( tempList ); //Adding list without duplicates 
    } 
 } 
</pre>
<p>In above example in order to maintain the sorting order of the arrayalist we are first adding the element to the hashset if element doesnt get added we are not adding it to arraylist.<br />
I would like to add one more method for removing duplicates from arraylist. In this method we will be using LinkedHashSet instead of HashSet because LinkedHashSet maintains the order of the ArrayList while removing duplicate elements from ArrayList </p>
<h3>Java program to delete duplicates from ArrayList using LinkedHashSet</h3>
<pre class="brush:java"> 
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>( arList );  
List<String> arListWithoutDuplicates = new ArrayList<String>( linkedHashSet ); 
</pre>
<p>In above example we are creating first LinkedHashSet from the ArrrayList which has duplicates, LinkedHashSet removes the duplicates and maintain the same order as the ArrayList. Once we get the LinkedHashSet we will get the new ArrayList from the LinkedHashSet which do not contain the duplicates and order remains same as previous one.</p>
<p>So we have just looked at two methods to remove the duplicate or repetitive elements from ArrayList one is using HashSet and other is using LinkedHashSet.</p>
<div class="shr-publisher-1252"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tutiez.com/how-to-remove-duplicate-elements-from-arraylist-in-java.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to check number is kaprekar number java example</title>
		<link>http://tutiez.com/how-to-check-number-is-kaprekar-number-java-example.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-check-number-is-kaprekar-number-java-example</link>
		<comments>http://tutiez.com/how-to-check-number-is-kaprekar-number-java-example.html#comments</comments>
		<pubDate>Mon, 20 May 2013 14:40:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://tutiez.com/?p=1250</guid>
		<description><![CDATA[Kaprekar number is the number whose square in that base can be split into two parts that add up to the original number. To find the Kaprekar number we need to follow 3 steps 1. First take the square of the number 2. Get the middle point of that digit and split it into two. [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Kaprekar number is the number whose square in that base can be split into two parts that add up to the original number.<br />
To find the Kaprekar number we need to follow 3 steps<br />
 1. First take the square of the number<br />
 2. Get the middle point of that digit and split it into two.<br />
 3.Then take the total of the two digits and check with the original number, if they are equal then it is a Kaprekar Number.<br />
 e.g. Suppose user has entered number as 9, take the square of that number which is 81 if we split this into two parts then 8 and 1. But the total of 8 and 1 is 9 , so the number is Kaprekar number </p>
<h3>Java example to test Kaprekar Number</h3>
<p>In following example, we are accepting the user entered number and testing that number whether it is Kaprekar number or not.<br />
1. First we are taking square of it.<br />
2. Then we are converting it from int to String.<br />
3 Find the length of the String<br />
4. Take mid point of the String and split it in two parts.<br />
 5 Converting the parts to int again.<br />
6. Checking total of these number is same as original number. If it is same then it is a Kaprekar number and if it is different then it is not Kaprekar number. </p>
<pre class="brush:java">
import java.io.*; 
class KaprekarTest 
{ 
public static void main(String[] args) throws IOException 
{ 
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
        System.out.print("Enter a Number to check for Kaprekar Number : "); 
        int numberToTest=Integer.parseInt(br.readLine()); //Get the input from user 
        int squareOfNum = numberToTest*numberToTest; // Our first step is to find square of the number 
        String squareStr=Integer.toString(squareOfNum); //converting the square into a String to get mid point 
        if(squareOfNum <= 9) 
            squareStr="0"+squareStr; 
        int lengthOfDigit = squareStr.length(); //Finding length of the String 
        int mid= lengthOfDigit/2; //finding the middle point to check Kaprekar number 
        String leftDigitsStr=squareStr.substring(0,mid); //taking out digits from left side of the square 
        String rightDigitsStr=squareStr.substring(mid); //taking out digits from right side of the square 
        int leftDigit=Integer.parseInt(leftDigitsStr); //converting the left side String into Integer 
        int rightDigit=Integer.parseInt(rightDigitsStr); //converting the right side String into Integer 
        if( leftDigit+rightDigit == numberToTest ) //Check for Kaprekar number 
            System.out.println(numberToTest+" is a Kaprekar Number"); 
        else 
            System.out.println(numberToTest+" is Not a Kaprekar Number"); 
    } 
} 
</pre>
<div class="shr-publisher-1250"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tutiez.com/how-to-check-number-is-kaprekar-number-java-example.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to reverse string in java without using reverse method</title>
		<link>http://tutiez.com/how-to-reverse-string-in-java-without-using-reverse-method.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-reverse-string-in-java-without-using-reverse-method</link>
		<comments>http://tutiez.com/how-to-reverse-string-in-java-without-using-reverse-method.html#comments</comments>
		<pubDate>Fri, 17 May 2013 14:59:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://tutiez.com/?p=1247</guid>
		<description><![CDATA[How to reverse string in java without using reverse method How to reverse string without using reverse method of StringBuffer is one of the frequently asked interview questions in java. It is also important for ICSE and ISC students for understanding of String and characters and iterators etc. In interview most of the java programmers [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><h2>How to reverse string in java without using reverse method</h2>
<p>How to reverse string without using reverse method of StringBuffer is one of the frequently asked interview questions in java. It is also important for ICSE and ISC students for understanding of String and characters and iterators etc.</p>
<p>In interview most of the java programmers answer this String reverse question by using StringBuffer reverse() method which is used to reverse the String. But interviewer is not interested in this answer so tweaks his question and ask How to reverse the String without using reverse method of StringBuffer. This tutorial explains how to reverse the String using two methods one is iterative and other is recursive.</p>
<h3>Reverse string in java using iterative method</h3>
<p>In case of iterative method we are using character array of String in java. Once we get the character array we iterate over it in reverse order and use StringBuilder to append each character as shown in example below</p>
<pre class="brush:java">
public static String reverseUsingChar(String str) {

StringBuilder stringBuilder = new StringBuilder();

char[] charsInStr = str.toCharArray();

for (int i = charsInStr.length - 1; i >= 0; i--) {

stringBuilder.append(charsInStr[i]);

}

return stringBuilder.toString();

}
</pre>
<h3>Reverse string in java using recursive method</h3>
<p>Next method we use to reverse the String is recursive method as shown in example below. We are passing the argument of strRev.substring(1) to the method recursively and in the method we are appending the first character of current String to it which do the reverse of the String. But use the recursive code in development code very carefully as it may give stackoverflow error because of long string or some program error itself.</p>
<pre class="brush:java">
public static String reverseStringRecursively(String strRev) {

if (strRev.length() < 2) {

return strRev;

}

return reverseStringRecursively(strRev.substring(1)) + strRev.charAt(0);

}
</pre>
<p>Thus we have seen two methods to reverse the String without using StringBuffer reverse method. </p>
<p>Hope you find this article helpful.</p>
<div class="shr-publisher-1247"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tutiez.com/how-to-reverse-string-in-java-without-using-reverse-method.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to swap two numbers without using third variable in java</title>
		<link>http://tutiez.com/how-to-swap-two-numbers-without-using-third-variable-in-java.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-swap-two-numbers-without-using-third-variable-in-java</link>
		<comments>http://tutiez.com/how-to-swap-two-numbers-without-using-third-variable-in-java.html#comments</comments>
		<pubDate>Thu, 16 May 2013 16:32:43 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://tutiez.com/?p=1243</guid>
		<description><![CDATA[Three Simple ways to swap two numbers without using third variable This article explains how to swap two numbers without using third temp variable. This java example of swapping two numbers without using third variable is important because it covers fundamentals and test your logic as well. This is the reason this is very important [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><h2>Three Simple ways to swap two numbers without using third variable</h2>
<p>This article explains how to swap two numbers without using third temp variable. This java example of swapping two numbers without using third variable is important because it covers fundamentals and test your logic as well. This is the reason this is very important interview question for freshers. This is very important question for ICSE students as well.</p>
<p>We will see three methods to swap two numbers without using third temp variable.</p>
<h3>1. Swap two numbers using addition and subtraction</h3>
<p>In the example below first we are doing addition of two numbers and then subtracting the numberTwo from total. Then again subtracting new numberTwo from the total.</p>
<pre class="brush:java">
public class SwapNumberTest {

public static void main(String[] args) {

int numberOne = 36;

int numberTwo = 63;

System.out.println("Before Swapping numberOne = "+ numberOne +" numberTwo "+numberTwo );

numberOne = numberOne + numberTwo;

numberTwo = numberOne - numberTwo;

numberOne = numberOne - numberTwo;

System.out.println("After Swapping numberOne = "+ numberOne +" numberTwo "+numberTwo );

}

}
</pre>
<p>Output :<br />
Before Swapping numberOne = 36 numberTwo 63<br />
After Swapping numberOne = 63 numberTwo 36</p>
<h3> 1. Swap two numbers using multiplication and division technique </h3>
<p>Second method is to use multiplication and division technique to swap two number without using third variable. In this method similar to addition and subtraction we are do multiply and divide operation as shown in the example below which is very self explanatory.</p>
<pre class="brush:java">
public class SwapNumberTest {

public static void main(String[] args) {

int numberOne = 3; //0011

int numberTwo = 6; //0110

System.out.println("Before Swapping numberOne = "+ numberOne +" numberTwo "+numberTwo );

numberOne = numberOne * numberTwo;

numberTwo = numberOne / numberTwo;

numberOne = numberOne / numberTwo;

System.out.println("After Swapping numberOne = "+ numberOne +" numberTwo "+numberTwo );

}

}
</pre>
<p>Output :<br />
Before Swapping numberOne = 3 numberTwo 6<br />
After Swapping numberOne = 6 numberTwo 3</p>
<h3> 1. Swap two numbers using XOR operation </h3>
<p>Third method to swap the two numbers without using third variable is to use XOR operation. The binary XOR operation will always produce a 1 output if either of its inputs is 1 and will produce a 0 output if both of its inputs are 0 or 1. So as shown in the example below if we use XOR operation then we can easily swap the numbers</p>
<pre class="brush:java">
public class SwapNumberTest {

public static void main(String[] args) {

int numberOne = 3; //0011

int numberTwo = 6; //0110

System.out.println("Before Swapping numberOne = "+ numberOne +" numberTwo "+numberTwo );

numberOne = numberOne ^ numberTwo;

numberTwo = numberOne ^ numberTwo;

numberOne = numberOne ^ numberTwo;

System.out.println("After Swapping numberOne = "+ numberOne +" numberTwo "+numberTwo );

}

}
</pre>
<p>Output :<br />
Before Swapping numberOne = 3 numberTwo 6<br />
After Swapping numberOne = 6 numberTwo 3</p>
<p>Thus we have seen three ways to swap two numbers in java without using third or temp variable.</p>
<div class="shr-publisher-1243"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tutiez.com/how-to-swap-two-numbers-without-using-third-variable-in-java.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Singleton and multithreading in java</title>
		<link>http://tutiez.com/singleton-and-multithreading-in-java.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=singleton-and-multithreading-in-java</link>
		<comments>http://tutiez.com/singleton-and-multithreading-in-java.html#comments</comments>
		<pubDate>Wed, 15 May 2013 17:38:09 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Singleton pattern]]></category>

		<guid isPermaLink="false">http://tutiez.com/?p=1238</guid>
		<description><![CDATA[Thread safe singleton in java We all know Singleton pattern ensures a class has only one instance and provides a global point of access to it. But the question is how can we create single instance in case of multi threading ? Simple answer to this is to make getInstance() method as synchronized method, but [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><h2>Thread safe singleton in java</h2>
<p>We all know Singleton pattern ensures a class has only one instance and provides a global point of access to it. But the question is how can we create single instance in case of multi threading ?<br />
Simple answer to this is to make getInstance() method as synchronized method, but by doing this we force every thread to waits its turn before it can enter the method. Here we need to understand two points one is synchronization is expensive and synchronization we done on getInstance() method is only relevant to the first time call of this method, once we get the unique instance we expected, we do not need to synchronize this method.</p>
<p>Now lets see how we can improve this situation in case of multithreading as we often need Singleton in presence of multiple threads.</p>
<p>First thing we can do is we can create eagerly created instance than the lazy instance as shown below :</p>
<pre class="brush:java">
public class SingletonTest{
       private static SingletonTest uniqueInstance = new SingletonTest();
       private SingletonTest(){
       }
       public static SingletonTest getInstance(){
            return uniqueInstance;
       }  
}
</pre>
<p>Here in above example we are creating instance of Singleton in a static initialization instead of creating it in getInstance() method i.e. Using lazy initialization. When the class is loaded JVM creates a unique instance of this class and hence it achieves our purpose of not creating multiple instances of Singleton in multithreading environment.</p>
<h3>Double checked locking by using volatile keyword</h3>
<p><img src="http://tutiez.com/wp-content/uploads/2013/05/singletonandmultithreading.png" alt="singleton and multithreading in java" width="97" height="110" class="alignright size-full wp-image-1241" /></p>
<p>Second thing we can do is to use <b>double checked locking.</b> Lets see what is the <u>double checked locking</u> approach is we first check whether instance is created or not if it is not created then synchronize otherwise not. We achieve this <b>double checked locking by using volatile keyword</b> as shown in example below :</p>
<h4>Double checked locking example</h4>
<pre class="brush:java">
public class SingletonTest{
       private volatile static SingletonTest uniqueInstance;
       private SingletonTest(){
       }
       public static SingletonTest getInstance(){
            if( uniqueInstance == null ){
                synchronized ( SingletonTest.class  ){
                       if( uniqueInstance == null ){
                              uniqueInstance = new SingletonTest();
                       } 
                }
            }
            return uniqueInstance;
       }  
}
</pre>
<p>Volatile keyword make sure multiple treads handle uniqueInstance when it is being initialized. In case of double checked locking before doing synchronization we are checking uniqueInstance as null or not, and in synchronization block also we are checking uniqueInstance is null or not before creating instance.</p>
<div class="shr-publisher-1238"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tutiez.com/singleton-and-multithreading-in-java.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to start one thread after another thread in java?</title>
		<link>http://tutiez.com/how-to-start-one-thread-after-another-thread-in-java.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-start-one-thread-after-another-thread-in-java</link>
		<comments>http://tutiez.com/how-to-start-one-thread-after-another-thread-in-java.html#comments</comments>
		<pubDate>Tue, 14 May 2013 14:55:26 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://tutiez.com/?p=1233</guid>
		<description><![CDATA[How to start one thread after another thread in java? To start one thread after another thread is the functionality we often need in programming. So this makes a good interview question and often asked. You may get question like How to ensure that a thread runs after another ? Or There are thread Thread1, [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><h2>How to start one thread after another thread in java?</h2>
<p>To start one thread after another thread is the functionality we often need in programming. So this makes a good interview question and often asked. You may get question like How to ensure that a thread runs after another ? Or There are thread Thread1, Thread2 and Thread3, how can we ensure that thread Thread2 run after Thread1 and thread Thread3 run after Thread2?</p>
<p>Java provides one method to Thread object which is join() this method simply waits for this thread to die. join() method also has two variants such as join(long millis ) which waits for millis millisecond to die and join(long millis, int nanos) which waits for millis plus nanos to die.</p>
<p>To <strong>start one thread after another</strong> we need join() method.</p>
<p>As shown in example below we are creating three thread objects and in each thread we are passing runnable objects.</p>
<p>Important thing to note is after starting the thread with start() method we are calling join() method which waits for this thread to die and start another thread which fulfils our requirement</p>
<pre class="brush:java">
public class ThreadTest {

public static void main(String[] args) {

//creating 3 Thread objects and passing it an object of type Runnable

try{

Thread thread1 = new Thread(new MyRunnable("Thread 1"));

thread1.start();

thread1.join();

Thread thread2 = new Thread(new MyRunnable("Thread 2"));

thread2.start();

thread2.join();

Thread thread3 = new Thread(new MyRunnable("Thread 3"));

thread3.start();

thread3.join();

}catch(Exception es){

es.printStackTrace();

}

}

}

class MyRunnable implements Runnable {

String runnerName = "";

public MyRunnable(String name){

runnerName = name;

}

public void run() {

for(int i = 0 ; i < 5; i++){

try{

Thread.sleep(3000);

}catch(Exception es){

}

System.out.println(runnerName+" Counting i = " + i);

}

System.out.println("Thread executed!");

}

}
</pre>
<p>Output</p>
<p>Thread 1 Counting i = 0</p>
<p>Thread 1 Counting i = 1</p>
<p>Thread 1 Counting i = 2</p>
<p>Thread 1 Counting i = 3</p>
<p>Thread 1 Counting i = 4</p>
<p>Thread executed!</p>
<p>Thread 2 Counting i = 0</p>
<p>Thread 2 Counting i = 1</p>
<p>Thread 2 Counting i = 2</p>
<p>Thread 2 Counting i = 3</p>
<p>Thread 2 Counting i = 4</p>
<p>Thread executed!</p>
<p>Thread 3 Counting i = 0</p>
<p>Thread 3 Counting i = 1</p>
<p>Thread 3 Counting i = 2</p>
<p>Thread 3 Counting i = 3</p>
<p>Thread 3 Counting i = 4</p>
<p>Thread executed!</p>
<div class="shr-publisher-1233"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tutiez.com/how-to-start-one-thread-after-another-thread-in-java.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jtable interview questions and answers in java</title>
		<link>http://tutiez.com/jtable-interview-questions-and-answers-in-java.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jtable-interview-questions-and-answers-in-java</link>
		<comments>http://tutiez.com/jtable-interview-questions-and-answers-in-java.html#comments</comments>
		<pubDate>Sat, 11 May 2013 13:59:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JTable]]></category>

		<guid isPermaLink="false">http://tutiez.com/?p=1218</guid>
		<description><![CDATA[jtable interview questions and answers in java 1. What is jtable in java and why it is used? JTable is a component from java swing package which is used to show the data in table format. The data can be presented in many forms using the table models which can be customized too. JTable is [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><h1>jtable interview questions and answers in java</h1>
<h3>1. What is jtable in java and why it is used?</h3>
<p>JTable is a component from java swing package which is used to show the data in table format. The data can be presented in many forms using the table models which can be customized too.</p>
<p>JTable is used for tabular presentation of the data, but it gives more than that such as you can edit the jTable values, customize the each row and column , show images in rows and column or headers.<br />
Apart from that it gives very important facility to sort using the individual columns so it is very important component in java swing and used frequently in UI</p>
<h3>2. Create a simple jtable in java and populate it with data</h3>
<p>If you are doing face to face interview, possibility is that you will be asked to write a code for creating a simple jtable and populate it with data. It is one of the important <b>jtable interview questions</b> because it shows you know the constructor of the jtable and passing the two dimensional array structure to jtable in java.</p>
<pre class="brush:java">
String columnNames[] = { "Column 1", "Column 2", "Column 3" };

// Create some data
String dataValues[][] =
{
	{ "a", "b", "c" },
	{ "l", "m", "n" },
	{ "p", "q", "r" },
	{ "x", "y", "z" }
};

// Create a new table instance
table = new JTable( dataValues, columnNames );
</pre>
<h3>3. What is the difference between DefaultTableModel and AbstractTableModel?</h3>
<p><b>AbstractTableModel vs DefaultTableModel</b> </p>
<p>The AbstractTableModel is a class that implements TableModel interface. Though many of the methods of the TableModel interface implemented by the AbstractTableModel, these methods are simple and minimal changes done. So AbstractTableModel gives you the choice to implement those methods, which collection to use etc. On the other hand DefaultTableModel is a subclass of AbstractTableModel, which makes defaultTableModel concrete but easy to use.A defaultTableModel uses Vectors of Vectors.</p>
<p>This question is again one of very important <u>jtable interview questions</u> because these two models are frequently used in jtable.<br />
Choosing the model is dependent of usage because AbstractTableModel gives more flexibiliy than DefaultTableModel in java</p>
<h3>4. Write a simple jtable with AbstractTableModel</h3>
<p> This question is one of the tough jtable interview questions because it shows how you have used abstractTableModel to fill the data in jtable. Here you will find <a href="http://tutiez.com/simple-jtable-example-using-abstracttablemodel.html" title="Simple JTable example using AbstractTableModel" target="_blank">Simple JTable example using AbstractTableModel</a>  </p>
<p><img src="http://tutiez.com/wp-content/uploads/2013/05/jtableinterviewquestions.png" alt="jtable interview questions" width="87" height="95" class="alignright size-full wp-image-1227" /></p>
<h3>5. How to write cell renderer component to the jtable?</h3>
<p>jtable often requires cell to be rendered , it makes really one of the good jtable interview questions. You can find here how to create custom cell renderer for the jtable cell and make custom changes in jtable cell <a href="http://tutiez.com/jtable-with-custom-cell-renderer-example.html" title="JTable with custom cell renderer example" target="_blank">JTable with custom cell renderer example</a></p>
<h3>6. How do you set the tooltip to the jtable</h3>
<p>jtable cell have more data than their size, so it is very important to show the correct tool tip for each cell, so this is also one of the very important jtable interview questions. To find how to set tooltip for the jtable please click below :</p>
<p><a href="http://tutiez.com/how-to-set-tooltip-to-jtable-cell.html" title="How to set tooltip to JTable cell" target="_blank">How to set tooltip to JTable cell</a> </p>
<h3>7. How to add custom cell editor to jtable </h3>
<p>This is really a one of the important <u>jtable interview questions</u> for senior level developers. A jtable cell editor requires to implement the TableCellEditor interface. We also need to extend AbstractCellEditor class to have listeners supported by the TableCellEditor. So most important things to remember is the implementing the TableCellEditor interface and extending the AbstractCellEditor class.</p>
<p>When we consider table cell editor , it is slightly different than the <a href="http://tutiez.com/jtable-with-custom-cell-renderer-example.html" title="JTable with custom cell renderer example" target="_blank">JTable with custom cell renderer</a> where the editor not required create a new component each time  getTableCellEditorComponent() is called. It should call the same component again. </p>
<pre class="brush:java">
public class CustomCellEditor extends AbstractCellEditor implements TableCellEditor {
    JComponent component = new JTextField();
    public Component getTableCellEditorComponent(JTable table, Object value,
            boolean isSelected, int rowIndex, int vColIndex) {
        // 'value' is value located at rowIndex, vColIndex

        if (isSelected) {
            // if cell is selected
        }

        // Setting the text
        ((JTextField)component).setText((String)value);

        return component;
    }

    public Object getCellEditorValue() {
        return ((JTextField)component).getText();
    }
    // getCellEditorValue method is called when editing is completed.
     
}
</pre>
<p>Using getTableCellEditorComponent() method you can get the value from the cell and configure it as show as setText. getCellEditorValue() method is called when editing is completed and returns the new value stored in the cell.</p>
<p>But how to use this CustomCellEditor class? Lets see with following code :</p>
<pre class="brush:java">
TableColumn col = table.getColumnModel().getColumn(columnIndex);
col.setCellEditor(new CustomCellEditor());
</pre>
<p>Thus we have seen how we can create custom cell editor in jtable, important things to note that TableCellEditor interface and AbstractCellEditor class. And methods to remember are getTableCellEditorComponent() and getCellEditorValue()</p>
<h3>8. How to add background image to the jtable?</h3>
<p>This is also one of the important jtable interview questions. Many times we need a watermark or insert an image behind the jtable. Following tutorial <a href="http://tutiez.com/how-to-add-watermark-or-background-image-to-the-jtable.html" title="How to add watermark or background image to the JTable?" target="_blank">How to add watermark or background image to the JTable?</a> have detailed explanation of adding background image to the jtable.</p>
<p>Hope you find these jtable interview questions and answers helpful.<br />
If you like this article share it with your friends <img src='http://tutiez.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="shr-publisher-1218"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tutiez.com/jtable-interview-questions-and-answers-in-java.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to disable automatic scanning in Netbeans?</title>
		<link>http://tutiez.com/how-to-disable-automatic-scanning-in-netbeans.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-disable-automatic-scanning-in-netbeans</link>
		<comments>http://tutiez.com/how-to-disable-automatic-scanning-in-netbeans.html#comments</comments>
		<pubDate>Mon, 11 Mar 2013 17:26:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Netbeans]]></category>

		<guid isPermaLink="false">http://tutiez.com/?p=1203</guid>
		<description><![CDATA[Sometimes you are using a PC with low memory or old processor, but while using Netbeans IDE you find scanning projects or scan for external changes taking quite a while which sometimes not very comfortable. The scanning is supposed to occur intermittently and its intention is good, but sometimes it affects the performance.So we will [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Sometimes you are using a PC with low memory or old processor, but while using Netbeans IDE you find scanning projects or scan for external changes taking quite a while which sometimes not very comfortable.<br />
The scanning is supposed to occur intermittently and its intention is good, but sometimes it affects the performance.So we will see how we can disable automatic scanning feature in Netbeans in such cases.</p>
<p>But before actually disabling the auto scanning feature, you may want to check how many projects and files are open, if there are too many files open or unused projects are open then it is better to close these projects. When you close all the unused Projects , these products do not get scanned when you start the Netbeans.</p>
<h2>Disabling auto scanning in Netbeans :</h2>
<p>To disable the auto scanning in Netbeans you need to go to the Tools -> Options -> Miscellaneous -> Files</p>
<p>You can disable the checkbox as shown in image below :<br />
<br style="clear:left;" /><br />
<img src="http://tutiez.com/wp-content/uploads/2013/03/disableautoscanning.png" alt="Disable auto scanning in Netbeans" width="582" height="428" class="alignleft size-full wp-image-1205" /></p>
<p><br style="clear:left;" /></p>
<p>Though you can disable the auto scanning by this option by deselecting the checkbox, but you should try first option first and then go for the second one, as the scanning is sometimes desired.</p>
<h3> Scan for external changes</h3>
<p>Whenever main window of the Netbeans gets the focus then by default Netbeans looks for external changes. So you can also see the message scan for External Changes , the above mentioned option also stops this scan for external changes. </p>
<h3>How to start scan for External changes manually</h3>
<p>Now lets see you have disabled the auto scanning option but still you want to keep the code information up to date and correct then you can use the option in Sources Menu, that option is Scan for external changes. </p>
<p>You may also want to read another article about <a href="http://tutiez.com/netbeans-auto-complete-shortcuts-you-must-know.html" title="Netbeans auto complete shortcuts you must know" target="_blank">shortcuts available in netbeans here</a>. </p>
<div class="shr-publisher-1203"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://tutiez.com/how-to-disable-automatic-scanning-in-netbeans.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
