Skip to content

Instantly share code, notes, and snippets.

@antonioalmeidab
Last active March 22, 2021 02:33
Show Gist options
  • Save antonioalmeidab/74051d5505555c99f84ef03e48e6aaeb to your computer and use it in GitHub Desktop.
Save antonioalmeidab/74051d5505555c99f84ef03e48e6aaeb to your computer and use it in GitHub Desktop.

Java

Writing a Test program

  1. Launch Terminator
  2. Make a new directory for your Java project
    1. Type mkdir new_project && cd new_project
    2. Type touch Test.java.
    3. Type osub Test.java and paste this code.
      public class Test {
          public static void main(String[] args) {
      	    System.out.println("Hello World!");
          }
      }
      
    4. This program declares a Test class and a main function that prints out "Hello World!" to the console.
    5. Optionally, see this page for more information.

Compiling

  1. Compile Test program.
    1. Type javac Test.java on Terminator.
    2. Notice that a new file Test.class was created, this is a bytecode file for the Test class that java will use to run your program
    3. If you want to compile ALL files ending in .java you can run javac *.java
    4. Optionally, see javac documentation for more information.
  2. Running the test program
    1. Type java Test
    2. You should see a prompt saying Hello World!.
    3. If that was not the message displayed, try reviewing the previous steps.

Importing

  1. In order to use Classes and Interfaces from other packages, first you must import them.
  2. Importing java.util, a builtin Java package.
    1. Add import java.util. to the beginning of the Test.java file. Like this:
      import java.util.*;
      public class Test {
          public static void main(String[] args) {
              System.out.println("Hello World!");
          }
      }
      
    2. Now you can use all Classes or Interfaces from the java.util package. See documentation for more information about java.util package.
  3. Using classes from imported package.
    1. Using the Random class.
    2. Add the Random random = new Random(); line to the main function. This will declare an the "random" object from the Random class.
    3. To generate a random number from 0 to 49 and assign it to a variable, you must add
      int randomNumber = random.nextInt(50);.
    4. Finally you should print the generated number adding System.out.println("Generated number" + randomNumber);
    5. This is what your Test.java must look like this:
      import java.util.*;
      public class Test {
          public static void main(String[] args) {
              System.out.println("Hello World!");
              Random random = new Random();
              int randomNumber = random.nextInt(50);
              System.out.println("Generated number: " + randomNumber);
          }
      }
      
    6. Compile and run, and your output should look something like this:
      Hello World!
      Generated number: 24
      

Packages

  1. In real life Java projects, the files are organized in packages. On the previus section we imported all files/classes/interfaces from the package java.util.
  2. Now we are going to put our Test.java file inside the com.hello.world package.
    1. Create the file structure com/hello/world inside your Java project folder.
      Type mkdir -p com/hello/world on Terminator.
    2. Type mv Test.java com/hello/world on Terminator to move the file to the package folder.
    3. Add the line package com.hello.world; to the beginning of the file. This will tell Java that the file belongs to the com.hello.world package.
  3. Compiling the file in the package.
    1. On Terminator type javac com/hello/world/Test.java to compile.
    2. Type la com/hello/world and see that a Test.class was created.
  4. Executing the program.
    1. On Terminator, type java com.hello.world.Test and check if the output is similar
    2. When we Type the command above, we are telling Java to execute the class Test inside the com.hello.world package.
  5. Optionally, see Java docs for more information.

Inheritance

  1. In Java we can create classes that inherits methods from another class. That is important because we can reuse code without having to rewrite it.
  2. To inherit, we use the extends keyword on the declaration of the class.
    public class NewClass extends SuperClass {
    
  3. Type touch com/hello/world/Hello.java on Terminator and osub com/hello/world/Hello.java to open it.
  4. Create a Hello class with a sayHello method:
    package com.hello.world;
    public class Hello {
        public Hello() {
        }
        public void sayHello() {
            System.out.println("Hello World!");
        }
    }
    
  5. Have your Test class inherit from Hello.
    1. Add extends Hello to the Test class declaration.
    2. Remove the line that prints out Hello World.
  6. Have your Test main method use the sayHello method.
    1. Add a line to instantiate an object from Hello class in the beginning of your main method.
      Hello hello = new Hello();
      
    2. Add the following line right after the instatiation to execute sayHello method.
      hello.sayHello();
      
  7. Type javac *.java inside the directory with the two classes, and execute your Test class.
  8. Your final Test.java should look like this
    package com.hello.world;
    import java.util.*;
    public class Test {
        public static void main(String[] args) {
            Hello hello = new Hello();
            hello.sayHello();
            Random random = new Random();
            int randomNumber = random.nextInt(50);
            System.out.println("Generated number: " + randomNumber);
        }
    }
    
  9. The new and old outputs should look similar
  10. See inheritance for more information

Overloading

  1. You can create methods with the same name in the same class, as long as you have different parameteres. That is called overloading.
  2. How to overload a method?
    1. Let's overload the sayHello method.
    2. Type osub com/hello/world/Hello.java.
    3. Create a new sayHello method
      public void sayHello(String name) {
          System.out.println("Hello " + name);
      }
      
    4. That way we are overloading sayHello, that should work because they have differente signatures.
  3. Now on Test.java, we must call the overloaded method, by adding this line at the ending of the main method:
    hello.sayHello("Johnny")
    
  4. Compile and execute, the output should look something like this:
    Hello World!
    Generated number: 15
    Hello Johnny
    
  5. Now try switching Johnny for your own name and see what happens.
  6. See overloading for more information.

Passing by reference or by value?

  1. In Java, method arguments are passed by value, this means that a copy of the value will be passed to the method and not the real variable.
  2. With that in mind, what will be the output from the following program? Remember the file must be named after the class containing the main method.
    public class Primitive {
        public static void main(String[] args) {
            New test = new New();
            int variable = 10;
            test.changeVariable(variable);
            System.out.println(variable);
        }
        public void changeVariable(int variable) {
            variable = 15;
        }
    }
    
  3. Compile and run to check your answer.
  4. The value printed was 10, even when we changed it inside the changeVariable method, can you explain why this happens?
  5. What about this program, what will be its output?
    public class ObjectExample {
        public static void main(String[] args) {
            ObjectExample test = new ObjectExample();
            Person person = new Person();
            person.name = "John";
            test.changeName(person);
            System.out.println(person.name);
        }
        public void changeName(Person person) {
            person.name = "Charles";
        }
    }
    class Person {
        String name;
    }
    
  6. Compile and run to check your answer.
  7. Now the behavior was different, the value printed was the one assigned inside the changeName method.
  8. That happens because Java object variables are references that point to the real objects in the memory.
  9. So even if you are changing a copy of the value in the method, it points to the same Object in memory, so any modifications to the Object variable attributes, will affect its true value.
  10. This only happens because we are making changes to the Object's attributes and not trying to reassign the person variable. Check what the output would be in this case.
    public class ObjectExample {
        public static void main(String[] args) {
            ObjectExample test = new ObjectExample();
            Person person = new Person();
            person.name = "John";
            test.changeName(person);
            System.out.println(person.name);
        }
        public void changeName(Person person) {
            person = new Person();
            person.name = "Charles";
        }
    }
    class Person {
        String name;
    }
    
  11. Can you explain why this happened?
  12. By reassigning the person variable in the method, we are reassigning a copy of the original person in the main method. So another Object is allocated in memory and it does not affect the original person.name attribute. Now they are two references to two different Objects in memory.
  13. Since Java treats Arrays as Objects, the same logic applies. Try guessing the output from the following program and then run it to check your answer.
    public class ArrayExample {
    	public static void main (String[] args) {
    		int[] array = {1, 1, 1};
    		ArrayExample arrayExample = new ArrayExample();
    		arrayExample.changeArray(array);
    		for (int i = 0; i < 3; i++) {
    			System.out.println(array[i]);
    		}
    	}
    
    	public void changeArray(int[] array) {
    		array[1] = 0;
    	}
    }
    
  14. So by changing array elements is similar to changing object attributes. Change the program to see if reassigning the array will change the output
@brianchandotcom
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment