Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Sunday, April 13, 2014

How to fix org.hibernate.MappingException: Unknown entity Exception in Java

If you have used Hibernate with JPA and using annotation to declare your entity bean then you might have seen this confusing error called "org.hibernate.MappingException: Unknown entity". This error message is so misleading that you could easily lose anywhere between few minutes to few hours looking at wrong places. I was using Spring 3 and Hibernate 3.6 when I got this error,which occurs when addEntity() method was executed. I checked everything, from Spring configuration file applicationContext.xml, Hibernate config file, my Entity class and DAO class to see whether my Entity class is annotated or not, but I was still getting this error message. After some goggling I eventually find that, it was an incorrect import which was causing this error. Both hibernate and JPA has @Entity annotation and some how Eclipse was automatically importing org.hibernate.annotations.Entity instead of javax.persistence.Entity annotation. Once I fixed this import issue, everything went smooth. Unfortunately, this error is not easy to spot, the org.hibernate.annotations.Entity import seemed completely appropriate to many programmers. For a newbie Java or hibernate developer it�s really hard to understand which Entity annotation to use, shouldn't be in org.hibernate.annotations.Entity, but instead it's javax.persistence.Entity. By the way, if you are using auto-complete functionality of Eclipse IDE, then you can blame it them, alternatively you can configure your preferred import in Eclipse.
Read more �

Thursday, April 10, 2014

Difference between FileInputStream and FileReader in Java | InputStream vs Reader

Before going to explain specific difference between FileInputStream and FileReader in Java, I would like to state fundamental difference between an InputStream and a Reader in Java, and when to use InputStream and when to go for Reader. Actually, Both InputStream and Reader are abstractions to read data from source, which can be either file or socket, but main difference between them is, InputStream is used to read binary data, while Reader is used to read text data, precisely Unicode characters. So what is difference between binary and text data? well everything you read is essentially bytes, but to convert a byte to text, you need a character encoding scheme. Reader classes uses character encoding to decode bytes and return characters to caller. Reader can either use default character encoding of platform on which your Java program is running or accept a Charset object or name of character encoding in String format e.g. "UTF-8". Despite being one of the simplest concept, lots of Java developers make mistakes of not specifying character encoding, while reading text files or text data from socket. Remember, if you don't specify correct encoding, or your program is not using character encoding already present in protocol e.g. encoding specified in "Content-Type" for HTML files and encoding presents in header of XML files, you may not read all data correctly. Some characters which are not present in default encoding, may come up as ? or little square. Once you know this fundamental difference between stream and reader, understanding difference between FileInputStream and FileReader is quite easy. Both allows you to read data from File, but FileInputStream is used to read binary data, while FileReader is used to read character data.
Read more �

Wednesday, April 9, 2014

For Each loop Puzzle in Java

From Java 5 onwards, we have a for-each loop for iterating over collection and array in Java. For each loop allows you to traverse over collection without keeping track of index like traditional for loop, or calling hasNext() method in while loop using Iterator or ListIterator. For-each loop indeed simplified iteration over any Collection or array in Java, but not every Java programmer is aware of some useful details of for-each loop, which we will see in this tutorial. Unlike other popular items from Java 5 release alias Generics, Autoboxing and variable arguments, Java developers tend to use for-each loop more often than any other feature, but when asked about how does advanced foreach loop works or what is basic requirement of using a Collection in for-each loop, not everyone can answer. This small tutorial and example aims to bridge that gap by going through some interesting foreach loop puzzles. So, without any further delay let's see our first puzzle on Java 5 for-each loop.
Read more �

Friday, April 4, 2014

How to replace line breaks , New lines from String in Java.- Windows, Mac or Linux

We often need to replace line terminator characters, also known as line breaks e.g. new line \n and carriage return \r with different characters. One of the common case is to replace all line breaks with empty space in order to concatenate multiple lines into one long line of String. In order to replace line breaks, you must know line terminator or new line characters for that platform. For example, In Windows operating system e.g. Windows 7 and 8, lines are terminated by \n\r also known as CR+LF, while in Unix environment e.g. Linux or Solaris line terminator is \n, known as line feed LF. You can also get line terminator pragmatically by using Java system property line.terminator. Now question is, How can you replace all line breaks from a string in Java in such a way that will work on both Windows and Linux (i.e. no OS specific problems of carriage return/line feed/new line etc.)? Well, You can use System.getProperty("line.terminator") to get the line break in any OS and by using String replace() method, you can replace all line breaks with any character e.g. white space. replace() method from java.lang.String class also supports regular expressions, which makes it even more powerful. In next section we will learn how to replace all line breaks from Java String by following a simple code example. By the way, if you are removing line breaks from String then don't forget to store result of replace() method into same variable. Since String is immutable in Java, any change on it will always produce a new String, if you assume that call to replace() will change the original string then it's not going to happen. For example, in below code original String text will remain unchanged, even after calling replace() method.
Read more �

Monday, March 31, 2014

How to use EnumSet in Java with Example

EnumSet is one of the specialized implementation of Set interface for enumeration type, introduced in Java 1.5 along with enumeration type itself. Programmer often stores Enum into common collection classes e.g. HashSet or ArrayList, mostly because they are unaware of this little gem. Even I wasn't aware of this class few years ago, until I come across one of the finest book for Java programmers, Effective Java. It has an Item on EnumSet, which highlight some typical use-cases for this collection class instead of using int variable and bitwise operator. Since Enum constants are unique and has pre-defined length, as you can not define a new enum constant at runtime; it allows Java API designer to highly optimize EnumSet. If you look closely, EnumSet also teaches you couple of good design practices to create flexible and maintainable code. For example, EnumSet is an abstract class, and it provides lots of static factory method to create instance of EnumSet e.g. EnumSet.of(...). This method takes advantage of method overloading and variable argument to provide Set of only provided Enum constants. Second good thing is there are two concrete sub-classes of EnumSet e.g. RegularEnumSet and JumboEnumSet, but both are package-private, which means client can not use them directly. Only way to use them is via EnumSet. At runtime, depending upon key size of requested Enum, implementation automatically decide which implementation to use. This provides you immense flexibility and control to rollout a new better version of EnumSet implementation without any change on client side. Anyway, this article is not just about design lessons form this class but more importantly how and when to use EnumSet in Java program. I have shared simple example to demonstrate power of EnumSet, which you will see in next section.
Read more �

Tuesday, March 25, 2014

Difference between WeakReference vs SoftReference vs PhantomReference vs Strong reference in Java

WeakReference and SoftReference were added into Java API from long time but not every Java programmer is familiar with it. Which means there is a gap between where and how to use WeakReference and SoftReference in Java. Reference classes are particularly important in context of How Garbage collection works. As we all know that Garbage Collector reclaims memory from objects which are eligible for garbage collection, but not many programmer knows that this eligibility is decided based upon which kind of references are pointing to that object. This is also main difference between WeakReference and SoftReference in Java. Garbage collector can collect an object if only weak references are pointing towards it and they are eagerly collected, on the other hand Objects with SoftReference are collected when JVM absolutely needs memory. These special behaviour of SoftReference and WeakReference makes them useful in certain cases e.g. SoftReference looks perfect for implementing caches, so when JVM needs memory it removes object which have only SoftReference pointing towards them. On the other hand WeakReference is great for storing meta data e.g. storing ClassLoader reference. If no class is loaded then no point in keeping reference of ClassLoader, a WeakReference makes ClassLoader eligible for Garbage collection as soon as last strong reference removed. In this article we will explore some more about various reference in Java e.g. Strong reference and Phantom reference.
Read more �

Wednesday, March 19, 2014

2 Examples of Streams with Collections in Java 8

Finally Java 8 is here, after more than 2 years of JDK 7, we have a much expected Java 8 with lots of interesting feature. Though Lambda expression is the most talked item of coming Java 8 release, it wouldn't have been this much popular, if Collections were not improved and Stream API were not introduced. Java 8 is bringing on new Streams API java.util.stream package, which allow you to process elements of Java Collections in parallel. Java is inheritably sequential and there is no direct mean to introduce parallel processing at library level, stream API is going to fill that gap. By using this, you can filter elements of collection on given criterion e.g. if you have a List of orders, you can filter buy orders with sell orders, filter orders based upon there quantity and price and so on. You can also perform two of most popular functional programming functions e.g. map and reduce. java.util.stream class provides function such mapToInt(), mapToLong(), and map function to apply an operation on all elements of Collections. By the way, these are just few of gems of Stream API, I am sure you will find several more, when you start exploring lambda expression and java.util.stream package. In this tutorial, we will see 2 examples of using Java 8 Stream with Collections classes. I have chosen List for these example, but you can use any Collection e.g. Set, LinkedList etc. By the way, use of Stream is not limited to Collections only, you can even use an array, a generator function, or an I/O channel as source. In most cases, a Stream pipeline in Java 8 consists a source, followed by zero or more intermediate stream operations e.g. filter() or map(); and a terminal operation such as forEach() or reduce().
Read more �

Monday, March 17, 2014

How to Check if a Number is Binary in Java - Programming Problem

Today we will take a look on another simple programming exercise, write a program to check if a number is binary in Java. A number is said to be binary if it only contains either 0 or 1, for example 1010 is binary number but 1234 is not. You can not any library method to solve this problem, you need to write a function to check if given number is binary, you can use basic constructs of Java programming language e.g. operators, keywords, control statements etc. If you are a regular reader of Javarevisited, then you know that I love to share simple programming problems here, because they serve two purposes, first they help beginners to apply their basic knowledge to do something which looks challenging at first, and second they serve as good coding questions to differentiate candidates on Java interviews between who can program and who can not. FizzBuzz is one of such problems but their are lot many, e.g. Prime numbers, Fibonacci series or factorial. But if you truly want to test your candidate then you need to give them some questions which are not so popular. If a candidate can apply his programming knowledge to a problem he is seeing first time, he is probably going to perform better than the candidate who has already seen the problem. That's why I was always looking at programming problems, which are not difficult to solve but has some element of freshness and not so common. This problem of checking whether a number is binary or not is not very different from converting a decimal to binary, but it will pose challenge for those programmers who can't code. By the way, if you are looking for simple programming problems, you can check my list of Top 30 programming interview questions, their I have shared questions from several popular topics including String, Array, Data Structure and Logic.
Read more �

Thursday, March 13, 2014

Why use Underscore in Numbers from Java SE 7 - Underscore in Numeric Literals

JDK 1.7 release had introduced several useful features, despite most of them being syntactic sugar, there use can greatly improve readability and code quality. One of such feature is introduction of underscore in numeric literals. From Java 7 onwards you can write a long digit e.g. 10000000000 to a more readable 10_000_000_000 in your Java source code. One of the most important reason of using underscore in numeric literal is avoiding subtle mistakes which is hard to figure out by looking at code. It's hard to notice a missing zero or extra zero between 10000000000 and 1000000000, than 10_000_000_000 and 1_000_000_000. So if you are dealing with big numbers in Java source code, use underscore in numbers to improve readability. By the way, there are rules to use underscore in numeric literals, as they are also a valid character in identifier, you can only use them in between digits, precisely neither at the start of numeric literal nor at the end of numeric literals. In next couple of section, we will learn how underscore in numeric literal is implemented and rules to use them in numerical literals.
Read more �

Tuesday, March 11, 2014

How to Clone Collection in Java - Deep copy of ArrayList and HashSet

Programmer often mistook copy constructors provided by various collection classes, as a mean to clone Collection e.g. List, Set, ArrayList, HashSet or any other implementation. What is worth remembering is that, copy constructor of Collection in Java only provides shallow copy and not deep copy, which means objects stored in both original List and cloned List will be same and point to same memory location in Java heap. One thing, which adds into this misconception is shallow copy of Collections with Immutable Objects. Since Immutable can't be changed, It's Ok even if two collections are pointing to same object. This is exactly the case of String contained in pool, update on one will not affect other. Problem arise, when we use Copy constructor of ArrayList to create a clone of List of Employees, where Employee is not Immutable. In this case, if original collection modifies an employee, that change will also reflect into cloned collection. Similarly if an employee is modified in cloned collection, it will also appeared as modified in original collection. This is not desirable, in almost all cases, clone should be independent of original object. Solution to avoid this problem is deep cloning of collection, which means recursively cloning object, until you reached to primitive or Immutable. In this article, we will take a look at one approach of deep copying Collection classes e.g. ArrayList or HashSet in Java. By the way, If you know difference between shallow copy and deep copy, it would be very easy to understand how deep cloning of collection works.
Read more �

Monday, March 3, 2014

Covariant Method Overriding of Java 5 - Coding Best Practices

Sometime knowledge of a specific Java feature can improve code quality, Covariant method overriding is one of such feature. Covariant method overriding was introduced in Java 5, but it seems it lost between other more powerful features of that release. Surprisingly not many Java programmer knows about Covariant overriding, including myself, until I read, one of the best Java book on Collection framework, Java Generics and Collection. Covariant method overriding helps to remove type casting on client side, by allowing you to return subtype of actually return type of overridden method. Covariant overriding can be really useful, while overriding methods which returns object e.g. clone() method. Since clone() return object every client needs to cast on to appropriate subclass, not any more. By using Java 5 covariant overriding, we can directly return subtype instead of object, as we will seen in examples of this article. This feature is not a star feature like Generics or Enum, but it's definitely something worth knowing, given overriding methods are integral part of Java programming. I have discussed a bit about this feature earlier in difference between overriding and overloading article, and here I will show couple of more examples to justify it's usage.
Read more �

Wednesday, February 26, 2014

10 Example of Lambda Expressions and Streams in Java 8

Java 8 release is just a couple of weeks away, scheduled at 18th March 2014, and there is lot of buzz and excitement about this path breaking release in Java community. One of feature, which is synonymous to this release is lambda expressions, which will provide ability to pass behaviours to methods. Prior to Java 8, if you want to pass behaviour to a method, then your only option was Anonymous class, which will take 6 lines of code and most important line, which defines the behaviour is lost in between. Lambda expression replaces anonymous classes and removes all boiler plate, enabling you to write code in functional style, which is some time more readable and expression. This mix of bit of functional and full of object oriented capability is very exciting development in Java eco-system, which will further enable development and growth of parallel third party libraries to take advantage of multi-processor CPUs. Though industry will take its time to adopt Java 8, I don't think any serious Java developer can overlook key features of Java 8 release e.g. lambda expressions, functional interface, stream API, default methods and new Date and Time API. As a developer, I have found that best way to learn and master lambda expression is to try it out, do as many examples of lambda expressions as possible. Since biggest impact of Java 8 release will be on Java Collections framework its best to try examples of Stream API and lambda expression to extract, filter and sort data from Lists and Collections. I have been writing about Java 8 and have shared some useful resources to master Java 8 in past. In this post, I am going to share you 10 most useful ways to use lambda expressions in your code, these examples are simple, short and clear, which will help you to pick lambda expressions quickly.
Read more �

Monday, February 24, 2014

How to Format and Display Number to Currency in Java - Example Tutorial

Displaying financial amount in respective currency is common requirement in Java based E-commerce applications. For example if you are selling products on-line globally, you will show price of product in their local currency rather than USD or some other currency. Storing price in every currency is not a good option because of maintenance, and more realistically fluctuation in exchange rates. That's why many of these application prefer stores price of books, electronic goods or whatever product they are selling in USD, and responsibility of converting that price to local currency and displaying is left to client side code. If your client is Java based client e.g. Swing GUI , Java FX client, or a JSP web page, you can use java.text.NumberFormat class to format currency in Java. NumberFormat class allows you to display price in multiple currency depending upon Locale supported by your Java version. All you need to do is to get correct Currency Instance based upon Locale, for example to display amount in US dollar, call NumberFormat.getCurrencyInstance() method with Locale as Locale.US, similarly to display currency as UK pound sterling, pass Locale.UK and for displaying money in Japanese Yen, pass Locale.JAPAN. Once you get the correct instance of currency formatter, all you need to do is call their format() method by passing your number. We will see an example of converting one currency to other and displaying amount in multiple currency in Java. It's actually very much similar to formatting date in Java, so if you are familiar to that part, it would be easy to format currency as well.
Read more �

Wednesday, February 19, 2014

Top 30 Java Phone Interview Questions Answers for Freshers, 1 to 2 Years Experienced

In this article, I am sharing 30 core Java technical questions, from screening and phone round of interviews. In telephonic interviews, questions are short, fact based and Interviewer expects some keyword in answers. Accordingly, I have given very short answers to these question, only main points; just to make this as revision post. I am expecting every Java programmer to know answers of all these Java technical questions, if he has more than 4 to 5 years experience. it's only freshers, and junior developers who needs to do bit of research to understand topics well. I have tried to include all classical and hugely popular, frequently asked questions from different topics like String, multi-threading, collection, design pattern, object oriented design, garbage collection, generics and advanced Java concurrency questions. Since core Java interviewer's normally don't ask questions on JSP, Servlets and other JEE technologies, I have not included them into this list. Sole purpose of this list is to given freshers and less experienced developers an idea of what kind of core Java technical questions are asked on phone interviews. For curious ones, I have also included links for more detail answers and discussions.
Read more �

Thursday, December 12, 2013

How to configure Log4j in Java program without XML or Properties File

Sometime configuring Log4j using XML or properties file looks annoying, especially if your program not able to find them because of some classpath issues, wouldn't it be nice if you can configure and use Log4j without using any configuration file e.g. XML or properties. Well, Log4j people has thought about it and they provide a BasicConfigurator class to configure log4j programmatically, thought this is not as rich as there XML and properties file version is, but it's really handy for quickly incorporating Log4j in your Java program. One of the reason programmer prefer to use System.out.println() over Log4j, of-course for testing purpose, because it doesn't require any configuration, you can just use it, without bothering about XML or properties file configuration, but most programmer will agree that, they would prefer to use Log4j over println statements, even for test programs if it's easy to set them up. By the way, for production use prefer SLF4J over Log4J. In this Java tutorial, we will see a nice little tip to use Log4j right away by configuring in couple of lines. In fact you can configure Log4J in just one line, if you intend to use there basic configuration which set's the log level as DEBUG.
Read more �

Wednesday, December 4, 2013

When to make a method final in Java

Final keyword in Java is not as mysterious as volatile or transient, but still it creates lot of doubts on programmers mind. I often receives questions like, When to make a method final in Java or When to make a method static in Java, later I answered in my earlier post. Questions like this is not trivial, knowing what a keyword does is just small part of mastering that functionality. Similar to real world, where knowing that a sword can cut lot of things is not enough for a warrior to survive, you need to know how to use that and more importantly, use if effectively. Final keyword can be applied to class, methods and variable and has different meaning for each of them, but the motive remains same, it state completeness, it opposes change. For example, final class can not be extended, value of final variable can not be change and a final method can not be overridden in Java. This gives you first hint, when to make a method final in Java, obviously to prevent subclass for changing it's definition, technical preventing it from overridden. There are lot of clues on How to use final keyword on methods in Java API itself, one of the prime example of this java.lang.Object class, which declares a lot of method final including wait method with timeout. Another example of making a method final is template method, which outlines algorithm in Template method design pattern. Since, you don't want a sub class to change the outline of algorithm, making it final will prevent any accidental or malicious overriding. In this tutorial, we will learn few things, which will help you to effectively use final keywords with Java methods.
Read more �

Friday, November 29, 2013

Java vs Python - Which Programming Language Should Learn First

Java and Python are two of most popular and powerful programming language of present time. Beginner programmer often get confused, one of the most frequently asked question is should I learn Java or Python, Is Python is good programming language to start with, Which programming language would you recommend for beginners to learn first etc. Since I am a Java developer, my opinion is biased, I will always suggest you to start with Java and then learn Python, but if you ask this question to a Python developer, you might get just opposite answer. I have well documented my reasons as Why Java is best Programming language and Why a programmer should learn Java. One of the most important reason you would see on that blog post is strong Java community, which will help you though out your Java career. You can ask some beginner stuff starting from how to set PATH and classpath to advanced stuff about debugging Java program in Eclipse, no matter what kind of question is, there is always some one is Java community, who is ready to answer and help you. This is one of the reason that StackOverflow is full of Java questions. By the way Python is not spring chicken anymore, it has fully grown and giving strong competition to main stream language like Java and C++. When I first come across Python, I thought it's a scripting language, but that is an understatement. You can do object oriented programming in Python as well. On beginners point of view, I always suggest pick a language which is easier to learn, powerful to attract you and have strong community support, now both Java and Python fits this bill, and until you do some really good comparative analysis, you can not decide which language to learn from Java vs Python. Thankfully, we have an infographic, which highlights some important difference between Python and Java, I am sure after taking a look on this Infographic, you will be able to decide which is the right programming language to start with.
Read more �

Thursday, November 28, 2013

Difference between static vs non static method in Java

In this article, we will take a look at 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 these method, which is what you need to do to access non static method of a class. Static method are treated differently by compiler and JVM than non static methods, static methods are bonded during compile time, as opposed to binding of non static method, which happens at runtime. Similarly you can not access non static members inside static context, which means you can not use non static variables inside static methods, you can not call non static methods from static ones, all those will result in compile time error. Apart from these significant differences between static and non static methods, we will also take a look at few more points in this Java tutorial, with a code example, which shows some of these differences in action.By the way this is the second article on static method, in first article, we have learned about when to use static method in Java
Read more �

Wednesday, November 20, 2013

Scala vs Java - Differences and Similarities between them

Scala is new generation JVM language, which is generating popularity as alternative of arguable 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. Since tremendous works has already been done in form of open source framework and library in Java, it's best to reuse them, rather than creating a separate set for Scala. Out of several differences, one of the main difference between Scala and Java is it's ability to take advantage of Functional programming paradigm and multi-core architecture of current  CPU. Since current CPU development trend is towards adding more cores, rather than increasing CPU cycles, it also favors functional programming paradigm. Though this differences may not be significant, once Java 8 will introduce lambdas, but it might be too early to comment. Apart from functional programming aspect, there are many other differences as well. One of the obvious one is improved readability and succinct code. Java is always on firing line for being too verbose, I thing Scala does take care of that and code which took 5 to 6 lines in Java, can be written in just 2 to 3 lines in Scala. Well Grounded Java Developer has some nice introduction on JVM languages like Scala, Groovy and Closure, which is worth reading.  In this article, we will see such kind of similarities and differences between Scala and Java.



Similarities between Scala and Java

Following are some of the major similarities between Scala and Java programming language :

1) Both are JVM based language, Scala produce same byte code as Java and runs on Java Virtual Machine. Similar to Java compiler javac, Scala has a compiler scalac, which compiles Scala code into byte code. At this level, all JVM language like Groovy, JRuby, Scala becomes equals to Java, because they use same memory space, type system and run inside same JVM.

2) You can call Scala from Java and Java from Scala, it offers seems less integration. Moreover, you can reuse existing application code and open source Java libraries in Scala.

3) Major Java programming IDE like Eclipse, Netbeans and InetelliJ supports Scala.

4) One more similarity between Scala and Java is that both are Object Oriented, Scala goes one steps further and also supports functional programming paradigm, which is one of it's core strength.



Differences between Scala and Java

1) First and Major difference you will notice between Scala and Java is succinct and concise code. Scala drastically reduce number of lines from a Java application by making clever use of type inference, treating everything as object, function passing and several other features.

2) Scala is designed to express common programming patterns in elegant, concise and type-safe way. Language itself encourage you to write code in immutable style, which makes applying concurrency and parallelism easily.

3) One difference, which some might not notice is learning curve. Scala has steep learning curve as compared to Java, my opinion may be slightly biased because I am from Java background, but with so much happening with little code, Scala can be really tricky to predict. Syntax of Scala looks confusing and repulsive as compared to Java, but I am sure that is just the starting hurdle. One way to overcome this hurdle is following a good Scala book like  Programming in Scala or Scala in Action, both are excellent books for a Java developer, who wants to learn Scala

4) One of Scala's cool feature is built-in lazy evaluation, which allows to defer time consuming computation, until absolutely needed and you can do this by using a keyword called "lazy" as shown in below code :
 
// loading of image is really slow, so only do it if need to show image
lazy val images =getImages()  //lazy keyword is used for lazy computation

if(viewProfile){
    showImages(images)
}
else(editProfile){
    showImages(images)
    showEditor()
}
else{
    // Do something without loading images.
}

If you love to learn by following examples, then I guess Scala CookBook is a another good buy, contains tons of examples on different features of Scala.

5) Some one can argue that Java is more readable than Scala, because of really nested code in Scala. Since you can define functions inside function, inside another functions, inside of an object inside of a class. Code can be very nested. Though some time it may improve clarity, but if written poorly it can be really tricky to understand.

6) One more difference between Scala and Java is that Scala supports Operator overloading. You can overload nay operator in Java and you can also create new operators for any type, but as you already know, Java doesn't support Operator Overloading.

7) Another major difference between Java and Scala is that functions are objects in Java. Scala treats any method or function as they are variables. When means, you can pass them around like Object. You might have seen code, where one Scala function is accepting another function. In fact this gives the language enormous power.

8) Let's compared some code written in Scala and Java to see How much different it look:


Java:

List<Integer> iList = Arrays.asList(2, 7, 9, 8, 10);
List<Integer> iDoubled = new ArrayList<Integer>();
for(Integer number:iList){
    if(number % 2 == 0){
        iDoubled.add(number  2);
    }
}

Scala:

val iList = List(2, 7, 9, 8, 10);
val iDoubled = iList.filter(_% 2 == 0).map(_  2)

You can see that Scala version is lot succinct and concise than Java version. You will see more of such samples, once you start learning functional programming concepts and patterns. I am eagerly waiting for Scala Design Patterns: Patterns for Practical Reuse and Design by John Hunt, which is not yet released and only available for pre order. This book is going to release this month.


That's all on this article about similarities and differences between Scala and Java.  Though they are two separate programming language, they have lot in common, which is not a bad thing at all and in my opinion that's the only thing, which will place Scala as Java alternative, if at all it happens in future. As I had mentioned in my post 10 reason to learn Java programming, that Java tools, libraries, and community is it's biggest strength and if Scala can somehow reuse that, it will be well ahead, forget about competing though, it will take years to build such community and code. For a Java programmer, I would say nothing harm in learning Scala, most likely you will learn few good practices, which you can even apply in Java, as corporate sector is still on Java, and Scala in it's early days, you can be well ahead, if you learn Scala now. On closing note, at high  level Scala looks very promising, all design decision made are really good and they came after several years of experience with Java.

Recommended Books on Scala for Java Programmers
Books are best way to learn a new programming language, first of all they contains complete information but also in much more readable and authentic form. I strongly recommend to follow at-least one book, before jumping on blogs and online articles. One reading any Scala Programming book is must to build fundamental, which is indeed necessary, given rather steep learning curve of Scala. Following are my list of some books from which you can choose one.

Programming in Scala: A Comprehensive Step-by-Step Guide, 2nd Edition by Martin Odersky, Lex Spoon and Bill Venners
Scala for the Impatient by Cay S. Horstmann
Scala in Depth by Joshua D. Suereth and Martin Odersky

Thanks folks, Enjoy learning Scala.

Monday, November 18, 2013

Do you need to pass OCAJP before taking OCPJP - Java Certification for SE 7

One thing, which I certainly noticed after Oracle's acquisition of Sun Microsystems is creating confusion around Java certifications like hell. I used to remember those days, where Java Certifications are well defined and well known e.g. SCJP, SCWCD, SCBCD etc, but currently Java certification for SE 7 is known as either SCJP 7, OCJP 7 or even OCPJP 7. By the way official name of two most sought after Java certifications are Oracle Certified Associate, Java SE 7 Programmer ( Code : 1Z0-803) and Oracle Certified Professional, Java SE 7 Programmer ( Code 1Z0-804 ). I receive lots of questions regarding Java Certifications for Java SE 6 and 7, with range of queries from how to prepare for exam, to suggestions on books, resources and mock exam simulators. One of the questions, which lot of my reader email me is about, whether taking OCAJP is mandatory for giving OCPJP or not? Many of them have doubt about whether OCA is required for taking OCP or not? Well, answer is both Yes and No. If you are appearing for Java SE 7 certification and haven't done any Java certification before than you need to first clear OCAJP and only than you can take OCPJP, but if you are upgrading from an earlier version e.g. you have already passed Oracle Certified Professional, Java SE 6 or SE 5 Programmer (OCPJP 6 or OCPJP 5) or any version of Sun Certified Java programmer exam ( SCJP) than you don't need to go through OCA path. You can directly appear for OCPJP 7. By the way exam code is different for upgrade version, you need to take 1Z0-805, Upgrade to Java SE 7 Programmer. On similar note, if you are appearing for Java SE 6 certification than you don't need to pass OCA, you can directly take Java 1.6 certification.
Read more �