Welcome to my blog, hope you enjoy reading
RSS

Tuesday 26 February 2013

How To Use Reflection To Call Java Method At Runtime


How To Use Reflection To Call Java Method At Runtime


Reflection is a very useful approach to deal with the Java class at runtime, it can be use to load the Java class, call its methods or analysis the class at runtime.
In this example, you will load a class called “AppTest” and call each of its methods at runtime.

Share

What does Class.forname method do?


What does Class.forname method do?


A call to Class.forName("X") causes the class named X to be dynamically loaded (at runtime). A call to forName("X") causes the class named X to be initialized (i.e., JVM executes all its static block after class loading). Class.forName("X") returns the Class object associated with the "X" class. The returned Class object is not an instance of the "x" class itself.
Class.forName("X") loads the class if it not already loaded. The JVM keeps track of all the classes that have been previously loaded. This method uses the classloader of the class that invokes it. The "X" is the fully qualified name of the desired class.
Share

Friday 22 February 2013

Inserting or Updating records using mysql REPLACE INTO

Inserting or Updating records using mysql REPLACE INTO

Inserting records into a specific table can be achieved simply by using the INSERT statement while updating records can be done by issuing an UPDATE statement. But what if you are asked for a conditional insert/update? That is, given a specific data, you need to query against a specific table to check whether it was previously inserted. If it does exist, update that record and insert otherwise. Typically, you might solve this first by firing a SELECT statement to check for the record and eventually executing UPDATE or INSERT depending on the result gathered by the the previous query. This means you need 2 statements to achieve the desired result.
Better solution? The result of the two SQL commands above can be achieved using a single query – using REPLACE INTO. REPLACE statement works the same way as the INSERT query. The only difference is the way they handle duplicate records. If there exists a unique index on a table and you attempted to insert a record that has a key value that’s previously inserted, that record will be deleted first and will insert the new record.
REPLACE syntax is also similar to the INSERT statement.
REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name [(col_name,...)]
    {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
OR
REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name
    SET col_name={expr | DEFAULT}, ...
OR
REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name [(col_name,...)]
    SELECT ...
Below are some examples of REPLACE statements in different forms:
  • Single row REPLACE
    REPLACE INTO pet (id, type, name) VALUES(1, 'Dog', 'Pluto');
  • Multiple row REPLACE
    REPLACE INTO pet (id,name,age) VALUES(1, 'Dog', 'Pluto'), VALUES(2, 'Cat', 'Furry'), VALUES(3, 'Bird', 'Chloe');
  • Singe row REPLACE with SET
    REPLACE INTO pet SET id = 1, type= 'Dog',  name = 'Pluto'
Share

Thursday 21 February 2013

Find out duplicate number between 1 to N numbers


Find out duplicate number between 1 to N numbers

You have got a range of numbers between 1 to N, where one of the number is repeated. You need to write a program to find out the duplicate number.
package com.javanotes2all.java.others; import java.util.ArrayList; import java.util.List; public class DuplicateNumber { public int findDuplicateNumber(List numbers){ int highestNumber = numbers.size() - 1; int total = getSum(numbers); int duplicate = total - (highestNumber*(highestNumber+1)/2); return duplicate; } public int getSum(List numbers){ int sum = 0; for(int num:numbers){ sum += num; } return sum; } public static void main(String a[]){ List<Integer> numbers = new ArrayList<Integer>(); for(int i=1;i<30;i++){ numbers.add(i); } //add duplicate number into the list numbers.add(22); DuplicateNumber dn = new DuplicateNumber(); System.out.println("Duplicate Number: "+dn.findDuplicateNumber(numbers)); } }
Share

Wednesday 20 February 2013

How to attach multiple files to an email using JavaMail


How to attach multiple files to an email using JavaMail?

Sending files to an emill in the folder all files
package com.javanotes2all.java.mail;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendFilesInDirectory 
{
public static void main(String[] args) 
{
 SendFilesInDirectory send=new SendFilesInDirectory();
 send.sendAttachments();
}
public void sendAttachments()
{
   try
    {
                String host = "smtp.gmail.com";
  BufferedReader breader=new BufferedReader(new InputStreamReader(System.in));
  System.out.println("enter from email");
  String username=breader.readLine().trim();
  System.out.println("enter password");
  String password=breader.readLine().trim();
  System.out.println("enter to email");
  String to=breader.readLine().trim();
  System.out.println("enter attach file path");
  String filename=breader.readLine().trim();
  Properties props = System.getProperties();
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", host);
  props.put("mail.smtp.user", username);
  props.put("mail.smtp.password", password);
  props.put("mail.smtp.port", 587);
  props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props,  new GMailAuthenticator(username, password));

  Message msg=new MimeMessage(session);
  msg.setSubject("File Attached");
  msg.setFrom(new InternetAddress(username));
 msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
  BodyPart msgBP=new MimeBodyPart();
  msgBP.setText("Take a look at this\n");
  Multipart mPart=new MimeMultipart();
  mPart.addBodyPart(msgBP);
  addAttachments(mPart,filename,0);
  msg.setContent(mPart);
  Transport.send(msg);
  System.out.println("mail sent");
 }catch(Exception e)
 {
  System.out.println(e);
 }

}
public void addAttachments(Multipart mPart,String filepath,long size)
{
 try
 {
  File dir=new File(filepath);
  if(dir.isDirectory())
  {
   for (File file : dir.listFiles()) 
   {
    if (file.isFile()) 
     {
      BodyPart msgBP=new MimeBodyPart();
      DataSource src=new FileDataSource(file.getPath());
      msgBP.setDataHandler(new DataHandler(src));
      msgBP.setFileName(file.getName());
      mPart.addBodyPart(msgBP);
      size += file.length();
      }
        else
    addAttachments(mPart,file.getName(),size);
   }
  }else if(dir.isFile())
  {
   size += dir.length();
  }

  double sizeInMB =(double)size / 1024 / 1024;
  String s="MB";
  if(sizeInMB<1)
{ sizeInMB=(double)size / 1024; s="KB"; } System.out.println("file size"+sizeInMB+" "+s); }catch(Exception e) { System.out.println(e.getMessage()); } } class GMailAuthenticator extends Authenticator { String user; String pw; public GMailAuthenticator (String username, String password) { super(); this.user = username; this.pw = password; } public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pw); } } }
Share

Tuesday 19 February 2013

Find Size of folder or file in java


Find Size of folder or file in java


package com.javanotes2all.java.files; import java.io.File; public class FindSizeOfFile { public static void main(String[] args) { File file= new File("file/directoty"); long size =0; size=getSize(file); // Convert the size in bytes to mega bytes/Killo bytes. double sizeInMB =(double)size / 1024 / 1024; String s="MB"; if(sizeInMB<1) { sizeInMB=(double)size / 1024; s="KB"; } System.out.println(file.getName()+":"+sizeInMB+s); } public static long getSize(File dir) { long size = 0; if(dir.isDirectory()) { for (File file : dir.listFiles()) { if (file.isFile()) { size += file.length(); } else size += getSize(file); } }else if(dir.isFile()) { size += dir.length(); } return size; } }
Share

Monday 18 February 2013

Java Interview Programs





  1. Write a program to find maximum repeated words from a file.
  2. Write a program to find the size of file or folder.
  3. What does Class.forname method do?
  4. How To Use Reflection To Call Java Method At Runtime
  5. How to swap two numbers without using temp or third variable
  6. Why is Java not a pure OOP Language?
  7. What is Autoboxing and Unboxing?
  8. How many ways to create object in java?






Share

Write a program to find maximum repeated words from a file.


Write a program to find maximum repeated words from a file.



package com.javanotes2all.java.files; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.Map.Entry; public class WordsCountInFile { public Map<String, Integer> getWordCount(String fileName){ FileInputStream fis = null; DataInputStream dis = null; BufferedReader br = null; Map<String, Integer> wordMap = new HashMap<String, Integer>(); try { fis = new FileInputStream(fileName); dis = new DataInputStream(fis); br = new BufferedReader(new InputStreamReader(dis)); String line = null; while((line = br.readLine()) != null){ StringTokenizer st = new StringTokenizer(line, " "); while(st.hasMoreTokens()){ String tmp = st.nextToken().toLowerCase(); if(wordMap.containsKey(tmp)){ wordMap.put(tmp, wordMap.get(tmp)+1); } else { wordMap.put(tmp, 1); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try{if(br != null) br.close();}catch(Exception ex){} } return wordMap; } public List<Entry<String, Integer>> sortByValue(Map<String, Integer> wordMap){ Set<Entry<String, Integer>> set = wordMap.entrySet(); List<Entry<String, Integer>> list = new ArrayList<Entry<String,Integer>>(set); Collections.sort( list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String,Integer> o1,Map.Entry<String,Integer> o2 ) { return (o2.getValue()).compareTo( o1.getValue() ); }
} ); return list; } public static void main(String a[]){ WordsCountInFile mdc = new WordsCountInFile(); Map<String, Integer> wordMap = mdc.getWordCount("/home/prabhu/test.txt"); List<Entry<String, Integer>> list = mdc.sortByValue(wordMap); for(Map.Entry<String, Integer> entry:list){ System.out.println(entry.getKey()+" ==== "+entry.getValue()); } } }

OUTPUT:

java ==== 2
is ==== 1
for ==== 1
javanotes2all ==== 1
the ==== 1
notes ==== 1
blog ==== 1
developers ==== 1
all ==== 1
Share

Use SVN externals to Simplify Working with Multiple Projects

Use SVN externals to Simplify Working with Multiple Projects


The SVN externals feature is one of the most useful but underutilized feature of SVN.
Many projects require assets that already exist in other repositories, and handling linking to these assets often leads to messy and confusing project structures.
There are three approaches to include linked assets:

Share

Tuesday 12 February 2013

How can I check if the given URL of an image exists using GWT?

How can I check if the given URL of an image exists using GWT?

Image img = new Image("some_url/img.jpg");
img.addErrorHandler(new ErrorHandler() {                
    @Override
    public void onError(ErrorEvent event) {
        System.out.println("Error - image not loaded.");
    }
});
Share

MYSQL: Get the Auto-Increment Values after Insert Statement

MYSQL: Get the Auto-Increment Values after Insert Statement

In general, the PRIMARY KEY field is the AUTO_INCREMENT field. Now wen you insert a row, a new key is generated and you can’t get it through usual way as this row can be accessed only using the primary key.
So here is how it can be done:

Share

JDBC Interview questions


JDBC Interview questions


JDBC Interview Questions
Here you can find out a list of interview questions for JDBC. These questions are often asked by the interviewer for JDBC (Java Database Connectivity) interview. We put our maximum effort to make this answers error free. But still there might be some errors. If you feel out any answer given for any question is wrong, please, please inform us by clicking on report bug button provided below.
In this section we are offering interview questions for JDBC only. if you need interview questions for any other java related technologies , please check the relevant sections.
1. What is JDBC?
JDBC technology is an API (included in both J2SE and J2EE releases) that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files. With a JDBC technology-enabled driver, you can connect all corporate data even in a heterogeneous environment
Share

Saturday 9 February 2013

ReentrantLock Example

ReentrantLock Example

Java concurrency lib implementations provide additional functionality over the use of synchronized, they providing a non-blocking attempt to acquire a lock (tryLock()), an attempt to acquire the lock that can be interrupted (lockInterruptibly(), and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)).
 A Lock class is quite different from that of the implicit monitor lock, it can provide guaranteed ordering, reentrant usage and deadlock detection.
 An example of some ReentrantLocks using tryLock() :

package com.javanotes2all.java.multithread; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ReentrantLockingDemo { final Lock lock = new ReentrantLock(); public static void main(final String... args) { new ReentrantLockingDemo().go(); } private void go() { new Thread(newRunable(), "Thread1").start(); new Thread(newRunable(), "Thread2").start(); new Thread(newRunable(), "Thread3").start(); new Thread(newRunable(), "Thread4").start(); new Thread(newRunable(), "Thread5").start(); } private Runnable newRunable() { return new Runnable() { @Override public void run() { do { try { if (lock.tryLock(500, TimeUnit.MILLISECONDS)) { try { System.out.println("locked thread " + Thread.currentThread().getName()); Thread.sleep(1000); } finally { lock.unlock(); System.out.println("unlocked locked thread " + Thread.currentThread().getName()); } break; } else { System.out.println("unable to lock thread " + Thread.currentThread().getName() + " will re try again"); } } catch (InterruptedException e) { e.printStackTrace(); } } while (true); } }; } }
OUTPUT:

locked thread Thread1
unable to lock thread Thread3 will re try again
unable to lock thread Thread2 will re try again
unable to lock thread Thread4 will re try again
unable to lock thread Thread5 will re try again
unlocked locked thread Thread1
locked thread Thread3
unable to lock thread Thread2 will re try again
unable to lock thread Thread5 will re try again
unable to lock thread Thread4 will re try again
unable to lock thread Thread2 will re try again
unable to lock thread Thread4 will re try again
unable to lock thread Thread5 will re try again
unlocked locked thread Thread3
locked thread Thread2
unable to lock thread Thread4 will re try again
unable to lock thread Thread5 will re try again
unable to lock thread Thread4 will re try again
unable to lock thread Thread5 will re try again
unlocked locked thread Thread2
locked thread Thread4
unable to lock thread Thread5 will re try again
unable to lock thread Thread5 will re try again
unlocked locked thread Thread4
locked thread Thread5
unlocked locked thread Thread5

Share

Friday 8 February 2013

Calculating the Difference Between Two Java Date Instances


Calculating the Difference Between Two Java Date Instances


package com.javanotes2all.java.date; import java.text.SimpleDateFormat; import java.util.Date; public class DifferenceBetweenTodates { public static void main(String[] args) throws Exception { String date1 = "08/02/2013 00:00:00"; String date2 = "08/02/2013 00:00:01"; String format = "dd/MM/yyyy HH:mm:ss"; SimpleDateFormat sdf = new SimpleDateFormat(format); Date dateObj1 = sdf.parse(date1); Date dateObj2 = sdf.parse(date2); long diff = dateObj2.getTime() - dateObj1.getTime(); System.out.println(dateObj1+" "+dateObj2); int diffDays = (int) (diff/(24*60*60*1000)); System.out.println("difference between days "+diffDays); int diffhours = (int) (diff/(60*60*1000)); System.out.println("difference between hours "+diffhours); int diffmin = (int) (diff/(60*1000)); System.out.println("difference between minitues "+diffmin); int diffsec = (int) (diff/(1000)); System.out.println("difference between seconds "+diffsec); System.out.println("difference between miliseconds "+diff); } }
OUTPUT:


Fri Feb 08 00:00:00 IST 2013 Fri Feb 08 00:00:01 IST 2013
difference between days 0
difference between hours 0
difference between minitues 0
difference between seconds 1
difference between miliseconds 1000

Share

Java Timer and TimerTask Example


Java Timer and TimerTask Example 

In this tutorial we are going to see how you can use Timer and TimerTask classes of the java.util package in order to schedule the execution of a certain process.
The Timer class uses several flexible methods to make it possible to to schedule a task to be executed at a specific time, for once or for several times with intervals between executions.
To create your own schedulable processes, you have to create your own class the extends TimerTask class. TimerTask implements Runnable interface, so you have to override the run() method.
Let’s see the code :
Share

How to convert Character to String and a String to Character Array in Java


How to convert Character to String and a String to Character Array in Java

In this short tutorial we are going to see how to convert  a Character to a String and a String to a StringArray.
In the first Java program we convert a Character to String. Basically there are two ways to do that:
  • the Character.toString(char ) method of the Character class
  • the String.valueOf(char ) method of the String Class.
To be precise the  Character.toString(char ) method internally uses  String.valueOf(char ) method. So you are be better off withString.valueOf(char).
Share

Thursday 7 February 2013

How to get IP address in Java using InetAddress


How to get IP address in Java using InetAddress

An Internet Protocol address (IP address) is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. The designers of the Internet Protocol defined an IPv4 address as a 32-bit number.
In this tutorial we are going to see how can you get the IP Address that is assigned to your own machine inside your local network and the IP Addresses assigned to specific Domain Names(e.g. www.google.com…)
Share

Wednesday 6 February 2013

Comparable and Comparator Example to sort Objects


Comparable and Comparator Example to sort Objects

In Java, it’s very easy to sort an array or a list with primitive types. But you can also use Comperable and Comparator interfaces when you want to be able to short arrays or lists of your own custom objects.
Let’s begin with a very simple example using arrays of primitive types:
package com.javanotes2all.java.sorting;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ObjectSortingExample {
public static void main(String[] args) {
int[] integerArray = {1,0,3,2};
Arrays.sort(integerArray);
System.out.println(Arrays.toString(integerArray));
String[] stringArray = {"J", "A", "V", "A", "C"};
Arrays.sort(stringArray);
System.out.println(Arrays.toString(stringArray));
List<String> stringList = new ArrayList<String>();
stringList.add("J");
stringList.add("A");
stringList.add("V");
stringList.add("A");
stringList.add("C");
Collections.sort(stringList);
for(String elem: stringList)
System.out.print(" "+elem);
}
}

output:

[0, 1, 2, 3]
[A, A, C, J, V]
 A A C J V

Share

Tuesday 5 February 2013

Google Cloud Messaging for Android

Creating a Google API project

To create a Google API project:
  1. Open the Google APIs Console page.
  2. Create project:
  1. Click Create project. Your browser URL will change to something like: https://code.google.com/apis/console/#project:4815162342
   4. Take note of the value after #project: (4815162342 in this example). This is your project number, and it will be used later on as the GCM sender ID.
Share

Saturday 2 February 2013

Adding CAPTCHA to your GWT application


Adding CAPTCHA to your GWT application


What is CAPTCHA?
In a world full of malicious bots, what can you do to protect your precious web application? One of the basic things that you really should do is add CAPTCHA capabilities to it. If you are not familiar with the (rather bizarre sounding) term, CAPTCHA is a simplistic way to ensure that a user is actually a real person, and not a computer. This can be done by challenging the user and asking from him to provide a response to a “problem”. Because computers are unable to solve the CAPTCHA, any user entering a correct solution is presumed to be human. The most common way is to ask the user to type letters or digits from a distorted image that appears on the screen.

Share

How to Use String.Split mehod in java


How to Use String.Split mehod in java


In java split mothod is woking with the characters a-z and numbers 0-9 is good.
Using single character:
Example:

Share