Monday, 11 April 2016

Best Book to Learn Java Programming for Beginners?

There is no doubt that the best book to learn Java for beginners is indeed Head First Java, 2nd Edition. It's interesting, informative and yet easy to read, which is what a beginner wants. The only drawback of this book is that there is no 3rd Edition available. Java has moved a long way since 2nd edition of this book was released. Yes, the core of the Java programming language is not changed much and information given in this book is still relevant and sufficient for anyone who wants to learn Java programming, but an up to date book comprising changes introduced in Java 7 and Java 8 would have been much appreciated. I was hoping for Head First Java 3rd Edition when Java 8 was launched last year, but no update yet. The changes introduced in Java 8 does demand a new edition of the book, but that is for advanced level.
For a beginner, it's important to learn basics of Java before diving into lambda expression and other stuff. Head first Java will give you a head start in Java programming by first explaining What is Java, What is Java's competitive advantage over another popular programming language e.g. C, C++ or Python and What is the best way to learn Java. Once you start reading this book, you will learn very quickly.
Best Book to Learn @Java for Beginners? http://t.co/TG4xls3VPw #Java #Programming #book
— javinpaul (@javinpaul) May 30, 2015



Why is Head First Java the best book to learn Java Programming?
Somebody will definitely ask, why I consider Head First Java as the best book? Did I read this book before recommending? Did I have read any other book to say that Head First Java is the best compared to others? Can they trust my words on Head First Java? Well, Yes I have read Head First Java, not once but twice and thrice. I do read it even now after having 9 years of working experience in Java when I want to refresh some concept. I consider Head First Java, 2nd edition best because of following reasons:
The Head First style of teaching which is full of diagrams, images, and characters.
If you know a picture is worth thousand words, to give you an example from Head First Java book, you might know that abstract methods are methods without body, they have just declaration and how they explain it by just showing a human head without body :)
The content of the book is really great and easy to digest. As a beginner, you would hate reading boring subjective content which is bookish and not in conversational style. Head First Java is not a book, its a teacher with full of conversation.
Head First Java is best because it contains lots of quizzes, fill in the blanks, matching exercise, which forces your mind to work. This helps to retain the knowledge you have acquired by reading book.
Head First Java is full of good examples, which is very important from a beginners point of view. Remember you will not learn by just reading the book, you will learn only if you do examples and exercises given in the book.
Authors, Bert Bates, and Kathy Sierra are respectable and are an authority in the field of Java programming language. They have also authored several other books including SCJP guides which are some of the most recommended books for Java developer looking to get certified. 


Best book to learn Java Programming

Any other Good Book to Learn Java?
I am sure these reasons are enough to explain why I think Head First Java is the best book for beginners or anyone who wants to learn Java. On a similar note, since everyone has different taste and some may not like comic book style of Head First Java and look for a traditional style of Java programming book to learn, they can try Core Java, Volume 1 and 2 by Cay S. Horstmann. That book is also a gem and gives comprehensive knowledge of Java programming in an easy way. An author is very renowned and I love his writing style, you won't feel bored while reading his book.



Best book to learn Java
No matter which book you choose to learn Java programming, you should write Java programs, use an IDE like Eclipse or Netbeans because busy developers learn faster than those who just read books. 

All the best and don't forget to come back here if you face any problem while learning Java :)


Update 7th February 2016
Cay S. Horstmann, the author of popular Java 8 book, Java SE 8 for Really Impatient and the classic two-volume introduction of Java programming language has come up with another masterpiece to teach core Java, including Java SE 8. The
 Core Java for the Impatient 1st Edition by Cay S. Horstmann is a complete but concise guide to Java SE 8. It covers all important material of Java programming language, but it's presented in small chunks organized for quick access and easy understanding. I am not sure if it can replace Head First Java but at the moment, it certainly look the best and most updated book to learn Java for beginners.

Best book to learn Java programming


P.S.
 If  you are someone who wants to learn from more than one author and looking for a comprehensive guide on the particular topic, then check my post about 9 books Every Java Developer Should Read. You will find books about multi-threading, Java Generics and Collections,  Design Pattern and several other important topics important for Java developers.

Read More »

java.lang.IllegalStateException: getOutputStream() has already been called for this response

This error comes when you call include() or forward() method after calling  the getOutputStream() from ServletResponse object and writing into it.  This error is similar to java.lang.IllegalStateException: getWriter() has already been called for this response error, which we have seen in the earlier article.

This is the exception:
org.apache.jasper.JasperException: java.lang.IllegalStateException: getOutputStream() has already been called for this response
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:424)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
HelloServlet.doGet(HelloServlet.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)

and here is the root cause :


java.lang.IllegalStateException: getOutputStream() has already been called for this response
org.apache.catalina.connector.Response.getWriter(Response.java:611)
org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:198)
javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:112)
org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:180)
org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:118)
org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:77)
org.apache.jsp.hello_jsp._jspService(hello_jsp.java:80)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
HelloServlet.doGet(HelloServlet.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)


If you look at the stack trace it points to 
HelloServlet class, which is our Servlet, the line 25 of HelloServlet seems to be causing the problem.

You can see that we are calling the 
include() method after calling the getOutputStream() on Servlet object. Just comment out the call to getOutputStream() and everything will be Ok.  To learn more about Servlet and JSP,  read Head First Servlet and JSP, one of the best books from last 10 years for learning JSP and Servlet.


Here is the complete Java Servlet for your testing, you can run this Servlet into Tomcat right from your Eclipse IDE.

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String userAgent = req.getHeader("user-agent");
        String clientBrowser = "Not known!";
        if (userAgent != null) {
            clientBrowser = userAgent;
        }
        req.setAttribute("client.browser", clientBrowser);
        //req.getRequestDispatcher("/hello.jsp").forward(req, resp);

        resp.getOutputStream().println("This is written from Servlet");
        req.getRequestDispatcher("/hello.jsp").include(req, resp);
    }

}

That's all about java.lang.IllegalStateException: getOutputStream() has already been called for this response error in Servlet. You have learned what cause this error and how to fix this. In short, this error comes when you call the
include() or forward() method after committing the response or by calling the getOutputStream() on the response object. 
Read More »

How to convert java.util.Date to java.sql.Timestamp in Java - JDBC Example

You can convert java.util.Date tojava.sql.Timestamp by first taking the long millisecond value using the getTime() method ofDate class and then pass that value to the constructor of Timestamp object. Yes, it's as simple as that. For better code reusability and maintenance, you can create a DateUtils or MappingUtilsclass to keep these kinds of utility or mapping functions. Now, the questions comes, why do you need to convert java.util.Date to java.sql.Timestamp? Well, If you are storing date values to database using JDBC, you need to convert a java.util.Date to its equivalent java.sql.Timestamp value. Even though both of them represent date + time value and can be stored in DATETIME SQL type in Microsoft SQl Server database or equivalent in other databases like Oracle or MySQL, there is no method in JDBC API which takes thejava.util.Date object. Instead, you have got three separate methods to set DATE, TIME, and TIMESTAMP in the java.sql package.


Anyway, It's easy to convert a java.util.Date object to java.sql.Timestamp in Java, all you need to do is call the getTime() method to get the long value from 
java.util.Date object and pass it tojava.sql.Timestamp constructor, as shown below:


public Timestamp getTimestamp(java.util.Date date){
  return date == null ? null : new java.sql.Timestamp(date.getTime());
}

Here I am using the ternary operator of Java to first check if the date is null, if yes then I am returning
null, but if it's not null then I am getting the long millisecond value by calling date.getTime() and constructing a Timestamp object. Remember, similar to Hashtable, Timestamp also doesn't use camel case, it's Timestamp and not TimeStamp.



Using ternary operator is also a nice trick to prevent null pointer exception in Java code, without losing readability or adding more lines of code.


Worth noting, Timestamp is a subclass of java.util.Date but you cannot pass a Timestamp instance where a 
java.util.Date is expected because Timestamp class violates Liskov Substitution Principle. According to which subclass doesn't honor the superclass contract. You can read Clean Code by Uncle Bob Martin to learn more about Liskov Substitution principle and other object-oriented design principles.


Java Program to convert Date to Timestamp in JDBC
Now, let's see the Java program to show how you can convert a Date value to Timestamp value for storing into the database using JDBC API. Remember, if you happen to use both java.sql.Date and java.util.Date on same class then uses full name i.e. with the package to avoid ambiguity e.g. java.sql.Date


import java.sql.Timestamp;
import java.util.Date;

/**
 * Java Program to convert java.util.Date to java.sql.Timestamp
 *
 * @author WINDOWS 8
 */
public class DateToTimeStamp {

    public static void main(String args[]) {

        Date today = new Date();

        // converting date to Timestamp in JDBC
        Timestamp timestamp = new Timestamp(today.getTime());
        Timestamp t2 = getTimestamp(today);

        System.out.println("date: " + today);
        System.out.println("timestamp: " + timestamp);
        System.out.println("timestamp2: " + t2);

    }

    /**
     * Utility method to convert Date to Timestamp in Java
     * @param date
     * @return Timestamp
     */
    public static Timestamp getTimestamp(Date date) {
        return date == null ? null : new java.sql.Timestamp(date.getTime());
    }

}

Output
date: Sat Mar 12 10:53:26 GMT+08:00 2016
timestamp: 2016-03-12 10:53:26.996
timestamp2: 2016-03-12 10:53:26.996


That's all about how to convert java.util.Date to java.sql.Timestamp in Java. You need this conversion while storing Date values e.g. date of birth, maturity date etc into database table where column type is DATETIME. Just remember that similar to Hashtable, Timestamp also doesn't use capital case and if you happen to use both Date classes from java.sql and java.util package in the same class then use full name e.g. 
java.util.Date for util date and java.sql.Date for SQL Date.

Read More »

How to Convert String to LocalDateTime in Java 8


Suppose you have a date time String "2016-03-04: 11:01:20" and you want to convert this into aLocalDateTime object of Java 8 new date and time API, how do you do that? Well, if you have worked previously with String and Date then you know that you can parse String to Date in Java. Prior to Java 8, we used to use SimpleDateFormat, which was mutable and not thread-safe, and advised not to be shared between threads. In Java 8, you can use 
theDateTimeFormatter class to convert String to LocalDateLocalTime or LocalDateTime. Unlike SimpleDateFormat, 
the DateTimeFormatter is immutable and thread-safe and you can use it as a static variable 
for sharing and reuse. It also comes with pre-defined date time format e.g. ISO-8601 format. The ISO_LOCAL_DATE_TIME formats or parses a date-time without an offset, such 
as '2016-03-04T10:15:30'.


In this article, I'll show you how to convert a String to LocalDateTime in Java 8, and 
then back to a formatted String, but you can also check out Java SE 8 for Really Impatient 
to learn more about new Date and Time API, which is quite vast.

Java 8 String to Date conversion example


Converting String to LocalDateTime

To create a LocalDateTime object from a string you can use the static LocalDateTime.parse()method. It takes a String and a DateTimeFormatter as a parameter. The DateTimeFormatter is used to specify the date/time pattern. You can use 
predefined format e.g. ISO_LOCAL_DATE_TIME or can specify by yourself as String into the 
second parameter. If you are new to formatting instructions, see here.
String str = "2016-03-04 11:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

If your String contains seconds as well e.g. "2016-03-04 11:30: 40", then you can change 
your date time format to yyyy-MM-dd HH:mm:ss" as shown below:
String str = "2016-03-04 11:30: 40";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

Here is is another example of formatting dates in Java 8:
DateTimeFormatter Example in Java 8


That's all about how to convert String to LocalDateTime in Java 8. As I said, you can use thejava.time.DateTimeFormatter class for parsing and formatting String in Java 8. UnlikeDateFormat and SimpleDateFormat of old date and time API, this class is both 
immutable and thread-safe, and you can also store it into a static variable.

In the next part of this tutorial, I'll show you how to convert LocalDateTime to String in Java by formatting date into different patterns.

Other Date and Time Tutorials for curious developers:
  • How to convert util Date to LocalDateTime in Java 8? (solution)
  • How to convert java.util.Date to java.sql.Date in JDBC? (solution)
  • How to display dates in different timezones in Java? (answer)
  • How to parse String to Date in multithreading using Joda Time? (example)
  • How to get the current date and time in Java? (example)
Read More »

Java Interview Programs



  1. Find out duplicate number between 1 to N numbers.
  2. Find out middle index where sum of both ends are equal.
  3. Write a singleton class.
  4. Write a program to create deadlock between two threads.
  5. Write a program to reverse a string using recursive algorithm.
  6. Write a program to reverse a number.
  7. Write a program to convert decimal number to binary format.
  8. Write a program to find perfect number or not.
  9. Write a program to implement ArrayList.
  10. Write a program to find maximum repeated words from a file.
  11. Wrie a program to find out duplicate characters in a string.
  12. Write a program to find top two maximum numbers in a array.
  13. Write a program to sort a map by value.
  14. Write a program to find common elements between two arrays.
  15. How to swap two numbers without using temporary variable?
  16. Write a program to print fibonacci series.
  17. Write a program to find sum of each digit in the given number using recursion.
  18. Write a program to check the given number is a prime number or not?
  19. Write a program to find the given number is Armstrong number or not?
  20. Write a program to convert binary to decimal number.
  21. Write a program to check the given number is binary number or not?
  22. Write a program for Bubble Sort in java.
  23. Write a program for Insertion Sort in java.
  24. Write a program to implement hashcode and equals.
  25. How to get distinct elements from an array by avoiding duplicate elements?
  26. Write a program to get distinct word list from the given file.
  27. Write a program to get a line with max word count from the given file.
  28. Write a program to convert string to number without using Integer.parseInt() method.
  29. Write a program to find two lines with max characters in descending order.
  30. Write a program to find the sum of the first 1000 prime numbers.
  31. Find longest substring without repeating characters.
  32. Write a program to remove duplicates from sorted array.
  33. How to sort a Stack using a temporary Stack?
Read More »

Monday, 4 April 2016

The Path to Higher Education Through the Eyes of Search

The Path to Higher Education Through the Eyes of Search

Like many sectors, education can be evaluated in part by its performance in Google search queries. In this Hangout On Air, Jen Howard, Google's Education Industry Director, discusses how the education landscape fared in search during the third quarter of 2013. This includes the fact that demand for education maintained growth, traditional schools had a 7% year-over-year increase and nursing topped the fastest-growing program terms.
Published
October 2013
Topics
 
 
 Across all the major categories that we evaluate, growth continued to happen in Q3.
- Jennifer Howard, Director of Education, Google
Read More »

Wednesday, 30 March 2016

7)Write a Java Program that simulates a Traffic Light. The program lets the use select one of three lights :red, yellow or Green with radiobuttons.On selecting radio button, an appropriate message with “stop” or “Ready” or “GO” should appear above the button in selected color.Intially ,there is no message shown.

PDF FILES DOWNLOAD


CLICK HERE TO DOWNLOAD







NETBEANS PROJECT


CLICK HERE TO DOWNLOAD

Read More »