tutiez - tech and java tutorials, tech news and gadgets » Java http://tutiez.com tech and java tutorials, tech news and virtualization Sat, 22 Mar 2014 16:09:23 +0000 en-US hourly 1 http://wordpress.org/?v=3.9.2 Simple yes or no program in java swinghttp://tutiez.com/simple-yes-or-no-program-in-java-swing.html?utm_source=rss&utm_medium=rss&utm_campaign=simple-yes-or-no-program-in-java-swing http://tutiez.com/simple-yes-or-no-program-in-java-swing.html#comments Sun, 15 Dec 2013 10:30:26 +0000 http://tutiez.com/?p=1594 Simple yes or no program in java swing

After taking a look at article best book to buy to learn Java , in this article we will see how to write a simple yes or no program in java swing , to create option dialog of with Yes and No we will use the JOptionPane class to show the Yes and No options. Below is the simple yes or no program in java swing, in this program we can see the JOptionPane.showConfirmDialog being used to show the Yes and No options using JOptionPane in java swing. Now we will see what argument it takes and what does it signify.

The first argument to showConfirmDialog method is the parent component, which must be a Frame, null or a component inside a Frame. If we specify a Frame, then the option dialog which we are showing appears on the center and follow the focus of the Frame. Second argument is the question string we want to pass and third argument is the title of the option dialog. The fourth argument is to specify which buttons we want to show on the options dialog.

 

public class YesOrNoProgram{
JFrame frame;
public static void main(String[] args){
YesOrNoProgram dbShow = new YesOrNoProgram();
}

public YesOrNoProgram(){
frame = new JFrame("Simple Yes or No Options Demo");
JButton button = new JButton("Show YES/NO Options");
button.addActionListener(new DialogYesNoAction());
frame.add(button);
frame.setSize(500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(  JFrame.EXIT_ON_CLOSE );
}

public class DialogYesNoAction implements ActionListener{
public void actionPerformed( ActionEvent evt ){
int ret = JOptionPane.showConfirmDialog(
frame,
"Do you want to take next step?",
"Confirm Dialog Options",
JOptionPane.YES_NO_OPTION //YES and NO options
);
System.out.println("ret "+ret);
}
}
}

simple yes or no program in java swing

 

 

 

 

 

 

 

 

 

 

 

Customizing the button text in JOptionPane

To achieve customizing button text in JOptionPane we need to use showOptionDialog as shown in the code example below : Here we are passing the array of button text to the showOptionDialog and we can also set which button you want to be set as default button.

public class YesOrNoProgram {

    JFrame frame;

    public static void main(String[] args) {
        YesOrNoProgram dbShow = new YesOrNoProgram();
    }

    public YesOrNoProgram() {
        frame = new JFrame("Simple Yes or No Options Demo");
        JButton button = new JButton("Show YES/NO Options");
        button.addActionListener(new DialogYesNoAction());
        frame.add(button);
        frame.setSize(500, 400);
        frame.setVisible(true);
        frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
    }

    public class DialogYesNoAction implements ActionListener {

        public void actionPerformed( ActionEvent evt) {
            Object[] options = {"Yes it is",
                "No at all"};
            int ret = JOptionPane.showOptionDialog(frame,
                    "Is it what/how you want? ",
                    "Question",
                    JOptionPane.YES_NO_OPTION ,
                    JOptionPane.QUESTION_MESSAGE ,
                    null, //Keep null if you dont need custom icon
                    options, //these are titles of buttons
                    options[0]); //default title for button
            System.out.println("ret " + ret);
        }
    }
}

simple yes or no program in java swing

 

 

 

 

 

So here in this article we have seen the simple yes or no program in java swing, to see more about JOptionPane check JOptionPane example and JOptionPane tutorial

]]>
http://tutiez.com/simple-yes-or-no-program-in-java-swing.html/feed 0
Best book to buy to learn Javahttp://tutiez.com/best-book-to-buy-to-learn-java.html?utm_source=rss&utm_medium=rss&utm_campaign=best-book-to-buy-to-learn-java http://tutiez.com/best-book-to-buy-to-learn-java.html#comments Sun, 01 Dec 2013 06:08:40 +0000 http://tutiez.com/?p=1572 Best book to buy to learn Java is hard to find as there are so much books available in the market and each book has its own specialty. Though there are lot of free resources available on the internet, the books for Java language are really important to understand the programming language more deeply and step by step. These books guide you through the entire course and it makes very easy to grasp and understand each topic better. So here is a try to find best book to buy to learn Java, I would suggest you to get all these books and read.

First book I really like which helped me to clear lot of concepts about Java, So it is one of the best book to buy to learn Java.

Head First Java

This book is unconventional but is very enjoyable to learn. It is the best Java book for beginners which help them to learn Java in very easy manner and understand the concepts more deeply. The exercise and puzzle section makes really interesting to learn Java. Best part I like about this book is the “There are no dumb questions” section which is included in every chapter. It helps to clear some doubts in understanding the topic. So this makes Head First Java a very entertaining yet motivational book to learn Java.
It is no doubt best Java book for beginners.

Head First Object Oriented Analysis and Design

If you really want to know how object oriented analysis and design works or you are keen to make your thought process while programming more object oriented then this is must book for you. Complex analysis and design techniques are so much simplified in this book which makes this book a really one of the best book to buy to learn Java. So anybody who wants to write more maintainable or reusable code then you need to buy this book and start reading it. This books contains really a simplified explanation of composition over inheritance, why programming for interface is better and many more.

Thinking in java

Thinking in Java is again a complete book to learn Java language. Examples given for each concept is the best part of this book and this makes it one of the best book to buy to learn Java. New topics such as generics, annotations are covered in this book. This book also can easily used as a reference book. This is also a best Java book for beginners as this book is very organized and have lots of exercises in this book which helps to practice and understand more clearly.

Head First Design Patterns

This is another gem of a book. This is again a best Java book for beginners who want to explore design pattern. This book is all about how you apply object oriented programming concepts while you code. In each chapter this book explains the problem, what is the solution and why we are applying this pattern to make code more maintainable and reusable. Each chapter has exercises and puzzles which makes learning these complex concepts easier. As always I like the “There are no dumb questions” section which makes topic more clear. So if you want to buy a book for learning design pattern then it is one of the best book to buy to learn java. This book covers almost all the design patterns which are explained in simple language and with bullet points. This is the book which will take you to the next level of coding which will definitely help you to write a code which is of top quality, maintainable and reusable.

Effective Java

This is the best book to read if you are the professional Java Programmer. This book is from one of favorite java authors Joshua Bloch. This book as name suggest teaches you how to use Java programming language more effectively so this makes it one of the best book to buy to learn java. The explanation provided in this book is excellent and which makes it a top class Java book. If you are seasoned programmer in java I would recommend this book to you. Item based structure of this book helps you to read the book in short time intervals. This book also helps you to understand best practices about the reflection, serialization, enum and many more. So dont wait, get this book and start reading, this is really good book to learn Java.

Java Puzzlers

Java puzzlers is also a very different but very effective Java book I have come across. This is the book from Joshua Bloch with Neal Gafter. This books is important read because it explains many corner cases and pitfalls in Java language. This book is different and has many puzzles which makes you to think and understand Java language more You may find many of these puzzles often included by the interviewer in his/her questions to test the knowledge. So if you like to solve or understand corner cases, like to solve puzzles then this is a must read for you. These things makes this book one of the best book to buy to learn java.

Refactoring: Improving the Design of Existing Code

This is one of my favorite book recently. As you code more and more then you might need to improve design of the existing code. I have been in such need, so I come across this gem of a book. This book has dozens of tips to improve the code which you will find definitely beneficial. Each topic in this book explains problems in implementation and applying the correct solution. There is one chapter in this book called as “Bad smells in Code”, this chapter I found really interesting and I am sure you will find it too. I am sure this will change how you view the code and help you tremendously to make tired old code to a better code. So if you are experienced programmer and want to get rid of old and bad code without affecting the external behavior of the code, then get this book right now.

Java Generics and Collections

This is another my favorite book because it helped me a lot when I was struggling to understand Generics in Java and various types of collections. This book really helped me to understand collections which is really important part of day to day coding and interview too. Collection in Java is today the most hot topic asked in interviews. As this book is dedicated to Generics and Collections you will get good idea about both the things so it is one of the best book to buy to learn Java. This book is written by Maurice Naftalin and Philip Wadler and I am really thankful to them for helping me to understand Generics and Collections in better way.
This book contains explanation of each Collection interface such as List, Set, Queue and Map. Most important thing is the compare part which shows how each collection performs in different situation. So if you want to master in Java Generics and Java Collections then go and get this book and have it as part of your Java books.

Concurrency Practice in Java

If you are struggling to get your threads correct, then this is the book for you. This book explains basic concepts of thread safety and concurrency, ways to build and compose thread safe classes, performance optimization tips etc. It also includes some advance concepts such as non blocking algorithms, automic variables etc. This book really helped me to gain good understanding about the threading and how to apply in Java. It also helped me to understand best practices to improve performance of the code. This makes it a really a one of the best book to buy to learn Java. This book is for who uses threads regularly and care about performance issues. Simple and clear explanation of concurrency makes this book as one of the best Java programming book.

Java Performance

This is one of the best Java programming book if you care about performance. As you progress to the senior level as a programmer, performance tuning is added as a part of coding and thought process. This book is all about the performance monitoring, tools to monitor it, profiling etc. If you are finding hard to understand what is Java Heap , how exactly the garbage collection works, how the JVM works etc. then this book has explanation to all which will clear your concepts. Only thing is before reading this book you should have some experience in Java programming, which will help you to use this book in better way. So if you are concern about he performance then this is must read book.

Thus we have seen some of the books, I am sure you will find best book to buy to learn Java from these books.

]]>
http://tutiez.com/best-book-to-buy-to-learn-java.html/feed 0
10 Singleton Pattern Interview Questions and Answers in javahttp://tutiez.com/10-singleton-pattern-interview-questions-and-answers-in-java.html?utm_source=rss&utm_medium=rss&utm_campaign=10-singleton-pattern-interview-questions-and-answers-in-java http://tutiez.com/10-singleton-pattern-interview-questions-and-answers-in-java.html#comments Sat, 25 May 2013 14:03:04 +0000 http://tutiez.com/?p=1266 Singleton pattern is one of the most widely asked pattern in interviews. So lets see some of the interview questions on Singleton Design Pattern in java.

10 Singleton Pattern in java Interview Questions and Answers

1. What is singleton class or singleton design pattern? Have you used any of these?

This might be the first question you will face while dealing with singleton or singleton design pattern.
A singleton is a class of which there can be only one instance in your application. You can get the instance using getInstance method and this instance can be shared throughout your application.
If you have really used singleton then tell you have used and explain how you have used it. If you have not used it, you can give examples of SingleTon used in JDK such as in java.lang.Runtime getRuntime() method and in java.awt.Desktop getDesktop() method.
To know more about Singleton design pattern click here.

2. Write a code for getInstance() method used in Singleton

This is a very tricky question, it is actually a door to more deeper questions about to come on Singleton. So unless you know about Double Locking mechanism, don’t write code using double locking mechanism, instead write simple mechanism of creating the getInstance() as shown below

 
class SingletonTest 
 {  
// 1. Make all constructors private - This is the main thing to remember :)   
private SingletonTest() {} 
 // 2. Second step is to declare a private and static variable which will hold our single instance of a class 
 private static Singleton instance = null;  
// 3. Now we will write public static getInstace() method 
 public static Singleton getInstance() {  
// 4. Simple initialization - lazy initialization 
       if(instance == null) {  
            instance = new Singleton(); 
       }  
return instance;  
}  
}  

3. Could you give some of the examples which follows Singleton Pattern in Standard Java Development Kit ?

This is also one of the important Singleton Pattern Interview Questions asked, there are many classes in standard Java Development Kit which follows Singleton Pattern such as java.lang.Runtime classs where we have the getRuntime() method, Java.awt.Desktop which has the getDesktop() method etc.

4.How we can create a thread safe Singleton in java? or in other words explain singleton and mulithreading.

This is a very important Singleton Pattern Interview Question because of two reasons, one is it shows what you know about the initialization ways in Singleton Pattern and as well as multithreading knowledge. The detail answer can be found at Singleton and multithreading in Java post.

singleton pattern interview questions and answers

5.Explain double checked locking in Singleton Pattern

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. And the most important thing is we declare uniqueInstance variable as volatile keyword. More information and example for double checked locking can be found at Singleton and multithreading in Java post.

6. How to prevent creating another instance of Singleton using Clone() method?

Singleton is all about the single instance, why there is need to create clone of it so simple and preferred way is not to implement the Cloneable interface. If somebody WANTS to implement Cloneable interface then to prevent the another instance to be created from singleton instance we can throw exception from inside the clone() method.

7. How to prevent creating another instance of Singleton using reflection?

We all know reflection can access private fields and methods so there is a chance that getting another instance created, to prevent it in the constructor we can throw the Exception.

 
private SingletonTest() { 
if( Singleton.singleton != null )  
{  
       throw new InstantiationError( "Second instance is not allowed." );  
}  
} 

8.How to prevent creating another instance of Singleton using serialization?

This is also one of the important singleton interview questions because it also shows your knowledge of serialization and deserialization. During serialization we know that readObject always creates new instance but if we use readResolve method then it doesn’t create new instance.

  
//readResolve method to prevent another instance of Singleton 
    private Object readResolve(){ 
        return INSTANCE; 
    } 
 

Best way to avoid multiple instances of singleton in serialization is to use Enum Singleton.

9. Where we use Singleton Design pattern?

In case of simple logger system we can use Logger class as singleton.
In cache mechanism, we can use the cache as a singleton object because it have a global point of reference. Also often factories are also implemented as Singleton. In simple UI application we can have main frame as singleton as well.

10 . Why can’t use static class as Singleton?

This question might be asked as what is the difference between Singleton and static class or what are the advantages of singleton over the static class etc.
Singletons can implement interfaces or extend classes but static class cannot. Also static class has all the members as static but Singleton this is not the case.

Thus we have seen 10 Singleton Pattern Interview Questions and answers.If you like to add more questions, they are most welcomed by comments :)

]]>
http://tutiez.com/10-singleton-pattern-interview-questions-and-answers-in-java.html/feed 0
How to find or check palindrome String in javahttp://tutiez.com/how-to-find-or-check-palindrome-string-in-java.html?utm_source=rss&utm_medium=rss&utm_campaign=how-to-find-or-check-palindrome-string-in-java http://tutiez.com/how-to-find-or-check-palindrome-string-in-java.html#comments Thu, 23 May 2013 16:58:26 +0000 http://tutiez.com/?p=1262 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.

Java Example for checking String is palindrome String

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’t matter because it doesn’t need to compare.
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.

 
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());
    }
}

Output :

testWord : aibohphobia is a palindrome string
testWord : aibohphobia is a palindrome string

testWord : test is not a palindrome string
testWord : test is not a palindrome string

]]>
http://tutiez.com/how-to-find-or-check-palindrome-string-in-java.html/feed 0
How to find LCM of two numbers – Java Examplehttp://tutiez.com/how-to-find-lcm-of-two-numbers-java-example.html?utm_source=rss&utm_medium=rss&utm_campaign=how-to-find-lcm-of-two-numbers-java-example http://tutiez.com/how-to-find-lcm-of-two-numbers-java-example.html#comments Wed, 22 May 2013 18:08:28 +0000 http://tutiez.com/?p=1255 How to find LCM of two numbers – 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 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.

Java example to find LCM of two numbers

Following example shows how to find the LCM of the two numbers. Now lets see how we are finding LCM step by step.

1. We are taking two inputs from users and deciding min and max among those.
2. After deciding min and max of these two numbers, we will be iterating till the min number.
3. Then we are multiplying index to the max number. Then checking this value is fully divided by the min value.
4. If it is divisible then we get the LCM value for it. We can stop our iteration at this point.

Simple java program to find LCM of two numbers

 
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()); 
    } 
    } 
}

Thus we have seen how to find LCM from two numbers in java.

]]>
http://tutiez.com/how-to-find-lcm-of-two-numbers-java-example.html/feed 0
How to remove duplicate elements from ArrayList in Javahttp://tutiez.com/how-to-remove-duplicate-elements-from-arraylist-in-java.html?utm_source=rss&utm_medium=rss&utm_campaign=how-to-remove-duplicate-elements-from-arraylist-in-java http://tutiez.com/how-to-remove-duplicate-elements-from-arraylist-in-java.html#comments Tue, 21 May 2013 14:43:53 +0000 http://tutiez.com/?p=1252 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 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

Java program to delete duplicates from ArrayList using HashSet

 
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 
    } 
 } 

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.
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

Java program to delete duplicates from ArrayList using LinkedHashSet

 
LinkedHashSet linkedHashSet = new LinkedHashSet( arList );  
List arListWithoutDuplicates = new ArrayList( linkedHashSet ); 

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.

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.

]]>
http://tutiez.com/how-to-remove-duplicate-elements-from-arraylist-in-java.html/feed 0
How to check number is kaprekar number java examplehttp://tutiez.com/how-to-check-number-is-kaprekar-number-java-example.html?utm_source=rss&utm_medium=rss&utm_campaign=how-to-check-number-is-kaprekar-number-java-example http://tutiez.com/how-to-check-number-is-kaprekar-number-java-example.html#comments Mon, 20 May 2013 14:40:42 +0000 http://tutiez.com/?p=1250 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.
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.
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

Java example to test Kaprekar Number

In following example, we are accepting the user entered number and testing that number whether it is Kaprekar number or not.
1. First we are taking square of it.
2. Then we are converting it from int to String.
3 Find the length of the String
4. Take mid point of the String and split it in two parts.
5 Converting the parts to int again.
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.

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"); 
    } 
} 
]]>
http://tutiez.com/how-to-check-number-is-kaprekar-number-java-example.html/feed 0
How to reverse string in java without using reverse methodhttp://tutiez.com/how-to-reverse-string-in-java-without-using-reverse-method.html?utm_source=rss&utm_medium=rss&utm_campaign=how-to-reverse-string-in-java-without-using-reverse-method http://tutiez.com/how-to-reverse-string-in-java-without-using-reverse-method.html#comments Fri, 17 May 2013 14:59:17 +0000 http://tutiez.com/?p=1247 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 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.

Reverse string in java using iterative method

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

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();

}

Reverse string in java using recursive method

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.

public static String reverseStringRecursively(String strRev) {

if (strRev.length() < 2) {

return strRev;

}

return reverseStringRecursively(strRev.substring(1)) + strRev.charAt(0);

}

Thus we have seen two methods to reverse the String without using StringBuffer reverse method.

Hope you find this article helpful.

]]>
http://tutiez.com/how-to-reverse-string-in-java-without-using-reverse-method.html/feed 1
How to swap two numbers without using third variable in javahttp://tutiez.com/how-to-swap-two-numbers-without-using-third-variable-in-java.html?utm_source=rss&utm_medium=rss&utm_campaign=how-to-swap-two-numbers-without-using-third-variable-in-java http://tutiez.com/how-to-swap-two-numbers-without-using-third-variable-in-java.html#comments Thu, 16 May 2013 16:32:43 +0000 http://tutiez.com/?p=1243 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 interview question for freshers. This is very important question for ICSE students as well.

We will see three methods to swap two numbers without using third temp variable.

1. Swap two numbers using addition and subtraction

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.

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 );

}

}

Output :
Before Swapping numberOne = 36 numberTwo 63
After Swapping numberOne = 63 numberTwo 36

1. Swap two numbers using multiplication and division technique

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.

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 );

}

}

Output :
Before Swapping numberOne = 3 numberTwo 6
After Swapping numberOne = 6 numberTwo 3

1. Swap two numbers using XOR operation

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

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 );

}

}

Output :
Before Swapping numberOne = 3 numberTwo 6
After Swapping numberOne = 6 numberTwo 3

Thus we have seen three ways to swap two numbers in java without using third or temp variable.

]]>
http://tutiez.com/how-to-swap-two-numbers-without-using-third-variable-in-java.html/feed 0
Singleton and multithreading in javahttp://tutiez.com/singleton-and-multithreading-in-java.html?utm_source=rss&utm_medium=rss&utm_campaign=singleton-and-multithreading-in-java http://tutiez.com/singleton-and-multithreading-in-java.html#comments Wed, 15 May 2013 17:38:09 +0000 http://tutiez.com/?p=1238 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 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.

Now lets see how we can improve this situation in case of multithreading as we often need Singleton in presence of multiple threads.

First thing we can do is we can create eagerly created instance than the lazy instance as shown below :

public class SingletonTest{
       private static SingletonTest uniqueInstance = new SingletonTest();
       private SingletonTest(){
       }
       public static SingletonTest getInstance(){
            return uniqueInstance;
       }  
}

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.

Double checked locking by using volatile keyword

singleton and multithreading in java

Second thing we can do is to use double checked locking. Lets see what is the double checked locking approach is we first check whether instance is created or not if it is not created then synchronize otherwise not. We achieve this double checked locking by using volatile keyword as shown in example below :

Double checked locking example

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;
       }  
}

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.

]]>
http://tutiez.com/singleton-and-multithreading-in-java.html/feed 0