Wednesday, June 22, 2011

install flex_sdk_4.1 on windows 7

Well this is no big deal. You only have to insert the bin folder path to the path environment variable

On my computer the path is

D:\Program Files (x86)\flex_sdk_4.1\bin

Usually on windows you append this to the path variable.

intersection of two int arrays - java

public class Test {

 public static void main(String[] args) {
  printAll(intersection(new int[]{-5} ,new int[]{6,55,66,-4,-5} ) );
 }

 static int [] intersection(int array1[] , int array2[]){

  java.util.ArrayList<Integer> arrayList = new java.util.ArrayList<Integer>();

  for(int outer=0; outer< array1.length ; outer++){

   for(int inner=0; inner < array2.length ; inner++){

    if(array1[outer] == array2[inner]){
     arrayList.add(array1[outer]);
     // or arrayList.add(array2[outer]); will do
    } 
   }
  }

  int intersectionArray[] = new int[arrayList.size()];

  // now add all the elements in arrayList to intersectionArray[] 

  for(int i = 0 ; i  < arrayList.size() ; i++){
   intersectionArray[i] = arrayList.get(i); 
  }

  return intersectionArray;

 }

 static void printAll(int array[]){

  for(int i =0 ; i < array.length ; i++){
   System.out.println(array[i]);
  }
 }

}

indexOf character in word - return all indices of occurance - java

static int [] indexOfArray(char character, String word){

  java.util.ArrayList<Integer> arrayList = new java.util.ArrayList<Integergt;();

// loop through word to find the occurrence of character

  for(int i = 0 ; i < word.length() ; i++){
   if( word.charAt(i) == character){
    arrayList.add(i); // if character found add i to arrayList
   }
  } 

  int [] array = new int[arrayList.size()];

  int i =0;

// add all elements in arrayList to int array

  for(int x : arrayList){
   array[i] = arrayList.get(i);
   i++;
  }

  return array; 
 }

 static void printAll(int array[]){

  for(int i =0; i < array.length ; i++){
   System.out.println(array[i]);
  }

 }

Unable to locate tools.jar. Expected to find it in ..\Java\jre6\lib\tools.jar and installing Ant


How to resolve this error in windows

So this is a very common error. Almost everyone would stumble upon this one in a while. I myself got myself tangled in this error even though i closely followed the installation instructions (I installed ant in the way i mentioned below in this post) . Anyhow without further ado i am going to reveal the solution to solve this problem . The solution is a very simple one. You have to add the JAVA_HOME variable to the windows environment.

JAVA_HOME = C:\Program Files (x86)\Java\jdk1.6.0_23

If you get the error in linux this is how you resolve it


add the following to your .bashrc file
export JAVA_HOME=/somedirectory/jdk1.5.0_08/
And reload the .bashrc file

And after adding the windows environment variables, and began to run without much hesitation.
Well for those of you who wanna know how to install ant can read the clearly listed instructions
below. Should you happen to come across any difficulties, please don't hesitate to drop
a comment in the comments section below. I will be more than willing to help you with resolving
your issue.

Installing ant on windows

Step 1:- Goto http://ant.apache.org and download ant-current-bin.zip file.

Step 2:- Extract the zip file

Step 3:- Set environment variables. Path = location of bin folder (Eg:- D:\Program Files (x86)\apache-ant-1.8.2\bin) ANT_HOME = Location of ant home folder (Eg:- D:\Program Files (x86)\apache-ant-1.8.2) ANT_OPTS=-Xmx256M 

Notice i installed ant in drive D instead of C. You might want to install in drive C or in a entirely different drive. Its upto you guys to decide where you wanna install. Personally I prefer not to install my programs on drive C.

Installing ant on linux


Well how to you actually install ant on linux? I took the easy way out by telling apt-get to do all the hardwork
apt-get install ant
Well certainly apt-get saved my day :). Well but there is still a small configuration part left to do Add the following statements into your .bashrc file 

export ANT_OPTS="-Xmx256M"
export ANT_HOME=/usr/bin/ant
export PATH=$PATH:/usr/bin/ant/bin



Monday, June 20, 2011

isNumber check for String in java

static boolean isNumber(String number){

  if(number.charAt(0)=='-'){

   for(int i = 1 ; i < number.length() ; i++){
    if( Character.isDigit(number.charAt(i))){

    }
    else{
     return false;
    }
   }
  }
  else{

   for(int i = 0 ; i < number.length() ; i++){
    if( Character.isDigit(number.charAt(i))){

    }
    else{
     return false;
    }
   }

  }

  return true;
 }

Well the above code can be simplified alot with the use of ternary operator
 static boolean isNumber(String number){

  for(int i = number.charAt(0)=='-' ? 1: 0 ; i < number.length() ; i++){
    if( Character.isDigit(number.charAt(i))){
    }
    else{
     return false;
    }
   }
  return true;
  
 }

Tuesday, June 14, 2011

Validate a email address in java

public static void main(String[] args) {

  System.out.println(vaidateEmailAddress("exa.mple@gmail.com") );
  System.out.println(vaidateEmailAddress("exa..mple@gmail.com") );

 }


 static boolean vaidateEmailAddress(String email){

  boolean valid = false;

  String domain[] = {"gmail.com" , "yahoo.com", "hotmail.com" };
  String localPart = email.substring(0, email.indexOf('@', 0));
  String domainPart = email.substring( localPart.length() + 1, email.length());

  int noOfAts = 0;

  for(int i = 0 ; i < email.length(); i++){

   if(  email.indexOf('@', i) != -1){
    noOfAts++;
    i = email.indexOf('@', i);
   }
  }

  if(noOfAts > 1 || noOfAts == 0) {
   // if more than one @ symbol appears no point in further checking. Its a invalid email address
   return false;
  }
  else{
   // now that it has been found that there is only one @ symbol lets check the domain 

   for( int i = 0 ; i < domain.length ; i++){
    if( domainPart.equals(domain[i])){
     valid = true;
     // still further processing of the string is needed. Thats why it doesn't return true
    }
   }
  }

  // checks for the presence of invalid characters in the local part

  if(localPart.charAt(0) == '.' || localPart.charAt(localPart.length() -1) == '.'){
   return false;
  }
  else{

   for(int i =0 ; i < email.indexOf('@', 0); i++){

    if(validCharacter(email.charAt(i)) ){
    }
    else if(email.charAt(i)== '.' && email.charAt(i+1)== '.'){
     return false;
    }
    else if(email.charAt(i)=='.'){
    }
    else{
     return false;
    }
   }
  }
  return valid;
 }


 static boolean validCharacter(char c){

  char validSymbols[] = {'!', '#' ,'$' ,'%' ,'&' ,'\'' ,'*' ,'+', '-', '/', '=' ,'?', '^','_','`' ,'{' ,'|' ,'}', '~'}; 

  for(int i =0 ; i < validSymbols.length; i++){
   
   if(validSymbols[i] == c ){
   }
   else{
    if(Character.isLetter(c)){
    }
    else if(Character.isDigit(c)){ 
    }
    else{
     return false;
    }
   }
  }
  return true;
 }
}

Runtime Exceptions Examples - Java

1.) Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6

int array[] = {4,5,22,33};
int a = array[6];


2.) Exception in thread "main" java.lang.NullPointerException

int array2[]  = null;
int b = array2[1];


3.) Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

String string  = "Hello World";
String subString = string.substring(-1, 5);


4.) Exception in thread "main" java.lang.ArithmeticException: / by zero

int a = 4;
int b = a/0;


5.) Exception in thread "main" java.util.EmptyStackException

Stack<integer> ese = new Stack<integer>();
ese.pop();


6.) NumberFormatException

int no=0;
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(inputStreamReader);
no =  Integer.parseInt(in.readLine() );


7.) java.lang.StackOverflowError

Call this method with a large long value

eg:- sof(7000);

static long sof(long n){
if(n==4) return 1;
else return n + (sof(n-1)) ;
}

Read text file into 2D array - Java

The text file is read line by line.

String array[x][y] ;

x - xth line in text file
y - yth word

So

array[x][y] - yth word in xth line

Here is the code

 static void readTo2DArray() throws IOException {

  FileInputStream fstream = new FileInputStream("test.txt");
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));

  String strLine;
  int arraySize = 6;
  String array[][] = new String[arraySize][];
  int index = 0;
  while ((strLine = br.readLine()) != null) {
   
   if (index >= arraySize - 1) {
    System.out.println("Error : Increase array size !");
    break;
   }
   array[index] = strLine.split(" ");
   index++;
   
  }

  printAll(array);

 }

 static void printAll(String array[][]) {

  for (int i = 0; i < array.length; i++) {

   if (array[i] != null) {
    for (int j = 0; j < array[i].length; j++) {
     System.out.print(array[i][j] + " ");
    }
    System.out.println(" ");
   }
  }

 }




Print All Digits In a int - java

Method 1:- Using % operator. Print from left to right

static void printAll(int number) {

  while (number > 10) {
   int digit = number % 10;
   number = (number - digit) / 10;
   System.out.print(digit + " ");
  }
  System.out.print(number);
 }


Method 2:- Convert int to a String and then printing individual characters.

static void printAll(int number) {

  String numberString = Integer.toString(number);

  for(int i = numberString.length()-1 ; i >=0 ; i--){
   System.out.print(numberString.charAt(i) + " ");
  }

 }


You can make it print the digits print in the reverse direction by changing the parameters of the for loop.

Reverse a int in java

Method 1 - Without using any other data structure. Making extensive use of % operator. I love this method and you will love it too.

static int rev(int number) {

  int rev = 0;

  while (true) {
   int digit = number % 10;
   number = (number - digit) / 10;
   rev += digit;

   if (number < 10) {
    rev *= 10;
    rev += number;
    break;
   } else {
    rev *= 10;

   }
  }

  return rev;
 }
Method 2 - Using StringBuffer and String
static int rev2(int number){

  int rev2 = 0;
  String numString = Integer.toString(number);
  String rev2String = "";
  StringBuffer stringBuffer = new StringBuffer();

  for(int i = numString.length() - 1 ; i >=0; i--){
   stringBuffer.append(numString.charAt(i));
  }

  rev2String = stringBuffer.toString();
  rev2 = Integer.parseInt(rev2String);  

  return rev2;
 }

Monday, June 13, 2011

Determine whether a decimal number is odd or even

Method 1:-

static void method1(int number){

  if(number % 10 == 1 || number % 10 == 3  || number % 10 == 5  || number % 10 == 7 || number % 10 == 9){
   System.out.println("ODD");
  }
  else{
   System.out.println("EVEN");
  }

 }


Method 2:-

static void method2(int number){

  if(number % 2 == 1){
   System.out.println("ODD"); 
  }
  else{
   System.out.println("EVEN");
  }
 }


Method 3:- Using integer class to convert int to binary and check whether least signifiant bit is a one or zero.

lsb = 1 => odd
lsb = 0 => even

static void method3(int number){

  if(Integer.lowestOneBit(number) == 1){
   System.out.println("ODD");
  }
  else{
   System.out.println("EVEN");
  }
 }

replace Vector element with new one

static void foo() {

  Vector<String[]> vector = new Vector<String[]>();

  String array1[] = { "word1", "word2", "word3" };
  String array2[] = { "word4", "word5", "word6" };
  String array3[] = { "word7", "word8", "word9" };

  vector.add(array1);
  vector.add(array2);

  printall(vector);
  
  vector.set(1, array3);
 
  printall(vector);

 }

 static void printall(Vector<String[]> vector) {

  System.out.println("\n");

  for (int i = 0; i < vector.size(); i++) {

   for (int j = 0; j < vector.get(i).length; j++) {
    System.out.println(vector.get(i)[j]);
   }

  }

 }
}


Modify a String element of a Vector String Array

static void foo(){
  
  Vector<String []> vector = new Vector<String []>();
  
  String array1[] = {"word1","word2","word3"};
  String array2[] = {"word4","word5","word6"};
  String array3[] = {"word7","word8","word9"};
  
  vector.add(array1);
  vector.add(array2);
  vector.add(array3);
  
  printall(vector);
   
  String newarray[] = vector.get(1);
  newarray[0]="newword";
  
  printall(vector);
  
 }
 
 static void printall(Vector<String []> vector){
 
        System.out.println("\n");
    
        for(int i =0; i < vector.size();i++){
    
            for(int j=0; j < vector.get(i).length ; j++){
            System.out.println(vector.get(i)[j]); 
            }
        
    }

remove line break and carriage return from string java

Using String replaceAll

String s1 = "hello\r world \nhello world";
System.out.println(s1);
String s2 = s1.replaceAll("[\n\r]", "");
System.out.println(s2);


Here the first argument is replaced with the second argument.

First argument = regular expression used to specify what you want to replace
Second argument = string


I will show you a manual method to replace newline and carriage return from a string

Method 1:- Using two for loops , substring , indexOf , ternary operator

String s1 = "hello\r world \nhello world";

  String s2 ="";

  for(int j =0 ; j < 2 ; j++){
   
   for(int i = 0 ; i < s1.length() ; i++){

    if(s1.indexOf( j==0 ? '\n' : '\r' , i) != -1){
     s2 += s1.substring(i, s1.indexOf(j==0 ? '\n' : '\r', i));
     i = s1.indexOf(j==0 ? '\n' : '\r', i);
    }
    else{
     s2+=s1.substring(i, s1.length());
     break;
    }
   }

   if(j==0){
    s1 = s2;
    s2="";
   }
  }
  System.out.println(s2);


Method 2:- Using StringBuffer. This is a much cleaner method
StringBuffer stringBuffer = new StringBuffer();
  
  String s1 = "hello\r world \nhello world";
  
  for(int i = 0 ; i < s1.length() ; i++){
   
   if(s1.charAt(i) != '\n' && s1.charAt(i) != '\r' ){
    stringBuffer.append(s1.charAt(i));
   }
  }
  
  System.out.println(stringBuffer.toString());

Sunday, June 12, 2011

Factorial in java

Method 1 Using a for loop

Well the simplest is to use a for loop to find the factorial of a number.

static long factorial(int factorial) {

  int fact = 1;

  for (int i = factorial; i > 0; i--) {
   fact *= i;
  }

  return fact;
 }


Method 2 : Using recursion

public static long factorial( int n )
    {
        if( n <= 1 )     // base case
            return 1;
        else
            return n * factorial( n - 1 );
    }

Friday, June 10, 2011

Pass a array by reference to a method in java

Well what happens if you do something like this

void method1(){
int array[] = {3,4,33,22};
method2(array);
}

void method2(int array[]){
// modify array contents
}

The modifications that you do inside method2 wont reflect once the method returns. So how you make the changes that happen inside method2 to reflect in method1 even after it returns ? Well the answer in C/C++ would be to pass by reference. But how do you do that in java? Here's the trick. You actually wrap the int array inside a object and pass the objectname.arrayname to the method.

class intarray{
int array[] = {3,4,33,22};
}


void method1(){
intarray object = new intarray();
method2(objectarray);
}

void method2(int array[]){
// modify array contents
}

So in this case whatever you do to the array from method2 once it returns the changes are seen in method1 as well.

Shuffle int array java - random swapping

import java.util.Random;
import java.util.Random;

class integer {
 // this class is created to pass the array as a reference
 int array[] = { 55, 44 };
}

public class shuffle {

 public static void main(String[] args) {

  integer object = new integer();

  shuffleByRandomSwapping(object.array, 2);
  printAll(object.array);
 }

 static void printAll(int array[]) {

  for (int i = 0; i < array.length; i++) {
   System.out.println(array[i]);
  }

 }

 static void shuffleByRandomSwapping(int array[], int amount) {

  Random generator = new Random();

  if (array.length == 1) {
   // no meaning of swapping
   return;
  } else

   for (int i = 0; i < amount; i++) {

    if (array.length == 2) {

     if (amount % 2 != 0) {
      // just a simple swap
      int temp = array[0];
      array[0] = array[1];
      array[1] = temp;
     } else {
      // no effective swapping takes place
      return;
     }
    } else {

     int index1 = generator.nextInt(array.length);
     int index2 = generator.nextInt(array.length);

     while (index1 == index2) {
      // if index1==index2 no swapping takes place
      index2 = generator.nextInt(array.length);
     }

     int temp = array[index1];
     array[index1] = array[index2];
     array[index2] = temp;

    }
   }
 }
}

Multiply two arrays using two threads

import java.util.Random;

public class Matrix implements Runnable {

 static int matrixSize = 5000;

 static long mult = 0;
 static int m1[];
 static int m2[];

 static void init() {

  m1 = new int[matrixSize];
  m2 = new int[matrixSize];

  Random randomGenerator = new Random();

  for (int i = 0; i < matrixSize; i++) {
   
   m1[i] = randomGenerator.nextInt(10);
   m2[i] = randomGenerator.nextInt(10);

  }

 }

 public static void main(String[] args) {
               
  init();
                // create two threads
  Thread th1 = new Thread(new Matrix()); 
  Thread th2 = new Thread(new Matrix());

                // sets names
  th1.setName("1");
  th2.setName("2");

                // start threads
  th1.start();
  th2.start();

  try {
                        // joins threads to main thread
   th1.join();
   th2.join();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }

  System.out.println("mult" + mult);
 }

 public void run() {

  if (Thread.currentThread().getName().equals("1")) {
   long localMult = 0;
   for (int i = 0; i < matrixSize / 2; i++) {
    localMult += m1[i] * m2[i];
   }
   sum(localMult);

  } else if (Thread.currentThread().getName().equals("2")) {
   long localMult = 0;
   for (int i = matrixSize / 2; i < matrixSize; i++) {
    localMult += m1[i] * m2[i];
   }
   sum(localMult);
  }
 }

 synchronized void sum(long amount) {
// this method is synchronized because this updates global variable
  System.out.println("Sum " + amount);
  mult += amount;
 }
}

For-Each Loop Java

import java.util.ArrayList;

public class ForEach {
 
 static void array(){
 
  double[] array = {9.5, 4.3, 3.8, 8.8};
  double sum = 0;
  
  for (double d : array) {  
   sum += d;
  } 
  
  System.out.println(sum);
  
 }
 
 static void arrayList(){
  
  ArrayList<Integer> arrayList = new ArrayList<Integer>();
  arrayList.add(1);
  arrayList.add(2);
  arrayList.add(3);
  arrayList.add(4);
  arrayList.add(5);
  
   for (int integer : arrayList)
        System.out.print(integer + " ");
 }
 
 public static void main(String args[]){
  
 array();
 arrayList();
  
 }
 
}

I will be updating this post to show how to use for-each loop with other datastructures.

Wednesday, June 8, 2011

How to read a properties file - java

The properties file

message = How are you

And the java code to read it

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class testmain {

    public static void main(String[] args) {
     
       Properties props = new Properties();
       
       try {

              props.load(new FileInputStream("message.properties"));

              String message = props.getProperty("message");

              System.out.println(message);

               }

              //catch exception in case properties file does not exist

              catch(IOException e)
              {
              e.printStackTrace();
              }          
    }
}

ant Unable to locate tools.jar. Expected to find it in /usr/lib/jvm/java-6-openjdk/lib/tools.jar

add the following to your .bashrc file

 export JAVA_HOME=/somedirectory/jdk1.5.0_08/

And reload the .bashrc file

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Well i was screwing around with the system and i found that i forgot to actually start mysql server. You start mysql server by running mysqld. And now you try running mysql. It works right.

libaio.so.1 shared object file not found

Installing software under linux is a nightmare sometimes. I installed mysql but when i tried to start it i got

libaio.so.1 shared object file not found

Error msg. Oops so now what to do. Well the obvious solution is to somehow install that file into your system. But how in the heck do you do it ?

Well try running this command

sudo aptitude install libaio-dev

And then run mysqld. Wow where did the error go ?