If you have used Hibernate with JPA and using annotation to declare your entity bean then you might have seen this confusing error called "org.hibernate.MappingException: Unknown entity". This error message is so misleading that you could easily lose anywhere between few minutes to few hours looking at wrong places. I was using Spring 3 and Hibernate 3.6 when I got this error,which occurs when addEntity() method was executed. I checked everything, from Spring configuration file applicationContext.xml, Hibernate config file, my Entity class and DAO class to see whether my Entity class is annotated or not, but I was still getting this error message. After some goggling I eventually find that, it was an incorrect import which was causing this error. Both hibernate and JPA has @Entity annotation and some how Eclipse was automatically importing org.hibernate.annotations.Entity instead of javax.persistence.Entity annotation. Once I fixed this import issue, everything went smooth. Unfortunately, this error is not easy to spot, the org.hibernate.annotations.Entity import seemed completely appropriate to many programmers. For a newbie Java or hibernate developer it�s really hard to understand which Entity annotation to use, shouldn't be in org.hibernate.annotations.Entity, but instead it's javax.persistence.Entity. By the way, if you are using auto-complete functionality of Eclipse IDE, then you can blame it them, alternatively you can configure your preferred import in Eclipse.
Read more �
Showing posts with label core java. Show all posts
Showing posts with label core java. Show all posts
Sunday, April 13, 2014
Thursday, April 10, 2014
Difference between FileInputStream and FileReader in Java | InputStream vs Reader
Before going to explain specific difference between FileInputStream and FileReader in Java, I would like to state fundamental difference between an InputStream and a Reader in Java, and when to use InputStream and when to go for Reader. Actually, Both InputStream and Reader are abstractions to read data from source, which can be either file or socket, but main difference between them is, InputStream is used to read binary data, while Reader is used to read text data, precisely Unicode characters. So what is difference between binary and text data? well everything you read is essentially bytes, but to convert a byte to text, you need a character encoding scheme. Reader classes uses character encoding to decode bytes and return characters to caller. Reader can either use default character encoding of platform on which your Java program is running or accept a Charset object or name of character encoding in String format e.g. "UTF-8". Despite being one of the simplest concept, lots of Java developers make mistakes of not specifying character encoding, while reading text files or text data from socket. Remember, if you don't specify correct encoding, or your program is not using character encoding already present in protocol e.g. encoding specified in "Content-Type" for HTML files and encoding presents in header of XML files, you may not read all data correctly. Some characters which are not present in default encoding, may come up as ? or little square. Once you know this fundamental difference between stream and reader, understanding difference between FileInputStream and FileReader is quite easy. Both allows you to read data from File, but FileInputStream is used to read binary data, while FileReader is used to read character data.
Read more �
Wednesday, April 9, 2014
For Each loop Puzzle in Java
From Java 5 onwards, we have a for-each loop for iterating over collection and array in Java. For each loop allows you to traverse over collection without keeping track of index like traditional for loop, or calling hasNext() method in while loop using Iterator or ListIterator. For-each loop indeed simplified iteration over any Collection or array in Java, but not every Java programmer is aware of some useful details of for-each loop, which we will see in this tutorial. Unlike other popular items from Java 5 release alias Generics, Autoboxing and variable arguments, Java developers tend to use for-each loop more often than any other feature, but when asked about how does advanced foreach loop works or what is basic requirement of using a Collection in for-each loop, not everyone can answer. This small tutorial and example aims to bridge that gap by going through some interesting foreach loop puzzles. So, without any further delay let's see our first puzzle on Java 5 for-each loop.
Read more �
Labels:
core java,
java collection tutorial,
programming,
puzzles
Friday, April 4, 2014
How to replace line breaks , New lines from String in Java.- Windows, Mac or Linux
We often need to replace line terminator characters, also known as line breaks e.g. new line \n and carriage return \r with different characters. One of the common case is to replace all line breaks with empty space in order to concatenate multiple lines into one long line of String. In order to replace line breaks, you must know line terminator or new line characters for that platform. For example, In Windows operating system e.g. Windows 7 and 8, lines are terminated by \n\r also known as CR+LF, while in Unix environment e.g. Linux or Solaris line terminator is \n, known as line feed LF. You can also get line terminator pragmatically by using Java system property line.terminator. Now question is, How can you replace all line breaks from a string in Java in such a way that will work on both Windows and Linux (i.e. no OS specific problems of carriage return/line feed/new line etc.)? Well, You can use System.getProperty("line.terminator") to get the line break in any OS and by using String replace() method, you can replace all line breaks with any character e.g. white space. replace() method from java.lang.String class also supports regular expressions, which makes it even more powerful. In next section we will learn how to replace all line breaks from Java String by following a simple code example. By the way, if you are removing line breaks from String then don't forget to store result of replace() method into same variable. Since String is immutable in Java, any change on it will always produce a new String, if you assume that call to replace() will change the original string then it's not going to happen. For example, in below code original String text will remain unchanged, even after calling replace() method.
Read more �
Wednesday, April 2, 2014
Difference between Stub and Mock object in Java Unit testing - JUnit
JUnit is the most popular framework for unit testing Java code. Unit testing is used to test a single programming unit e.g. a class or a method, in-fact many Java developer write unit test on per method basis. Stub and Mock objects are two concepts which helps during unit testing, they are not real object, but act like real object for unit testing purpose. By the way, If you are absolutely beginner in Java Unit testing then you can see this post to learn how to create JUnit test in Eclipse. Coming back to Stubs and Mocks, One reason of using Stub and Mock object is dependency of one unit into another. Since in real world, most unit doesn't work in isolation, they use dependent class and object to complete there task. One of the common testing approach to test a unit, which depends on other unit is by using Stubs and Mock objects. They help to reduce complexity, which may be require to create actual dependent object. In this tutorial, we will learn few basic difference between Stub and Mock object in Java Unit testing. This post is rather small to tackle this whole topic, at best it just provide an introduction. I would suggest to follow on some good books on Java Unit testing e.g. Pragmatic Unit Testing in Java. This is one of the must read book in Java Unit testing, and my personal favourite as well. Apart from teaching basics of Unit testing it also gives a nice overview of Mock objects and mock framework. Actually, from there, I came to know about EasyMock and jMock frameworks and how useful they can be. Even if you have been using JUnit and unit testing, you can learn a lot form this book. It's like learning from basics to best practices of Unit testing. Mockito is another useful library enables mocks creation, verification and stubbing.
Read more �
Monday, March 31, 2014
How to use EnumSet in Java with Example
EnumSet is one of the specialized implementation of Set interface for enumeration type, introduced in Java 1.5 along with enumeration type itself. Programmer often stores Enum into common collection classes e.g. HashSet or ArrayList, mostly because they are unaware of this little gem. Even I wasn't aware of this class few years ago, until I come across one of the finest book for Java programmers, Effective Java. It has an Item on EnumSet, which highlight some typical use-cases for this collection class instead of using int variable and bitwise operator. Since Enum constants are unique and has pre-defined length, as you can not define a new enum constant at runtime; it allows Java API designer to highly optimize EnumSet. If you look closely, EnumSet also teaches you couple of good design practices to create flexible and maintainable code. For example, EnumSet is an abstract class, and it provides lots of static factory method to create instance of EnumSet e.g. EnumSet.of(...). This method takes advantage of method overloading and variable argument to provide Set of only provided Enum constants. Second good thing is there are two concrete sub-classes of EnumSet e.g. RegularEnumSet and JumboEnumSet, but both are package-private, which means client can not use them directly. Only way to use them is via EnumSet. At runtime, depending upon key size of requested Enum, implementation automatically decide which implementation to use. This provides you immense flexibility and control to rollout a new better version of EnumSet implementation without any change on client side. Anyway, this article is not just about design lessons form this class but more importantly how and when to use EnumSet in Java program. I have shared simple example to demonstrate power of EnumSet, which you will see in next section.
Read more �
Thursday, March 27, 2014
3 ways to Find First Non Repeated Character in a String - Java Programming Problem
Write a Java program to find first non repeated character in a String is a common question on coding tests. Since String is a popular topic in various programming interviews, It's better to prepare well with some well-known questions like reversing String using recursion, or checking if a String is palindrome or not. This question is also in the same league. Before jumping into solution, let's first understand this question. You need to write a function, which will accept a String and return first non-repeated character, for example in world "hello" , except 'l' all are non-repeated, but 'h' is the first non-repeated character. Similarly in word "swiss" 'w' is the first non-repeated character. One way to solve this problem is creating a table to store count of each character, and then picking the first entry which is not repeated. Key thing to remember is order, your code must return first non-repeated letter. By the way, In this article, we will see 3 examples to find first non repeated character from a String. Our first solution uses LinkedHashMap to store character count, since LinkedHashMap maintains insertion order and we are inserting character in the order they appear in String, once we scanned String, we just need to iterate through LinkedHashMap and choose the entry with value 1. Yes, this solution require one LinkedHashMap and two for loops. Our second solution is a trade-off between time and space, to find first non repeated character in one pass. This time, we have used one Set and one List to keep repeating and non-repeating character separately. Once we finish scanning through String, which is O(n), we can get the magic character by accessing List which is O(1) operator. Since List is an ordered collection get(0) returns first element. Our third solution is also similar, but this time we have used HashMap instead of LinkedHashMap and we loop through String again to find first non-repeated character. In next section, we will the code example and unit test for this programming question. You can also see my list of String interview Questions for more of such problems and questions from Java programming language.
Read more �
Tuesday, March 25, 2014
Difference between WeakReference vs SoftReference vs PhantomReference vs Strong reference in Java
WeakReference and SoftReference were added into Java API from long time but not every Java programmer is familiar with it. Which means there is a gap between where and how to use WeakReference and SoftReference in Java. Reference classes are particularly important in context of How Garbage collection works. As we all know that Garbage Collector reclaims memory from objects which are eligible for garbage collection, but not many programmer knows that this eligibility is decided based upon which kind of references are pointing to that object. This is also main difference between WeakReference and SoftReference in Java. Garbage collector can collect an object if only weak references are pointing towards it and they are eagerly collected, on the other hand Objects with SoftReference are collected when JVM absolutely needs memory. These special behaviour of SoftReference and WeakReference makes them useful in certain cases e.g. SoftReference looks perfect for implementing caches, so when JVM needs memory it removes object which have only SoftReference pointing towards them. On the other hand WeakReference is great for storing meta data e.g. storing ClassLoader reference. If no class is loaded then no point in keeping reference of ClassLoader, a WeakReference makes ClassLoader eligible for Garbage collection as soon as last strong reference removed. In this article we will explore some more about various reference in Java e.g. Strong reference and Phantom reference.
Read more �
Friday, March 21, 2014
Binary Search vs Contains Performance in Java List
There are two ways to search an element in a List class, by using contains() method or by using Collections.binarySearch() method. There are two versions of binarySearch() method, one which takes a List and Comparator and other which takes a List and Comparable. This method searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If List is not sorted, then results are undefined. If the List contains multiple elements equal to the specified object, there is no guarantee which one will be returned. This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons. In the end this method returns the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. This means that return value will be >= 0 if and only if the key is found. Since common implementation of List interface e.g. ArrayList, Vector, CopyOnWriteArrayList and Stack implements RandomAccess interface, they can be used for performing binary search, but there are other implementations like LinkedList, which doesn't implement java.util.RandomAccess, hence not suitable for binary search operation. Since binary search can only be performed in sorted list, you also need to sort your collection before doing search, which may potentially impact performance, especially if your List is big and not in sorted order already.
Read more �
Wednesday, March 19, 2014
2 Examples of Streams with Collections in Java 8
Finally Java 8 is here, after more than 2 years of JDK 7, we have a much expected Java 8 with lots of interesting feature. Though Lambda expression is the most talked item of coming Java 8 release, it wouldn't have been this much popular, if Collections were not improved and Stream API were not introduced. Java 8 is bringing on new Streams API java.util.stream package, which allow you to process elements of Java Collections in parallel. Java is inheritably sequential and there is no direct mean to introduce parallel processing at library level, stream API is going to fill that gap. By using this, you can filter elements of collection on given criterion e.g. if you have a List of orders, you can filter buy orders with sell orders, filter orders based upon there quantity and price and so on. You can also perform two of most popular functional programming functions e.g. map and reduce. java.util.stream class provides function such mapToInt(), mapToLong(), and map function to apply an operation on all elements of Collections. By the way, these are just few of gems of Stream API, I am sure you will find several more, when you start exploring lambda expression and java.util.stream package. In this tutorial, we will see 2 examples of using Java 8 Stream with Collections classes. I have chosen List for these example, but you can use any Collection e.g. Set, LinkedList etc. By the way, use of Stream is not limited to Collections only, you can even use an array, a generator function, or an I/O channel as source. In most cases, a Stream pipeline in Java 8 consists a source, followed by zero or more intermediate stream operations e.g. filter() or map(); and a terminal operation such as forEach() or reduce().
Read more �
Labels:
core java,
Java 8,
programming,
Stream API examples
Monday, March 17, 2014
How to Check if a Number is Binary in Java - Programming Problem
Today we will take a look on another simple programming exercise, write a program to check if a number is binary in Java. A number is said to be binary if it only contains either 0 or 1, for example 1010 is binary number but 1234 is not. You can not any library method to solve this problem, you need to write a function to check if given number is binary, you can use basic constructs of Java programming language e.g. operators, keywords, control statements etc. If you are a regular reader of Javarevisited, then you know that I love to share simple programming problems here, because they serve two purposes, first they help beginners to apply their basic knowledge to do something which looks challenging at first, and second they serve as good coding questions to differentiate candidates on Java interviews between who can program and who can not. FizzBuzz is one of such problems but their are lot many, e.g. Prime numbers, Fibonacci series or factorial. But if you truly want to test your candidate then you need to give them some questions which are not so popular. If a candidate can apply his programming knowledge to a problem he is seeing first time, he is probably going to perform better than the candidate who has already seen the problem. That's why I was always looking at programming problems, which are not difficult to solve but has some element of freshness and not so common. This problem of checking whether a number is binary or not is not very different from converting a decimal to binary, but it will pose challenge for those programmers who can't code. By the way, if you are looking for simple programming problems, you can check my list of Top 30 programming interview questions, their I have shared questions from several popular topics including String, Array, Data Structure and Logic.
Read more �
Thursday, March 13, 2014
Why use Underscore in Numbers from Java SE 7 - Underscore in Numeric Literals
JDK 1.7 release had introduced several useful features, despite most of them being syntactic sugar, there use can greatly improve readability and code quality. One of such feature is introduction of underscore in numeric literals. From Java 7 onwards you can write a long digit e.g. 10000000000 to a more readable 10_000_000_000 in your Java source code. One of the most important reason of using underscore in numeric literal is avoiding subtle mistakes which is hard to figure out by looking at code. It's hard to notice a missing zero or extra zero between 10000000000 and 1000000000, than 10_000_000_000 and 1_000_000_000. So if you are dealing with big numbers in Java source code, use underscore in numbers to improve readability. By the way, there are rules to use underscore in numeric literals, as they are also a valid character in identifier, you can only use them in between digits, precisely neither at the start of numeric literal nor at the end of numeric literals. In next couple of section, we will learn how underscore in numeric literal is implemented and rules to use them in numerical literals.
Read more �
Tuesday, March 11, 2014
How to Clone Collection in Java - Deep copy of ArrayList and HashSet
Programmer often mistook copy constructors provided by various collection classes, as a mean to clone Collection e.g. List, Set, ArrayList, HashSet or any other implementation. What is worth remembering is that, copy constructor of Collection in Java only provides shallow copy and not deep copy, which means objects stored in both original List and cloned List will be same and point to same memory location in Java heap. One thing, which adds into this misconception is shallow copy of Collections with Immutable Objects. Since Immutable can't be changed, It's Ok even if two collections are pointing to same object. This is exactly the case of String contained in pool, update on one will not affect other. Problem arise, when we use Copy constructor of ArrayList to create a clone of List of Employees, where Employee is not Immutable. In this case, if original collection modifies an employee, that change will also reflect into cloned collection. Similarly if an employee is modified in cloned collection, it will also appeared as modified in original collection. This is not desirable, in almost all cases, clone should be independent of original object. Solution to avoid this problem is deep cloning of collection, which means recursively cloning object, until you reached to primitive or Immutable. In this article, we will take a look at one approach of deep copying Collection classes e.g. ArrayList or HashSet in Java. By the way, If you know difference between shallow copy and deep copy, it would be very easy to understand how deep cloning of collection works.
Read more �
Wednesday, March 5, 2014
Top 10 MQ Series Interview Questions Answers - WebSphere and Active MQ
MQ Series Interview Questions and Answers are collection of some of the questions asked on various MQ implementation e.g. IBM WebSphere MQ, Active MQ or Sonic MQ from different core Java and Enterprise Java (JEE) interviews. Most of these questions are from websphere MQ as it's the one which is most popular in large organization, especially in finance domain. By the way messaging is a key aspect of any enterprise application and you will always see some form of messaging between different systems in a organization. For example, In finance world, most of the middle office to back office communication happens over messaging middle-ware like TIBCO or MQ Series. Its one of the popular Message Oriented Middleware used in Core Java and Enterprise Java application deployed on IBM WebSphere Server, which means if your organization is using IBM WebSphere as application server, you are likely see WebSphere MQ there. By the way that's not the only one messaging solution available, you have couple of choices depending upon requirement e.g. Tibco Rendezvous for high speed messaging, Tibco EMS for a JMS based messaging, mostly for durable messages and MQ series as well. It's long time I have written any article on messaging after my articles based on Tibco messaging, along with some Tibco Interview Questions e.g. difference between Tibco RV and Tibco EMS. In this messaging article, focus will on MQ Series and in particular WebSphere MQ. These 10 WebSphere MQ interview Question and Answers will certainly help you to prepare better for any Java interview which expect experience on MQ Series.
Read more �
Monday, March 3, 2014
Covariant Method Overriding of Java 5 - Coding Best Practices
Sometime knowledge of a specific Java feature can improve code quality, Covariant method overriding is one of such feature. Covariant method overriding was introduced in Java 5, but it seems it lost between other more powerful features of that release. Surprisingly not many Java programmer knows about Covariant overriding, including myself, until I read, one of the best Java book on Collection framework, Java Generics and Collection. Covariant method overriding helps to remove type casting on client side, by allowing you to return subtype of actually return type of overridden method. Covariant overriding can be really useful, while overriding methods which returns object e.g. clone() method. Since clone() return object every client needs to cast on to appropriate subclass, not any more. By using Java 5 covariant overriding, we can directly return subtype instead of object, as we will seen in examples of this article. This feature is not a star feature like Generics or Enum, but it's definitely something worth knowing, given overriding methods are integral part of Java programming. I have discussed a bit about this feature earlier in difference between overriding and overloading article, and here I will show couple of more examples to justify it's usage.
Read more �
Friday, February 28, 2014
Why Catching Throwable or Error is bad?
We often hear advice that catching Throwable or Error is bad practice and Java developer should avoid catching these, but have you thought Why? If language allows you to catch anything which is instance of java.lang.Throwable, then what is the problem of catching them or their subclass java.lang.Error? If they are bad, shouldn't Java itself has prohibited them from catching? Well this all looks good on theory, but not in real world programming. As I said before in Java Exception best practices post, Ideally you should never catch Throwable or in particular Error. There are several reasons why catching instance of java.lang.Throwable is bad idea, because in order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable. When you do this, no body knows what kind of Error this method is going to throw, and until you know what is the problem, how can you resolve that. Main purpose of providing Exception handling mechanism is to handle error situation properly, but you can't a provide a solution which can solve all problems. That's why we have specific Exception classes e.g. FileNotFoundException, IllegalArgumentException, IOException and so on. So if you don't know how to resolve or handle error, there is no point catching Throwable, all it make your code hard to read and comprehend. Remember, each error handling code is driven by business/audit/reporting or quality requirement and catching Throwable just obscure those logics.
Read more �
Wednesday, February 26, 2014
10 Example of Lambda Expressions and Streams in Java 8
Java 8 release is just a couple of weeks away, scheduled at 18th March 2014, and there is lot of buzz and excitement about this path breaking release in Java community. One of feature, which is synonymous to this release is lambda expressions, which will provide ability to pass behaviours to methods. Prior to Java 8, if you want to pass behaviour to a method, then your only option was Anonymous class, which will take 6 lines of code and most important line, which defines the behaviour is lost in between. Lambda expression replaces anonymous classes and removes all boiler plate, enabling you to write code in functional style, which is some time more readable and expression. This mix of bit of functional and full of object oriented capability is very exciting development in Java eco-system, which will further enable development and growth of parallel third party libraries to take advantage of multi-processor CPUs. Though industry will take its time to adopt Java 8, I don't think any serious Java developer can overlook key features of Java 8 release e.g. lambda expressions, functional interface, stream API, default methods and new Date and Time API. As a developer, I have found that best way to learn and master lambda expression is to try it out, do as many examples of lambda expressions as possible. Since biggest impact of Java 8 release will be on Java Collections framework its best to try examples of Stream API and lambda expression to extract, filter and sort data from Lists and Collections. I have been writing about Java 8 and have shared some useful resources to master Java 8 in past. In this post, I am going to share you 10 most useful ways to use lambda expressions in your code, these examples are simple, short and clear, which will help you to pick lambda expressions quickly.
Read more �
Monday, February 24, 2014
How to Format and Display Number to Currency in Java - Example Tutorial
Displaying financial amount in respective currency is common requirement in Java based E-commerce applications. For example if you are selling products on-line globally, you will show price of product in their local currency rather than USD or some other currency. Storing price in every currency is not a good option because of maintenance, and more realistically fluctuation in exchange rates. That's why many of these application prefer stores price of books, electronic goods or whatever product they are selling in USD, and responsibility of converting that price to local currency and displaying is left to client side code. If your client is Java based client e.g. Swing GUI , Java FX client, or a JSP web page, you can use java.text.NumberFormat class to format currency in Java. NumberFormat class allows you to display price in multiple currency depending upon Locale supported by your Java version. All you need to do is to get correct Currency Instance based upon Locale, for example to display amount in US dollar, call NumberFormat.getCurrencyInstance() method with Locale as Locale.US, similarly to display currency as UK pound sterling, pass Locale.UK and for displaying money in Japanese Yen, pass Locale.JAPAN. Once you get the correct instance of currency formatter, all you need to do is call their format() method by passing your number. We will see an example of converting one currency to other and displaying amount in multiple currency in Java. It's actually very much similar to formatting date in Java, so if you are familiar to that part, it would be easy to format currency as well.
Read more �
Labels:
core java,
Java Programming Tutorials,
programming
Friday, February 21, 2014
Fixing java.net.BindException: Cannot assign requested address: JVM_Bind in Tomcat, Jetty
Some of the most dreaded error in Java based client server based application is networking related error, e.g. java.net.BindException: Cannot assign requested address: JVM_Bind. I have faced this issue, while working with web servers like Tomcat, Jetty, and Weblogic before, but yesterday it came again, when one of my colleague faced this issue in Windows. As soon as Java programmers sees java.net.BindException, they come to conclusion that it's issue with two process listening on same port, and often mistook it for Java.net.BindException: Address already in use: JVM_Bind:8080, which is slightly different than this. If you look Java documentation for java.net.BindExcpetion, you will find this "Signals that an error occurred while attempting to bind a socket to a local address and port. Typically, the port is in use, or the requested local address could not be assigned." It's the second part, which is more interesting in case of java.net.BindException: Cannot assign requested address: JVM_Bind.
Read more �
Thursday, December 19, 2013
JUnit Testing Tips - Constructor is Called Before Executing Test Methods
Most of Java programmers either use JUnit or TestNG for there unit testing need, along with some mock object generation libraries e.g. Mockito, but not everyone spend time and effort to learn subtle details of these testing libraries, at least not in proportion of any popular framework e.g. Spring or Hibernate. In this blog post, I am sharing one of such details, which has puzzled me couple of years ago. At that time, though I had been using JUnit for significant time, I wasn't aware that code written inside constructor of Test class is executed before each test method. This behaviour of JUnit has caused, some of my test to failed and putting hours of investigation in my code, without realizing that this is happening because of JUnit is initializing object by calling constructor before executing test method annotated with @Test annotation. I had following code to test my vending machine implementation as coding exercise. If you look at closely, I have initialized vending machine in class body, which is executed as part of constructor. I was assuming one instance of vending machine is shared between all test methods, as I was not using @Before and @After, JUnit 4 annotation for setup() and tearDown(). In first test, one item from Inventory is consumed and in second test another item, but when you assert count of items based upon previous test, it will fail, because you are testing a different vending machine instance, which has different inventory. So always, remember that JUnit calls constructor of test class before executing test method. You can verify it by putting a System.out.println message in constructor itself.
Read more �