Thursday, November 30, 2017

2nd highest salary in Oracle using ROW_NUMBER and RANK in Oracle and MSSQL

This is the second article about calculating 2nd highest salary in SQL. In the first part, you have learned how to find the second highest salary in MySQL, SQL SERVER and by using ANSI SQL, which should also work in all database which confirms ANSI standard e.g. PostgreSQL, SQLLite etc. In this part, I will show you how to find the 2nd maximum salary in Oracle and SQL SERVER using ROW_NUMBER(), RANK() and DENSE_RANK() method. These are window function in Oracle, which can be used to assign unique row id, or rank to each row based on any column and then select the right row. For example, to calculate the 2nd highest salary, we can create row numbers using ROW_NUMBER() function over salary and then get the second row, which would be your 2nd maximum salary. Though these ranking functions handles duplicates differently, so depending upon whether your table has the duplicate salary, you need to choose either ROW_NUMBER(), RANK() or DENSE_RANK(), which handle duplicate differently. This is also one of the most frequently asked SQL Interview questions for your reference.

Tuesday, November 28, 2017

How to Find Missing Number on Integer Array of 1 to 100 - BitSet Example

One of the most frequently asked question on programming interviews is, write a program to find the missing number in an array in Java, C# or any other language; depending upon which language you choose. This kind of coding interview questions are not only asked in small start-ups but also on some of the biggest technical companies like Google, Amazon, Facebook, Microsoft, mostly when they visit the campus of reputed universities to hire graduates. Simplest version of this question is to find missing elements in an area of 100 integers, which contains numbers between 1 and 100. This can easily be solved by calculating the sum of the series using n(n+1)/2, and this is also one of the quickest and efficient ways, but it cannot be used if the array contains more than one missing numbers or if the array contains duplicates.

Difference between static vs non static method in Java

In this article, we will take a look at the difference between static and non-static method in Java, one of the frequently asked doubt from Java beginner. In fact, understanding static keyword itself is one of the main programming fundamental, thankfully it's well defined in Java programming language . A static method in Java belongs to class, which means you can call that method by using class name e.g. Arrays.equals(), you don't need to create any object to access this method, which is what you need to do to access non-static method of a class. Static method is treated differently by compiler and JVM than non-static methods, static methods are bonded during compile time, as opposed to binding of the non static method, which happens at runtime.

Saturday, November 25, 2017

Database Transaction Tutorial in SQL with Example for Beginners

A database transaction is an important concept to understand while working in database and SQL. Transaction in the database is required to protect data and keep it consistent when multiple users access the database at the same time.  In this database transaction tutorial we will learn what is a transaction in a database, why do you need transaction in the database, ACID properties of database transaction and an example of database transaction along with commit and rollback.   Almost all vendors like Oracle, MySQL, SQL Server or Sybase provide transaction facility but MySQL only provide it for certain storage engines like InnoDB and BDB and not for MyISAM.

Friday, November 24, 2017

Don't use System.exit() on Java Web Application

I have recently come across a code snippet, where programmer was using System.exit() if application failed to acquire necessary resource after couple of retry. His reasoning was that since, application cannot function, if essential resources like database is not available or there is no disk space to write records in File system. Ok, I hear you; but System.exit() in Java Web application, which runs inside either web server or application server, which itself is Java program is not a good idea at all. Why? because invoking System.exit() kills your JVM, invoking this from Tomcat or Jetty, will not only kill your application but most likely server itself. This can be potentially dangerous, if that server also host other critical application, which is not uncommon at all. As per my experience, System.exit() calls are quite common in overly broad try-catch blocks in web application start-up code that loads environment variables, properties files, connect to MQ Series, establishes database connection, opens socket connections, etc. This is still ok, if you are writing core Java based server, where each application has their own JVM, but with web application deployed on Tomcat, JBoss, WebSphere, Weblogic or any other application server, using System.exit() is big mistake. In worst case can result in outage for lots of other critical application. On the other hand, there are ways to prevent your web application from someone else’s mistake, by enabling Security Manager. System.exit() and Runtime.exit() both goes through the security manager. Enabling Security manager will catch these calls and reduce them into an exception rather than shutting down the whole VM. It's not difficult to enable the security manager in most application servers, Tomcat, JBoss both has documented steps to enable security Manager.

Great Example of Open Closed Design Principle in Java

Great Example of Open Closed Design Principle
I am big fan of design pattern article and love to read articles on design patterns and recently wrote about decorator design pattern in JavaObserver patternstatic factory pattern and about Singleton pattern. Today I come across this good article on open closed design pattern, what I like most is there example and clear way of explanation, first example is true value and it will help you understand open closed principle very quickly and second example is also not bad. I have also shared many questions on design patterns and Object oriented design principles like 10 Java singleton interview questions , which discusses some of the most common questions on Singleton pattern like how to write Thread-Safe Singleton class , should we use Enum as Singleton or not etc and 20 design pattern interview questions, if you are preparing for senior level Java interview, where questions from design is expected, its worth looking for quick review.

open closed design principle exampleOne word about Open Closed principle is a design principle which says that a class should be open for extension but closed for modification. Open Closed Principles is one of the principle from SOLID design principle where it represent "O". Read more about OOPS and SOLID design pattern in my post 10 OOPS and SOLID design principles Java programmer should know.  

In Simple language Open closed design principles says that new functionality should be added by introducing new classes, methods or fields instead of modifying already tried and tested code. One of the way to achieve this is Inheritance where class is extended to introduce new functionality on top of inherited basic features.

Benefit or Open Closed Design Principle:
1) Application will be more robust because we are not changing already tested class.
2) Flexible because we can easily accommodate new requirements.
3) Easy to test and less error prone.

Thursday, November 23, 2017

Top 10 Struts Interview Question And Answer - J2EE

This time its Struts interview questions, After writing Spring interview questions few weeks back I was thinking what to pick for my interview series and then I thought about any web framework, and on that struts is my favorite. Struts are open source framework used for web application. These Struts interview questions are based on my experience as well as collected by friends and colleague and they are not only good for interview practice but also shows a new direction of learning for anyone who is not very familiar with struts. The best way to use these interview questions does revise before going for any Struts interview or any Java or J2EE interview. I have also provided answers to these struts interview questions but you can also research more on Google but these answers of struts are sufficient on interview perspective.

What is difference between BeanFactory and ApplicationContext in Spring framework

BeanFactory vs ApplicationContext
The difference between BeanFactory and ApplicationContext in Spring framework is another frequently asked Spring interview question mostly asked Java programmers with 2 to 4 years experience in Java and Spring. Both BeanFactory and ApplicationContext provides a way to get a bean from Spring IOC container by calling getBean("bean name"), but there is some difference in there working and features provided by them. One difference between bean factory and application context is that former only instantiate bean when you call getBean() method while ApplicationContext instantiates Singleton bean when the container is started,  It doesn't wait for getBean to be called. This interview questions is third on my list of frequently asked spring questions e.g. Setter vs Constructor Injection and  What is default scope of Spring bean. If you are preparing for Java interview and expecting some Spring framework question, It’s worth preparing those questions. 

Wednesday, November 22, 2017

How to join three tables in SQL query – MySQL Example

Three table JOIN Example SQL
Joining three tables in single SQL query can be very tricky if you are not good with the concept of SQL Join. SQL Joins have always been tricky not only for new programmers but for many others,  who are in programming and SQL for more than 2 to 3 years. There are enough to confuse someone on SQL JOIN ranging from various types of SQL JOIN like INNER and OUTER join, LEFT and RIGHT outer join, CROSS join etc. Between all of these fundamentals, What is most important about Join is, combining multiple tables. If you need data from multiple tables in one SELECT query you need to use either subquery or JOIN. Most of the times we only join two tables like Employee and Department but sometimes you may require joining more than two tables and a popular case is joining three tables in SQL.

Difference between char, varchar, nchar and nvarchar data type in SQL Server database

What is the difference between char and varchar in SQL, followed by nchar and nvarchar, is one of the popular SQL interview questions, and surprisingly not every programmer knows this basic difference. If you go with the name, which you should, then you can figure out that char is a fixed length data type while varchar should be variable length data type. Though all char, varchar, nchar, and nvarchar are used to store text or String data there are subtle differences between them. As I said char is fixed length, which means a variable or a column e.g. Zipcode char(10) will take only 10 bytes to store data, including space.

Monday, November 20, 2017

Scala vs Java - Differences and Similarities

Scala is new generation JVM language, which is generating popularity as an alternative of arguably one of the most popular language Java. It's not yet as popular as Java, but slowly getting momentum. As more and more Java developers are learning Scala and inspired by Twitter, more and more companies are using Scala, it's future looks very bright. To start with, Scala has several good feature, which differentiate it from Java, but same time it has lot of similarities as well e.g. both Scala and Java are JVM based language, You can code Scala in Java way and Scala can use any Java library, which in my opinion a great decision made by designers of Scala.

Sunday, November 19, 2017

Top 25 Java Collection Framework Interview Questions Answers for Freshers and Experienced Programmers

Interview questions from Collection package or framework are most common in any Core Java Interview yet a tricky one. Together Collection and multithreading make any Java interview tough to crack and having a good understanding of Collection and threads will help you to excel in Java interview. I thought about writing interview questions on Java collection framework and important classes like ArrayList, HashMap, Hashtable, and newly added concurrent collections e.g. ConcurrentHashMap when I first wrote 10 multi-threading Interview questions  but somehow this article got delayed. Though I have shared several questions individually in between.

Saturday, November 18, 2017

Difference between Setter vs Constructor Injection in Spring

Spring Setter vs. Constructor Injection
Spring supports two types of dependency Injection, using a setter method, e.g. setXXX(), where XXX is a dependency or via a constructor argument. The first way of dependency injection is known as setter injection while later is known as constructor injection. Both approaches of Injecting dependency on Spring bean has there pros and cons, which we will see in this Spring framework article. The difference between Setter Injection and Constructor Injection in Spring is also a popular Spring framework interview questionSome time interviewer also asks as When do you use Setter Injection over Constructor injection in Spring or simply benefits of using setter vs. constructor injection in Spring framework. Points discussed in this article not only help you to understand Setter vs. Constructor Injection but also Spring's dependency Injection process. 

Decorator design Pattern in Java with Example Java Tutorial

I was thinking to write on decorator design pattern in Java when I first wrote 10 interview questions on Singleton Pattern in Java. Since design pattern is quite important while building software and it’s equally important on any Core Java Interview, It’s always good to have clear understanding of various design patterns in Java. In this article we will explore and learn Decorator Design pattern in Java which is a prominent core Java design pattern and you can see lot of its example in JDK itself. JDK use decorator pattern in IO package where it has decorated Reader and Writer Classes for various scenario, for example BufferedReader and BufferedWriter are example of decorator design pattern in Java. From design perspective its also good idea to learn how existing things work inside JDK itself for example How HashMap works in Java or How SubString method work in Java, that will give you some idea of things you need to keep in mind while designing your Class or interface in Java. Now let’s Move on to Decorator pattern in Java.

Friday, November 17, 2017

File permissions in UNIX Linux with Example >> Unix Tutorial

Whenever we execute ls command in UNIX you might have observed that it list file name with lot of details e.g.
stock_options:~/test ls -lrt
total 8.0K
-rw-r--r-- 1 stock_options Domain Users 1.1K Jul 15 11:05 sample

If you focus on first column you will see the file permissions as "-rw-r--r--" this is made of three parts user, group and others. User part is permission relate to user logged in, group is for all the members of group and others is for all others. also each part is made of three permissions read, write and execute so "rw-" means only "read and write" permission and "r--" means read only permission. So if you look permission of example file it has read and writes access for user, read only access for groups and others. Now by using chmod command in UNIX we can change the permissions or any file or directory in UNIX or Linux. Another important point to remember is that we need execute permission in a directory to go inside a directory; you can not go into directory which has just read and write permission.

Why Use Interface in Java or Object Oriented Programming

Many times, I have seen questions like why should we use interface in Java, if we can not define any concrete methods inside interface? Or even more common, What is the real use of interface in Java? I can understand beginners asking this question, when they just see name of the method inside interface and nothing else. It takes time to realize real goodness or actual use of interface or abstraction in Java or any object oriented programming. One reason of this is lack of experience in really modelling something real in program using object oriented analysis and design. In this article, I will try to answer this question and give you couple of reason to use interface in your code. If you have good understanding of Object oriented basics e.g. Polymorphism, then you know that it allows you to write flexible code. Interface or abstraction are key to achieve polymorphism, when a caller use interface for calling a method, he introduce flexibility and dynamism in code, as that code will work with any implementation of that interface, not just the present concrete implementation. You will never going to get this flexibility, if you use concrete classes for calling methods, we will see this in more details in next section. Also Programming for Interfaces, is also well recognized and one of the key object oriented design principle for coding. Another use of interface in Java is that, it opens new opportunities for other goodies e.g. design patterns. Lot's of design patterns are heavily relied on interfaces and Polymorphism e.g. Decorator, Composite, Proxy or Adapter pattern, all implements same interface, as there target, and because they are based on interfaces, they can be used interchangeably.

Thursday, November 16, 2017 Map failed and java.lang.OutOfMemoryError: Map failed

While working with memory mapped file, you may get Map failed error, which is mainly caused by Caused by: java.lang.OutOfMemoryError: Map failed error as shown below. This error usually comes while mapping a big file in memory e.g. trying to map a file greater than 1 or 2GB Map failed
Caused by: java.lang.OutOfMemoryError: Map failed
 at Method)
 ... 6 more

Tuesday, November 14, 2017

Java Array Tutorial and Example for Beginners

Array is one of the most important data structure in any programming language, at same time different programming languages implement and treat array differently. Any one who is done some programming knows value of array and importance of knowing about array type, using them in there program. Together with linked list, array forms a set of basic data-structures. Though Java offers excellent Collection API and some of collection classes like ArrayList and  HashMap , they are internally based on array.  If you are coming from C or C++ background then you will find some difference about how array behaves there and how it does in Java, most notable difference between array in C and array in Java is bounds checking. C compiler doesn't check if program is accessing valid array index, while in Java, JVM does that and throws ArrayIndexOutOfBoundException, if program tries to access invalid array index. In this Java article, we will take a look on array in Java, both primitive and object arrays. It's a collection of important things about Java array and there properties.

How to Make and Run batch .bat file in Windows 8

batch files and shell scripts are developers best friend, they help to improve productivity a lot. They not only help you to automate boring, time consuming task but also saves lot of time doing and doing them again. Batch file also reduce chances of error, once tested and encourage re-usability by sharing them across team or people with similar needs. Though not every programmer, developer or computer user has mindset to use batch file, something it's too difficult to write, some just not able to fight with initial resistance and many of them are not even aware of batch file. As a Java programmer, you really don't need to learn these stuff, as almost everybody who use windows operating system for more than year, knows about it. Anyway knowing is not enough, main thing is adapting and taking full advantage of them, developing mentality towards scripting, automation and writing batch files. Remember, shell scripting is one of the important skill to get a programming job and more important to support application running on UNIX operating sytem in Investment banking domain. Writing batch scripts are not full blown scripting, but it's lighter form of it, It works best to train yourself and develop that scripting mentality to improve productivity. In this article, we will learn how to write a batch file in windows 8 operating system and revisit some important things about batch file.

Monday, November 13, 2017

Difference between jQuery Document Ready Method and JavaScript Window Onload Event

Though both jQuery ready event and window onload event is used to perform task when page is loaded, there is subtle difference between them. jQuery document.ready method, which is not method but a jQuery event is fired, when DOM is ready i.e. all elements of DOM is available, but not necessarily all contents e.g. images and video, on the other hand JavaScript built-in window.onload event is fired when the HTML document is complete loaded, including DOM and all it's content e.g. images, audio and videos. Because of this reason, you may see that scripting code defined in jQuery $(document).ready() executes before code defined on window.onload event, especially if loading of images take long time. By the way difference between JavaScript window onload event and jQuery document.ready event is also one of the popular jQuery Interview Question, asked to both beginners and experienced web developers. In this article, we will explore some key differences between jQuery ready vs onload and will find it out when to use jQuery ready method vs window onload event.

Friday, November 10, 2017

Helloworld Example Java : How to run Java Program from command prompt

This article contains HelloWorld Example in Java and step by step guide to run Java program from command prompt. Beginners who just started to learn Java or using Java often struggled and doesn't know how to run a Java program from command prompt. Running a Java program is simple but setting up Java environment is rather cumbersome especially if you are new in Programming world and not
very familiar with words like PATH, CLASSPATH or even command prompt. I don't blame you because we all start at some point of time and even When I started to wrote my first Java program, What I was doing was simply typing HelloWorld from a textbook in a notepad editor, to my surprise my Java program ran without any issue because I was running that on school PC where PATH and CLASSPATH were already setups but when I tried the same thing on my home Windows PC I had tough time to run my Java program including HelloWorld Example in Java.

Wednesday, November 8, 2017

10 Examples of HotSpot JVM Options in Java

There are hundreds of JVM parameters or JVM Options exists inside sun JDK and its virtually impossible to keep track of every single JVM option and based on my experience we don't even use most of JVM flags except couple of important JVM option related to java heap size, java options for printing garbage collection details and most likely JVM switches for setting up remote debugging in Java. but there are many other useful category of JVM parameters which you at least like to be familiar even if not intending to use it more frequently. In this article we will see examples of 10 different categories of JVM parameter which I found useful and use more frequently than other. I would recommend to get a full knowledge of what does a particular JVM options does by referring official list of JVM options.

Tuesday, November 7, 2017

Difference between TreeSet, LinkedHashSet and HashSet in Java with Example

TreeSet, LinkedHashSet and HashSet all are implementation of Set interface and by virtue of that, they follows contract of Set interface i.e. they do not allow duplicate elements. Despite being from same type hierarchy,  there are lot of difference between them; which is important to understand, so that you can choose most appropriate Set implementation based upon your requirement. By the way difference between TreeSet and HashSet or LinkedHashSet is also one of the popular Java Collection interview question, not as popular as Hashtable vs HashMap or ArrayList vs Vector but still appears in various Java interviews. In this article we will see difference between HashSet, TreeSet and LinkedHashSet on various points e.g. Ordering of elements, performance, allowing null etc and then we will see When to use TreeSet or LinkedHashSet or simply HashSet in Java.

What is Static Variable Class method and keyword in Java - Example Tutorial

What is Static in Java
Static in Java is an important keyword and used to create static method, static class and static variable in Java. Correct understanding of static keyword is required to understand and write sophisticated Java programs. Java 5 also introduced static imports along with Autoboxing, Generics, Enum and varargs method, which allows to import static members of one class or package into another using import keyword and then using them like they are member of that class. In this Java tutorial we will learn about What is is static in Java, What does it mean to be a static field, static class or method in Java and various points and issues involved around How to use static members in Java. This Java tutorial is also about how to use static keyword in Java and where not to use static keyword. Common rule is anything which you want to share between all object can be made static e.g. singleton instance of a  Singleton Class in Java.

Monday, November 6, 2017

Difference between final, finally and finalize method in Java

What is the difference between final, finally and finalize method is asked to my friend in a Java interview with one of the US based Investment bank. Though it was just a telephonic round interview, he was asked a couple of good questions e.g. how to avoid deadlock in Java, How to get() method of HashMap works and one of the puzzles which are based on recursion. In short final keyword can be used along with variable, method and class and has a different meaning for all of them. finally is another Java keyword which is used in Exception handling along with try, catch, throw and throws. finalize() is a special method in Java which is called by Garbage Collector before reclaiming GC eligible objects. In this Java interview questions article, we will compare final vs finally vs finalize and highlight some important difference between final, finally and finalize method in Java.

Sunday, November 5, 2017

10 Examples of tar command in UNIX and Linux

tar command in UNIX or Linux is one of the important command which provides archiving functionality in unix. we can use UNIX tar command to create compressed or uncompressed archive files by using either gzip or bzip2. In this unix tar command tutorial we will see examples of unix tar command related to basic archiving task e.g. How to create tar archive in Unix and Linux, How to extract files from tar archive in unix, How to view contents of tar file in Unix and Linux or how to update and existing tar file in Unix. Examples of tar command in unix are kept simple and easy to understand and master each of basic task using unix tar command.

Saturday, November 4, 2017

5 Free OCAJP8, OCPJP8 Mock Exams and Practice questions - 1Z0-808 809 (Java 8 Certification)

In order to do well on Java certifications, you need good books and a reasonable number of practice questions before you go for exams. Practice questions and mock exams will help you to assess your topic-wise preparation level and help you to identify your strong and weak areas. Based on the result of the mock exams, you can concentrate on areas where you lack expertise e.g. multi-threading is one of the tricky areas. It will also expose you to exam patterns and different types of questions you can expect in examination e.g. multiple choice questions, rearranging code, fill in the blanks etc. Though I highly recommend commercial exam simulators like Whizlabs and Enthuware, I also suggest you take advantage of many mock questions which are freely available.

4 Ways to Search Java Array to Find an Element or Object - Tutorial Example

Searching in Java Array sounds familiar? should be,  because its one of frequently used operations in Java programming. Array is an index based data structure which is used to store elements but unlike Collection classes like ArrayList or HashSet which has contains() method, array in Java doesn't have any method to check whether an element is inside array or not. Java programming language provides several ways to search any element in Java array. In this Java tutorial we will see 4 examples of searching Array in Java for an element or object.  Every example is different than other and some of them are faster and others are slow but take less memory. These technique also valid for different types of array e.g. primitive and object array. I always suggest to prefer List over Array until you need every bit of performance from your Java application, it not only convenient to work but also more extensible.

Friday, November 3, 2017

Why use @Override annotation in Java - Coding Best Practice

@Override annotation was added in JDK 1.5 and it is used to instruct compiler that method annotated with @Override is an overridden method from super class or interface. Though it may look trivial @Override is particularly useful while overriding methods which accept Object as parameter just like equals, compareTo or compare() method of Comparator  interface. @Override is one of the three built in annotation provided by Java 1.5, other two are @SuppressWarnings and @Deprecated. Out of these three @Override is most used because of its general nature, while @SuppressWarnings is also used while using Generics, @Deprecated is mostly for API and library. If you have read my article common errors while overriding equals method than you have see that one of the mistake Java programmer makes it,  write equals method with non object argument type as shown in below example:

How to override compareTo method in Java - Example Tutorial

compareTo in Java is in the same league of equals() and hashcode() and used to implement natural order of object, compareTo is slightly different to compare() method of Comparator interface which is used to implement custom sorting order. I have seen during java interviews that many Java programmers not able to correctly write or implement equals(), hashCode() and compareTo() method for common business objects like Order or Employee. Simple reason behind this is that they either not understand the concept well enough or doesn't write this stuff at all. I will try to fill that gap in this Java tutorial and will see What is compareTo() method in java, how to write compareTo in Java and things to remember while implementing compareTo in Java.

Thursday, November 2, 2017

Prefer TimeUnit Sleep over Thread.Sleep - Java Coding Tips

What is TimeUnit in Java
in Java is a class on java.util.concurrent package, introduced in Java 5 along with CountDownLatch, CyclicBarrier, Semaphore and several other concurrent utilities. TimeUnit provides a human readable version of Thread.sleep() method which can be used in place of former. From long time Thread's sleep() method is standard way to pause a Thread in Java and almost every Java programmer is familiar with that. In fact, sleep method itself is a very popular and has appeared on many Java interviews. The difference between wait and sleep is one of the tough Java questions to answer. If you have used Thread.sleep() before and I am sure you do, you might be familiar with a fact like it's a static method, it doesn't release the lock when pausing Thread and it throws InterruptedException