Wednesday, November 26, 2014

Essential Java Concepts

http://www.javatpoint.com/java-oops-concepts
Rules for Constructor
rule for static
Usage of this()

Sunday, November 16, 2014

Sorting algos in java

Queue implementation in Java

Stack implementation in java

Multithreading in JAVA


States of thread





 What is a context switch :each thread is assigned a priority
a thread with higher priority dosent mewan it will run any faster.
Priority is used ro decide when to switch from one thread to another
This is called Context switch.


A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping,or blocking on pending I/O. In this scenario, all other threads are examined, and the highest-priority thread that is ready to run is given the CPU.

• A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted—no matter what it is doing— by a higher-priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking.


Regular expressions in java

http://www.vogella.com/tutorials/JavaRegularExpressions/article.html


Generic Java function to match RE

public static boolean testRE (String s){
    Pattern pattern = Pattern.compile("\\d{3}");
    Matcher matcher = pattern.matcher(s);
    if (matcher.find()){
      return true; 
    } 
    return false; 










[tT]rue - match true or true

[tT]rue|[yY]es - matches true,True,yes,Yes

*true.* - matches exactly true

[a-zA-Z]{3} - match 4 character word

^[^\\d] - true if String dosent match a digit at beggining

([\\w&&[^b]])* - true if string contains characters excluding b

"[^0-9]*[12]?[0-9]{1,2}[^0-9]*" - less than 300 (HOW????)

.*(jim|joe).* - Match either jim or Joe

A phone number in this example consists either out of 7 numbers in a row or out of 3 number, a (white)space or a dash and then 4 numbers. 

\\d\\d\\d([,\\s])?\\d\\d\\d\\d - 1233323322

[0-9]{2} (Check Correctness) -check if a text contains a number with 3 digits.
\\d{3} 

\b(\w+)\s+\1\b  - find duplicated words

 following regular expression allows you to find the "title" word, in case it starts in a new line, potentially with leading spaces.

(\n\s*)title 


Password compexity :


((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})


(   # Start of group
  (?=.*\d)  #   must contains one digit from 0-9
  (?=.*[a-z])  #   must contains one lowercase characters
  (?=.*[A-Z])  #   must contains one uppercase characters
  (?=.*[@#$%])  #   must contains one special symbols in the list "@#$%"
              .  #     match anything with previous condition checking
                {6,20} #        length at least 6 characters and maximum of 20 
)   # End of group



^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$

   #start of the line
  [_A-Za-z0-9-]+ #  must start with string in the bracket [ ], must contains one or more (+)
  (   #  start of group #1
    \\.[_A-Za-z0-9-]+ #     follow by a dot "." and string in the bracket [ ], must contains one or more (+)
  )*   #  end of group #1, this group is optional (*)
    @   #     must contains a "@" symbol
     [A-Za-z0-9]+       #        follow by string in the bracket [ ], must contains one or more (+)
      (   #    start of group #2 - first level TLD checking
       \\.[A-Za-z0-9]+  #      follow by a dot "." and string in the bracket [ ], must contains one or more (+)
      )*  #    end of group #2, this group is optional (*)
      (   #    start of group #3 - second level TLD checking
       \\.[A-Za-z]{2,}  #      follow by a dot "." and string in the bracket [ ], with minimum length of 2
      )   #    end of group #3
$   #end of the line


([^\s]+(\.(?i)(jpg|png|gif|bmp))$

Image file extension

(   #Start of the group #1
 [^\s]+   #  must contains one or more anything (except white space)
       (  #    start of the group #2
         \.  # follow by a dot "."
         (?i)  # ignore the case sensitive checking
             (  #   start of the group #3
              jpg #     contains characters "jpg"
              |  #     ..or
              png #     contains characters "png"
              |  #     ..or
              gif #     contains characters "gif"
              |  #     ..or
              bmp #     contains characters "bmp"
             )  #   end of the group #3
       )  #     end of the group #2 
  $   #  end of the string
)   #end of the group #



IP address
^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.
([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$


^  #start of the line
 (  #  start of group #1
   [01]?\\d\\d? #    Can be one or two digits. If three digits appear, it must start either 0 or 1
  #    e.g ([0-9], [0-9][0-9],[0-1][0-9][0-9])
    |  #    ...or
   2[0-4]\\d #    start with 2, follow by 0-4 and end with any digit (2[0-4][0-9]) 
    |           #    ...or
   25[0-5]      #    start with 2, follow by 5 and end with 0-5 (25[0-5]) 
 )  #  end of group #2
  \.            #  follow by a dot "."
....            # repeat with 3 time (3x)
$  #end of the line


12 hr TIME format 
(1[012]|[1-9]):[0-5][0-9](\\s)?(?i)(am|pm)


(    #start of group #1
 1[012]    #  start with 10, 11, 12
 |    #  or
 [1-9]    #  start with 1,2,...9
)    #end of group #1
 :    #    follow by a semi colon (:)
  [0-5][0-9]   #   follow by 0..5 and 0..9, which means 00 to 59
            (\\s)?  #        follow by a white space (optional)
                  (?i)  #          next checking is case insensitive
                      (am|pm) #            follow by am or pm


24hr time format

([01]?[0-9]|2[0-3]):[0-5][0-9]

(    #start of group #1
 [01]?[0-9]   #  start with 0-9,1-9,00-09,10-19
 |    #  or
 2[0-3]    #  start with 20-23
)    #end of group #1
 :    #  follow by a semi colon (:)
  [0-5][0-9]   #    follow by 0..5 and 0..9, which means 00 to 

dat format dd/mm/yyyy

(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)

   #start of group #1
 0?[1-9]  #  01-09 or 1-9
 |                   #  ..or
 [12][0-9]  #  10-19 or 20-29
 |   #  ..or
 3[01]   #  30, 31
)    #end of group #1
  /   #  follow by a "/"
   (   #    start of group #2
    0?[1-9]  # 01-09 or 1-9
    |   # ..or
    1[012]  # 10,11,12
    )   #    end of group #2
     /   # follow by a "/"
      (   #   start of group #3
       (19|20)\\d\\d #     19[0-9][0-9] or 20[0-9][0-9]
       )  #   end of group #3





html regular exprerssion

<("[^"]*"|'[^']*'|[^'">])*>

<    #start with opening tag "<"
 (  #   start of group #1
   "[^"]*" # only two double quotes are allow - "string"
   |  # ..or
   '[^']*' # only two single quotes are allow - 'string'
   |  # ..or
   [^'">] # cant contains one single quotes, double quotes and ">"
 )  #   end of group #1
 *  # 0 or more
>  #end with closing tag ">"
For advanced regular expressions the java.util.regex.Pattern and java.util.regex.Matcher classes are used. You first create a Pattern object which defines the regular expression. This Pattern object allows you to create a Matcher object for a given string. This Matcher object then allows you to do regex operations on a String.

Classes in Java

Singleton class refer :

http://howtodoinjava.com/2012/10/22/singleton-design-pattern-in-java/

File handling in Java





Important classes for file reading:

  FileReader;
  BufferedReader
  FileWriter
  BufferedWriter writer

File file = new File("foo/bar/test.txt");
File parent = file.getParentFile();

if(!parent.exists() && !parent.mkdirs()){
    throw new IllegalStateException("Couldn't create dir: " + parent);


Program from read write file :

Find string in a file
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class StringFinder {

public static void main(String[] args)
{
    double count = 0,countBuffer=0,countLine=0;
    String lineNumber = "";
    String filePath = "C:\\Users\\allen\\Desktop\\TestText.txt";
    BufferedReader br;
    String inputSearch = "are";
    String line = "";

    try {
        br = new BufferedReader(new FileReader(filePath));
        try {
            while((line = br.readLine()) != null)
            {
                countLine++;
                //System.out.println(line);
                String[] words = line.split(" ");

                for (String word : words) {
                  if (word.equals(inputSearch)) {
                    count++;
                    countBuffer++;
                  }
                }

                if(countBuffer > 0)
                {
                    countBuffer = 0;
                    lineNumber += countLine + ",";
                }

            }
            br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("Times found at--"+count);
    System.out.println("Word found at--"+lineNumber);
}
}
import java.io.*;
import java.util.*;

public class Assign6 {

    public static void main(String[] args)     throws FileNotFoundException {

       Scanner console = new Scanner(System.in);
   

       intro();

       

        System.out.print("\tEnter the first file name: ");

                String file1 = console.nextLine();



                System.out.print("\tEnter the second file name: ");

                String file2 = console.nextLine();

                System.out.println();

                System.out.println("Differences Found: \n");

                compareFiles(new Scanner(new File(file1)), (new Scanner(new File(file2))));

    }


Find difference between two files :

    public static void intro() {

        System.out.println("This program reads from two given input files and");

        System.out.println("prints information about the differences between them. \n");

    }

    public static void compareFiles (Scanner file1, Scanner file2) {

        String lineA ;

        String lineB ;

        int x = 1;

        while (file1.hasNextLine() && file2.hasNextLine()) {

            lineA = file1.nextLine();

           lineB = file2.nextLine();

            if (!lineA.equals(lineB)) {

                System.out.println("Line " + x++);

                System.out.println("< " + lineA);

                System.out.println("> " + lineB + "\n");

            }

        }

    }

}

Find matching lines in two files

public int findMatchingLines(java.lang.String file1Name, java.lang.String file2Name) throws java.io.IOException
 {
  Scanner scan1 = new Scanner(new File(file1Name));
  Scanner scan2 = new Scanner(new File(file2Name));
  int i = 1;
 
   while (scan1.hasNext() && scan2.hasNext())
   {
    if(scan1.nextLine().equals(scan2.nextLine()))
    {
    System.out.print(i + " ");
    System.err.println(scan1.nextLine());
    i++;
    }
   }

  return i;
 }
Find a line in file and remove it
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

String lineToRemove = "bbb";
String currentLine;

while((currentLine = reader.readLine()) != null) {
    // trim newline when comparing with lineToRemove
    String trimmedLine = currentLine.trim();
    if(trimmedLine.equals(lineToRemove)) continue;
    writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);

C Program to merge alternate lines
/*
 * C Program that Merges Lines Alternatively from 2 Files & Print Result
 */
#include
main()
{
    char file1[10], file2[10];

    puts("enter the name of file 1");      /*getting the names of file to be concatenated*/
    scanf("%s", file1);
    puts("enter the name of file 2");
    scanf("%s", file2);
    FILE *fptr1, *fptr2, *fptr3;
    fptr1=fopen(file1, "r");             /*opening the files in read only mode*/
    fptr2=fopen(file2, "r");
    fptr3=fopen("merge2.txt", "w+");   /*opening a new file in write,update mode*/
    char str1[200];
    char ch1, ch2;
    int n = 0, w = 0;
    while (((ch1=fgetc(fptr1)) != EOF) && ((ch2 = fgetc(fptr2)) != EOF))
    {
        if (ch1 != EOF)             /*getting lines in alternately from two files*/
        {
            ungetc(ch1, fptr1);
            fgets(str1, 199, fptr1);
            fputs(str1, fptr3);
            if (str1[0] != 'n')
                n++;      /*counting no. of lines*/
        }
        if (ch2 != EOF)
        {
            ungetc(ch2, fptr2);
            fgets(str1, 199, fptr2);
            fputs(str1, fptr3);
            if (str1[0] != 'n')
                n++;        /*counting no.of lines*/
        }
    }
    rewind(fptr3);
    while ((ch1 = fgetc(fptr3)) != EOF)       /*countig no.of words*/
    {
        ungetc(ch1, fptr3);
        fscanf(fptr3, "%s", str1);
        if (str1[0] != ' ' || str1[0] != 'n')
            w++;
    }
    fprintf(fptr3, "\n\n number of lines = %d n number of words is = %d\n", n, w - 1);
    /*appendig comments in the concatenated file*/
    fclose(fptr1);
    fclose(fptr2);
    fclose
Replace a line or word in File
Replace a line or word in a file

import java.io.*;

public class BTest
    {
     public static void main(String args[])
         {
         try
             {
             File file = new File("file.txt");
             BufferedReader reader = new BufferedReader(new FileReader(file));
             String line = "", oldtext = "";
             while((line = reader.readLine()) != null)
                 {
                 oldtext += line + "\r\n";
             }
             reader.close();
             // replace a word in a file
             //String newtext = oldtext.replaceAll("drink", "Love");
           
             //To replace a line in a file
             String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
           
             FileWriter writer = new FileWriter("file.txt");
             writer.write(newtext);writer.close();
         }
         catch (IOException ioe)
             {
             ioe.printStackTrace();
         }
     }
}

Append content to a file in java
package com.mkyong.file;

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class AppendToFileExample
{
    public static void main( String[] args )
    {
     try{
      String data = " This content will append to the end of the file";

      File file =new File("javaio-appendfile.txt");

      //if file doesnt exists, then create it
      if(!file.exists()){
       file.createNewFile();
      }

      //true = append file
      FileWriter fileWritter = new FileWriter(file.getName(),true);
             BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
             bufferWritter.write(data);
             bufferWritter.close();

         System.out.println("Done");

     }catch(IOException e){
      e.printStackTrace();
     }
    }
}
List files in directory
import java.io.*;

class Main {
   public static void main(String[] args) {
      File dir = new File("F:");
      File[] files = dir.listFiles();
      FileFilter fileFilter = new FileFilter() {
         public boolean accept(File file) {
            return file.isDirectory();
         }
      };
      files = dir.listFiles(fileFilter);
      System.out.println(files.length);
      if (files.length == 0) {
         System.out.println("Either dir does not exist
         or is not a directory");
      }
      else {
         for (int i=0; i< files.length; i++) {
            File filename = files[i];
            System.out.println(filename.toString());
         }
      }
   }
}

read file and reverse it

import java.io.*;
    import java.utili.*;

        public class ReverseFile
         {
         public static void main(String[] args) throws IOException
          {
      try{
      File sourceFile=new File(args[0]);
      Scanner content=new Scanner(sourceFile);
      PrintWriter pwriter =new PrintWriter(args[1]);

      while(content.hasNextLine())
      {
         String s=content.nextLine();
         StringBuffer buffer = new StringBuffer(s);
         buffer=buffer.reverse();
         String rs=buffer.toString();
         pwriter.println(rs);
      }
      content.close();  
      pwriter.close();
      System.out.println("File is copied successful!");
      }

      catch(Exception e){
          System.out.println("Something went wrong");
      }
   }
      }

join-lines-2-files-and-store-in-new-file


http://www.sanfoundry.com/c-program-join-lines-2-files-and-store-in-new-file/