Here is complete code example of reading InputStream as byte array in Java. This Java program has two methods, one uses Apache commons IOUtils library to convert InputStream as byte array, while other uses core Java class methods. If you look at Apache commons code, it's just a one liner and it's tested for various kind of input e.g. text file, binary file, images, and both large and small files.
By writing your own method for common utilities, which is good in sense of ownership; It's difficult to get same kind of...
Monday, 22 April 2013
Friday, 19 April 2013
Keyboard Shortcuts (Microsoft Windows)
1. CTRL+C (Copy)2. CTRL+X (Cut)... 3. CTRL+V (Paste)4. CTRL+Z (Undo)5. DELETE (Delete)6. SHIFT+DELETE (Delete the selected item permanently without placing the item in the Recycle Bin)7. CTRL while dragging an item (Copy the selected item)8. CTRL+SHIFT while dragging an item (Create a shortcut to the selected item)9. F2 key (Rename the selected item)10. CTRL+RIGHT ARROW (Move the insertion point to the beginning of the next word)11. CTRL+LEFT ARROW (Move the insertion point to the beginning of the previous word)12. CTRL+DOWN...
Tuesday, 16 April 2013
Converting a Date object to a calendar object
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();...
Compare Two Date In Java
public static void main( String[] args )
{
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2009-12-31");
Date date2 = sdf.parse("2010-01-31");
System.out.println(sdf.format(date1));
System.out.println(sdf.format(date2));
if(date1.compareTo(date2)>0){
System.out.println("Date1 is after Date2");
}else if(date1.compareTo(date2)<0){
System.out.println("Date1 is before Date2");
}else...
String to Date Conversion in Java
//String to Date Conversion
stringDate = "10-04-2013";
public Date stringToDate(String stringDate)
{
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
date = sdf.parse(stringDate);
System.out.println(date);
return date;
} catch (ParseException e) {
e.printStackTrace();
return date;
}
}...
Timestamp to Date Conversion In Java
Use This Import.
import java.sql.Timestamp;
//Timestamp to Date Conversion
public Date timeStampToDate(Timestamp timestamp)
{
Date date = null;
try
{
date = new Date(timestamp.getTime());
return date;
}catch (Exception e) {
e.printStackTrace();
return date;
}
}...
Abstract Class and Interface Interview Questions Answers in Java
1) Can abstract class have constructors in Java?
Yes, abstract class can declare and define constructor in Java. Since you can not create instance of abstract class, constructor can only be called during constructor chaining, i.e. when you create instance of concrete implementation class. Now some interviewer, ask what is the purpose of constructor, if you can not instantiate abstract class? Well, it can still be used to initialize common variables, which are declared inside abstract class, and used by various implementation....
if condition in display tag?
Use JSTL for if condition in display tag.
Include this library in your jsp page:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<display:column sortable="true" title="Grand Total">
<c:if test="${data.zone != 'GRAND TOTAL'}">
<html:link action="/exceptionScoreCardGrandReport.do?zone=${data.zone}">
...
Monday, 15 April 2013
Convert JSON String to Java object using Jackson
This method takes an Jon String which represent a User object in JSON format and convert it into Java User object. In this Java example I have create User as nested static class for convenience, You may create a separate top level class if needed.
import java.io.IOException;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
/*
* Java program to convert JSON String into Java object using Jackson...
Wednesday, 10 April 2013
Enum to String to Enum in Java
Enum to String
public class EnumTest {
private enum LOAN {
HOME_LOAN {
@Override
public String toString() {
return "Always look for cheaper Home loan";
}
},
AUTO_LOAN {
@Override
public String toString() {
return "Cheaper Auto Loan is better";
}
},
PEROSNAL_LOAN{
@Override
public String toString() {
return "Personal loan is not cheaper...
Compare two String in Java
Here are four examples of comparing String in Java
1) String comparison using equals method
2) String comparison using equalsIgnoreCase method
2) String comparison using compareTo method
4) String comparison using compareToIgnoreCase method
public class StringComparisonExample {
public static void main(String args[]) {
String tv = "Bravia";
String television = "Bravia";
// String compare example using equals
if (tv.equals(television)) {
System.out.println("Both tv and...
Compare Two Enum in Java - Equals, == ,CompareTo
you can use both == and equals() method to compare Enum, they will produce same result because equals() method of Java.lang.Enum internally uses == to compare enum in Java.
Every Enum in Java implicitly extends java.lang.Enum ,and since equals() method is declared final, there is no chance of overriding equals method in user defined enum. If you are not just checking whether two enum are equal or not, and rather interested in order of different instance of Enum, than you can use compareTo() method of enum to compare two...
Convert Secons in to mm:ss formatted time
/**
* Converting Second In to MM:SS time
* @param seconds
* @author harit Kumar
* @return time MM:SS
*/
public String secToTime(int seconds)
{
String time= "";
if(seconds > 59)
{
int minutes = seconds/60;
int sec = seconds%60;
time = minutes+":"+sec;
}
else
{
time = "00:"+seconds;
}
return time;
}...
Monday, 8 April 2013
How to get current stack trace in Java for a Thread
what is stack trace in Java
Thread executes code in Java, they call methods, and when they call, they keep them in there stack memory. You can print that stack trace to find out, from where a particular method is get called in execution flow.
One of the easiest way of printing stack trace of current thread in Java is by using dumpStack() method from java.lang.Thread class. This method prints stack trace of thread on which it get's called. You can use Thread.currentThread() method to get reference of current...
Sunday, 7 April 2013
Increment & Decrements Date In Java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @author Harit
* */
public class IncrementDecrementDate
{
public static void main(String args[])
{
//Using Calendar to increment and decrement days from date in Java
Date today = new Date();
System.out.println("Today is " + toddMMyy(today));
Calendar cal = Calendar.getInstance();
//adding one day to current date
cal.add(Calendar.DAY_OF_MONTH, 1);
Date tommrrow = cal.getTime();
System.out.println("Tomorrow...
Thursday, 4 April 2013
JSON to Object Mapping using Jackson
JSON:
{
"recentVideosList":[{"tags":null,"followerId":null,"videoId":"hLta6iJGtH8=","videoViewCount":"0","title":"twitter2","videoURL":"https://s3.amazonaws.com/youbusk/63/1364047039_011760.mov","userFollowingThisVideo":"No","videosByThisUser":"5","videoTimer":"6","videoUploadDateTime":"2013-03-25 07:41:49.0","isAlreadyFlagged":"N","uploadedByCountryId":"96","uploadedByUserId":"xHj2V0LLsfE=","thumbnailURL":"https://s3.amazonaws.com/youbusk/63/1364047039_011760.png","aboutUploadedBy":"ddddddddretreyreyrtyrt","tips":"0","uploadedBy":"naveen140990","abuseCount":"0","videoShareCount":"0","isAlreadyLiked":"NO"}],
"challengeOfTheDayList":[{"notificationId":"1","notificationDescription":"This...
Tuesday, 2 April 2013
Why String is immutable or final in Java
1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.
2)String has been widely used as parameter for many Java...
Immutable Class and Object in Java
Immutable objects are those, whose state can not be changed once created.
Immutable object offers several benefits in multi-threaded programming and it’s a great choice to achieve thread safety in Java code.
For e.g. java.lang.String, once created can not be modified e.g. trim, uppercase, lowercase. All modification in String result in new object,
Here are few rules, which helps to make a class immutable in Java :
1. State of immutable object can not be modified after construction, any modification...
System.out.println()
Here is what the different pieces of System.out.println() actually look like:
//the System class belongs to java.lang package
class System {
public static final PrintStream out;
//...
}
//the Prinstream class belongs to java.io package
class PrintStream{
public void println();
//...
}...
How to convert Char to String in Java with Example
1: Character.toString
Character class provides a convenient toString() method which takes a character and return its String equivalent. toString() is static method in Character class and can be accessed using class name like Character.toString(). here is an example of converting char to String using Character.toString():
char ch = 'U';
String charToString = Character.toString(ch);
2: String concatenation operator
In Java + can be used to concatenate String but it can also concatenate an String and a character and can...
String vs StringBuffer vs StringBuilder in Java
Some fundamental properties of String Class in Java
String is immutable in Java.Immutability offers lot of benefit to the String class e.g. his hashcode value can be cached which makes it a faster hashmap key and one of the reason why String is a popular key in HashMap. Because String is final it can be safely shared between multiple threads without any extra synchronization.
when we represent string in double quotes like "abcd" they are referred as String literal and String literals are created in...
How Synchronization works in Java ?
Synchronization
Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of java object or synchronization of java class becomes extremely important. Synchronization in Java is possible by using java keyword "synchronized" and "volatile”. Concurrent access of shared objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these...
Why wait, notify and notifyAll is defined in Object Class and not on Thread
1) Wait and notify is not just normal methods or synchronization utility, more than that they are communication mechanism between two threads in Java. And Object class is correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized. Remember synchronized and wait notify are two different area and don’t confuse that they are same or related. Synchronized is to provide mutual exclusion and ensuring thread safety of Java class like race condition while wait and...
Difference between Wait and Sleep in Java
Main difference between wait and sleep is that wait() method release the acquired lock when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting.
wait method in java should be called from synchronized method or block while there is no such requirement for sleep() method.
Thread.sleep() method is a static method and applies on current thread, while wait() is an instance specific method and only got wake up if some other thread calls notify method on same object.
in...
Monday, 1 April 2013
Is Java 100% object oriented?
No, because it has data types that are not objects (such as int and byte).
it does not support multiple inheritance directly.But it does so by using the concept of interfaces.
Many More......
static block in Java
which holds piece of code to executed when class is loaded in Java. This is also known as static initialize block as shown in below example.
static {
String category = "electronic trading system";
System.out.println("example of static block in java");
}
Beware that if your static initialize block throws Exception than you may get java.lang.NoClassDefFoundError when you try to access the class which failed to load.&nbs...
How to access non static variable inside static method or block
You access non static variable inside static method or block by creating an instance of class
and using that instance to reference instance variable.
public class Test {
private int count=0;
public static void main(String args[]) throws IOException {
StaticTest test = new StaticTest(); //accessing static variable by creating an instance of class
test.count++;
}
}
...
Why non-static variable cannot be referenced from a static context?
Lets See This Example.
public class Test {
private int count=0;
public static void main(String args[]) throws IOException {
count++; //compiler error: non-static variable count cannot be referenced from a static context
}
}
Static variable in Java belongs to Class and its value remains same for all instance. static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either...