Sunday, February 2, 2014

PriorityQueue Sorted By String Length

Source:
import java.util.Comparator;
import java.util.PriorityQueue;

public class MyPriorityQueue {
   public static void main(String[] args) {
      Comparator<String> com = new MyComparator();
      PriorityQueue<String> q = new PriorityQueue<String>(10, com);
      q.add("a");
      q.add("zz zz zz zz zz");
      q.add("cc cc cc");
      q.add("The cat in the hat");
      q.add("dddd");
      while (q.size() != 0) {
         System.out.println(q.remove());
      }
   }
}

// sort by string length of string
class MyComparator implements Comparator<String> {
   public int compare(String x, String y) {
      if (x.length() < y.length()) {
         return -1;
      }
      if (x.length() > y.length()) {
         return 1;
      }
      return 0;
   }
}

Output:
   $ java MyPriorityQueue 
   a
   dddd
   cc cc cc
   zz zz zz zz zz
   The cat in the hat

Test is a file is a symbolic link

Source:
import java.nio.file.*;
 
public class SymbolicLink {
 
   public static void main(String[] args) {
 
      Path path = Paths.get("./file.txt");
 
      if (Files.isSymbolicLink(path)) {
         System.out.println("file.txt is a symbolic link");
      } else {
         System.out.println("file.txt is note a symbolic link");
      }
 
   }
}

Output:
   $ java SymbolicLink 
   file.txt is a symbolic link

   $ file file.txt 
   file.txt: symbolic link to `foo.txt'

   $ ls -l file.txt 
   lrwxrwxrwx 1 dennis dennis 7 Feb  2 08:53 file.txt -> foo.txt

Check if two paths using symbolic links are the same file

Source:
import java.io.*;
import java.nio.file.*;

public class TestFile {

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

      Path p1 = Paths.get("./file1");
      Path p2 = Paths.get("./file2");

      if (p1.equals(2)) {
         System.out.println("Same paths");
      } else {
         System.out.println("Different Paths");
      }

      if (Files.isSameFile(p1, p2)) {
         System.out.println("Same File");
      } else {
         System.out.println("Different File");
      }

   }
}

Output:
   $ java TestFile 
   Different Paths
   Same File

   $ ls -l file2
   lrwxrwxrwx 1 dennis dennis 5 Feb  2 07:52 file2 -> file1

Java example using try-with-resources

Source:
import java.io.*;
 
public class TryWithResources {
 
   public static void main( String[] args ) {
 
      String path = "/tmp/file.txt";

      // No need to close the BufferedReader
      try (BufferedReader br = new BufferedReader(new FileReader(path))) {
         String line;
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      } catch(IOException e) {
      }
 
   }
}

Output:
   $ java TryWithResources 
   The cat in the hat
   
   $ cat /tmp/file.txt 
   The cat in the hat

Saturday, February 1, 2014

Example of a NullPointerException

Source:
public class NullPointerExample {
   public static void main(String[] args) {
      String str = "This is a string";
      System.out.println(str);
      System.out.println(str.length());

      str = null;
      System.out.println(str);

      // Should trigger NullPointerException
      System.out.println(str.length());
   }
}

Output:
   $ java NullPointerExample 
   This is a string
   16
   null
   Exception in thread "main" java.lang.NullPointerException
       at Foo.main(Foo.java:11)

How do I check if a file exists?

Source:
import java.io.File;
 
public class FileExists {
   public static void main(String[] args) {
 
      String str = "/etc/hostname";
      File f = new File(str);
      if(f.exists()) { 
         System.out.println("File " + str + " exist.");
      }
   }
}

Output:
   $ java FileExists 
   File /etc/hostname exist.

Try Catch Exception Matching

Source:
public class ExceptionMatching {
 
   public static void main(String[] args) {
      try {
         method();
      } catch (NullPointerException e) {
         System.out.println("Exception match: NullPointerException");
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception match: ArrayIndexOutOfBoundsException");
      } catch (Exception e) {
         System.out.println("Exception not matched " + e.toString());
      }
 
   }
 
   public static void method() {
      int x[] = new int[10];
 
      // this should throw an ArrayIndexOutOfBoundsException
      int y = x[21];
   }
}

Output:
   $ java ExceptionMatching 
   Exception match: ArrayIndexOutOfBoundsException

Example of a try catch finally block where finally is not run.

Source:
// Example of finally clause that does not run
public class FinallyNotRun {
   public static void main(String[] args) {
      try {
        System.out.println("Inside try");

        // should throw exception
        int x = 10 / 0;

      } catch (Exception e) {
        System.out.println("Inside catch");

        // Lets pretend to crash
        System.exit(0);

      } finally {
        // Will not run
        System.out.println("Inside finally");
      }
   }
}

Output:
   $ java FinallyNotRun 
   Inside try
   Inside catch

Example of a Shut Down Hook

Source:
public class ShutDownHook {

   public static void main(String[] args) {

      // try and run before shutdown
      Runtime.getRuntime().addShutdownHook(new Thread() {
         public void run() {
            System.out.println("Shutdown Hook is running....");
         }
      });

      try {
        System.out.println("Inside try");

        // throw  an exception
        int x = 10 / 0;

      } catch (Exception e) {
        System.out.println("Inside catch");
        // Shut down and test hook
        System.exit(0);

      } finally {
        // should not run
        System.out.println("Inside finally");
      }
   }
}

Output:
   $ java ShutDownHook 
   Inside try
   Inside catch
   Shutdown Hook is running....

Using Try Catch Finally blocks without Catch

Source:
// Using a try block without catch clause
public class TryFinally {
   public static void main(String[] args) {
      try {
        System.out.println("Inside try");
      } finally {
        System.out.println("Inside finally");
      }
   }
}

Output:
   $ java TryFinally 
   Inside try
   Inside finally

Friday, January 31, 2014

How to rethrow an exception in java?

Source:
class MyException extends Exception { }
 
public class RethrowException {
 
   public static void main(String[] args) {
 
      try {
         M1();
      } catch (Exception e) {
         System.out.println("main(): Caught "  + e.toString());
      }
   }
 
   public static void M1() throws MyException {
      try {
         M2();
      } catch (Exception e) {
         System.out.println("M1(): Caught " + e.toString());
 
         System.out.println("M1(): Rethrowing " + e.toString());
         throw e;
      }
   }
 
   public static void M2() throws MyException {
      System.out.println("M2(): Throwing MyException...");
      throw new MyException();
   }
}

Output:
   $ java RethrowException 
   M2(): Throwing MyException...
   M1(): Caught MyException
   M1(): Rethrowing MyException
   main(): Caught MyException

How to handle more than one type of exception?

Source:
public class MultipleExceptions {

   public static void main(String[] args) {

      try {
        int x = 10/0;
      } catch (NullPointerException|ArithmeticException ex) {
         System.out.println("NullPointer or Arithmetic caught");
      }
   }
}

Output:
   $ java MultipleExceptions 
   NullPointer or Arithmetic caught

error: Class names, 'HelloWorld', are only accepted if annotation processing is explicitly requested

If you receive this error, you forgot to include the .java suffix when compiling the program.

Remember, the command is javac HelloWorld.java not javac HelloWorld.

Example:
   $ javac HelloWorld
   error: Class names, 'HelloWorld', are only accepted if annotation processing is explicitly requested
   1 error

   $ javac HelloWorld.java

   $ java HelloWorld 
   Hello World

How to initialize an array in java?

Source:
import java.util.Arrays;

public class NewArray {

   public static void main(String[] args) {

      int a1[] = new int[99]; 
      int a2[] = new int[] {10,20,30,40,50};

    System.out.println("a1.length: " + a1.length);
    System.out.println("a2 content: " + Arrays.toString(a2));
   }
}

Output:
   $ java NewArray 
   a1.length: 99
   a2 content: [10, 20, 30, 40, 50]

Thursday, January 30, 2014

How to throw an exception in java?

Source:
public class ThrowException {
   public static void main(String[] args) {
      throw new IllegalArgumentException("Bad Argument");
   }
}

Output:
   $ java ThrowException 
   Exception in thread "main" java.lang.IllegalArgumentException: Bad Argument
      at ThrowException.main(ThrowException.java:3)

How to propagate an exception in java?

This java example demonstrates an exception being propagated. The exception is thrown in M4() but is handled in M2().

Source:

public class PropagateException {

   public static void main(String[] args) {
      M1();
   }

   public static void M1() {
      System.out.println("M1 started");
      M2();
      System.out.println("M1 finished");
   }
  
   public static void M2() {
      System.out.println("M2 started");

      // The Exception thrown in M4() is handled here
      try {
         M3();
      } catch (Exception e) {
         System.out.println("M2: " + e.toString() );
      }

      System.out.println("M2 finished");
   }

   public static void M3() {
      System.out.println("M3 started");
      M4();
      System.out.println("M3 finished");
   }

   public static void M4() {
      System.out.println("M4 started");
      int x = 10 / 0;  // Should throw Exception
      System.out.println("M4 finished");
   }
}

Output:
   $ java PropagateException 
   M1 started
   M2 started
   M3 started
   M4 started
   M2: java.lang.ArithmeticException: / by zero
   M2 finished
   M1 finished

How to print a java stack trace from an exception?

Source:
public class PrintStack {
   public static void main(String[] args) {
      try {
         Class1 c1 = new Class1();
         c1.test1();
      } catch (Exception e) {
        e.printStackTrace();
      }
   }
}
 
class Class1 {
   void test1() {
      Class2 c2 = new Class2();
      c2.test2();
   }
}
 
class Class2 {
   void test2() {
      int x = 10 / 0;
   }
}

Output:
   $ java PrintStack 
   java.lang.ArithmeticException: / by zero
       at Class2.test2(PrintStack.java:22)
       at Class1.test1(PrintStack.java:16)
       at PrintStack.main(PrintStack.java:6)

Example on how to catch multiple exception types

Source:
public class ExceptionMatching {
   public static void main(String[] args) {
 
      String[] str = new String[2]; 
      str[0] = "String 0";
 
      for (int x = 0; x < 3; x++) {
         try {
            System.out.println("String length: " + str[x].length());
         } catch (NullPointerException e) {
            System.out.println("Handling Null Pointer Exception");
         } catch ( ArrayIndexOutOfBoundsException e) {
            System.out.println("Handling ArrayIndexOutOfBounds Exception");
         } catch (Exception e) {
            System.out.println("Handling Unknown Exception");
         }
      }
   }
}

Output:
   $ java ExceptionMatching 
   String length: 8
   Handling Null Pointer Exception
   Handling ArrayIndexOutOfBounds Exception

Creating your own exception class in java

Source:
class MyException extends Exception {
   public MyException() { }
   public MyException(String msg) {
      super(msg);
   }
};
 
public class CreateException {
   public static void main(String[] args) {
      try {
         throw new MyException("my message");
      } catch (Exception e) {
         System.out.println("Exception Type: "  + e );
      }
   }
}

Output:
   $ java CreateException 
   Exception Type: MyException: my message

Java Exception Handling: Basic Try Catch Finally

Source:

public class TryCatchFinally {
   public static void main(String[] args) {
 
      for (int count = 1; count != -1 ; count--) { 
 
         try {
           System.out.println("Inside try - count: "  + count);
           int x = 1 / count;
         } catch (Exception e){
           System.out.println("Inside catch - count: "  + count );
         } finally {
           System.out.println("Inside finally - count: "  + count );
         }
 
      }
 
   }
}


Output:
   $java TryCatchFinally 
   Inside try - count: 1
   Inside finally - count: 1
   Inside try - count: 0
   Inside catch - count: 0
   Inside finally - count: 0

The use of try and catch in java.

Source:
public class BasicTryCatch {
   public static void main(String[] args) {
 
      int[] array = new int[3];
 
      try {
         array[4] = 1; // outside its boundry
      } catch (Exception e) {
        System.out.println("Exception thrown: " + e.toString());
      }
 
   }
}

Output:
   $ java BasicTryCatch 
   Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 4

Wednesday, January 29, 2014

Classic Tower Of Hanoi Example

Source:
public class TowerOfHanoi {  
 
   private static void hanoi (int disks) {  
      hanoi (disks, "Pole 1", "Pole 3", "Pole 2");  
   }  
 
   private static void hanoi (int disks, String from, String to, String using) {  
      if (disks != 0) {  
         hanoi (disks -1, from, using, to) ;   
         System.out.println("Move disk " + disks + " from " + from + " to " + to);  
         hanoi (disks -1, using, to, from);  
      }  
   }  
 
   public static void main (String[] arg) throws Exception {  
      hanoi(4);  
   }  
}  

Output:
   $ java TowerOfHanoi 
   Move disk 1 from Pole 1 to Pole 2
   Move disk 2 from Pole 1 to Pole 3
   Move disk 1 from Pole 2 to Pole 3
   Move disk 3 from Pole 1 to Pole 2
   Move disk 1 from Pole 3 to Pole 1
   Move disk 2 from Pole 3 to Pole 2
   Move disk 1 from Pole 1 to Pole 2
   Move disk 4 from Pole 1 to Pole 3
   Move disk 1 from Pole 2 to Pole 3
   Move disk 2 from Pole 2 to Pole 1
   Move disk 1 from Pole 3 to Pole 1
   Move disk 3 from Pole 2 to Pole 3
   Move disk 1 from Pole 1 to Pole 2
   Move disk 2 from Pole 1 to Pole 3
   Move disk 1 from Pole 2 to Pole 3

Calculate the time it takes for light to travel from the sun to the earth?

Source:
import java.text.DecimalFormat;
 
public class Sunlight {
   public static void main(String[] args) {
 
      double distance = 92960000;
      double speed = 186282.397; 
 
      double time = Math.round(distance/speed);
 
      System.out.println("Total time: " + time + " seconds");
 
      double minutes = Math.floor(time / 60);
      double seconds = time % 60;
 
      DecimalFormat df = new DecimalFormat("#.##");
 
      System.out.println("It takes " + df.format(minutes) + " minutes and " 
            + df.format(seconds) + " seconds.");
 
   }
}

Output:
   # java Sunlight 
   Total time: 499.0 seconds
   It takes 8 minutes and 19 seconds.

How to round a number to n'th decimal places in java?

Source:
public class RoundNumber {
   public static void main(String[] args) {
      System.out.println(round(1.23456789));
      System.out.println(round(9.99999999));
      System.out.println(round(2.22222222));
      System.out.println(round(3.123451234512345));
      System.out.println(round(9.87654321));
   }
 
   public static double round(double number) {\
      // round to five places
      return (double)Math.round(number * 100000) / 100000;
   }
}

Output:
   $ java RoundNumber 
   1.23457
   10.0
   2.22222
   3.12345
   9.87654

Quadratic Formula Example in java.

Source:
class QuadraticFormula {
   public static void main(String[] args) {
 
      double a = 0;
      double b = 0;
      double c = 0;
      double discriminant = 0;
      double root1 = 0;
      double root2 = 0;
 
      if (args.length == 3) {
         a = Double.parseDouble(args[0]);
         b = Double.parseDouble(args[1]);
         c = Double.parseDouble(args[2]);
      } else {
         System.err.println("Wrong.");
      }
 
      discriminant = Math.pow(b,2) - 4*a*c; 
      root1 = (-b + Math.sqrt(discriminant))/(2*a); 
      root2 = (-b - Math.sqrt(discriminant))/(2*a); 
 
      System.out.println("Discriminant = " + discriminant);
 
      if(discriminant > 0) {
         System.out.println("Roots: " + root1  + ", " + root2);
      } 
 
      else if(discriminant == 0) {
         System.out.println("Only one root.");
         System.out.println("Root: " + root1);
      } 
 
      else {
         System.out.println("It has Complex Roots.");
         root1 = -b/(2*a);
         root2 = Math.sqrt(-discriminant)/(2*a);
         System.out.println("Roots: " + root1 + " + " + root2 + "i, " 
               + root1 + " - " + root2 + "i");
      }
   }
}

Output:
   # java QuadraticFormula 2 5 -3
   Discriminant = 49.0
   Roots: 0.5, -3.0

   # java QuadraticFormula 3 6 3
   Discriminant = 0.0
   Only one root.
   Root: -1.0

   # java QuadraticFormula 1 2 3
   Discriminant = -8.0
   It has Complex Roots.
   Roots: -1.0 + 1.4142135623730951i, -1.0 - 1.4142135623730951i

How to find prime numbers in java?

Source:
public class PrimeNumbers {

   public static void main(String args[]) {
      for(int x = 2; x < 50; x++) {
         if(isPrime(x)){
            System.out.print(x +", ");
         }
      }
   }

   public static boolean isPrime(int x) {
      for(int i=2; i<x; i++) {
         if(x % i == 0) {
            return false; 
         }
      }
      return true; 
   }
}

Output:
   $ java PrimeNumbers 
   2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 

Calculating divisors in java.

Source:
public class Divisors {

   public static void main(String[] args) { 
      int N = Integer.parseInt(args[0]);

      for (int i = 1; i <= N; i++) {
         System.out.print(i+ ": ");
         for (int j = 1; j <= N; j++) {
            if (i % j == 0) {
               System.out.print(j + " "); 
            }
         }
         System.out.println("");
      }
   }
}

Output:
   $ java Divisors 15
   1: 1 
   2: 1 2 
   3: 1 3 
   4: 1 2 4 
   5: 1 5 
   6: 1 2 3 6 
   7: 1 7 
   8: 1 2 4 8 
   9: 1 3 9 
   10: 1 2 5 10 
   11: 1 11 
   12: 1 2 3 4 6 12 
   13: 1 13 
   14: 1 2 7 14 
   15: 1 3 5 15 

Leibniz Formula For PI

Source:
public class LeibnizFormula {
   public static void main(String[] args) {
 
      int count = 999999999;
      double pi = 0;
      double denominator = 1;
 
      for (int x = 0; x < count; x++) {
 
         if (x % 2 == 0) {
            pi = pi + (1 / denominator);
         } else {
            pi = pi - (1 / denominator);
         }
         denominator = denominator + 2;
      }
      pi = pi * 4;
      System.out.println(pi);
   }
}

Output:
   $ java LeibnizFormula 
   3.1415926545880506

Java program to generate Harmonic Series

Source:
public class Harmonic { 
   public static void main(String[] args) { 
 
      int x = Integer.parseInt(args[0]);
 
      // compute 1/1 + 1/2 + 1/3 + ... + 1/x
      double sum = 0.0;
      for (int i = 1; i <= x; i++) {
            //sum += 1.0 / i;
         sum = sum + (1.0/i);
      }
 
      System.out.println(sum);
   }
}

Output:
   $ java Harmonic 1
   1.0

   $ java Harmonic 2
   1.5

   $ java Harmonic 10
   2.9289682539682538

   $ java Harmonic 100
   5.187377517639621

How to generate random numbers within a range?

Source:
import java.util.Random;
 
public class RandomNumber {
   public static void main(String[] args) {
 
      int low =  10;
      int high = 80;
      Random r = new Random();
 
      System.out.println( r.nextInt(high-low) + low );
      System.out.println( r.nextInt(high-low) + low );
      System.out.println( r.nextInt(high-low) + low );
      System.out.println( r.nextInt(high-low) + low );
   }
}

Output:
   $ java RandomNumber 
   37
   28
   14
   35

Java floor and ceiling example.

Source:
class FloorCeiling {
   public static void main(String args[]){
 
     double x = 7.5;
     double y = -8.4;    
 
     System.out.println("Math.floor(x) : " + Math.floor(x));
     System.out.println("Math.ceil(x) : " + Math.ceil(x));
 
     System.out.println("Math.floor(y) : " + Math.floor(y));
     System.out.println("Math.ceil(y) : " + Math.ceil(y));
   }
}

Output:
   $ java FloorCeiling 
   Math.floor(x) : 7.0
   Math.ceil(x) : 8.0
   Math.floor(y) : -9.0
   Math.ceil(y) : -8.0

Fibonacci recursion example in java.

Source:
public class Fibonacci {

   public static long fib(int n) {
      if (n <= 1) {
         return n;
      } else {
         return fib(n-1) + fib(n-2);
      }
   }

   public static void main(String[] args) {
      for (int x = 0; x <= 15; x++) {
         long total = 0;
         for (int i = 1; i <= x; i++) {
            total = fib(i); 
         }
         System.out.print(total + ", ");
      }
   System.out.println("...");
   }
}

Output:
   $ java Fibonacci 
   0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, ...

Factorial recursion example in java.

Source:
public class Factorial {
 
   public static void main(String args[]) {
 
      int x = Integer.parseInt(args[0]); 
      int result= fact(x);
      System.out.println("The factorial of " + x + ": " + result);
   }
 
   static int fact(int b) {
      if(b <= 1) {
         return 1;
      } else {
         return b * fact(b-1);
      }
   }
}

Output:
   $ java Factorial 5
   The factorial of 5: 120

   $ java Factorial 10
   The factorial of 10: 3628800

Using exponents in java

Example: 83 = 8 × 8 x 8 = 512

Source:
public class Exponents {
   public static void main(String[] args) {
      System.out.println(Math.pow(8, 3));
   }
}

Output:
   $ java Exponents 
   512.0

Euclidean Algorithm in java.

Source:
//The Euclidean algorithm is a way to find the greatest common 
//divisor of two positive integers. 
public class Euclidean {
 
    // find greatest common divisor
    public static int gcd(int a, int b) {
 int r = a % b;
        while (r != 0) {
     a = b;
     b = r;
     r = a % b;
 }
 return b;
    }
 
    public static void main(String[] args) {
      System.out.println("Common Divisors:");
      System.out.println("   5  7 : " + gcd(5,7));
      System.out.println("  99  6 : " + gcd(99,6));
      System.out.println(" 100 10 : " + gcd(100,10));
      System.out.println(" 990 77 : " + gcd(990,77));
    }
}

Output:
   $ java java Euclidean 
   Common Divisors:
      5  7 : 1
     99  6 : 3
    100 10 : 10
    990 77 : 11

Calculating compound interest over five years.

Source:
public class CompoundInterest {
   public static void main( String args[] ) {

      double principal = 10000;
      int years = 5;
      double rate = .05;

      System.out.printf("Principle: %.2f \n", principal);
      System.out.println("Years: " + years);
      System.out.println("Interest rate: " + rate);

      System.out.println("Total amount componded over the " + years + " years:" );
      for(int x = 1; x <= years; x++) {
         double amount = principal * Math.pow(1+ rate, x);
         System.out.printf("Year " + x + ": %.2f \n" , amount);
      }
   }
}

Output:
   $ java CompoundInterest  
   Principle: 10000.00 
   Years: 5
   Interest rate: 0.05
   Total amount compounded over the 5 years:
   Year 1: 10500.00 
   Year 2: 11025.00 
   Year 3: 11576.25 
   Year 4: 12155.06 
   Year 5: 12762.82 

Java bit shifting example.

Source:
public class BitShift {
   public static void main(String args[]) {

      int x = 16;

      System.out.println("Before Shift");
      System.out.println(" Decimal: " + x);
      System.out.println(" Binary: 0x" + Integer.toBinaryString(x));

      x = x << 2;

      System.out.println("After Shift");
      System.out.println(" Decimal: " + x);
      System.out.println(" Binary: 0x" + Integer.toBinaryString(x));
   }
}

Output:
   $ java BitShift 
   Before Shift 
    Decimal: 16
    Binary: 0x10000
   After Shift
    Decimal: 64
    Binary: 0x1000000

Calculating the area of a circle.

Source:
import java.util.Scanner;
 
public class CircleArea {
 
   static Scanner sc = new Scanner(System.in);
 
   public static void main(String args[]) {
      System.out.print("Enter the radius of your circle: ");
      double r = sc.nextDouble();
      double area = Math.PI * (r * r);
      System.out.println("The area is " + area);
   }
}

Output:
   $ java CircleArea 
   Enter the radius of your circle: 2
   The area is 12.566370614359172

Java program to print Floyd's Triangle.

Source:
class FloydTriangle {
   public static void main(String args[]) {

      int rows = 7;  
      int n = 1;
      int c; 
      int d;

      System.out.println("Floyd's triangle:");
 
      for ( c = 1 ; c <= rows ; c++ ) {
         for ( d = 1 ; d <= c ; d++ ) {
            System.out.print(n + " ");
            n++;
         }
         System.out.println();
      }
   }
}

Output:
   $ java FloydTriangle
   Floyd's triangle:
   1 
   2 3 
   4 5 6 
   7 8 9 10 
   11 12 13 14 15 
   16 17 18 19 20 21 
   22 23 24 25 26 27 28 

Finding all Leap Years between a range of years.

Source:
import java.util.*;

public class LeapYears {
   public static void main(String[] args) {

      GregorianCalendar cal = new GregorianCalendar();

      System.out.println("Leap years between 1975 and 2015:");
      for (int year = 1975; year < 2015; year++) {
         if (cal.isLeapYear(year)) {
            System.out.println(year);
         }
      }
   }
}

Output:
   $ java LeapYears 
   Leap years between 1975 and 2015:
   1976
   1980
   1984
   1988
   1992
   1996
   2000
   2004
   2008
   2012

Java program to list prime numbers.

Source:
public class PrimeNumbers {
 
   public static void main(String args[]) {
      for(int x = 1; x < 50; x++) {
         if(isPrime(x)){
            System.out.println(x);
         }
      }
   }
 
   public static boolean isPrime(int x) {
      if (x < 2)
         return false; 
      for(int i=2; i<x; i++) {
         if(x % i == 0) {
            return false; 
         }
      }
      return true; 
   }
}


Output:
   $ java PrimeNumbers 
   2
   3
   5
   7
   11
   13
   17
   19
   23
   29
   31
   37
   41
   43
   47

Java program to reverse a number.

Source:
class ReverseNumber {
   public static void main(String args[]) {
      int number = 123456789;
      int reverse = 0;
 
      System.out.println("Number  : " + number);
 
      while( number != 0 ) {
         reverse = reverse * 10;
         reverse = reverse + number%10;
         number = number/10;
      }
 
      System.out.println("Reversed: " + reverse);
   }
}

Output:
   $ java ReverseNumber 
   Number  : 123456789
   Reversed: 987654321

How to list java TimeZone IDs?

Source:
import java.util.TimeZone;

public class ListTimeZoneIDs {
   public static void main(String[] args) throws Exception {
      for (String id : TimeZone.getAvailableIDs()) {
         System.out.println(id);
      }
   }
}

Output:
   $ java ListTimeZoneIDs
   Etc/GMT+12
   Etc/GMT+11
   Pacific/Midway
   Pacific/Niue
   Pacific/Pago_Pago
   Pacific/Samoa
   US/Samoa
   America/Adak
   .....

How to convert Celsius to Fahrenheit?

Source:
class CelsiusToFahrenheit {

  public static void main(String[] args) {

    // Water boils at this temperature
    double temp = 100;
    System.out.println("Celsius: " + temp);
 
    temp = temp * 9 / 5 + 32;
    System.out.println("Fahrenheit: " + temp);
 
  }
}

Output:
   $ java CelsiusToFahrenheit 
  Celsius: 100.0
  Fahrenheit: 212.0

How to convert Fahrenheit to Celsius?

Source:
class FahrenheitToCelsius {

  public static void main(String[] args) {

    // body temperature
    double temp = 98.6;
    System.out.println("Fahrenheit: " + temp);

    temp = (temp - 32) * 5 / 9;

    System.out.println("Celsius: " + temp);
  }
}

Output:
   $ java FahrenheitToCelsius 
   Fahrenheit: 98.6
   Celsius: 37.0

Tuesday, January 28, 2014

How to calculate total seconds in a year?

Source:
import java.util.*;

public class CalculateSeconds {
   public static void main(String[] args) {

      Calendar cal  = Calendar.getInstance();
      cal.set(Calendar.YEAR, 2013);
      cal.set(Calendar.MONTH, 0);
      cal.set(Calendar.DAY_OF_MONTH, 1);

      cal.set(Calendar.HOUR, 0);
      cal.set(Calendar.MINUTE, 0);
      cal.set(Calendar.SECOND, 0);

      long start = cal.getTimeInMillis();

      // set one year later
      cal.set(Calendar.YEAR, 2014);
      long end = cal.getTimeInMillis();

      long seconds = (end - start) / 1000;
      System.out.println("There are " + seconds + " seconds in the year.");

   }
}

Output:
   $ java CalculateSeconds
   There are 31536000 seconds in the year. 

How do I calculate someone's age in Java?

Source:
import java.util.*;

public class CalculateAge {
   public static void main(String[] args) {

      Calendar born  = Calendar.getInstance();
      born.set(Calendar.YEAR, 1970);
      born.set(Calendar.MONTH, 5);
      born.set(Calendar.DAY_OF_MONTH, 1);

      Calendar now  = Calendar.getInstance();

      int years = now.get(Calendar.YEAR) - born.get(Calendar.YEAR);

      System.out.println("You are " + years + " years old.");

   }
}

Output:
   $ java CalculateAge
   You are 44 years old.

How can I increment a date by one day in Java?

Source:
import java.util.*;
import java.text.*;

public class IncrementDay {
   public static void main(String[] args) {

      Calendar cal = Calendar.getInstance();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
      System.out.println(sdf.format(cal.getTime()));

      // Add one day
      cal.add(Calendar.DATE, 1);
      System.out.println(sdf.format(cal.getTime()));

   }
}

Output:
   $ java IncrementDay
   2014-01-28 05:37:26
   2014-01-29 05:37:26

Monday, January 27, 2014

Example using the Calendar API

Source:
import java.util.*;
import java.text.*;
 
public class SimpleCalendar {
   public static void main(String[] args) {

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss"); 
      Calendar calendar = new GregorianCalendar(2014,5,28,12,00,15);
 
      int year       = calendar.get(Calendar.YEAR);
      int month      = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11
      int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); 
      int dayOfWeek  = calendar.get(Calendar.DAY_OF_WEEK);
      int dayOfYear  = calendar.get(Calendar.DAY_OF_YEAR);
      int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
      int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);
 
      int hour       = calendar.get(Calendar.HOUR);        // 12 hour clock
      int hourOfDay  = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
      int minute     = calendar.get(Calendar.MINUTE);
      int second     = calendar.get(Calendar.SECOND);
      int millisecond= calendar.get(Calendar.MILLISECOND);

      int am_pm       = calendar.get(Calendar.AM_PM); 
 

      System.out.println(sdf.format(calendar.getTime()));

      System.out.println("year \t\t: " + year);
      System.out.println("month \t\t: " + month);
      System.out.println("dayOfMonth \t: " + dayOfMonth);
      System.out.println("dayOfWeek \t: " + dayOfWeek);
      System.out.println("dayOfYear \t: " + dayOfYear);
      System.out.println("weekOfYear \t: " + weekOfYear);
      System.out.println("weekOfMonth \t: " + weekOfMonth);
 
      System.out.println("hour \t\t: " + hour);
      System.out.println("hourOfDay \t: " + hourOfDay);
      System.out.println("minute \t\t: " + minute);
      System.out.println("second \t\t: " + second);
      System.out.println("millisecond \t: " + millisecond);

      System.out.print("am_pm \t\t: " + am_pm + " ");
      if ( am_pm == Calendar.PM ) {
        System.out.println("(PM)");
      }
      if ( am_pm == Calendar.AM ) {
        System.out.println("(AM)");
      }
   }
}

Output:
   $ java SimpleCalendar
   2014 Jun 28 12:00:15
   year            : 2014
   month           : 5
   dayOfMonth      : 28
   dayOfWeek       : 7
   dayOfYear       : 179
   weekOfYear      : 26
   weekOfMonth     : 4
   hour            : 0
   hourOfDay       : 12
   minute          : 0
   second          : 15
   millisecond     : 0
   am_pm           : 1 (PM)

How do I display a date and time in different time zones?

Source:
import java.util.*;
import java.text.*;

public class DifferentDates {
   public static void main(String[] args) {

      TimeZone tz = TimeZone.getTimeZone("EST");
      Calendar cal = Calendar.getInstance(tz);
      cal.set(Calendar.MONTH, 11); //December
      cal.set(Calendar.DATE, 31);
      cal.set(Calendar.YEAR, 2013);
      cal.set(Calendar.HOUR,23);
      cal.set(Calendar.MINUTE,45);
      cal.set(Calendar.SECOND,52);

      Date date = cal.getTime();

      SimpleDateFormat sdf = new SimpleDateFormat("zzz yyyy-MM-dd HH:mm:ss"); 

      System.out.println(sdf.format(date));  

      sdf.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo")); 
      System.out.println(sdf.format(date));  

      sdf.setTimeZone(TimeZone.getTimeZone("Europe/Luxembourg")); 
      System.out.println(sdf.format(date));  

   }
}

Output:
   $ java DifferentDates 
   EST 2013-12-31 23:45:52
   JST 2014-01-01 13:45:52
   CET 2014-01-01 05:45:52

Sunday, January 26, 2014

How to convert a string to a long?

Source:
public class StringToLong {
   public static void main(String[] args) {

      String text = "123456789";

      // convert string to a long
      long value = Long.parseLong(text);

      System.out.println( value );

   }
}

Output:
   $ java StringToLong 
   123456789

How to print quotes in java?

Source:
public class PrintQuotes {

   public static void main(String[] args) {

      // Use an escape sequence \" or \'
      System.out.println("\"hello\" \'c\'");

   }
}

Output:
   $ java PrintQuotes 
   "hello" 'c'

How to use a string in switch case?

Source:
public class StringSwitch {

   public static void main(String[] args) {

      String str = "def";

      switch (str) {
         case "abc" : System.out.println("String case: abc");
                      break;
         case "def" : System.out.println("String case: def");
                      break;
         default:     System.out.println("Invalid String case");
      };

   }
}

Output:
   $ java StringSwitch 
   String case: def

How to convert a string to a double?

Source:
public class StringToDouble {
   public static void main(String[] args) {

      String text = "12.34";

      // convert string to double
      double value = Double.parseDouble(text);

      System.out.println( value );

      // just to make sure
      value = value + 11.11;
      System.out.println( value );

   }
}

Output:
   $ java StringToDouble 
   12.34
   23.45

How to generate a random String?

Source:
import java.util.Random;

public class RandomString {
   public static void main(String[] args) {

      String string = null;

      // Size of random string
      int length = 10;

      char[] text = new char[length];
      Random random = new Random();

      //All the characters available for random string
      String characters = "abcdefABCDEF12345";

      for (int i = 0; i < length; i++) {
         text[i] = characters.charAt(random.nextInt(characters.length()));
      }

      string = new String(text);
      System.out.println( string );

   }
}

Output:
   $ java RandomString 
   4BaADeBAce

How to convert a String to a Hexadecimal?

Source:
public class ConvertStringToHex {
   public static void main(String[] args) {

      String str = "123456789";
      System.out.println( "String: " + str );

      // Convert the String to an int
      int x = Integer.parseInt(str);
      System.out.println( "int: " + x );

      // Display as HEX number
      System.out.println( "hex: " + Integer.toHexString( x ) );
   }
}

Output:
   $ java ConvertStringToHex 
   String: 123456789
   int: 123456789
   hex: 75bcd15

How to remove line breaks from a file?

Source:
import java.io.*;

public class RemoveLineBreaks {

   public static void main(String[] args) {
      String content = "";
      try {
         FileInputStream is = new FileInputStream("file1.txt");
         BufferedReader br = new BufferedReader(new InputStreamReader(is));
         String str;
         while ((str = br.readLine()) != null)   {
            content = content + str + " ";
         }
         br.close();

         FileWriter fw = new FileWriter("file2.txt");
         BufferedWriter bw = new BufferedWriter(fw);
         bw.write(content);
         bw.close();

      } catch (Exception e) {
         System.out.println(e);
      }
   }
}

Output:
   $ cat file1.txt 
   First first line.
   Second first line.
   Third first line.

   $ cat file2.txt 
   First first line. Second first line. Third first line.

How to remove the last character from a string?

Source:
public class RemoveLastChar {
   public static void main(String[] args) {

      String str = "This is a string.Z";
      System.out.println(str);

      str = str.substring(0, str.length()-1);
      System.out.println(str);
   }
}

Output:
   $ java RemoveLastChar 
   This is a string.Z
   This is a string.

How to capitalize the first char of each word in a String?

Source:
import java.util.Arrays;

public class UpperCaseWords {
   public static void main(String[] args) {

      String str1 = "is this is a string with lower case letters?";
      String str2 = "";

      String[] words = str1.split("\\s");

      for(int i=0; i < words.length; i++) {
         char first = Character.toUpperCase(words[i].charAt(0));
         words[i] = first + words[i].substring(1);

         str2 = str2 + words[i];
         // no spaces at end of string
         if (i < words.length ) {
            str2 = str2 + " ";
         }
      }

      System.out.println(str1);
      System.out.println(str2);
   }
}

Output:
   $ java UpperCaseWords 
   is this is a string with lower case letters?
   Is This Is A String With Lower Case Letters? 

How to remove duplicate white spaces in a string?

Source:
public class RemoveDuplicates {
   public static void main(String[] args) {

      String s1 = "This   is      a    string with     spaces.";
      String s2 = s1.replaceAll("\\s+", " ");
      System.out.println(s1);
      System.out.println(s2);
   }
}

Output:
   $ java RemoveDuplicates 
   This   is      a    string with     spaces.
   This is a string with spaces.

How to convert Strings to and from UTF8 byte arrays?

Source:
public class UTF8Example {
   public static void main(String[] args) {

      String s1 = "This is a string";
      byte[] b = null;
      String s2 = null;

      try {
         //Convert from String to byte[]:
         b = s1.getBytes("UTF-8");

         //Convert from byte[] to String:
         s2 = new String(b, "UTF-8");
      } catch (Exception e) {
      }

      System.out.println(s2);
   }
}

Output:
   $ java UTF8Example 
   This is a string

How to convert comma separated String to ArrayList?

Source:
import java.util.*;

public class CommaArrayList {
   public static void main(String[] args) {

      String str = "Paul,John,George,Ringo";
      System.out.println("String: " + str);

      ArrayList<String> list = null;

      list = new ArrayList(Arrays.asList(str.split("\\s*,\\s*")));

      System.out.println("ArrayList: " + list);

   }
}

Output:
   $ java CommaArrayList 
   String: Paul,John,George,Ringo
   ArrayList: [Paul, John, George, Ringo]

Test if a string is not null and empty

Source:
public class EmptyString {
   public static void main(String[] args) {

      String str = new String();

      if( (str != null) && (str.isEmpty()) ) {
        System.out.println("str is not null and empty");
      } else {
        System.out.println("str is either null or not empty");
      }
   }
}

Output:
   $ java EmptyString 
   str is not null and empty

Convert an ArrayList to a String

Source:
import java.util.ArrayList;

public class ArrayListToString {
   public static void main(String[] args) {

      ArrayList<String> list = new ArrayList<String>();
      list.add("The");
      list.add("cat");
      list.add("in");
      list.add("the");
      list.add("hat");

      System.out.println("ArrayList: "+ list);

      String str = "";

      for (String s : list) {
         str = str + s + " ";
      }

      System.out.println("String: " + str);
   }
}

Output:
   $ java ArrayListToString 
  ArrayList: [The, cat, in, the, hat]
  String: The cat in the hat 

How do I count the number of occurrences of a char in a String?

Source:
public class CountChars {
   public static void main(String[] args) {

      String str = "a b a c a d a e a f a g a h";

      int count = 0;
      for (int i = 0; i < str.length(); i++) {
         if (str.charAt(i) == 'a') {
            count++;
         }
      }

      System.out.println("Total a count: " + count);
   }
}

Output:
   $ java CountChars 
   Total a count: 7

Left padding numbers with zeros

Source:
public class LeftPadding {
   public static void main(String[] args) {

      int n1 = 1;
      int n2 = 22;
      int n3 = 333;
      int n4 = 4444;

      // zero padding with length 5
      System.out.println( String.format("%05d", n1) );
      System.out.println( String.format("%05d", n2) );
      System.out.println( String.format("%05d", n3) );
      System.out.println( String.format("%05d", n4) );
   }
}

Output:
   $ java LeftPadding 
   00001
   00022
   00333
   04444

String to Date conversion

Source:
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Date;

public class ConvertStringToDate {
   public static void main(String[] args) {

      String string = "January 15, 2012";

      try {
         Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
         System.out.println(date);
      } catch (Exception e) {
      }

   }
}

Output:
   $ java ConvertStringToDate 
   Sun Jan 15 00:00:00 EST 2012

How to use java.String.format?

Source:
import java.util.Date;

public class FormatString {
   public static void main(String[] args) {

      String name = "Tom";
      int age = 100;
      Date date = new Date();
      float f = 1.2f;

      String s1 = String.format("Hello %s", name);
      System.out.println(s1);

      String s2 = String.format("The age %d is old", age);
      System.out.println(s2);

      String s3 = String.format("%s is %d years old", name, age);
      System.out.println(s3);

      System.out.printf("%.3f %n", f);

      String day = String.format("Today is %tD", date);
      System.out.println(day);
   }
}

Output:
   $ java FormatString 
   Hello Tom
   The age 100 is old
   Tom is 100 years old
   1.200 
   Today is 01/26/14

How to convert a string to int?

Source:
public class ConvertStringToInt {
   public static void main(String[] args) {

      String str = "123456";
      int x = Integer.parseInt(str);
 
      System.out.println("String: " + str);
      System.out.println("Type: " + str.getClass().getSimpleName());

      System.out.println();

      System.out.println("int: " + x);
      if (x == (int)x ) {
         System.out.println("Type: int");
      }
   }
}

Output:
   $ java ConvertStringToInt 
   String: 123456
   Type: String

   int: 123456
   Type: int

How to check if a string contains a substring?

Source:
public class TestSubString {
   public static void main(String[] args) {
      String str = "Do you like green eggs and ham";
      System.out.println(str);

      // indexOf() returns the index within this string of the first 
      // occurrence of the specified substring.
      int i = str.indexOf("green eggs");
      System.out.println("Index: " + i );

      // indexOf() returns -1 if not found
      i = str.indexOf("yellow eggs");
      System.out.println("Index: " + i );
   }
}

Output:
   $ java TestSubString 
   Do you like green eggs and ham
   Index: 12
   Index: -1

How to remove leading and trailing whitespace in a string.

Source:
public class RemoveTest {
   public static void main(String[] args) {
      String s1 = "    This is a string     ";

      System.out.println(s1);
      System.out.println("length: " + s1.length());

      //  trim() returns a copy of the string, with leading 
      //  and trailing whitespace omitted.
      String s2 = s1.trim();

      System.out.println(s2);
      System.out.println("length: " + s2.length());

   }
}

Output:
   $ java RemoveTest 
       This is a string     
   length: 25
   This is a string
   length: 16

How to determine the length of a string?

Source:
public class StringLength {
   public static void main(String[] args) {
      String str = "abcdefghijflmnopqrstuvwxyz";
      System.out.println(str);
      System.out.println("length: " + str.length());
   }
}

Output:
   $ java StringLength 
   abcdefghijflmnopqrstuvwxyz
   length: 26

Concatenating Strings in Java

Source:
public class ConcatenateString {

   public static void main(String args[]) {
      String string1 = "abcdefghijklm";
      String string2 = "nopqrstuvwxyz";
      String string3 = string1.concat(string2);

      System.out.println("string1: " + string1);
      System.out.println("string2: " + string2);
      System.out.println("string3: " + string3);
   }
}

Output:
   $ java ConcatenateString 
   string1: abcdefghijklm
   string2: nopqrstuvwxyz
   string3: abcdefghijklmnopqrstuvwxyz

How to convert a string into upper case?

Source:
public class StringToUpperCase {
   public static void main(String[] args) {
      String str = "abcdefghijflmnopqrstuvwxyz";
      String upper = str.toUpperCase();
      System.out.println(str);
      System.out.println(upper);
   }
}

Output:
   $ java StringToUpperCase 
   abcdefghijflmnopqrstuvwxyz
   ABCDEFGHIJFLMNOPQRSTUVWXYZ

Iterate over all the chars in a String

Source:
public class IterateChars {
   public static void main(String[] args) {
      String str = "abcdefg";
      int n=0;
      for (char c : str.toCharArray()) {
         System.out.println("pos " + n++ + " : " + c);
      }
   }
}

Output:
   $ java IterateChars 
   pos 0 : a
   pos 1 : b
   pos 2 : c
   pos 3 : d
   pos 4 : e
   pos 5 : f
   pos 6 : g

How to determine the Unicode code of a String?

Source:
public class StringUniCode {
   public static void main(String args[]){
      String str="abcd EFGH 1234";
      System.out.println( str );
      for (int i=0; i<str.length(); i++ ) {
         System.out.println("Unicode for " + str.charAt(i) + " : " + str.codePointAt(i));
      }
   }
}

Output:
   $ java StringUniCode 
   abcd EFGH 1234
   Unicode for a : 97
   Unicode for b : 98
   Unicode for c : 99
   Unicode for d : 100
   Unicode for   : 32
   Unicode for E : 69
   Unicode for F : 70
   Unicode for G : 71
   Unicode for H : 72
   Unicode for   : 32
   Unicode for 1 : 49
   Unicode for 2 : 50
   Unicode for 3 : 51
   Unicode for 4 : 52


Another example can be found here: http://javacodex.com/Strings/Get-Unicode-Values-Of-A-String

How to replace a substring inside a string?

Source:
public class ReplaceSubString {
   public static void main(String args[]){
      String str="abcdefghijklmnopqrstuvwxyz";
      System.out.println( str );
      System.out.println( str.replace( 'q','Q' ) );
      System.out.println( str.replace( "abc","ABC" ) );
      System.out.println( str.replaceFirst("jkl", "-K-") );
      System.out.println( str.replaceAll("lmno", "XXXX") );
   }
}

Output:
   $ java ReplaceSubString 
   abcdefghijklmnopqrstuvwxyz
   abcdefghijklmnopQrstuvwxyz
   ABCdefghijklmnopqrstuvwxyz
   abcdefghi-K-mnopqrstuvwxyz
   abcdefghijkXXXXpqrstuvwxyz

How to remove a character from a string ?

Source:
public class RemoveCharacter {
   public static void main(String args[]) {
      String str = "This is a java string.";
      System.out.println(str);

      // Remove 3d character
      System.out.println(str.substring(0, 3) + str.substring(3 + 1));
   }
}

Output:
   $ java RemoveCharacter 
   This is a java string.
   Thi is a java string.

How to reverse a String?

Source:
public class StringReverse {
   public static void main(String[] args){
      String string="abcdefg";
      String reverse = new StringBuffer(string).reverse().toString();
      System.out.println("String before reverse: " + string);
      System.out.println("String after reverse : " + reverse);
   }
}

Output:
   $ java StringReverse 
   String before reverse: abcdefg
   String after reverse:  gfedcba

How to compare two strings ?

Source:
public class CompareStrings { 
  public static void main(String[] args) { 
    String string1 = "This is a string."; 
    String string2 = "This is a string."; 
    String string3 = "This is a different string."; 
 
    // if 0 then strings are the same
    System.out.print("string1.compareTo(string2) :");
    System.out.println(string1.compareTo(string2));

    System.out.print("string1.compareTo(string3) :");
    System.out.println(string1.compareTo(string3));

    // if true then strings are the same
    System.out.print("string1.equals(string2) :");
    System.out.println(string1.equals(string2));

    System.out.print("string1.equals(string3) :");
    System.out.println(string1.equals(string3));
  } 
}


Output:
   $ java CompareStrings 
   string1.compareTo(string2) :0
   string1.compareTo(string3) :15
   string1.equals(string2) :true
   string1.equals(string3) :false

Saturday, January 25, 2014

Set Posix File Permissions

Source:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Set;

public class FilePermissions {

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

      //using PosixFilePermission to set file permissions 777
      Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
      //add owners permission
      perms.add(PosixFilePermission.OWNER_READ);
      perms.add(PosixFilePermission.OWNER_WRITE);
      perms.add(PosixFilePermission.OWNER_EXECUTE);
      //add group permissions
      perms.add(PosixFilePermission.GROUP_READ);
      perms.add(PosixFilePermission.GROUP_WRITE);
      perms.add(PosixFilePermission.GROUP_EXECUTE);
      //add others permissions
      perms.add(PosixFilePermission.OTHERS_READ);
      perms.add(PosixFilePermission.OTHERS_WRITE);
      perms.add(PosixFilePermission.OTHERS_EXECUTE);

      Files.setPosixFilePermissions(Paths.get("/tmp/file.txt"), perms);
   }
}

Output:
   $ ls -l /tmp/file.txt
   -r--r--r-- 1 dennis dennis 0 Jan 25 16:44 /tmp/file.txt

   $ java FilePermissions 

   $ ls -l /tmp/file.txt
   -rwxrwxrwx 1 dennis dennis 0 Jan 25 16:44 /tmp/file.txt

Split a String with StringTokenizer

Source:
import java.util.StringTokenizer;

public class SplitString {
   public static void main(String[] args) {

      String str = "This is string 1:Another String:abcdef:TUVWXYZ";

      StringTokenizer st = new StringTokenizer(str, ":");

      while (st.hasMoreElements()) {
         System.out.println(st.nextElement());
      }
   }
}

Output:
   $ java SplitString 
   This is string 1
   Another String
   abcdef
   TUVWXYZ

How to split a String

Source:
public class SplitString {
   public static void main(String[] args) {

      String string = "ABCDEF-GHIJKL";
      String[] parts = string.split("-");
      String part1 = parts[0];
      String part2 = parts[1];
      System.out.println("part1: " + part1 );
      System.out.println("part2: " + part2 );

   }
}

Output:
   $ java SplitString 
   part1: ABCDEF
   part2: GHIJKL

Sorting an ArrayList

Source:
import java.util.ArrayList;
import java.util.Collections;
 
public class ArrayListSort { 
  public static void main(String[] args) { 
 
    ArrayList<String> list = new ArrayList<String>();
    list.add("John");
    list.add("Ringo");
    list.add("George");
    list.add("Paul");
 
    for(String str: list){
      System.out.println("Before: " + str);
    }
 
    Collections.sort(list);
 
    for(String str: list){
      System.out.println("After: " + str);
    }
 
  } 
}

Output:
   # java ArrayListSort 
   Before: John
   Before: Ringo
   Before: George
   Before: Paul
   After: George
   After: John
   After: Paul
   After: Ringo

Selection Sort

Source:
public class SelectionSort {
 
   public static void main(String args[]) {
 
      int[] array = {1,10,2,9,3,8,4,7,5,6};
      System.out.print("Start : " );     
      for(int x = 0; x < array.length; x++) {
         System.out.print( " " + array[x]);     
      }
      System.out.println(" "); 
 
      int first; 
      int tmp; 
      int count=1; 
      for ( int i=array.length-1; i>0; i--,count++ ) {
         first = 0;
         for(int j=1; j<=i; j++) {
            if( array[j] < array[first] )  
               first = j;
         }
         tmp = array[first]; 
         array[first] = array[i];
         array[i] = tmp; 
 
      System.out.print("Pass " + count + ": " );
      for(int x = 0; x < array.length; x++) {
         System.out.print( " " + array[x]);
      }
      System.out.println(" ");
 
 
      } 
   }
}

Output:
   # java SelectionSort 
   Start :  1 10 2 9 3 8 4 7 5 6 
   Pass 1:  6 10 2 9 3 8 4 7 5 1 
   Pass 2:  6 10 5 9 3 8 4 7 2 1 
   Pass 3:  6 10 5 9 7 8 4 3 2 1 
   Pass 4:  6 10 5 9 7 8 4 3 2 1 
   Pass 5:  6 10 8 9 7 5 4 3 2 1 
   Pass 6:  7 10 8 9 6 5 4 3 2 1 
   Pass 7:  9 10 8 7 6 5 4 3 2 1 
   Pass 8:  9 10 8 7 6 5 4 3 2 1 
   Pass 9:  10 9 8 7 6 5 4 3 2 1 

Quick Sort

Source:
import java.io.*;
import java.util.*;
 
public class QuickSort {
   public static void swap (int A[], int x, int y) {
      int temp = A[x];
      A[x] = A[y];
      A[y] = temp;
   }
 
   public static int partition(int A[], int f, int l) {
      int pivot = A[f];
      while (f < l) {
         while (A[f] < pivot) f++;
         while (A[l] > pivot) l--;
         swap (A, f, l);
      }
      return f;
   }
 
   public static void Quicksort(int A[], int f, int l) {
      if (f >= l) return;
      int pivot_index = partition(A, f, l);
      Quicksort(A, f, pivot_index);
      Quicksort(A, pivot_index+1, l);
   }
 
   public static void main(String argv[]) {
      int []numbers={55,2,93,1,23,10,66,12,7,54,3};
      System.out.println(Arrays.toString(numbers));
      Quicksort(numbers, 0, numbers.length-1);
      System.out.println(Arrays.toString(numbers));
   }
}

Output:
   $ java QuickSort 
   [55, 2, 93, 1, 23, 10, 66, 12, 7, 54, 3]
   [1, 2, 3, 7, 10, 12, 23, 54, 55, 66, 93]

Insertion Sort

Source:
public class InsertionSort {
 
   public static void main(String args[]) {
      int[] array = {9,7,5,3,1,8,6,4,2,0};
 
      System.out.print("Before:  " );
      for(int x: array) { 
         System.out.print(x + " ");
      }
      System.out.println(" ");
 
      int tmp;
      for (int i = 1; i < array.length; i++) {
         for(int j = i ; j > 0 ; j--) {
            if(array[j] < array[j-1]) {
               tmp = array[j];
               array[j] = array[j-1];
               array[j-1] = tmp;
            }
         }
         System.out.print("pass " + i + ":  " );
         for(int x: array) {
            System.out.print(x + " ");
         }
         System.out.println(" ");
      }
      System.out.println("Done");
   }
}

Output:
   # java InsertionSort 
   Before:  9 7 5 3 1 8 6 4 2 0  
   pass 1:  7 9 5 3 1 8 6 4 2 0  
   pass 2:  5 7 9 3 1 8 6 4 2 0  
   pass 3:  3 5 7 9 1 8 6 4 2 0  
   pass 4:  1 3 5 7 9 8 6 4 2 0  
   pass 5:  1 3 5 7 8 9 6 4 2 0  
   pass 6:  1 3 5 6 7 8 9 4 2 0  
   pass 7:  1 3 4 5 6 7 8 9 2 0  
   pass 8:  1 2 3 4 5 6 7 8 9 0  
   pass 9:  0 1 2 3 4 5 6 7 8 9  
   Done

Heap Sort

Source:
import java.util.*;
 
public class HeapSort {
 
   private static int[] a;
   private static int n;
   private static int left;
   private static int right;
   private static int largest;
 
 
   public static void buildheap(int []a) {
      n = a.length-1;
      for(int i=n/2; i>=0; i--){
         maxheap(a,i);
      }
   }
 
   public static void maxheap(int[] a, int i) { 
      left = 2*i;
      right = 2*i+1;
 
      if(left <= n && a[left] > a[i]){
         largest=left;
      } else {
         largest=i;
      }
 
      if(right <= n && a[right] > a[largest]) {
         largest=right;
      }
      if(largest!=i) {
         exchange(i, largest);
         maxheap(a, largest);
      }
   }
 
   public static void exchange(int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t; 
   }
 
   public static void sort(int[] myarray) {
      a = myarray;
      buildheap(a);
      for(int i=n; i>0; i--) {
         exchange(0, i);
         n=n-1;
         maxheap(a, 0);
      }
   }
 
   public static void main(String[] args) {
      int []numbers={55,2,93,1,23,10,66,12,7,54,3};
      System.out.println(Arrays.toString(numbers));
      sort(numbers);
      System.out.println(Arrays.toString(numbers));
   }
}

Output:
   $ java HeapSort 
   [55, 2, 93, 1, 23, 10, 66, 12, 7, 54, 3]
   [1, 2, 3, 7, 10, 12, 23, 54, 55, 66, 93]

Exchange Sort

Source:
public class ExchangeSort {
 
   public static void main(String args[]) {
 
      int[] array = {1,10,2,9,3,8,4,7,5,6};
      System.out.print("Start : " );     
      for(int x = 0; x < array.length; x++) {
         System.out.print( " " + array[x]);     
      }
      System.out.println(" "); 
 
      int temp; 
      for (int i=0; i < array.length-1; i++) {
         for (int j = i+1; j<array.length; j++) {
            if(array[ i ] < array[ j ]) {
               temp = array[i]; 
               array[i] = array[j];
               array[j] = temp; 
            }           
         }
 
      System.out.print("loop " + i + ": ");
      for(int x = 0; x < array.length; x++) {
         System.out.print( " " + array[x]);
      }
      System.out.println(" ");
      } 
   }
}

Output:
   # java ExchangeSort 
   Start :  1 10 2 9 3 8 4 7 5 6 
   loop 0:  10 1 2 9 3 8 4 7 5 6 
   loop 1:  10 9 1 2 3 8 4 7 5 6 
   loop 2:  10 9 8 1 2 3 4 7 5 6 
   loop 3:  10 9 8 7 1 2 3 4 5 6 
   loop 4:  10 9 8 7 6 1 2 3 4 5 
   loop 5:  10 9 8 7 6 5 1 2 3 4 
   loop 6:  10 9 8 7 6 5 4 1 2 3 
   loop 7:  10 9 8 7 6 5 4 3 1 2 
   loop 8:  10 9 8 7 6 5 4 3 2 1 

Bubble Sort

Source:
class BubbleSort {
 
   public static void main(String []args) {
 
      int[] array = {10,8,6,4,2,9,7,5,3,1};
      int right_border = array.length - 1;
 
      System.out.print("Before sort: " );     
      for(int x = 0; x < array.length; x++) {
         System.out.print( " " + array[x]);     
      }
      System.out.println(" ");     
 
      int remaining = array.length - 1;
      for(int x = 0; x < (array.length-1); x++) {
         for(int y = 0; y < (remaining); y++) {
            int tmp;
            if ( array[y] > array[y+1] ) {
              tmp =  array[y+1]; 
              array[y+1] = array[y];
              array[y] = tmp;
            }
         }
         remaining--;
      }
 
      System.out.print("After sort: " );     
      for(int x = 0; x < array.length; x++) {
         System.out.print( " " + array[x]);     
      }
      System.out.println(" ");     
   }
}

Output:
   # java BubbleSort 
   Before sort:  10 8 6 4 2 9 7 5 3 1 
   After sort:  1 2 3 4 5 6 7 8 9 10 

Bucket Sort

Source:
import java.util.*;
 
public class BucketSort{
 
   public static void sort(int[] a, int maxVal) {
      int [] bucket=new int[maxVal+1];
 
      for (int i=0; i<bucket.length; i++) {
         bucket[i]=0;
      }
 
      for (int i=0; i<a.length; i++) {
         bucket[a[i]]++;
      }
 
      int outPos=0;
      for (int i=0; i<bucket.length; i++) {
         for (int j=0; j<bucket[i]; j++) {
            a[outPos++]=i;
         }
      }
   }
 
 
   public static void main(String[] args) {
      int maxVal=5;
      int [] data= {5,3,0,2,4,1,0,5,2,3,1,4}; 
 
      System.out.println("Before: " + Arrays.toString(data));
      sort(data,maxVal);
      System.out.println("After:  " + Arrays.toString(data));
   }
}

Output:
   $ java BucketSort  
   Before: [5, 3, 0, 2, 4, 1, 0, 5, 2, 3, 1, 4]
   After:  [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]

How do I convert a String to an InputStream in Java?

Source:
public class Example {
   public static void main(String[] args) {

      String mystring = "This is an example";

      // Must be caught or declared to be thrown 
      try {
         InputStream stream = new ByteArrayInputStream(mystring.getBytes("UTF-8"));
      } catch (Exception e) {
      }
   }
}

Blog Archive