day-1

Getting Started with Java

  1. Download and install Java 16 https://www.oracle.com/java/technologies/javase-downloads.html

For Windows users you need to set JAVA_HOME environment variable. Follow this example

  1. IDE for Java Development IntelliJ Download the community or professional version

  • Use Amigo2021 and get IntelliJ professional for 3 months. Redeem here

  1. Verify installation

Open your Terminal or CMD and type java --version

  1. Your First Java Program

New Project Screenshot 2021-08-17 at 17 42 41

Select Project SDK and Next Screenshot 2021-08-17 at 17 43 08

Tick Create project from template Screenshot 2021-08-17 at 17 43 33

Screenshot 2021-08-17 at 17 43 59
Screenshot 2021-08-17 at 19 54 19

Open Main file and add the following code

System.out.println("Hello World");

then run by clickng on the play button

Screenshot 2021-08-17 at 17 45 57
Alt Text

Compiling and Running using Terminal


  1. Open the terminal inside IntelliJ. Refer to image bellow

  2. cd src

  3. javac com/amigoscode/Main.java - This creates a file called Main.class

  4. java com.amigoscode.Main

You should see Hello World on the terminal

Screenshot 2021-08-17 at 18 09 36

Notice Main.class

Byte Code

Bytecodes are the machine language of the Java virtual machine. There are other so called JVM languages such:

  1. Java

  2. Groovy

  3. Scala

  4. Kotlin

  5. Closure

This means that we just need to have JDK installed and we can write code in any other above languages.

This Java code needs to be compiled into bytecode for the JVM to run it.

package com.amigoscode;

public class Main {

    public static void main(String[] args) {
        // write your code here
        System.out.println("Hello World");
    }
}

Inside IntelliJ Select the file called Main under GettingStarted/out/production/GettingStarted/com/amigoscode

Screenshot 2021-08-17 at 18 15 40

Select View from the menu item and then Show Bytecode Screenshot 2021-08-17 at 18 18 04

Bytecode Screenshot 2021-08-17 at 18 18 26

The above code is what is fed to to the JVM to run our program.

Java Reserved Keywords

Java has a set of keywords that are reserved words that cannot be used as variables, methods, classes, or any other identifiers:

Taken from https://www.w3schools.com/java/java_ref_keywords.asp

Keyword
Description

abstract

A non-access modifier. Used for classes and methods: An abstract class cannot be used to create objects (to access it, it must be inherited from another class). An abstract method can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from)

assert

For debugging

boolean

A data type that can only store true and false values

break

Breaks out of a loop or a switch block

byte

A data type that can store whole numbers from -128 and 127

case

Marks a block of code in switch statements

catch

Catches exceptions generated by try statements

char

A data type that is used to store a single character

class

Defines a class

continue

Continues to the next iteration of a loop

const

Defines a constant. Not in use - use final instead

default

Specifies the default block of code in a switch statement

do

Used together with while to create a do-while loop

double

A data type that can store whole numbers from 1.7e−308 to 1.7e+308

else

Used in conditional statements

enum

Declares an enumerated (unchangeable) type

exports

Exports a package with a module. New in Java 9

extends

Extends a class (indicates that a class is inherited from another class)

final

A non-access modifier used for classes, attributes and methods, which makes them non-changeable (impossible to inherit or override)

finally

Used with exceptions, a block of code that will be executed no matter if there is an exception or not

float

A data type that can store whole numbers from 3.4e−038 to 3.4e+038

for

Create a for loop

goto

Not in use, and has no function

if

Makes a conditional statement

implements

Implements an interface

import

Used to import a package, class or interface

instanceof

Checks whether an object is an instance of a specific class or an interface

int

A data type that can store whole numbers from -2147483648 to 2147483647

interface

Used to declare a special type of class that only contains abstract methods

long

A data type that can store whole numbers from -9223372036854775808 to 9223372036854775808

module

Declares a module. New in Java 9

native

Specifies that a method is not implemented in the same Java source file (but in another language)

new

Creates new objects

package

Declares a package

private

An access modifier used for attributes, methods and constructors, making them only accessible within the declared class

protected

An access modifier used for attributes, methods and constructors, making them accessible in the same package and subclasses

public

An access modifier used for classes, attributes, methods and constructors, making them accessible by any other class

requires

Specifies required libraries inside a module. New in Java 9

return

Finished the execution of a method, and can be used to return a value from a method

short

A data type that can store whole numbers from -32768 to 32767

static

A non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class

strictfp

Restrict the precision and rounding of floating point calculations

super

Refers to superclass (parent) objects

switch

Selects one of many code blocks to be executed

synchronized

A non-access modifier, which specifies that methods can only be accessed by one thread at a time

this

Refers to the current object in a method or constructor

throw

Creates a custom error

throws

Indicates what exceptions may be thrown by a method

transient

A non-accesss modifier, which specifies that an attribute is not part of an object's persistent state

try

Creates a try...catch statement

var

Declares a variable. New in Java 10

void

Specifies that a method should not have a return value

volatile

Indicates that an attribute is not cached thread-locally, and is always read from the "main memory"

while

Creates a while loop

Comments


Comments are used to documment code or temporarily stop exuction of line or multile lines of code.

There single and multi line comments.

Single comments


Single comments start with // and can be seen in the following code as // write your code here

package com.amigoscode;

public class Main {

    public static void main(String[] args) {
        // write your code here
        System.out.println("Hello World");
    }
}

Add a single line comment to System.out.println("Hello World"); then run the application and see what the outout will be.

Multiline comments

Multiline comments start with /* and end with */ any code or text inside opening /* and the closing of */ will be treated as a comment therefore the code will will not run

package com.amigoscode;

public class Main {
    /*
    public static void main(String[] args) {
        // write your code here
        System.out.println("Hello World");
    }
    */
}

Variables

Variables are placehoders allowing you to store primitives and reference types. Each variable has an associated data type.

For example if you store a number

int number = 20;

If you want to store a sequence of characters

String firstName = "Mariam";

If you want to store some coordinates you can you for example

Point p = new Point(20, 10);

Primitives

Primitive types are used to store simple values. For example, whole numbers, decimal and characters. Here are the available data types for primitives.

  • boolean

  • byte

  • short

  • char

  • int

  • long

  • float

  • double

The difference between them is the type of value can be stored and the amount of memory required.

Type
Size (bits)
Minimum
Maximum
Example

byte

8

-128

127

byte b = 100;

short

16

-32,768

32,767

short s = 30_000;

int

32

-2147483648

2147483647

int i = 100_000_000;

long

64

-9223372036854775808

9223372036854775807

long l = 100_000_000_000_000;

float

32

-2-149

(2-2-23)·2127

float f = 1.456f;

double

64

-2-1074

(2-2-52)·21023

double f = 1.456789012345678;

char

16

0

216– 1

char c = ‘c';

boolean

1

boolean b = true;

Arithemtic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator
Name
Description
Example

+

Addition

Adds together two values

x + y

-

Subtraction

Subtracts one value from another

x - y

*

Multiplication

Multiplies two values

x * y

/

Division

Divides one value by another

x / y

%

Modulus

Returns the division remainder

x % y

++

Increment

Increases the value of a variable by 1

++x

--

Decrement

Decreases the value of a variable by 1

--x

Reference Types

Reference Types are used to strore complex types. i.e Objects. For example store details about a person.

Person john = new Person("John", 22, Gender.MALE);

more on Reference types later.

Arrays

Arrays are used to store multiple values using any datatype in a single variable, instead of declaring separate variables for each value.

Instead of

String nameOne = "Ali";
String nameTwo = "Adam";
String[] names = new String[2];
names[0] = "Ali";
names[2] = "Adam";

or slightly better

String[] names = {"Ali", "Adam"};

Arrays size are fixed. Once you the array the size cannot be extended. In the above names arrays if we want to add third item we can't.

names[2] = "Mike";

The above code will throw

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
	at com.amigoscode.Main.main(Main.java:7)

Each item in the array are called element. The first element starts at index 0 even though the size is 2.

System.out.println(names.length); // 2

So:

  • size = 2

  • "Ali" index is 0

  • "Adam" index is 1.

You can override the value inside each element as such:

names[0] = "Jamal"

Read more about Arrays - https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/Arrays.html

Strings


Strings allows you store sequence of characters.

String brand = new String("Amigoscode")

or

String brand = "Amigoscode"
Alt Text

Ok let me explain. Strings in Java are special in Java. Because they are used to often, the JVM sets aside a special area of memory for Strings.

Strings are immutable in Java. Immutable means unmodifiable or unchangeable. When a String is created using String literal:

String brand = "Amigoscode";

The the value Amigoscode is stored in a special area in the memory called String constant pool

Now lets create another variable using String Object. Not the new keyword. It creates a new Object.

String youtubeChannelName = new String("Amigoscode");

Since Amigoscode is already present inside the String Pool youtubeChannelName refers to Amigoscode

Now both brand and youtubeChannelName refer to Amigoscode

Screenshot 2021-08-18 at 11 46 55

The reason Strings are immutable is because image if there are other variables referring to Amigoscode and the value changes, i.e Amigoscode to Friendscode. This can be problematic since all other variables would have a different value due to this side effect causing all sorts of unexpected behavior. To prevent this, Strings are immutable.

What about

String brand = new String("Amigoscode");

The difference is that when we create a String object using the new keyword, it always creates a new object in heap memory. And as we just saw, if we create an object using String youtubeChannelName = "Amigoscode";, it may return an existing object from the String pool, if it already exists. Otherwise, it will create a new String object inside the String Pool

String equality

  • == returns true if and only if both variables refer to the same object

  • .equals() returns true the "value" inside String is the same

For this example == returns true because both brand and youtubeChannelName refer to the same object inside the String Pool.

String brand = "Amigoscode";
String youtubeChannelName = "Amigoscode";
System.out.println(brand == youtubeChannelName); // True
System.out.println(brand.equals(youtubeChannelName)); // True

For this example == returns false because both brand and youtubeChannelName refer to different objects inside the Heap.

String brand = new String("Amigoscode");
String youtubeChannelName = new String("Amigoscode");
System.out.println(brand == youtubeChannelName); // False
System.out.println(brand.equals(youtubeChannelName)); // True

++ and -- Operators

++ and -- operator are used to inline increment or decrement a value

Consider

int i = 0;
  • i++ Returns the value and increments

int i = 0;
System.out.println(i++); // 0
System.out.println(i); // 1
  • ++i Increments and returns the value

int i = 0;
System.out.println(++i); // 1
System.out.println(i); // 1
  • i-- Returns the value and decrements

int i = 0;
System.out.println(i--); // 0
System.out.println(i); // -1
  • --i Decrements the value and increments

int i = 0;
System.out.println(i--); // -1
System.out.println(i); // -1

Loops

In computer programming, loops are used to repeat a block of code. For example, your want to print all numbers of 0 to 10, then rather than typing the same code 10 times, you can use a loop.

In Java there many types of loops.

Fori loop

for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}
/*
Output:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
*/

for is the construct. Then inside () we have:

  • int i = 1; This is the initial expression

  • i<=10; This logical operator indicates when to stop the loop. If false keep looping else stop.

  • i++ updates the value of initial expression.

Looping through arrays

String[] names = {"Jamila", "Mark"};
for (int i = 0; i < names.length; i++) {
    System.out.println(names[i]);
}

The above syntax is a little bit confusing. So we can use the enhanced for loop

for (String name : names) {
    System.out.println(name);
}

In Java there are other types of Loops that we will explore later

Beak, Continue and Return keywords

Break

The break statement is used to jump out of a loop or statement

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  System.out.println(i);
}
/* 
Output:
    0
    1
    2
    3
*/

Continue

The continue statement is used to skip the rest of the code inside a loop for the current iteration only.

for (int i = 0; i < 10; i++) {
  if (i <= 4) {
    continue;
  }
  System.out.println(i);
}
/* 
Output:
    5
    6
    7
    8
    9
    10
*/

Return

The return statement can be used to end function execution or return values.

public int getNumber() {
    return 1;
}
public void terminateEarly(boolean exit) {
    System.out.println("I run :)");
    if (exit) {
        return;
    }
    System.out.println("I don't run :(");
}

Packages

A package is simply a folder that groups related types (Java classes, interfaces, enumerations, and annotations).

Java ships with pre existing packages and classes that we can take advantage of. For example if we want to accept user input from the terminal/cmd we can user the Scanner class.

To use the scanner class we need to import the class or the entire package. This has to be done right after package com.amigoscode; as follow

package com.amigoscode;

import java.util.Scanner;

The above code import Scanner class and we can use it as follows.

Scanner scanner = new Scanner(System.in);

or we can import the entire package. Avoid this method since it is harder to know which classes you are using from the package.

package com.amigoscode;

import java.util.*;

Here is an example with multiple imports

package com.amigoscode;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

You are not just limited to import existing packages and classes. You can import your own as follows

  1. Right click on com.amigoscode, the create package and name it model for example

Screenshot 2021-08-19 at 11 22 00
  1. Create a class called Person inside com.amigoscode.model package

Screenshot 2021-08-19 at 11 31 37
Screenshot 2021-08-19 at 11 30 50
  1. Inside the class Main, have a look at the import statement.

package com.amigoscode;

import com.amigoscode.model.Person;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Person person = new Person();
    }
}

Comparison Operators

Comparison operators are used to compare values and return true or false

Operator
Sign
Example

Equal to

==

a==b

Not equal to

!=

a!=b

Less than

<

a<b

Greater than

>

a>b

Less than or equal to

<=

a<=b

Greater than or equal to

>=

a>=b

Logical Operators

Logical operators are used to combine 2 more or more comparison operators

Operator
Sign
Example

And

&&

a==b

Or

||

a!=b

Conditions and If Statements

If statements allows you decide weather to execute code based on the result of boolean expressions. Any code which returns true or false can be used with if statements.

Java has the following conditional statements:

  • if

  • else

  • else if

  • switch

if

if (condition) {
  // block of code to be executed if the condition is true
}
if (1 > 0) {
  System.out.println("1 is greater than 0");
}

else

if (condition) {
  // block of code to be executed if the condition is true
} else {
  // block of code to be executed if the condition is false
}

else if

if (condition1) {
  // block of code to be executed if condition1 is true
} else if (condition2) {
    // block of code to be executed if above condition is false
} else if (condition3) {
  // block of code to be executed if above all conditions are false
} else {
    // block of code to be executed if above all conditions are false
}

Switch

The switch statement allow you to replace multiple nested if else statements. The break keyword is used to terminate a statement. The break statement is optional. If omitted, execution will continue on into the next case.

int day = 4;

switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    case 6:
        System.out.println("Saturday");
        break;
    case 7:
        System.out.println("Sunday");
        break;
    default:
        System.out.println("Invalid day");
}

Reading User Input with Scanner class

Note the import statement

package com.amigoscode;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter username");

        String userName = scanner.nextLine();  // Read user input
        System.out.println("Username is: " + userName);
    }
}

nextLine() reads Strings input. There are other methods available for different data types.

Last updated

Was this helpful?