Skip to main content

Programmer Reference Material

    Java was originally developed by James Gosling at Sun Microsystems (now
    merged with Oracle Corporation). Java applications are compiled to
    bytecode (a .class file) that can run on any Java Virtual Machine (JVM)
    regardless of the underlying computer architecture. The language first
    appeared in 1995 and is now in version 7.

    Java source code is saved in .java files. Files consist of class
    definitions. A .java file can have multiple class definitions (where a
    .class file will be generated for each), but only one class may be
    marked public. If there is a public class in the .java file, the file-
    name of the .java file must exactly match the name of the public class
    within it.

    After you get the JDK installed and included in the Path environment
    variable, you can compile your programs using:

        javac myFile.java

    And you can run them using:

        java myFile

    The remainder of this file includes code snippets that show how to
    accomplish common programming tasks, using Java. Each code snippet is an
    independent class definition, so you could cut and paste all of these into
    a single .java file. Once compiled, you will have individual .class
    files for each numbered Review. You can then run these by calling
    'java Review_01' substituting the number of the programming task you'd
    like to see.

class Review_01 {
   
    // Basic output.

    public static void main(String[] args) {

        System.out.println("\n Hello World!");
    }
}

class Review_02 {
   
    // Display today's date and time.

    public static void main(String[] args) {

        java.util.Calendar today = java.util.Calendar.getInstance();

        System.out.println("\n Today's date and time: " + today.getTime());
    }
}

class Review_03 {

    // Array datatype (including iteration).

    public static void main(String[] args) {

        int[] m = new int[3];

        m[0] = 128;
        m[1] = 97;
        m[2] = 235;

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

            System.out.println("\n Element " + i + " = " + m[i]);
        }
    }
}

class Review_04 {
   
    // Display all command line arguments given.

    public static void main(String[] args) {

        if (args.length == 0) {

            System.out.println("\n Provide some command line arguments.");

        } else {
       
            for (int i = 0; i < args.length; i++) {

           
                System.out.println("\n Argument " + i + " = " + args[i]);
            }
        }   
    }
}

class Review_05 {
   
    // Get user input (byte level).
  
    // java.io.InputStream.read() returns -1 on EOF
    // ASCII codes range from 0 to 255 (0 to 127 standard)

    public static void main(String[] args) {

        System.out.print("\n Enter something here: ");

        try {
       
            int n = System.in.read();

            System.out.println("\n First character is " + (char)n);
            System.out.println(" Decimal value of this character is " + n);

        } catch (java.io.IOException ioe) {

            System.out.println("\n Error reading input.");
        }
    }
}

class Review_06 {

    // Use of a standard library container (including iteration).
  
    public static void main(String[] args) {

       java.util.ArrayList<String> list = null;

       list = new java.util.ArrayList<String>();

       list.add("hearts");
       list.add("diamonds");
       list.add("clubs");
       list.add("spades");

       java.util.Iterator itr = list.listIterator();

       while (itr.hasNext()) {

          System.out.println("\n " + itr.next());
       }
    }
}

class Review_07 {

    // Sort a standard library container.
      
    public static void main(String[] args) {

        java.util.ArrayList<String> list = null;

        list = new java.util.ArrayList<String>();

        list.add("hearts");
        list.add("diamonds");
        list.add("clubs");
        list.add("spades");

        // The Java 5 String class implements the Comparable interface,
        // overriding the compareTo() method.
        java.util.Collections.sort(list);

        java.util.Iterator itr = list.listIterator();

        while (itr.hasNext()) {

           System.out.println("\n " + itr.next());
        }
    }
}

class Review_08 {
   
    // Get user input (line level).
  
    // java.io.BufferedReader.readLine() returns null on EOF.

    public static void main(String[] args) {

        java.io.InputStreamReader isr = null;
        isr = new java.io.InputStreamReader(System.in);
       
        java.io.BufferedReader br = null;
        br = new java.io.BufferedReader(isr);

        System.out.print("\n Enter something here: ");

        try {
       
            String s = br.readLine();

            System.out.println("\n Test entered: " + s);

            System.out.println("\n Number of characters: " + s.length());

        } catch (java.io.IOException ioe) {

            System.out.println("\n Error reading input.");
        }
    }
}

class Review_09 {

    // Random numbers.
  
    public static void main(String[] args) {

       int r = (int)(java.lang.Math.random() * 10);
       r++;
       System.out.print("\n A random number (1 to 10 inclusive): ");
       System.out.println(r);

       long seedValue = 334345;
       java.util.Random rand = new java.util.Random(seedValue);
       r = rand.nextInt(10);
       r++;
       System.out.print("\n A random number (1 to 10 inclusive): ");
       System.out.println(r);
    }
}

class Review_10 {

    // Primitive types, range limits.
   
    public static void main(String[] args) {
  
        System.out.println("\n Integers are represented using " +
                Integer.SIZE + " bits, in two's compliment form.");
        System.out.println("\n Integer range: " +
                Integer.MIN_VALUE + " to " +
                Integer.MAX_VALUE + ".");
  
        System.out.println("\n Doubles are represented using " +
                Double.SIZE + " bits, in two's compliment form.");
        System.out.println("\n Double range: " +
                Double.MIN_VALUE + " to " +
                Double.MAX_VALUE + ".");

        System.out.println("\n Longs are represented using " +
                Long.SIZE + " bits, in two's compliment form.");
        System.out.println("\n Long range: " +
                Long.MIN_VALUE + " to " +
                Long.MAX_VALUE + ".");
    }
}

class Review_11 {

    // Format big numbers using commas.
   
    public static void main(String[] args) {

       java.text.NumberFormat nf = null;
       nf = java.text.NumberFormat.getIntegerInstance(java.util.Locale.US);

       System.out.println("\n Maximum value of Long primitive: " +
              nf.format(Long.MAX_VALUE));
    }
}

class Review_12 {

    // Convert string to usable integer for calculations.
  
    public static void main(String[] args) {
   
        String good = "2342";
        String bad = "two";

        try {

            System.out.println("\n First value: " + Integer.parseInt(good));

            System.out.println("\n Second value: " + Integer.parseInt(bad));

        } catch (NumberFormatException nfe) {

            System.out.println("\n Invalid string representation of a number.");
        }
    }
}

class Review_13 {

    // Timers.
   
    public static void main(String[] args) {

       java.util.Calendar startTime = java.util.Calendar.getInstance();
      
       for (int i = 0; i < 50000000; i++) {

          ;
       }

       java.util.Calendar endTime = java.util.Calendar.getInstance();

       long runTime = endTime.getTimeInMillis() - startTime.getTimeInMillis();
      
       System.out.println("\n Elapsed time for loop: " + runTime + " ms.");
    }
}

class Review_14 {

    // Basic inheritance and polymorphism. Call a subclass method on a
    // collection of superclass references.
  
    public static void main(String[] args) {

        class BaseGamePiece {

            public void name() {

                System.out.println("\n Name is: BaseGamePiece");
            }
        }

        class ShipGamePiece extends BaseGamePiece {

            public void name() {

                System.out.println("\n Name is: ShipGamePiece");
            }
        }

        class PersonGamePiece extends BaseGamePiece {

            public void name() {

                System.out.println("\n Name is: PersonGamePiece");
            }
        }
  
        java.util.ArrayList<BaseGamePiece> pieceSet = null;
        pieceSet = new java.util.ArrayList<BaseGamePiece>();

        pieceSet.add(new ShipGamePiece());
        pieceSet.add(new PersonGamePiece());
        pieceSet.add(new BaseGamePiece());

        java.util.Iterator itr = pieceSet.listIterator();
        while (itr.hasNext()) {

            BaseGamePiece bgp = (BaseGamePiece)itr.next();
            bgp.name();
        }
    }
}

class Review_15 {

    // Save text data to an output file.
  
    public static void main(String[] args) {
      
        java.io.File f = null;
        java.io.FileWriter fw = null;
        java.io.BufferedWriter bw = null;

        try {

            f = new java.io.File("data.txt");
            fw = new java.io.FileWriter(f);
            bw = new java.io.BufferedWriter(fw);

            bw.write("clubs,hearts,spades,diamonds\n");
            bw.write("ace,jack,king,queen\n");
            bw.flush();
            bw.write("four,three,two,one\n");

            bw.close();

            System.out.println("\n Output file created.");

        } catch (java.io.IOException ioe) {

            ioe.printStackTrace();
        }
    }
}

class Review_16 {

    // Tokenize a string given a token character.
   
    public static void main(String[] args) {

       String original = "clubs,hearts,spades,diamonds";

       String[] t = original.split(",");

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

           System.out.println("\n " + t[i]);
       }
    }
}
   
class Review_17 {

    // Read text data from a file.
  
    public static void main(String[] args) {
      
        java.io.File f = null;
        java.io.FileReader fr = null;
        java.io.BufferedReader br = null;

        try {

            f = new java.io.File("data.txt");
            fr = new java.io.FileReader(f);
            br = new java.io.BufferedReader(fr);

            String inputLine = br.readLine();

            while (inputLine != null) {

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

                inputLine = br.readLine();
            }

            br.close();

        } catch (java.io.IOException ioe) {

            ioe.printStackTrace();
        }
    }
}

class Review_18 {

    // Sorting user-defined objects.
  
    public static void main(String[] args) {

        class GamePiece {

            private int id;

            public GamePiece() {

                id = (int)(Math.random() * 100);
            }

            public int getId() {

                return id;
            }
        }

        class GamePieceCompare implements java.util.Comparator<GamePiece> {

            public int compare(GamePiece a, GamePiece b) {

                if (a.getId() > b.getId()) {

                    return 1;

                } else if (a.getId() < b.getId()) {

                    return -1;

                } else {

                    return 0;
                }
            }
        }
       
        java.util.LinkedList<GamePiece> gameSet = null;
        gameSet = new java.util.LinkedList<GamePiece>();

        gameSet.add(new GamePiece());
        gameSet.add(new GamePiece());
        gameSet.add(new GamePiece());
        gameSet.add(new GamePiece());
        gameSet.add(new GamePiece());

        java.util.Collections.sort(gameSet, new GamePieceCompare());

        java.util.Iterator itr = gameSet.listIterator();
       
        while (itr.hasNext()) {

            System.out.println("\n Piece " + ((GamePiece)itr.next()).getId());
        }
    }
}

class Review_19 {

    // Convert a string to a date object (date only).

    public static void main(String[] args) {

        String birthday = "03/25/1973";

        java.text.DateFormat df = new java.text.SimpleDateFormat("MM/dd/yyyy");

        try {

            java.util.Date bd = (java.util.Date)df.parse(birthday);

            System.out.println("\n Birthday: " + bd);

        } catch (java.text.ParseException pe) {

            pe.printStackTrace();
        }
    }
}

class Review_20 {

    // Calculate the number of days between two date objects.
   
    public static void main(String[] args) {

       java.util.Date a = new java.util.Date();
       java.util.Date b = new java.util.Date();

       b.setTime(9823475234L); // number of ms since Epoch

       System.out.println("\n Comparing " + a + " and " + b + ".");
       long msDiff = a.getTime() - b.getTime();

       long dayDiff = (long)(msDiff / 1000.0 / 60.0 / 60.0 / 24.0);
       System.out.println("\n This is a difference of " + dayDiff + " days.");
    }
}

class Review_21 {

    // Convert a string to a date object (time of day only).
   
    public static void main(String[] args) {

        String time = "18:42";

        java.text.DateFormat df = new java.text.SimpleDateFormat("hh:mm");

        try {

            java.util.Date bd = (java.util.Date)df.parse(time);

            System.out.println("\n Time: " + bd);

        } catch (java.text.ParseException pe) {

            pe.printStackTrace();
        }
    }
}

class Review_22 {

    // Calculate the number of hours between two date objects (time only).
  
    public static void main(String[] args) {

       java.text.DateFormat df = new java.text.SimpleDateFormat("hh:mm");

       try {
       
           java.util.Date a = (java.util.Date)df.parse("08:35");
           java.util.Date b = (java.util.Date)df.parse("13:36");

           System.out.println("\n Comparing " + a + " and " + b + ".");
           long msDiff = b.getTime() - a.getTime();

           long hourDiff = (long)(msDiff / 1000.0 / 60.0 / 60.0);
           System.out.println("\n This is a difference of " + hourDiff + " hours.");
      
       } catch (java.text.ParseException pe) {

           pe.printStackTrace();
       }
    }
}

class Review_23 {

    // Find the absolute value of a number

    public static void main(String[] args) {

        System.out.print(" The absolute value of -12 is ");

        int x = Math.abs(-12);

        System.out.println(x);
    }
}

class Review_24 {

    // Find the maximum and minimum values of an array

    public static void main(String[] args) {

        int[] mylist = {3, 56, 23, 11, 54, -5, 23, 16, 0, 1};

        int maximum = -1000;
        int minimum = 1000;

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

            maximum = Math.max(maximum, mylist[i]);
            minimum = Math.min(minimum, mylist[i]);
        }

        System.out.println(" Maximum value is " + maximum);
        System.out.println(" Minimum value is " + minimum);
    }
}

class Review_25 {

    // Sort a primitive array

    public static void main(String[] args) {

        int[] mylist = {3, 56, 23, 11, 54, -5, 23, 16, 0, 1};

        java.util.Arrays.sort(mylist);

        System.out.print(" My List = (");

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

            System.out.print(mylist[i] + " ");
        }

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

class Review_26 {

    // Parse a string based on a specific token, using StringTokenizer.
    // Literally cuts the token from the string in array form.
  
    public static void main(String[] args) {

       String s = "This is a string , with three parts, split up";

       java.util.StringTokenizer st = new java.util.StringTokenizer(s, ",");

       while (st.hasMoreElements()) {

           System.out.println(" *" + st.nextElement() + "*");
       }

       st = new java.util.StringTokenizer(s, " ");

       while (st.hasMoreElements()) {

           System.out.println(" *" + st.nextElement() + "*");
       }
    }
}

class Review_27 {

    // Use binary search to search a primitive array for a primitive value.
    // Return value is index starting at 1.
   
    public static void main(String[] args) {

        int[] mylist = {3, 56, 23, 11, 54, -5, 23, 16, 0, 1};

        java.util.Arrays.sort(mylist);

        System.out.println(" Result of searching for 12: INDEX = "
                + java.util.Arrays.binarySearch(mylist, 12));
       
        System.out.println(" Result of searching for 23: INDEX = "
                + java.util.Arrays.binarySearch(mylist, 23));
    }
}

class Review_28 {

    // Use TreeSet to collect items without duplicates, for very fast search,
    // and for sorting on the fly.

    public static void main(String[] args) {

        java.util.TreeSet<String> ts = new java.util.TreeSet<String>();

        ts.add("j");
        ts.add("g");
        ts.add("b");
        ts.add("h");
        ts.add("g");
        ts.add("b");
        ts.add("h");
        ts.add("a");
        ts.add("z");

        java.util.Iterator itr = ts.iterator();
        // java.util.Iterator itr = ts.descendingIterator();
        while (itr.hasNext()) {
   
            String s = (String)itr.next();
   
            System.out.println(s);
        }
   
        System.out.println(" First item is " + ts.first());
        System.out.println(" Last item is " + ts.last());
        System.out.println(" Set contains 'a': " + ts.contains("a"));
        System.out.println(" Set contains 'w': " + ts.contains("w"));
   
        ts.remove("a");
        System.out.println(" First item now is " + ts.first());
   
        System.out.println(" There are now a total of " + ts.size()
                + " items in this set.");
    }
}   

class Review_29 {

    // Use TreeMap as an array where keys can be anything, not just unsigned
    // integers. This is useful to associate some additional information with
    // and already established list/set. Also useful is the ability to use
    // integers as keys, like in a normal array, but not bound to being
    // sequential.

    public static void main(String[] args) {

        java.util.TreeMap<Integer, String> tm
            = new java.util.TreeMap<Integer, String>();

        tm.put(4, "John Doe");
        tm.put(2834823, "Ralph Smith");
        tm.put(1000, "Jane Baker");
        tm.put(2, "Tom Smith");
        tm.put(34958, "Todd Hall");

        java.util.Set entries = tm.entrySet();

        java.util.Iterator itr = entries.iterator();

        while (itr.hasNext()) {

            java.util.Map.Entry entry = (java.util.Map.Entry)itr.next();

            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        System.out.println(" Map contains '4': " + tm.containsKey(4));
        System.out.println(" Map contains 'Todd Hall': "
                + tm.containsValue("Todd Hall"));
    }
}

class Review_30 {

    // How to use 2D arrays.
    // grid[col][row]
   
    public static void main(String[] args) {

        int[][] grid = new int[4][3];

        int c,r;
        int counter = 1;
        for (r = 0; r < 3; r++) {
            for (c = 0; c < 4; c++) {
                grid[c][r] = counter;
                counter++;
            }
        }

        System.out.println(" Item at 2,1 is: " + grid[2][1]);
        System.out.println();

        for (r = 0; r < 3; r++) {
            for (c = 0; c < 4; c++) {
                System.out.print(" " + grid[c][r]);
            }
            System.out.println();
        }
    }
}

class Review_31 {

    // How to use a Stack data structure (from Java Standard Library)
    //
    // There are 5 main methods:
    //    1. push(E)
    //    2. E <-- peek()     *does not remove element
    //    3. E <-- pop()      *removes element
    //    4. n <-- search(E)  *returns the 1-based index from top, or -1
    //    5. true/false <-- isEmpty()
    //
    //    * pop() may return java.util.EmptyStackException
    //
    //    The below code will return:
    //   
    //        peek() returns: sentence
    //        isEmpty() returns: false
    //        search('idol') returns: -1
    //        search('full') returns: 2
    //        search('is') returns: 4
    //        search('not') returns: -1
    //        pop() returned: sentence
    //        pop() returned: full
    //        pop() returned: a
    //        pop() returned: is
    //        pop() returned: This
    //        Exception: java.util.EmptyStackException   
   
    public static void main(String[] args) {

        java.util.Stack<String> stack = new java.util.Stack<String>();

        stack.push("This");
        stack.push("is");
        stack.push("a");
        stack.push("full");
        stack.push("sentence");

        System.out.println(" peek() returns: " + stack.peek());
        System.out.println(" isEmpty() returns: " + stack.isEmpty());
        System.out.println(" search('idol') returns: " + stack.search("idol"));
        System.out.println(" search('full') returns: " + stack.search("full"));
        System.out.println(" search('is') returns: " + stack.search("is"));
        System.out.println(" search('not') returns: " + stack.search("not"));

        String returnValue = stack.pop();
        System.out.println(" pop() returned: " + returnValue);
        returnValue = stack.pop();
        System.out.println(" pop() returned: " + returnValue);
        returnValue = stack.pop();
        System.out.println(" pop() returned: " + returnValue);
        returnValue = stack.pop();
        System.out.println(" pop() returned: " + returnValue);
        returnValue = stack.pop();
        System.out.println(" pop() returned: " + returnValue);
        returnValue = stack.pop();
        System.out.println(" pop() returned: " + returnValue);
    }
}   

Comments

Popular posts from this blog

How to disable encryption ? FBE ROM 1st time flashing guide with FBE encryption through Orange Fox Recovery.

 It is now mandatory to format your data for the first time when you flash this FBE ROM. ***Backup everything from phone Internal storege to PC/Laptop/OTG/SD card.

What is BLACK WINDOWS 10 V2 windows based penetration testing os,and what are its features.Download link inside

                         Black Windows 10 V2