Posts

Mystry of Java String.intern

Mystery of Java String.intern We have all learn about how Java has optimised handling string objects. The String class has been made immutable and string literal definition makes sure that existing instance from string pool will be returned instance creating new one. Here is simple code snippet that explains it String firstName = "John"; String firstNameWithNew = new String("John"); String duplicateFirstName = "John"; //All there strings are same System.out.println(firstName.equals(duplicateFirstName) && firstName.equals(firstNameWithNew));//=> true //Since they defiend using string iterals, even there memory references are same System.out.println(firstName == duplicateFirstName);//=> true //Since one of the object has defined explictly using new operator, there memory references are different. System.out.println(firstName == firstNameWithNew);//=> false This is very basic understanding that everyone has. Then I came across String.in...

Table sorting accessibility for AngularJS table/list

Has your SPA accessibility compliance done ? Ahhh … let me get back to you. That’s usual scenario for dynamic single page application. Since content of the web app changes dynamically/asynchronously. It required need addition planning to make dynamic web accessibility complain. For those who are new to web accessibility The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect. There are many tools are being provided to make the web accessible like screen reader. The screen reader read out the html content with help of aria attributes. One of the accessibility attribute is aria-sort . It let the user know that the given html table is sorted by of the its column and in which order. The sorted column of the table expected to have ng-aria=”ascending/descending”. The problem with SPA table is that on sorting the table the content get sorted without loading the web, so having static aria-sort attribute is going t...

Management lesson from The Bridge Riddle

Most of us come across the Bridge Riddle sometime before, it is all about optimizing time to cross the bridge. Here is the riddle You, an assistance, a jenitor and a scientist have to cross a wooden bridge in 17 minutes . The bridge is weak and only able to carry the weight of two of them at a time. Because they are in a rush and the light is fading they must cross in the minimum time possible and must carry a torch (flashlight,) on each crossing. They only have one torch and it can’t be thrown. Because of their different fitness levels and some minor injuries they can all cross at different speeds. You can cross in 1 minute, assistance in 2 minutes, the janitor in 5 minutes and the scientist in 10 minutes. Below TED Ed video explains and solve this riddle https://www.youtube.com/watch?v=7yDmGnA8Hw0 As explained in the video the key decision is to reply on the assistant who is comparatively less efficient than “You”, the assistant takes double time t...

All about Java stream collect offering

Lets start with a problem statement “Provided collection of employees, we need to find average, max and min age of employee by county” public static void avgMaxMinEmployeeAgeByCounter() { String AVG = "AVG"; String MAX = "MAX"; String MIN = "MIN"; String SUM = "SUM"; String COUNT = "COUNT"; List<Employee> employees = Employee.EMPLOYEES;//LIst of all employees, pojos // Mapping country name to average, max, min age of employee Map<String, Map<String, Double>> summary = new HashMap<>(); for(Employee e: employees) { if(summary.containsKey(e.getCountry())){ Map<String, Double> map = summary.get(e.getCountry()); map.put(SUM, (map.get(SUM) + e.getAge())); map.put(COUNT, map.get(COUNT) +1); map.put(MAX, map.get(MAX) < e.getAge() ? e.getAge():map.get(MAX)); map.put(MIN, map.get(MIN) > e.getAge() ? e.ge...

Utilizing ES6 Generator

I am going through Mozilla documentation about the Iterator and Generator concept introduced in ECMAScript6. Here is the overview as per Mozilla JS guide Processing each of the items in a collection is a very common operation. JavaScript provides a number of ways of iterating over a collection, from simple for loops to map() and filter(). Iterators and Generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of for…of loops. This post is not about how it works, it is better explained at Mozilla JS guide . I have tried to apply the JS generator for one of the our day to day code. I think it is better suitable for lazy traversing and evaluating each item and proceed further if required. A common example comes in my mind is the tree traversing. I have implemented Depth First Search ( pre-order) using generator. Consider the scenario where you need to traverse the tree node, evaluate/process t...

Looping & Closure

Image
Here is simple code to dynamically create set of buttons that greet in different languages. document.body.onload = createButtons; function createButtons() { var greetings = [ {lang:'English', msg:'Good Morning !!'}, {lang:'German', msg:'Guten Morgen !!'}, {lang:'French', msg:'Bonjour !!'}, {lang:'Finnish', msg:'Huomenta !!'} ]; document.createElement('h1'); console.log(greetings); for(var i=0;i<greetings.length; i++){ var greet = greetings[i] var input = document.createElement("button"); input.appendChild(document.createTextNode(greet.lang)); input.setAttribute('class','btn btn-default btn-lg'); input.onclick = function(event){ alert(greet.msg); }; document.body.appendChild(input); } } Pretty simple, looping through array of objects and adding buttons with lan...

NPE as well as Null check free code ... Really ?

Image
NPE as well as Null check free code … Really ? Is this how your Java code review start ? NPE is always nightmare for a Java developer. Lets not discussion to much and jump on an usual Java code snippet public interface Service { public boolean switchOn(int timmer); public boolean switchOff(int timmer); //Other controls } public class RefrigeratorService implements Service { // ... } public class HomeServices { private static final int NOW = 0; private static HomeServices service; public static HomeServices get() { //Null Check #1 if(service == null) { service = new HomeServices(); } return service; } public Service getRefrigertorControl() { return new RefrigeratorService(); } public static void main(String[] args) { /* Get Home Services handle */ HomeServices homeServices = HomeServices.get(); //Null Check #2 if(homeServices != null) { Serv...

Java doesn't have "Diamond" problem : Really ..?

Java doesn’t have “Diamond” problem : Really ..? We have been confidently telling that Java doesn’t have diamond problem even if it support multiple inheritance. In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. But do you that the diamond problem is now there in newly introduced Java 8. It is because of the introduction of default methods in Interface. In Java8 Interfaces not only have method declaration but their default implementation. Any class implementing can either use default implementation from interface or provide its own implementation. Since Java class can implement multiple interfaces it is possible that two interfaces has same default methods, that brings diamond problem. How do we overcome diamond problem ? Consider following code snippet public interface InterfaceA { ...

Overloaded function in Javascript

Coming from Java background, it is happened to be searched java language constructs while coding javascript. One of such construct is overloaded methods/function. Take a look following code snippet   //Normal sum var intergerSum = sum ( 10 , 20 ); //Expecting item price sum var objectSum = sum ( {item_id: '01' ,name: 'abc' , price: 100 }, {item_id: '02' ,name: 'xyz' , price: 200 } ); As per above code snippet, implementation of ‘sum’ has been abstracted from the user. In the world of type safe language like Java, it is very straight forward, but in case of javascript we need to have our custom implementation. Lets see how can we achieve above in javascript. Lets start with defining a constructor function which introduce a common function to all our custom object so that we can extract integer value for summation. //constructor function to introduce new function to custom object function item (options) { var instance = Object...

Do you know Javascript … Try these puzzle

Do you know Javascript … Try these puzzle Javascript is one the most miss-understood language among developers. Everyday I learn new lesson about it.While going through few articles I thought of following JS language puzzles. Handling Array var days = [ 'Monday' , 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday' , 'Saturday' ]; var length = days. length ; console. log ( 'No of days are ' + days. length ); //Opps we missed Sunday, lets add it days[++ length ] = 'Sunday' ; console. log ( 'Final no of days are ' + days. length ); It is obvious that no of days are 7…. is it ? Written with StackEdit . StackEdit is a full-featured, open-source Markdown editor based on PageDown, the Markdown library used by Stack Overflow and the other Stack Exchange sites. ↩ Here is the text of the footnote . ↩

All you need to know about JSON Processing in JEE7

JSON is the choice data transfer format used all RESTful services because it is light weight, open standard, less verbose and easy to understand. One of the most important factor for all current generation services is performance and JSON format satisfies all such needs. There are already few third party Java APIs available to JSON parsing but with growing popularity, JEE introduced new JSON processing 1.0 API as part of JSR-353. This API supports both object model as well as streaming model for processing JSON, which are similar to those used for XML documents.This API is limited to JSON processing but not binding, JSON-binding framework will be available in subsequent version of JEE. Object vs Streaming Model : The object model creates a tree that represents the JSON data in memory. The tree can then be navigated, analyzed, or modified. This approach is the most flexible and allows for processing that requires access to the complete contents of the tree. However, it is often sl...

Getting started with Java 7

Recently out product has adapted JDK 7 for development as well as run-time. So get familiar everybody in the team with the new features of JDK , so i prepared a presentation "Getting started with Java 7". Sharing same presentation to refer you haven't still adapted JDK7.  Presentation:

Eclipse Editor: Partially editable/read-only editor Part 4

Image
Blocking drag & drop action to non-editable section It is an additional post to Eclipse Editor: Partially editable/read-only editor series . In all the previous pos ts I have explained making editor partially editable step by step to make functionality more robust. This post I am going to explain how to block drag & drop action to non-editable section of editor. Eclipse’s default implementation of text editor supports drag and drop of selection of text. When you have read-only as well as editable code section present, then such drag and drop may disturb read-only code section. To prevent the read-only code section from getting modified knowing or unknowingly , any drop action on read-on code section should be disabled. Eclipse TextEditor gives handle to DragAndDrop service , using it you can install your own implementation for DropTragetListener against the expected source viewer control. In your implementation any drop operation on the read-only code section can be ignore...