How to Become an Expert Developer

I've been asked several times about how to become an expert developer, so I decided to finally answer this question to the best of my ability. Of course there is no single path to expertise that works or is right for everyone. It depends a lot on what industry you are developing software for, and what tools your company uses etc. Anyways, in this text I'll present a general "path" to expertise which you can adapt to your own situation.

Keep in mind as you go through this text, that there is a difference between being an expert, and being perceived as an expert. Lots of people are being promoted as experts, who really aren't. But, if people believe they are, they still make lots of money, being only mediocre. Additionally, there are many experts that nobody knows are experts. If you truly are an expert, your next move would be to also be perceived as an expert. How to become that is out of the scope of this text though. That's a different story about personal branding etc.

What is an "Expert", and How Long Time Does it Take to Become One?

Before I start discussing how to become an expert, let me spend 30 seconds on what an expert is, and how long time it takes to become one.

No, you are not an expert after 3 months of using a skill, nor after 3 years. According to the book "Outliers" by Malcom Gladwell, it takes 10.000 hours on average to become a true expert. A virtuous if you like. 10.000 hours! That's 10 hours a day, every day, for 3 years. Or, more likely, 5 hours a day, 200 days a year, for 10 years. 10 years!

Along this claim, I've noticed that I believed I was an expert or senior developer already after about 3 years of experience. Now, in 2010 with about 10 years of experience, I've learned how much there is to know, and how much I still don't know, and now I don't feel like such an expert anymore.

Additionally, the industry (Java enterprise development) has changed a lot over the last 10 years, so the skill I used to master, are not all that "cool" anymore. So even if you are an expert, you may find yourself becoming obsolete, and having to start over.

One more thing: You are seldom an expert in everything, meaning you may be better than person B in one skill, and person B may be better than you in another skill. It's not like you are either better in every skill than someone else, or worse. You can almost always learn something from everyone. Several developers I have met act as if they know everything best, even when the clearly don't.

In fact, this is often a way to spot a noob. The believe they know it all, and will argue to death either online or offline. They will argue in absolutes, like "This is ALWAYS better than that", or "This is THE way to things" etc. Experts rarely do that. They know, that it all depends on situation, skills your developers have, tools chosen by your company, company policies, personal preferences etc. Inexperienced developers (and people in general) tend to believe the world is black and white. Experts know, it's full of gray scales, and even lots of additional colors and shades.

How to Become an Expert

For most skills you need to learn, there are four steps that will help you become an expert. Most often you will go through these steps in sequence, yet with iterations up and down the steps on the way too. Here they are:
  • Learn it
  • Do it
  • Discuss it
  • Teach it

Learn it

Before you can master a skill you must learn it in theory. You can do this via books, tutorials, via education, or by messing around with it.

Do it

Once you have learned the skill in theory, you need to apply the skill in reality. By applying your skill in reality, you learn where the theory you learned is right, and where it is wrong. Yes, often universities will teach you theory that doesn't work in reality, or that doesn't apply in your situation.

Discuss it

Once you have used your skill for a longer period, and find that you were able to solve pretty much any problem thrown at you, which required this skill, it is time to discuss the skill with other experienced people. Discuss what the best ways to apply the skill is, where the limits of the theory are, what could be added etc. In short, discuss how to push the skill even further (e.g. an API. How to make it better / different etc.).

Through discussion you will learn a lot from other people, even if you thought you new it all.

Teach it

Teaching your skill to others is a really great way to polish the last corners of your skill. There may be many things to just do, without thinking about why you do them like that. Having to explain your ways and methods forces you to think about why you do what you do.

Additionally, there may be corners of your skill that you have never needed to master (say, corners of the web service specification). Having to teach your skill will force you to also master these corners too, making you better than you were before.

How to Become an Expert Developer

Now that I've talked about becoming an expert in general, I'll talk a bit more about how to become an expert developer.

As a developer you will most likely be developing software for a specific industry (at least for a while), and using a specific platform. If not, if you are switching tools and industry constantly, like some web developers do, you will most likely never become a real expert. You will become a Jack-of-All-Trades, which is also useful in some situations. If you are not focused on platform and industry, and you want to become an expert, you need to focus.

On your path to expertise, you will have to chose a platform, and possibly an industry too. Industry is less important, but having business domain knowledge really strengthens your profile.

When learning a platform you will start out with the language. For instance, the Java language. After the language you need to learn the platform (all the API's and tools). In Java, the platform is divided in two: The standard edition and the enterprise edition.

Once you begin to master your platform, you should start learning platform independent skills, like design patterns, distributed system design, architecture, usability etc. As you get better, you will spend more and more time learning these skills. This is a good thing. These skills are more easily transferable to a new technology platform.

Finally, you may move away from software development all together, moving into different business areas like project management, an architect job etc. Just remember, that once you stop using your developer skills, you will slowly stop being an expert.

You have to fill in the concrete tools, techniques etc. for your industry, your company, and your platform. This is not something I can do once and for all, for everyone.

A good way to find out what you should learn is to look at job ads. What tools and techniques are they requiring most often? Read software magazines online. What technologies are they talking most about? Read forums. What technologies are people asking most questions about? And, what technologies are people buzzing most about? In other words, what will become hot tomorrow?

How to Become an Expert Developer

What is scoped memory and why java uses it?

In java, a frequent occurrence of a common phenomenon related to memory management is creation and destruction of temporary objects.

What are java temporary objects?

For example in java, when two strings are concatenated, a StringBuffer object is created. As two Java String objects cannot be added directly (immutable property), a helper object StringBuffer is used to construct a resultant java String object. This StringBuffer object is a temporary object, which is of no direct interest to the programmer.

Most of the programming constructs are built in this type of model. Result of it is there are lot of garbage left behind.

Now the question is, what happens to the temporary java object and such garbage after the intended operation completes? Will it be saved for the life time of the program, or JVM (java virtual machine) or what is the underlying policy to destroy it?

In automatic memory management the hassles of allocating and deallocating memory is no more a part of programmer’s job in java. But the downside of it is you never know, when an object will be freed. The java garbage collector (GC) doesnot provide any defined time boundaries.

This is where the java scoped memory concept comes into picture. Scoped memory concept is declaring to the JVM that, I am going to use this much amount of memory and those can be freed after this period. That is defining a boundary and bringing predictability. This predictability is needed the most for real time programming. Where you need to be certain about the cycles, time and cost of the operation.

What is scoped memory in Java

In java scoped memory, the memory is preallocated for the task. This will ensure that the program will not get struck in the mid of operation because of memory resource shortage and constraints. Memory is deallocated and freed when the associated task gets completed. Therefore the recycling process of the memory is fast. But, all the objects related to that task and comes under that designated scope will disappear. If some objects are needed for future reference then that particular object needs to be associated to a different memory mechanism.

This is one of the latest feature in java adding power to the real-time java implementation. For more detail look into the Oracle Java Real-Time System (Java RTS). It is Oracle’s commercial implementation of the Real-Time Specification for Java (JSR-001).

What is scoped memory and why java uses it?

AngularJS : Hello World Example

AngularJS is a java script framework developed by google. It is a library written in JavaScript. AngularJS extends HTML directives and binds data with HTML expressions.

AngularJS is based on the MVC pattern (Model View Control). Therefore AngularJS separates your RIA (Rich Internet Applications) application into models, views and controllers.

View - The views are specified using HTML + AngularJS's own template language.

Models and Controllers - The models and controllers are specified via JavaScript objects and JavaScript functions.

Thus, the views are specified declaratively, as HTML normally is, and the models and controllers are specified imperatively, as JavaScript normally is.

If you don't know the difference between declarative and imperative programming, don't worry. It is not important to know before learning AngularJS. Besides, it is pretty simple to find the definition on the web.

The MVC model is an example of what computer scientists and developers call a design pattern. It’s not a concept specific to Angular, but rather an approach to program architecture which has been implemented successfully across a variety of programming languages and environments, and which has been found to yield some good practical efficiencies as a time-tested design.

AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag: AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:

NOTE : - It is a good idea to place scripts at the bottom of the body element.This improves page loading, because HTML loading is not blocked by scripts loading.

AngularJS Hello World Example :

AngularJS applications are a mix of HTML and JavaScript (as you have already seen) so the first thing we need is an HTML page :

<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>

Second, we need to include the AngularJS JavaScript file in the HTML page so we can use AngularJS:

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>


Third, we need to tell AngularJS what part of our HTML page contains the AngularJS app. You do so by adding the ng-app attribute to the root HTML element of the AngularJS app. Typically, the root element is either the html element or thebody element. In this example I insert the ng-app attribute into the body element:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<body ng-app="myapp">
</body>
</html>

Fourth, we need a view. A view is a section of HTML which is enclosed in an HTML element. Here is an example:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="HelloController">
<h2> Hello {{helloTo.title}} !</h2>
</div>
</body>
</html>

Fifth, we need a controller function. A controller function is a normal JavaScript function which takes a single parameter: The $scope parameter. The $scope parameter is the model object to be used by the controller function and the corresponding view. The controller function can insert data and functions into the model object. The view can then use the data and the functions.

Here is our little web app with the controller function inserted:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="HelloController">
<h2> Hello {{helloTo.title}} !</h2>
</div>
<script>
angular.module("myapp", [])
.controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "World, AngularJS"; });
</script>
</body>
</html>

The controller function is registered in angular via the angular.module(...).controller(...) function call.

The angular object is a global object created by the AngularJS JavaScript which is included at the beginning of the page.

Notice the first of the parameters to the angular.module()function call. The value of that parameter is
"myapp". This name matches the name specified in the ng-app attribute in the body element. This way AngularJS knows that the controller function being registered belongs to the myapp module, which happens to be the module which this AngularJS application is using (specified in the ng-app attribute in the body element).

The controller() function call is what registers the controller function itself. The first parameter passed to the controller() function is the name of the controller function. This is the name you refer to in the ng-controller attribute of the view. The second parameter is the controller function itself.

AngularJS : Hello World Example

Java Polymorphism Tutorial with Examples

Polymorphism is THE concept to master if you want to master object-oriented programming. Because Java is an object-oriented language, it makes sense that you should learn the concepts and power of polymorphism in Java.

Simply put, polymorphism is what allows actions to act differently based on the object performing the action or the object the action is being performed on. Let's just use a super simple, real life example. What is a typical sound that a cat makes? Let's just say it's meow. Let's call this action makeSound() because remember, a method can represent an action. What sound does a dog make? Let's just say a dog goes woof. We can also call this action makeSound(). Let's also just pretend that all animals can makeSound(). Thus, makeSound(), depending on the type of animal, does something different. The action acts differently based on the object.

This concept of polymorphism in Java especially, is actually not hard to understand at all. Oh look, different animals make different sounds, and the same method can be used to make each distinct sound. If you've done the Java inheritance tutorial, you already know how to do this!.

One powerful tool for using polymorphic behavior is to use the same method name but in the same class, over and over again to get the desired effects you want. How can we use polymorphism in Java to accomplish this?

Overloaded Methods

Let's use our makeSound() example again. Let's say a dog makes a woof sound, but if the dog is injured, the dog might make a whimper noise instead. How can we use makeSound() to produce both sounds? Take a look at this code snippet:
public class Dof extends Animal{
 public void makeSound(){
  System.out.println("Woof!");
 }
 public void makeSound(boolean injured){
  System.out.println("Whimper");
 }
}


NOTE: At this point, if you're not sure you understand the code you see, you REALLY should go back to the Intermediate Tutorials and read the tutorial on Methods In Java. Then you can come back to learn about polymorphism in Java once you have a better understanding of methods.

We can see here that depending on the number of parameters we pass to makeSound(), the dog will make a different sound. But wait! Couldn't we have just used an if statement and make this just one method? Yes, we could have done that and that's probably a better way of programming this for this particular example. What if an outside action causes the difference in dog sound though? Something like this:
 

public void makeSound(boolean injured){
  if(injured){
   System.out.println("Whimper");
  }
 }


If the dog did not have the variable to know it was hurt, you would not be able to write that if statement as easily. You can overload a method as much as you want as long as the number of parameters are different or the types of parameters are different. You could not do this for example:
 

public void makeSound(int x, int y){

 }
 public void makeSound(int dog, int cat){

 }


This is because those are the same number of parameters AND are the same types of parameters.

Overridden Methods

In Java, you can create a method in a superclass (or parent class), then in a subclass ALSO define that method. Let's see an example of this using Animal:
public abstract class Animal{
 public void makeSound(){
 }
}
public class Dog extends Animal{
 public void makeSound(){
  System.out.println("Woof!");
 }
 public void makeSound(boolean injured){
  if(injured){
   System.out.println("Whimper");
  }
 }
}
public class Cat extends Animal{
}


Now, let's say you could actually create Animals. If you could, then calling makeSound() would call the method defined in the superclass. If you create a specific Dog, calling makeSound() will display "woof". Now let's say you created a specific Cat. In that example, Cat does not have a makeSound() method, so when you call makeSound() on Cat, it calls the method in the superclass Animal and does nothing. Remember, Cat and Dog are subclasses of Animal because they extend Animal.

This behavior is called method overriding, and it is EXTREMELY powerful stuff when it comes to polymorphism in Java. Java will let you do this because its possible more specific types of objects have more specific behaviors for actions. How does Java then know which method to actually call? Java will always pick the object's true type for choosing which method to call, the superclass or the subclass. We will see what true type really means in the next section.

Dynamic Method Binding

Do not let the long name confuse you. This is not that scary of a term! We won't discuss why this is dynamic, but let's just say that Java decides what method to call during runtime, or once the program is running. Dynamic method binding is how Java decides what method to call when it has to decide between the superclass and the subclass. So, how exactly does it decide? To illustrate this point, we must first illustrate the concept of true type versus referenced type.
public static void main(String[] args){
 Animal dog = new Dog();
}


Look, we just made a Dog but declared it as an Animal! Normally you would see this:
public static void main(String[] args){
 Dog dog = new Dog();
}


However, you can also declare a variable by its supertype or abstract type to make it more generic. Let's say you don't know what kind of animal you want:
public static void main(String[] args){
 Animal animal;
}


Notice how the variable is not assigned to anything! We have an animal that has not been instantiate, and it does not equal anything. We can't create just Animals because they are abstract, so we must make a specific kind of animal, which is what we did with the example above by making the Animal be a new Dog.

So, which version of makeSound() would you use if you saw Animal animal = new Dog() ? Would you choose the Animal's version or the Dog's version? The answer is that Java will choose the true type, and the true type is the object that actually gets created. In this example, what we are really creating is a Dog, even though we are referencing the variable as an Animal.

Why in the world wouldn't we just do Dog dog = new Dog() ? The answer is that by using abstraction, you can actually group many different types of objects together. Let's see how we can use this concept for storing objects:

public static void main(String[] args){
 Animal dog = new Dog();
 Animal cat = new Cat();
 ArrayList<animal> animals = new ArrayList<animal>();
 animals.add(dog);
 animals.add(cat);
}


We could not do the above if the Cat objects and Dog objects were made the traditional way and not by referencing them as Animals.
It is very important you do not flip the reference and the true type! You could not do this:
public static void main(String[] args){
 Dog dog = new animal();
}


First of all, in our example, you cannot create Animal objects because they are abstract. Let's assume you could though. This is still illegal because a specific type cannot be the reference of a more broad type. Think about it this way: A dog is an animal but an animal is not necessarily a dog. The above example is basically saying that an Animal is a Dog, and this is not always true.

Polymorphism in Java allows you to fully control how you group objects together and gives you the power to make them as specific as you want. It is also the crucial part of object-oriented programming that allows you to build hierarchies of objects, objects that have a logical structure that makes sense in the real world. Because of polymorphism, you can create highly sophisticated programs in Java that are easy to read and are well organized. It does not guarantee an awesome organization of your code, but if you're careful it can help you immensely in doing so.

My final advice about polymorphism in Java is to practice! Practice making a bunch of abstract and regular classes. Create your own object structures. Make different objects extend each other. Write the same methods over and over again using different parameters and putting them in the parent classes and subclasses. Then, test out your objects by writing a main class that uses the classes and methods you write in different ways. By doing so, you will be on your way to mastering this highly abstract, highly powerful concept!.

Polymorphism In Java

Checked Exceptions Vs Unchecked Exceptions in Java

Types of exceptions in java are checked exceptions and unchecked exceptions. This classification is based on compile-time checking of exceptions. There is also a classification based on runtime in java. It is not widely known! That is synchronous and asynchronous exceptions. First let us see the java checked exceptions and unchecked exceptions.

Checked Exceptions Vs Unchecked Exceptions in Java

At compile time, the java compiler checks that a program contains handlers for checked exceptions. Java compiler analyzes by which checked exceptions can result from execution of a method or constructor.For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class or its superclasses of that exception.

The class RuntimeException and its subclasses, and the class Error and its subclasses are unchecked exceptions classes. Because the compiler doesn’t forces them to be declared in the throws clause. All the other exception classes that are part of Throwable hierarchy are checked exceptions.
Now let us see a see small discussion on why exceptions are classified as checked exceptions and unchecked exceptions.

Those unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking in java because they can occur at many points in the program and recovery from them is difficult or impossible.

Example: OutOfMemoryError

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java, having to declare such exceptions would not aid significantly in establishing the correctness of programs.

Example:NullPointerException

Thrown when an application attempts to use null in a case where an object is required.
So the java compiler doesn’t forces them to be declared in the above two cases.

Synchronous and Asynchronous Exceptions in Java

The interpreter executes the java program sequentially. An exception E can occur relative to a line (L) of program. That is that exception E will always occur at the execution of that line L. This is called Synchronous exception.
An asynchronous exception in java can occur at any point in the execution of a program. They occur only as a result of:
  • An invocation of the stop methods of class Thread or ThreadGroup
  • An internal error in the Java virtual machine
Checked Exceptions Vs Unchecked Exceptions in Java

Lamba expressions in Java 8

Background

Functional Interface :

In single line description, Interface with only abstract method are referred as Functional Interface. However, A functional interface can have more than one static or default methods, and also can Override some methods from java.lang.Object.
Luckily you do not need to verify the Functional Interface, Compiler will do it for you. But you can specify @FunctionalInterface annotation to reduce it’s workload.

Below is an example of Functional interface.

interface Demo {
    // Only abstract method. void abc(Collection collection);
    // Functional interface can have more than one static or default methods.
    default void cdf() {
    System.out.println("This is default in Functional Interface.");
}
// And also can override methods of java.lang.Object
@Override
public String toString();
}

Vertical problem :

The main problem with Anonymous classes are the syntax. For some simple operation we need to write additional syntactical code each time (However this is not true in some cases, described later in this article).
The problem of bulky syntax is refereed as “Vertical problem” by Java people.

For example : consider the ActionListener interface

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // Do some operation.
    }
});

Above code uses additional code lines each time when you write the anonymous ActionListener class, Just to avoid writing extra class implementing ActionListener interface.

What is a Lambda Expression ?

Lambda expressions are anonymous methods, aimed at mainly addressing the “vertical problem” by replacing the machinery of anonymous inner classes with a lighter-weight mechanism in applicable cases.
@FunctionalInterface
interface IsFunctional {
    void testMetod(String data);
}
class LambdaChild {
    // With Anonymous class.IsFunctional isFunc = new IsFunctional() {
    @Override
    public void testMetod(String data) {
        System.out.println("Printing " + data + " from Anonymous class.");
    }
};
    // With lambda expression.
    IsFunctional func = ( demoData ) -> {
        System.out.println("Printing " + demoData + " from Lambda expression.");
    };
}

Lambda expressions are implementation of only abstract method of functional interface that is being implemented or instantiated anonymously.

In above example, first one is the traditional way by creating anonymous inner class that will implement IsFunctional interface and Override testMethod().

Second one is brand new Lambda, with light syntax and no additional typing overhead.

The statements between {…} are body part of Overridden method and (…) are arguments passed to the method.

I can see a suggestion in my NetBeans IDE 8.0 “Use Lambda Expression” where anonymous class is written in above example.

Structure of Lambda expression :

Lambda expression syntax can be divided into three parts.
  1. Arrow (->) token
  2. Argument List :
A lambda expression can contain zero or more arguments.
// No argument.
    () -> { 
        System.out.println("No argument"); 
    }
    // Single argument.
    (int arg) -> { 
        System.out.println("Single integer argument : " + arg); 
    }
    // More than one arguments.
    ( int arg1, String arg2 ) -> { 
        System.out.println("Two arguments : " + arg1 + " and " + arg2); 
    }

You can eliminate the argument type while passing it to lambda expressions, those are inferred types. i.e. ( int a ) and ( a ) both are same.

More than one arguments are separated by comma (,) operator.

You can also eliminate “()” if there is only argument to avoid Horizontal Problem.
    ( arg ) -> {...} can be written as arg -> {...}

You can not use inferred and declared types together, Following is invalid.
    ( int arg1, arg2 ) // This is invalid

Body of a lambda expression :

Body can be a single expression or a statement block.
If a body contains only single expression than expression will be simply evaluated and returned.
    () -> System.out.println("No argument");

If a body is statement of block, than it will be evaluated same as a method body, that will be called and a hidden return statement at the end block that will return control to caller after execution of block. So, branching statements ( continue and break ) are illegal and return is not necessary to write.
    () -> {
        System.out.println("Bad lambda");
        break ; // this statement is not allowed here.
    }

Type of a Lambda expression :

Example :
    @FunctionalInterface
    interface IsTypeOne {
    // #1 Only abstract method of IsTypeOne
    public void hasOne();
    }
    @FunctionalInterface
    interface IsTypeTwo {
        // #1 Only abstract method of IsTypeOne
        public void hasTwo();
    }
    class TestType {
        // #2 Method parameter is of type IsTypeOne
        public void first( IsTypeOne one ){
        //#5 Method that is overridden by Lambda will be called.
        one.hasOne();
    }
    //#6 Method parameter is of type IsTypeTwo
    public void second( IsTypeTwo two ){
        //#9 Method that is overridden by Lambda will be called.
        two.hasTwo();
    }
    public void invoke() {
        //#3 Here labmda type is "IsTypeOne", because first() has parameter of type "IsTypeOne"
        //#4 Body {...} of lambda is body part of Overridden hasOne method.
        first(() -> { System.out.println("Invoking first."); });
        //#7 Here labmda type is "IsTypeTwo", because second() has parameter of type "IsTypeTwo"
        //#8 Body {...} of lambda is body part of Overridden hasTwo method.
        second(() -> { System.out.println("Invoking second."); });
   }
}

Explanation of above example :

#1 : IsTypeOne and IsTypeTwo are two different functional interfaces with only abstract method hasOne and hasTwo respectively.
#2 : Parameter type of first() method in TestType class is IsTypeOne
#3 : first() method is called from invoke() method having lambda as argument, So lambda is of type IsTypeOne.
#4 : Lambda expression is Overriding hasOne() of IsTypeOne interface as anonymous method.
#5 : Method Overridden by lambda expression will be called.
#6 : Parameter type of second() method in TestType class is IsTypeTwo
#7 : second() method is called from invoke() method having lambda as argument, So lambda is of type IsTypeTwo.
#8 : Lambda expression is Overriding hasTwo() of IsTypeTwo interface as anonymous method.
#9 : Method Overridden by lambda expression will be called.

The compiler is responsible for inferring the type of each lambda expression. It uses the type expected in the context in which the expression appears; this type is called the Target type.

In above example, target type of first() at #3 is IsTypeOne, so Compiler will use lambda type as IsTypeOne and target type of second() at #7 is IsTypeTwo, so Compiler will use lambda type as IsTypeTwo.

A lambda expression can only appear in a context whose target type is a functional interface.

A lambda expression can be assigned to a Reference which is of target type T if all of the following conditions hold:

T is a functional interface type

The lambda expression has the same number of parameters as T’s method, and those parameters’ types are the same.

Each expression returned by the lambda body is compatible with T’s method’s return type

Each exception thrown by the lambda body is allowed by T’s method’s throws clause

When to use a lambda ?

Lambda is replacement of Anonymous class ? NO, Lambdas are anonymous functions which are designed to eliminate overhead (Constructor and other bulky code) of Anonymous class where it is not required.

Anonymous class :

If you want to declare constructor, some variables and going to write additional methods that will not be part of Interface, Then use Anonymous class.

Lambda Expression :

If you want to implement only method of functional interface, than use Lambda expressions or you want to pass that to other code.

Lamba expressions in Java 8

Hope we are able to explain you java Lamba expressions, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Swap two numbers without using third variable in Java

Swapping two numbers without using third or temporary variable is one of the most commonly asked question not just on Java but also on C and C++ tests and interviews. Swapping two numbers or strings is a very easy question till the condition of using only two variable is not applied, lots of freshers failed to solve this swap without using the third variable. Mostly we come out with a solution with just arithmetic operator but if the test level is little up and asks about other approaches of swapping two variables without using third or temp variable, than you have to look over this little program.

Since you are looking for a swap two numbers program in java without using any temp variable, let me tell that this post is a complete resource to learn different approaches on swapping two numbers without using third variable.

We just have to swap (interchange) the 2 numbers, stored in 2 different variables. Don't forget we are not using the third variable.

Example:
INPUT> x=12 & y=53
OUTPUT>x=53 & y=12

as I told you earlier, you may be asked to swap two numbers with different approaches without using any temporary or third variable. This post contains four methods to do so!

Method 1: Swapping Using Arithmetic Operator
In 90% of cases this method strikes first to a fresher while swapping without using third variable.

import java.io.*;
class swap{
        public static void main(String args[]) throws IOException{
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter 1st no: ");
            int x=Integer.parseInt(br.readLine());
            System.out.print("Enter 2nd no: ");
            int y=Integer.parseInt(br.readLine());
            System.out.println("\nNumbers Before Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
            //Swapping Method 1
            x=x+y;
            y=x-y;
            x=x-y;
            System.out.println("\nNumbers After Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
        }
}

Method 2: Swapping Using Bitwise Operators
Second approach two swap to numbers without using third variable is using XOR bitwise operators.

import java.io.*;
class swap{
        public static void main(String args[]) throws IOException{
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter 1st no: ");
            int x=Integer.parseInt(br.readLine());
            System.out.print("Enter 2nd no: ");
            int y=Integer.parseInt(br.readLine());
            System.out.println("\nNumbers Before Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
            //Swapping Method 2
            x = x^y;
            y = x^y;
            x = x^y;
            System.out.println("\nNumbers After Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
        }
}

Method 3: Swapping Using Multiplication & Division
Like  Method 1 where we swapped two numbers x and y without using third variable by the simple logic of addition and subtraction, In this method we do the same swapping using multiplication and division logic keeping in mind that we don't have to use third variable.

import java.io.*;
class swap{
        public static void main(String args[]) throws IOException{
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter 1st no: ");
            int x=Integer.parseInt(br.readLine());
            System.out.print("Enter 2nd no: ");
            int y=Integer.parseInt(br.readLine());
            System.out.println("\nNumbers Before Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
            //Swapping Method 3
            x = x*y;
            y = x/y;
            x = x/y;
            System.out.println("\nNumbers After Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
        }
}

Method 4: Swapping Using 'One Line Logic!'
Now here comes my favorite method to swap two numbers... Its the best method for swapping because only one line logic is required for this.
x = y-x+(y=x);

import java.io.*;
class swap{
        public static void main(String args[]) throws IOException{
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter 1st no: ");
            int x=Integer.parseInt(br.readLine());
            System.out.print("Enter 2nd no: ");
            int y=Integer.parseInt(br.readLine());
            System.out.println("\nNumbers Before Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
            //Swapping Method 4
            x = y-x+(y=x);
            System.out.println("\nNumbers After Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
        }
}

Swap two numbers without using third variable in Java

Hope we are able to explain you Swap two numbers without using third variable in Java, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

program to check the given number is a prime number or not

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number. For example, 5 is prime, as only 1 and 5 divide it, whereas 6 is composite, since it has the divisors 2 and 3 in addition to 1 and 6. The fundamental theorem of arithmetic establishes the central role of primes in number theory: any integer greater than 1 can be expressed as a product of primes that is unique up to ordering. This theorem requires excluding 1 as a prime.
program to check the given number is a prime number or not


package com.tutorialsdesk.algos;   
public class MyPrimeNumCheck {       
public boolean isPrimeNumber(int number){                   
for(int i=2; i<=number/2; i++){             
if(number % i == 0){                 
return false;             
}         
}         
return true;     
}           
public static void main(String a[]){         
MyPrimeNumCheck mpc = new MyPrimeNumCheck();         
System.out.println("Is 17 prime number? "+mpc.isPrimeNumber(17));         
System.out.println("Is 19 prime number? "+mpc.isPrimeNumber(19));         
System.out.println("Is 15 prime number? "+mpc.isPrimeNumber(15));     
} 
} 


Hope we are able to explain you program to check the given number is a prime number or not, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

program to reverse a string using recursive algorithm in Java


Write a program to reverse a string using recursive methods.
You should not use any string reverse methods to do this.

package com.tutorialsdesk.algo;   
public class StringRecursiveReversal {       
String reverse = "";           
public String reverseString(String str){                   
if(str.length() == 1){             
return str;         
} else {             
reverse += str.charAt(str.length()-1)+reverseString(str.substring(0,str.length()-1));             
return reverse;         
}     
}           
public static void main(String a[]){         
StringRecursiveReversal srr = new StringRecursiveReversal();         
System.out.println("Result: "+srr.reverseString("Java2novice"));     
} 
}

program to reverse a string using recursive algorithm in Java

Hope we are able to explain you program to reverse a string using recursive algorithm in Java, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Writing a deadlock and resolving in java

In java, a deadlock is a situation where minimum two threads are holding lock on some different resource, and both are waiting for other’s resource to complete its task. And, none is able to leave the lock on resource it is holding. (See image below)

Writing a deadlock and resolving in java

In above case, Thread- has A but need B to complete processing and Similarly Thread-2 has resource B but need A first.

Let write above scenario in java code:

package thread;  
public class ResolveDeadLockTest {       
public static void main(String[] args) {         
ResolveDeadLockTest test = new ResolveDeadLockTest();           
final A a = test.new A();         
final B b = test.new B();           
// Thread-1         
Runnable block1 = new Runnable() {             
public void run() {                 
synchronized (a) {                     
try {                         
// Adding delay so that both threads can start trying to                         
// lock resources                         
Thread.sleep(100);                     
} catch (InterruptedException e) {                         
e.printStackTrace();                     
}                     
// Thread-1 have A but need B also                     
synchronized (b) {                         
System.out.println("In block 1");                     
}                 
}             
}         
};           
// Thread-2         
Runnable block2 = new Runnable() {             
public void run() {                 
synchronized (b) {                     
// Thread-2 have B but need A also                     
synchronized (a) {                         
System.out.println("In block 2");                     
}                 
}             
}         
};           
new Thread(block1).start();         
new Thread(block2).start();     
}       
// Resource A     
private class A {         
private int i = 10;           
public int getI() {             
return i;         
}           
public void setI(int i) {             
this.i = i;         
}     
}       
// Resource B     
private class B {         
private int i = 20;           
public int getI() {             
return i;         
}           
public void setI(int i) {             
this.i = i;         
}     
} 
} 

Running above code will result in deadlock for very obvious reasons (explained above). Now we have to solve this issue.

I believe, solution to any problem lies in identifying the root of problem. In our case, it is the pattern of accessing A and B, is main issue. So, to solve it, we will simply re-order the statements where code is accessing shared resources.

After rewriting the code, it will look like this ::

// Thread-1 
Runnable block1 = new Runnable() {     
public void run() {         
synchronized (b) {             
try {                 
// Adding delay so that both threads can start trying to                 
// lock resources                 
Thread.sleep(100);             
} catch (InterruptedException e) {                 
e.printStackTrace();             
}             
// Thread-1 have A but need B also             
synchronized (a) {                 
System.out.println("In block 1");             
}         
}     
} 
}; 
// Thread-2 
Runnable block2 = new Runnable() {     
public void run() {         
synchronized (b) {             
// Thread-2 have B but need A also             
synchronized (a) {                 
System.out.println("In block 2");             
}         
}     
} 
}; 

Run again above class, and you will not see any deadlock kind of situation. I hope, it will help you in avoiding deadlocks, and if encountered, in resolving them.


Hope we are able to explain you Writing a deadlock and resolving in java, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Java program to check armstrong number

This java program checks if a number is armstrong or not.

import java.util.*; 
class ArmstrongNumber
{
   public static void main(String args[])
   {
      int n, sum = 0, temp, r;
 
      Scanner in = new Scanner(System.in);
      System.out.println("Enter a number to check if it is an armstrong number");      
      n = in.nextInt();
 
      temp = n;
 
      while( temp != 0 )
      {
         r = temp%10;
         sum = sum + r*r*r;
         temp = temp/10; 
      }
 
      if ( n == sum )
         System.out.println("Entered number is an armstrong number.");
      else
         System.out.println("Entered number is not an armstrong number.");         
   }
}

Java program to check armstrong number


Hope we are able to explain you jJava program to check armstrong number, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Fibonacci Series Java Example

Fibonacci Series Java Example



/*
        Fibonacci Series Java Example
        This Fibonacci Series Java Example shows how to create and print
        Fibonacci Series using Java.
*/
 
public class JavaFibonacciSeriesExample {
 
        public static void main(String[] args) {
                
                //number of elements to generate in a series
                int limit = 20;
                
                long[] series = new long[limit];
                
                //create first 2 series elements
                series[0] = 0;
                series[1] = 1;
                
                //create the Fibonacci series and store it in an array
                for(int i=2; i < limit; i++){
                        series[i] = series[i-1] + series[i-2];
                }
                
                //print the Fibonacci series numbers
                
                System.out.println("Fibonacci Series upto " + limit);
                for(int i=0; i< limit; i++){
                        System.out.print(series[i] + " ");
                }
        }
}
 
/*
Output of the Fibonacci Series Java Example would be
Fibonacci Series upto 20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 
*/


Hope we are able to explain you Fibonacci Series Java Example, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Frequently Asked Programming and Coding Interview questions answers in Java

Here is my list of top Java coding interview questions and answers, which is good to prepare before appearing on any Java interviews. As I said Java coding questions are mostly based on programming, logical analysis and problem solving skill and are on top of any list of  tough Java interview questions, so better to get it right in first place. Any way you may be able to solve and find answers of these Java coding questions by yourself, but if you stuck do a google, and you can get many alternative ways to solve these problems. Some times knowing more than one way to solve any programming question or coding problem in Java also helps to impress interviewer. This list mainly contains basic programs asked on Interviews.
Frequently Asked Programming and Coding Interview questions answers in Java

1. Write a Java program to replace certain characters from String

This is a tricky Java coding interview question is asked in one of the written test my friend had appeared recently. This Java coding question can be solved in multiple way e.g. by using charAt() or subString() method,  but any approach throws couple of follow-up question e.g. you may be asked to write two version to solve this coding exercise, one by using recursion and other by using Iteration. They may also ask you to write JUnit test for this function which means handling null, empty string etc. By the way this programming question is quite common on technical interviews not just Java but also C, C++ or Scala, but knowing API definitely helps to produce better solution quickly.

2. Write a Java program to print Fibonacci series upto 100?

This is one of the most popular coding interview question asked in Java programming language. Even though, writing program for Fibonacci series is one of the basic Java program, not every Java developer get it right in interview. Again interview can ask to solve this programming interview question, by using recursion or Iteration. This Java programming question also tests your problem solving skills and if you come up with an original solution that may even help. See here for complete code example of Fibonacci series in Java.

3. FizzBuzz problem:

Write a Java program that prints the numbers from 1 to 50. But for multiples of three print "Fizz"instead of the number and for the multiples of five prints "Buzz". For numbers which are multiples of both three and five print "FizzBuzz"
This is also one of the classical programming questions, which is asked on any Java programming or technical interviews. This question is very basic but can be very trick for programmers, who can't code, that's why it is used to differentiate programmers who can do coding and who can't. Here is a sample Java program to solve FizzBuzz problem:
public class FizzBuzzTest{
 
    public static void main(String args[]){
    
        for(int i = 1; i <= 50; i++) {
            if(i % (3*5) == 0) System.out.println("FizzBuzz");
            else if(i % 5 == 0) System.out.println("Buzz");
            else if(i % 3 == 0) System.out.println("Fizz");
            else System.out.println(i);
        } 
    } 
}

4. Write a Comparator in Java to compare two employees based upon there name, departments and age?

This is pure Java based Coding exercise. In order to solve this Java coding or programming interview question you need to know What is comparator in Java and How to use compare method in Java for sorting Object. Sorting is one of the most logical and practical question on technical interview and ability to sort Java object is must to code in Java.  This article help you to solve this Java coding question by explaining how to sort object in Java using Comparable and Comparator. Just remember that Comparable has compareTo() method and use to sort object based upon there natural order e.g. numeric order for number, and alphabetic order for String, while Comparator can define any arbitrary sorting. A good followup question can also be difference between Comparator and Comparable in Java, so be ready for that.

5. Design vending machine in Java which vends Item based upon four denomination of coins and return coin if there is no Item.

This kind of Java coding interview question appear in written test and I believe if you get it right, you are almost through the Interview. These kind of problem solving questions in Java are not easy, you need to design , developer and write JUnit test within 2 to 3 hours and only good Java developers, with practical coding experience can solve this kind of Java programming question. What helps you is to keep practicing your coding skill even before interview. See this programming exercise in Java to get yourself going. I personally like to ask programming questions, which test your object oriented design skills e.g. designing ATM machine, designing parking lot or implementing logic for Traffic Signal controller.

6. Write a Java program

Another popular logical coding interview questions in Java, which is based on programming logic. In order to answer this programming question, you need to know what is Armstrong number, but that is not a problem because question may specify that and even provide sample input and output. Key thing to demonstrate is logic to check if a number is Armstrongor not. In most cases, you can not use utility methods defined by logic and you need to produce logic by yourself by using basic operators and methods. By the way this is also one of the basic programming questions and I have already provided asolution for this. I suggest to see this Java program to find Armstrong Number in Java to answer this coding question.

7. Write a Java program to prevent deadlock in Java ?

Some of the programming or coding interview question is always based on fundamental feature of Java programming language e.g. multi-threading, synchronization etc. Since writing deadlock proof code is important for a Java developer, programming questions which requires knowledge of concurrency constructs becomes popular coding question asked in Java Interviews. Deadlock happens if four condition is true e.g. mutual exclusion, no waiting, circular wait and no preemption. If you can break any of this condition than you can create Java programs,which are deadlock proof. One easy way to avoid deadlock is by imposing an ordering on acquisition and release of locks. You can further check How to fix deadlock in Java to answer this Java programming questions with coding in Java.

8. Write Java program to reverse String in Java without using API functions ?

Another classic Java programming or coding exercise mostly asked on 2 to 5 years experienced Java interviews. Despite being simple answering this coding question is not easy, specially if you are not coding frequently. Its best to prepare this programming question in advance to avoid any embarrassment during interviews. I suggest to see this post which shows How to reverse String using recursion in Java

9. Write a Java program to find if a number is prime number or not

One more basic Java program, which made it's way to Interviews. One of the simplest coding question and also a very popular Java programming exercise. Beauty of these kinds of logical questions is that, they can really test basic programming skills or a coder, programmer or developer. Not just problem solving, you can also check there coding style and thought process. By the way. you can  check this article.

10. How to Swap two numbers without using third variable in Java?

This Java program might require just four lines to code, but it's worth preparing. Most of the programmers make same kind of mistakes, while writing solution for this program e.g. Integer overflow, they tend to forget that integer can overflow if it's limit exceeded, which is not very big. Sure shot way to answer this programming questions is to use XOR trick to swap numbers, as mentioned in that blog post.

11. Write a Java program to calculate Factorial of a number in Java?

This Java coding interview questions is also based on list of basic Java programs for beginners. As usual, you better remember how to calculate factorial and how to code solution using loop and recursive method calls. For complete code solution of this programming question, see Java program to calculate factorial.

Merging multiple PDFs into a single PDF using iText.

iText is a library that allows you to generate PDF files on the fly. Please find more details on iText on below link.

http://www.lowagie.com/iText/

Here is a code snippet which takes multiple PDFs stream as input and merging them to a new PDF file. The snippet uses iText java library.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;

 public class ItextMerge {
    public static void main(String[] args) {
        List<inputstream> list = new ArrayList<inputstream>();
        try {
            // Source pdfs            
            list.add(new FileInputStream(new File("f:/1.pdf")));
            list.add(new FileInputStream(new File("f:/2.pdf")));

            // Resulting pdf            
            OutputStream out = new FileOutputStream(new File("f:/result.pdf"));

            doMerge(list, out);

         } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

     /**
     * Merge multiple pdf into one pdf
     *
     * @param list
     *            of pdf input stream
     * @param outputStream
     *            output file output stream
     * @throws DocumentException
     * @throws IOException
     */
    public static void doMerge(List<inputstream> list, OutputStream outputStream)
            throws DocumentException, IOException {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        
        for (InputStream in : list) {
            PdfReader reader = new PdfReader(in);
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                document.newPage();
                //import the page from source pdf
                PdfImportedPage page = writer.getImportedPage(reader, i);
                //add the page to the destination pdf
                cb.addTemplate(page, 0, 0);
            }
        }
        
        outputStream.flush();
        document.close();
        outputStream.close();
    }
}