tag:blogger.com,1999:blog-10107327812034441092024-03-13T22:12:48.251+05:30Deepu Mohan Puthrote - A Technology EnthusiastDeepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comBlogger69125tag:blogger.com,1999:blog-1010732781203444109.post-33584300908014378512016-02-02T02:38:00.001+05:302016-02-02T03:42:18.221+05:30Top 10 Most Common Mistakes That Java Developers Make: A Java Beginner’s Tutorial<div dir="ltr" style="text-align: left;" trbidi="on">
<p>Java is a programming language that <a href="http://www.oracle.com/technetwork/java/javase/overview/javahistory-index-198355.html">was initially developed for interactive television</a>, but over time it has become widespread over everywhere software can be used. Designed with the notion of object-oriented programming, abolishing the complexities of other languages such as C or C++, garbage collection, and an architecturally agnostic virtual machine, Java created a new way of programming. Moreover, it has a gentle learning curve and appears to successfully adhere to its own moto - “Write once, run everywhere”, which is almost always true; but Java problems are still present. I’ll be addressing ten Java problems that I think are the most common mistakes.</p>
<h3 style="text-align: left;">
Common Mistake #1: Neglecting Existing Libraries</h3>
<p>It’s definitely a mistake for <a href="http://www.toptal.com/java">Java Developers</a> to ignore the innumerable amount of libraries written in Java. Before reinventing the wheel, try to search for available libraries - many of them have been polished over the years of their existence and are free to use. These could be logging libraries, like logback and Log4j, or network related libraries, like Netty or Akka. Some of the libraries, such as Joda-Time, have become a de facto standard.</p>
<p>The following is a personal experience from one of my previous projects. The part of the code responsible for HTML escaping was written from scratch. It was working well for years, but eventually it encountered a user input which caused it to spin into an infinite loop. The user, finding the service to be unresponsive, attempted to retry with the same input. Eventually, all the CPUs on the server allocated for this application were being occupied by this infinite loop. If the author of this naive HTML escape tool had decided to use one of the well known libraries available for HTML escaping, such as <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/html/HtmlEscapers.html">HtmlEscapers</a> from <a href="https://github.com/google/guava">Google Guava</a>, this probably wouldn’t have happened. At the very least, true for most popular libraries with a community behind it, the error would have been found and fixed earlier by the community for this library.</p>
<h3 style="text-align: left;">Common Mistake #2: Missing the ‘break’ Keyword in a Switch-Case Block</h3>
<p>These Java issues can be very embarrassing, and sometimes remain undiscovered until run in production. Fallthrough behavior in switch statements is often useful; however, missing a “break” keyword when such behavior is not desired can lead to disastrous results. If you have forgotten to put a “break” in “case 0” in the code example below, the program will write “Zero” followed by “One”, since the control flow inside here will go through the entire “switch” statement until it reaches a “break”. For example:</p>
<pre>
<code class="java">
public static void switchCasePrimer() {
int caseIndex = 0;
switch (caseIndex) {
case 0:
System.out.println("Zero");
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
default:
System.out.println("Default");
}
}
</code>
</pre>
<p>In most cases, the cleaner solution would be to use polymorphism and move code with specific behaviors into separate classes. Java mistakes such as this one can be detected using static code analyzers, e.g. <a href="http://findbugs.sourceforge.net/">FindBugs</a> and <a href="http://pmd.sourceforge.net/">PMD</a>.</p>
<h3 style="text-align: left;">Common Mistake #3: Forgetting to Free Resources</h3>
<p>Every time a program opens a file or network connection, it is important for Java beginners to free the resource once you are done using it. Similar caution should be taken if any exception were to be thrown during operations on such resources. One could argue that the FileInputStream has a finalizer that invokes the close() method on a garbage collection event; however, since we can’t be sure when a garbage collection cycle will start, the input stream can consume computer resources for an indefinite period of time. In fact, there is a really useful and neat statement introduced in Java 7 particularly for this case, called <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html">try-with-resources</a>:</p>
<pre>
<code class="java">
private static void printFileJava7() throws IOException {
try(FileInputStream input = new FileInputStream("file.txt")) {
int data = input.read();
while(data != -1){
System.out.print((char) data);
data = input.read();
}
}
}
</code>
</pre>
<p>This statement can be used with any object that implements the AutoClosable interface. It ensures that each resource is closed by the end of the statement.</p>
<h3 style="text-align: left;">Common Mistake #4: Memory Leaks</h3>
<p>Java uses automatic memory management, and while it’s a relief to forget about allocating and freeing memory manually, it doesn’t mean that a beginning Java developer should not be aware of how memory is used in the application. Problems with memory allocations are still possible. As long as a program creates references to objects that are not needed anymore, it will not be freed. In a way, we can still call this memory leak. Memory leaks in Java can happen in various ways, but the most common reason is everlasting object references, because the garbage collector can’t remove objects from the heap while there are still references to them. One can create such a reference by defining class with a static field containing some collection of objects, and forgetting to set that static field to null after the collection is no longer needed. Static fields are considered GC roots and are never collected.</p>
<p>Another potential reason behind such memory leaks is a group of objects referencing each other, causing circular dependencies so that the garbage collector can’t decide whether these objects with cross-dependency references are needed or not. Another issue is leaks in non-heap memory when JNI is used.</p>
<p>The primitive leak example could look like the following:</p>
<pre>
<code class="java">
final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
final Deque<BigDecimal> numbers = new LinkedBlockingDeque<>();
final BigDecimal divisor = new BigDecimal(51);
scheduledExecutorService.scheduleAtFixedRate(() -> {
BigDecimal number = numbers.peekLast();
if (number != null && number.remainder(divisor).byteValue() == 0) {
System.out.println("Number: " + number);
System.out.println("Deque size: " + numbers.size());
}
}, 10, 10, TimeUnit.MILLISECONDS);
scheduledExecutorService.scheduleAtFixedRate(() -> {
numbers.add(new BigDecimal(System.currentTimeMillis()));
}, 10, 10, TimeUnit.MILLISECONDS);
try {
scheduledExecutorService.awaitTermination(1, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
</code>
</pre>
<p>This example creates two scheduled tasks. The first task takes the last number from a deque called “numbers” and prints the number and deque size in case the number is divisible by 51. The second task puts numbers into the deque. Both tasks are scheduled at a fixed rate, and run every 10 ms. If the code is executed, you’ll see that the size of the deque is permanently increasing. This will eventually cause the deque to be filled with objects consuming all available heap memory. To prevent this while preserving the semantics of this program, we can use a different method for taking numbers from the deque: “pollLast”. Contrary to the method “peekLast”, “pollLast” returns the element and removes it from the deque while “peekLast” only returns the last element.</p>
<p>To learn more about memory leaks in Java, please refer to article on <a href="http://www.toptal.com/java/hunting-memory-leaks-in-java">Toptal that demystified this problem</a>.</p>
<h3 style="text-align: left;">Common Mistake #5: Excessive Garbage Allocation</h3>
<p>Excessive garbage allocation may happen when the program creates a lot of short-lived objects. The garbage collector works continuously, removing unneeded objects from memory, which impacts applications’ performance in a negative way. One simple example:</p>
<pre>
<code class="java">
String oneMillionHello = "";
for (int i = 0; i < 1000000; i++) {
oneMillionHello = oneMillionHello + "Hello!";
}
System.out.println(oneMillionHello.substring(0, 6));
</code>
</pre>
<p>In Java, strings are immutable. So, on each iteration a new string is created. To address this we should use a mutable StringBuilder:</p>
<pre>
<code class="java">
StringBuilder oneMillionHelloSB = new StringBuilder();
for (int i = 0; i < 1000000; i++) {
oneMillionHelloSB.append("Hello!");
}
System.out.println(oneMillionHelloSB.toString().substring(0, 6));
</code>
</pre>
<p>While the first version requires quite a bit of time to execute, the version that uses StringBuilder produces a result in a significantly less amount of time.</p>
<h3 style="text-align: left;">Common Mistake #6: Using Null References without Need</h3>
<p>Avoiding excessive use of null is a good practice. For example, it’s preferable to return empty arrays or collections from methods instead of nulls, since it can help prevent NullPointerException.</p>
<p>Consider the following method that traverses a collection obtained from another method, as shown below:</p>
<pre>
<code class="java">
List<String> accountIds = person.getAccountIds();
for (String accountId : accountIds) {
processAccount(accountId);
}
</code>
</pre>
<p>If getAccountIds() returns null when a person has no account, then NullPointerException will be raised. To fix this, a null-check will be needed. However, if instead of a null it returns an empty list, then NullPointerException is no longer a problem. Moreover, the code is cleaner since we don’t need to null-check the variable accountIds.</p>
<p>To deal with other cases when one wants to avoid nulls, different strategies may be used. One of these strategies is to use Optional type that can either be an empty object or a wrap of some value:</p>
<pre>
<code class="java">
Optional<String> optionalString = Optional.ofNullable(nullableString);
if(optionalString.isPresent()) {
System.out.println(optionalString.get());
}
</code>
</pre>
<p>In fact, Java 8 provides a more concise solution:</p>
<pre>
<code class="java">
Optional<String> optionalString = Optional.ofNullable(nullableString);
optionalString.ifPresent(System.out::println);
</code>
</pre>
<p>Optional type has been a part of Java since version 8, but it has been well known for a long time in the world of functional programming. Prior to this, it was available in Google Guava for earlier versions of Java.</p>
<h3 style="text-align: left;">Common Mistake #7: Ignoring Exceptions</h3>
<p>It is often tempting to leave exceptions unhandled. However, the best practice for beginner and experienced Java developers alike is to handle them. Exceptions are thrown on purpose, so in most cases we need to address the issues causing these exceptions. Do not overlook these events. If necessary, you can either rethrow it, show an error dialog to the user, or add a message to the log. At the very least, it should be explained why the exception has been left unhandled in order to let other developers know the reason.</p>
<pre>
<code class="java">
selfie = person.shootASelfie();
try {
selfie.show();
} catch (NullPointerException e) {
// Maybe, invisible man. Who cares, anyway?
}
</code>
</pre>
<p>A clearer way of highlighting an exceptions’ insignificance is to encode this message into the exceptions’ variable name, like this:</p>
<pre>
<code class="java">
try { selfie.delete(); } catch (NullPointerException unimportant) { }
</code>
</pre>
<h3 style="text-align: left;">Common Mistake #8: Concurrent Modification Exception</h3>
<p>This exception occurs when a collection is modified while iterating over it using methods other than those provided by the iterator object. For example, we have a list of hats and we want to remove all those that have ear flaps:</p>
<pre>
<code class="java">
List<IHat> hats = new ArrayList<>();
hats.add(new Ushanka()); // that one has ear flaps
hats.add(new Fedora());
hats.add(new Sombrero());
for (IHat hat : hats) {
if (hat.hasEarFlaps()) {
hats.remove(hat);
}
}
</code>
</pre>
<p>If we run this code, “ConcurrentModificationException” will be raised since the code modifies the collection while iterating it. The same exception may occur if one of the multiple threads working with the same list is trying to modify the collection while others iterate over it. Concurrent modification of collections in multiple threads is a natural thing, but should be treated with usual tools from the concurrent programming toolbox such as synchronization locks, special collections adopted for concurrent modification, etc. There are subtle differences to how this Java issue can be resolved in single threaded cases and multithreaded cases. Below is a brief discussion of some ways this can be handled in a single threaded scenario:</p>
<h2 style="text-align: left;">Collect objects and remove them in another loop</h2>
<p>Collecting hats with ear flaps in a list to remove them later from within another loop is an obvious solution, but requires an additional collection for storing the hats to be removed:</p>
<pre>
<code class="java">
List<IHat> hatsToRemove = new LinkedList<>();
for (IHat hat : hats) {
if (hat.hasEarFlaps()) {
hatsToRemove.add(hat);
}
}
for (IHat hat : hatsToRemove) {
hats.remove(hat);
}
</code>
</pre>
<h2 style="text-align: left;">Use Iterator.remove method</h2>
<p>This approach is more concise, and it doesn’t need an additional collection to be created:</p>
<pre>
<code class="java">
Iterator<IHat> hatIterator = hats.iterator();
while (hatIterator.hasNext()) {
IHat hat = hatIterator.next();
if (hat.hasEarFlaps()) {
hatIterator.remove();
}
}
</code>
</pre>
<h2 style="text-align: left;">Use ListIterator’s methods</h2>
<p>Using the list iterator is appropriate when the modified collection implements List interface. Iterators that implement ListIterator interface support not only removal operations, but also add and set operations. ListIterator implements the Iterator interface so the example would look almost the same as the Iterator remove method. The only difference is the type of hat iterator, and the way we obtain that iterator with the “listIterator()” method. The snippet below shows how to replace each hat with ear flaps with sombreros using “ListIterator.remove” and “ListIterator.add” methods:</p>
<pre>
<code class="java">
IHat sombrero = new Sombrero();
ListIterator<IHat> hatIterator = hats.listIterator();
while (hatIterator.hasNext()) {
IHat hat = hatIterator.next();
if (hat.hasEarFlaps()) {
hatIterator.remove();
hatIterator.add(sombrero);
}
}
</code>
</pre>
<p>With ListIterator, the remove and add method calls can be replaced with a single call to set:</p>
<pre>
<code class="java">
IHat sombrero = new Sombrero();
ListIterator<IHat> hatIterator = hats.listIterator();
while (hatIterator.hasNext()) {
IHat hat = hatIterator.next();
if (hat.hasEarFlaps()) {
hatIterator.set(sombrero); // set instead of remove and add
}
}
</code>
</pre>
<br/>
<p>Use stream methods introduced in Java 8 With Java 8, programmers have the ability to transform a collection into a stream and filter that stream according to some criteria. Here is an example of how stream api could help us filter hats and avoid “ConcurrentModificationException”.</p>
<pre>
<code class="java">
hats = hats.stream().filter((hat -> !hat.hasEarFlaps()))
.collect(Collectors.toCollection(ArrayList::new));
</code>
</pre>
<p>The “Collectors.toCollection” method will create a new ArrayList with filtered hats. This can be a problem if the filtering condition were to be satisfied by a large number of items, resulting in a large ArrayList; thus, it should be use with care. Use List.removeIf method presented in Java 8 Another solution available in Java 8, and clearly the most concise, is the use of the “removeIf” method:</p>
<pre>
<code class="java">
hats.removeIf(IHat::hasEarFlaps);
</code>
</pre>
<p>That’s it. Under the hood, it uses “Iterator.remove” to accomplish the behavior.</p>
<h2 style="text-align: left;">Use specialized collections</h2>
<p>If at the very beginning we decided to use “CopyOnWriteArrayList” instead of “ArrayList”, then there would have been no problem at all, since “CopyOnWriteArrayList” provides modification methods (such as set, add, and remove) that don’t change the backing array of the collection, but rather create a new modified version of it. This allows iteration over the original version of the collection and modifications on it at the same time, without the risk of “ConcurrentModificationException”. The drawback of that collection is obvious - generation of a new collection with each modification.</p>
<p>There are other collections tuned for different cases, e.g. “CopyOnWriteSet” and “ConcurrentHashMap”.</p>
<p>Another possible mistake with concurrent collection modifications is to create a stream from a collection, and during the stream iteration, modify the backing collection. The general rule for streams is to avoid modification of the underlying collection during stream querying. The following example will show an incorrect way of handling a stream:</p>
<pre>
<code class="java">
List<IHat> filteredHats = hats.stream().peek(hat -> {
if (hat.hasEarFlaps()) {
hats.remove(hat);
}
}).collect(Collectors.toCollection(ArrayList::new));
</code>
</pre>
<br />
<p>The method peek gathers all the elements and performs the provided action on each one of them. Here, the action is attempting to remove elements from the underlying list, which is erroneous. To avoid this, try some of the methods described above.</p>
<h3 style="text-align: left;">Common Mistake #9: Breaking Contracts</h3>
<p>Sometimes, code that is provided by the standard library or by a third-party vendor relies on rules that should be obeyed in order to make things work. For example, it could be hashCode and equals contract that when followed, makes working guaranteed for a set of collections from the Java collection framework, and for other classes that use hashCode and equals methods. Disobeying contracts isn’t the kind of error that always leads to exceptions or breaks code compilation; it’s more tricky, because sometimes it changes application behavior without any sign of danger. Erroneous code could slip into production release and cause a whole bunch of undesired effects. This can include bad UI behavior, wrong data reports, poor application performance, data loss, and more. Fortunately, these disastrous bugs don’t happen very often. I already mentioned the hashCode and equals contract. It is used in collections that rely on hashing and comparing objects, like HashMap and HashSet. Simply put, the contract contains two rules:</p>
<p>If two objects are equal, then their hash codes should be equal.</p>
<p>If two objects have the same hash code, then they may or may not be equal.</p>
<p>Breaking the contract’s first rule leads to problems while attempting to retrieve objects from a hashmap. The second rule signifies that objects with the same hash code aren’t necessarily equal. Let us examine the effects of breaking the first rule:</p>
<pre>
<code class="java">
public static class Boat {
private String name;
Boat(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Boat boat = (Boat) o;
return !(name != null ? !name.equals(boat.name) : boat.name != null);
}
@Override
public int hashCode() {
return (int) (Math.random() * 5000);
}
}
</code>
</pre>
<p>As you can see, class Boat has overridden equals and hashCode methods. However, it has broken the contract, because hashCode returns random values for the same object every time it’s called. The following code will most likely not find a boat named “Enterprise” in the hashset, despite the fact that we added that kind of boat earlier:</p>
<pre>
<code class="java">
public static void main(String[] args) {
Set<Boat> boats = new HashSet<>();
boats.add(new Boat("Enterprise"));
System.out.printf("We have a boat named 'Enterprise' : %b\n", boats.contains(new Boat("Enterprise")));
}
</code>
</pre>
<p>Another example of contract involves the finalize method. Here is a quote from the official java documentation describing its function:</p>
<p>The general contract of finalize is that it is invoked if and when the JavaTM virtual machine has determined that there is no longer any means by which this object can be accessed by any thread (that has not yet died), except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.</p>
<p>One could decide to use the finalize method for freeing resources like file handlers, but that would be a bad idea. This is because there’s no time guarantees on when finalize will be invoked, since it’s invoked during the garbage collection, and GC’s time is indeterminable.</p>
<h3 style="text-align: left;">Common Mistake #10: Using Raw Type Instead of a Parameterized One</h3>
<p>Raw types, according to Java specifications, are types that are either not parametrized, or non-static members of class R that are not inherited from the superclass or superinterface of R. There were no alternatives to raw types until generic types were introduced in Java. It supports generic programming since version 1.5, and generics were undoubtedly a significant improvement. However, due to backward compatibility reasons, a pitfall has been left that could potentially break the type system. Let’s look at the following example:</p>
<pre>
<code class="java">
List listOfNumbers = new ArrayList();
listOfNumbers.add(10);
listOfNumbers.add("Twenty");
listOfNumbers.forEach(n -> System.out.println((int) n * 2));
</code>
</pre>
<p>Here we have a list of numbers defined as a raw ArrayList. Since its type isn’t specified with type parameter, we can add any object into it. But in the last line we cast elements to int, double it, and print the doubled number to standard output. This code will compile without errors, but once running it will raise a runtime exception because we attempted to cast a string to an integer. Obviously, the type system is unable to help us write safe code if we hide necessary information from it. To fix the problem we need to specify the type of objects we’re going to store in the collection:</p>
<pre>
<code class="java">
List<Integer> listOfNumbers = new ArrayList<>();
listOfNumbers.add(10);
listOfNumbers.add("Twenty");
listOfNumbers.forEach(n -> System.out.println((int) n * 2));
The only difference from the original is the line defining the collection:
List<Integer> listOfNumbers = new ArrayList<>();
</code>
</pre>
<p>The fixed code wouldn’t compile because we are trying to add a string into a collection that is expected to store integers only. The compiler will show an error and point at the line where we are trying to add the string “Twenty” to the list. It’s always a good idea to parametrize generic types. That way, the compiler is able to make all possible type checks, and the chances of runtime exceptions caused by type system inconsistencies are minimized.</p>
<h3 style="text-align: left;">Conclusion</h3>
<p>Java as a platform simplifies many things in software development, relying both on sophisticated JVM and the language itself. However, its features, like removing manual memory management or decent OOP tools, don’t eliminate all the problems and issues a regular Java developer faces. As always, knowledge, practice and Java tutorials like this are the best means to avoid and address application errors - so know your libraries, read java, read JVM documentation, and write programs. Don’t forget about static code analyzers either, as they could point to the actual bugs and highlight potential bugs.</p>
This article was originally published on <a href="http://www.toptal.com/java/top-10-most-common-java-development-mistakes">Toptal</a>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comLondon, UK51.5073509 -0.1277582999999822351.1912379 -0.77320529999998222 51.8234639 0.51768870000001777tag:blogger.com,1999:blog-1010732781203444109.post-6239877407571300272014-04-20T05:55:00.001+05:302014-09-13T21:47:49.103+05:30SOLID design principle<p>When it comes to OO designing, it is a good idea to have a strategy to follow. A strategy allows you to think and organize ideas in a particular fashion that is comfortable to you. I’ve found SOLID principle easy enough for beginners and experts to understand and practice. This was originally put forward by <a href="http://en.wikipedia.org/wiki/Robert_C._Martin">Rober C. Martin</a>, who is a pioneer in agile software development and extreme programming. Checkout <a href="http://cleancoders.com/">Cleancoders</a> to know more.</p>
<p>Chances are, you may be already using SOLID principle, just without giving it a name. </p>
<h2 id="tldr">tl;dr</h2>
<p>S - Single Responsibility Principle (SRP)</p>
<p>O - Open/Closed Principle (OCP)</p>
<p>L - Liskov Substitution Principle (LSP)</p>
<p>I - Interface Segregation Principle (ISP)</p>
<p>D - Dependency Inversion Principle (DIP)</p>
<p>Thats right, SOLID stands for a bunch of other acronyms.</p>
<p><div class="toc">
<ul>
<li><ul>
<li><a href="#tldr">tl;dr</a></li>
<li><a href="#read-on">Read on</a><ul>
<li><a href="#s-single-responsibility-principle-srp">S - Single Responsibility Principle (SRP)</a></li>
<li><a href="#o-openclosed-principle-ocp">O - Open/Closed Principle (OCP)</a></li>
<li><a href="#l-liskov-substitution-principle-lsp">L - Liskov Substitution Principle (LSP)</a></li>
<li><a href="#i-interface-segregation-principle-isp">I - Interface Segregation Principle (ISP)</a></li>
<li><a href="#d-dependency-inversion-principle-dip">D - Dependency Inversion Principle (DIP)</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</p>
<h2 id="read-on">Read on</h2>
<h3 id="s-single-responsibility-principle-srp">S - Single Responsibility Principle (SRP)</h3>
<blockquote>
<p>The single responsibility principle states that every class should <br>
have a single responsibility, and that responsibility should be <br>
entirely encapsulated by the class. All its services should be <br>
narrowly aligned with that responsibility.</p>
</blockquote>
<p>Fairly simple. A Student class should manipulate Student properties and not the the properties of School. Specification of the class remains mostly untouched unless there is a big change in requirement of your software.</p>
<p>It is good to keep in mind that, there can be some exceptions to this. For example a utility class may provide methods for managing both Students and Schools. </p>
<h3 id="o-openclosed-principle-ocp">O - Open/Closed Principle (OCP)</h3>
<blockquote>
<p>Software entities should be open for extension, but closed for modification.</p>
</blockquote>
<p>The idea is that once a class is implemented completely, it should not be modified for including new features. Bugs and error correction must be done as and when required. Adding a new feature will require new specification and release of newer version.</p>
<p><a href="http://en.wikipedia.org/wiki/Open/closed_principle">http://en.wikipedia.org/wiki/Open/closed_principle</a></p>
<h3 id="l-liskov-substitution-principle-lsp">L - Liskov Substitution Principle (LSP)</h3>
<blockquote>
<p>Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. See also <a href="http://en.wikipedia.org/wiki/Design_by_contract">design by contract</a>.</p>
</blockquote>
<p>That right there is the basic use of Dependency Injection, right? You define a parent interface and replace them by concrete implementation which are derivatives.</p>
<pre class="prettyprint"><code class="language-java hljs ">class Animal {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeNoise</span>() {
System.out.println(<span class="hljs-string">"noise"</span>);
}
}
class Dog extends Animal {
<span class="hljs-annotation">@override</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeNoise</span>() {
bark();
}
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">bark</span>() {
System.out.println(<span class="hljs-string">"bow bow bow"</span>);
}
}
Dog dog = <span class="hljs-keyword">new</span> Animal();
dog.makeNoise();
<span class="hljs-annotation">@Inject</span>
Animal animal; <span class="hljs-comment">// can be replaced by Dog</span></code></pre>
<p><a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">http://en.wikipedia.org/wiki/Liskov_substitution_principle</a></p>
<h3 id="i-interface-segregation-principle-isp">I - Interface Segregation Principle (ISP)</h3>
<blockquote>
<p>Many client-specific interfaces are better than one general-purpose interface.</p>
</blockquote>
<p>Interfaces provide abstraction no implementation. When developing client interfaces, it should be kept at minimum and should only expose those methods which are essential for that client.</p>
<p><a href="http://en.wikipedia.org/wiki/Interface_segregation_principle">http://en.wikipedia.org/wiki/Interface_segregation_principle</a></p>
<pre class="prettyprint"><code class="language-java hljs ">
interface Jumbable {
<span class="hljs-keyword">void</span> jump();
}
interface Climbable {
<span class="hljs-keyword">void</span> climb();
}
class Dog extends Animal implements Jumbable {
<span class="hljs-annotation">@override</span>
<span class="hljs-keyword">void</span> jump() {
<span class="hljs-comment">//jump</span>
}
}
class Monkey extends Animal implements Jumbable, Climbable {
<span class="hljs-annotation">@override</span>
<span class="hljs-keyword">void</span> jump() {
}
<span class="hljs-annotation">@override</span>
<span class="hljs-keyword">void</span> climb() {
}
}</code></pre>
<h3 id="d-dependency-inversion-principle-dip">D - Dependency Inversion Principle (DIP)</h3>
<blockquote>
<p>One should “Depend upon Abstractions. Do not depend upon concretions.”</p>
</blockquote>
<p>Dependency injection is one method of following this principle.</p>
<pre class="prettyprint"><code class="language-java hljs ">
interface JumpringService {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">jump</span>();
}
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">JumpingServiceImpl</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">JumpingService</span> {</span>
<span class="hljs-annotation">@Inject</span>
<span class="hljs-keyword">private</span> Jumpable jumbable;
<span class="hljs-annotation">@override</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">jump</span>() {
jumpable.jump();
}
}</code></pre>
<p><a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">http://en.wikipedia.org/wiki/Dependency_inversion_principle</a></p><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-35139848301999737122014-04-06T12:20:00.001+05:302014-06-07T01:41:05.605+05:30map() function in JavaScript, Scala etc<p>These are absolutely awesome functions. They allow you to apply a function on every element of an array and return a new array with the result of the function.</p>
<p>In theory these are called <a href="http://en.wikipedia.org/wiki/Higher-order_function">higher-order functions</a>, i.e they can take one or more function as an argument.</p>
<p>Consider the following JavaScript function:</p>
<pre class="prettyprint"><code class="language-javascript hljs "><span class="hljs-keyword">var</span> array = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>];
<span class="hljs-keyword">var</span> twoTimesArray = array.map(<span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(n)</span> {</span><span class="hljs-keyword">return</span> n*<span class="hljs-number">2</span>;});
console.log(twoTimesArray);</code></pre>
<p>output: [2, 4, 6, 8, 10]</p>
<p>So that just multiplies every element of <code>array</code> by 2 and returns the resulting array.</p>
<p>Without map functions you would have done something like this:</p>
<pre class="prettyprint"><code class="language-javascript hljs "><span class="hljs-keyword">var</span> array = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>];
<span class="hljs-keyword">var</span> twoTimesArray = [];
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i < array.length; i++ ) {
twoTimesArray[i] = array[i] * <span class="hljs-number">2</span>;
}
console.log(twoTimesArray);</code></pre>
<p>Clearly, that is a lot of code compared to the previous one.</p>
<p>And, if you use Scala, code becomes much more concise.</p>
<pre class="prettyprint"><code class="language-scala hljs ">scala> <span class="hljs-keyword">val</span> l = List(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>)
l: List[Int] = List(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
scala> l.map(x => x*<span class="hljs-number">2</span>)</code></pre>
<p><br> <br>
Imagine doing the same thing in Java. First we will look at Java 6</p>
<pre class="prettyprint"><code class="language-java hljs ">List<Integer> array = Arrays.asList(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>);
List<Integer> twoTimesArray = <span class="hljs-keyword">new</span> ArrayList<Integer>();
<span class="hljs-keyword">for</span>(Integer i: array) {
twoTimesArray.add(i*<span class="hljs-number">2</span>);
}</code></pre>
<p><br> <br>
And in Java 8:</p>
<pre class="prettyprint"><code class="language-java hljs ">List<Integer> array = Arrays.asList(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>);
List<Integer> twoTimesArray = <span class="hljs-keyword">new</span> ArrayList<Integer>();
array.stream().forEach((string) -> {
twoTimesArray.add(string*<span class="hljs-number">2</span>);
});</code></pre>
<p><br> <br>
The difference between for-each loop and using <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html">stream api</a> (collection.stream()) in Java 8 is that we can easily implement parallelism when using the stream api with collection.parallelStream(). Whereas, in for-each loop you will have to handle threads on your own.</p>
<p>Programming becomes fun when we add bit of functional style into OO languages.</p><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-1924472763608747852014-03-30T12:20:00.001+05:302014-04-04T10:33:59.848+05:30Closures<p>Closures are a bit hard to understand concept for someone from an Object Oriented programming background, mainly because popular OO programming languages, <s>(Java/C++) does not have this feature</s> (As <a href="http://www.reddit.com/user/bjzaba">bjzaba</a> pointed out in <a href="http://www.reddit.com/r/programming/comments/223b7p/closures/cgiyg9o">reddit</a>, C++ 11 has Closures) haven’t embraced or promoted this feature until recently. It is more of a functional programming concept, although many Object Oriented languages has started to support Closures through first class functions or higher order functions. </p>
<p>I first heard about Closures while developing something in Javascript. If you have used the popular javascript library <a href="http://jquery.com" title="jQuery">jQuery</a>, you have already used closures, knowingly or unknowingly.</p>
<p>Here is my attempt to explain Closures, through examples in few programming languages. I will try to be as simple as possible.</p>
<p>From Wikipedia:</p>
<blockquote>
<p>In programming languages, a closure (also lexical closure or function <br>
closure) is a function or reference to a function together with a <br>
referencing environment—a table storing a reference to each of the <br>
non-local variables (also called free variables or up values) of that <br>
function. A closure—unlike a plain function pointer—allows a <br>
function to access those non-local variables even when invoked outside <br>
its immediate lexical scope.</p>
</blockquote>
<p>What that means: <br>
1. Closure is a function (or a reference to a function) <br>
2. You get a pointer to closure <br>
3. So you can pass it around like an object <br>
4. It knows about non-local variables <br>
5. It can access those non-local variables, even when invoked outside of its scope <br>
6. So we say, closures ‘closes’ on its environment <br>
7. A function may create a closure and return it.</p><div class="se-section-delimiter"></div>
<h3 id="few-programming-languages-that-support-closures">Few programming languages, that support Closures</h3>
<ul>
<li>Lisp</li>
<li>Javascript</li>
<li>Scala</li>
<li>Clojure</li>
<li>Ruby</li>
<li>Python</li>
<li>Haskell</li>
<li>PHP</li>
<li>Go</li>
</ul>
<p>In closures procedure/method/function contexts become first-class. That means, with closures you can create functions that return functions, although that is only an outcome. An important point to understand here is, the closure methods refer to the context in which it was created, not to the one it was called.</p>
<p>To better understand closures one has to understand a variable’s scope, the best read about that would be <a href="http://www.coolcoder.in/2014/03/everything-you-need-to-know-about.html" title="Everything you need to know about javascript variable scope">understanding javascript variable scope</a>. </p>
<p>Closures store references to the outer function’s variables; they do not store the actual value. So if we change the value of reference in closure it changes value outside of its scope.</p>
<p>You may implement closures using Anonymous functions, but all anonymous functions need not be a closure, although many of them are.</p><div class="se-section-delimiter"></div>
<h3 id="why-would-anyone-use-closures">Why would anyone use Closures?</h3>
<ul>
<li>Reusability</li>
<li>Do more with less code</li>
<li>Make functional code stateful</li>
</ul>
<p>Closures help us to write more expressive and concise code(once you get a hang of it!). We know objects have a state, using Closure we can give state to functions as well.</p>
<p>Now, let us take a look at examples of how to use closures in a few programming languages.</p>
<h3 id="examples">Examples</h3>
<p>All of the following examples do the same thing: Create a closure to increment a number by another number.</p>
<h4 id="1-closure-example-in-javascript">1. Closure example in Javascript</h4>
<p>This would be the easiest to understand code.</p>
<pre class="prettyprint"><code class="language-javascript hljs "><span class="hljs-keyword">var</span> incrementBy = <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(x)</span> {</span>
<span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(y)</span> {</span>
<span class="hljs-keyword">return</span> x+y;
};
};
<span class="hljs-comment">// this will remember the value of 'x' forever</span>
<span class="hljs-keyword">var</span> incrementBy2 = incrementBy(<span class="hljs-number">2</span>);
<span class="hljs-keyword">var</span> incrementBy3 = incrementBy(<span class="hljs-number">3</span>);
console.log(incrementBy2(<span class="hljs-number">4</span>));
console.log(incrementBy3(<span class="hljs-number">8</span>));
<span class="hljs-comment">// Here you are creating a closure and calling it immediately</span>
console.log(incrementBy(<span class="hljs-number">5</span>)(<span class="hljs-number">8</span>));</code></pre>
<p>In the Javascript example above, we define a function <code>incrementBy(x)</code>, which returns a function, that accepts parameter ‘y’ and returns sum of x and y. Here the value of ‘x’ will go into the closure of the returned function and will be accessible whenever the function is invoked.</p>
<p>Note that when calling <code>incrementBy2(4)</code> our closure remembers the value 2 (i.e ‘x’) that was passed earlier when doing <code>var incrementBy2 = incrementBy(2);</code>. And when invoking <code>incrementBy2(4)</code> we are actually passing the value of <code>y</code> as 4. Hence the statement <code>return x+y</code> will transform to <code>return 2+4</code>. Cool right!!? <br>
<br></p>
<h4 id="2-closure-example-in-scala">2. Closure example in <a href="http://scala-lang.org/" title="Scala">Scala</a></h4>
<pre class="prettyprint"><code class="language-scala hljs "><span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">Closure</span> {</span>
<span class="hljs-comment">// define the closure using one line of code, power of Scala</span>
<span class="hljs-keyword">def</span> incrementBy(x:Int) = (y:Int) => x + y
<span class="hljs-keyword">def</span> main(args: Array[String]) = {
<span class="hljs-keyword">var</span> incrementBy3 = incrementBy(<span class="hljs-number">3</span>)
<span class="hljs-keyword">val</span> incrementBy5 = incrementBy(<span class="hljs-number">5</span>)
println(incrementBy3(<span class="hljs-number">5</span>))
println(incrementBy5(<span class="hljs-number">10</span>))
println(incrementBy(<span class="hljs-number">20</span>)(<span class="hljs-number">20</span>))
}
}</code></pre>
<p>The example in Scala is similar to the example in Javascript except for Scala’s awesome one liner syntax. <br>
<br></p>
<h4 id="3-closure-example-in-lisp-clisp">3. Closure example in Lisp (Clisp)</h4>
<pre class="prettyprint"><code class="language-lisp hljs "><span class="hljs-list">(<span class="hljs-title">defun</span> increment<span class="hljs-list">(<span class="hljs-title">y</span>)</span>
<span class="hljs-list">(<span class="hljs-title">defun</span> incrementBy<span class="hljs-list">(<span class="hljs-title">x</span>)</span>
<span class="hljs-list">(<span class="hljs-title">+</span> y x)</span>
)</span>
)</span>
<span class="hljs-list">(<span class="hljs-title">increment</span> <span class="hljs-number">4</span>)</span>
<span class="hljs-list">(<span class="hljs-title">incrementBy</span> <span class="hljs-number">5</span>)</span> <span class="hljs-comment">; 9</span>
<span class="hljs-list">(<span class="hljs-title">incrementBy</span> <span class="hljs-number">10</span>)</span> <span class="hljs-comment">; 14</span></code></pre>
<p>There are several ways of doing this is lisp. This is only one way of doing it. Here you are not getting a pointer to the closure function and will probably make it useless. See <a href="http://dunsmor.com/lisp/onlisp/onlisp_9.html">this link</a> to see how to return functions is Clisp. <br>
<br></p>
<h4 id="4-closure-example-in-clojure">4. Closure example in Clojure</h4>
<pre class="prettyprint"><code class="language-clojure hljs "><span class="hljs-list">(<span class="hljs-title"><span class="hljs-built_in">def</span></span> increment <span class="hljs-list">(<span class="hljs-title"><span class="hljs-built_in">fn</span></span> <span class="hljs-collection">[y]</span>
<span class="hljs-list">(<span class="hljs-title"><span class="hljs-built_in">def</span></span> incrementBy <span class="hljs-list">(<span class="hljs-title"><span class="hljs-built_in">fn</span></span> <span class="hljs-collection">[x]</span>
<span class="hljs-list">(<span class="hljs-title"><span class="hljs-built_in">+</span></span> x y)</span>
)</span>)</span>
)</span>)</span>
<span class="hljs-list">(<span class="hljs-title">increment</span><span class="hljs-number"> 4</span>)</span>
<span class="hljs-list">(<span class="hljs-title">incrementBy</span><span class="hljs-number"> 5</span>)</span> <span class="hljs-comment">; 9</span>
<span class="hljs-list">(<span class="hljs-title">incrementBy</span><span class="hljs-number"> 10</span>)</span> <span class="hljs-comment">; 14</span></code></pre>
<p>As you can see, the syntax of clojure and lisp are extremely similar. <br>
<br></p>
<h4 id="5-closure-example-in-python">5. Closure example in Python</h4>
<pre class="prettyprint"><code class="language-python hljs "><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">incrementBy</span><span class="hljs-params">(x)</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">increment</span><span class="hljs-params">(y)</span>:</span>
<span class="hljs-keyword">return</span> x+y
<span class="hljs-keyword">return</span> increment
incrementBy4 = incrementBy(<span class="hljs-number">4</span>)
incrementBy6 = incrementBy(<span class="hljs-number">6</span>)
<span class="hljs-keyword">print</span> incrementBy4(<span class="hljs-number">5</span>) <span class="hljs-comment"># 9</span>
<span class="hljs-keyword">print</span> incrementBy6(<span class="hljs-number">10</span>) <span class="hljs-comment"># 16</span></code></pre>
<p>The above example in Python is pretty similar to the one in Javascript and is easy to understand. Here we define the closure function <code>increment(y)</code> and then return it. Just remember to take care of the tabs! <br>
<br></p>
<h4 id="6-closure-example-in-ruby">6. Closure example in Ruby</h4>
<pre class="prettyprint"><code class="language-ruby hljs "><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Closure</span></span>
<span class="hljs-comment"># Ruby example using Proc.new</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> </span>incrementBy(x)
<span class="hljs-keyword">return</span> <span class="hljs-constant">Proc</span>.new {|y| x+y }
<span class="hljs-keyword">end</span>
<span class="hljs-comment"># Ruby example using lambda</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> </span>incrementByLambda(x)
lambda {|y| x+y}
<span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
closure = <span class="hljs-constant">Closure</span>.new
increment5 = closure.incrementBy(<span class="hljs-number">5</span>)
incrementByLambda7 = closure.incrementByLambda(<span class="hljs-number">7</span>)
puts increment5.call(<span class="hljs-number">6</span>)
puts incrementByLambda7.call(<span class="hljs-number">6</span>)</code></pre>
<p>Ruby can do this is in two ways, using Proc and using lambda. The lambda functions in Ruby are similar to lambda’s in lisp. <br>
<br> <br>
So that was examples about closures. Hope that gives you at least some idea about Closures. If you know how do the same in any other languages, please feel free to share. Also checkout the references, they are good reads.</p>
<h3 id="references">References:</h3>
<ul>
<li><a href="http://martinfowler.com/bliki/Lambda.html">Martin Fowler on Lambda</a></li>
<li><a href="http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/">http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/</a></li>
<li><a href="http://stackoverflow.com/questions/111102/how-do-javascript-closures-work">http://stackoverflow.com/questions/111102/how-do-javascript-closures-work</a></li>
<li><a href="http://psg.com/~dlamkins/sl/chapter11.html#closures">http://psg.com/~dlamkins/sl/chapter11.html#closures</a></li>
<li><a href="http://innig.net/software/ruby/closures-in-ruby">http://innig.net/software/ruby/closures-in-ruby</a></li>
<li><a href="http://en.wikipedia.org/wiki/Closure_(computer_programming)">http://en.wikipedia.org/wiki/Closure_(computer_programming)</a></li>
<li><a href="http://learn.jquery.com/javascript-101/closures/">http://learn.jquery.com/javascript-101/closures/</a></li>
<li><a href="http://javascriptissexy.com/understand-javascript-closures-with-ease/">http://javascriptissexy.com/understand-javascript-closures-with-ease/</a></li>
<li><a href="http://awaxman11.github.io/blog/2013/08/05/what-is-the-difference-between-a-block/">http://awaxman11.github.io/blog/2013/08/05/what-is-the-difference-between-a-block/</a></li>
<li><a href="http://csharpindepth.com/Articles/Chapter5/Closures.aspx">http://csharpindepth.com/Articles/Chapter5/Closures.aspx</a></li>
</ul>
<p><em>Thanks to Craig for sharing <a href="http://golang.org/" title="The Go Programming Language">Go</a> <a href="http://tech.deepumohan.com/2014/03/closures.html#comment-1316532644">snippet</a></em></p>
<p>Reddit thread here: <a href="http://redd.it/223b7p">http://redd.it/223b7p</a></p><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-7114041473989234272014-03-18T18:00:00.000+05:302014-03-31T19:12:43.365+05:30PostgreSQL 9.3 initial setup on Mac OSX 10.9.2<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>After <code>sudo port install postgresql93 postgresql93-server</code></p>
<pre>
<code class="language-bash hljs">
# switch to su
sudo su
mkdir /var/lib/pgsql/
chown -R postgres:wheel /var/lib/pgsql
su postgres
export PGDATA=/var/lib/pgsql/9.3/data
initdb
createdb pgdbname
createuser -A -D pgusername
exit
exit
# startdb
sudo -u postgres postgres -D /var/lib/pgsql/9.3/data/
# check if login works
psql -h localhost pgdbname pgusername
\q
# add PGDATA to ~/.bash_profile
echo "export PGDATA=/var/lib/pgsql/9.3/data" >> ~/.bash_profile
</code>
</pre>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-38923517001568568162014-03-06T14:48:00.003+05:302014-03-06T14:48:48.615+05:30Getty Images just made their 35 million images free to embed<div dir="ltr" style="text-align: justify;" trbidi="on">
<p><a href="http://www.gettyimages.com/">Getty Images</a> just made their 35 million images free for non-commercial use, to fight copy-right infringement. The new embed feature will allow any to embed images from Getty Images, without any ugly watermark on them. However these images will have links to original licensing page. </p>
<p>Read the article on <a href="http://www.bjp-online.com/">British Journal of Photography</a>.</p>
<a href="http://www.bjp-online.com/2014/03/getty-images-makes-35-million-images-free-in-fight-against-copyright-infringement/">http://www.bjp-online.com/2014/03/getty-images-makes-35-million-images-free-in-fight-against-copyright-infringement/</a>
<iframe src="//embed.gettyimages.com/embed/186381608?et=Pagjoq2JeUmaUg4g4yAaXg&sig=imwuz8vjgsPBmnkzx2CMtbI5grEmdqsI1PRq_Qbd3-A=" width="473" height="431" frameborder="0" scrolling="no"></iframe>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-2239346079669685222014-02-02T22:49:00.003+05:302014-02-02T22:49:51.958+05:30Sample app for Play! 2.2, Spring-data-jpa and Backbonejs<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>I have made a sample application to demo Play! framework 2.2, Spring data jpa and Backbonejs.</p>
<p>It is available at
<a href="https://github.com/WarFox/play-spring-data-jpa-backbonejs">https://github.com/WarFox/play-spring-data-jpa-backbonejs</a>.</p>
<p>Also a demo app is hosted in Heroku at <a href="http://play-spring-data-jpa-backbone.herokuapp.com/">http://play-spring-data-jpa-backbone.herokuapp.com/</a></p>
<p>It started as a fork from <a href="https://github.com/typesafehub/play-spring-data-jpa/">https://github.com/typesafehub/play-spring-data-jpa</a> and then created a separated repo to include backbonjs. </p>
<p>Feel free to fork and play with it.</p>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-4217301685777695752014-01-20T12:57:00.001+05:302014-01-20T12:57:12.756+05:30Backbonejs in jsFiddle.net<div dir="ltr" style="text-align: justify;" trbidi="on">
<p><a href="http://jsfiddle.net/">jsFiddle</a> does not provide <a href="http://backbonejs.org/">backbonejs</a> library through its Frameworks & Extensions dropdown. Thankfully, it allows you to add any external resources via External Resources option. I have made this blank template for you guys to start playing with Backbonejs in jsFiddle. Feel free to use it directly or fork it.</p>
<iframe width="100%" height="300" src="http://jsfiddle.net/deepumohanp/6fLw6/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<ul>
<li><a href="http://jsfiddle.net/deepumohanp/6fLw6/">Backbonejs Playground</a></li>
</ul>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-37881064139198107712014-01-09T00:03:00.003+05:302014-01-09T00:22:02.396+05:30jQuery :: Populate Select box dynamically (plugin version)<div dir="ltr" style="text-align: justify;" trbidi="on">
In my previous <a href="http://tech.deepumohan.com/2014/01/jquery-populate-selet-box-options.html">post</a>, I had shown how to populate a select box dynamically using jQurey. Here is the same thing as jQuery plugin.
<iframe width="100%" height="300" src="http://jsfiddle.net/deepumohanp/kNQ6s/0/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<p><a href="http://jsfiddle.net/deepumohanp/kNQ6s/">http://jsfiddle.net/deepumohanp/kNQ6s/</a> </p>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-22609229251827634412014-01-08T16:22:00.002+05:302014-01-08T16:31:53.612+05:30Use Requirejs to load scripts from cdn server like cdnjs<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>Fiddle here.</p>
<iframe width="100%" height="400" src="http://jsfiddle.net/deepumohanp/73xVu/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<p><a href="http://jsfiddle.net/deepumohanp/73xVu/">http://jsfiddle.net/deepumohanp/73xVu/</a></p>
<h3>References</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/8131265/loading-backbone-and-underscore-using-requirejs">http://stackoverflow.com/questions/8131265/loading-backbone-and-underscore-using-requirejs</a></li>
<li><a href="http://stackoverflow.com/questions/13464846/loading-bootstrap-from-cdn-with-require-js">http://stackoverflow.com/questions/13464846/loading-bootstrap-from-cdn-with-require-js</a></li>
</ul>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-38246269220838322042014-01-05T23:04:00.001+05:302014-01-08T15:49:59.060+05:30jQuery :: Populate Selet box options dinamically<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>Here is an example code to populate select box options dynamically using <a href="http://jquery.com/">jQuery</a></p>
<iframe width="100%" height="300" src="http://jsfiddle.net/deepumohanp/8EQjY/1/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<p><a href="http://jsfiddle.net/deepumohanp/8EQjY/">http://jsfiddle.net/deepumohanp/8EQjY/</a></p>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-35688528108076778522013-12-31T15:12:00.000+05:302014-01-05T23:11:14.467+05:30Youtube embed video html code without branding and controls (seekbar, play/pause and volume)<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>Youtube embedded player can be adjusted a lot using the parameters available here <a href="https://developers.google.com/youtube/player_parameters">https://developers.google.com/youtube/player_parameters</a>. Some parameters are available on both HTML5 and flash players and some are not.</p>
<p>Check out <a href="https://developers.google.com/youtube/youtube_player_demo">https://developers.google.com/youtube/youtube_player_demo</a>, for all availabel configuration and play with it.</p>
<p>For example you can hide the controllers in embedded video, <a name='more'></a> by setting parameter <code>controls</code> to 0</p>
<pre class="brush:html">
<iframe
src="http://www.youtube.com/embed/p09QlQQazo0?controls=0"
width="640" height="360">
</iframe>
</pre>
<div class="container">
<iframe src="http://www.youtube.com/embed/p09QlQQazo0?controls=0" width="640" height="360" ></iframe>
</div>
<p>Default video quality can be set using <code>vq</code>.</p>
<pre class="brush:html">
<iframe src="http://www.youtube.com/embed/p09QlQQazo0?vq=hd720" style="border: 5px solid #cccccc; overflow: hidden;" width="640" height="360" frameborder="0"
allowfullscreen></iframe>
</pre>
<div class="container">
<iframe src="http://www.youtube.com/embed/p09QlQQazo0?vq=hd720" style="border: 5px solid #cccccc; overflow: hidden;" width="640" height="360" frameborder="0" allowfullscreen></iframe>
</div>
<p>Youtube allows you to have its logo to be modest, by setting <code>modestbranding</code> to 1.</p>
<pre class="brush:html">
<iframe src="http://www.youtube.com/embed/p09QlQQazo0?modestbranding=1" width="640" height="360" frameborder="0" allowfullscreen></iframe>
</pre>
<div class="container">
<iframe src="http://www.youtube.com/embed/p09QlQQazo0?modestbranding=1" width="640" height="360" frameborder="0" allowfullscreen></iframe>
</div>
<p>We can also set all of these values together</p>
<pre class="brush:html">
<iframe src="http://www.youtube.com/embed/p09QlQQazo0?rel=0&autoplay=0&showinfo=0&modestbranding=1&controls=0&vq=hd720"
style="border: 5px solid #cccccc; overflow: hidden;" width="640" height="360"
frameborder="0" allowfullscreen></iframe>
</pre>
<div class="container">
<iframe src="http://www.youtube.com/embed/p09QlQQazo0?rel=0&autoplay=0&showinfo=0&modestbranding=1&controls=0&vq=hd720"
style="border: 5px solid #cccccc; overflow: hidden;" width="640" height="360"
frameborder="0" allowfullscreen></iframe>
</div>
<h3>References</h3>
<ol>
<li><a href="https://developers.google.com/youtube/player_parameters/">https://developers.google.com/youtube/player_parameters/</a></li>
<li><a href="http://www.labnol.org/internet/embed-youtube-videos-logoless/19532/">http://www.labnol.org/internet/embed-youtube-videos-logoless/19532/</a></li>
<li><a href="https://developers.google.com/youtube/youtube_player_demo/">https://developers.google.com/youtube/youtube_player_demo/</a></li>
</ol>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-64295521605245516992013-11-30T23:48:00.000+05:302014-03-31T20:36:31.671+05:30Java :: Get last date of a month<p>In Java we can use the Calendar class to get day_of_month, day_of_week etc. Last day of a month varies depending on the Month and on leap year we have extra day in February. So to figure out the last day of any given month in a year, we write some code which is apparently simple.</p>
<p>Calendar object allows us to manipulate days, go forward or backward on the Calendar, add days, hours, minutes or seconds to any given time etc. We will use these capabilities of Calendar class to get our last_of_month.</p>
<p>The idea here is to get the first day of next month and then reduce one day from it, which gives us the last day of the month relative to input date.</p>
<pre class="prettyprint"><code class="language-java hljs "><span class="hljs-javadoc">/**
* The trick is to add a month, set the date as 1st and then reduce a date.
*
*<span class="hljs-javadoctag"> @param</span> calendar
*/</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setCalendarToLastDayOfMonth</span>(Calendar calendar) {
calendar.add(Calendar.MONTH, <span class="hljs-number">1</span>);
calendar.set(Calendar.DAY_OF_MONTH, <span class="hljs-number">1</span>);
calendar.set(Calendar.HOUR, <span class="hljs-number">0</span>);
calendar.set(Calendar.MINUTE, <span class="hljs-number">0</span>);
calendar.set(Calendar.SECOND, <span class="hljs-number">0</span>);
calendar.set(Calendar.MILLISECOND, <span class="hljs-number">0</span>);
calendar.add(Calendar.DATE, -<span class="hljs-number">1</span>);
}</code></pre>
<p>But, Java Calendar has a better way of doing this, by using getActualMaximum() method which is far more convenient.</p>
<pre class="prettyprint"><code class="language-java hljs "><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setCalendarToLastDayOfMonth</span>(Calendar calendar) {
<span class="hljs-keyword">int</span> lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, lastDay);
calendar.set(Calendar.HOUR, <span class="hljs-number">0</span>);
calendar.set(Calendar.MINUTE, <span class="hljs-number">0</span>);
calendar.set(Calendar.SECOND, <span class="hljs-number">0</span>);
calendar.set(Calendar.MILLISECOND, <span class="hljs-number">0</span>);
}</code></pre>
<p>A sample calendar util class which gives you few convenient methods is given below.</p>
<pre class="prettyprint"><code class="language-java hljs "><span class="hljs-javadoc">/**
* Copyright (C) 2013 Deepu Mohan Puthrote. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/</span>
<span class="hljs-keyword">import</span> java.util.Calendar;
<span class="hljs-keyword">import</span> java.util.Date;
<span class="hljs-keyword">import</span> java.text.SimpleDateFormat;
<span class="hljs-keyword">import</span> java.util.Locale;
<span class="hljs-keyword">import</span> java.text.ParseException;
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CalendarUtil</span> {</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span>(String[] args) <span class="hljs-keyword">throws</span> Exception {
String string = <span class="hljs-string">"January 2, 2010"</span>;
CalendarUtil calendarUtil = <span class="hljs-keyword">new</span> CalendarUtil();
System.out.println(calendarUtil.getLastDateOfMonth(string));
System.out.println(calendarUtil.getLastDateOfMonth());
}
<span class="hljs-keyword">public</span> Date <span class="hljs-title">getLastDateOfMonth</span>() {
<span class="hljs-keyword">return</span> getLastDateOfMonth(<span class="hljs-keyword">new</span> Date());
}
<span class="hljs-keyword">public</span> Date <span class="hljs-title">getLastDateOfMonth</span>(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
<span class="hljs-keyword">return</span> getLastDateOfMonth(calendar);
}
<span class="hljs-keyword">public</span> Date <span class="hljs-title">getLastDateOfMonth</span>(Calendar calendar) {
setCalendarToLastDayOfMonth(calendar);
<span class="hljs-keyword">return</span> calendar.getTime();
}
<span class="hljs-keyword">public</span> Date <span class="hljs-title">getLastDateOfMonth</span>(String date) <span class="hljs-keyword">throws</span> ParseException {
<span class="hljs-keyword">return</span> getLastDateOfMonth(date, <span class="hljs-string">"MMMM d, yyyy"</span>);
}
<span class="hljs-keyword">public</span> Date <span class="hljs-title">getLastDateOfMonth</span>(String date, String format) <span class="hljs-keyword">throws</span> ParseException {
<span class="hljs-keyword">return</span> getLastDateOfMonth(date, format, Locale.US);
}
<span class="hljs-keyword">public</span> Date <span class="hljs-title">getLastDateOfMonth</span>(String stringDate, String format, Locale locale) <span class="hljs-keyword">throws</span> ParseException {
Date date = <span class="hljs-keyword">new</span> SimpleDateFormat(format, locale).parse(stringDate);
<span class="hljs-keyword">return</span> getLastDateOfMonth(date);
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setCalendarToLastDayOfMonth</span>(Calendar calendar) {
<span class="hljs-keyword">int</span> lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, lastDay);
calendar.set(Calendar.HOUR, <span class="hljs-number">0</span>);
calendar.set(Calendar.MINUTE, <span class="hljs-number">0</span>);
calendar.set(Calendar.SECOND, <span class="hljs-number">0</span>);
calendar.set(Calendar.MILLISECOND, <span class="hljs-number">0</span>);
}
}</code></pre>
<p>References <br>
<a href="http://stackoverflow.com/questions/13624442/getting-last-day-of-the-month-in-given-string-date/">http://stackoverflow.com/questions/13624442/getting-last-day-of-the-month-in-given-string-date/</a> <br>
<a href="http://docs.oracle.com/javase/7/docs/api/java/util/Date.html">http://docs.oracle.com/javase/7/docs/api/java/util/Date.html</a> <br>
<a href="http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html">http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html</a> <br>
<a href="http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html">http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html</a> <br>
<a href="http://docs.oracle.com/javase/7/docs/api/java/util/Locale.html">http://docs.oracle.com/javase/7/docs/api/java/util/Locale.html</a></p><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-14139546577696562802013-10-14T17:17:00.001+05:302013-10-14T17:35:23.245+05:30How to change extension of multiple files (bash script)<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>The following is the script I use in Macbook (Mountain Lion). It should work on most *nix shell like <tt>bash</tt>, <tt>csh</tt>, <tt>ksh</tt> etc. However, I have tested it only in <code>bash</code>. </p>
<a name='more'></a>
<div class="panel panel-success">
<div class="panel-heading"><span class="panel-title">Script</span></div>
<div class="panel-body">
<pre class="brush:bash">
#!/bin/bash
for f in *.$1; do
[[ -f "$f" ]] && mv -v "$f" "${f%$1}$2"
done
</pre>
</div>
<div class="panel-footer">filename: chext</div>
</div>
<p>Save this file as "chext", make it executable <code>chmod +x chext</code> and add to your <code>$PATH</code>.</p>
<p>Now you can use it like this:</p>
<div class="panel panel-info">
<div class="panel-heading">Usage</div>
<div class="panel-body">
cd path-to-dir<br/>
chext oldextension newextension
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Example</div>
<div class="panel-body">
chext JPG jpg
</div>
</div>
<h3>Reference:</h3>
<ol>
<li><a href="http://forums.appleinsider.com/t/106498/how-to-change-the-file-extension-of-multiple-files/">http://forums.appleinsider.com/t/106498/how-to-change-the-file-extension-of-multiple-files/</a></li>
<li><a href="http://stackoverflow.com/questions/15829702/how-to-change-the-extension-of-multiple-files-using-bash-script/">http://stackoverflow.com/questions/15829702/how-to-change-the-extension-of-multiple-files-using-bash-script</a>/</li>
<li><a href="http://kb.iu.edu/data/abec.html">http://kb.iu.edu/data/abec.html</a></li>
</ol>
</div>
<div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-57132544582924154042013-10-07T11:39:00.001+05:302013-10-07T14:37:02.503+05:30Correct way to embed Flash content<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>This <a href="http://alistapart.com/">A List Apart</a> <a href="http://alistapart.com/article/flashsatay/">article</a> discusses, a correct way of embedding Flash content in HTML, while following W3C standards.</p>
<p>If you need <a href="http://validator.w3.org/docs/help.html">valid</a> HTML content, that passes <a href="http://validator.w3.org/">http://validator.w3.org/</a>, you must use <code><object></code> tag, instead of <code><embed></code> tag.</p>
<p>Link: <a href="http://alistapart.com/article/flashsatay/">http://alistapart.com/article/flashsatay/</a></p>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-7194749340256837992013-10-02T11:33:00.001+05:302013-10-02T11:33:37.631+05:30JavaMail :: javax.mail.NoSuchProviderException: smtp <div dir="ltr" style="text-align: justify;" trbidi="on">
<p>When you are using Java's <tt>mailapi.jar</tt>, it also expects supporting libraries like <tt>smtp.jar</tt>, <tt>imap.jar</tt>, <tt>pop3.jar</tt>, <tt>gimap.jar</tt>, <tt>dsn.jar</tt>. If you are using Java EE platform, then it is already included. But if you are getting the following error, you might have to include additional libraries, from <a href="https://java.net/projects/javamail/pages/Home/">Java mail API</a>.</p>
<pre class="brush:java">
Exception in thread "main" javax.mail.NoSuchProviderException: smtp
at javax.mail.Session.getService(Session.java:746)
at javax.mail.Session.getTransport(Session.java:685)
at javax.mail.Session.getTransport(Session.java:628)
at javax.mail.Session.getTransport(Session.java:608)
at javax.mail.Session.getTransport(Session.java:663)
at javax.mail.Transport.send0(Transport.java:154)
at javax.mail.Transport.send(Transport.java:80)
</pre>
<p>There are several forums and discussions happening on this same issue. Surprisingly, this is a small class path issue.</p>
<p>To solve this error, make sure you have both <tt>mailapi.jar</tt> and <tt>smtp.jar</tt> in your classpath. Also, make sure you don't have duplicate jar files in your class path.</p>
<p>Reading the FAQ on Oracle's documentation will give you a better idea. <a href="http://www.oracle.com/technetwork/java/javamail/faq/index.html">http://www.oracle.com/technetwork/java/javamail/faq/index.html</a></p>
<h3>References</h3>
<ol>
<li><a href="http://www.oracle.com/technetwork/java/javamail/javamail-138606.html">http://www.oracle.com/technetwork/java/javamail/javamail-138606.html</a></li>
<li><a href="http://www.coderanch.com/t/601387/java/java/smtp-error/">http://www.coderanch.com/t/601387/java/java/smtp-error/</a></li>
<li><a href="http://stackoverflow.com/questions/2980408/problem-with-java-mail-no-provider-for-smtp/">http://stackoverflow.com/questions/2980408/problem-with-java-mail-no-provider-for-smtp/</a></li>
<li><a href="http://stackoverflow.com/questions/16861553/javax-mail-nosuchproviderexception-no-provider-for-smtps/">http://stackoverflow.com/questions/16861553/javax-mail-nosuchproviderexception-no-provider-for-smtps/</a></li>
<li><a href="https://answers.atlassian.com/questions/167299/unable-to-send-email-and-error-as-javax-mail-nosuchproviderexception/">https://answers.atlassian.com/questions/167299/unable-to-send-email-and-error-as-javax-mail-nosuchproviderexception/</a></li>
</ol>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comBangalore, Karnataka, India12.9715987 77.59456269999998312.4764182 76.949115699999979 13.4667792 78.240009699999987tag:blogger.com,1999:blog-1010732781203444109.post-91607601743708637142013-09-08T14:53:00.001+05:302013-09-08T14:54:33.040+05:30Get content from ace editor to a textarea<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>Ace editor is awesome! We get to edit code with instant syntax highlighting. But often, we have to get the content from the editor, than just typing some with syntax highlighting. Ace editor have a function to get the value <tt>editor.getSession().getValue()</tt>.</p>
<p>Here is a demo on getting value from the editor and setting it with <tt>textarea</tt>.</p>
<p>Fiddle here: <a href="http://jsfiddle.net/deepumohanp/tGF6y/">http://jsfiddle.net/deepumohanp/tGF6y/</a></p>
<iframe width="100%" height="300" src="http://jsfiddle.net/deepumohanp/tGF6y/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<h2>References</h2>
<ol>
<li>
<a href="http://stackoverflow.com/questions/6440439/how-do-i-make-a-textarea-an-ace-editor/">How do I make a textarea an ace editor?</a>
</li>
</ol>
</div>
<div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-71708055436011539102013-09-02T21:54:00.000+05:302013-09-07T13:33:57.975+05:30Javascript :: Ace Editor Positioning with Bootstrap3<div dir="ltr" style="text-align: justify;" trbidi="on" class="container">
<p><a href="http://ace.c9.io/">Ace editor</a> is a fantastic option for live source code editor on the web. One problem you come across when using Ace Editor is with the default <tt>absolute</tt> positioning. Also <a href="https://github.com/ajaxorg/ace/issues/75">it doesn't fit inside a container div</a> by default. Here is how I overcame these issues.</p>
<p>The <a href="http://ace.c9.io/#nav=embedding">example</a> from ace website uses absolute positioning by default, as show below. But luckily, ace can work perfectly with <tt>relative</tt> positioning</p>
<a name='more'></a>
<pre class="brush:html">
<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<style type="text/css" media="screen">
#editor {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
</head>
<body>
<div id="editor">function foo(items) {
var x = "All this is syntax highlighted";
return x;
}</div>
<script src="/ace-builds/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
</script>
</body>
</html>
</pre>
<p>In order to put ace-editor inside a container div, we can give relative positioning to the <code>editor</code> and remove the positioning attribs, like top, right, bottom and left.</p>
<pre class="brush: css">
#editor {
position: relative;
}
</pre>
<p>We also need to give height, otherwise editor won't show up.</p>
<pre class="brush: css">
#editor {
position: relative;
height: 300px;
}
</pre>
<p>That said, when using Twitter Bootstrap, you can absolutely forget about relative positioning of ace. But we still need to set height, as ace does not fill. In the following jsfiddle, I have used Bootstrap's panel component for showing the editor.</p>
<script src="https://gist.github.com/WarFox/6473534.js"></script>
<p>Full Screen Result is available <a href="http://jsfiddle.net/deepumohanp/U5JtP/embedded/result/">here</a>. <a href="http://jsfiddle.net/deepumohanp/U5JtP/embedded/result/">http://jsfiddle.net/deepumohanp/U5JtP/embedded/result/</a></p>
<p>Fiddle here: <a href="http://jsfiddle.net/deepumohanp/U5JtP/">http://jsfiddle.net/deepumohanp/U5JtP/</a> </p>
<iframe width="100%" height="300" src="http://jsfiddle.net/deepumohanp/U5JtP/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<h3>References</h3>
<ol>
<li><a href="http://stackoverflow.com/questions/6440439/how-do-i-make-a-textarea-an-ace-editor/">How do I make a textarea an ace editor?</a></li>
<li><a href="https://github.com/ajaxorg/ace/issues/75/">Ace doesn't fit inside a container div</a></li>
</ol>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comBangalore, Karnataka, India12.9715987 77.59456269999998312.4737417 76.946369199999978 13.4694557 78.242756199999988tag:blogger.com,1999:blog-1010732781203444109.post-56305129012542814942013-08-31T09:39:00.000+05:302013-08-31T09:39:07.686+05:30Blog Update :: Bootstrap awesomeness<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>Yesterday, I spend some to change the blog template using <a href="http://getbootstrap.com/" rel="nofollow">Bootstrap</a>.</p>
<p>Thanks to Blogger's new template editor. Now it is much easier to understand the templates.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="http://3.bp.blogspot.com/-bh9axs527CE/UiA0rCh0EYI/AAAAAAAAEGU/BiubEPADblY/s1600/Screen+Shot+2013-08-30+at+11.28.05+AM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-bh9axs527CE/UiA0rCh0EYI/AAAAAAAAEGU/BiubEPADblY/s640/Screen+Shot+2013-08-30+at+11.28.05+AM.png" /></a></div>
<p>The template was built on top of my older template <tt>Simple</tt> by <a href="http://noaesthetic.com">Joshua Peterson</a>. The process was simple and straight forward.</p>
<p>Blogger templates are mostly collection of widgets. I introduced few new divs with Bootstrap classes and removed few divs from older template. Bootstrap documentation has everything clearly explained along with examples.</p>
<p>I haven't tested this new template on all screens yet.</p>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-44685567436521712852013-07-29T23:19:00.000+05:302014-02-04T14:28:36.108+05:30Javascript :: Pass function as parameter<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>Javascript allows you to pass functions as parameter to another function and that makes Javascript super awesome!. Great things can be achieved from this power. </p>
<p>Quote from Mozilla developer website: </p>
<blockquote>In JavaScript, functions are first-class objects, i.e. they are objects and can be manipulated and passed around just like any other object.</blockquote>
<p>Every Javascript function is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function">Function</a> object. Hence we can pass them as arguments, like any other object.</p>
<h3>How to do that?</h3>
<p>Passing function as parameter is no different from passing any other object when it comes to syntax.</p>
<p>I am gonna try and explain that with an example (hopefully, easy to understand) </p>
<a name='more'></a>
<h3>The example problem</h3>
<p>Bob wants to get sum of values [1, 2, 3, 4, 5, 6, 7, 8, 9]</p>
<p>So we give him the following solution</p>
<pre class="brush:javascript">
// find sum of values
var total = function(values) {
var sum = 0;
values.forEach( function(value) {
sum += value;
});
return sum;
};
</pre>
<p>Bob is happy with the function. But now he wants to get sum of all even numbers in the list of values.</p>
<p>So we copy-paste the above function, rename it and make slight changes.</p>
<pre class="brush:js">
// find sum of values
var total = function(values) {
var sum = 0;
values.forEach( function(value) {
sum += value;
});
return sum;
};
// find sum of even numbers in list of values
var totalEven = function(values) {
var sum = 0;
values.forEach( function(value) {
if( value % 2 === 0 ) sum += value;
});
return sum;
};
</pre>
<p>Bob is happy again. But he wants more. Now he need sum of all odd numbers from the same list.</p>
<p>As usual, we copy-paste, rename and make slight changes.</p>
<pre class="brush:js">
// find sum of values
var total = function(values) {
var sum = 0;
values.forEach( function(value) {
sum += value;
});
return sum;
};
// find sum of even numbers in list of values
var totalEven = function(values) {
var sum = 0;
values.forEach( function(value) {
if( value % 2 === 0 ) sum += value;
});
return sum;
};
// find sum of odd numbers in list of values
var totalOdd = function(values) {
var sum = 0;
values.forEach( function(value) {
if( value % 2 !== 0 ) sum += value;
});
return sum;
};
</pre>
<h3>The problem with that approach</h3>
<ul>
<li>Lot of duplicate code.</li>
<li>Cluttered and ugly source code.</li>
<li>Source file becomes unnecessarily lengthy.</li>
<li>Not applying re-usabilty principle.</li>
<li>Have to create separate function for each additional request.</li>
</ul>
<h3>Better code with passing function as argument</h3>
<p>We can improve the above code a lot by passing the selection functionality as argument. In the above example, the basic operation is summation. Then, we need some kind of selection of values to sum. This selection can be anything, like even numbers, odd numbers etc. This is what we will pass an argument.</p>
<pre class="brush:js">
var totalSelectValues = function(values, selector) {
var sum = 0;
values.forEach(function(value) {
if(selector(value)) sum += value;
});
return sum;
};
</pre>
<p>The <code>selector</code>, is function passed as parameter. Here we are expecting it to return a boolean value.</p>
<pre class="brush:js">
var values = [1,2,3,4,5,6,7,8,9];
// even numbers
totalSelectValues(values, function(value) { return value % 2 === 0});
// odd numbers
totalSelectValues(values, function(value) { return value % 2 !== 0});
// greater than 5
totalSelectValues(values, function(value) { return value > 5 });
</pre>
<p>Awesome! We just created functions on the fly and passed it as parameters, didn't even bother to name it! Neat eh? Also we have reduced the code base by far. Just a single function and no ugly repetition.</p>
<h3>But that is not enough</h3>
<p>We also need to make sure our little function works perfectly even if the second argument is not send.</p>
<pre class="brush:js">
var totalSelectValues = function(values, selector) {
// handle undefined selector
if (typeof selector == 'undefined' ) {
selector = function() {return true;};
}
var sum = 0;
values.forEach(function(value) {
if(selector(value)) sum += value;
});
return sum;
};
</pre>
<p>Now that should work.</p>
<p>The complete example is available in the following jsFiddle. <a href="http://jsfiddle.net/deepumohanp/s2DBJ/">http://jsfiddle.net/deepumohanp/s2DBJ/</a> </p>
<iframe width="100%" height="876px" src="http://jsfiddle.net/deepumohanp/s2DBJ/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
<h3>References</h3>
<ol>
<li> I got the example inspiration from Dr. Venkat Subramaniam's talk an Scala.
<ul>
<li><a href="http://www.youtube.com/watch?v=LH75sJAR0hc">http://www.youtube.com/watch?v=LH75sJAR0hc</a></li>
<li><a href="https://vimeo.com/57988159">https://vimeo.com/57988159</a></li>
</ul>
</li>
<li> <a href="http://www.joelonsoftware.com/items/2006/08/01.html">http://www.joelonsoftware.com/items/2006/08/01.html</a> </li>
<li> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope</a> </li>
<li> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function</a> </li>
</ol>
</div>
<div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comBangalore, Karnataka, India12.9715987 77.59456269999998312.4764182 76.949115699999979 13.4667792 78.240009699999987tag:blogger.com,1999:blog-1010732781203444109.post-77120555007848827882013-06-24T11:34:00.000+05:302013-06-27T12:40:21.070+05:30Java :: Print "Hello World" without using Semicolon (;)<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>This Gist shows how to print something in Java, without the use of Semicolon (;). The code is self explanatory.</p>
<a href="https://gist.github.com/WarFox/5847999">https://gist.github.com/WarFox/5847999</a>
<br/>
<script src="https://gist.github.com/WarFox/5847999.js"></script>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comBangalore, Karnataka, India12.9715987 77.59456269999998312.4764182 76.949115699999979 13.4667792 78.240009699999987tag:blogger.com,1999:blog-1010732781203444109.post-64628925176727031072013-06-14T11:09:00.001+05:302013-08-30T12:05:59.499+05:30emacs:: Show line numbers in the left margin<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>So, I recently started using <code>emacs</code> as a text editor, instead of <code>vi</code>. It didn't seem easy to get things up straight at start. But gradually I understood why many experienced developers prefer <code>emacs</code>: <em>it is highly customisable and extensible</em>.</p>
<p><code>vi</code> gives you easy to use command to show line numbers, <code>:set nu</code> and you are done. That is not the case with <code>emacs</code>, and hence this blog post. You need to install linum package and enable <code>linum-mode</code> for this.</p>
<p>Make sure you have the latest version of <code>emacs</code>, at the time of writing 24.3, so that you have emacs package manager ready. Add marmalade and melba to the package archive list by adding the following to your <code>~/.emacs.d/init.el</code>.</p>
<pre class="brush:lisp">
(require 'package)
(add-to-list 'package-archives
'("marmalade" . "http://marmalade-repo.org/packages/") t)
(add-to-list 'package-archives
'("melpa" . "http://melpa.milkbox.net/packages/") t)
(package-initialize)
</pre>
<a name='more'></a>
<p>Now list the packages using <code>M-x list-packages</code> command.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="http://3.bp.blogspot.com/-C9vwda5ezn4/UbquDn_xIgI/AAAAAAAAEB8/xJ9Oludx5EA/s1600/Screen+Shot+2013-06-14+at+11.12.30+AM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://3.bp.blogspot.com/-C9vwda5ezn4/UbquDn_xIgI/AAAAAAAAEB8/xJ9Oludx5EA/s1600/Screen+Shot+2013-06-14+at+11.12.30+AM.png" /></a></div>
<p>You should get a list of packages like this.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/--vuorjxpGOg/UbqupLSrq3I/AAAAAAAAECE/lGaKi8lnvFY/s1600/Screen+Shot+2013-06-14+at+11.16.41+AM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/--vuorjxpGOg/UbqupLSrq3I/AAAAAAAAECE/lGaKi8lnvFY/s400/Screen+Shot+2013-06-14+at+11.16.41+AM.png" /></a></div>
<p>Next locate <code>linum</code> package using <code>Ctrl-s</code> command. You may have to repeatedly use <code>Ctrl-s</code> to get the right package. It would say <em>display line numbers in the left margin</em>.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/-_4b9KgqIPI8/Ubqxfmw1-CI/AAAAAAAAECU/0UogSTSbDvk/s1600/Screen+Shot+2013-06-14+at+11.28.13+AM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-_4b9KgqIPI8/Ubqxfmw1-CI/AAAAAAAAECU/0UogSTSbDvk/s1600/Screen+Shot+2013-06-14+at+11.28.13+AM.png" /></a></div>
<p>Select and install that using arrow keys and return key. You can enable linum-mode right away using <code>M-x linum-mode</code> command.</p>
<div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/-a9FUTdLh8DM/Ubq3O7P_R8I/AAAAAAAAECk/6PU8WgocLVE/s1600/Screen+Shot+2013-06-14+at+11.54.24+AM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-a9FUTdLh8DM/Ubq3O7P_R8I/AAAAAAAAECk/6PU8WgocLVE/s1600/Screen+Shot+2013-06-14+at+11.54.24+AM.png" /></a></div>
<h3>References:</h3>
<ul>
<li><a href="http://goo.gl/DlqUI">EmacsWiki:LineNumbers</a></li>
<li><a href="http://goo.gl/VhUc7">SuperUser:How do I display line numbers in emacs (not in the mode line)?</a></li>
<li><a href="http://goo.gl/w8Tqn">ErgoEmacs:How to Set Emacs's User Interface to Modern Conventions</a></li>
</ul>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comtag:blogger.com,1999:blog-1010732781203444109.post-5578879165697909542013-05-11T18:23:00.000+05:302013-05-11T18:26:35.571+05:30Turn off unlimited trailing whitespace in IntelliJ IDEA<div dir="ltr" style="text-align: left;" trbidi="on">
<p>By default, IntelliJ IDEA allows you to click any where on the editor and type. Some users find it annoying. If you are new to IntelliJ, you may find it a bit difficult to change the setting. This is available in the Virtual Space section of Editor Settings in IDEA preferences.</p>
<p>Turn it of by going to File menu -> Settings -> Editor -> Virtual Space and uncheck 'Allow placement of caret after end of line'.</p>
<p><a href="http://1.bp.blogspot.com/-0TweG1pBNgI/UY4vGJ-mWuI/AAAAAAAAEBg/MUTHKRLU6g0/s1600/Screen+Shot+2013-05-11+at+4.07.26+PM.png" imageanchor="1"><img border="0" height="393" src="http://1.bp.blogspot.com/-0TweG1pBNgI/UY4vGJ-mWuI/AAAAAAAAEBg/MUTHKRLU6g0/s640/Screen+Shot+2013-05-11+at+4.07.26+PM.png" width="640" /></a></p>
<p>Peace of mind.</p>
<iframe width="560" height="315" src="http://www.youtube.com/embed/GP5ZIGU6ufo" frameborder="0" allowfullscreen></iframe>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comBangalore, Karnataka, India12.9715987 77.59456269999998312.4764147 76.949115699999979 13.4667827 78.240009699999987tag:blogger.com,1999:blog-1010732781203444109.post-63194165744676258302013-03-27T00:04:00.002+05:302013-08-30T12:08:39.242+05:30Java :: Count the number of times a method is called<div dir="ltr" style="text-align: justify;" trbidi="on">
<h2>How to find how many times a method is used?</h2>
<p>A general answer to this question would be something like this:</p>
<pre class="brush:java">
public class MyClass {
static int count = 0;
public void myMethod() {
count++;
}
}
</pre>
<br/>
<p>Using <code>static int</code> would seem a perfect solution. Static will share the instance variable <code>count</code> among all instances of MyClass.</p>
<p>However, problem occurs in a multi threaded environment, as the count incrementation is not synchronised.</p>
<a name='more'></a>
<pre class="brush:java">
package com.deepumohan.tech.methodinvocationcount;
public class MyClass {
static int count = 0;
public void myMethod() {
synchronized(this) {
count++;
}
}
}
</pre>
<br/>
<p>Now this works perfect in a multi-threaded environment.</p>
<p>Java provides a better option to use thread-safe increments through Atomic classes available in <code>java.util.concurrent.atomic</code> packag.</p>
<pre class="brush:java">
package com.deepumohan.tech.methodinvocationcount;
import java.util.concurrent.atomic.AtomicInteger;
public class MyClass {
AtomicInteger atomicInteger = new AtomicInteger(0);
public int getMethodInvocationCount() {
return atomicInteger.incrementAndGet();
}
}
</pre>
<p>Here is a good read about <code>AtomicInteger vs static int</code>: <a href="http://goo.gl/zSwHk">Java - using AtomicInteger vs Static int</a></p>
</div><div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.comElectronics City, Bangalore, Karnataka, India12.8399389 77.67700309999997912.7780114 77.596322099999981 12.9018664 77.757684099999977tag:blogger.com,1999:blog-1010732781203444109.post-36522906889158585442013-03-26T14:35:00.001+05:302013-08-30T12:09:27.034+05:30Java :: How to convert primitive char to String in Java<div dir="ltr" style="text-align: justify;" trbidi="on">
<p>Char is 16 bit unsigned data type in Java used to store characters and <code>String</code> is an immutable array of <code>char</code>. In Java you cannot cast a primitive <code>char</code> element to <code>String</code>.</p>
<p>Below I have given five methods to convert a <code>char</code> to <code>String</code>. Also I have included common mistakes that gives compile time errors.</p>
<a name='more'></a>
<pre class="brush:java">
package com.deepumohan.tech.chartostring;
public class CharToString {
public static void main(String[] args) {
char x = 'x';
System.out.println(concatBlankString(x));
System.out.println(stringValueOf(x));
System.out.println(characterToString(x));
System.out.println(characterObjectToString(x));
System.out.println(charArray(x));
}
// append a blank string
public static String concatBlankString(char x) {
return x + "";
}
// use String.valueOf(char) static function
public static String stringValueOf(char x) {
return String.valueOf(x);
}
// use Character.toString(char) static function
public static String characterToString(char x) {
return Character.toString(x);
}
// create new Character object from the given char and
// then use object's toString() method
public static String characterObjectToString(char x) {
return new Character(x).toString();
}
// create new char[] array from the char and pass it to
// String constructor
public static String charArray(char x) {
return new String(new char[]{x});
}
/*
// Compile time error
// No suitable constructor found
public static String noConstructor(char x) {
return new String(x);
}
// Compile time error
// Inconvertible types
public static String inconvertibleTypes(char x) {
return (String) x;
}
*/
}
</pre>
<p>I wonder why Java doesn't include <code>String</code> constructor that accept a single <code>char</code> as argument.</p>
<h3>Also see</h3>
<ul>
<li><a href="http://goo.gl/E3aKf">How to convert Char to String in Java with Example</a></li>
<li><a href="http://goo.gl/BI05v">How to convert a char to a string in Java?</a></li>
</ul>
</div>
<div class="blogger-post-footer"><div style="border-top: 1px solid #efefef; margin-top: 10px; font-size:80%;">
<hr/>
Thank you for reading. This blog post was originally posted to <a href="http://tech.deepumohan.com/">Deepu's Technology Blog</a>.
</div></div>Deepuhttp://www.blogger.com/profile/06387000136668333691noreply@blogger.com