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

Saturday 31 August 2013

Top Most How to Convert Double to String to Double in Java Program with Example

Many scenarios come in day to day Java programming when we need to convert a Double value to String or vice versa. In my earlier article we have seen how to convert String to Integer and in this article we will first see how to convert double to String and later opposite of  that from String to double. One important thing to note is Autoboxing which automatically converts primitive type to Object type and only available from Java 5 onwards. These conversion example assumes code is running above Java 5 version and actually tested in JDK 1.6, which makes it enable to pass Double object when method is expecting double primitive value e.g. String.valueOf(double d) which expect a double value.
Read more »

Top Most How to create read only List, Map and Set in Java – unmodifiable example

Read only List, Map and Set in Java
Read only List means a List where you can not perform modification operations like add, remove or set. You can only read from the List by using get method or by using Iterator of List, This kind of List is good for certain requirement where parameters are final and can not be changed. In Java you can use Collections.unModifiableList() method  to create read only List , Collections.unmodifiableSet() for creating read-only Set like read only HashSet and similarly creating a read only Map in Java, as shown in below example. Any modification in read only List will result in java.lang.UnSupportedOperationException in Java.  This read-only List example is based on Java 5 generics but also applicable  to other Java version like JDK 1.4 or JDK 1.3, just remove Generics code i.e. angle bracket which is not supported prior to Java 5. One common mistake programmer makes is that assuming fixed size List and read only List as same. As shown in our 3 example of converting Array to ArrayList , we can use Arrays.asList() method to create and initialized List at same line.List implementation returned by this method is fixed size and it doesn’t allow adding or removal of element but it is not read only because you can update objects by calling set(index) method. How to make a collection read only is also a popular Java collection interview question, which makes this Java collection tutorial even more important.
Read more »

Top Most Best Practices while dealing with Password in Java

While working in core Java application or enterprise web application there is always a need of working with passwords in order to authenticate user. Passwords are very sensitive information like Social Security Number(SSN) and if you are working with real human data like in online banking portal or online health portal its important to follow best practices to deal with passwords or Social security numbers. here I will list down some of the points I learned and take care while doing authentication and authorization or working with password. I recommend to read more on this topic and have a checklist of things based on your application requirement. Anyway here are few points which make sense to me:
Read more »

Top Most Difference between Wait and Sleep , Yield in Java

Difference between wait and sleep or difference between Sleep and yield in Java are popular core Java interview questions and asked on multi-threading interviews. Out of three Sleep () and Yield () methods are defined in thread class while wait() is defined in Object class, which is another interview question. In this Java tutorial we will learn what is sleep in Java, important points of sleep in java and difference between Wait and sleep in Java.
Read more »

Top Most Private in Java: Why should you always keep fields and methods private?

Making members private in Java is one of best coding practice. Private members (both fields and methods) are only accessible inside the class they are declared or inside inner classes. private keyword is one of four access modifier  provided by Java and its a most restrictive among all four e.g. public, default(package), protected and private. Though there is no access modifier called package, rather its a default access level provided by Java. In this Java tutorial we will see why should we always make members of class by default as private and answer to one of popular Java interview question can override private methods in Java.

This article is in continuation of my earlier post on Java e.g. 10 Object Oriented Design principles Java programmer should know and 10 best practice to follow while writing comments. If you haven’t read them already you may find them interesting and worth reading.
Read more »

Friday 30 August 2013

Top Most Step By Step guide to Read XML file in Java Using SAX Parser Example

Reading XML file in java using SAX Parser is little different than reading xml file in Java with DOM parser which we had discussed in last article of this series. This tutorial is can be useful for those who are new to the java world and got the requirement for read an xml file in java in their project or assignment, key feature of java is it provides built in class and object to handle everything which makes our task very easy. Basically this process of handling XML file is known as parsing means break down the whole string into small pieces using the special tokens.
Parsing can be done using two ways:
Read more »

Top Most java.lang.UnsupportedClassVersionError: Bad version number in .class files Cause and Solution

How to fix Bad version number in .class file

"java.lang.UnsupportedClassVersionError: Bad version number in .class file" is common error in Java programming language which comes when you try to run a Java class file. In our last article we discussed that how to resolve Java.lang.UnSupportedClassVersionError and found that it comes when major and minor version of class is not supported by Java virtual machine or JRE running the program. Though "java.lang.UnsupportedClassVersionError: Bad version number in .class file" is little different than that in its manifestation and Cause. UnsupportedClassVersionError is not as difficult as Java.lang.OutOfMemoryError  and neither its solution is too complex but what is hard is thinking in right direction because cause of different types of UnsupportedClassVersionError is different.
Read more »

Top Most Difference between DOM and SAX Parsers in Java

Difference between SAX and DOM Parser is very popular Java interview and often asked when interviewed on Java and XML. Both DOM and SAX parser are extensively used to read and parse XML file in java and have there own set of advantage and disadvantage which we will cover in this article. Though there is another way of reading xml file using xpath in Java which is more selective approach like SQL statements people tend to stick with XML parsers. DOM Parser vs SAX parsers are also often viewed in terms of speed, memory consumption and there ability to process large xml files.
Read more »

Top Most How to read and write Images in java using ImageIO Utility

Writing an Image file in Java is very common scenario and in this article we will see a new way to write images into file in Java. javax.imageio.ImageIO is a utility class which provides lots of utility method related to images processing in Java. Most common of them is reading form image file and writing images to file in java. You can write any of .jpg, .png, .bmp or .gif images to file in Java. Just like writing, reading is also seamless with ImageIO and you can read BufferedImage directly from URL. Reading Images are little different than reading text or binary file in Java as they they are associated with different format. Though you can still use getClass().getResourceAsStream() approach for loading images.
Read more »

Top Most Difference between EnumMap and HashMap in Java

HashMap vs EnumMap in Java
What is difference between EnumMap and HashMap in Java is the latest Java collection interview question which has been asked to couple of my friends. This is one of the tricky Java question, specially if you are not very much familiar with EnumMap in Java, which is not uncommon, given you can use it with only Enum keys. Main difference between EnumMap and HashMap is that EnumMap is a specialized Map implementation exclusively for Enum as key. Using Enum as key, allows to do some implementation level optimization for high performance which is generally not possible with other object's as key. We have seen lot of interview questions on HashMap in our article How HashMap works in Java but what we missed there is this question which is recently asked to some of my friend. Unlike HashMap, EnumMap is not applicable for every case but its best suited when you have Enum as key. We have already covered basics of EnumMap and some EnumMap example in my last article What is EnumMap in Java and In this post we will focus on key differences between HashMap and EnumMap in Java.
Read more »

Top Most ThreadLocal in Java - Example Program and Tutorial

ThreadLocal in Java is another way to achieve thread-safety apart from writing immutable classes. If you have been writing multi-threaded or concurrent code in Java then you must be familiar with cost of synchronization or locking which can greatly affect Scalability of application, but there is no choice other than synchronize if you are sharing objects between multiple threads. ThreadLocal in Java is a different way to achieve thread-safety, it doesn't address synchronization requirement, instead it eliminates sharing by providing explicitly copy of Object to each thread. Since Object is no more shared there is no requirement of Synchronization which can improve scalability and performance of application. In this Java ThreadLocal tutorial we will see important points about ThreadLocal in Java, when to use ThreadLocal in Java and a simple Example of ThreadLocal in Java program.
Read more »

Top Most How to Find Runtime of a Process in UNIX and Linux

So you checked your process is running in Linux operating system and it's running find, by using ps command. But now you want to know, from how long process is running, What is start date of that process etc. Unfortunately ps command in Linux or any UNIX based operating system doesn't provide that information. But as said, UNIX has commands for everything, there is a nice UNIX tip, which you can use to check from how long a process is running. It’s been a long time, I have posted any UNIX or Linux command tutorial, after sharing some UNIX productivity tips . So I thought to share this nice little tip about finding runtime of a process in UNIX based systems e.g. Linux and Solaris. In this UNIX command tutorial, we will see step by step guide to find, since when a particular process is running in a server.
Read more »

Top Most How to Convert Map to List in Java Example

Map and List are two common data-structures available in Java and in this article we will see how can we convert Map values or Map keys into List in Java. Primary difference between Map (HashMap, ConcurrentHashMap or TreeMap) and List is that Map holds two object key and value while List just holds one object which itself is a value. Key in hashmap is just an addon to find values, so you can just pick the values from Map and create a List out of it. Map in Java allows duplicate value which is fine with List which also allows duplicates but Map doesn't allow duplicate key.
Read more »

Top Most How to compare Arrays in Java – Equals vs deepEquals Example

java.util.Arrays class provides equals() and deepEquals() method to compare two Arrays in Java. Both of these are overloaded method to compare primitive arrays e.g. int, long, float, double and Object arrays e.g. Arrays.equals(Object[] , Object[]). Arrays.equals() returns true if both Arrays which it is comparing are null, If both array pointing to same Array Object or they must be of same length and contains same element in each index. In all other cases it returns false. Arrays.equals() calls equals() method of each Object while comparing Object arrays. One of the tricky question in Java related to Array comparison is Difference between Arrays.equals() and Arrays.deepEquals() method.  Since both equals and deepEquals is used for array comparison, what is difference between them becomes important. Short answer of this questions is that, Array's equals() method does not perform deep comparison and fails logical comparison in case of nested Array,  on other hand deepEquals() perform deep comparison and returns logical comparison in case of nested array.
Read more »

Top Most How to reverse String in Java using Iteration and Recursion

How to reverse string in java is popular core java interview question and asked on all levels from junior to senior java programming job. since Java has rich API most java programmer answer this question by using StringBuffer reverse() method which easily reverses an String in Java and its right way if you are programming in Java but most interview doesn't stop there and they ask interviewee to reverse String in Java without using StringBuffer or they will ask you to write an iterative reverse function which reverses string in Java. In this tutorial we will see how to reverse string in both iterative and recursive fashion. This example will help you to prepare better for using recursion in java which is often a weak area of Java programmer and exposed during a programming interview.
Read more »

Top Most How to Stop Thread in Java Code Example

Thread is one of important Class in Java and multi-threading is most widely used feature,but there is no clear way to stop Thread in Java. Earlier there was a stop method exists in Thread Class but Java deprecated that method citing some safety reason. By default a Thread stops when execution of run() method finish either normally or due to any Exception.In this article we will How to Stop Thread in Java by using a boolean State variable or flag. Using flag to stop Thread is very popular way  of stopping thread and its also safe, because it doesn't do anything special rather than helping run() method to finish it self.
Read more »

Top Most How to use string in switch case in Jdk 7 with example

Have you ever feel that String should be used in switch cases as like int and char? JDK 7 has made an important enhancement in there support of String, now you can use String in switch and case statement, No doubt String is most widely used type in Java and in my opinion they should have made this enhancement long back when they provided support for enum in java and allowed enum to be used in switch statement. In this java tutorial we will see how we can use String inside switch and case statement in JDK 7. This article is in continuation of my earlier post on JDK7 feature improved exception handling using multi cache block in Java

string and switch in jdk7 example tutorial many a times we want to switch based upon string output received from user or other part of program but before JDK7 we can't do it directly instead either we need to map those String to final integer constant or char constant to use them inside switch and case or you need to fallback on if-else statement which gets clumsy once number of cases getting increased. But now with jdk7 you can directly use String inside switch and case statement. Though it’s pretty straight forward feature let see an example of how to use String inside switch and case statement in JDK7.

Example of String in Switch in JDK7


public static void tradingOptionChooser(String trading) {
 switch (trading) {
  case "Stock Trading":
       System.out.println("Trader has selected Stock Trading option");
       break;
  case "Electronic Trading":
       System.out.println("Trader has selected Electronic Trading option");
       break;
  case "Algorithmic Trading":
       System.out.println("Trader has selected Algorithmic Trading option");
       break;
  case "Foreign exchange trading":
       System.out.println("Trader has selected Foreign exchange Trading option");
       break;
  case "commodity trading":
       System.out.println("Trader has selected commodity trading option");
       break;
 default:
       throw new IllegalArgumentException();
 }
}

Example of String in Switch prior JDK7

Now let's see how it can be done prior to JDK 7 using if-else statement:
public static void tradingOptions(String trading) {

if (trading.equals("Stock Trading")) {
System.out.println("Trader has selected Stock Trading option");

} else if (trading.equals("Electronic Trading")) {
System.out.println("Trader has selected Electronic Trading option");

} else if (trading.equals("Algorithmic Trading")) {
System.out.println("Trader has selected Algorithmic Trading option");

} else if (trading.equals("Foreign exchange trading")) {
System.out.println("Trader has selected Foreign exchange Trading option");

} else if (trading.equals("commodity trading")) {
System.out.println("Trader has selected commodity trading option");

} else {
throw new IllegalArgumentException();
}
}

Overall allowing String into switch and case statement is not a wow feature but in my opinion very useful one and definitely makes coding easier and make code more readable by either removing clumsy if-else statement. So I definitely vote plus one to JDK 7 String in switch feature and thanks to guys involved in project coin for making life easier of java developers.

You also need to ensure that your JRE must have source 1.7 otherwise if you try to run string in switch in JRE less than 7 you will get following errro

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - strings in switch are not supported in -source 1.6
  (use -source 7 or higher to enable strings in switch)
        at jdk7demo.JDK7Demo.tradingOptionChooser(JDK7Demo.java:34)
        at jdk7demo.JDK7Demo.main(JDK7Demo.java:25)


That’s all from me on String and Switch on JDK7, Please share how you are using this new feature of java 7.

Here are some of my other post on Java you may find interesting:

Thursday 29 August 2013

Top Most Builder Design pattern in Java - Example Tutorial

Builder design pattern in Java is a creational pattern i.e. used to create objects, similar to factory method design pattern which is also creational design pattern. Before learning any design pattern I suggest find out the problem a particular design pattern solves. Its been well said necessity is mother on invention. learning design pattern without facing problem is not that effective, Instead if you have already faced issues than its much easier to understand design pattern and learn how its solve the issue. In this Java design pattern tutorial we will first see what problem Builder design pattern solves which will give some insight on when to use builder design pattern in Java, which is also a popular design pattern interview question and then we will see example of Builder design pattern and pros and cons of using Builder pattern in Java. 
Read more »

Top Most How to append text into File in Java – FileWriter Example

Some times we need to append text into File in Java instead of creating new File. Thankfully Java File API is very rich and it provides several ways to append text into File in Java. Previously we have seen how to create file and directory in Java and how to read and write to text file in Java and in this Java IO tutorial we will see how to append text into file in Java. We are going to use standard FileWriter and  BufferedWriter approach to append text to File. One of the key point to remember while using FileWriter in Java is to initialize FileWriter to append text i.e. writing bytes at the end of File rather than writing on beginning of the File. In next section we will see complete Java program to append text into File in Java.  By the way you can also use FileOutputStream instead of FileWriter if you would like to write bytes, instead of text. Similar to FileWriter, FileOutputStream constructoralso takes a boolean append argument to open connection to append bytes into File in Java.
Read more »

Top Most How to traverse or loop HashMap in Java Example

There are multiple way to iterate, traverse or loop through Map, HashMap or TreeMap in Java and we all familiar of either all of those or some of those. But to my surprise one of my friends was asked in his interview (he has more than 6 years of experience in java programming) to write code for getting values from hashmap or TreeMap in Java with at least 4 ways. Just like me he also surprised on this question but written it. I don't know why exactly some one ask this kind of java interview question to a relatively senior java programmer. Though my closest guess is to verify that whether he is still hands on with coding in java. Anyway that gives me idea to write this Java tutorial and here is multiple ways to traverse, iterate or loop on a Map in Java, so remember this because you may also ask this question J.
Read more »

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt