Pages

How to reverse string in java is popular core java interview question and asked on all levels from junior to senior java programmingjob. since Java has rich API most java programmer answer this question by using StringBufferreverse() method which easily reverses an Stringin Java and its right way if you are programming in Java but most interview doesn't stop there and they ask interviewee to reverse Stringin Java without using StringBuffer or they will ask you to write an iterative reverse function which reverses string in Java. In this tutorial we will see how to reverse string in both iterative and recursive fashion. This example will help you to prepare better for using recursion in java which is often a weak area of Java programmer and exposed during a programming interview.

Recently Google made new update called page layout algorithm improvement update which targets website, blogs having excessive ads on Above the fold page area. if you are experiencing sudden traffic drop from last Friday 20th January 2012 , you are most likelyaffected by Google page layout algorithm update. This Recent Google search update is causing severe drop more than half of normal trafficto various sites and blogs which has two or three ads around header and above the fold area.here are important points I have read and collected regarding Google page layout algorithm update and how it affecting various sites and blog:

Google page layout algorithm update and Above the folds ads.

1) Google Page layout Algorithm improvement update was done around 19th- 20th January 2012. So if your website traffic is down or reducing from that period and you have ads above the fold you may be affected by this Google update.

Default Character encoding in Javaor charset is the character encoding used by JVM to convert bytes into Strings or characters when youdon't define java system property "file.encoding". Java gets character encoding by calling System.getProperty("file.encoding","UTF-8") at the time of JVM start-up. So if Java doesn't get any file.encoding attribute it uses "UTF-8" character encoding for all practical purpose e.g. on String.getBytes() or Charset.defaultCharSet(). Most important pointto remember is that Java caches character encoding or value of system property "file.encoding" in most of its core classes like InputStreamReader which needs character encoding after JVM started. so if you change system property "file.encoding" programmatically you don't see desired effect and that's why you should always work with your own character encoding provided to your application and if its need to be set than set character encoding or charset while you start JVM.In this Java tutorial, we will see couple of different way by which we can set default character encoding or charset of Java and how toretrieve value of charset inside java program.

There are two ways to define Error page in Java web application written using Servlet and JSP. First way is page wise error page which is defined on each jsp page and if there is any unhanded exception thrown from that page, corresponding error page will be displayed. Second approach is an application wide general or default error page which is shown if any Exception is thrown from any Servlet or JSP and there is no page specific error page defined.

In this java tutorial we will see both approach to declare error page in JSP and when should we use page specific error page and when should we choose generate default application wide error page in Java web application. This is in continuation of my earlier post on Servlet and JSP like top 10 Servlet interview questions and top 10 JSP interview questions.

"java.sql.SQLException: Invalid column index" is a frequent error while working in Java Database Connectivity (JDBC). As thename suggests "Invalid column index" its related to accessing or setting column in your SQL Query using prepared statement in Java. I have seen "java.sql.SQLException: Invalid column index" coming mostly due to two reason:

Most common cause of "java.sql.SQLException: Invalid column index" is a misconception that column index started with "0" like arrayor String index but that's not true instead column index starts with "1" so whenever you try to get or Set column data with columnindex "0" you will get "java.sql.SQLException: Invalid column index".

Thread vs Runnable in Java is always been a confusing decision for beginners in java. Thread in Java seems easy in comparison of Runnable because you just deal with one class java.lang.Thread while in case of using Runnable to implement Thread you need to deal with both Thread and Runnable two classes. though decision of using Runnable or Thread should be taken considering differences between Runnable and Thread and pros and cons of both approaches. This is also a very popular thread interview questions and most of interviewer are really interested to know what is your point of view while choosing Thread vs Runnable or opposite. In this java article we will try to point out some differences between Thread and Runnable in Java which will help you to take an informed decision.

You can find JVM bit size e.g. 32 bit or 64 bit by using either running java command from the command prompt or by using System.getProperty() from Java program. The question is why do you want to know hardware or platform configuration while writing Java code which is supposed to write once and read anywhere(32 bit, 64 bit etc)? Yes we don't really need to know whether JVM is 32 bit or 64 bit more often but there are many situations when this matters

Constructor overloading in java allows having more than one constructor inside one Class. in the last article we havediscussed method overloading and overriding and constructor, overloading is not much different than methodoverloading. Just like in the case of method overloading you have multiple methods with the same name but differentsignature, in Constructor overloading you have multiple constructors with a different signature with the only differencethat Constructor doesn't have a return type in Java. That constructor will be called as an overloaded constructor . Overloading is also another form of polymorphism in Java which allows having multiple constructors with a different name in one Class in java.

Difference between serializable and externalizable is popular java interview question which we have touched on my earlier post on Serialization: Top 10 java serialization interview questions. knowing differences between externalizable and serializable is not just important from interview point of view but also getting control of serialization processand optimizing performance of serialization. both serializable and extenalizable used to serialize or persist java objects but the way they do is little different. In case of Serializable Java Virtual machine has full control for serializing object while in case of Externalizable, application gets control for persisting objects. writeExternal() and readExternal() method provides complete control on format and content of Serialization process to application which can be leverage to increase performance and speed of serialization process.

URL-rewriting vs URL-encoding in Servlet JSP

Main difference between URL-rewriting and URL-encoding is that URL-rewriting is a technique to maintain user session if cookies are not enabled on client browser or browser doesn't support cookie while URL-encoding is a way to pass string to server containing special characters by converting special characters like space into some other characters like + . people often confuse between URL encoding and URL rewriting because of there names which sounds quite similar for new guys but functionality wise they are totally different to each other, Also servlet encodeURL() method adds more confusion because its sounds like its used for URL Encoding but indeed used for URL Rewriting. This is also a very popular servlet and JSP interview questions , I have also shared some more questions on my posts 10 Servlet Interview questions answers and 10 JSP interview questions and answers for Java programmer.

Getting free memory, total memory and max memory on JVM is using Runtime class in Java. and many java programmer is interested to know whether they have any relationship with JVM argument -Xms and -Xmx which is used to specify starting heap size and maximum heap size of JVM. I have touched this on 10 Points on Java heap and how to set heap size in ANT and Maven but here we will see some way to find out starting and maximum heap size from Java program.

Where and when to useAssertion in Java is probably the most important thing you want to know about Assertions. In last couple of articles we have seen What is Assertion in Javaand How to enable or disable Assertion in Java while in this article we will discuss most important part “Where to use Java Assertions” as I have always said Java Assertion should be taken as replacement of JUnit testing or Exception in Java Instead Assertion compliments both Unit testing and Exception and if used property provides you another testing tool which may test application with more real data than JUnit tests.

The good thing about Assertion in Java is that you can enable or disable Assertion at runtime. The designer of java are really very thoughtful, they have thought of many situations while designing java and its API. one of the gems is the ability to enable or disable assertion in runtime without any change on code. In last article we see how Assertion works in Java and now we will see some step by step guide on how to disable or enable Assertion in Java By default assertions in Java are disabled at runtime and JVM provides following options to deal with assertion in Java :

JDBC Performance tips are collection of some tried and tested way of coding and applying process which improves performance of JDBC code. Performance of core Java application or J2EE web application is very important, especially if its using database in back end which tend to slow down performance drastically. do you experience your java j2ee web application to be very slow (taking few seconds to process simple requests which involves database access, paging, sorting etc) than below tips may improve performance of your Java application. these tips are simple in nature and can be applied to other programming language application which uses database as back-end. If you are interested learning how to use JDBC in right way I suggest you to take a look at Practical database programming with Java book by Ying Bai. It's one of the rare book in JDBC which not only explains how to use different JDBC classes but also the right way of using it. You can also find lots of JDBC performance tips there.

Quite often we need to sort array in Java luckily java.util.Arrays class provide several utility method to sort java array of any type e.g. primitive, object or int, String etc. Arrays is in java.util package and exposed all sorting related method as static utility functions. you can access sort() as Arrays.sort() and just pass your array and it will sort that array object. You can sort array in ascending order, descending order or any custom order defined by custom comparator in Java. In last article we have seen how to Sort ArrayList in Java and in this java article we will see examples of sorting array in ascending order, descending order and sorting sub arrays in java.

Sort Array in Java on ascending and descending order

Sorting Java Array into Ascending Order:

In order to sort an array (String, int or any type) in ascending order we don't need to to anything special. Arrays.sort() method by default sort elements in there natural order implemented by CompareTo method. String array in Java will be sorted lexicographically. integer will be sorted numerically ascending order. look on code section for complete example of how to sort java array into ascending order. You can also sort anonymous array in Java by this method but since you don’t have any name to refer that it doesn’t make much sense.

Sorting Java Array into Descending Order:

In order to sort a java array into descendingorder you need to provide an external Comparator in Java which can sort elements in there reverse order and luckily we have that built int as java.util.Collections.reverseOrder(), which returns a reverse order comparator which gives reverse of natural ordering of element objects. pass this reverse comparator to sort method and it will sort array into descending order as shown in code example on last section. There is another way in which you can convert Array into ArrayList and than sort the arraylist but that’s again a two step process so its better to sort array using Arrays.sort() method

Sorting Sub Array in Java

Arrays class also provide methods to sort part of java array or sub array. So in case if you have big array and you only need to sort a particular section than just provide start index and end index to java.util.Arrays.sort(array,index,index) and it will sort the array only for that range. this is much faster than sorting whole array and than getting a range of values out of it. here is code example of sorting part of array in Java:

Code Example of Sorting Array in Java

In this section of code example we will see how to sort Java array into ascending order, descending order and sorting sub arrays in Java:

import java.util.Arrays;

import java.util.Collections;

publicclass HashtableDemo {

publicstaticvoid main(String args[]) {

String[] companies = { "Google", "Apple", "Sony" };

// sorting java array in ascending order

System.out.println("Sorting String Array in Ascending order in Java Example");

System.out.println("Unsorted String Array in Java: ");

printNumbers(companies);

Arrays.sort(companies);

System.out.println("Sorted String Array in ascending order : ");

printNumbers(companies);

// sorting java array in descending order

System.out.println("Sorting Array in Descending order in Java Example");

System.out.println("Unsorted int Array in Java: ");

printNumbers(companies);

Arrays.sort(companies, Collections.reverseOrder());

System.out.println("Sorted int Array in descending order : ");

printNumbers(companies);

System.out.println("Sorting part of array in java:");

int[] numbers = { 1, 3, 2, 5, 4 };

Arrays.sort(numbers, 0, 3);

System.out.println("Sorted sub array in Java: ");

for (int num : numbers) {

System.out.println(num);

}

}

publicstaticvoid printNumbers(String[] companies) {

for (String company : companies) {

System.out.println(company);

}

}

}

Output:

Sorting String Array in Ascending order in Java Example

Unsorted String Array in Java:

Google

Apple

Sony

Sorted String Array in ascending order :

Apple

Google

Sony

Sorting Array in Descending order in Java Example

Unsorted int Array in Java:

Apple

Google

Sony

Sorted String Array in descending order :

Sony

Google

Apple

Sorting part of array in java:

Sorted sub array in Java:

1

2

3

5

4

Important points about Sort method of Arrays:

Here are some important and worth noting point about sort method of Arrays class for quick references:

1. Arrays.sort() is an overloaded method and can sort int, byte, short, char or object[] arrays.

2. Arrays.sort)( also allows you to sort a sub-array or part of array in Java.

That’s all on how to sort java array on ascending and descending order and part of array in Java. You can also use the workaround by converting array into arraylist and than sorting but I think Arrays.sort() is preferred method for sorting arrays in Java.

Java Assertion or assert keyword in java is little unknown and not many programmer is familiar with this and it's been rarely used specially if you have not writing unit test using JUnit which extensively uses Java assertion to compare test result. Junit itself is the biggest manifestation of what assertion in Java can do and believe me by using assertion along with Exception you can write robust code. Assertion not only improve stability of code but also help you to become better programmer by forcing you to think about different scenario while writing production quality code and improving your think through ability.

In last article we saw how to check hidden files in Java and now we will see how to hide file in Java or make hidden file in Java. As we said File API in Java doesn’t provide any method to make a file hidden in Java but still you can apply some quick tricks to hide files from Java program. Like in Unix environment any file whose names begin with dot (.) is hidden so you can name your file starting with dot (.) and your File will be hidden in Linux or Unix Environment. On Windows you need to directly execute DOS command as stated in how to execute shell commands from Java by using Runtime.getRuntime.exec(“command”) to make the file hidden in Windows. Here is an example of making file hidden in Windowsusing Java Program.

This article is quick tip to find hidden files in Java by checking hidden properties of a File or directory from Java Program. File Handling is a crucial topic in java already we have discussed about how to create file in java , how to create directory, how to read write in a text file in Java , how to set permissions on file and some more aspect and we will discuss one more property of file, i.e. hidden property. Now the question arise can we make a file Hidden using our java code or not. So the answer would be No-using java File API it’s not possible to make any file hidden because it’s a OS or platform dependent property.

·If we are working in UNIX environment then file is considered as Hidden if its name begins with “.”

·And if we are dealing with Windows environment then a file is hidden if we set file hidden property, and also it’s should not be a directory.

Getting current data and timestamps in java is requirement for most of java enterprise application. Formatting date in java or parsing date in Java is such a common functionalitythat you will need it now and than. Though most of programmer look Google for finding current date and timestamps code in Java, its worthto having an idea how you can do that by using java.util.Date class. some time you might need formatted data string say "yyyy-MM--dd:HH:mm:ss". That is also possible by using dateformat in Java. I have touched base on string to date conversion and now in this article we willsee that in detail in terms of current date, time-stamp and timezone values. if you are working in global core java application which runson different timezones you must need to include timezone in your date and timestamp to avoid any confusion.

Difference between include directive and include actionis one of the most popular JSP interview questions and also asked as What is difference between page include and file include in JSP. Similar to difference between forward and send redirect and URL encoding vs URL rewriting, this is also asked at beginners level. Here we will see page include vs file include in detail. Both include directive and includeaction is used to include output of a static page e.g. HTML or a dynamic page e.g. jspinside another jsp file. In this JSP tutorial we will see what is include directive in JSP and what is include action and difference between include directive and include action. ThisJSP interview questionis mostly asked during 2-4 years experience in Java J2EE.

this keyword in Java is a special keyword which can be used to represent current object or instance of any class in Java. “this” keyword can also call constructor of same class in Java and used to call overloaded constructor. In this Java tutorial we will see how to use this keyword in Java and

different examples of this in Java. this sometime also associate with super keyword which is used to denote instance of super class in Java and can be used to call overloaded constructor in Java.

Sorting ArrayList in Java is a common task for Java developer and we have touched it while discussing in my last article 10 Examples of ArrayList in Java and again when we discussed comparator and comparable in Java. In order to sortan ArrayList, we need to use Collections utility class which contains overloaded sort() method for sorting different collections and supports different comparator in Java. In this article, we will see how to sort ArrayList in the natural order of element and then sorting ArrayList in Java with a comparator. The java.util.Collections class provide a reverse Comparator which can be used to sort the array in decreasing order. You can obtain this Comparator by calling the Collections.reverseOrder() method.

thread-safety or thread-safe code in Java refers to code which can safely be used or shared in concurrent ormulti-threading environment and they will behave as expected. any code, class or object which can behave differently from its contract on concurrent environment is not thread-safe. thread-safety is one of the riskintroduced by using threads in Java and I have seen java programmers and developers struggling to write thread-safe code or just understanding what is thread-safe code and what is not? This will not be very detailed article on thread-safety or low level details of synchronization in Javainstead we will keep it simple and focus on one example of non thread-safe code and try to understand what is thread-safety and how to make an code thread-safe.