Powered by
/src$ make
  • Home
  • About
  • Directory
  • Contact
  • Home
  • About
  • Directory
  • Contact

The Java Series - Learn Java From Scratch (Beginner Friendly)

2/2/2018

 

Introduction: Programming and Java

This article/series of videos will be aimed for beginning programmers or anyone who wants to learn the Java programming language. Except for the introduction video, each subsequent video is meant to be very short and will be used to simply speak about the programming concept as well as demonstrate the code in Java. 
Here are the main points that you need to know: 
  • Computers use software to do various aspects, from programs like Excel and Calculators, to web browsers and webpages.
  • Software is created using a programming language. That language allows us to type instructions for a computer to perform.
  • Java, the programming language we use, is special in that the code we write is interpreted by a Java Virtual Machine (JVM). This lets Java code run basically everywhere. (As opposed to other programming languages that may need special setups.)
  • Our code needs to be compiled into an executable file. We're going to use the most basic java compiler on the command line to do this, but later in the series we'll look at build tools such as Maven and Gradle.

The Java Series

Instead of article form, this series will be in youtube video series so I can speak clearly and we can learn about programming and Java quickly.
The github link for this series can be found here. 

Video 0: Introduction and Goals

Video 1: Setup and Hello World, Java

Install Java using the following commands: 
sudo apt-get install default-jre
sudo apt-get install default-jdk
java -version
If you're using Windows and really want to use a build tool, see one of the appendix sections near the end of the article.
Create a file named MainStartup.java and enter the following code in it:
1
2
3
4
5
6
7
class MainStartup
        {
        public static void main(String[] args)      
                {
                System.out.println("Hello World from srcmake.");
                }
        }
Compile the code, and then run the executable that's created by using the following two commands:
javac MainStartup.java
java MainStartup

Video 2: Basic Data Types (Variables)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class MainStartup
        {
        public static void main(String[] args)      
                {
                System.out.println("Variables, basic data types.");
                
                int count;
                int subscribers = 100;
                subscribers = -100;
                long subs = 10000000L;
                double decimal = 120.4; 
                final int constant = 1;
                                
                boolean mySubscribersAreCool = true; // false
                                
                char c = 'A'; // ASCII
                String warning = "Always compile, to make sure the code works.";
                
                System.out.println(warning);
                }
        }
 

Video 3: For Loops, If Statements

 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
29
30
class MainStartup
        {
        public static void main(String[] args)      
                {
                System.out.println("Program began.");
                
                int max = 5;
                
                for(int i = 0; i < max; i++)
                        {
                        System.out.print(i + " ");
                        }
                System.out.println(".");
                
                
                if(max > 4) 
                        {
                        System.out.println("The number stored in \"max\" is greater than 4.");
                        }
                else if (max > 2) 
                        {
                        System.out.println("The number stored in \"max\" is greater than 2 but less than 4.");
                        }
                else 
                        {
                        System.out.println("The number stored in \"max\" is less than 2.");
                        }
                
                }
        }
 

Video 4: Functions

 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class MainStartup
        {
        public static void SayHi(String name)
                {
                System.out.println("Hi from " + name);
                }
        
        public static int ReturnsFive()
                {
                int five = 5;
                return five;
                }
                
                public static boolean IsEven(int num)
                        {
                        if(num % 2 == 0) // Means the number is even.
                                { 
                                return true; 
                                }
                        
                        return false;
                        }
        
        public static void main(String[] args)      
                {
                System.out.println("Program began.");
                
                SayHi("srcmake");
                
                int num = ReturnsFive(); // num = 5
                
                if(IsEven(num) == true)
                        {
                        System.out.println(num + " is even!");
                        }
                else
                        {
                        System.out.println(num + " is odd!");
                        }
                
                System.out.println("Program ended.");
                }
        }
 

Video 5: Arrays, ArrayLists, and Import

 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.ArrayList;

class MainStartup
        {
        public static void main(String[] args)      
                {
                System.out.println("Program began.");

                // Basic arrays. Don't use them. 
                // You MUST initialize the array with it's values to use it. Lame.
                int[] myArray = { 0, 1, 2 };
                myArray[0] = 5;
                System.out.println(myArray[0]);
                
                        
                // Arraylists. These are our basic arrays.
                ArrayList<Integer> myList = new ArrayList<Integer>();
                
                // Add the numbers 0, 1, ..., 9 to the list.
                for(int i = 0; i < 10; i++)
                        {
                        myList.add(i);
                        }
                
                // Access the numbers and print them out.
                int n = myList.size();
                for(int i = 0; i < n; i++)
                        {
                        int num = myList.get(i);
                        System.out.print(num + " ");
                        }
                System.out.println();
                        
                // Other types.
                ArrayList<Long> longList;
                ArrayList<Double> doubleList;
                ArrayList<Boolean> boolList;
                ArrayList<Character> charList;
                ArrayList<String> stringList;

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

Video 6: Classes 

Create a new file for our new class. Name the file "srcMathLibrary.java" and enter the following code into it:
 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
29
30
31
32
33
34
35
36
37
38
class srcMathLibrary
        {
        // Private variables/functions.
        private int favenum;
        
        // Constructor
        public srcMathLibrary()
                {
                SetFaveNum(7);
                }
        
        // Overloaded constructor, so we can set the fave number up when we create an object.
        public srcMathLibrary(int fave)
                {
                SetFaveNum(fave);
                }
        
        // Public variables/functions.
        public int Add(int a, int b)
                {
                return a + b;
                }
                
        public void PrintFaveNum()
                {
                System.out.println(GetFaveNum());
                }
                
        public int GetFaveNum()
                {
                return this.favenum;
                }
                
        public void SetFaveNum(int fave)
                {
                this.favenum = fave;
                }
        }
Finally, our MainStartup.java file will test our class out.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class MainStartup
        {
        public static void main(String[] args)      
                {
                System.out.println("Program began.");

                srcMathLibrary math = new srcMathLibrary();
                math.PrintFaveNum();
                math.SetFaveNum(200);
                math.PrintFaveNum();
                int addition = math.Add(2, 2);
                System.out.println(addition);
                
                srcMathLibrary anothermath = new srcMathLibrary(-1);
                anothermath.PrintFaveNum();

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

Video 7: Object Oriented Programming, Inheritance, Abstract

Some classes act as base classes, that other classes are derived from. For example, Dogs are a type of Mammal, and Mammals are a type of Animal. Since we may want to make classes for Fishes, Amphibeans, Frogs, etc. in the future, a good object oriented approach is to plan classes by a hierchary.

​We start with Animal.java, where we define an abstract Animal class (which means that it must be filled in by the derived class before it can be used):
1
2
3
4
5
abstract class Animal
        {
        public int legs;
        abstract public void Speak();
        }
Next, we extend the Animal class by created a new file named Mammal.java for all of our mammals. 
1
2
3
4
5
abstract class Mammal extends Animal
        {
        public boolean hasFur;
        abstract void Eat();
        }
Next, we can make a Dog.java file with some Dog class code.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Dog extends Mammal
        {
        public Dog()
                {
                legs = 4;
                hasFur = true;
                }
                
        // You must fill in the base methods since this isn't an abstract class.
        public void Speak()
                {
                System.out.println("Bark.");
                }
                
        public void Eat()
                {
                System.out.println("I eat bones.");
                }
        
        }
Finally, our MainStartup.java file will create an instance of the Dog class and use its methods.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class MainStartup
        {
        public static void main(String[] args)      
                {
                System.out.println("Program began.");

                Dog srcdog = new Dog();
                srcdog.Speak();
                srcdog.Eat();
                
                System.out.println("Program ended.");
                }
        }

Video 8: Complex Data Structures

  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
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
// Copyright srcmake.com 2018.
import java.util.*;

class MainStartup
        {     
        public static void main(String[] args)      
                {
                System.out.println("Program began.");
                
                //////////////////////////////////////
                /* Stacks */
                // First in - Last out 
                // Reference: https://www.geeksforgeeks.org/stack-class-in-java/
                
                System.out.println("\nStacks!");
                Stack<Integer> stack = new Stack<Integer>();
                stack.push(5);
                stack.push(3);
                stack.push(4);
                stack.pop();
                stack.push(2);
                stack.push(1);
                
                int stacksize = stack.size();
                System.out.println("There are " + stacksize + " elements in the stack.");
                
                while(stack.isEmpty() == false)
                        {
                        int top = stack.peek();     // The top item is...
                        System.out.print(top + " ");
                        stack.pop(); // Remove the top item from the stack.
                        }
                System.out.println();
                //////////////////////////////////////
                
                
                //////////////////////////////////////
                /* Queues */
                // First in - First Out
                // A good reference: https://www.javatpoint.com/java-priorityqueue
                // Another reference: https://www.geeksforgeeks.org/queue-interface-java/
                
                System.out.println("\nQueues!");
                Queue<Integer> q = new LinkedList<Integer>();
                q.add(4);
                q.add(5);
                q.add(2);
                
                int qsize = q.size();
                System.out.println("There are " + qsize + " elements in the queue.");
                
                while(q.isEmpty() == false)
                        {
                        int top = q.peek(); // The front of the queue.
                        System.out.print(top + " ");
                        q.remove(); // Remove this front of the queue.
                        }
                System.out.println();
                //////////////////////////////////////
                
                
                //////////////////////////////////////
                /* Priority Queues */
                // A queue where order is preserved
                // Reference: https://www.javatpoint.com/java-priorityqueue
                
                System.out.println("\nPriority Queues!");
                
                PriorityQueue<String> pq = new PriorityQueue<String>();
                
                pq.add("B");
                pq.add("Z");
                pq.add("A");
                pq.add("F");
                pq.add("M");
                pq.add("X");
                
                int pqsize = pq.size();
                System.out.println("There are " + pqsize + " elements in the priority queue.");
                
                while(pq.isEmpty() == false)
                        {
                        String top = pq.peek(); // The front of the queue.
                        System.out.print(top + " ");
                        pq.remove(); // Remove this front of the queue.
                        }
                System.out.println();
                
                //////////////////////////////////////
                
                
                //////////////////////////////////////
                /* Sets */
                // A set won't add duplicate entries. 
                // Reference: https://stackoverflow.com/questions/2490178/how-to-use-java-set
                // Another Reference: https://www.geeksforgeeks.org/set-in-java/
                
                System.out.println("\nSets!");
                
                Set<String> set = new TreeSet<String>(); 
                // You can also use "new HashSet" but don't. It won't be in order, then.
                
                set.add("src");
                set.add("make");
                set.add("java");
                set.add("make");
                set.add("src");
                set.add("icecream");
                
                int setsize = set.size();
                System.out.println("There are " + setsize + " elements in the set.");
                
                // A while loop doesn't make sense since removing from a set isn't ideal.
                // We'll use a for loop that iterates through set items instead of by index.
                for(String setitem : set)
                        {
                        System.out.print(" " + setitem + " |");
                        }
                System.out.println();
                //////////////////////////////////////
                
                
                //////////////////////////////////////
                /* Hash Maps */
                // A hash map stores key value pairs.
                // Reference: https://www.javatpoint.com/java-hashmap
                // Reference: https://stackoverflow.com/questions/1066589/iterate-through-a-hashmap
                
                System.out.println("\nHash Maps!");
                
                HashMap<String, Integer> map = new HashMap<String, Integer>(); // Maps strings to ints.
                map.put("srcmake", 100);
                map.put("vegetables", 0);
                map.put("chocolate", 50);
                
                // Get a value.
                System.out.println("srcmake scores a value of " + map.get("srcmake"));
                
                // Go through all values. 
                
                for(Map.Entry<String, Integer> pair : map.entrySet())
                        {
                        String key = pair.getKey();
                        int value = pair.getValue();
                        System.out.println("Key: " + key + "\tValue: " + value);
                        }
                
                
                //////////////////////////////////////
                
                
                System.out.println("\nProgram ended.");
                }
        }

Video 9: Generic Classes/Methods

Generics allow us to code so that one set of code will work no matter which data type the user's data structure comes in. For example, sorting an Array of Integers isn't that different from sorting an Array of Doubles or Longs. The only real difference is data type. To keep our sorting code concise, and to make it easier for the user, we use generics so that our classes (and methods) can handle different data types.
First, we create a helper class in a file named "ArrayUtility.java", to show a generic method that can print any array, regardless of the type.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Copyright srcmake.com 2018.
// Generics Class/Method.
// Reference: https://www.tutorialspoint.com/java/java_generics.htm
public class ArrayUtility
        {
        public static <T> void PrintArray(T[] array)
                {
                for(T element : array)
                        {
                        System.out.print(element + " ");
                        }
                System.out.println();
                }
        }
Next, we create a "GenericClass.java"  file for a class that declares a type for the class, so that certain methods and variables can be of that type. (This is what all the data structure classes do.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Copyright srcmake.com 2018.
// Reference: https://www.tutorialspoint.com/java/java_generics.htm
class GenericClass<T>
        {
        private T somevariable;
        
        public void PrintT(T element)
                {
                System.out.println(element);
                somevariable = element;
                }
        }
Finally, our MainStartup.java file will test the generic method and class.
 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright srcmake.com 2018.
class MainStartup
        {     
        ////////////////////////////////////////////////////////////////////////
        // This method is limited and can only accept Integer arrays.
        // We'd have to overload it for Double, Long, String, Boolean, etc. arrays.
        public static void PrintArraysBad(Integer[] array)
                {
                for(int element : array)
                        {
                        System.out.print(element + " ");
                        }
                System.out.println();
                }
        ////////////////////////////////////////////////////////////////////////

        
        ////////////////////////////////////////////////////////////////////////
        public static void main(String[] args)      
                {
                System.out.println("Program began.\n");
                
                /* Generic methods */
                // We have a bunch of arrays.
                Integer[] intArray = { 0, 2, 4, 6, 8, 10 };
                Double[] doubleArray = { 1.5, 2.5, 3.5, 4.5, 5.5 };
                Long[] longArray = { 100L, 200L, 300L, 400L, 500L };
                Boolean[] boolArray = { true, true, false, true, false };
                Character[] charArray = { 'a', 'b', 'c', 'd', 'e' };
                String[] stringArray = { "Apple", "Book", "Candy", "srcmake" };
                
                // If we want to print them, it makes sense to have a function to do it
                // Since it would be cumbersome to have a bunch of for loops.
                
                // But PrintArraysBad only accepts Integer arrays....
                PrintArraysBad(intArray);
                
                // We'll use the generic class's PrintArray method instead.
                // (We don't need to instantiate an object since the methos is static.)
                ArrayUtility.PrintArray(intArray);
                ArrayUtility.PrintArray(doubleArray);
                ArrayUtility.PrintArray(longArray);
                ArrayUtility.PrintArray(boolArray);
                ArrayUtility.PrintArray(charArray);
                ArrayUtility.PrintArray(stringArray);
                
                System.out.println();
                
                /* Generic Class */
                GenericClass<Integer> intT = new GenericClass<Integer>();
                intT.PrintT(5);
                
                GenericClass<String> stringT = new GenericClass<String>();
                stringT.PrintT("src make");
                
                System.out.println("\nProgram ended.");
                }
        ////////////////////////////////////////////////////////////////////////
        }

Video 10: Interfaces

Interfaces do the same thing that abstract classes do: they specify certain methods and variables that a derived class must define. 

The reason to use interfaces instead of just abstract classes is that a derived class may inherit from multiple interfaces, but only from one class. Variables in interfaces are final (meaning unchangeable). 
Create a file named "Dog.java" and add the following code to it.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
interface Animal
        {
        // Public, static, and final.
        boolean eatsFood = true;
        
        // Public and abstract.
        void Speak();
        }
        
class Dog implements Animal
        {
        public void Speak()
                {
                
                if(eatsFood == true)
                        {
                        System.out.println("I eat bones.");
                        }
                else
                        {
                        System.out.println("Too hungry to eat.");
                        }
                }
        }
Test the Dog class in "MainStartup.java".
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class MainStartup
    {           
    public static void main(String[] args)      
        {
        System.out.println("Program began.");
                
                Dog srcdog = new Dog();
                srcdog.Speak();
                
        System.out.println("Program ended.");
        }
    }
As mentioned, all variables in interfaces are final. Add the following to line 14 of Dog.java and try to make the program, again.
eatsFood = false;
The code won't compile because you're trying to change a constant variable.

Video 11: Annotations

Video A: Building with Maven

Maven is a Java build tool. Here's a reference article. The reason you would use it is because it manages your java dependencies for you. Not necessary for our tiny programs, but in real world huge applications, there are many dependencies with different versions and compatibilities, and so Maven manages all of that for you.

Install Maven with the following command in your terminal. (The next line ensures that it's working.)
sudo apt-get install maven
mvn -version

Okay, before we use Maven, we need to take care of some issues that may come up. The first thing is to make sure that your JAVA_HOME environment is set. (If not, Maven know what what Java compiler to use.) Find your java download location and make sure it's set. On Ubuntu in the command line: 
cd /usr/lib/jvm
ls
Find the name of the folder for your Java installation. In my case, it's "openjdk-8-jdk". Next, set your JAVA_HOME environment variable to point to this path. In the command line:
export JAVA_HOME=/usr/local/openjdk-8-jdk
. /etc/environment
And that should set our environment variable. 

Now, make sure that your java is actually up-to-date. This may not be necessary, but for me it was because openjdk-8 didn't install everything the first time I installed it. In the terminal...
sudo apt-get install openjdk-8-jdk
sudo apt-get upgrade
FINALLY, we can use Maven itself to build a project. Create a new project folder, and cd inside of it. Then type:
mvn archetype:generate
This will start creating a new Maven project. Press enter through everything, but for the following, you need to set some project IDs up. 
groupID: com.srcmake.builder
artifactId: ExampleBuild
version: 1.0
For groupID, say com.srcmake.builder. "com" is standard, "srcmake" is the company/website name, and "builder" is the project name. ArtifactID is also the project name. Sort of...The version will be 1.0. 

Again, for everything else, just press enter. 

The project will be made, and there are three important files right now. 
1. pom.xml - This file manages our project, from dependencies, libraries, names, versions, etc. This is defines our project.
2. test - Has a bunch of folders for our project's unit tests.
​3. src - Holds our project's Java source code. 
Let's build our project. In the root directory, in the command line:
mvn clean package 
If you see a failure...google it. If you see a success, then great. That just compiled our code from the src folder. It also created a bunch of stuff in the newly made "target" folder. To actually run our Java code, cd into the classes folder and java run our groupID and app entry point.
cd target/classes
java com.srcmake.builder.App
And you should see Hello World.
That was a lot of work, compared to our old method, right?Our command line way of using javac and java to compile is very good for quick programs, but any real project should be built using Maven or Gradle. 

For a more in-depth look, see this resource.

Video B: Building with Gradle

Gradle is another build tool to manage our Java projects.

​To install Gradle, in the command line:
sudo add-apt-repository ppa:cwchien/gradle
sudo apt-get update
sudo apt-get install gradle
Next, we create a project using Gradle. Then we build and run it. 
gradle init --type java-application
./gradlew build
./gradlew tasks
./gradlew run
And that's it.

Video C: API Project (Spring)

The spring tutorial can be found here.

Video D: Deploy an API onto a Heroku Instance (Cloud API)

Follow the instructions on heroku's website for beginning a Spring Java project.

To use the Spring commands, download the tool, navigate to bin, and use the spring file as a script to run the command's you need. 
wget https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/1.5.10.RELEASE/spring-boot-cli-1.5.10.RELEASE-bin.zip
unzip spring-boot-cli-1.5.10.RELEASE-bin.zip
cd spring-1.5.10.RELEASE/bin
./spring init --dependencies=web myapp
Then copy the myapp folder with our starter project back into our actual project directory. 
Like this content and want more? Feel free to look around and find another blog post that interests you. You can also contact me through one of the various social media channels. 

Twitter: @srcmake
Discord: srcmake#3644
Youtube: srcmake
Twitch: www.twitch.tv/srcmake
​Github: srcmake

Comments are closed.

    Author

    Hi, I'm srcmake. I play video games and develop software. 

    Pro-tip: Click the "DIRECTORY" button in the menu to find a list of blog posts.
    Metamask tip button
    License: All code and instructions are provided under the MIT License.

    Discord

    Chat with me.


    Youtube

    Watch my videos.


    Twitter

    Get the latest news.


    Twitch

    See the me code live.


    Github

    My latest projects.

Powered by Create your own unique website with customizable templates.