Tuesday, 21 June 2016

Difference between == and equals() method in Java - String Object

What is difference between == and equals() method for comparing Objects in Java is one of the classical Interview Questions which appears now and then on many interviews. This question is mostly asked in conjunction with String because comparing String using == and equals() method returns different results. I have often seen as along with other popular String question e.g. StringBuffer vs StringBuilder, Why String is final etc. Java is a pure object oriented language and every object has one state and location in the memory and equals () and == are related with the state and location of the object, now in this article will try to understand this concept and difference between == and equals method in Java.


What is equals method and == operator in Java
equals vs == or eqaulity operator in Java
Both equals() method and == operator is used to compare two objects in Java. == is an operator and equals() is method. But == operator compare reference or memory location of objects in heap, whether they point to same location or not .whenever we create any object using the operator new it will create new memory location for that object. So we use == operator to check memory location or address of two objects are same or not. And when we talk about equals() method main purpose is two compare the state of two objects or contents of the object. But there is one relation between this two isdefault implementation of equals() method  work like == means it will check the memory reference of the object if they point to same location then two objects are equals and it is defined in  Object class .as we know java.lang.Object class is parent for every other object so default  implementation is common for every object but if we want to override the method and want to give own implementation  for checking the equality for two objects we can do, and most of the Java  classes have their own implementation for equals method where they check the contents of the object .

For example  java.lang.String class override the equals() and hashcode method and in overridden method it will check that two string contains same value or character if yes then they are equals other wise not equal.

Difference between == and equals method in Java
Now we know what is equals method, how it works and What is equality operator (==) and How it compare objects, its time to compare them. Here is some worth noting difference between equals() method and == operator in Java:

·          First difference between them is, equals() is a method defined inside the java.lang.Object class and == is one type of operator and you can compare both primitive and objects using equality operator in Java.

·          Second difference between equals and == operator is that, == is used to check reference or memory address of the objects whether they point to same location or not, and equals() method is used to compare the contents of the object e.g. in case of comparing String its characters, in case of Integer its there numeric values etc. You can define your own equals method for domain object as per business rules e.g. two Employes objects are equal if there EmployeeId is same.

·          Third difference between equals and == operator is that, You can not change the behavior of == operator but we can override equals() method and define the criteria for the objects equality.

Let clear all these differences between equals and == operator using one Java example :

String s1=new String("hello");
String s2=new String("hello");
Here we have created two string s1 and s2 now will use == and equals () method to compare these two String to check whetherthey are equal or not.

First we use equality operator  == for comparison  which only returns true if both reference variable are pointing to same object.

if(s1==s2) {
     System.out.printlln("s1==s2 is TRUE");
} else{
     System.out.println("s1==s2 is FALSE");
}

Output of this comparison is FALSE because we have created two objects which have different location in heap so == compare their reference or address location and return false. Now if we use equals method to check their equivalence what will be the output


if(s1.equals(s2)) {
      System.out.println("s1.equals(s2) is TRUE");
} else { 
      System.out.println("s1.equals(s2) is FALSE");
}

Output of this comparison is TRUE because java.lang.String class has already overridden the equals() method of Object class and check that contents are same or not because both have same value hello so they are equal according to String classequals() method .

Point to remember:
If you have not overridden equals() method in  a user defined object,  it will only compare the reference or memory address, as defined in default equals() method of java.lang.Object class and return true only if both reference variable points to same object. So in a user defined class, both equals() and == operator behave similarly but that may not be logically correct and that’s why we should always define the equivalence criteria for custom or domain objects.

That’s all on difference between equals() method and == operator in Java. Both can compare objects for equality but equals()is used for logical and business logic comparison while == mostly for object reference comparison in Java.

Other Java articles and Interview questions from java 67

Hashtable vs HashMap in Java



TAGS :     SQL          SQL TUTORIAL           SQL STUDY ONLINE                 GNIIT HELP
Read More »

Difference between transient vs volatile variable or modifier in Java

transient vs volatile modifier in Java
What is difference between transient and volatile variable or modifier in Java is one of the most common Serialization Interview Question in Java. Though volatile variables are not related to Serialization at all, this question is mostly asked in conjunction with other Serialization question. Both transient and volatile modifiers are completely different to each other. In fact this question is as popular as Serializable vs Externalizable in Java. Main difference between transient vs volatile variable is that transient variables are not serialized during Serialization process in Java while volatile variables are used to provide alternative synchronization in Java. By using volatile keyword or modifier on fields, signals compiler that this variable is accessed by multiple thread and any reordering or optimization by compiler should be avoided. In this Java article we will see some difference between transient and volatile variable by learning each of them and When to use transient and volatile variable in Java.

Difference between transient vs volatile variables Java

Let's see difference between transient and volatile variables in point format for easy understanding and revision :

1) By making a variable or field
 transient in a Class prevents it from being Serialized in Java. Along with static variables, transient variables are not serialized during Serialization and they are initialized with
there default value during deserialization process e.g. an int transient variable is initialized with zero during deserialization in Java. to
 learn more about transient variable, See What is transient variable in Java.

2) On the other hand
 volatile variables are used in Concurrent programming in Java. When we declare a variable volatile, every thread reads its value from main memory and don't used cached value available in every thread stack. volatile variable also prevents compiler from doing reordering which can compromise synchronization. to learn more about volatile variables, read What is volatile variable in Java. Many Java programmer though know about volatile variables they are not sure where to use volatile modifier in Java. One of the popular example of  using volatile variable is implementing double checked locking in Singleton, where Singleton instance of class is declared volatile in Java.

That's all on difference between transient and volatile variables in Java.
 transient variables are used to prevent serialization or a field while volatile variables are used to prevent reordering and avoid reading cached value of field in multithreaded Java program. Only similarity between transient andvolatile keyword is that they are only applicable to field or properties of class. You can not use transient or volatile keyword during class or method declaration in Java.

Other
 Java Interview questions from java67
Difference between Serializable and Externalizale in Java
Difference between Abstraction and Encapsulation in Java
Difference between Abstract class and interface in Java
Difference on Hashtable vs HashMap in Java
Difference on ArrayList vs Vector in Java


TAGS:   mkniit           mkniit            GNIIT HELP            mkniit              mkniit
Read More »

5 Books to Improve Coding Skills of Programmers - Must Read, Best of Lot

Learning a Programming language e.g. Java or C++ is easy but learning to write good code is not. Writing good code is an art and also an important differentiating factor between an average programmer vs a good programmer. Since most of the programmers often look for inspiration and resource to improve their coding skill, I decide to share some of the good books which can help them to improve their coding. Since many universities, colleges and training courses only teachprogramming languages but not the art of coding, it still remains one of the self-learned skill. The internet has helped a lot to coders with several websites coming up to teach code, programming contest, helping to solve you programming interview questions and all, but IMHO, books are still vital for overall improvement. In this article, I am going to share some of the great books, written by both great author and great programmers, which can certainly help you to write good code and become a better programmer.



5 Books to Improve Coding Skill of Software Developers
Coding is an art and like many arts, it takes a lot of practice, study, and self-discipline to become a good coder. In my childhood, I have read that "books are your best friend, keep them near to you", and that has been proved absolutely correct in the world of Programming and Coding.

Programming is a challenging field with new development happening every day and knowledge quickly becomes obsolete, but
 good coding skill and self-discipline is something, which will never get obsolete and help you throughout your career. Books have helped me a lot and in this article, I am going to share 5 great books which will help you to improve your coding skill.

You might have read some of them already, but they are worth reading again. I have always learned new things while reading a good book like
 Clean Code twice. They are must read books for any Programmer who wants to become a good coder as well. They will also help you to do well in your Job, earn respect from peers and seniors, and also do well in job interviews.


1) Clean Code by Uncle Bob Martin
Clean code is one of
 the best books for java programmer but any programmer can benefit from it. This book will help you to write better code.This book teaches you about code smell, function and data structure, object-oriented design principles, design patterns. Uncle Bob Martin who himself is a great programmer has done a tremendous job of imparting his year of experience in simple words. The title"Clean Code" aptly justifies advice, best practices given to the programmers in this book. If you have to choose  just one book then pick the clean code.
Best book to learn Coding in Java




2) Working Effectively With Legacy Code
This is the one book I recommend to every Programmer who codes. Since development and maintenance are primary jobs of software engineers, and a bad code is hard to maintain, but sometimes you have no choice but to live with that, this book will help you how to work effectively with legacy code. This is also from the Rober C. Martin Series, the same series where
 "Clean Code" and other good books like "Clean Coder" belongs.
Book to become good Coder




3) Refactoring to Patterns 1st Edition by Joshua Kerievsky
This is one of the rare books where you will find the best combination of theory and practice. Refactoring is a process to make your working code more beautiful and this book can help you there by leveraging already tried and tested patterns of software development world. This is one of
 the best books to learn how and when to use design patterns. Java developers have added advantage because examples are given in Java, but it's not a big problem for C++, Scala or Python developer because examples are easy to follow and can be understood by anyone who knows how to read the pseudo code. Java's verbosity and English like language will also help a lot.
Good book to improve coding



4) Refactoring: Improving the Design of Existing Code
Refactoring is a process of making a working code beautiful, refactoring helps to improve the design of working code.It is also one of the important tricks of good
 programmers, more often than not good coders are also good on refactoring. This book will teach you both the art and science of refactoring code.It doesn't matter whether you are a Java programmer, C++ developer or a Python developer, every programmer can benefit from this book. This book  is a collective effort of some of the best authors in the programming world. List of authors includes Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts, and forward by Erich Gamma.
Best book to learn Coding




5) Beautiful Code: Leading Programmers Explain How They Think
This is one of the
 great books to improve your coding skill because it offers you an opportunity to see how expert programmer approach a problem, how the written code and how do they solve the problem and still able to keep their code beautiful. This book is a collection of case studies that tells how those expert programmers, which includes, Brian Kernighan, Jon Bentley (author of Programming Pearls), Tim Bray, Karl Fogel, Michael Feathers (author of Working Effectively with Legacy Code), and many more great authors and programmers. No matter, which programming language  you use for coding e.g. Java, C++, Python or Ruby, you will find something interesting in this book.
Great book to learn Coding skill



That's all about some of the great books to improve coding skill. Both beginners and experiencedprogrammers can benefit from these books. In fact, these are the best resource for expert beginners which has experience but lack the knowledge to support those experience. It's a real shame if you have 10 years of experience but cannot write good code and believe me it happens.

If you are not writing code on the daily basis, not trying to improve, not introspecting than a number of years in the job will grow but your programming experience will not. You will struggle to write
 good code and good unit tests, which is one of the important traits of a good programmer. Never is too late, read some of this book to get back on track, if you are not sure which one to start, just read the Clean Code.



TAGS:          mkniit              sonu giri             kamalsharma              gniit help
Read More »

10 Books Every Programmer Should Read

book and follow advice from the great programmer and authors who are gone to that path. I still regret that why I didn't come to know about Clean Code when I started programming. These are the books which can change your career, can make you a better programmer. These books are more about a way of thinking, organizing, and becoming better at the craft of software engineering. They won't make you better at any particular programming language e..g Java but they will help you to become a better Programmer.



There is one more thing I like about all these books, you can read them in the couch, in bed or even in your daily commute to work. I mean you don't need a compiler or IDE to trying the stuff in the book to see how it works like other hardcore programming books. For example, you won't get anything from Java Concurrency In Practice without writing applications, executing tests and understanding output. Even though I have read them already, I have PDF versions of these books in myiPad and read them in my commute to work. BTW, in order to get most from any programming book, coding and trying out their example is a must. 

1) Programming Perls
This is the first book I read for preparing programming interview. It contains some of the toughest problems for newbie and if you try to solve them by your own, you will learn a lot. They challenge your understanding of core concept in memory, CPU, and algorithms. Some of you might think that this book is out of date, as it first published in 1999, but you will be wrong. It's a true classic and all the analysis, explanations are still valuable for any programmer. It's a great book to practice
 data structure, algorithms design, searching, sorting, heaps and performance tuning techniques. To give you a glimpse of what you get, try to solve this problem by your own:
"How to sort up to 10 million unique non-negative integers, all of which are less than 107 in 1.25M memory? What if we have only 1M (or less) memory available? What if our integers are not unique, but number of occurrences of each value is limited?"
Salute to Jon Bentley for creating a masterpiece, it fully justifies its name "Programming Pearls".

Best Programming books to read



2) GOF Design Patterns
How many of you have surprised when you see your senior partner solving problem in more elegant way by applying object oriented design principles and design patterns? Well, I am. When I started my career I didn't know anything about design patterns and how it helps to write better code. I came from C, C++ background and what I know was to write code in some classes or structures and use main to test the stuff. It was when I started learning Java and its API I come to know about things like
Collections.sychronizedList(), which is used to synchronize a List in Java andBufferedReader which is used to read character data are examples of Decorator design pattern. I realize the true power of design pattern when during a code review, one of my senior partner re-factor my big if-else block into state design pattern. Now coming back to the book, Design Patterns, Elements of Reusable Object-Oriented Software is another classic and original source of those 23 patterns put together by famous Gang of Four, Eric Gamma, Richard Hel, Ralph Johnson and John Vlissides. I was in doubt to recommend Head First Design pattern or this book because frankly I was benefited more from Head First, but again serious developer doesn't like Headfirst style and being classic, this book can't be ignored. BTW, if you like Head first series, then go for Head First Design pattern, another gem.
10 books every programmer must read



3) The Mythical Man Month
You must read this book if you want to know about software development, estimates, project management and things which can go wrong in software development. I always wonder, why creating a multistory building can be better planned and can be better estimated than building a software. Why all other industry has better tools, process, and quality controls than software world and this is one of the books which help you to understand why. If you aspire to become a project manager, this is the must-read for you.
Must read books for programmers



4) Clean Code
My favorite, I have read it almost 3 to 4 times and still love to read it. I always regret why I didn't get a copy of this book when I started my career. Uncle Bob has done a fabulous job teaching craftsmanship of software development through his series of books and this one is simply best. You will learn how to name your variable,
 how to write better methods, how to structure your code better, what is the code smell, why the solving problem in one way is wrong and why another way is better. You will connect more if you are a Java developer, but I think any object oriented programmer e.g. C++ or Python will benefit from general advice about code, programming, and art of software development. If you like the style of Uncle Bob, you can also take a look at Clean Coder, the second part of this book, which will help you to become a better professional programmer.
Great books to learn Programming




5) Refactoring by Martin Fowler
Once you finish Clean code and hungry for more then this is the book to read. It is the best book an intermediate programmer can read, it will help you to teach the art of refactoring which is the second step towards clean code, first step being designing and writing test. In this book, you will learn
 step by step how to make your code better. It will also help you to learn test-driven development, a proven strategy to write clean code, as you can't refactor code without having enough test cases. In order to get most of this book, not just read but do the examples at your pace. This books about doing things along with reading. The great thing is Martin is very clear about why you do that refactoring and how it improves the code quality.
Best book to learn code refactoring



6) The Design of Everyday Things
Many of you would be surprised to see this book in a list of must read books forprogrammers, some of you might be thinking what the heck a 27-year-old book is doing in
 the list created in 2015, as this book was first published in 1988 with the title "The Psychology of Everyday things".  I recommend this book because programmers are curious by nature and they are heavily involved in designing of the product, and this book will teach you how design serves as the communication between product and user. You will be a much better designer and have an understanding of how things works after reading this book. If you need another reason, this is one of the best seller created by Donald A. Norman.
list of good programming books



7) Effective Java
Wow, my another favorite and holy grail of Java developers. Understanding of Java API is incomplete without reading this book. This book is written by none other than Joshua
 Bloch, who has written a lot of important code in JDK e.g. Java Collection framework and many core classes in java.langpackage. Almost all Java developer is familiar of this book and if anyone has not read it, go read it, this is simply great. You will not only learn best practices but also understand the reasoning behind why Java API is designed that way, as you are getting first-hand information from the programmer who has created that. I don't think, I need to convince any Java developer to read this book but for my C++, Python and Ruby programmers, you can learn a lot about API design, design patterns and writing clean and robust code from this book. I told you about learning from other's experience and Clean Code and Effective Java is the best example of that philosophy.
Best Java Books Ever



8) Clean Coder

This is the second part of the Clean Code, not officially but usually considered it. As the name suggest first part teach you about how a professional programmer write code and this part teaches you how to behave as a professional developer. It's a book about the code of conduct for Professional Programmers, as tagline rightly suggests. I like this book because of Uncle Bob's storytelling and style which feels like he is talking to you, you will feel part of the conversation and you will learn how a professional developer should behave in the different situation. You will learn how to say Yes and how to say No, sounds funny? but this is the best lesson I have learned from this book. I am sure you will not regret about missing this book.
Must read book for every programmer



9) Domain Driven Design
The software is complex and anything which helps you to reduce that complexity or allow you to better deal with that complexity will much appreciate. Domain Drive Design is a rather different way to develop software and that's why I have included this book in my list of must read books for programmers. Eric Evans has done a fabulous job in explaining this term "domain driven design" and showing how it can work to tackle complexity. An intermediate and experienced developer would understand the value of domain knowledge. In fact, a programmer cannot become a subject matter expert and design a better system without knowing about his domain. This is the reason, programmer stick to one domain e.g. Finance, healthcare, Insurance etc. Its combination of both domain knowledge and programming skill which makes you a better programmer.
great book on domain driven design



10) Coders at work

I feel lucky that a book like this is available in my time. Coders at work are based upon nearly 8 hours of interview with fifteen all-time great programmers and computer scientists. You will learn from their experience by following this interview about how great programmers learn to program, how they practice their craft, and what they think about future of programming. You will feel excited by just reading the table of contents and knowing the names of the programmers, which include greats like Joshua Bloch, Peter Norvig, Donald Knuth, Ken Thomson, and Jamie Zawinski. I strongly recommend that every programmer should have a copy of this book in his self or at least PDF version in his iPad or Kindle. This books is not only interesting but motivating and expand your vision, thoughts, and experience.
Books to become better coders



That's all about
 my list of 10 books every programmer should read. You don't need a technical book, full of code every time to become a better programmer. I agree that Programming and Coding are two important aspects of a programmer's job, but there are more things as well. In fact, you do need some books, which shares real experience from programmers of last decade. These books motivate you and fill new energy. These books are not for any programming language expert e.g. a Java or C++ developer, instead, it's for all programmer and software developer. Before learning Java, C++ or Python it's important to learn to program. Languages are just tools, not art. The craftsmanship of programming is in these books. In today's busy world, I highly recommend you to have ebooks, pdfs in your iPad, Kindle or your smartphone and read it whenever you get some free time, you will feel recharged.


If you like this article and hungry for more, check out my post
 10 Articles Every Programmer Must Read, I am sure you will find it interesting.



TAGS:          mkniit              sonu giri             kamalsharma              gniit help
Read More »