java.util.Arrays class provides equals() and deepEquals() method to compare two Arrays in Java. Both of these are overloaded method to compare primitive arrays e.g. int, long, float, double and Object arrays e.g. Arrays.equals(Object[] , Object[]). Arrays.equals() returns true if both Arrays which it is comparing are null, If both array pointing to same Array Object or they must be of same length and contains same element in each index. In all other cases it returns false. Arrays.equals() calls equals() method of each Object while comparing Object arrays. One of the tricky question in Java related to Array comparison is Difference between Arrays.equals() and Arrays.deepEquals() method. Since both equals and deepEquals is used for array comparison, what is difference between them becomes important. Short answer of this questions is that, Array's equals() method does not perform deep comparison and fails logical comparison in case of nested Array, on other hand deepEquals() perform deep comparison and returns logical comparison in case of nested array.
Showing posts with label coding. Show all posts
Showing posts with label coding. Show all posts
Friday 30 August 2013
Thursday 29 August 2013
Top Most What is static import in Java 5 with Example
Static import in Java allows to import static members of class and use them, as they are declared in the same class. Static import is introduced in Java 5 along with other features like Generics, Enum, Autoboxing and Unboxing and variable argument methods. Many programmer think that using static import can reduce code size and allow you to freely use static field of external class without prefixing class name on that. For example without static import you will access static constant MAX_VALUE of Integer class as Integer.MAX_VALUE but by using static import you can import Integer.MAX_VALUE and refer it as MAX_VALUE. Similar to regular importstatements, static import also allows wildcard * to import all static members of a class. In next section we will see Java program to demonstrate How to use static import statements to import static fields.
Labels:
coding,
Core Java,
java 5 tutorial,
programming
Wednesday 28 August 2013
Top Most How to find middle element of LinkedList in Java in one pass
How do you find middle element of LinkedList in one pass is a programming question often asked to Java and non Java programmers in telephonic Interview. This question is similar to checking palindrome or calculating factorial, where Interviewer some time also ask to write code. In order to answer this question candidate must be familiar with LinkedList data structure i.e. In case of singly LinkedList, each node of Linked List contains data and pointer, which is address of next Linked List and last element of Singly Linked List points towards null. Since in order to find middle element of Linked List you need to find length of LinkedList, which is counting elements till end i.e. until you find the last element on Linked List. What makes this data structure Interview question interesting is that you need to find middle element of LinkedList in one pass and you don’t know length of LinkedList. This is where candidates logical ability puts into test, whether he is familiar with space and time trade off or not etc. As if you think carefully you can solve this problem by using two pointers as mentioned in my last post on How to find length of Singly Linked List in Java. By using two pointers, incrementing one at each iteration and other at every second iteration. When first pointer will point at end of Linked List, second pointer will be pointing at middle node of Linked List. In fact this two pointer approach can solve multiple similar problems e.g. How to find 3rd element from last in a Linked List in one Iteration or How to find nth element from last in a Linked List. In this Java programming tutorial we will see a Java program which finds middle element of Linked List in one Iteration.
Labels:
coding,
Core Java,
core java interview question,
programming
Tuesday 27 August 2013
Top Most Recursion in Java with example – Programming Techniques Tutorial
Recursion is one of the tough programming technique to master. Many programmers working on both Java and other programming language like C or C++ struggles to think recursively and figure out recursive pattern in problem statement, which makes it is one of the favorite topic of any programming interview. If you are new in Java or just started learning Java programming language and you are looking for some exercise to learn concept of recursion than this tutorial is for you. In this programming tutorial we will see couple of example of recursion in Java programs and some programming exercise which will help you to write recursive code in Java e.g. calculating Factorial, reversing String and printing Fibonacci series using recursion technique. For those who are not familiar with recursion programming technique here is the short introduction: "Recursion is a programming technique on which a method call itself to calculate result". Its not as simple as it look and mainly depends upon your ability to think recursively. One of the common trait of recursive problem is that they repeat itself, if you can break a big problem into small junk of repetitive steps then you are on your way to solve it using recursion.
Labels:
coding,
Core Java,
programming
Monday 26 August 2013
Top Most JSTL foreach tag example in JSP - looping ArrayList
JSTL foreach loop in JSP
JSTL foreach tag is pretty useful while writing Java free JSP code. JSTL foreach tag allows you to iterate or loop Array List, HashSetor any other collection without using Java code. After introduction of JSTL and expression language(EL) it is possible to write dynamic JSP code without using scriptlet which clutters jsp pages. JSTL foreach tag is a replacement of for loop and behaves similarly like foreach loop of Java 5 but still has some elements and attribute which makes it hard for first-timers to grasp it. JSTL foreach loop can iterate over arrays, collections like List, Setand print values just like for loop. In this JSP tutorial we will see couple of example of foreach loop which makes it easy for new guys to understand and use foreach loop in JSP. By the way this is our second JSP tutorial on JSTL core library, in last tutorial we have seen How to use core <c:set> tag in JSP page.
Labels:
coding,
interview questions,
Jsp,
JSTL,
programming
Top Most How to check if a number is a palindrome or not in Java - Example
How to check if a number is a palindrome or not is a variant of popular String interview question how to check if a String is a palindrome or not. A number is said to be a palindrome if number itself is equal to reverse of number e.g. 313 is a palindrome because reverse of this number is also 313. On the other hand 123 is not a palindrome because reverse of 123 is 321 which is not equal to 123, i.e. original number. In order to check if a number is a palindrome or not we can reuse the logic of How to reverse number in Java. Since in most of interview, you are supposed to solve this question without taking help from API i.e. only using basic programming construct e.g. loop, conditional statement, variables, operators and logic. I have also seen programmer solving this question by first converting integer to String and than reversing String using reverse() method of StringBuffer and than converting String back to Integer, which is not a correct way because you are using Java API. Some programmer may think that this is just a trivial programming exercise but it’s not. Questions like this or Fibonacci series using recursion can easily separate programmers who can code and who can’t. So it’s always in best interest to keep doing programing exercise and developing logic.
Labels:
coding,
Core Java,
core java interview question,
programming
Top Most Inner class and nested Static Class in Java with Example
Inner class and nested static class in Java both are classes declared inside another class, known as top level class in Java. In Java terminology, If you declare a nested class static, it will called nested static class in Java while non static nested class are simply referred as Inner Class. Inner classes are also a popular topic in Java interviews. One of the popular question is difference between inner class and nested static class , some time also refereed as difference between static and non static nested class in Java. One of the most important question related to nested classes are Where should you use nested class in Java? This is one of the tricky Java question, If you have read Effective Java from Joshua Bloch than in one chapter he has suggested that if a class can only be useful to one particular class, it make sense to keep that inside the class itself otherwise declare it as top level class. Nested class improves Encapsulationand help in maintenance. I actually look JDK itself for examples and if you look HashMap class, you will find that Map.Entry is a good example of nested class in Java. Another popular use of nested classes are implementing Comparator in Java e.g. AgeCompartor for Person class. Since some time Comparator is also tied with a particular class, it make sense to declare them as nested static class in Java. In this Java tutorial we will see what is Inner class in Java, different types of Inner classes, what is static nested classand finally difference between static nested class and inner class in Java.
Labels:
coding,
Core Java,
core java interview question,
programming
Top Most What is Type Casting in Java - Casting one Class to other class or interface Example
Type casting in Java is to cast one type, a class or interface, into another type i.e. another class or interface. Since Java is an Object oriented programming language and supports both Inheritance and Polymorphism, It’s easy that Super class reference variable is pointing to Sub Class object but catch here is that there is no way for Java compiler to know that a Super class variable is pointing to Sub Class object. Which means you can not call method which is declared on sub class. In order to do that, you first need to cast the Object back into its original type. This is called type-casting in Java. This will be more clear when we see an example of type casting in next section. Type casting comes with risk of ClassCastException in Java, which is quite common with method which accept Object type and later type cast into more specific type. we will see when ClassCastException comes during type casting and How to avoid it in coming section of this article. Another worth noting point here is that from Java 5 onwards you can use Generics to write type-safe codeto reduce amount of type casting in Java which also reduces risk of java.lang.ClassCastException at runtime.
Labels:
coding,
Core Java,
object oriented programming
Sunday 25 August 2013
Top Most How to convert String to long in Java - 4 Examples
How to convert string to long in Java is one of those frequently asked questions by beginner who has started learning Java programming language and not aware of how to convert from one data type to another. Converting String to long is similar to converting String to Integer in Java, in-fact if you know how to convert String to Integer than you can convert String to Long by following same procedure. Though you need to remember few things while dealing with long and String first of all long is primitive type which is wrapped by Long wrapper class and String is an Object in Java backed by character array. Before Java 5 you need to take an extra step to convert Long object into long primitive but after introduction of autoboxing and unboxing in Java 5, Java language will perform that conversion for you. This article is in continuation of our previous conversion tutorial like how to convert String to Double in Java or how to convert String to Enum in Java. In this Java tutorial we will learn 3 different ways to convert String to long by code example and we will also analyze pros and cons of each approach.
Labels:
coding,
Core Java,
programming
Top Most Difference between valueOf and parseInt method in Java
Both valueOf and parseInt methods are used to convert String to Integer in Java, but there are subtle difference between them. If you look at code of valueOf() method, you will find that internally it calls parseInt() method to convert Integer to String, but it also maintains a pool of Integers from -128 to 127 and if requested integer is in pool, it returns object from pool. Which means two integer objects returned using valueOf() method can be same by equality operator. This caching of Immutable object, does help in reducing garbage and help garbage collector. Another difference between parseInt() and valueOf() method is there return type. valueOf() of java.lang.Integer returns an Integer object, while parseInt() method returns an int primitive. Though, after introducing Autoboxing in Java 1.5, this doesn't count as a difference, but it's worth knowing.
Labels:
coding,
Core Java,
Java Programming Tutorials
Top Most How to initialize List with Array in Java - One Liner Example
Initializing list while declaring it is very convenient for quick use. If you have been using Java programming language for quite some time then you must be familiar with syntax of array in Java and how to initialize an arrayin the same line while declaring it as show below:
String[] oldValues = new String[] {"list" , "set" , "map"};
or even shorter :
String[] values = {"abc","bcd", "def"};
Similarly we can also create List and initialize it at same line, popularly known as initializing List in one line example. Arrays.asList() is used for that purpose which returns a fixed size List backed by Array. By the way don’t confuse between Immutable or read only List which doesn’t allow any modification operation including set(index) which is permitted in fixed length List.Here is an example of creating and initializing List in one line :
Labels:
coding,
Core Java,
java collection tutorial,
programming
Top Most Eclipse shortcut to System.out.println in Java program - Tips
Eclipse IDE provides quick shortcut keys to print System.out.println statement in Java but unfortunately not every Java programmers are familiar of that. Even programmers with 3 to 4 year of experience sometime doesn't know this useful Eclipse shortcut to generate System.out.println messages. This Eclipse tips is to help those guys. Let me ask you one question, How many times you type System.out.println in your Java program? I guess multiple time, while doing programming, debuggingand testing small stuff. System.out.println is most preferred way to print something on console because it doesn’t required setup like configuring Log4J or java.util.Logger . Though I recommend using logging for better information display in production code, nobody can undermine importance of System.out.println statement in Java. On the quest of learning Eclipse shortcut, some of them which I have discussed in my list of Top 30 Eclipse shortcut for Java programmers, I found a very useful Eclipse shortcut for generating code for System.out.println statement in Java source file. By using this Eclipse shortcut you can create System.out.println() messages in 60% less time, as you only need to type the message. This Eclipse shortcut will place your cursor right in the place, where it should be i.e. inside System.out.println method.
Labels:
coding,
Core Java,
Eclipse,
programming
Top Most Java program to calculate area of Triangle - Homework, programming exercise example
Calculate area of Triangle in Java
Write a Java program to calculate Area of Triangle, accept input from User and display output in Console is one of the frequently asked homework question. This is not a tough programming exercise but a good exercise for beginners and anyone who has started working in Java. For calculating area of triangle using formula 1/2(base*height), you need to use arithmetic operator. By doing this kind of exercise you will understand how arithmetic operators works in Java, subtle details which affect calculation like precedence and associativity of operator etc. Fortunately this question is not very popular on Java interview like other exercise we have seen e.g. Java program to print Fibonacci series and Java program to check for palindrome. Nevertheless its a good Java homework.
Labels:
coding,
Core Java,
homework,
programming
Saturday 24 August 2013
Top Most How to get current date, month, year and day of week in Java program
Here is quick Java tip to get current date, month, year and day of week from Java program. Java provides a rich Date and Time API though having thread-safety issue but its rich in function and if used locally can give you all the date and time information which you need for your enterprise Java application. In last Java tutorial on Date and Time API we have seen how to get current date and time from different timezone using DateFormat and SimpleDateFormat classes and in this post we will get some more details like current month, year, day of week etc by using java.util.Calendar class. Just keep in mind that Calendar instance should not be shared between multiple threads. Calendar class in Java provides different fields to get different information e.g. Calendar.DATE gives you current date while Calendar.MONTH gives you current month based on what type of Calendar you are using, which depends upon locale.
Labels:
coding,
Core Java,
date and time tutorial,
programming
Top Most How to create and modify Properties file form Java program in Text and XML format
Though most of the time we create and modify properties file using text editor like notepad, word-pad or edit-plus, It’s also possible to create and edit properties file from Java program. Log4j.properties, which is used to configure Log4J based logging in Java and jdbc.properties which is used to specify configuration parameters for database connectivity using JDBC are two most common example of property file in Java. Though I have not found any real situation where I need to create properties file using Java program but it’s always good to know about facilities available in Java API. In last Java tutorial on Properties we have seen how to read values from properties file on both text and XML format and in this article we will see how to create properties file on both text and XML format. Java API’s java.util.Properties class provides several utility store() methods to store properties in either text or xml format. Store() can be used to store property in text properties file and storeToXML() method can be used for creating a Java property file in XML format.
Labels:
coding,
Core Java,
Java xml tutorial,
programming
Top Most How to count occurrence of a character in String - Java programming exercise
Write a program to count number of occurrence of a character in String is one of common programming interview question not just in Java but also in other programming language like C or C++. As String in a very popular topic on programming interviews and there are lot of good programming exercise on String like "count number of vowels or consonants in String", "count number of characters in String" , How to reverse String in Java using recursion or without using StringBuffer etc, it becomes extremely important to have solid knowledge of String in Java or any other programming language. In Interview, most of the time Interviewer will ask you to write program without using any API method, as Java is very rich and it always some kind of nice method to do the job, But it also important to know rich Java and open source libraries for writing production quality code. Anyway in this question we will see both API based and non API based(except few) way of to count number of occurrence of a character in String on Java.
Labels:
coding,
Core Java,
core java interview question,
programming
Top Most How to read input from command line in Java using Scanner
Java 5 introduced a nice utility called java.util.Scanner which is capable to read input form command line in Java. Using Scanner is nice and clean way of retrieving user input from console or command line. Scanner can accept InputStream, Reader or simply path of file from where to read input. In order to reading from command line we can pass System.in into Scanner's constructor as source of input. Scanner offers several benefit over classical BufferedReader approach, here are some of benefits of using java.util.Scanner for reading input from command line in Java:
Labels:
coding,
Core Java,
homework,
programming
Friday 23 August 2013
Top Most 2 ways to combine Arrays in Java – Integer, String Array Copy Example
There are multiple ways to combine or join two arrays in Java, both for primitive like int array and Object e.g. String array. You can even write your own combine() method which can use System.arrayCopy() to copy both those array into third array. But being a Java developer, I first looked in JDK to find any method which concatenate two arrays in Java. I looked at java.util.Arrays class, which I have used earlier to compare two arrays and print arrays in Java, but didn't find a direct way to combine two arrays. Then I looked into Apache Commons, ArrayUtils class and bingo, it has several overloaded method to combine int, long, float, double or any Object array. Later I also found that Guava ,earlier known as Google collections also has a class ObjectArrays in com.google.common.collect package, which can concatenate two arrays in Java. It's always good to add Apache commons and Guava, as supporting library in Java project, they have lots of supporting classes, utility and method, which complements rich Java API. In this Java programming tutorial, we will see example of these 2 ways to combine, join or concatenate two arrays in Java and will write a method in core Java to concatenate two int arrays in Java.
Labels:
coding,
Core Java,
Java Programming Tutorials
Thursday 22 August 2013
Top Most How to Reverse Array in Java - Int and String Array Example
This Java tips is about, how to reverse array in Java, mostly primitive types e.g. int, long, double and String arrays. Despite of Java’s rich Collection API, use of array is quite common, but standard JDK doesn’t has great utility classes for Java. It’s difficult to convert between Java Collection e.g. List, Setto primitive arrays. Java’s array utility class java.util.Arrays, though offers some of critical functionalities like comparing arrays in Java and support to print arrays, It lacks lot of common features, such as combining two arrays and reverse primitive or object array. Thankfully, Apache commons lang, an open source library from Apache software foundation offers one interesting class ArrayUtils, which can be used in conjunction with java.util.Arrays class to play with both primitive and object array in Java. This API offers convenient overloaded method to reverse different kinds of array in Java e.g. int, double, float, log or Object arrays. On a similar note, you can also write your own utility method to reverse Array in Java, and this is even a good programming question. For production usage, I personally prefer tried and tested library methods instead of reinventing wheel. Apache commons lang fits the bill, as it offer other convenient API to complement JDK. In this Java tutorial, we will reverse int and String array in Java using ArrayUtils to show How to reverse primitive and object array in Java.
Labels:
coding,
Core Java,
Java Programming Tutorials
Wednesday 21 August 2013
Top Most How to escape text when pasting as String literal in Eclipse Java editor
Whenever you paste String in Eclipse which contains escape characters, to store in a String variable or just as String literal it will ask to manually escape special characters like single quotes, double quotes, forward slash etc. This problem is more prominent when you are pasting large chunk of data which contains escape characters like a whole HTML or XML file, which contains lots of single quotes e.g. ‘’ and double quotes “” along with forward slash on closing tags. It’s very hard to manually escape all those characters and its pretty annoying as well. While writing JUnit test for XML documents, parsing and processing I prefer to have whole XML file as String in Unit test, which pointed me to look for that feature in Eclipse. As I said earlier in my post Top 30 Eclipse keyboard shortcuts, I always look to find new shortcut and settings in Eclipse which help to automate repetitive task. Thankfully Eclipse has one setting which automatically escapes text as soon as you paste it. This is even more useful if you prefer to copy file path and just paste it, Since windows uses forward slash it automatically escape that instead of you going manually and escaping them. By default this setting is disabled in Eclipse IDE and you need to enable it.
Subscribe to:
Posts (Atom)
Labels
Core Java
programming
core java interview question
Core Java Faq's
Servlets
coding
database
jsp-servlet
spring
Java
linux
unix
interview questions
java investment bank
Web Services
Interview
investment bank
mysql
Senior java developer interviews
best practices
java collection tutorial
RMI
SQL
Eclipse
FIX protocol tutorial
tibco
J2EE
groovy
java questions
SCJP
grails
java 5 tutorial
jdbc
beginner
error and exception
Design Patterns
Java Programming Tutorials
fundamentals
general
object oriented programming
xml
Java Programs
Hibernate
Examples
Flex
JAMon
Java xml tutorial
logging
Jsp
Struts 2.0
Sybase and SQL Server
debugging
java interviews
performance
FIX Protocol interview questions
JUnit testing
WebSphere
date and time tutorial
experienced
java IO tutorial
java concurrency
thread
Ejb
Freshers Papers
IT Management
Java Exapmle
Java Script
SQL and database tutorial examples
Scwcd
ant tutorials
concurrency example and tutorial
future state
homework
java changes
java threading
tricky
Agile
Business of IT
Development
JSTL
Java JSON tutorial
Java multithreading Tutorials
PM
Scrum
data structure and algorithm
java puzzles
java tips
testing
tips
windows 8
5 way to create Singleton Object
Architect Interview Questions and Answers
Architecture
Architecure
Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device.
C Programming
CIO
Callable Statement in Java
Circular dependency of Objects in Java
Comparable Example in Collection
Custom annotation in Java
Developer Interview
Divide and rule example in java
Drupal
Example of Singleton Pattern
FIX protocol
ForkJoin Example in Java 7
Get data from dynamic table with Java Script
Git
HTML and JavaScript
Health
Hello World TCP Client Server Networking Program
Hibernate Basics
Hibernate Interview Question Answer
J2EE Interview Question And Answers
J2ME GUI Program
JEE Interview QA
JMS interview question
Java J2EE Hibernate Spring Struts Interview Question
Java System Property
Java Threads
Manager
Portlets
Provident Fund
Read data from any file in same location and give the required result.
Reading Properties File in Java
Redpoint
Rest WebService Client
Rest Webservice Test
SAL join with ven diagram
SCP UNIX COMMAND
SSL
Singleton Pattern in Java
Spring Bean Initialization methods and their order
Spring Interview Questions
Struts
Struts 2.0 Basics
Struts 2.0 Design Pattern
Submit Html Form With Java Script On The Fly
Unix executable For Java Program
XOM DOM SAX
XP
books
computers
core java;
core java; object oriented programming
data structure; java investment bank;
design pattern
dtd
duplicate rows in table
get browser name with jquery
grails podcast
inner class
java beginners tutorial
java cache
java networking tutorial
java spring
java util; java collections; java questions
java.java1.5
linked list
mailto function with all browser
oracle database
oracle duplicate rows
orm
schema
social
spring mvc questions
struts
transaction
tricks
tweet
windows
xslt