These are some interview question and answer asked during my recent
interview. Oracle interview questions are very important during any programming
job interview. Interviewer always want to check how comfortable we are with
any database either we go for Java developer position or C, C++ programmer position .So here I have discussed
some basic question related with oracle database. Apart from these questions
which is very specific to Oracle database you may find some general questions
related to database fundamentals and SQL e.g. Difference
between correlated and noncorrelated subquery in database or truncate
vs delete in SQL etc. Some of the most important topics in Oracle Interview
questions are SQL, date, inbuilt function, stored procedure and less used
features like cursor, trigger and views. These questions also gives an idea
about formats of questions asked during Oracle Interview.
Monday, December 31, 2012
Sunday, December 30, 2012
How to compare Arrays in Java – Equals vs deepEquals Example
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.
Labels:
coding,
core java,
java collection tutorial,
programming
Saturday, December 29, 2012
How to append text into File in Java – FileWriter Example
Some times we need to append text into File in Java instead of creating
new File. Thankfully Java File API is very rich and it provides several ways to
append text into File in Java. Previously we have seen how
to create file and directory in Java and how
to read and write to text file in Java and in this Java IO tutorial we will
see how to append text into file in Java. We are going to use standard FileWriter and BufferedWriter approach
to append text to File. One of the key point to remember while using FileWriter in Java is
to initialize FileWriter to append text i.e. writing bytes
at the end of File rather than writing on beginning of the File. In next
section we will see complete Java program to append text into File in Java. By the way you can also use FileOutputStream instead of
FileWriter if you would like to write bytes, instead of text. Similar
to FileWriter, FileOutputStream constructor
also takes a boolean append argument to open connection to append bytes into
File in Java.
Labels:
core java,
java IO tutorial,
programming
Difference between equals method and "==" operator in Java - Interview Question
Both equals() and "=="
operator in Java is used to compare objects to check equality but main difference between equals method and == operator is that former is method and later is operator. Since Java
doesn’t support operator overloading, == behaves identical for every object
but equals() is method, which can be overridden in Java and logic to compare
objects can be changed based upon business rules. Another notable difference between == and equals method is that former is used to compare both primitive and objects while later is only used for objects comparison. At the same time beginners struggle to find when to use
equality operator (==) and when to use equals method for comparing Java
objects. In this tutorial we will see how equals() method and
== operator works in Java and what is difference between "==" and
equals method in Java and finally when to use "==" and equals() to compare
objects.
Labels:
core java,
core java interview question,
programming
How to add, subtract days, months, years, hours from Date and Time in Java
Adding days, hours, month or years to dates is a common task in Java. java.util.Calendar can be
used to perform Date and Time arithmetic in Java. Calendar class not only
provides date manipulation but it also support time manipulation i.e. you can
add, subtract hours, minutes and seconds from current time. Calendar class
automatically handles date transition or month transition for example if you
ask date after 30 days it will return you date based on whether current month
is 30 or 31 days long. Same is true in case of adding and subtracting years,
Calendar takes care whether current or following year is a leap
year or not. For example 2012 is a leap year and it has February with 29
days, if you ask Calendar day before 365 it will return 24th July (assuming
current date 23rd July) which shows it take care of leap year. By
the way there are couple of more date and time related articles e.g. How
to find current date and time in Java and How
to convert Date to String in Java. If you haven’t read them already, It’s
worth checking to know more about Date and Time in Java.
Labels:
core java,
date and time tutorial,
programming
Difference between Primary key vs Foreign key in table – SQL database tutorial
Main difference between Primary key and Foreign key in a table is that, it’s
the same column which behaves as primary key in parent table and as foreign key
in child table. For example in Customer and Order
relationship, customer_id is primary key in Customer table but
foreign key in Order table. By the way what is foreign key in a
table and difference between Primary and Foreign key are some of the popular
SQL interview questions, much like truncate
vs delete in SQL or difference
between correlated and noncorrelated subquery. We have been learning key SQL
concepts along with these frequently asked SQL questions and in this SQL
tutorial we will discuss about what is foreign key in SQL and purpose of foreign
key in any table. By the way this is the third article related to primary key
in SQL, other being difference
between primary and unique key and How
to find second highest salary in SQL. If you are preparing for any technical
job interview where you expect some SQL questions, check out these questions,
they are worth preparing.
Labels:
database,
mysql,
SQL,
Sybase and SQL Server
Friday, December 28, 2012
java.lang.classcastexception cannot be cast to in Java - cause and solution
As name suggests ClassCastException in Java
comes when we try to type cast an object and object is not of the type we are
trying to cast into. In fact ClassCastException in Java is
one of most common exception in Java along with java.lang.OutOfMemoryError
and ClassNotFoundException
in Java before Generics was introduced in Java 5 to avoid frequent
instances of java.lang.classcastexception cannot be cast to while
working with Collection classes like ArrayList
and HashMap,
which were not type-safe before Java 5. Though we can minimize and avoid java.lang.ClassCastException in Java by
using Generics and writing type-safe
parameterized classes and method, its good to know real cause of ClassCastException and How to
solve it. In this Java tutorial we will see Why java.lang.ClassCastException
comes and how to resolve ClassCastException in Java. We
will also see how to minimize or avoid ClassCastException in Java by
using Generics,
as prevention is always better than cure.
Labels:
core java,
error and exception,
programming
Difference between Class and Object in Java and OOPS with Example
Class and Object are two most important concept of Object oriented
programming language (OOPS) e.g. Java. Main
difference between a Class and an Object in Java is that class
is a blueprint to create different objects of same type. This may looks
simple to many of you but if you are beginner or just heard term Object
Oriented Programming language it might not be that simple. I have met many
students, beginners and programmers who don’t know difference between class and
object and often used them interchangeably. Also Java API having classes like java.lang.Object and java.lang.Class also adds more
confusion in beginners mind. Both of them are totally different things, class
and object in OOPS are concepts and applicable to all Object oriented
programming language e.g. C++ or Scala. On the other hand java.lang.Class and java.lang.Object are part
of Java API. Along with other OOPS concepts like Abstraction,
Encapsulation,
Inheritance
and Polymorphism,
this is also one of the most fundamental of Object oriented programming (OOPS) which
needs to be clearly understood before proceeding into serious application
programming. Without clear understanding of Class and Object you are more prone
to make errors, not able to comprehend an already written program and it would
be pretty hard for you to find bugs or fix errors or exceptions in Java code.
By the way difference between class and object is also a popular programming
interview question, which is quite frequently asked at fresher level
interviews. In this article we will look
this on different angles to differentiate Class and object in Java. Once you
get hold of key OOPS concepts, I would recommend to read 10
OOPS and SOLID design principles for Java programmer, which is tried and
tested design pattern for writing better code.
Labels:
core java,
object oriented programming
How to attach source in eclipse for Jars, debugging and code look-up – JDK Example
Attaching source of any Jar in Eclipse e.g. JDK or open source libraries like
Spring framework is good idea because it help during debugging and code development.
As a Java programmer at least you should attach source of JDK in Eclipse IDE to
find out more about JDK classes. Though Eclipse IDE is pretty good on code
assist, sometime You want to know what's going inside a library or a JDK method,
rather than just reading documentation. Interview questions like How
HashMap works in Java or How
substring cause memory leak can only be answered if you are familiar with source
code of these classes. Once you attach
source code of Java or Spring in Eclipse IDE, You can check code with just a
single click. Some one may argue for Java decompiler like JAD which can create
source from .class
file which is also a smart way to look code for open source library, but
decompiled source file is not same as original source file, as you lost comment
and readability. As per my experience attaching source code corresponding to
JAR file is much better than decompiling a class file using JAD decompiler.
Labels:
core java,
Eclipse,
java tips,
programming
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
Thursday, December 27, 2012
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
What is Referential Integrity in Database or SQL - MySQL Example Tutorial
Referential Integrity is set of constraints applied to foreign key which
prevents entering a row in child table (where you have foreign key) for which
you don't have any corresponding row in parent table i.e. entering NULL or
invalid foreign keys. Referential
Integrity prevents your table from having
incorrect or incomplete relationship e.g. If you have two tables Order and Customer where Customer is parent
table with primary
key customer_id and Order is child
table with foreign key customer_id. Since as per business rules you
can not have an Order without a Customer and this
business rule can be implemented using referential
integrity in SQL on relational database. Referential Integrity will
cause failure on any INSERT or UPDATE SQL
statement changing value of customer_id in child
table, If value of customer_id is not present in Customer table. By
the way What is Referential Integrity in SQL is also an important SQL question
similar to finding
second highest salary in SQL or difference
between truncate and delete and
should be prepared well before going for any job interview, where knowledge of SQL
is one of the requirement.
How to create thread safe Singleton in Java - Java Singleton Example
Thread safe Singleton means a Singleton class which returns exactly same
instance even if exposed to multiple threads. Singleton in Java has been a
classical design pattern like Factory
method pattern or Decorator
design pattern and has been used a lot even inside JDK like java.lang.Runtime
is an example of Singleton class. Singleton pattern ensures that exactly
one instance of class will remain in Java program at any time. In our last post
10
Interview questions on Singleton in Java we have discussed many different
questions asked on Singleton pattern, One of them was writing Thread safe
singleton in Java. Prior to Java 5 double
checked locking mechanism is used to create thread-safe singleton in Java which breaks if one Thread doesn't
see instance created by other thread at same time and eventually you will end
up with more than one instance of Singleton class. From Java 5 onwards volatile
variable guarantee can be used to write thread safe singleton by using
double checked locking pattern. I personally don't prefer that way as there are many other
simpler alternatives to write thread-safe singleton is available available like
using static
field to initialize Singleton instance or using Enum
as Singleton in Java. Let’s see example of both ways to create thread-safe
Singleton in Java.
Oracle Pagination SQL query example for Java programmer
Many time we need SQL query which return data page by page i.e. 30 or 40
records at a time, which can be specified as page size. In fact Database
pagination is common requirement of Java web developers, especially dealing with largest data sets. In this article we
will see how to query Oracle 10g database for pagination or how to retrieve
data using paging from Oracle. Many Java programmer also use display
tag for paging in JSP which supports both internal and external paging. In
case of internal paging all data is loaded in to memory in one shot and display
tag handles pagination based upon page size but it only suitable for small data
where you can afford those many objects in memory. If you have hundreds of row
to display than its best to use external pagination by asking database
to do pagination. In pagination, ordering is another important aspect which can
not be missed. It’s virtually impossible to sort large collection in Java using
Comparator or Comparable
because of limited memory available to Java program, sorting data in database
using ORDER BY clause itself is good solution while doing paging in web
application.
Labels:
core java,
database,
programming,
SQL
How to convert milliseconds to Date in Java - tutorial example
Do you want to convert milliseconds to Date in Java ? Actually java.util.Date is internally
specified in milliseconds from epoch. So any date is number of millisecond
passed since January 1, 1970, 00:00:00 GMT and Date provides constructor
which can be used to create Date from
milliseconds. Knowing the fact that Date is internally maintained in
milliseconds allows you to store date in form of millisecond in Server or in
your Class
because that can be effectively expressed with a long
value. In fact many experienced Java programmer store Date as long value
while writing Immutable class which requires Date, one of the reason for that
is Date being mutable and long value of Date can be very handy. By the ways
this is next in Date related article, we have already discussed How
to convert String to Date and How
to get current month, year and day of week from Date in Java. If you haven’t
read them already, you may find them useful. In this Java tutorial we will see
example of converting millisecond into Date in Java.
Labels:
core java,
date and time tutorial,
programming
3 Example to print array values in Java - toString and deepToString from Arrays
Printing array values in Java or values of array element in Java would
have been much easier if arrays are
allowed to directly prints its values whenever used inside System.out.println() or format
and printf method, Similar to various classes in Java do this by overriding
toString() method. Despite being an object, array in Java doesn't print any
meaningful representation of its content when passed to System.out.println() or any
other print methods. If you are using array in method argument or any other
prominent place in code and actually interested in values of array then you
don't have much choice than for loop until Java 1.4. Things has been changed
since Java 5 because it introduced two extremely convenient methods for
printing values of both primitive and object
arrays in Java. Arrays.toString(array) and Arrays.deepToString(twoDimensionArray) can print
values of any array. Main difference between Arrays.toString() and Arrays.deepToString is that deepToString is used to
print values of multidimensional array which is far more convenient than
nesting of multiple for loops. In this Java tutorial we will see 3 different
ways of printing array values in Java or value of element from Array in
Java.
Wednesday, December 26, 2012
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
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 Encapsulation
and 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 class
and finally difference between static nested class and inner class in Java.
Labels:
coding,
core java,
core java interview question,
programming
SQL query to add, modify and drop column in table with default value NOT NULL constraint – MySQL database
How to add column in existing table with default value is another popular
SQL
interview question asked for Junior level programming
job interviews. Though syntax of SQL query to add column with default value
varies little bit from database to database, it always been performed using
ALTER keyword of ANSI SQL. Adding column in existing table in MySQL database
is rather easy and straight forward and we will see example of SQL query for MySQL database which adds a column with default value. You can also provide
constraints like NULL or NOT NULL while
adding new column in table. In this SQL tutorial we are adding third column in a table called Contacts which
contains name and phone of
contacts. Now we want to add another column email with default value "abc@yahoo.com". We will
use ALTER command in SQL to do that. By the way this is next in our SQL
tutorials e.g. How
to join three tables in SQL and SQL
query to find duplicate records in table. If you haven’t read them yet,
then you may find them useful.
Labels:
database,
mysql,
SQL,
Sybase and SQL Server
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 code
to reduce amount of type casting in Java which also reduces risk of java.lang.ClassCastException at
runtime.
Labels:
coding,
core java,
object oriented programming
Tuesday, December 25, 2012
How to create auto incremented identity column in SQL Server, MySQL, Sybase and Oracle ?
Automatic incremented ID, Sequence or Identity columns are those columns
in any table whose value is automatically incremented by database based upon
predefined rule. Almost all databases e.g. Microsoft
SQL Server, MySQL,
Oracle
or Sybase supports auto incremented identity columns but in different ways like
Oracle provides SEQUENCE object which can be used to
generate automatic numbers, Microsoft SQL Server upto 2008 version provides IDENTITY() functions
for similar purpose. Sybase also has IDENTITY function
but little different than SQL Server and MySQL uses auto_incremented keyword to
make any numeric column auto incremented. As first normal form advised
about primary keys which is used to uniquely identity row and if there is no
natural column or combination of column exists to act as primary
key, mostly database developer use auto incremented surrogate keys which is
used to uniquely identify each row. In this SQL tutorial we will see how to
generate auto incremented ID column in Microsoft SQL Server, Oracle 11g, MySQL
and Sybase ASE Server. By the way this SQL article is continuation of my earlier
post on SQL and database like difference
between truncate and delete in SQL and Finding
second highest salary in MySQL and SQL Server. If you haven't got chance to
read them than I suggest they are worth looking.
Labels:
database,
mysql,
SQL,
Sybase and SQL Server
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
How to fix java.io.NotSerializableException: org.apache.log4j.Logger Error in Java
java.io.NotSerializableException:
org.apache.log4j.Logger error says that instance of org.apache.lo4j.Logger is not
Serializable. This error comes when we use log4j for logging
in Java and create Logger in a Serializable class e.g. any domain class or
POJO which we want to store in HttpSession or want to
serialize it. As we know from 10
Java Serialization interview question that, if you have a non serializable
class as member in a Serializable class, it will throw java.io.NotSerializableException Exception.
Look at the below code :
public class Customer implements Serializable{
private Logger logger = Logger.getLogger(Customer.class)
......
}
If instance of Customer will be stored in HttpSession or
Serialized externally it will throw "java.io.NotSerializableException:
org.apache.log4j.Logger" because here logger instance is neither static
or transient
and it doesn't implement Serializable
or Externalzable interface.
How to solve java.io.NotSerializableException: org.apache.log4j.Logger
Solving java.io.NotSerializableException:
org.apache.log4j.Logger is simple,
you have to prevent logger instance from default serializabtion process, either
make it transient
or static. Making it static final is preferred option due to many reason
because if you make it transient than after deserialization logger instance
will be null and any logger.debug() call will result in NullPointerException
in Java because neither constructor
not instance initializer block is called during deserialization. By making it static
and final you ensure that its thread-safe
and all instance of Customer class can share same logger
instance, By the way this error is also one of the reason Why Logger should
be declared static and final
in Java program. Just make following code change to fix java.io.NotSerializableException:
org.apache.log4j.Logger in Java.
public class Customer implements Serializable{
private static final Logger logger = Logger.getLogger(Customer.class)
......
}
That's all on how to fix java.io.NotSerializableException:
org.apache.log4j.Logger in Java. We have seen what cause
java.io.NotSerializableException: org.apache.log4j.Logger, it's because Logger
class is not Serializable but we also learned that there is no point
serializing Logger instance and better to make
Logger static and final.
Other Serialization and troubleshooting articles from Javarevisited
Blog
Labels:
core java,
debugging,
error and exception
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 array
in 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
How to create and evaluate XPath Expression in Java:
You can use XPathExpression from javax.xml.xpath package to create and
execute XPATH expression in Java. Java
API provides javax.xml.xpath package, which contains classes like Xpath, XpathFactory to work
with XPATH and XML documents. By the way this is third article on Xpath, In
last couple of tutorials e.g. XPATH examples to select values using
attributes and my XPATH notes for Java programmer,
we have seen basics of Xpath expression from XML and Java point of view. Anyone who has work with XML technologies in
Java knows importance of XPATH, it is one the most useful technology to
retrieve selected data from XML files. XPATH is like SQL which is used to
retrieve data from relational database. Many back-office and middle-office Java
application which transfers data in form of XML documents makes extensive use
of XPATH expression to retrieve value
for printing or for decision making. Though there are lot of open source XML
libraries are available to assist with Java and XML development e.g. XML Beans.
I personally prefer to use standard Java API if functionality is available there. In this Java
tutorial we will learn how to create XPath expression in Java program and retrieving values from XPATH e.g. text, numbers and boolean values, which is
critical for programming flow.
Labels:
core java,
Java xml tutorial,
programming,
xml
Monday, December 24, 2012
Sybase and SQL Server PATINDEX CHARINDEX Example to split String in Stored procedure
Some time we need to split a long comma separated String in Stored
procedure e.g. Sybase or SQL Server
stored procedures. Its quite common to pass comma
delimited or delimiter separated String as input parameter to Stored
procedure and than later split comma separated String into multiple values
inside stored proc. This is not just case of input parameter but you can also
have comma separated string in any table data. Unfortunately there is no split() function
in Sybase or SQL Server 2005 or 2008 which can directly split string based on
delimiter just like in Java
string split method. Fortunately Sybase Adaptive Server and Microsoft SQL
server has functions like CHARINDEX and PATINDEX which can
be used to split comma separated String. This is next on our SQL tutorials
after seeing SQL
query to find duplicate records in table and How
to find 2nd and Nth maximum salary in SQL.
Labels:
database,
SQL,
Sybase and SQL Server
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
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
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
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
Sunday, December 23, 2012
How to remove duplicates elements from ArrayList in Java
You can remove duplicates or repeated elements from ArrayList in Java by converting
ArrayList into HashSet in Java. but before doing that just keep in mind that
Set doesn't preserver insertion order which is guaranteed by List,
in fact that’s the main difference
between List and Set in Java. So when you convert ArrayList to HashSet all
duplicates elements will be removed but insertion order will be lost.
Let’s see this in action by writing a Java program to remove duplicates from ArrayList
in Java. In this Java collection tutorial we will see both approach of deleting
duplicates from ArrayList e.g using Hashset
and LinkedHashSet and compare order of elements in final ArrayList which
contains no duplicates. If you are not very familiar of What is an ArrayList
and HashSet in Java collection framework, I suggest reading Java
ArrayList Example and 10
HashSet Example in Java. These articles contains good introduction of most
common used collection in Java i.e. ArrayList and HashSet.
Labels:
core java,
java collection tutorial,
programming
Saturday, December 22, 2012
How to find second highest or maximum salary of Employee in SQL - Interview question
How to find second highest or second maximum salary of an Employee is one
of the most frequently asked SQL interview question similar to finding duplicate records in table
and when to use truncate vs delete.
There are many ways to find second highest salary based upon which database you
are using as different database provides different feature which can be used to
find second maximum or Nth maximum salary of employee. Well this
question can also be generalized with other scenario like finding second
maximum age etc. In this SQL tutorial we will see different example of SELECT SQL query to find
second highest salary independent of databases or you may call in ANSI SQL and
other SQL queries which uses database specific feature to find second maximum
salary.
Labels:
database,
interview questions,
mysql,
SQL
XPath Tutorial - How to select elements in XPATH based on attribute and element value example
In this XPATH tutorial we will see example of selecting elements based
upon its value or attribute value. We will see how to select between two
elements based upon value of its child elements or based upon value of its
attribute. XPATH is an important concept to understand if you are working with
XML files. Most of Back-office platform relies on XML
files for transporting data from one system to other and if you are working
on any back-office or middle office system in Java or .NET, its important to know
about XPATH and be able to use XPATH to select data from XML. Some time back I
have shared my XPATH
notes for Java programmer and this example shows true power of XPATH as how convenient its to made selective decision. For those who are completely new in
XML and XPATH, XPATH is great xml tool which allows you to query XML document
and select or retrieve selective data much like SQL but if you are new to XPATH
or haven't had much experience with XML tool and technology than you will
struggle to find correct syntax of XPATH for your different need.
Labels:
core java,
Java xml tutorial,
xml
Constructor Chaining in Java - Calling one constructor from another using this and super
Constructor Chaining in Java
In Java you can call one constructor from another and it’s known as
constructor chaining in Java. Don’t confuse between constructor
overloading and constructor chaining, former is just a way to declare more
than one constructor
in Java. this and super keyword is
used to call one constructor from other in Java. this() can be
used to call other constructor of same class while super() can be
used to call constructor from super class in Java. Just keep in mind that this() in realty
calls no argument constructor of same class, while this(2) calls
another constructor of same class which accepts one integer parameter.
Similarly super() can be used to call no argument
constructor of super class and super with parameter can be used to call other overloaded
constructor of parent class. Calling one constructor from other is called constructor chaining in Java, which we
seen while discussing constructor overloading in Java. Constructor chaining is
also used to implement telescoping
pattern where an object can be created with combination of multiple
property. In our last tutorial we have seen some important properties of Java
constructor as well as answered question What
is Constructor in Java and in this Java tutorial we will see example of how to call one constructor from other for
same class and super class.
Labels:
core java,
core java interview question,
programming
Friday, December 21, 2012
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.
Invalid initial and maximum heap size in JVM - How to fix
I was getting "Invalid initial heap size: -Xms=1024M" while
starting JVM and even after changing maximum heap size from 1024 to 512M it keep
crashing by telling "Invalid initial heap size: -Xms=512m , Could not
create the Java virtual machine" , I check for almost everything
starting form checking how much physical memory my machine has to any typo in JVM
parameters, only to find out that instead of M, I had put MB there. Java
accepts both small case and capital case for Kilo, Mega and Gigs. you can use m
or M, g or G etc but never used MB, GB or KB.
Similar problem can occur with maximum
heap size specified by -Xmx. Also from Java 6 update 18
there is change on default
heap size in JVM.
Labels:
core java,
debugging,
error and exception,
programming
Thursday, December 20, 2012
SQL query to copy, duplicate or backup table in MySQL, Oracle and PostgreSQL database
Many times we need to create backup or copy of tables in database like
MySQL, Oracle or PostgreSQL while modifying table schema like adding new
columns, modifying column or dropping columns. Since its always best to have a
backup of table which can be used in any event. I was looking for an easy way
to create exact copy or duplicate tables which must be same in schema as well
as in data, similar to creating copy of folder. Luckily there is an easy SQL
query "CREATE table table_name AS" which allows you to create exact
copy of table by executing just one SQL query. Yes, you read it
correctly, no tool is required to create backup of table you just need to
execute an SQL query. This is simply awesome given its importance and best part
of this SQL query is that it works in almost all the database. I have tested it
in MySQL and Oracle but t it should work
perfectly find in other databases like PostgreSQL, SQL Server and DB2 as well.
This SQL query tip is in continuation of my earlier SQL query examples like SQL query to find duplicate rows in a
table and SQL query to join three tables in MySQL
.
Labels:
database,
mysql,
programming,
SQL
Subscribe to:
Posts (Atom)