Programming Tutorials

  • View all tutorials
  • ,
    Learn the basics of Java
    Java is a popular programming language developed by Sun Microsystems. It is an object-oriented, class-based, concurrent, portable language. In this tutorial we'll go through how to create a simple Java program, and we'll discuss various Java features like variables, functions, and arrays.

    Structure

    In Java, the filename needs to match the public classname, which in our case we named Main. The Java program initially starts from the main() function, which is mandatory in any Java program. String[] args are command-line arguments that can optionally be passed into the program.
    public class Main {
    
      public static void main (String[] args) {   
        System.out.println("Hello world!");
      } 
    
    }
    
    The program above simply prints "Hello world!" via the System.out.println function. You can copy this code and run it directly in the editor on any Coderbyte challenge.

    Variables

    Variables in Java begin with a data type and then a name for the variable. There are several data types you can use in Java.
    int a = 10;
    int b = 20;
    int added = a + b; // => 30
    
    double pi = 3.14;
    
    boolean f = false;
    boolean t = true;
    
    String str = "Hello world";
    char c = 'a';
    
    Java is a type-safe language so you cannot declare a variable to be one type, and then assign it a value of a different type later on, otherwise an error will occur at compile-time.
    int num = 10;
    num = "hello world" // error: incompatible types
    
    In Java, there are also different types of variables such as local variables, instance variables, class variables, and others. You can read more about those here, and we'll cover some of these in another tutorial.

    Loops

    We'll cover two popular loops commonly used, for loops and while loops. To loop through a set of elements or a range, a for loop is useful because we can specify the start, end, and increment variables. So, for example if we want to loop through an array and search for the first number greater than 9:
    public class Main {
    
      public static void main (String[] args) {   
    
        // create an array in Java with [] after the data type
        int[] nums = {1, 2, 5, 10, 12};  
    
        // initialization; termination; increment
        for (int i = 0; i < nums.length; i++) {
          if (nums[i] > 9) {
            System.out.println("At index " + i + " is the first number greater than 9");
            break;
          }
        }
    
      } 
    
    }
    
    In the code above, we use a for loop to loop through an array, and when we finally find an element greater than 9, we print a string and then break out of the loop. There is also a slightly easier way to write for loops in Java using the enhanced for loop syntax:
    public class Main {
    
      public static void main (String[] args) {   
    
        // create an array in Java with [] after the data type
        int[] nums = {1, 2, 5, 10, 12};  
    
        // declaration: expression
        for (int num: nums) {
          if (num > 9) {
            System.out.println("Element " + num + " is the first number greater than 9");
            break;
          }
        }
    
      } 
    
    }
    
    The while loop is good to use if you are not sure how long you'll need to loop for, so you keep running the loop until some stop condition is met. For example, in the code below we keep running the code until the condition becomes true:
    import java.util.Random;
    
    public class Main {
    
      public static void main (String[] args) {   
    
        int[] nums = {1, 2, 5, 10, 12};  
        int counter = 0;
        boolean check = false;
    
        while (!check) {
         
          // generate random number between 0 and 5
          Random rand = new Random();
          int random = rand.nextInt(nums.length);
    
          // if position of this random number is 5 within our array
          // then set 'check' to true which will stop the loop
          if (nums[random] == 5) {
            check = true;
          }
    
          counter++;
    
        }
    
        System.out.println("The loop ran " + counter + " times until it found 5 within the nums array.");
    
      } 
    
    }
    
    In the above code, we have an array, and we keep on generating a random number using a method from java.util.Random and checking if the position of this random number in the array is equal to 5. Once we find 5, we set a condition to stop the loop and we report how long it took to stop via the counter variable. You can copy the above code into the editor on Coderbyte and you'll get outputs like the following: The loop ran 4 times until it found 5 within the nums array. The loop ran 9 times until it found 5 within the nums array. The loop ran 2 times until it found 5 within the nums array.

    Arrays and Lists

    You can create an array of some data type in Java by adding the [] after the data type, and then specifying the size of the array, or specifying the elements with which it will be initialized.
    // array of ints
    int[] A = {1, 2, 3, 4};
    
    // array of doubles
    double[] B = {1.0, 2.2, 5}; // B[2] converts to 5.0 when accessed
    
    // array of strings
    // specify exactly how large the array will be beforehand 
    String[] C = new String[3];
    C[0] = "Fish";
    C[1] = "Cat";
    C[2] = "Dog";
    
    // array of characters
    // must use single quotes not double for chars
    char[] D = {'a', 'b', 'z', '2'}; 
    System.out.println(Character.isLetter(D[0])); // => true
    System.out.println(Character.isLetter(C[0])) // => false
    System.out.println(Character.isDigit(D[3])) // => true
    
    You can read more about arrays in Java on the Oracle documentation page. In the program below, we have an array of characters and we want to add up all the digits that appear in the array. We use a for loop to loop through the array, and then we check if the current character is a digit, if so, we add it to the total which we return at the end. We use a built-in Java function to convert the numeric character to an actual integer. You can view a list of built-in Java methods here for reference.
    public class Main {
    
      public static void main (String[] args) {   
    
        char[] charArr = {'a', 'b', '1', '3', '6', 'z'};
        int total = 0;
        
        for (char c: charArr) {
          if (Character.isDigit(c)) {
            total += Character.getNumericValue(c);
          }
        }
        
        System.out.println(total); // => 10
    
      } 
    
    }
    
    Once you create an array in Java, you cannot change the size of it. You either specify the size of the array beforehand, or you create an array with a set number of elements within it. But, if you want to use an array-type structure where you can update and add values on the fly, you can use what is called an ArrayList in Java. When using an ArrayList, you can dynamically add or remove elements, determine if an elements exists in the list, and more. Below is an example of an ArrayList and a few of its functions.
    import java.util.*;
    
    public class Main {
    
      public static void main (String[] args) {   
    
        // create an ArrayList we will manipulate
        ArrayList list = new ArrayList();
        
        // add elements even of different data types using the add method
        list.add(1);
        list.add(2);
        list.add("hello");
        list.add(true);
        
        // retrieve element using the get method
        System.out.println(list.get(3)); // => true
        
        // determine where an element exists in the ArrayList
        // returns -1 if not found
        System.out.println(list.indexOf("hello")); // => 2
        
        // you can easily print the whole list
        System.out.println(list); // => [1, 2, hello, true]
        
        // remove element at specific index
        list.remove(0);
        
        // add element at a specific index
        list.add(0, -100);
        
        System.out.println(list); // => [-100, 2, hello, true]
    
      } 
    
    }
    
    You can read more about ArrayLists here and here.

    Methods

    To create methods in Java the syntax is as follows: modifier[optional] returnType name(paramters) { // code goes here... } Below is an example of a method that reads in a parameter, and then returns a value.
    public class Main {
        
      // this functions takes in an array of numbers
      // and then returns the average of them
      public static int average(int[] arr) {
          int sum = 0;
          for (int n: arr) {
              sum += n;
          }
          return sum / arr.length;
      }
    
      public static void main (String[] args) {   
    
        // create an array of numbers and pass in this array
        // into our function
        int[] nums = {1, 2, 5, 10, 3, 16};
        int avg = average(nums);
        
        System.out.println("The average is: " + avg); // => The average is: 6
    
      } 
    
    }
    
    You can read more about methods and what public static means here.
    mrdaniel wrote this tutorial on 5/29/16 | java
    Comments
    Log in to submit a comment.