Thursday, May 26, 2016

Recursion

In the Java language the programmer is allowed to call a method within a method, the act of doing so is called recursion. the usefulness of recursion is to repeat methods multiple times without the use of a for loop or in other very specific ways. The benefit is efficiency however it is a more difficult way to program. It is also very useful to use radicals and exponents.
public int pow(int num, int exp){
int answer;
if(exp == 1){
   return num;
}
else{
   answer = num +pow(num, exp - 1);
}
return answer;
}
// this method will return the number to the exp power.
A recursive method can also be used to sort and search like in other tutorials in this blog, it helps it to be more effective but it is considerably more complicated, Trees and Graphs also use these kind of methods.

Friday, April 22, 2016

ArrayLists and Lists

Lists and ArrayLists in Java programming are objects that store other objects inside of them, they are very useful for storing data in multiple levels.
A usual object can store data inside of it as well as objects but ArrayLists keep the data organized in a deeper level. They are somewhat like normal arrays (String[]) however they are elastic instead of solid, meaning that they can increase and decrease in size depending on how much is required, instead of in a set amount.

public static void main(String[]args){

ArrayList<String> names = new ArrayList();// This is an example of instantiating an array list
List<String> moreNames = new ArrayList();//Lists and ArrayLists are similar however ArrayLists //are child objects from the List class. Thus the ArrayList class contains all of the previous methods //and more.

names.add("Joseph");//This is how to add a new object to an array list, it returns a boolean: true;
names.add("Smigla");
names.add(0, "Edward");//This adds a new object in the place of what ever is located in the index 
           //and moves the object in that index to the index higher than itself
           // The array will end up as: Edward, Joseph.
names.remove(1);//This removes an object from the array and and if it is larger than the index it //moves all objects after it downward an index unit, it also returns the object.

for(String n: names){System.out.print(n + " ");}//This will print in the console the objects in the list:
// Edward Smigla

}

Thursday, April 7, 2016

Sorting: Quick Sort

Quick sort is a divide and conquer approach to sorting just like Merge sort, however this method is more efficient but it does take up more memory space.
The method divides a list of integers, picks an integer of an array to be a pivot, then moves the integers that are larger in value and moves it to the right of the pivot, and then does that to the smaller ones.

Quick Sort
Algorithm:
public class MyQuickSort {
     
    private int array[];
    private int length;
    public void sort(int[] inputArr) {
         
        if (inputArr == null || inputArr.length == 0) {
            return;
        }
        this.array = inputArr;
        length = inputArr.length;
        quickSort(0, length - 1);
    }
    private void quickSort(int lowerIndex, int higherIndex) {
         
        int i = lowerIndex;
        int j = higherIndex;
        // calculate pivot number, I am taking pivot as middle index number
        int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
        // Divide into two arrays
        while (i <= j) {
            /**
             * In each iteration, we will identify a number from left side which
             * is greater then the pivot value, and also we will identify a number
             * from right side which is less then the pivot value. Once the search
             * is done, then we exchange both numbers.
             */
            while (array[i] < pivot) {
                i++;
            }
            while (array[j] > pivot) {
                j--;
            }
            if (i <= j) {
                exchangeNumbers(i, j);
                //move index to next position on both sides
                i++;
                j--;
            }
        }
        // call quickSort() method recursively
        if (lowerIndex < j)
            quickSort(lowerIndex, j);
        if (i < higherIndex)
            quickSort(i, higherIndex);
    }
    private void exchangeNumbers(int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
     
    public static void main(String a[]){
         
        MyQuickSort sorter = new MyQuickSort();
        int[] input = {24,2,45,20,56,75,2,56,99,53,12};
        sorter.sort(input);
        for(int i:input){
            System.out.print(i);
            System.out.print(" ");
        }
    }
}

Friday, March 18, 2016

Sorting: Merge Sort

Sorting is a combination of algorithms or instructions that you give in Java for the program to organize an array of numbers either from smallest to biggest or from biggest to smallest, this helps for your computer to more easily and quickly run a program which has to find a specific number. There are several ways to sort in Java there are Selection, Merge, and Insertion Sorts and each are differently efficient and are used for different reasons.

Merge Sort
Algorithm:
public class MyMergeSort {
     
    private int[] array;
    private int[] tempMergArr;
    private int length;
 
    public static void main(String a[]){
         
        int[] inputArr = {45,23,11,89,77,98,4,28,65,43};
        MyMergeSort mms = new MyMergeSort();
        mms.sort(inputArr);
        for(int i:inputArr){
            System.out.print(i);
            System.out.print(" ");
        }
    }
     
    public void sort(int inputArr[]) {
        this.array = inputArr;
        this.length = inputArr.length;
        this.tempMergArr = new int[length];
        doMergeSort(0, length - 1);
    }
 
    private void doMergeSort(int lowerIndex, int higherIndex) {
         
        if (lowerIndex < higherIndex) {
            int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
            // Below step sorts the left side of the array
            doMergeSort(lowerIndex, middle);
            // Below step sorts the right side of the array
            doMergeSort(middle + 1, higherIndex);
            // Now merge both sides
            mergeParts(lowerIndex, middle, higherIndex);
        }
    }
 
    private void mergeParts(int lowerIndex, int middle, int higherIndex) {
 
        for (int i = lowerIndex; i <= higherIndex; i++) {
            tempMergArr[i] = array[i];
        }
        int i = lowerIndex;
        int j = middle + 1;
        int k = lowerIndex;
        while (i <= middle && j <= higherIndex) {
            if (tempMergArr[i] <= tempMergArr[j]) {
                array[k] = tempMergArr[i];
                i++;
            else {
                array[k] = tempMergArr[j];
                j++;
            }
            k++;
        }
        while (i <= middle) {
            array[k] = tempMergArr[i];
            k++;
            i++;
        }
 
    }
}

There are different reasons why anyone would use Merge Sort instead of other kinds:
1) it is the most efficient type of sorting for bigger arrays of numbers.
2) it offers performance just bellow Quick Sort but uses less memory space.
Merge Sort
Merge Sort Demo.
However it takes more knowledge of coding and a greater understanding of algorithms, and it takes a considerable amount of memory space, if used frequently.

Friday, March 11, 2016

Abstract and Interfaces.

There are ways to assist with inheritance and polymorphism which is done by abstract classes and interfaces these kinds of java files are used for different reasons. They both have abstract methods and those methods cannot be described like normal methods and have to be implemented in any child class of the abstract class and implemented classes.
public interface AnInteface{ // This is how to create an interface.
  public void aMathod(); // This is the way to instaciate an abstract method.
public abstract class AnAbstractClass{ // This is how to create an abstract class.
  public abstract void aMethod(); //This is another way to write an abstract method but abstract 
  // classes can also implement non-abstract methods.
 public String aString(){
  String a = "A string";
  return a;
 }
}
There are two ways to implement these classes to another class:
public class NormalClass extends AnAbstractClass implements AnInterface{
 public void AMethod(){
 }// You have to incorporate the same abstract methods in a class that implements the interface or          // extends the abstract class 
}

Friday, March 4, 2016

Encapsulation and Polymorphism

Encapsulation is a term in Java programming and in general programming that refers to the privatization of files for classes and encapsulation of packages, there are different encapsulation key words: public, private and protected. they all do different things to your variables, classes, or methods. the public word allows to access a class, variable, or methods from one another if they are imported. The private keyword does not allow the interchange of classes, methods or variables even if they are imported. And the protected keyword only allows for methods, classes and variables to be used only within the same package. The way to import packages in any IDE from one class file is the keyword 'import' followed by a space. Ex: import java.util.*; the java.util library imports many very useful classes to the class to which you use this on, such as Random which has methods that create random numbers, or the Scanner class which reads user input from the console and gives it to a variable.
Plymorphism is a way to import classes in Java and assign them to another class as a child of that class, the best way to understand this is - Imagine that you have a dog, well that dog is an animal, but not all animals are dogs. In Java the way to assign an object as a sub-variable of another object is polimorphism.
the way to do that is to use the extends keyword it is used like this:
public class Cats extends Animals()
// all of the public methods from Animals will be usable in the Cats class.

Friday, February 26, 2016

System.out.print("Strings");

Strings are identifiers that are composed of one or many char identifiers, they can hold a big amount of characters and can be modified within a program in an amount of ways. a usual string is created in this way: String str1 = "Hello World";   It is very important that String is capitalized, that it's variable is stated with a quotation mark for both starting and beginning the string and that it ends with a semicolon.
Print method.
The print method is a method from the java.util.Object class in java that is the main class from which you import statements and methods from. It allows you to use String, String manipulation methods, the Print methods, and other equally important methods.
The print method is stated like this:
System.out.print("This is a print");
This will print the words "This is a print" to console. This is often used outside of the Graphic interfaces of programs for debugging purposes.
There are different methods that are used to manipulate String objects: charAt(), substring(), contains(), indexOf(), concat(), equals(), length(), trim(), etc.
These are used for different purposes, charAt(int) will find a char type data at a certain index from the string on which is used, it has parameters of int which means that you need to introduce an int and it will find the character from that position.
The method substring(int, int) requires two integers one for the beginning of the sub string and one for the end, it will take a chunk from between the two given indexes.
The method contains(String) has a String parameter and will find if the string it's used on has a sub string with the exact composition of the parameter string and will give it back as a boolean.
To find an index of a sub-string or a char then you use the indexOf(String) method which will return an int.
The method concat(String) allows you to concatenate two strings together, it will add the parameter string into the string to which the method is used.
equals(String) is the most secure way to see if two strings are equal to each other instead of using the == identifier.
length() will return an int with the number of characters that are in a single string variable.
trim() will erase from a string any excess white space from before or after a string.
REMEMBER: every time you modify a String object the String class does not dump the previous object instead it creates a new one and saves the other one.

String a = "\'a small fox sleeps\'"; if(a.contains("fox")){System.out.print(a);}
This will print: 'a small fox sleeps' to the console.

Apart from manipulating Strings with those three methods it is also possible to turn other primitive data to Strings. The method toString() from the class of any primitive data will turn it to Strings:
Integer.toString(), Double.toString(), Boolean.toString(), etc.