Search

Tuesday, June 30, 2015

How to write to File in Java using BufferedWriter

You can use either OutputStream or Writer class in Java to write data to a file in Java. For example you can use combination of FileWriter and BufferedWriter to write text content into a text file in Java. If you want to write raw bytes consider using FileOutputStream class. Just remember that InputStream is used to read data and OutputStream is used to write data to file or socket. You can write anything to file e.g. String, integer, float values etc. Java provides DataOutputStream to write different data type directly into file e.g. writeInt() to write integer values, writeFloat() to write floating point values into file and writeUTF() to write String into File.  BufferedWriter, like its counterpart BufferedReader allows you to perform buffered IO, which can drastically improve performance while reading large files. Java provides many convenient wrapper classes for reading and writing data into files e.g. you can use PrintWriter to write data line by line into file. It's println() method automatically adds line separator after each line.  Java 7 has also introduced even a brand new API known as new File API, which provides powerful methods to read whole file in just one line. All in all, Java has got really good support to deal with files in Java and we will explore more of them in coming tutorials. By the way, if you are beginner and just started learning Java, I would recommend you to at-least read one Java book to get a complete overview, later you can fine tune your knowledge by reading tutorials. You can refer Java: A Beginner's Guide by Herbert Schildt to start with Java. This book contains very good example and comprehensive theory and most important its up-to-date and covers even Java 8.
Read more »

Monday, June 29, 2015

Longevity via Consistency

May 20th, 2015 was a crisp, sunny day in California. The alarm on my iPhone went off at 5:31 a.m., and I rolled out of bed. In about 5 hours I was going to take off to Lake Tahoe for a trip with my dad for a few days. I wasn't looking forward to missing out on trading the rest of the week, but I knew I was starting to get burned out and I needed a break. This trip would be a great time to kick back, relax, and forget about stocks for a while. I knew I could come back the following week with a fresh mindset.

Fast forward 4 hours and 30 minutes, and I had a blood red P/L for the day staring right through my eyes, deep down into my soul. Nearly -$400k. Not a bad day at work, huh?

         I won't lie: the next week was tough. Very tough. Whenever I wasn't busy with something and had time to sit in silence and think, a whole flurry of emotions would hit me. One minute I would be punching the floor, the next I would be trying to pull my hair out or sobbing helplessly. What the hell just happened to me? ‘My life is over,’ I thought to myself. I don't even want to trade anymore; I can't. Trading was supposed to be my job and source of income, while pursuing freelance music jobs on the side. But not anymore--not after what had just happened. I was up over 450k at one point in 2015 alone, at 20 years old, and now I was basically back to square one. Game over. Life over.

Just last year, around September 2014, I had lost a lot of my YTD profits and was faced with a decision to either get back to the grind, or quit. What kind of idiot do you have to be to get yourself in this bad a situation, twice?

"A mistake repeated more than once is a decision." - Paulo Coelho

         After every mistake I make in life, whether in trading or some other activity, I like to clear my mind and dig back to the root of that mistake. I try to find out what REALLY caused it. Each time I tried to do this during that week, a brick would hit me in the face. The thought of the gap between where I had been and where I stood now filled me with dread and sadness, like staring up at a mountain it had been hell to climb, and knowing I would have to start again from the beginning.  But luckily, after going on a family vacation the next few days, my head was cleared. The ‘old me' was back. I told myself to stop wasting time, feeling bad, or complaining, because in the end none of that would do ANYTHING except dig the hole even deeper. So what was at the root of this problem? What had caused this situation, not just on the surface, but deep down?

         My whole life, I have been a private and under-the-radar type of person. Instead of striving for popularity among peers, I have striven for perfection of my craft, regardless of what others see or think. But after trading for a year and being part of the trading community, I had flipped the switch and become more public. Not in the real world--only in the online world. In real life, I was still very private about my success, only telling my parents and siblings, never flaunting it to anyone else. The online trading community and Twitter give a nice outlet for many traders to show off their wins and successes, because, after all, it’s just the internet. You can type or tweet anything and then go right back to living your normal life outside of trading if you wish, as I did.

         But I realized that as I shared more and more of my wins and success publicly, I suddenly became more and more invested in being seen as the young gun trader who is “making bank.” And, of course, along with that image came the pressure to uphold it and not allow any dents in the armor of the image, no matter what. Perhaps that is not the case for everyone, but for someone with my personality and competitive spirit, this was definitely the case (although subconscious), and I had never really thought about it or realized it until now. I had also realized that posting big wins on Twitter and in my trading community became less of an outlet for sharing and more of a way to get a quick satisfactory ego-boost.

         Since mid-February 2015, I had been reading The Fountainhead by Ayn Rand. I finally sat down and finished it the week after my loss, and this gave me fantastic insight into the root of my problems, and the solution going forward. (I highly recommend reading this book; discovering her philosophy on life was one of the turnings points in my life.) I thought about all my actions in the trading community and on Twitter the last 6 months or so, when I had really starting gaining traction in my trading, and asked myself this: Was there a legitimate reason to post this stuff? Was I really, truly helping anyone? Some argue that posting P/L on Twitter is positive because it inspires others to see what is possible from trading. But I had noticed a trend. Over the last 6 months, I had gone from sharing my success in a sincere effort to help others, to posting hollow green numbers simply for personal satisfaction. I was in shock. I suddenly cared more about what others thought of me, and the image I had to uphold, than how well I was executing my craft. Never before in my life had I been that guy; now I was.

Some may have differing opinions on this, and that’s fine. But perhaps ask yourself the same questions I was asking myself in these tweets:


         With each post of a big P/L on Twitter, I added one brick on my back. Eventually those bricks became a burden, and when I stumbled, the bricks came crumbling down on top of me. Ego got the best of me, and I believe that that will always come back to get you whether it's financially, emotionally, or physically.

--------------------------------------------------------------------------------------------------------------

Lessons Learned/Thoughts Moving Forward

1. Ego and Overconfidence are the bane of a successful trader.

         This year started out for me with a very slow January, and then quickly sped up. Week after week after week, pigs that perfectly fit my niche setup criteria were running huge. I was making money hand over fist, and I really couldn't do much wrong. I believe everyone has these phases in their trading careers, whether they last for a few days, weeks, or even months. But I was almost halfway through the year without encountering ANY serious reality checks. I was up a little over $500k in 2015 going into the month of May, and I felt pretty solid about my trading. What was there to stop me from making $1M this year?

Friday, May 1st, started with a nice dead cat bounce on VLTC, and I made around $60k on it. This was a fairly easy trade. I was never down on the trade, which took my feelings of self-confidence soaring to new highs. Over the weekend I relaxed, but I was ready to re-short VLTC on Monday for the next leg down, most likely a swing trade. Then Monday rolled around and there was ICLD--a much better setup. So, I traded ICLD. At the end of the day I had a realized loss of -$92k in one account on ICLD, and an open position of 60k shares to swing at a 3.94 avg. The next day, I added 30k short premarket in the mid 4.20s, and it ended up fading hard and closing at 3-3.05. I had made back ALL of my loss from the previous day! Pretty great right? Not quite. I decided to hold my full position in ICLD with the intention to cover at 2.60 or 2.70 the next day. I knew the company had a shelf out, so I figured they might do an offering. The following day, ICLD gapped up with news, shattering my trading plan and putting me back into the red on the trade. I had let greed get the best of me and held for a win instead of covering for break-even after a large drawdown the previous day.

These were the first signs of my death spiral into the abyss. The size I was trading was absurd. Of course, I had a reason to be trading large size. When you are on a hot streak in trading, you want to push your luck and play more size when the best setups present themselves. I was trading good setups, but my rules were not set in place. I wasn't locking in profits like I typically would, and I felt like going for the home-runs instead of taking quick $5-$10k profits when I had them. Basically, I was trading overconfidently. There is a huge and very important difference between overconfident trading, and trading with conviction.

During the rest of May, my accounts were swinging all over the place. I was swinging 100-150k shares of ICLD from May 5th to May 18th. A quick glance at the daily chart during this time period and you can see how ridiculous of a roller-coaster my account was going through.



What I thought was profound conviction in my short position in ICLD was actually just overconfidence. The night before their earnings report on May 12th, I had a late flight and didn't get to bed until around 2 a.m. PST. I decided to turn my alarms off for the next morning and sleep in. I just wanted to be ignorant to the earnings report, and avoid the whole situation. I knew if I woke up early, my stomach would feel awful and I would be staring at every pre-market tick, as I had been the last week as it squeezed from 3.05 to a high of 4.73.

Let me tell you, it's not healthy to get stomachaches and feel depressed about one particular position, or trading in general. But that was the situation I had put myself in. I was being truly reckless, and had spent the entire year with no grasp on the amount of money I was making and losing. This leads me to the next HUGE lesson I learned, and the changes I implemented in my trading because of it.

2. Pay yourself.

         Trading is very rewarding and not a typical "job". Nevertheless it is a job, and, if done well, a very lucrative one. Unlike some, I don't trade for the sole reason of making money. I trade because it is rewarding mentally and there is an endless amount of knowledge to absorb each and every day. From the day I started trading up until May 20th, 2015, my day of reckoning, I had never really wired money out of my accounts. Sure, I had wired out $10k here and there for small expenses, but for the most part, I had 80-90% of my net worth in my trading accounts at all times. In retrospect, this was a huge mistake, and by doing this I now know I had sealed my fate.

I don't spend money on much besides the necessities of life, as I prefer to grow my wealth instead of blowing money on trivial things. But going forward, at least until the end of 2015, I will be wiring out all excess money over $X. Specifying this number is not important because it will differ for each person and their style of trading; the point is, I really didn't NEED as much money as I had in my accounts. I will also be forcing myself to spend money instead of holding onto it for dear life. If I see a nice guitar or amp for $3-4k that I might not NEED but would like to have, I'll buy it! If I see a great deal on 2-for-1 skydiving lessons or another activity that I might not NEED to do but would like to try, I'll go for it! If I see a brand new house I might not NEED but would like to have, I'll...well, maybe not that. The point is, I need to create a connection between how much money I am making from trading, and what that money actually translates to in the real world.Before, I would make $50k+ in a single day and still buy the cheapest steak on the menu at dinner. Next time, it's the filet mignon!

3. Risk Management. Risk Management. Oh yeah, and Risk Management.

         After my large loss, I thought in depth about my future, both as a trader and just as a man. When I first started trading, I had no idea I would be making (and losing) the amount of money I am now. I figured it would just be a fun way to challenge myself and maybe make some spare change on the side. I have since proven to myself that I am very capable of consistently making money as a trader. But at some point, one has to step back and look at the bigger picture. I want to be a CAREER trader. That means I want to be around in 5 years. In 10 years. In 20 years. When I look back over the last couple years at all the people I have met trading, how many are still around? I have not seen or heard from the majority of them for a long time. Is it because they found another profession that is more fun and lucrative than trading? Odds are that's not the case. It's probably because they lost it all, and ran out of capital.

When I look at my future, I think in terms of goals. I think about the things that will assist me in reaching those goals, and, perhaps more importantly, the things that could STOP me from reaching those goals. One of my goals is to still be trading in 5-10 years. What is the one and only thing that will STOP me from reaching this goal? Running out of trading capital. Blowing up. Losing it all. I came close to experiencing this after PBMD, and I saw my trading life flash before my eyes. I never want to have to go through those moments in my life again, and to avoid doing so I have put a max loss on my trading accounts. Admittedly, I had a rough “max loss” number in mind this whole year, but several times I didn't respect it. Why? Maybe the stock was getting close to my max loss number, but the chart looked as if it was stuffing, so I decided to let it move around a little longer. Then I moved my max loss up to a bigger number to give myself more wiggle room. Or perhaps I convinced myself that since it was a “big picture trade,” a swing trade, I could just let it do its thing and it would come around eventually. I had any number of excuses.

No more of that. Many brokers can set up a max loss automatically for you: when this number is reached, they will close out the position for you, and even lock the account for the rest of the day. Again, my specific max loss number is beyond the scope of this blog, and really shouldn’t matter to you. Find that number for YOU that represents the max pain threshold you can stand before punching a hole in the wall. I am working on being robotic and having the ability to respect my max loss number automatically, but for now I need to put on training wheels. I need to have a system in place with my broker that robotically cuts the max loss off for me, reinforcing that number in my head so that over time, I will gain the ability to cut bad trades off before they get anywhere near it.

One important thing to note about this max loss number is the emotional connection tied to it. I have had some large losses before PBMD, but never that large. I know that I do not EVER want to go back to the place I was that week, where I was suffering emotionally and questioning everything I had done. By having this max loss number, I can avoid that train back to hell.

4. Green is good.

         In my previous blog posts, I have stressed the importance of being consistently green every day, and how critical it was to my early success in trading. In 2015, I had started looking bigger picture. Sure, green every day was nice, but it had started to matter less and less to me, as a day-by-day view was too granular for my style of trading. This is not just carelessness speaking. I believe that once you get your feet off the ground and can prove to yourself that you are consistently profitable for 3-6 months, then and ONLY then can you increase your size and think bigger picture. This year, my primary goal was to be green each week. I didn't really mind having one or two small red days in a week, as long as those red days did not wipe out a full week’s or month’s work. This mindset change was also due to the fact that I had shifted more and more into a swing trading mentality as opposed to only day trading, although I still do one just as much as the other.

Near the end of April and early May, however, I had ditched this mindset. It was not an intentional transition, but a subconscious one that came from recklessness and overconfidence. Due to the wild swings in my trading accounts, in May especially, I had been thrown far off-course. Looking back, it’s certainly not a coincidence that after I stopped focusing on consistency, my trading took a turn for the worse.

Moving forward, and in the spirit of thinking about my trading career over the long term, my main focuses are risk management (respecting my max loss NO MATTER WHAT) and consistent profitability, day in and day out. When I started trading again on June 1st, after my break, I refocused on being green every day, and June has been a very solid month due to this. I know that with these two things reprioritized, I have put myself on a solid path to reach my ultimate goal of longevity in my trading career.

Thanks,
Nikkos


Sunday, June 28, 2015

Update Record In Database For Selenium WebDriver Test

Main usage of database In selenium WebDriver Is getting records from table and use them In your selenium test as per your requirement. Simple example Is you can use that data to perform data driven testing or you can verify data In tables which you have Inserted through web application
forms. Now supposing you wants to update data directly In MySql data table and then you wants to verify same thing In UI then you can do It very easily.

Note : Please read all previous posts on database testing. Links are listed on THIS PAGE.

Updating specific data cell In MySql database table
In my previous post, We learnt how to select specific record using PreparedStatement Interface. Now we will use executeUpdate() method to update specific record which Is selected by where clause.

Bellow given example will set name = "Danial" where id = 5 In user table. Main thing to learn In this example Is how to write query string and set Its parameters to update specific record. Execute bellow given example In eclipse.

DOWNLOAD UpdateRecordInDB.zip folder. You will get UpdateRecordInDB.java test script file In zip folder when extract It. Import It In your eclipse and then execute


At the end of execution, It will show you databse table records In console as shown In above Image. You can see In Image that records with id = 5 Is updated with name = "Danial". Now If you have website UI then you can check same thing there using selenium webdriver.

Saturday, June 27, 2015

java.lang.NoClassDefFoundError: org/dom4j/DocumentException [Solution]

Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException comes when your program is using DOM4j library but necessary JAR is not present. This error can also come when you are indirectly using DOM4j library e.g. when you use Apache POI library to read XLSX file in Java,  this library need dom4j.jar in your classpath. Not just this one but there are several other libraries which uses this JAR internally, if you are using any of them but don't have this JAR then your program will compile fine but fail at runtime because JVM will try to load this class but will not be able to find it on classpath. Some curious developers might ask, why it didn't fail during compile time, if JAR was not present there? Well reason for that is that your code might not be using any class file directly from the dom4j.jar file. When you compile your program e.g. ExcelReader.java, then compiler will only look for class file which is directly referenced or required to generate class file, it will not look for transitive dependencies. For example, suppose you need WorkBook class from Apache  POI, which internally uses dom4j library, compiler will complain if poi.jar is not there, but will not complain even if dom4j.jar is not present because its compiling your code, its not compiling WorkBook class, its already compiled because class file of this code is already present in poi.jar. But things works differently when your run the program, at that time JVM will look for all the binary code. When it will load WorkBook class it will try to load the referenced class from DOM4j library and at that time if JVM didn't find those classes in CLASSPATH, it will throw java.lang.NoClassDefFoundError: org/dom4j/DocumentException.  It can also come as java.lang.ClassNotFoundException: org.dom4j.DocumentException but only if your code tries to load this class explicitly instead of JVM. That's actually the difference between ClassNotFoundException and NoClassDefFoundError in Java. Now million dollar question? How do you solve this error? Just add dom4j-1.6.1.jar file into classpath.
Read more »

Friday, June 26, 2015

2 Ways to Read a Text File in Java 6

You can read a text file in Java 6 by using BufferedReader or Scanner class. Both class provides convenient methods to read a text file line by line e.g. Scanner provides nextLine() method and BufferedReader provides readLine() method. If you are reading a binary file, you can use use FileInputStream. By the way, when you are reading text data, you also need to provide character encoding, if you don't then platform's default character encoding is used. In Java IO, streams like InputStream are used to read bytes and Readers like FileReader are used to read character data. BufferedReader is the traditional way to read data because it reads file buffer by buffer instead of character by character, so its more efficient if you are reading large files. BufferedReader is also there from JDK 1 itself, while Scanner was added on Java 5. Scanner has more features than BufferedReader, when it comes to file reading, for example you can specify any delimiter instead of new line, which is not possible with BufferedReader. Java 7 added new File API, which makes it reading/writing from file even more easier. Its's possible to read entire file in one line in Java 7, but given most of the projects are still running on Java 6, its good to know about these two ways to read a text file in Java. For Java beginners, I also suggest to refer a good book like Cay S. Horstmann, Core Java Volume 1 and 2 to learn basics of Java programming.
Read more »

Tuesday, June 23, 2015

How to Check is a String is Palindrome in Java using Recursion

In this tutorial, you will learn how to check if a string is a palindrome in Java using recursion. A String is nothing but collection of characters e.g. "Java" and String literals are encoded in double quotes in Java. A String is said to be palindrome if reverse of String is equal to itself e.g. "aba" is a palindrome because reverse of "aba" is also "aba", but "abc" is not a palindrome because reverse of "abc" is "cba" which is not equal. Recursion means solving a problem by writing a function which calls itself. In order to check if String is palindrome in Java, we need a function which can reverse the String. Once you have original and reversed String, all you need to do is check if they are equal to each other or not. If they are equal then String is palindrome or not. You can write this reverse() function by using either for loop or by using recursion. If you remember, I already shared logic of reversing String in my earlier post,  how to reverse String in Java using Iteration and recursion. Here we will use the same logic to check if String is palindrome or not. By the way, if you are preparing for coding interviews and looking for some coding problem to get hands on practice, I suggest you to take a look at Cracking the Coding Interview: 150 Programming Questions and Solutions. This is a wonderful book, which contains lots of easy and medium difficulty level coding problems, which will not only help you to prepare for interview but also develop your programming logic.
Read more »

Monday, June 22, 2015

How to pause Thread in Java using Sleep() and TimeUnit Example

There are multiple way to pause or stop execution of currently running thread, but putting thread into sleep state using Thread.sleep() method is the right way to introduce pause. Some people would say, why not use wait and notify?. Using those method just for pausing thread is not good. Those are tools for conditional wait and they doesn't upon time. A thread blocked using wait() will remain waiting until the condition on which it is waiting is changed. Yes, you can put timeout there but the purpose of wait is different, they are designed for inter thread communication in Java. By using sleep() method, you pause the current for some given time. You should never use sleep() in place of wait() and notify() and vice-versa. There is another reason why wait and notify should not be used to pause the thread, they need lock. You can only call them from a synchronized method or block and acquiring and release a lock is not cheap. More importantly, why do you need to introduce lock just for pausing thread. Also one of the key difference between wait() and sleep() method is that, Thread.sleep() puts the current thread on wait but doesn't release any lock it is holding, but wait does release the lock it holds before going into blocking state. In short, multi-threading is not easy, even simple task like creating a thread, stopping a thread or pausing a thread require good knowledge of Java API. You need to use right method at right place. If you are serious about mastering multi-threading and concurrency, I would suggest to read Java Concurrency in Practice twice and do every example given on that book. That book will change how you look a problem from multi-threading perspective.
Read more »

Sunday, June 21, 2015

How Programmers Life Can Bring a Smile to Your Face

I stumbled upon the site thecodinglove.com and just loved it . I want to use the images and quotes to share their  awesome work with you guys . Guess what! they have granted the permission . Although there are thousand of images to choose from the website . I am sharing which relates the most of programmer's lives.This is hilarious, so, pause your day and bring a smile to your face.




When a newbie suggests  to add a new feature to project



Fixing minor bugs




When I'm told that the module on which I have worked all the week will never be used




When I try to fix a bug at 3 in the morning




When I have no choice but to work directly on the Production server




When people tell me PHP is not a real programming language




Backend developer working on the user interface




"Just deploy it, it’s friday!"




When I'm told that my code is broken in production





When I show the boss that I have finally fixed this bug





When the project manager enters the office





When I apply a new CSS for the first time





When that nasty bug comes back again




When sysadmin finally gives us the root access





When the app goes into beta and the first bug reports arrive





Classic development cycle.





When the boss is looking for someone to urgently fix a difficult bug




Want to have more fun

Click here for part 2

Share this post and give a SMILE :) to someone else :D 

How to format numbers in Java? - NumberFormat Example

You can use java.util.text.NumberFormat class and its method setGroupingUsed(true) and setGroupingSize(3) to group numbers and add comma between them. Mostly numbers which are used to represent monetary value e.g. price, amount etc requires comma to be added to improve readability and follow conventions. For example, if your variable is storing 1 million dollar then you would like to see it as 1,000,000 rather than 1000000. Clearly first one is more readable the second one. Of course you can further format to add currency based upon locale, but this tutorial is not about that. In this tutorial, we are just looking to format numbers and group them. Its second part of my number formatting article, in first part you have learned how to format floating point numbers in Java and in this article shows step by step example to group numbers and add commas between them. There are mainly two ways to group numbers in Java, first by using NumberFormat class and second by using DecimalFormat class. Actually DecimalFormat is sub class of NumbeFormat and method used to enable grouping e.g. setGroupingUsed() is define there, but you cannot specify grouping size there. Grouping size is the number of digits between grouping separators in the integer portion of a number and by default NumberFormat use group size of three. So if grouping is your need and you are happy with grouping size of three then go for NumberFormat but if you want advanced formatting and custom grouping size then go for DecimalFormat class. If you are beginner in Java and interested in learning essential features e.g. text formatting, I suggest to take a look at Java: A Beginner's Guide by Herbert Schildt, a must read book for Java beginners.

Read more »

Using where Clause To Get Data From Table Using Selenium WebDriver

Now you are well aware about how to INSTALL MYSQL, CREATING TABLES and ACCESS DATA from MySql data tables for your selenium WebDriver test. You can compare and verify that data or you can use all those data as Input values In some web forms. In previous example, We learnt
how to execute simple select query to get all data from MySql table. You can also use where clause In query to get specific data rows from table.

How to use where clause with query In test
If you are executing query In database manually then you can use where clause very simply with your query. To use where clause In query, You need to use PreparedStatement Interface. PreparedStatement Interface will allow you to use where clause with query In your test. I have prepared example to get value from database using where clause as bellow. It will get and print result In console where name = "smith" and age = 25.

Download MySqlReadDatawithwhere.zip folder. There will be MySqlReadData.java test script file In zip folder. Extract zip folder and Import It In your eclipse and then execute.

When you execute above test In eclipse, It will return result as bellow In console.

This way you can use where clause with query to get specific result. Next post will show you how to update record In MySQL table to test data In selenium.

Saturday, June 20, 2015

Java 8 new features : Lambda expressions , optional class , Defender methods with examples

In JavaOne 2013 , Oracle  reveals the details about the Java 8 .  Java 8 is already released by Oracle last year. It is the most feature rich update then the previous version 6 and 7 , which both were somehow minor updates .

The major features of the java 8 are as follows :

 Introduction of Optional
 Defender Methods
 Lambda Expressions


Read Also :       Java 7 Features Revisited

1. Introduction Of Optional :

The main benefit of Optional is to Avoid null pointer exception : There is another class named Optional in the util package , as it is used to avoid the null pointer exception , If the value is present then it will return the true value otherwise it will show the false value  As it is boolean the value must be between false and true .


In java language , to access an object we use reference type .And when we are unable  to have a specific object to point to , then we set the value of the reference null , indicating it is not pointing to any object .
Null is a literal (also known as constant ) in java .

public static Cat  find(String name, List;Cat; cats) {
   for(Cat cat : cats) {
      if(cat.getName().equals(name)) {
         return cat;
      }
   }
   return null;
}

Method signature shows that  this method may not return a value but a null reference .





Cat;Cat; cats = asList(new Cat("lion"),
                            new Cat("snow leopard"),
                            new Cat("tiger"));

Cat found = find("mountain lion", cats);
//some code in between and much later on (or possibly somewhere else)...
String name = found.getName(); //uh oh!



The question we face is : Will optional helps  us to get rid of null pointer exceptions or references . then it is sadly NO !!


You can find the detail of the Optional Class here :

https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html



2. Defender Methods :

Till java 7 , every interface only has method declaration and no implementations  , and any non abstract class which implements the  interface has to implement every method in interface

public interface MyInterface  {
   public void doAnyWork();
}

class MyInterfaceImpl  implements   MyInterface {
  @Override
 public  void doAnyWork(){
 System.out.println("Do Any work in the class " );
}

public static void main (String args[])
 MyInterfaceImpl  myobject= new MyInterfaceImpl();
 myobject.doAnyWork();
 }
}

Now suppose if i add some method doMoreWork()  abstract method in MyInterface  interface , then , if we try to compile the code , we will get compiler error

$javac .\MyInterface.java .\MyInterface.java:18: error: MyInterfaceImpl is not abstract and does not override abstract method doMoreWork() in MyInterface
class MyInterfaceImpl implements MyInterface{
^ 1 error


 And this limitation makes the situation almost impossible to change the interface or APIs . To overcome this challenge  , java 8 introduces default method also known as defender method .



public interface MyInterface  {
   public void doAnyWork();
// A default  method in the interface  created using "default"  keyword

   default public void doMoreWork(){
    System.out.println ("Do More Work implementation in the interface ") ;
  }
}

class MyInterfaceImpl  implements   MyInterface {
  @Override
 public  void doAnyWork(){
 System.out.println("Do Any work implementation in the class " );
}
/*
 * Not required to override to provide an implementation
 * for doMoreWork
 */
public static void main (String args[])
 MyInterfaceImpl  myobject= new MyInterfaceImpl();
 myobject.doAnyWork();
 myobject.doMoreWork();
 }
}

And the output of the code will be : Do Any Work implementation in the class Do More Work implementation in the interface


  3. Lambda Expressions :



 Lambda expression is explained  in the pdf below :


Click here to Download pdf of Lamda expression
I would love to learn more java 8 features .Please mention in the comments about java 8 features or any other information you have  .

Friday, June 19, 2015

Can you Overload or Override main method in Java?

One of the common doubt among Java beginners while learning overloading and overriding is, whether its possible to overload main in Java ? Can you override main method in Java? How will JVM find if you change the signature of main method as part of method overloading? etc. These are good question and shows curiosity and application of knowledge of students, so if you are tutor you must answer these questions. Short answer to, can we overload main method in Java is Yes, you can overloading, nothing stops from overloading, but JVM will always call the original main method, it will never call your overloaded main method. we will learn this in little more detail later, now coming to next question, can you override main method in Java? answer is No, because main is a static method and static method cannot be overridden in Java. In order to answer this question understanding of overloading and overriding is necessary. You should know that overloading takes place at compile time and overriding takes place at runtime. You should also be familiar with rules of method overloading and overriding in Java. Though main is a special method because its the entry point of your Java application, it follows same rule of method overriding and overloading like any other method. In this article, you will learn how to overload main method to see whether JVM calls the original, standard main with string argument or not.
Read more »

Thursday, June 18, 2015

How to get first and last elements form ArrayList in Java

There are times when you need to get the first or last element of an ArrayList. One of the common scenario where you need first and last element of a list is suppose you have a sorted list and wants to get the highest and lowest element? How do you get that? The first element is your lowest and last element is your highest, provided ArrayList is sorted in ascending order. If its opposite then first element would be the maximum and last element would be the minimum. This is quite easy to do in ArrayList because the first element is stored at index 0 and last element is on index, size - 1. If you know how to get the size of ArrayList then you can easily get those two values. Just remember, that you need to use size() method and not length, which is used to get the length of array. Earlier we have seen how to get first and last element from linked list and In this tutorial we are going to see an example of how get the last element from ArrayList in Java.

By the way if you are serious about learning Java collection framework in deep and want to master different types of collection classes e.g. List, Set, Map, ConcurrentMap, Queue, Stack, BlockingQueue and other thread safe collections introduced on Java 5 and 6, then I suggest you to take a look at Java Generics and Collection by Maurice Naftalin and Philip Wadler, one of the best book to learn Java Collections.
Read more »

Tuesday, June 16, 2015

How to use CyclicBarrier in Java - Concurrency Tutorail

This is the second part of my concurrency tutorial, in first part, you have learned how to use CountDownLatch and in this part, you will learn how to use CyclicBarrier class in Java. CyclicBarrier is another concurrency utility introduced in Java 5 which is used when a number of threads (also known as parties) wants to wait for each other at a common point, also known as barrier before starting processing again. Its similar to CountDownLatch but instead of calling countDown() each thread calls await() and when last thread calls await() which signals that it has reached barrier, all thread started processing again, also known as barrier is broken. You can use CyclicBarrier wherever you want to use CountDownLatch, but opposite is not possible because you can not reuse the latch once count reaches to zero. Some of the common usage of CyclicBarrier is in writing unit test for concurrent program, to simulate concurrency in test class or calculating final result after individual task has completed.

In this tutorial, I will show you an example of how four worker thread waits for other before starting again. As I told in previous article, concurrency is hard to master, sometime even if you read couple of articles on one topic, you don't get what you are looking for. If you understand how and where to use CountDownLatch and CyclicBarrier, then only you will feel confident. Books are also good for mastering concurrency, and one book in particular is very useful to learn multi-threading and concurrency in Java. You guessed it right, I am talking about Java Concurrency in Practice by Brian Goetz, I strongly recommend this book to anyone seriously wants to master threading and concurrency in Java. If you can't get first hand, get second hand, if you can't buy then lend it from library but if you are serious about Java concurrency, you should read it.
Read more »

Monday, June 15, 2015

Java CountDownLatch Example

CountDowaLatch is a high level synchronization utility which is used to prevent a particular thread to start processing until all threads are ready. This is achieved by a count down. The thread, which needs to wait starts with a counter, each thread them make the count down by 1 when they become ready, once the last thread call countDown() method, then latch is broken and the thread waiting with counter starts running. CountDownLatch is a useful synchronizer and used heavily in multi-threaded testing. You can use this class to simulate truly concurrent behavior i.e. trying to access something at same time once every thread is ready. Worth noting is that CountDownLatch starts with a fixed number of counts which cannot be changed later, though this restriction is re-mediated in Java 7 by introducing a similar but flexible concurrency utility called Phaser. There is another similar utility called CyclicBarrier, which can also be used in this situation, where one thread needs to wait for other threads before they start processing. Only difference between CyclicBarrier and CountDownLatch is that you can reuse the barrier even after its broker but you cannot reuse the count down latch, once count reaches to zero. Mastering Concurrency is not easy but if you seriously wants to become an expert Java programmer, you got to tame this horse. One thing which can help you in your journey is the Brian Goetz classic, Java Concurrency in Practice. One of the most recommended book for Java programmer.
Read more »

Sunday, June 14, 2015

Fetching Data From MySQL Database Table For Selenium WebDriver Test

Earlier we learnt how to download and Install MySql database In THIS POST and create database and tables to store data In THIS POST. Both these steps are mandatory to read data through test script. Now this Is time to fetch data from MySQL database table using test script. You need to
follow bellow given steps to run data fetching script In eclipse.

Step 1 : Download required jar file
First of all you need "mysql-connector-java-3.1.13-bin.jar" file which will help us to create database connection In test script. You will find this jar file download link on THIS PAGE.

Step 2 : Add jar file In projects build path.
Now you need to add "mysql-connector-java-3.1.13-bin.jar" file In your project's build path. If you don't know, You can view THIS PAGE to learn how to add any jar file In projects build path.

Step 3 : Create test to fetch data from MySql database
Now you are all set to create test which will fetch data from MySql database table. I have created sample test script which will fetch data from "user" table of "test" database.

Note : Before running this example, Please verify database name, table name, user name and password. User name will be root for mysql database as per our configuration and use password which Is set by you during CONFIGURATION STEP. Modify all these detail accordingly before running test.

DOWNLOAD MySqlReadData.zip folder. You will get MySqlReadData.java test script file In zip folder when extract It. Import It In your eclipse and then execute.

If everything Is correct then console output of above example will be as bellow.


That means our MySql data fetching test Is successfully completed.

This Is sample test script to show you how to extract data from MySql database. If you have application which store data In MySql database then first you need to Insert data In database using Selenium WebDriver test and then you can verify that data directly from DB as given In this example script. NEXT POST  will describe you how to execute query with where clause to fetch specific record from db.

Saturday, June 13, 2015

5 Difference between HashMap and HashSet in java with example

We have already discussed the difference between HashMap and Hashtable . Now in this post you will understand the difference between HashMap and HashSet classes . We will also look into the HashMap and HashSet example. We have already discussed HashMap internal mechanism , HashSet internal working in java .


Read Also :  Frequently asked Java Collections Interview Questions 


Difference between HashMap and HashSet 

1. Duplicates  :  HashSet does not allow duplicate values , in other words, adding a duplicate value leaves the HashSet object unchanged.

If the HashMap previously contain the mapping for the key, the old value is replaced. HashMap  does not allow duplicate keys. In other words, HashMap duplicate values can exist in HashMap.


2. Dummy value : There is no concept of dummy value in HashMap .

HashSet internally uses HashMap to add elements. In HashSet , the argument passed in add(Object) method serves as key K . we need to associate dummy value (automatically created by jdk) for each value  passed in add(Object) method.

3.  Implementation : HashMap implements Map interface, while HashSet implements Set interface.

4. Number of objects during add(put) operation :  HashMap requires two objects put(K key , V Value) to add an element to HashMap object.
HashSet requires only one object add(Object o) .

5.  Adding or Storing mechanism : HashMap internally uses hashing to add or store objects. HashSet internally uses HashMap object to add or store the objects.



Example of HashMap and HashSet in Java




import java.util.HashMap;
import java.util.HashSet;
public class HashMapHashSetExample { public static void main(String[] args) { 
 
           
  
        HashSet<String> hashsetobj = new HashSet<String>();
hashsetobj.add("Alive is awesome");
hashsetobj.add("Love yourself");
System.out.println("HashSet object output :"+ hashsetobj);
 
         
 
        HashMap hashmapobj = new HashMap();
hashmapobj.put("Alive is ", "awesome");
hashmapobj.put("Love", "yourself");
System.out.println("HashMap object output :"+hashmapobj);  
 
 }
}




Output :  HashSet object output :{Love yourself, Alive is awesome}
                 HashMap object output :{Alive is =awesome, Love=yourself}
   



Similarities between HashMap and HashSet 


1. Performance : Performance of  add,put,remove operations are almost same i.e constant time for HashSet and HashMap. It is incorrect to say HashMap is faster than HashSet.

2. Insertion Order :  Both HashMap and HashSet does not guarantee that the order will remain constant over time.

3. Unsynchronized : Both HashMap and HashSet implementation is unsynchronized.

4. Iterator type  : Iterator's returned by both (HashMap and HashSet) class's iterator and collection view methods are fail-fast.  find detailed explanation here fail-safe vs fail-fast in java.



When to use HashMap and HashSet in Java ?



difference between hashmap and hashset in java

The only time we need to prefer HashSet over HashMap when we are asked to maintain uniqueness in our collection object. Otherwise , always prefer HashMap over HashSet as HashSet is just a wrapper around HashMap.




Recap  : Difference between HashMap and HashSet in Java 




HashMap  HashSet            
DuplicatesYes, Duplicate values
but  no duplicate keys
No                      
Adding or Storing mechanism Hashing techniqueHashMap object          
Dummy valuesNoYes
ImplementsMapSet
Number Of Objects required
during add operation  
21


In case you have any other query or doubts regarding difference between HashMap and HashSet in Java then please mention in the comments .

java.lang.ClassNotFoundException: org.Springframework.Web.Context.ContextLoaderListener [Solution]

Problem : java.lang.ClassNotFoundException : org.Springframework.Web.Context.ContextLoaderListener

Cause : This error comes when you are using Spring MVC framework in your Java Web application and configured org.springframework.web.context.ContextLoaderListener as a listener in your deployment descriptor also known as web.xml, but the JAR which contains this class is not available in web application's CLASSPATH. This is a very important class in Spring MVC framework, as it is used to load your spring configuration files e.g. applicatoin-Context.xml and others, defined in the context-param element of web.xml of your Java spring web application, as shown below :
    <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-Context.xml</param-value>
</context-param>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
Read more »

Friday, June 12, 2015

How to remove elements from ArrayList in Java?

In this Java ArrayList tutorial, you will learn how to remove elements from ArrayList in Java. There are actually two methods to remove an existing element from ArrayList, first by using remove(int index) method, which removes elements with given index, remember index starts with zero in ArrayList. So a call to remove(2) in an ArrayList of {"one", "two", "three"} will remove 3rd element which is "three". Second method to remove element is remove(Object obj), which removes given object from ArrayList. For example a call to remove("two") will remove the second element form ArrayList. Though you should remember to use Iterator or ListIterator remove() method to delete elements while iterating, using ArrayList's remove methods in that case will throw ConcurrentModificationException in Java. Things get little complicated when you are working with ArrayList of integral numbers e.g. ArrayList of integers. If your list contains numbers which are same as indexes e.g. then a call to remove(int index) can be confused with a call to remove(Object obj), for example, if you have an ArrayList containing {1, 2, 3} then a call to remove(2) is ambiguous, because it could be interpreted a call to remove 2, which is second element or a call to remove element at index 2, which is actually 3. If you want to learn more about Collection classes, I suggest you to take a look at one of the all time classic book, Java Generics and Collection. This is the book I refer to refresh my knowledge on the topic.
Read more »

Thursday, June 11, 2015

20 Java ArrayList Interview Questions Answers

In this article, I am going to share some of the good Java Interview questions based upon ArrayList class. I have hardly seen a Java interview without any question from ArrayList, and why not its one of the most popular collection class and every Java developer use it on their day to day work. Another reason of asking question related to ArrayList is that you can ask wide variety of question to really check breadth and depth of candidate's knowledge. To give you some idea about ArrayList, its a collection class which implements List interface. Its an alternative of array data structure whose size you cannot change once created. ArrayList is a dynamic array, which can grow and resize itself. By implementing List interface it also got some properties e.g. ordering, ArrayList keeps element in the order they are inserted and it also provides constant time search operation if you know index of element e.g. get(index) is O(1) operation. This makes ArrayList ideal choice when you are looking to retrieve values based upon index. On contrary to search, adding and removing in ArrayList is little costly because it can trigger re-sizing, which involves creating a new array and copying all elements from old array to new array. I am sure you know the basics but you will learn more by going through some of these frequently asked Java ArrayList questions. You can also take help of the Java Programming Interviews Exposed by Markham, one of the best book to prepare for Java interviews.

Read more »

Wednesday, June 10, 2015

How to reverse words in String Java? [Solution]

In this Java Coding tutorial, you will learn how to reverse words in String. It's also one of the popular coding question, so you will also learn how to take requirement, how to fill gaps in requirement by asking right question. A String is nothing but a sentence, which may contain multiple works, or just contain single word or it may be empty. Your program must produce a String contains word in reverse order , for example if given input is "Java is Great" then your program should return "Great is Java".  Now, if you are a good programmer then you should have some right questions for programmer. Never assume you know everything, even if its looks a simple problem. Always remember "Devil is in detail". Also asking question not only fill the gaps in requirement but also help you to make impression. One of the question candidate should definitely ask is, what constitutes a word here? For purpose of this program, word is nothing but a sequence of non-space characters. Another good question you can ask to Interview is about input, e.g. is it possible for input string to contain leading or trailing spaces? Yes, its possible. However, your reversed string should not any contain leading or trailing spaces. One more important question for Interviewer is about spacing between words, is it possible to have multiple spaces between two words? Yes, it could be possible but you can reduce them to a single space in the reversed string. BTW, if you preparing for programming job interview, you can also take a look at Cracking the Coding Interview: 150 Programming Questions and Solutions, you will not only find some good question on array and String on this book, but also about several other key topics e.g. SQL, database, networking and Java.
Read more »

Tuesday, June 9, 2015

How to Fix java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver [Solved]

Scenario : Your Java program, either standalone or Java web application is trying to connect to Oracle database using type 4 JDBC thin driver "oracle.jdbc.driver.oracledriver", JVM is not able to find this class at runtime. This JAR comes in ojdbc6.jar or ojdbc6_g.jar which is most probably not available in classpath.

Cause : When you connect to Oracle database from Java program, your program loads the implementation of Driver interface provided by the database vendor using class.forName() method, which throws ClassNotFoundException when driver class is not found in classpath. In case of Oracle the driver implementation is oracle.jdbc.driver.oracledriver and "java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver" error indicate that this class is  not available in classpath. Since this class is bundled into ojdbc6.jar, its usually the case of this JAR not present in Classpath
Read more »

Monday, June 8, 2015

MySQL - Creating Data Tables To Use In Selenium WebDriver Test

Before creating tables In MySQL database, It must be Installed In your system. You can read my previous post to know how to download and Install MySQL In windows system. We are going to perform MySQL database testing using selenium WebDriver. So We need to create table Inside
database and need to Insert some data In It manually. Execute bellow given steps.


Step 1 : Connect MySQL Server from command line
  • Open MySQL command line client from Start menu.
  • It will ask you to enter password. Enter your login password which was set during MySQL config step.

  • It will print message as bellow In command prompt. Now you are connected with database.

Step 2 : View available databases In MySQL
To view available databases In mysql, you need to execute bellow given command In command prompt.
  • Execute show databases; command In MySQL command line client as bellow. It will show you list of all available databases.
  • As you can see In above Image, there Is one default database with name "test". We can use It to create our table.
Step 3 : Select database to create table.
Execute bellow given command In MySQL command line to select "test" database for creating table In It.
  • Execute use test command to select "test" database from list.
  • It will show you message Database changed as shown In above Image.
Step 4 : Create table In "test" database.
Now we are going to create new table Inside "test" database. Let's check If there Is any table available In "test" database before creating table In It.
  • Execute show tables; command In command line. It will show you bellow given result.
  • There Is not available any table Inside "test" database. Let's create new table "user" In test database with four columns id, name, city and age.
  • To create "user" table, execute query CREATE TABLE user (id INT(6), name VARCHAR(20), city VARCHAR(20), age INT(6)); In command line as bellow.

  • It will create "user" table Inside "test" database with four columns.
Step 5 : Insert data In "user" table
Now we can Insert data In user table. Execute bellow given queries one by one In MySQL command line client. It will Insert record one by one In "user" table.

  • INSERT INTO user (id, name, city, age) VALUES (1, 'smith', 'London', 25);
  • INSERT INTO user (id, name, city, age) VALUES (2, 'Daniel', 'Boston', 37);
  • INSERT INTO user (id, name, city, age) VALUES (3, 'Anup', 'Delhi', 22);
  • INSERT INTO user (id, name, city, age) VALUES (4, 'Joshua', 'Boston', 33);
  • INSERT INTO user (id, name, city, age) VALUES (5, 'Karan', 'Delhi', 45);
  • INSERT INTO user (id, name, city, age) VALUES (6, 'Karishma', 'Delhi', 21);



Step 6 : view table data
Now we can view "user" table data. 
  • Execute query "select * from user;" to view data from user table.

Now we have data table In MySQL database which we can use In selenium WebDriver test. Next step will tell you how to fetch data from table using select query In test script.