Finding all the indexes of a whole word in a given string using java

Intent

To find all the indexes of a whole word in a given searchable string.

Motivation

Today, I had to write a piece of code in which I had to find all the indexes of a particular keyword in a searchable string. Most of the times, when we have to find index of a keyword in a searchable string we use indexOf method of String class.

For example,


String searchableString = “Don’t be evil. Being evil is bad”;

String keyword = “be”;

So, we can find the index of keyword as


int index = searchableString.indexOf(keyword);

This will give us the index of first occurrence of keyword (“be”). Now suppose, we have to find all the indexes of keyword (“be”), we will have to loop over searchableString and find all the indexes of keyword “be”.

This can be done as follows

	public static void findIndexes(){
		String searchableString = "don’t be evil.being evil is bad";
		String keyword = "be";

		int index = searchableString.indexOf(keyword);
		while (index >=0){
			System.out.println("Index : "+index);
			index = searchableString.indexOf(keyword, index+keyword.length())	;
		}

	}

	public static void main(String[] args) {
		findIndexes();
	}

This program will print :

Index :  6

Index : 14

There is a problem in this code as we should not get “Index : 14” because we are looking for a keyword “be” and the index it has found is from word “being” . This just looks for any occurrence of keyword in the string it does not have to be a whole word. To solve this problem, we will be writing a solution using Regular expressions.

Solution

We have to find out the indexes which correspond to the whole word. For example, we should only get “Index : 6” as that corresponds to the keyword “be” not “Index : 14” as it corresponds to the word “being” .

This can be done as follows :-

WholeWordIndexFinder.java

package org.dailywtf.string;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WholeWordIndexFinder {

	private String searchString;

	public WholeWordIndexFinder(String searchString) {
		this.searchString = searchString;
	}

	public List<IndexWrapper> findIndexesForKeyword(String keyword) {
		String regex = "\\b"+keyword+"\\b";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(searchString);

		List<IndexWrapper> wrappers = new ArrayList<IndexWrapper>();

		while(matcher.find() == true){
			int end = matcher.end();
			int start = matcher.start();
			IndexWrapper wrapper = new IndexWrapper(start, end);
			wrappers.add(wrapper);
		}
		return wrappers;
	}

	public static void main(String[] args) {
		WholeWordIndexFinder finder = new WholeWordIndexFinder("don’t be evil.being evil is bad");
		List<IndexWrapper> indexes = finder.findIndexesForKeyword("be");
		System.out.println("Indexes found "+indexes.size() +" keyword found at index : "+indexes.get(0).getStart());
	}

}

IndexWrapper.java

package org.dailywtf.string;

public class IndexWrapper {

	private int start;
	private int end;

	public IndexWrapper(int start, int end) {
		this.start = start;
		this.end = end;
	}

	public int getEnd() {
		return end;
	}

	public int getStart() {
		return start;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + end;
		result = prime * result + start;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		IndexWrapper other = (IndexWrapper) obj;
		if (end != other.end)
			return false;
		if (start != other.start)
			return false;
		return true;
	}

}

Explanation
First of all a regular expression is built using the keyword. Regex \b defines a word boundary. \b allows you to perform a “whole words only” search using a regular expression in the form of \bword\b.
More information on regex could be found at this link.  Next, we just iterate over the matcher till matcher can find any match. Whenever a match is found an wrapper object is created which contains the start and end position of the keyword.

Using the above code, we can find all the indexes of a keyword in a searchable string.

Anonymous Blogger

Anonymous Blogger

Today, I was thinking why I and many other bloggers write as anonymous blogger without disclosing their correct identity.   I am writing down some reasons which lead me to write in an anonymous manner:-

  1. Fear of not looking stupid: – I feel this is the number one reason why people hide their identity.  This can be related to a blog which does not make sense or poor code examples.
  2. Writing on the topics which you can’t write otherwise: – There are topics on which you don’t want to write with your correct identity like your workplace environment, your manager  J , interview questions and many others. By hiding your identity, you can very easily do this.

HQL which gives number of hours between two timestamps

Intent

To write down a hql (hibernate query language) which gives the difference between two timestamps.

Motivation

Today, i had to write down a hql which should return me the difference between two timestamps. It took me quite a long time to write down the hql query which gives me the correct result. So, i am writing down hql in this blog in order to help any developer who might face this problem.To explain the problem, suppose we have to find out the number of hours before which a user was last updated. The problem seemed quite easy when I first thought about the solution.  The most obvious solution i thought was to use hour() function of hql. So, I wrote down the hql

select hour(current_timestamp – user.lastUpdatedTimeStamp) from com.test.User as user where user.id=1;

It worked but only when both the timestamps are of the same date i.e. if the current_timestamp and lastUpdateTimeStamp are of same date (18th April 2010). This solution does not work if the timestamp are on different date as hour function gives number of hours based on time only, it does not consider dates. So, if current_timestamp is 19-04-2010 11:00:00 and lastUpdatedTimeStamp is 18-04-2010 5:00:00 , it will give answer as 6 which is wrong as number of hour between these timestamps is 30.

Solution

HQL which works is

select

(days(current_timestamp) *24 + hour(current_timestamp)) -( days(user.lastUpdatedTimeStamp)*24 + hour( user.lastUpdatedTimeStamp))

from com.test.User as user where user.id=1;

This hql will give the correct answer as it will add the number of hours corresponding to the date to the number of hours on that particular date.

Mathematically, this will be like this

((19*24 + 11)  -(18*24 +5)) == 467 – 437 = 30

So, we will get the correct answer 30.

The most inspirational video i have ever seen

Yesterday, i saw a great video on youtube.This is the Steve Jobs “Steve Jobs’ 2005 Stanford Commencement Address

Checkout this great video http://www.youtube.com/watch?v=UF8uR6Z6KLc

This video is worth watching million times. I have never seen such a great video.

If any of you have heard any other great presentation please put the link to that in comments.

Learning JavaScript Programming Language Functions Part 3

Intent of My Blog

Today, i heard the third lecture on javascript functions  by Douglas Crockford. This blog is third in this series. Please refer to first and second post regarding the history and statements in javascript.

Functions in JavaScript

Today i have seen the third lecture of the series.Checkout this lecture

Key points from the presentation are:-
  1. function are first class object
  2. function can be passed, returned and shared just like any other value.
  3. function inherit object and store name value pair.
  4. function are container like objects
  5. functions are equivalent to Lambda
  6. Lambda has enormous expressive power
  7. Unlike most power constructs, lambda is secure
  8. function statement var foo = function foo(){// statements to execute}
  9. In JavaScript, one function can contain other functions.
  10. An inner function has access to the variable and parameter of function that it is contained within.
  11. This is called static scoping or lexical scoping
  12. JavaScript also supports Closure
  13. The scope that an inner function enjoys continues even after the parent function has returned.This is called Closure
  14. Closure are one of the most powerful features of JavaScript
  15. JavaScript is the first lambda language to go mainstream
  16. when a function is called with too many arguments, the extra arguments are ignored
  17. When the function is called with too less arguments, the missing values are set to undefined
  18. Methods can be invoked in four ways
  19. Function Form –> functionObject(argument)
  20. Method Form –> thisObject.methodName(arguments) and thisObject[“methodname”](arguments)
  21. Constructor Form –> new Function(“x”,”y”,”return x*y”)
  22. Apply form –> functionObject.apply(thisObject, arguments)
  23. When a function is invoked, it also gets a special parameter called arguments.
  24. arguments contain all of the arguments from the invocation
  25. It is an array like object (it is not a full array)
  26. arguments.length gives the number of arguments passed.
  27. In JavaScript, you can extend the built-in types(like String, Boolean)
  28. Do not use eval function
  29. Built in wrapper types like String, Boolean, Integer are not useful
  30. Global variables are evil
  31. Implied global are evils too.
  32. Always use functional scope.

These were some of the points from the talk.

Learning Javascript Programming Language Part 2

Intent of my Blog

This blog is a second in the series of my learning javascript programming language. In the first blog i discussed and shared the history of the javascript programming language. For learning javascript, i am following Douglas Crockford videos on YUI theater and book “JavaScript: The Definitive Guide 4th Edition”. In this blog, i will share some of the things that i learned about the language.

Get Started

Today i have seen the second lecture of the series. Checkout this lecture

Key Points from the Presentation are :
  1. The statements in javascript are separated from each other with semicolon. If you place each statement on the separate line, javascript allows you to leave the semicolon.But it is a good idea to put semicolon.
  2. Expression statements are expressions which have a side-effect.
  3. Statements discussed are :- if, switch, while, for, throw, try/catch/finally, function, var, return
  4. If statements is the control statement that allows JavaScript to make decisions,or to execute statements conditionally.
  5. If statement is written like this  if(expression) statement
  6. if the expression is null, undefined, 0,”” or NaN it is converted to false.
  7. Switch statement in JavaScript are different from switch statement in C,C++ or java. In those languages, the case expression must be compile time constant.They must evaluate to integer or other integral types and they must evaluate to same type.
  8. JavaScript switch statement is not nearly as efficient as the switch statement in C, C++, and Java. Since the case expressions in those languages are compile-time constants, they never need to be evaluated at runtime as they are in JavaScript. Furthermore, since the case expressions are integral values in C, C++, and Java, the switch statement can often be implemented using a highly efficient “jump table.”
  9. There is a special version of for loop which exists for objects
    for(var name in object){
    of(object.hasOwnProperty(name)){
    // do something
    }
    }
    
  10. In the var statement, if no initial value is specified for a variable, the value of the variable is undefined
  11. throw statement can throw error or any subclass of error
  12. throw can also be useful to throw a string that contains an error message, or a numeric value that represents some sort of error code.
  13. Do not use with statement because the code that uses with is difficult to optimize.
  14. The try/catch/finally statement is JavaScript’s exception-handling mechanism. The try clause of this statement simply defines the block of code whose exceptions are to be handled. The try block is followed by a catch clause, which is a block of statements that are invoked when an exception occurs anywhere within the try block. The catch clause is followed by a finally block containing cleanup code that is guaranteed to be executed, regardless of what happens in the try block. Both the catch and finally blocks are optional, but a try block must be accompanied by at least one of these blocks.
  15. Every function will have a return statement, sometimes return will return some value and sometime it will be return without any expression.
These were some the important points from the talk. I have not covered functions and objects in this blog. I will share those in future posts.

Learning JavaScript Programming Language Part 1

Intent of my Blog

So finally, i have decided to learn “JavaScript Programming Language”, the world most popular language. In my five years of software development career, i have always tried to run away from learning and working on javascript. But today, i have decided that i will start learning javascript from the beginning. So, in this blog series on javascript i will be sharing my learning on javascript.

Get Started

I googled a bit, to find out the best resources to learn javascript and find out the video series by Douglas Crockford.

So, in today’s post i will be writing down the key points from his lecture.I would recommend that you should listen this presentation.

Key Points from the Presentation:-
  1. JavaScript is completely independent of Java.It has nothing to do with java except the name resemblance. (Please listen to presentation to find out why)
  2. It is not a scripting language but a complete Functional Programming Language
  3. It is the most Popular Programming Language
  4. JavaScript has design errors
  5. All the books on JavaScript in market are bad except JavaScript the Definitive Guide 4th Edition.
  6. The first name of JavaScript was LiveScript which was created by Netscape
  7. LiveScript was the first language to be put into the browser.
  8. NetScape and Sun Microsystems joined hands and renamed LiveScript to JavaScript
  9. NetScape and Sun Microsystems joined hands to beat MicroSoft
  10. Microsoft reverse engineered JavaScript to create a language called JScript
  11. JavaScript is a small but sophisticated language
  12. Key Ideas :-
  • Load and go definition – This means that programs are executed as source code as text
  • Loose Typing
  • Object as generic container
  • Prototypal Inheritance — Which means Objects can inherit objects
  • lambda -Function as first class objects
  • Linkage through global variables

13.  When you use parseInt function always use radix parseInt(“08”,10)
14. JavaScript is case sensitive
15. JavaScript syntactically belongs to C family
16. == and != do type coersion
17. === and !== are faster and more reliable.
18. Bitwise operators are slower because JavaScript does not have Integers to first 64 bit floats are converted to 32 bit integer and then reconverted to 64 bit float.

These were some of the important points from the talk.
I will share my learning on javascript as i move along.

Java Puzzlers on local variable initialization

Intent of my blog

Some time back, i posted a blog on common interview questions on overriding.The blog was very popular on dzone so i decided to write some of the java puzzlers on local variable initialization.One thing which should be kept in mind is that Local variables should be initalized before they are used.Knowing this fact try to answer these questions.

Local Variable Initialization Puzzlers

Question1


public class Question1{
 public static void main(String[] args) {
 int x;
 int y = 10;
 if (y == 10) {
 x = y;
 }
 System.out.println("x is " + x);
 }
}

Question 2


class Question2{
 public static void main(String[] args) {
 int x;
 if(true){
 x = 10;
 }
 System.out.println("x is " + x);
 }
}

Question 3


class Question3{
 public static void main(String[] args) {
 int x;
 final int y = 10;
 if(y == 10){
 x = 10;
 }
 System.out.println("x is " + x);

 }
}

Question 4


class Question4{
 static int y = 10;

 public static void main(String[] args) {
 int x ;
 if(y == 10){
 x = 10;
 }
 System.out.println("x is " + x);
 }
}

Question 5


class Question5{
 static final int y = 10;

 public static void main(String[] args) {
 int x ;
 if(y == 10){
 x = 10;
 }
 System.out.println("x is " + x);
 }
}

Again, like the previous post, i am not posting the solutions because i dont want to take away the fun. So, play with these and have fun.

Overriding Question asked in interviews

Intent of my Blog

Overriding is the concept which is very much asked in the interview.In almost every interview i have given or taken overriding questions were present.So, i decided to document all the possible overriding questions.Try out these questions and have fun.

What is Overriding?

According to wikipedia

“Method overriding, in object oriented programming, is a language feature that allows a subclass to provide a specific implementation of a method that is already provided by one of its superclasses. The implementation in the subclass overrides (replaces) the implementation in the superclass.”

Overriding Questions

Question 1

public class OverridingQuestion1 {

 public static void main(String[] args) {
 A a = new A();
 a.execute();
 B b = new B();
 b.execute();
 a = new B();
 a.execute();
 b = (B) new A();
 b.execute();
 }

}

class A {
 public void execute() {
 System.out.println("A");
 }
}

class B extends A {
 @Override
 public void execute() {
 System.out.println("B");
 }
}

Question 2


class A1 {

 private void prepare(){
 System.out.println("Preparing A");
 }
}

class B1 extends A1 {

 public void prepare(){
 System.out.println("Preparing B");
 }
 public static void main(String[] args) {
 A1 a1 = new B1();
 a1.prepare();
 }
}

Question 3

public class OverridingQuestion3 {

 public static void main(String[] args) {
 A2 a2 = new A2();
 System.out.println(a2.i);
 B2 b2 = new B2();
 System.out.println(b2.i);
 a2 = new B2();
 System.out.println(a2.i);
 }

}
class A2{
 int i = 10;

}
class B2 extends A2{
 int i = 20;

}

Question 4


public class OverridingQuestion4 {

 public static void main(String[] args) {
 A3 a3 = new A3();
 a3.execute();
 B3 b3 = new B3();
 b3.execute();
 a3 = new B3();
 a3.execute();
 b3 = (B3)new A3();
 b3.execute();
 }

}

class A3{
 public static void execute(){
 System.out.println("A3");
 }

}
class B3 extends A3{
 public static void execute(){
 System.out.println("B3");
 }
}

Question 5


public class OverridingQuestion5 {

 public static void main(String[] args) {
 A4 a4 = new B4();
 a4.execute();
 }

}

class A4{
 public void execute() throws Exception{
 System.out.println("A");
 }
}
class B4 extends A4{
 @Override
 public void execute(){
 System.out.println("B");
 }
}

As if now i can think of the above 5 questions. If you have any other overriding question, please put that in comment.
I am not posting solution to these questions. So, try these, and post the solution in comments.

Again fallen into java puzzler trap– Another Java Puzzler

Intent of My Blog
Today, while writing a piece of code, i found that i have again fallen into a java trap.This is a java puzzler that i read in java puzzler book.

What is the output of this java puzzler?

public class JavaPuzzler {

public static void main(String[] args) {
JavaPuzzler javaPuzzler = null;
System.out.println(javaPuzzler.get());
}

private static String get(){
return "i am a java puzzler";
}

}

Before reading the answer ,please try running this in eclipse and see whether you got it correct.

Solution

You might think that it should throw NullPointerException because the main method invokes get() method  on local variable which is initialized to null, and you can’t invoke a method on null.

But if you run this program, you will see that it prints “i am a java puzzler” . The reason  is that get() is a static method.