Saturday, November 29, 2014

Generate all possible combination of numbers in java

The Idea is fairly Simple. Break any number chosen in combination of four numbers.
Concept of solution: If we are choosing any number from "0-9" i.e total 10 numbers. Then to get all combinations of 4 numbers total trial will be 10*10*10*10=10000 trials.

package BreakNumber;

/**
 *
 * @author Manjeet
 */
public class BreaKNumber {

    public static void main(String[] args) {
        int[] first = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        int[] second = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        int[] third = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        int[] four = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

        //ALL Possible combination will be
        //first.length * second.length * third.length * four.length
        int len = first.length;// * second.length * third.length * four.length;
        String test = "1001";// Number to break
        int count = 0;
        len = 10;
        String s = "";
        for (int i = 0; i < len; i++) {
            for (int j = 0; j < len; j++) {
                for (int k = 0; k < len; k++) {
                    for (int l = 0; l < len; l++) {
                        count++;
                        s=first[i] + "" + second[j] + "" + third[k] + "" + four[l];
                        if (s.trim().equals(test)) {
                            System.out.println("NO OF TRY: " + count + " | NUMBER IS: " + s);
                        }
                    }
                }
            }
        }
    }
}

Friday, August 3, 2012

Take Input and Store in Array in Java Example

package InputToArray;

import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 * @author Manjeet Kumar
 */
public class InputToArray {

    public static void main(String args[]) {
        /*int a[]={0,0,0,0,0,0} , b[]={0,0,0,0,0,0};
        for ( int number = 5; number <=10; number++)
        {
        a[number-5] = number;
        b[number-5]= (number * number);
        System.out.println(a[number-5]);
        System.out.println(b[number-5]);
        }
    * 
    */
//I dont't think above example is justice to your quest to "Take Input and store in Array". Here is better example

        ArrayList name = new ArrayList();
        ArrayList phone = new ArrayList();
        ArrayList newName = new ArrayList();
        ArrayList newPhone = new ArrayList();
        Scanner sc = new Scanner(System.in);
        // while (true) {
        //or
        for (int i = 0; i < 3; i++) {
            System.out.println("Please enter your name: ");
            name.add(sc.next());
            System.out.println("Please enter your number: ");
            phone.add(sc.nextInt());
        }
        //}
        System.out.println("Total Name=" + name + " Total number=" + phone);

        for (int l = 0; l < name.size(); l++) {
            System.out.println(" Name=" + name.get(l));
            newName.add(name.get(l));
        }
        for (int m = 0; m < phone.size(); m++) {
            System.out.println(" Phone=" + phone.get(m));
            newPhone.add(phone.get(m));
        }
//after copying from one array to new array
        System.out.println("new Name=" + newName + " new phone=" + newPhone);
    }
}

Example Program in Java Using Hashmap,Hashset & Hashtable. Program also shows adding, deleting elements from these collection types

package HashTable;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author Manjeet Kumar
 */
public class HashTableDemo {

    public static void main(String[] args) {
        //exclusive Demo of hashmap
        Map map = new HashMap();
        map.put(1, "Abc");
        map.put(2, "Def");
        map.put(3, "Ijk");
        System.out.println("All of the mappings   " + map);

        //put all mappings of map into map1 
        Map map1 = new HashMap();
        map1.putAll(map);

        System.out.println("All of the mappings   " + map1);

        //Demo of Collections

        Hashtable numbers = new Hashtable();
        numbers.put("one", new Integer(1));
        numbers.put("two", new Integer(2));
        numbers.put("three", new Integer(3));
        numbers.put("four", new Integer(4));
        numbers.put("five", new Integer(5));
        numbers.put("Six", new Integer(6));


        Integer n = (Integer) numbers.get("two");

        if (n != null) {
            System.out.println("Two=" + n);
        }

        HashMap hMap = new HashMap();
        hMap.put("A", "apple");           //Without String construtor invocation|
        hMap.put("B", new String("ball"));//With String constructor invocation  |Both can be used
        hMap.put("C", "cat");
        hMap.put("D", new String("doll"));
        hMap.put("E", "eye");
        hMap.put("F", new String("fruit"));
        hMap.put("G", "go");
        hMap.put("H", new String("Hashmap"));


        String s = (String) hMap.get("A");
        if (!s.equals(null)) {
            System.out.println("A for " + s);
            System.out.println("B for " + hMap.get("B"));
        }

        HashSet hs = new HashSet();
        hs.add("Megan");
        hs.add("Regan");
        hs.add("Donald");
        hs.add("Eleen");
        hs.add("Cathy");
        hs.add("Fiennes");
        System.out.println(hs);

//Example using Set
        // Create the set
        Set set = new HashSet();

// Add elements to the set
        set.add("a");
        set.add("b");
        set.add("c");
        System.out.println("SET has following elements(after addition): " + set);
// Remove elements from the set
        set.remove("c");
        System.out.println("SET has following elements(after Removing C): " + set);


// Get number of elements in set
        int size = set.size();          // 2
        System.out.println("Number of elements in SET: " + size);


// Adding an element that already exists in the set has no effect
        set.add("a");
        size = set.size();              // 2
        System.out.println("Adding and Element(observe the difference): " + size + "  Now SET is " + set + "  Because 'a' allready exist in SET");

        set.add("m");
        size = set.size();
        System.out.println("Adding Element other than existing increases size to" + size + "Now SET is: " + set);
// Determining if an element is in the set
        boolean a = set.contains("a");
        boolean b = set.contains("b");  // true
//b = set.contains("c");          // false
        boolean c = set.contains("c");
        boolean m = set.contains("m");

        System.out.println("Checking if it contains A:" + a);
        System.out.println("Checking if it contains B:" + b);
        System.out.println("Checking if it contains C:" + c);
        System.out.println("Checking if it contains M:" + m);

// Iterating over the elements in the set
        Iterator it = set.iterator();
        while (it.hasNext()) {
            // Get element
            Object element = it.next();

            System.out.println("Check the Object :" + element);
        }

// Create an array containing the elements in the set (in this case a String array)
        String[] array = (String[]) set.toArray(new String[set.size()]);
        System.out.println("See array: " + array);

    }
}

Array Integer to String Parsing in Java

package Array_Int_to_String;

import java.util.Arrays;

/**
 *
 * @author Manjeet Kumar
 */
public class ArrayIntToStr {

    public static void main(String[] args) {
        int num[] = new int[]{1, 2, 3, 4, 5};
        /*
         * First approach is to loop through all elements of an int array
         * and append them to StringBuffer object one by one. At the end,
         * use toString method to convert it to String.
         */
        StringBuffer sbf = new StringBuffer();
        String sepRator = " ";
        if (num.length > 0) {
            //we don't want leading space for 1st elements
            sbf.append(num[0]);

            /*
             * Loop through the elements of an int array. Please
             * note that loop starts from 1 not from 0 because we
             * already appended the first element without leading space.s  
             */
            for (int i = 0; i < num.length; i++) {
                sbf.append(sepRator).append(num[i]);
            }
            System.out.println("Int Array Converted to String Loop");
            System.out.println(sbf.toString());

            /*
             * Second options is to use Arrays class as given below.
             * Use Arrays.toString method to convert int array to String.
             * However, it will return String like [1, 2, 3, 4, 5]
             */
            String strNum = Arrays.toString(num);
            System.out.println("String generated from Arrays.toString() method=" + strNum);

            //Use Replace all to replace brackets and commas
            strNum = strNum.replaceAll(",", sepRator).replace("[", "").replace("]", "");
            System.out.println("Final String=" + strNum);
        }
    }
}

Yahoo/Gmail E-mail Client Using Java

package Mailer_Yahoo;

/**
 *
 * @author Manjeet Kumar
 */

 
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class SendMailSSL {
    
 public static void main(String[] args) {
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.mail.yahoo.com");//smtp.gmail.com in case you want make gmail client 
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class",
    "javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
 
  Session session = Session.getDefaultInstance(props,
   new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication("username@yahoo.com","password");
    }
   });
 
  try {

   Message message = new MimeMessage(session);
                        Address addr[]=message.getFrom();
                        String email = addr == null ? null : ((InternetAddress) addr[0]).getAddress();
                        System.out.println("Email="+email);
   message.setFrom(new InternetAddress("me@yahoo.com"));
   message.setRecipients(Message.RecipientType.TO,
     InternetAddress.parse("me_at_gmail@gmail.com"));
                        //message.setRecipients(Message.RecipientType.CC,InternetAddress.parse("me@gdiindia.com"));
                        //message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse("xyz@gdiindia.com"));
   message.setSubject("Testing Subject");
   message.setText("Dear Recipient," +
     "\n\n This is to inform You that SSL has been Implemented");
 
   Transport.send(message);
 
   System.out.println("Mail Delivered Sucessfully");
 
  } catch (MessagingException e) {
   throw new RuntimeException(e);
  }
 }
}

Getting Complete System Information using Java

import java.util.Properties;

/**
 *
 * @author Manjeet Kumar
 */
public class GetCompleteSystemInfo {

    public static void main(String args[]) {
        //1.Get Java Runtime
        Runtime runtime = Runtime.getRuntime();
        System.out.println("Runtime=" + Runtime.getRuntime());

        //2. Get Number of Processor availaible to JVM
        int numberOfProcessors = runtime.availableProcessors();
        System.out.println(numberOfProcessors + " Processors ");

        //2. Get FreeMemory, Max Memory and Total Memory
        long freeMemory = runtime.freeMemory();
        System.out.println("Bytes=" + freeMemory + " |KB=" + freeMemory / 1024 + " |MB=" + (freeMemory / 1024) / 1024+" Free Memory in JVM");

        long maxMemory = runtime.maxMemory();
        System.out.println(maxMemory + "-Bytes " + maxMemory / 1024 + "-KB  " + (maxMemory / 1024) / 1024 + "-MB " + " Max Memory Availaible in JVM");

        long totalMemory = runtime.totalMemory();
        System.out.println(totalMemory + "-Bytes " + totalMemory / 1024 + "-KB " + (totalMemory / 1024) / 1024 + "-MB " + " Total Memory Availaible in JVM");


        //3. Suggest JVM to Run Garbage Collector
        runtime.gc();

        //4. Suggest JVM to Run Discarded Object Finalization
        runtime.runFinalization();

        //5. Terminate JVM
        //System.out.println("About to halt the current jvm");//not to be run always
        //runtime.halt(1);
        // System.out.println("JVM Terminated");

        //6. Get OS Name
        String strOSName = System.getProperty("os.name");
        if (strOSName != null) {
            if (strOSName.toLowerCase().indexOf("windows") != -1) {
                System.out.println("This is "+strOSName);
            } else {
                System.out.print("Can't Determine");
            }
        }

        //7. Get JVM Spec
        String strJavaVersion = System.getProperty("java.specification.version");
        System.out.println("JVM Spec : " + strJavaVersion);
        //8. Get Class Path
        String strClassPath = System.getProperty("java.class.path");
        System.out.println("Classpath: " + strClassPath);

        //9. Get File Separator
        String strFileSeparator = System.getProperty("file.separator");
        System.out.println("File separator: " + strFileSeparator);

        //10. Get System Properties
        Properties prop = System.getProperties();
        System.out.println("System Properties(detail): " + prop);

        //11. Get System Time
        long lnSystemTime = System.currentTimeMillis();
        System.out.println("Milliseconds since midnight, January 1, 1970 UTC : " + lnSystemTime + "\nSecond=" + lnSystemTime / 1000 + "\nMinutes=" + (lnSystemTime / 1000) / 60 + ""
                + "\nHours=" + ((lnSystemTime / 1000) / 60) / 60 + "\nDays=" + (((lnSystemTime / 1000) / 60) / 60) / 24 + "\nYears=" + ((((lnSystemTime / 1000) / 60) / 60) / 24) / 365);
    }
}

Reflection API(Reflection API Example in Java):


Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.

Sample Program which Demonstrate How can we try Reflection API:

package ReflectionAPI;

/**
 *
 * @author Manjeet Kumar
 */
public class ReflectionAPI {
public static void main(String[] args) throws CloneNotSupportedException
{
    System.out.println("we are testing reflection API");
    ReflectionAPI rap=new ReflectionAPI();
    System.out.println("rap.getClass(): "+rap.getClass());
    byte[] bytes = new byte[1024];
    System.out.println("rap.getClass(): "+bytes.getClass());
    String str="test str";
    System.out.println("str.getClass(): "+ str.getClass());
   
            System.out.println("getCanonicalName of class: "+RefAPI.class.getCanonicalName());
            System.out.println("getName of class: "+RefAPI.class.getName());
            System.out.println("getSimpleName of class: "+RefAPI.class.getSimpleName());   
            System.out.println("toString gives the name of class: "+RefAPI.class.toString());
            System.out.println("desiredAssertionStatus of class: "+RefAPI.class.desiredAssertionStatus());
            System.out.println("getAnnotations of class: "+RefAPI.class.getAnnotations());
            System.out.println("getClassLoader of class: "+RefAPI.class.getClassLoader());
            System.out.println("getClasses of class: "+RefAPI.class.getClasses());
            System.out.println("getClasses of class: "+ReflectionAPI.class.getClasses());
            System.out.println("getComponentType of class: "+ReflectionAPI.class.getComponentType());
            System.out.println("getConstructors of class: "+ReflectionAPI.class.getConstructors());
            System.out.println("getDeclaredAnnotations of class: "+ReflectionAPI.class.getDeclaredAnnotations());
            System.out.println("getDeclaredFields of class: "+ReflectionAPI.class.getDeclaredFields());
            System.out.println("getDeclaredMethods of class: "+ReflectionAPI.class.getDeclaredMethods());
            System.out.println("getModifiers of class: "+ReflectionAPI.class.getModifiers());
            System.out.println("getPackage of class: "+ReflectionAPI.class.getPackage());
            System.out.println("getProtectionDomain of class: "+ReflectionAPI.class.getProtectionDomain());
            System.out.println("getEnclosingClass of class: "+ReflectionAPI.class.getEnclosingClass());
            System.out.println("getEnclosingClass of class: "+RefAPI.class.getEnclosingClass());
            System.out.println("getSigners of class: "+ReflectionAPI.class.getSigners());
            System.out.println("getSuperClass of class: "+RefAPI.class.getSuperclass());
            System.out.println("getTypeParametrs of class: "+ReflectionAPI.class.getTypeParameters());
            System.out.println("checks if class isAnnotation: "+ReflectionAPI.class.isAnnotation());
            System.out.println("checks if class isAnonymousClass: "+ReflectionAPI.class.isAnonymousClass());
            System.out.println("checks if class isArray: "+ReflectionAPI.class.isArray());
            System.out.println("checks if class isEnum: "+ReflectionAPI.class.isEnum());
            System.out.println("checks if class isInterface: "+RefInterface.class.isInterface());
            System.out.println("checks if class isRefAPIEnum: "+RefAPIEnum.class.isEnum());
            System.out.println("checks if class isLocalClass: "+RefAPI.class.isLocalClass());
            System.out.println("checks if class isMemberClass: "+RefAPI.class.isMemberClass());
            System.out.println("checks if class isPrimitive: "+RefAPI.class.isPrimitive());
            System.out.println("checks if class isSynthetic: "+RefAPI.class.isSynthetic());
}
class RefAPI
{
    public int method1()
    {
        return 1+1;
    }
       
}
interface RefInterface
{
    public int num=0;
    public String str="Reflection API";
    public boolean bool=false;
}
enum RefAPIEnum<String,String>

Friday, July 20, 2012

WORLD Clock in JAVA


World Clock Code in Java:


Input Name of City across world and Print the Current Time.


1. It takes name of city from user.
2. Then it Parses name and Time Zones which is being returned by for loop.(note that for loop below is returning names 455 Time zones across world, with no duplicity at all!!! )
3. As soon your input and Time Zones matches if-block takes current timezone in loop and passes it to Calendar.



import java.util.*;
public class UltimateWorldClock {
    private static final String TAG="ULTIMATE WORLD CLOCK is Product of Alexander & BROS. CORP";
  private static final String GLOBAL_LIST =
      "^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
  private static List<TimeZone> TimeZoneS;
  public static List<TimeZone> getTimeZones() {
    if (TimeZoneS == null) {
      TimeZoneS = new ArrayList<TimeZone>();
      final String[] tZoneID = TimeZone.getAvailableIDs();
      for (final String id : tZoneID) {
        if (id.matches(GLOBAL_LIST)) {
          TimeZoneS.add(TimeZone.getTimeZone(id));
        }
      }
      Collections.sort(TimeZoneS, new Comparator<TimeZone>() {
        public int compare(final TimeZone t1, final TimeZone t2) {
          return t1.getID().compareTo(t2.getID());
        }
      });
    }
    return TimeZoneS;
  }
  public static String getName(TimeZone timeZone)//This is for Displaying Timezone ID and TimeZone Name
  { 
    return timeZone.getID().replaceAll("_", " ");
  }
  public static void main(String[] args) {
    TimeZoneS = getTimeZones();
    Scanner in=new Scanner(System.in);
    System.out.println(TAG+"\nEnter the Name of City You wish to Know Time of:");
    String city=in.next();
   for (TimeZone timeZone : TimeZoneS) {
 //System.out.println(getName(timeZone));
 if(getName(timeZone).matches("(?i).*"+city+".*"))
 {
     Calendar cal = new GregorianCalendar(TimeZone.getTimeZone(getName(timeZone)));
            int hour12 = cal.get(Calendar.HOUR);         
            int minutes = cal.get(Calendar.MINUTE);      
            int seconds = cal.get(Calendar.SECOND);      
            boolean am = cal.get(Calendar.AM_PM) == Calendar.AM;
            boolean pm = cal.get(Calendar.AM_PM) == Calendar.PM;
            if (am) {
                System.out.println(getName(timeZone) + " | Current Time: " + hour12 + ":" + minutes + ":" + seconds + " AM");
            }
            if (pm) {
                System.out.println(getName(timeZone) + " | Current Time: " + hour12 + ":" + minutes + ":" + seconds + " PM");
    }
 }
   }
  }
  }

You can try Example such as:
sofia or sof
sarajevo
tehran
kolkata
los angles
hong kong
........... 

Generate all possible combination of numbers in java

The Idea is fairly Simple. Break any number chosen in combination of four numbers. Concept of solution: If we are choosing any number from...