How to Count Number of Words in String - Java Coding Exercise

String is very popular among Interviewer, and you are bound to see some questions on any programming interview, Java Interviews are no exception. Questions based from Java fundamentals like why String is Immutable in Java to questions based on coding skills e.g. reverse String using recursion in Java, String has always troubled candidates. In this article, we will see a similar questions, how to count number of words in Java String. Before jumping to solution, just read below to make sure what a word means here. It's sequence of one or more non-space characters. We will see two examples to find number of words in Java String, first one is based upon pure logic, where it goes through all characters from String and then count each word. Second is more interesting than first one, here we have used regular expression to find all words. We split String by white space, passing \\s+ means greedy search i.e. it includes one or more white spaces.  BTW, this is one of the question I forgot to share when I wrote about Top 20 String coding questions, will include it on that list for sure.

How to Read File in One Line in JDK 7 or Java 8

Reading a file in Java is not simple, it requires lots of boiler plate code, as we have seen in our earlier example of reading text files. Various things had to wrapped e.g. a FileInputStream inside a BufferedReader, loops with weird terminating conditions had to be specified and so forth. From JDK 7 onward,  you can do a lot better. It provides lots of useful classes e.g. Files and Paths to deal with file and their actual path. In this article, we will see how we can read a file in just one line. Of course, your production code won't be like that, especially if you are reading a few gigabytes into memory and want to pay attention to the character set, if you don't specify, by platform's default character encoding will be used.  In short, you will need a little more code, but for quick and dirty file reading this should do the trick. By the way, It wouldn't be a one-liner if it had exception handling. In a production application you would need to deal with the fact that the file isn't there e.g. displaying an error for the user, posting metrics, logging the error etc, but it certainly be lot less boiler code than it used to be.

Top 20 jQuery Interview Questions and Answers

Without a doubt, jQuery has given a much needed boost to JavaScript, a language so useful but equally underrated at times. Before jQuery comes into picture, we used to write lengthy JavaScript code not just for bigger but even for smaller functionality. Those code were at times both difficult to read and maintain. Having written JavaScript before using this excellent library, I realized true power of jQuery, just after using it for a month. Given it's huge popularity, jQuery interview questions are increasingly asked in any web developer interview, not just beginners but also experienced developers, including HTML and JavaScript. Since jQuery is relatively new, most interview questions are asked from core jQuery library including selectors, DOM manipulation and jQuery basics.

How to disable JUnit Test - @Ignore annotation Example

If you are using JUnit 4, then you can use @Ignore annotation to disable a test case; what this means is that, any method which is annotated by @Ignore, will not be executed by JUnit. Why would you want to disable a test? Well, It may be because that particular test is for a functionality which is not yet implemented fully and because of that your build is failing. Like that there could be some other scenarios where you would like to temporarily disable a test or a group of tests. From JUnit 4 onward test methods are annotated with @Test, so if they are also annotated with @Ignore will not be executed as tests. Apart from disabling a single method you can also disable all methods of a class by using @Ignore annotation at class level. For example, If you annotate a class containing test methods with @Ignore and none of the containing tests will be executed. Native JUnit 4 test runners should report the number of ignored tests along with the number of tests that ran and the number of tests that failed. Also worth noting is that @Ignore annotation takes an optional default parameter if you want to record why a test is being ignored, very useful if you are not the only person who is working on that piece of code. If there is a reason to disable a test case, later that can be enabled if reason is already sorted.

Difference between UTF-8, UTF-16 and UTF-32 Character Encoding

Main difference between UTF-8, UTF-16 and UTF-32 character encoding is how many bytes it require to represent a character in memory. UTF-8 uses minimum one byte, while UTF-16 uses minimum 2 bytes. BTW, if character's code point is greater than 127, maximum value of byte then UTF-8 may take 2, 3 o 4 bytes but UTF-16 will only take either two or four bytes. On the other hand, UTF-32 is fixed width encoding scheme and always uses 4 bytes to encode a Unicode code point. Now, let's start with what is character encoding and why it's important? Well, character encoding is an important concept in process of converting byte streams into characters, which can be displayed. There are two things, which are important to convert bytes to characters, a character set and an encoding. Since there are so many characters and symbols in the world, a character set is required to support all those characters. A character set is nothing but list of characters, where each symbol or character is mapped to a numeric value, also known as code points.

On the other hand UTF-16, UTF-32 and UTF-8 are encoding schemes, which describe how these values (code points) are mapped to bytes (using different bit values as a basis; e.g. 16-bit for UTF-16, 32 bits for UTF-32 and 8-bit for UTF-8). UTF stands for Unicode Transformation, which defines an algorithm to map every Unicode code point to a unique byte sequence.

 For example, for character A, which is Latin Capital A, Unicode code point is U+0041, UTF-8 encoded bytes are 41, UTF-16 encoding is 0041 and Java char literal is '\u0041'. In short, you must need a character encoding scheme to interpret stream of bytes, in the absence of character encoding, you cannot show them correctly. Java programming language has extensive support for different charset and character encoding, by default it use UTF-8.

How to Find First and Last element in LinkedList Java - Doubly linked list

In this article you will learn how to get the first and last element of a linked list with the help of getFirst() and getLast() of LinkedList class. If you have programming or even gone to computer science course you probably know what is a linked list? It's a data structure which allows you to store objects in a such a way that you can don't need a big chunk of contiguous memory like another popular data structure array. It work perfectly even if you have a fragmented heap. LinkedList is Java's implementation of this fundamental data structure. There are two types of linked list, singly and doubly linked list, and Java's LinkedList is a doubly linked list. If you are wondering what is difference between a singly and doubly linked list, well in singly linked list you can traverse only in one direction from head to tail, or from first to last element because every node has address of only next node. While in doubly linked list, every node has reference to both previous and next node, thus allows you to traverse in both direction, from head to tail and backwards. You can verify this by yourself by looking at code of java.util.LinkedList in Eclipse, just use shortcut Ctrl + T and type the name, if you have added Java source code in Eclipse, it will open the class. You will find that LinkedList has a private static class called Node, which has reference to both previous and next node.

Difference between Right shift and Unsigned right shift in Java ( >> and >>> )

There are two types of right shift operator in Java >> and >>>,  former is known as right shift and later is known as right shift with zero fill or simply unsigned right shift operator in Java.  Though both of them are known as bit shift operators and moves bits patterns towards right hand side of a bit sequence, there is subtle difference between them. When we use right shift operator i.e. ">>" it keeps sign bit intact i.e. if original number is negative then it will remain negative even after right shift i.e. first or most significant bit never lost, doesn't matter how many times you shift. On the other hand unsigned right shift operator ">>>" doesn't preserve sign of original number and fills the new place with zero, that's why it's known as unsigned right shift operator or simply right shift with zero fill. Since Java represent negative numbers as 2's complement and all of its integral data types except char is signed, it's very important to remember this subtle difference between signed and unsigned right shift operator. This also means that negative numbers in Java has first or most significant bit (the left most) set, i.e. 1, while for positive number this bit is always zero. All these confusions will remain until you see an example of right shift operator and do it by yourself, so what are we waiting for, let's jump into an example.

Constructor vs Init method in Servlet - JEE Interview Question

Can we have Constructor in Java Servlet? or Why do we need constructor in Servlet if there is already an init() method for initializing Servlet, or what is difference between init() method and constructor in Servlet are couple of questions I have seen in various Java web developer interviews. All of these questions are related to role of constructor and init() method in Servlet implementation class. Though I had shared few thoughts on this, when I wrote top 10 Servlet questions for Java programmers,  I thought to cover it in more detail here. In this article, I will try to answer each of these question in detail. Key thing to remember is that Servlet are special in the sense that their life cycle is managed by web container like Tomcat and Jetty. They are responsible for creating instances of Servlet and destroying them when they don't have enough resource or need to support so many instances of Servlets. Let me first answer the question, Can we create constructor in Servlets? and then I will answer why you should be using init() method for Servlet initialization by describing difference between constructor and init() method.

How to Implement linked list in Java with JUnit test Example

In this article, we will learn two things, how to implement a linked list from scratch in Java and how to write a unit test using JUnit framework. Though Java has LinkedList class, which is an implementation of the doubly linked list, its good to know how to implement singly linked list in Java, mostly to practice coding interview questions. Coming to back to writing a unit test, from time to time, I have said that a Java programmer must write unit tests. IMHO, unit testing is the best development practice to improve code quality. Fortunately, Java ecosystem has the luxury of great unit testing frameworks in form of JUnit and TestNG, and every Java developer should take advantage of this. Writing unit test is one of the best programming practice along with code review. It's natural and I had experienced it myself that unit test, not only provides code coverage, but also present unique opportunities for code refactoring. Many times, while writing unit tests, I have discovered better names for my methods and refactored large methods into smaller ones. JUnit tests also helps to organize code and evaluate encapsulation. There is a good chance of you discovering that a particular field or method is exposing implementation detail, and should be abstracted in public method. What all this means is, you, a Java developer, must write unit tests. Since it always helps to start smaller, this JUnit tutorial will present another simple JUnit example to show how to write unit test in Java. In this JUnit tutorial, we will implement a linked list in Java and we will write unit test cases for a linked list. For those, who are not familiar with the linked list, it's one of the fundamental data structure to store objects, like an array, which is also used to store object. By the way, there is much difference between linked list and array data structure, which is subject of another blog post, but the main difference is in the way objects are stored. An array needs contiguous memory, while linked list doesn't need that.

How to Read/Write from RandomAccessFile in Java

Random access file is a special kind of file in Java which allows non-sequential or random access to any location in file. This means you don't need to start from 1st line if you want to read line number 10, you can directly go to line 10 and read. It's similar to array data structure, Just like you can access any element in array by index you can read any content from file by using file pointer. A random access file actually behaves like a large array of bytes stored in file system and that's why its very useful for low latency applications which needs some kind of persistence e.g. in front office trading application and FIX Engine, you can use random access file to store FIX sequence numbers or all open orders. This will be handy when you recover from crash and you need to build your in memory cache to the state just before the crash.  RandomAccessFile provides you ability to read and write into any random access file. When you read content from file, you start with current location of file pointer and pointer is moved forward past how many bytes are read. Similarly when you write data into random access file, it starts writing from current location of file pointer and then advances the file pointer past number of files written. Random access is achieved by setting file pointer to any arbitrary location using seek() method. You can also get current location by calling getFilePointer() method. There are two main ways to read and write data into RandomAccessFile, either you can use Channel e.g. SeekableByteChannel and ByteBuffer class from Java NIO, this allows you to read data from file to byte buffer or write data from byte buffer to random access file. Alternatively you can also use various read() and write() method from RandomAccessFile e.g readBoolean(), readInt(), readLine() or readUTF().  This is a two part Java IO tutorial, in this part we will learn how to read and write String from RandomAccess file in Java without using Java NIO channels and in next part we will learn how to read bytes using ByteBuffer and Channel API. .

How to Filter Collections in Java 8 with Streams and Predicates

Java 8 provides excellent features to support filtering of elements in Java Collections. Prior to Java 8, only better way to filter elements is by using foreach loop or iterating over Collection using Iterator and selecting required object, leaving out rest. Though that approach work, it was very difficult to run them in parallel and take advantage of multiple CPU available in modern day servers. Java 8 provides Streams, which not only makes it easy to run any operation parallel but also support lazy loading and lazy evaluation, which means as soon as filtering condition is satisfied, it stooped doing work, doesn't matter how many object collection contains. You can filter Java Collections like List, Set or Map in Java 8 by using filter() method of Stream class. You first need to obtain stream from Collection by calling stream() method and than you can use filter() method, which takes a Predicate as only argument. Predicate is a functional interface with couple of boolean valued method e.g. test(), which returns boolean true or false. Java 8 uses this method to filter Collection. Just remember that filter doesn't remove elements which matches the condition given in predicate, instead it selects them in output stream. I agree, little bit counter intuitive, select would have been better name for this method, but once you used it couple of times, you will be Ok. For example, if you have list of String and you want another list which contains only long string say whose length is greater than 20 character, you can use filter method to do that and you don't need a loop. Java 8 Stream is very efficient replacement of looping both design and performance wise, because it separates What to do from how to do, just like SQL. Leaving the implementation part to platform.

Top 50 Programmer Phone Interview Questions with Answers

It's 2015 now and from last few years, phone interviews also known as the telephonic round is the single most popular way to screen candidates in a programming job interview. It's easy for both parties to gauge each other, candidate doesn't need to travel to perspective Employer's premises and Interviewer also doesn't need to make any necessary arrangement. This is the second part of my article on programming interview questions, in the first part, I got feedback that it is a little bit heavy on coding based questions and many programmers asked me to share similar list for the telephonic round of programming Interviews. In order to clear telephonic round and proceed to next round, you must be good enough to answer all the questions related to your Job description.