Tampilkan postingan dengan label java. Tampilkan semua postingan
Tampilkan postingan dengan label java. Tampilkan semua postingan

Best Practices to write JUnit test cases in Java

Sabtu, 15 Maret 2014

JUnit best practices in Java
No doubt writing good JUnit test cases is a rare skill just like writing good Code. A good, well thought and well written JUnit test can prevent several production issues during initial development or later maintenance in Java application. Though one can only be perfect in writing JUnit test by practice and a level of business knowledge which is important to envision different scenarios on which a method gets called, some best practices or experience of other developer may help to guide other programmers. In this Java article I am sharing some JUnit tips and Junit best practices which I have learned and follow while writing unit tests using JUnit for Java programs. One of the book which helped me a lot is Pragmatic Unit Testing in Java with JUnit by Andrew Hunt and Dave Thomas,  This book shares lot of JUnit best practices which is worth reading and learning if you are serious about Unit testing using JUnit. Never undermine importance of automated testing and test cases written by Developer who writes the code and that's the reason many company are asking programmer to design, code and provide unit tests during there Java interviews. These JUnit best practices not just apply to JUnit but to any other testing framework as well like TestNG, they are more on testing and writing test cases which is more important skill than tool like JUnit or TestNG.
Read more »
Read More..

Why use PreparedStatement in Java JDBC – Example Tutorial

Rabu, 05 Maret 2014

PreparedStatement in Java is one of several ways to execute SQL queries using JDBC API. Java provides Statement,
PreparedStatement and CallableStatement for executing queries. Out of these three, Statement is used for general purpose queries, PreparedStatement is used for executing parametric query and CallableStatement is used for executing Stored Procedures. PreparedStatement is also a popular topic in java interviews. Questions like Difference between Statement and PreparedStatement in Java and How to prevent SQL Injection attacks in Java are popular java interview questions. In this Java JDBC tutorial we will see why should you use use PreparedStatement in Java, What are the major advantages of using PreparedStatement in Java and how PreparedStatement prevents SQL Injection attacks in Java.

This article is in continuation of my earlier post on database and java like 4 tips to improve performance of Java application with database and Difference between truncate and delete in SQL.If you haven’t read  them already you may found  those tutorial useful and interesting.
Read more »
Read More..

Convert String to integer int in Java

Senin, 03 Maret 2014

Java Code Online will discuss the Java Code to convert a String to an int. There is a feature provided in Java, which helps to perform this operation. The conversion is done with the help of a method called parseInt().

Actually any String which could be converted to a primitive can be converted to it, by using the parseXxx() method, where Xxx will replace the type in which it is to be converted, like int, float, etc.

I have provided a sample Java Code which asks the user to enter a number, which is taken as a String by the application. Later it is converted to an integer by using the parseInt() method. Go through the code for a clear understanding on how it is to be used.

  package developer;

  import java.util.Scanner;

  public class StringToInt {

  public static void main(String[] args) {

        System.out.println("Enter a number which would be taken as a String by the application");
        Scanner scanStr = new Scanner(System.in);
        String numStore = null;
        int numConvert = 0;

        // Takes the input as a String
        if (scanStr.hasNext()) {
            numStore = scanStr.next();
        }

        // Convert the String to int by using the Integer.parseInt() method
        numConvert = Integer.parseInt(numStore);

        System.out.println("The number entered by you is: " + numConvert);

     }
  }

The output is something like as shown below.


  Enter a number which would be taken as a String by the application
  22
  The number entered by you is: 22


Some observation points are:-
The String which is to be converted to a number must be a number in the String format. This is required so that the Java parser can parse the String successfully into an int.

If the value entered is not a number, suppose that you entered a String in words in place of a number in String format, then the output is shown below:-

 Enter a number which would be taken as a String by the application
 Conversion from String to int
 Exception in thread "main" java.lang.NumberFormatException: For input string: "Conversion"
     at java.lang.NumberFormatException.forInputString(Unknown Source)
     at java.lang.Integer.parseInt(Unknown Source)
     at java.lang.Integer.parseInt(Unknown Source)
     at developer.StringToInt .main(StringToInt .java:20)

So we see that if a String is entered to be parsed as an int, then the Java Compiler gives a big fat "NumberFormatException".

I hope the Java Code provide to convert an a String to an int was helpful. Do leave a comment if you liked the article. Java Code Online will soon be back with another interesting Java article.

Related Java Codes:-
Convert int to String in Java
Convert int to String in Java using Wrapper Classes
Read More..

How to Configure HTTPS SSL in Tomcat 6 and 7 Java Web Server

Jumat, 28 Februari 2014

Setting SSL (Secure Socket Layer) in Tomcat is often a requirement, especially while developing  secure web application, which requires access over https protocol. Since Tomcat web server doesn't provide SSL settings by default, you need to know how to configure SSL in tomcat, and even worse it varies between different tomcat versions. for Example SSL setup which works on tomcat 6, doesn't work as it is in tomcat 7. In this article we will see, how to configure tomcat for https in both tomcat 6 and 7. For those programmers who are not very familiar with SSL and https here is a quick overview of SSL, certificates and https, and I suggest reading that article to get better understanding of How SSL works and How websites are accessed security over internet.
Read more »
Read More..

Oracle 10g Pagination Query SQL Example for Java Programmer

Kamis, 27 Februari 2014

Many time we need SQL query which return data page by page i.e. 30 or 40 records at a time, which can be specified as page size. In fact Database pagination is common requirement of Java web developers, especially dealing with largest data sets.  In this article we will see how to query Oracle 10g database for pagination or how to retrieve data using paging from Oracle. Many Java programmer also use display tag for paging in JSP which supports both internal and external paging. In case of internal paging all data is loaded in to memory in one shot and display tag handles pagination based upon page size but it only suitable for small data where you can afford those many objects in memory. If you have hundreds of row to display than its best to use external pagination by asking databaseto do pagination. In pagination, ordering is another important aspect which can not be missed. It’s virtually impossible to sort large collection in Java using Comparator or Comparablebecause of limited memory available to Java program, sorting data in database using ORDER BY clause itself is good solution while doing paging in web application.
Read more »
Read More..

Inter Thread Communication in Java using Wait Notify Example

Selasa, 25 Februari 2014

Wait and notify methods in Java are used for inter-thread communication i.e. if one thread wants to tell something to another thread, it uses notify() and notifyAll() method of java.lang.Object. Classical example of wait and notify method is Producer Consumer design pattern, where One thread produce and put something on shared bucket, and then tell other thread that there is an item for your interest in shared object, consumer thread than pick than item and do his job, without wait() and notify(), consumer thread needs to be busy checking, even if there is no change in state of shared object. This brings an interesting point on using wait and notify mechanism, a call to notify() happens, when thread changed state of shared object i.e. in this case producer change bucket from empty to not empty, and consumer change state from non empty to empty. Also wait and notify method must be called from synchronized context, wondering why, read this link for some reasons which makes sense. Another important thing to keep in mind while calling them is, using loop to check conditions instead of if block. This is really tricky for beginners, which often don't understand difference and wonders why wait and notify get called form loops. Joshua Bloch has a very informative item on his book Effective Java, I strongly suggest reading that. In short, a waiting thread may woke up, without any change in it's waiting condition due to spurious wake up. For example, if a consumer thread, which is waiting because shared queue is empty, gets wake up due to a false alarm and try to get something from queue without further checking whether queue is empty or not than unexpected result is possible. Here is standard idiom for calling wait, notify and notifyAll methods in Java :

How to call wait method in Java :
Read more »
Read More..

Difference between ArrayList and Vector in Java

Senin, 24 Februari 2014

ArrayList and Vector are two of most used class on java collection package and difference between Vector and ArrayList is one of the most frequently asked java interview question on first round or phone interview. Though it’s quite a simple question in my opinion but knowledge of when to use Vector over ArrayList or does matter if you are working on a project. In this article we will some point based difference between Vector and ArrayList in Java and trying to understand the concept behind those differences. Ultimate goal is to familiarize yourself with distinguish property of ArrayList and Vector. By the way Java 5 adds another implementation of List interface which is similar to Vector and ArrayList but provides better concurrency access than Vector, its called CopyOnWriteArrayList. By the way this is the third article on discussing about Collection interview question,  Difference between LinkedList and ArrayList  and   List vs Set are other popular interview questions based upon collection framework in Java.

Read more »
Read More..

The pre Java Interview online written test questions that I hate

Minggu, 23 Februari 2014

Some online assessment sites basically try to test your memorizing capabilities with API based questions listed below. Also, about 30% - 50% of the questions are on API that you rarely use or obsolete. When you have the API documentation, why remember the API. Here are a few such questions I came across recently. If you want to ask such questions, then allow people to refer to the online API documentation. These tests are only going to filter out quality candidates.


Q. Which of the following are valid JavaMail message types?

a) Message.RecipientType.CC
b) MessageRecipientType.CC
c) Message.RecipientType.CCList
d) Message.RecipientType.BCC
e) MessageRecipientType.BCC

A. a and d


Q. Which of the following are JNDI event listeners?

a) NamespaceChangeListener
b) ObjectListener
c) ObjectChangeListener
d) UnsolicitedNotificationListener
e) ObjectNotFoundListenr

A. a, c, and d.


Q. Which of the following statements are correct, based on the following code snippet for uploading a file?

<form action="upload"  enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>


a) The enctype must be "text/form-data"
b) The method attribute is missing in the "form" element and it should be of type "GET"
c) The method attribute is missing in the "form" element and it should be of type "POST"
d) The "input" element must have the attribute "value"
e) The above syntax is correct

A. c. 

The correct format is:

<form action="upload"  method="post" enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>


Q. Which of the following objects are NOT part of the JavaBean Activation Framework (JAF)?

a) DataSource
b) DataFileHandler
c) DataHandler
d) DataContentHandler
e) FileDateHandler
f) FileTypeMap

A. b and e. All the others are part of JAF.


Q. Which of the following statements are INCORRECT?

a) HttpServletRequest.getRemoteUser( ) return null;
b) HttpServletRequest.isUserInRole(java.lang.String role) throws SecurityException ;
c) HttpServletRequest.getRemoteUser( ) return false;
d) HttpServletRequest.isUserInRole(java.lang.String role) return false;
e) HttpServletRequest.getUserPrincipal( ) throws SecurityException
f) HttpServletRequest.getUserPrincipal( ) return null;


A. b, c, and e are INCORRECT.

Q. Which of the following elements would you see in a SOAP payload with attachments?

a) <soap:header>
b) <soap:footer>
c) <soap:body>
d) <soap:content>
e) <soap:attachment>

A. a and c.


Q. Which of the following can be used in place of "****" in the code snippet shown below?


if(request.getParameter("location").equals("nextPage") {

      *****

}


a) request.sendRedirect("url");
b) response.sendRedirect("url");
c) request.redirect("url");
d) response.redirect("url");
e) response.send("url")


A.b

Q. Which of the following are valid JDBC  result set types?


a) TYPE_FORWARD_ONLY
b) TYPE_BACKWARD_ONLY
c) TYPE_SCROLL_INSENSITIVE
d) TYPE_SCROLL_SENSITIVE
e) TYPE_SCROLL_REVERSE

A. a, c, and d.


Q. Which of the following are valid JSP life cycle methods?

a) jspService( )
b)_jspService( )
c) jspInit( )
d) jspDestroy( )
e) _jspInit()

A. a, c, and d.


Q. Which of the following are CORRECT about JCA?

a)  JCA is a standard architecture for integrating heterogeneous EIS systems not written in Java
b)  JCA is a standard architecture for integrating other JEE systems
c)  JCA can be used to integrate with mainframe systems
d)  JCA can be used to integrate with ERP systems
e)  JCA can be used to integrate with Database systems
f)  The underlying EIS systems are integrated using pluggable resource adapters

A. a, c, d, e and f.

Q. Which of the following are INCORRECT about JAAS?

a) JAAS bring in location based authentication and authorization to JEE.
b) JAAS is designed to bring subject based authentication and authorization to JEE
c) JAAS is modeled after the Pluggable Authentication Module (PAM)-a popular API for defining authentication modules in a portable and extensible manner
d) JAAS can be used across managed resources such as servlet/JSP, EJB, or MBeans and over a variety of connection protocols such as HTTP, RMI/IIOP, or JMX/RMI.
e) JAAS was fully integrated into the core Java security architecture

A. a.

The last 2 questions are not bad, but for most of the other questions, the answers can be found by jumping on a search engine for 5 to 15 minutes. It is not really testing your understanding of the core concepts or hands-on experience.

Is it just me, or do you agree with me? Please post the Java Interview Questions that you hate.

Read More..

How to fix java io NotSerializableException org apache log4j Logger Error in Java

Jumat, 21 Februari 2014

java.io.NotSerializableException: org.apache.log4j.Logger error says that instance of org.apache.lo4j.Logger is not Serializable. This error comes when we use log4j for logging in Java and create Logger in a Serializable class e.g. any domain class or POJO which we want to store in HttpSession or want to serialize it. As we know from 10 Java Serialization interview question that, if you have a non serializable class as member in a Serializable class, it will throw java.io.NotSerializableException Exception.

Look at the below code :

public class Customer implements Serializable{

private Logger logger =  Logger.getLogger(Customer.class)

......

}

If instance of Customer will be stored in HttpSession or Serialized externally it will throw "java.io.NotSerializableException: org.apache.log4j.Logger" because here logger instance is neither staticor transientand it doesnt implement Serializable or Externalzable interface.

How to solve java.io.NotSerializableException: org.apache.log4j.Logger

How to fix java.io.NotSerializableException: org.apache.log4j.Logger Error in JavaSolving java.io.NotSerializableException: org.apache.log4j.Logger  is simple, you have to prevent logger instance from default serializabtion process, either make it transient or static. Making it static final is preferred option due to many reason because if you make it transient than after deserialization logger instance will be null and any logger.debug() call will result in NullPointerException in Java because neither constructornot instance initializer block is called during deserialization. By making it static and final you ensure that its thread-safeand all instance of Customer class can share same logger instance, By the way this error is also one of the reason Why Logger should be declared static and finalin Java program. Just make following code change to fix java.io.NotSerializableException: org.apache.log4j.Logger in Java.

public class Customer implements Serializable{

private static final Logger logger =  Logger.getLogger(Customer.class)

......

}

Thats all on how to fix java.io.NotSerializableException: org.apache.log4j.Logger in Java. We have seen what cause java.io.NotSerializableException: org.apache.log4j.Logger, its because Logger class is not Serializable but we also learned that there is no point serializing Logger instance and better to make Logger static and final.

Other Serialization and troubleshooting articles from Javarevisited Blog
Read More..

Why use SLF4J over Log4J for logging in Java

Rabu, 19 Februari 2014

Every Java programmers knows that logging is critical for any Java application, especially server side application, and many of them are already familiar with various logging libraries e.g. java.util.logging, Apache log4j, logback, but if you don't know about SLF4J, Simple logging facade for Java,  then it's time to learn and use SLF4J in your project. In this Java article, we will learn why using SLF4J is better than using log4j or java.util.logging. It’s been long time, since I wrote 10 logging tips for Java programmer,I don’t remember anything I have writing about logging. Anyway, let’s get back to topic, on contrary to all those logging libraries, there is a major difference between them and SLF4J. SLF4J or Simple logging Facade for Java is not really a logging implementation, instead it's an abstraction layer, which allows you to use any logging library in back-end. If you are writing API or utility library, which can be used internally or externally, then you really don't want that any client, which uses your library, should also stick with your choice of logging library. Suppose if a project is already using log4j, and you included a library say Apache Active MQ, which has dependency on logback, another logging library, then you need to include them as well, but if Apache Active MQ uses SL4J, you can continue with your logging library, without pain of adding and maintaining new logging framework. In short SLF4J make your code independent of any particular logging API, which is good think for public API developers. Though idea of abstracting logging library is not new and Apache commons logging is already using it, but now SLF4J is quickly becoming an standard for logging in Java world. Let's see couple of more reason to use SLF4J over log4j, logback or java.util.logging.
Read more »
Read More..

Difference between Singleton Pattern vs Static Class in Java

Kamis, 13 Februari 2014

Singleton pattern  vs  Static Class (a class, having all static methods) is another interesting questions, which I missed while blogging about Interview questions on Singleton pattern in Java. Since both Singleton pattern and static class provides good accessibility, and they share some similarities e.g. both can be used without creating object and both provide only one instance, at very high level it looks that they both are intended for same task. Because of high level similarities, interviewer normally ask questions like, Why you use Singleton instead of Static Methods, or Can you replace Singleton with static class, and  what are differences between Singleton pattern and static in Java. In order to answer these question, it’s important to remember fundamental difference between Singleton pattern and static class, former gives you an Object, while later just provide static methods. Since an object is always much more capable than a method, it can guide you when to use Singleton pattern vs static methods.
Read more »
Read More..

How to escape String literal in Java using Eclipse IDE

Selasa, 11 Februari 2014

Whenever you paste String in Eclipse which contains escape characters,  to store in a String variable or just as String literal it will ask to manually escape special characters like single quotes, double quotes, forward slash etc. This problem is more prominent when you are pasting large chunk of data which contains escape characters like a whole HTML or XML file,  which contains lots of single quotes e.g. ‘’ and double quotes “” along with forward slash on closing tags. It’s very hard to manually escape all those characters and its pretty annoying as well. While writing JUnit test for XML documents, parsing and processing I prefer to have whole XML file as String in Unit test, which pointed me to look for that feature in Eclipse. As I said earlier in my post Top 30 Eclipse keyboard shortcuts, I always look to find new shortcut and settings in Eclipse which help to automate repetitive task. Thankfully Eclipse has one setting which automatically escapes text as soon as you paste it. This is even more useful if you prefer to copy file path and just paste it, Since windows uses forward slash it automatically escape that instead of you going manually and escaping them. By default this setting is disabled in Eclipse IDE and you need to enable it.
Read more »
Read More..

How to configure Log4j in Java program without XML or Properties File

Senin, 10 Februari 2014

Sometime configuring Log4j using XML or properties file looks annoying, especially if your program not able to find them because of some classpath issues, wouldn't it be nice if you can configure and use Log4j without using any configuration file e.g. XML or properties. Well, Log4j people has thought about it and they provide a BasicConfigurator class to configure log4j programmatically, thought this is not as rich as there XML and properties file version is, but it's really handy for quickly incorporating Log4j in your Java program. One of the reason programmer prefer to use System.out.println() over Log4j, of-course for testing purpose, because it doesn't require any configuration, you can just use it, without bothering about XML or properties file configuration, but most programmer will agree that, they would prefer to use Log4j over println statements, even for test programs if it's easy to set them up. By the way, for production use prefer SLF4J over Log4J.  In this Java tutorial, we will see a nice little tip to use Log4j right away by configuring in couple of lines. In fact you can configure Log4J in just one line, if you intend to use there basic configuration which set's the log level as DEBUG.
Read more »
Read More..

How will you go about explaining the following Java concepts to a beginner

Minggu, 09 Februari 2014



Q. How will you go about explaining the following Java concepts to a beginner who is starting to learn Java
A.

1. Process Vs Threads
2. Heap versus Stack
3. Local variables versus instance variables
4. How do threads communicate with each other?
5. Are Java methods reentrant?
6. Does Java support recursive method calls?
7. Object creation and Garbage collection
8. Can you garbage collect objects that have a circular reference?
9. Producer-consumer design pattern.


The best way to do this is to write some basic code and then have a pictorial representation as to how the objects are created, how do threads work and communicate with each other, and what is stored in a heap and what is stored in a stack, etc.

Here is an example of a producer thread (thread-0) producing by incrementing the counter from 0, and the consumer thread (i.e. thread-1) consumes by decrementng the counter. These two user created threads are spawned by the main thread, which is created by the JVM and is alwyas there by default. The ConsumerProducer is the shared object with synchronized methods that commuincate with each other via wait( ) and notifyAll methods. Only one of the two synchronized methods can be executed at a time. The wait( ) call in consume( ) relinquishes the lock to the produce( ) method, and once the produce method has incremented the count, it notifies all threads and one of the waiting threads will resume. In this example, there is only one waiting consumer (i.e. Thread-1) thread. So, both threads will be communicating with each other via the wait( ) and notifyAll( ) calls in the shared object ConsumerProducer. This is an example of the producer-consumer design pattern.



Firstly, look at the code and then the diagram. The diagram is simplified to get an understanding and should not be construed as exactly what happens in the JVM.


public class ConsumerProducer {

private int count;

public synchronized void consume() {
while (count == 0) { // keep waiting if nothing is produced to consume
try {
wait(); // give up lock and wait
} catch (InterruptedException e) {
// keep trying
}
}

count--; // consume
System.out.println(Thread.currentThread().getName() + " after consuming " + count);
}

public synchronized void produce() {
count++; //produce
System.out.println(Thread.currentThread().getName() + " after producing " + count);
notifyAll(); // notify waiting threads to resume
}

}


The main thread spawns a consumer and a producer thread. The ConsumerProducer is shared between two threads. The boolean flag is used to signal if it is a consumer thread or a producer thread to invoke the relevant methods.


public class ConsumerProducerTest implements Runnable {

boolean isConsumer;
ConsumerProducer cp;

public ConsumerProducerTest(boolean isConsumer, ConsumerProducer cp) {
this.isConsumer = isConsumer;
this.cp = cp;
}

public static void main(String[] args) {
ConsumerProducer cp = new ConsumerProducer(); //shared by both threads to communicate

Thread producer = new Thread(new ConsumerProducerTest(false, cp));
Thread consumer = new Thread(new ConsumerProducerTest(true, cp));

producer.start();
consumer.start();

}

@Override
public void run() {
for (int i = 1; i <= 10; i++) {
if (!isConsumer) {
cp.produce();
} else {
cp.consume();
}
}

//try with introducing a sleep for 100ms.

}
}

The output will vary, but the last thing consumed will be 0
Thread-0 after producing 1
Thread-0 after producing 2
Thread-0 after producing 3
Thread-0 after producing 4
Thread-0 after producing 5
Thread-0 after producing 6
Thread-0 after producing 7
Thread-0 after producing 8
Thread-0 after producing 9
Thread-0 after producing 10
Thread-1 after consuming 9
Thread-1 after consuming 8
Thread-1 after consuming 7
Thread-1 after consuming 6
Thread-1 after consuming 5
Thread-1 after consuming 4
Thread-1 after consuming 3
Thread-1 after consuming 2
Thread-1 after consuming 1
Thread-1 after consuming 0




The above code can be diagramatically represented as shown below.




  • The JVM is a process. As you could see in the diagram above that each thread has its own stack, but share the same heap space. One heap space per process.

  • The local variables like producer, cp, and consumer are stored in the stack along with the method calls like main( ), run( ), etc.

  • The objects are created in the heap. For example, 2 instances of ConsumerProducerTest and a single instance of ConsumerProducer. Unless the methods of these instances are properly managed, multiple threads can concurrently access these intsnaces to cause thread-safety issues.

  • There are scenarios where the threads want to commuincate with each other. For example, a worker thread produces something and a consumer thread consumes what the producer thread consumed. This can be achieved through thread coordination with the wait and notify( ) / notifyAll( ) methods. In the above example, since both the produce( ) and consume( ) methods of the object ConsumerProducer are synchronized, only one thread can execute either one of the methods. If the count == 0, the consumer thread relinquishes the lock by invoking the wait( ) method and waits for it to be notified again to resume. The producer thread will increment the counter and then will notify all the waiting threads via the notifyAll( ) method. One of the waiting threads will then be able to resume from its waiting state.

  • The local variable isConsumer is used to differentiate between a consumer thread and a producer thread.

  • The count is an instance variable shared by both the consumer and producer thread in a thread-safe manner.



Here are the points that answers the above questions.

  • Each time an object is created in Java it goes into the area of memory known as heap.
  • The primitive variables like int, double, etc are allocated in the stack if they are local variables and in the heap if they are instance variables (i.e. fields of a class).
  • Java is a stack based language and local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed.
  • In a multi-threaded application, each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space.
  • The stack is thread-safe because each thread will have its own stack with say 1MB RAM allocated for each thread but the heap is not thread-safe unless guarded with synchronization through your code. The stack space can be increased with the –Xss option.
  • All Java methods are automatically re-entrant. It means that several threads can be executing the same method at once, each with its own copy of the local variables.
  • A Java method may call itself without needing any special declarations. This is known as a recursive method call. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive methods are useful in removing iterations from many sorts of algorithms. All recursive functions are re-entrant but not all re-entrant functions are recursive.
  • Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results.
  • Each time an object is created in Java, it goes into the area of memory known as heap. The Java heap is called the garbage collectable heap. The garbage collection cannot be forced. The garbage collector runs in low memory situations. When it runs, it releases the memory allocated by an unreachable object. The garbage collector runs on a low priority daemon (i.e. background thread). You can nicely ask the garbage collector to collect garbage by calling System.gc( ) but you can’t force it.
  • An object’s life has no meaning unless something has reference to it. If you can’t reach it then you can’t ask it to do anything. Then the object becomes unreachable and the garbage collector will figure it out. Java automatically collects all the unreachable objects periodically and releases the memory consumed by those unreachable objects to be used by the future reachable objects.
  • If two objects have circular reference with each other in the heap, but none of them are reachable from any thread, then those circular referenced objects can be garbage collected.
Read More..

What is Inheritance in Java and OOPS Tutorial Example

Jumat, 07 Februari 2014

Inheritance in Java is an Object oriented or  OOPS concepts, which allows to emulate real world Inheritance behavior, Inheritance allows code reuse in Object oriented programming language e.g. Java. Along with Abstraction, Polymorphismand Encapsulation, Inheritance forms basis of Object oriented programming. Inheritance is implemented using extends keyword in Java and When one Class extends another Class it inherit all non private members including fields and methods. Inheritance in Java can be best understand in terms of Parent and Child class, also known as Super class and Sub class in Java programming language. The classwhich extends another class becomes Child of the class it extends and inherit all its functionality which is not private or package-private given where Child class is created. Inheritance is the most easy way to reuse already written and tested code but not always best way to do so, which we will see in this article. There are lot of example of Inheritance in Object oriented world e.g. Child inherit properties from parent, Dog inherit properties of Animal etc. In this Java and OOPS tutorial we will learn What is Inheritance in Java, How to use Inheritance in Java, Simple Example of Java Inheritance and some important points about Inheritance in Java.
Read more »
Read More..

Java new I O Interview Questions and Answers



The Java New IO is very powerful and it is all about performance!, performance!!, and performance!!!. But, you need to get your head around how the buffers work. Here are some questions and answers that will help you do that. Q. How does the Java NIO (i.e New IO) introduced in Java version 1.4 differ from the old IO?
A. The NIO is all about better performance.

IONIO (New IO)
Stream oriented. This means that you read one or more bytes at a time, from a stream. What you do with the read bytes is up to you. They are not cached anywhere. Furthermore, you cannot move forward and back in the data in a stream. If you need to move forward and back in the data read from a stream, you will need to buffer yourself first.

Buffer oriented. This means better performance. Data is read into a buffer from which it be processed later. You can move forward and back in the buffer. This gives you a bit more flexibility during processing. However, you also need to check if the buffer contains all the data you need in order to fully process it.
Blocking IO. This means when a thread invokes a read() or write(), that thread is blocked until there is some data to read, or the data is fully written. The thread can do nothing else in the meantime.

Non blocking IO. This means better performance. NIOs non-blocking mode enables a thread to request reading data from a channel, and only get what is currently available, or do nothing at all, if no data is currently available. Rather than remain blocked until data becomes available for reading, the thread can proceed with doing something else.
You need to create additional threads to read and write data in parallel. More threads means more CPU context switching and consuming more thread stacks.Selectors.  This also means better performance. NIOs selectors allow a single thread to monitor multiple channels of input. You can register multiple channels with a selector, then use a single thread to "select" the channels that have input available for processing, or select the channels that are ready for writing. This selector mechanism makes it easy for a single thread to manage multiple channels. This is also known as multiplexing. The Apache MINA package is based on Java NIO to write high performance networking applications. For example, a TCP server.

Here is the diagrammatic overview:



Q. How do you manipulate the buffer in NIO?
A. The NIO buffer  has following 3 state variables -- position, limit, and capacity

  • position: The position value keeps track of how much you have gotten from the buffer. It specifies from which array element the next byte will come. Thus, if youve written 1 bytes as shown below with shaded area to a channel from a buffer, that buffers position will be set to 1 (starting from 0), referring to the second element of the array as shown in the diagram.
  • limit: The limit variable specifies how much room there is left to put data into -- in the case of reading from a channel into a buffer or how much data there is left to get -- in the case of writing from a buffer into a channel. The position is always less than, or equal to, the limit. The limit is 3 (counting from 0) in the diagram below.
  • capacity:  The capacity of a buffer specifies the maximum amount of data that can be stored in the underlying array. The limit can never be larger than the capacity. The capacity is 6 (counting from 0) in the diagram below.

In the above diagram, the position starts with 0, and after reading 1 byte, it becomes 1 byte, and the limit value of 3 states that there are 2 more bytes to be read. 



Q. What do you understand by terms flip( ) and clear( ) in NIO?
A.

Flip

When you are ready to write your data to an output channel. You must call the flip() method. This method does two key things:

1. It sets the limit to the current position.
2. It sets the position to 0.

You are now ready to begin writing data to a channel from the buffer starting from 0 to the limit.


Clear

After you have done your writes, the final step is to call the buffers clear() method. This method resets the buffer in preparation for receiving more bytes. Clear does two key things:

1. It sets the limit to match the capacity.
2. It sets the position to 0.


Also, the get and put methods are used to get and put data to and from the buffer respectively. some coding examples are discussed in Java I/O interview Questions and Answers.


Q. What is in the NIO.2 package introduced in Java 7?
A. The more New I/O APIs for the Java Platform (NIO.2) in Java 7 enhance the New I/O APIs (NIO) introduced in Java 1.4 by adding

  • The four asynchronous channels to the java.nio.channels package. 
  •  The java.io.File class is upgraded to the java.nio.file.Path that allows logical manipulating of paths in memory without accessing the file system.
  • The NIO.2 associates the notion of metadata like is hidden, is it a directory, size, access control, etc with attributes and provides access to them through the java.nio.file.attribute package. Since different file systems have different notions about which attributes should be tracked, NIO.2 groups the attributes into views, each of which maps to a particular file system implementation.
  • The NIO.2 provides support for both hard links and symbolic links and the Path class knows how to detect a link and will behave in the default manner if no configuration of behavior is specified.
  • The NIO.2 comes with a set of brand new methods for managing files and directories, such as create, read, write, move, delete, and so on. The most of these tasks are found in the java.nio.file.Files class.
  • The FileVisitor interface introduced in Java 7 makes recursing through directories and files a breeze.
  • The Watch Service API was introduced in Java 7 (NIO.2) as a thread-safe service that is capable of watching  a directory for changes to its content through actions such as create, delete, and modify. This means, with NIO.2, you no longer need to poll the file system for changes or use other in-house solutions to monitor the file system changes.
  • Java 7 (NIO.2) introduces a new interface for working with Random Access Files with its SeekableByteChannel and an interface named NetworkChannel that provides network channel classes for tetworking.
Read More..

How to parse String to Enum in Java Convert Enum to String with Example

Converting Enum into String and parsing String to Enum in Java is becoming a common task with growing use of Enum. Enum is very versatile in Java and preferred choice to represent bounded data and since is almost used everywhere to carry literal value its important to know how to convert Enum to String in Java. In this article we will see both first converting Strings to Enum in Java and than Changing an Enum to String in Java with Example. I thought about this Enum tutorial when I wrote 10 Examples of Enum in Java. I missed String to Enum conversion and one of reader pointed out that. So here we have now.

Enum to String to Enum in Java

This article is in continuation of other conversion related post e.g. how to convert Date to String in Java and How to Convert String to Integer in Java. As these are common needs and having best way to do things in mind saves lot of time while coding.
Read more »
Read More..

Why Default or No Argument Constructor is Important in Java Class

Kamis, 06 Februari 2014

Almost all Java developers knows that compiler adds a default constructor or better known as no argument constructor in every Java class, but many of them forget that, it only does when you don't provide any other constructor. Which means it becomes developers responsibility to add a no argument constructor, if he is adding explicit constructor. Now, Why it's important to provide default constructor in Java, What happens if your class don't have a no argument constructor? Well, this is how it's asked in many Java interviews, most commonly as part of Spring and Hibernate interviews. It's not mandatory to define default constructor, but if you are writing Hibernate persistent class, JPA entities or using Spring framework to manage object creation and wiring dependencies, you need to be bit careful. Many of open source framework, uses reflection to create instance or Object at runtime, based upon name of class. For example When Hibernate creates instance of entities using reflection it uses Class.newInstance() method, which require a no argument constructor to create an instance. It's effectively equivalent of new Entity(). This method throws InstantiationException if it doesn't found any no argument constructor in Entity class, and that's why it's advised to provide a no argument constructor.
Read more »
Read More..

Data Access Object DAO design pattern in Java Tutorial Example

Data Access Object or DAO design pattern is a popular design pattern to implement persistence layer of Java application. DAO pattern is based on abstractionand encapsulationdesign principles and shields rest of application from any change on persistence layer e.g. change of database from Oracle to MySQL, change of persistence technology e.g. from File System to Database. For example if you are authenticating user using relational database and later your company wants to use LDAP to perform authentication. If you are using DAO design pattern to access database, it would be relatively safe as you only need to make change on Data Access Layer. DAO design pattern also keeps coupling low between different parts of application. By using DAO design pattern your View Layer is completely independent to DAO layer and only Service layer has dependency on it which is also abstracted by using DAO interface. You can further use Genericsto template your DAO layer. If you are using Spring than you can leverage JdbcTemplate for performing JDBC calls which saves lot of boiler plate coding. Using DAO pattern to access database is one of the JDBC best practices to follow.
Read more »
Read More..

Top 20 Java technical interview questions and answers for experienced Java developers

Rabu, 05 Februari 2014

If you are an interviewer -- it really pays to ask well rounded questions to judge the real experience of the candidate as opposed to just relying on the number of years.

If you are an interviewee -- You have no control over what questions will be asked in Java job interviews, but there are a few Java interview questions that are very frequently asked in job interviews, and it really pays to prepare for those questions. Here are a few such questions. This is based on some of my recent interviews. Brushing up on these answers will boost your success rate in Java job interviews.

The focus is on judging your experience. So, go through your resume and reflect back on your hands-on experience. Many of these answers will also serve you well in selling your technical strengths to open ended questions like -- tell me about yourself? , why do you like software development?, when reviewing others work, what do you look for?, what was your most significant accomplishment?, etc

Q1. Can you describe the high level architecture of the application that you had worked on recently? or Can you give a 100 feet birds eye view of the application you were involved in as a developer or designer?

A1. The purpose is to judge your overall experience. Here are a few links that will prepare for this most sought-after question, especially for the experienced professionals.



Q2. How would you go about deciding between SOAP based web service and RESTful web service?
A2. Web services are very popular and widely used to integrate disparate systems. It is imperative to understand the differences, pros, and cons between each approach. Recently, I have been asked these questions very frequently, here is the answer that discusses the pros and cons of SOAP vs. RESTful web services in detail.  

Q3.How will you go about ensuring that you build a more robust application? or How do you improve quality of your application?
A3. This question is very popular with the interviewers because they want to hire candidates who write good quality application. Here are some useful links to prepare for this question.


Q4. What are some of the best practices regarding SDLC? Have you worked in an agile development environment? Did you use test driven development and continuous integration?
A4. 
Q5: Can you write code? How would you go about implementing .....?
A5:  You will be asked to write a small function or a program. The interviewer will be looking for things like
  • How well you analyze the requirements and the solution? Ask relevant questions if the requirements are not clear. Think out loud so that the interviewer knows that how you are approaching the problem.The approach is more important that arriving at the correct solution.
  • List all possible alternatives.
  • Write pseudo code.
  • Write unit tests.
  • Where required, brainstorm with the interviewer.
  • Find ways to improve your initial solution. Talk through thread safety and best practices where applicable.
Here are some links to popular coding questions and answers.
  • Java coding interview questions and answers:. Covers a number of coding questions with answers. These are some of the popular coding interview questions like reversing a string, calculating the Fibonacci number, recursion vs iteration, equals versus ==, etc.

Q6. How would you go about designing a car parking station?
A6.
Map out the requirements:
  • The car park needs to cater for different types of car parks like regular, handicapped, and compact.
  • It should keep track of empty and filled spaces.
  • It should also cater for valet parking.
Map out the classes that would be required. Use a UML class diagram. Here are some points to get started.
  • A CarPark class to represent a parking station.
  • A ParkingSpace can be an abstract class or an interface to represent a parking space, and RegularParkingSpace, HandicappedParkingSpace, CompactParkingSpace, etc are subtypes of a ParkingSpace. This means a RegularParkingSpace is a ParkingSpace.
  • A CarPark has a (i.e. composition) finite number of ParkingSpaces. A CarPark also keeps track of all the parking spaces and a separate list of all the vacant parking spaces.
  • A Vehicle class uses a (i.e. delegation) ParkingSpace.  The Vehicle class will hold attributes using enum classes like  VehicleType and ParkingType. The vehicle types could be Compact, Regular, and Handicapped. The parking types could be Self or Valet. Depending on the requirements, the self or valet types could be designed as subtypes of the Vehicle class.


Q7: Can you design the classes that represent a restaurant?
A7: Very popular. Good understanding of OO design is vital to job interview success. Learn the SOLID design principles, know why you favor composition over inheritance, and dont under estimate the power of coding to interface.
  • Java OO Interview Questions and Answers. A step-by-step tutorial explaining how you would go about designing your classes. The "Core Java Career Essentials" PDF covers more examples on SOLID design principles with working code.

How would you go about identifying thread safety issues in an application? How would you go about identifying memory leaks issues? How would you go about identifying performance issues?, etc to judge your experience. I am yet to work on a project that didnt face problems relating to thread safety, memory leaks, and performance issues. Hence, it really pays to market your skills and experience in fixing issues relating to these common challenges.


Q8. How will you go about fixing memory leaks in Java?
A8. Again, a very common problem, and a thorough answer will go a long way in securing your next Java job.

Q9: How will you go about fixing performance issues in Java?
A9:
  • Detecting performance issues in Java. A basic tutorial covering -- how to detect performance issues.
  • Also, refer to the JMeter tutorials in this blog as to learn how you can put load on your application to simulate concurrent users.

Q10: How will you go about detecting and fixing thread-safety issues in Java?
A10: Debugging concurrency issues and fixing any thread starvation, dead lock, and contention requires skills and experience to identify and reproduce these hard to resolve issues. Here are some techniques to detect concurrency issues.
  • Manually reviewing the code for any obvious thread-safety issues. There are static analysis tools like Sonar, ThreadCheck, etc for catching concurrency bugs at compile-time by analyzing their byte code.
  • List all possible causes and add extensive log statements and write test cases to prove or disprove your theories.
  • Thread dumps are very useful for diagnosing synchronization problems such as deadlocks. The trick is to take 5 or 6 sets of thread dumps at an interval of 5 seconds between each to have a log file that has 25 to 30 seconds worth of runtime action. For thread dumps, use kill -3 in Unix and CTRL+BREAK in Windows. There are tools like Thread Dump Analyzer (TDA), Samurai, etc. to derive useful information from the thread dumps to find where the problem is. For example, Samurai colors idle threads in grey, blocked threads in red, and running threads in green. You must pay more attention to those red threads.
  • There are tools like JDB (i.e. Java DeBugger) where a “watch” can be set up on the suspected variable. When ever the application is modifying that variable, a thread dump will be printed.
  • There are dynamic analysis tools like jstack and JConsole, which is a JMX compliant GUI tool to get a thread dump on the fly. The JConsole GUI tool does have handy features like “detect deadlock” button to perform deadlock detection operations and ability to inspect the threads and objects in error states. Similar tools are available for other languages as well.

Java Interview Questions 11- 13 for experienced developers

Read More..