Introduction to Java for beginners
Tags: java, beginners, programming, computerscience
Published: 2022-08-26 03:17:00

## Overview
Java is a high level OOP language. It is one of the most popular languages due to its platform independent nature, which is especially important for softwares that are required to work on multiple operating systems. This is because Java code are compiled to bytecode that can be executed on any Java virtual machine(JVM) across different platforms without recompilation.

![Java compilation process](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ofocryne6w28cche6fb.png)

_________________

##Introduction to Java

**Your first Java application: Hello World**
```java
// This is a comment

/* This is a 
multi-line comment */

/**
 * The HelloWorldApp class implements an application 
 * that prints the string "Hello World!" to the screen.
 */
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!"); 
    }
}
```
+ Every program in Java is enclosed within a class definition. In this case, the class name is `HelloWorld` and the class definition is `class HelloWorld {...}`.
+ The `main` method is the entry point of any Java program where the JVM will begin program execution. 
+ Don't worry if you don't understand the meaning of `class`, `public`, `static` for now. It will be discussed in the OOP articles which will be posted in the future.

_________________

**Java JDK, JRE, JVM**
In short, we use the **Java Development Kit(JDK)** to build Java applications. When you download the JDK, it comes with a compiler, the **Java Runtime Environment(JRE)**. The JRE provides a library of classes and the **Java Virtual Machine(JVM)** which is used to execute Java bytecode.

![Java JDK, JRE, JVM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fmo2tnowb8cy7ix1qjjq.png)
_________________

**Java Variables**
```java
// Method 1 to declare variables
int num = 7;

// Method 2 to declare variables
int num;
num = 7;

// Assigning a new value
num = 10; // num is now 10

// To make this variable unchangeable, use the 'final' keyword
final int fixedNum = 1;
fixedNum = 2; // Generates an error
```
_________________

**Java Data Types**
The data type should be specified during a variable declaration. Java data types can be categorised into 2 groups, namely **primitive types** and **reference types**.

+ Primitive data types:

| Data Type | Size(bits) | Description | 
|-----------|------------|-------------|
| byte      | 8        | Whole numbers from -128 to 127 |
| short     | 16       | Whole numbers from -32,768 to 32,767 |
| int       | 32       | Whole numbers from -2<sup>31</sup> to 2<sup>31</sup>-1 |
| long      | 64       | Whole numbers from -2<sup>63</sup> to 2<sup>63</sup>-1 |
| float     | 32       | Fractional numbers with 6-7 decimal digits precision |
| double    | 64       | Fractional numbers with 15-16 decimal digits precision |
| boolean.  | 1        | true or false values |
| char      | 16       | a single Unicode character |

+ Reference data types:

**Primitive types** are basic types that **stores values**. Non-primitive types, also known as **reference types**, **store the address** of dynamically created objects. They provide access to the objects stored in the memory. Say we have a class named `Animal` and we create an object `cat`, then the variable `cat` is considered a reference type. Some examples of reference types are `String`, `Array`, `class`, `interface`, etc. 
_________________

**Java Type Casting**
Type casting is assigning a value of one primitive data type to another primitive data type. In Java, there are 2 types of casting: 
+ **Widening casting (implicit)** -
It happens automatically when we try to store a value of smaller size type to a larger size type.
+ **Narrowing casting (explicit)** - 
It is done manually when we want to convert a value of larger size type to a smaller size type.

```java
// Example of widening casting: short(2 bytes) to int(4 bytes)
short x = 1; 
int y = x;

// Example of narrowing casting
int x = 1;
short y = (short) x;
```
![Java type casting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vy5tuwrlyu3en8y0zq4l.png)
_________________

**Java Input and Output**

There are a few ways to display the ouput to the standard output(screen).

| Method | Description |
|--------|-------------|
| print() | prints string inside the quotes |
| println() | prints string inside the quotes and inserts a new line |
| printf() | print formatted strings according to format specifiers |

Java also provides several ways to get user input. The most simple way is to create an object from the `Scanner` class as follows:

```java
// Import java.util.Scanner package to use the Scanner class
import java.util.Scanner;

// Create an object of Scanner
Scanner input = new Scanner(System.in);

// Take input from the user
int number = input.nextInt();

// Print user input
System.out.println("You entered " + number);
```
_________________

**Java Flow Control**
+ If-else statements:

```java
if (condition) { 
    // statement
} else if (condition) {
    // statement
} else (condition) {
    // statement
}
```
+ Ternary operator (shorthand for if-else statements):

```java
// Syntax: (condition) ? Expression 1 : Expression 2

/* Example: If marks is more than 40, assign grade as "Pass", 
otherwise assign it as "Fail" */
String grade = (mark > 40) ? “Pass” : “Fail”;
```
+ Switch statements:
```java
/* Syntax: 
switch (expression) {
  case value1:
    // code
    break;
  case value2:
    // code
    break;
  ...
  default:
    // default statements
}
*/

// Example: 
char size = "M"

switch (size) {
      case "S":
        size = "small";
        break;

      case "M":
        size = "Medium";
        break;

      case "L":
        size = "Large";
        break;
      
      default:
        size = "Unknown";
        break;
}
```
`break` statements are used to "jump out" of switch statements or loops and `continue` statements skip the current iteration of a loop if the specified condition is true.

+ While loops

```java
// While loop syntax
while (condition) {
    // code block to be executed
}

// Do...while loop syntax
do {
  /* Code here will be executed once before checking if it
     it true or false, then it will repeat the loop as long as
     it satisfies the condition. 
  */
}
while (condition);
```

+ For loops

```java
// For loop syntax
for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

// Example
int[] numbers = {1, 2, 3, 4};

for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

// For...each loop syntax
for (type variableName : arrayName) {
  // code block to be executed
}

// Example
int[] numbers = {1, 2, 3, 4};

for (int number : numbers) {
    System.out.println(number);
}
```
_________________

**Java Arrays**
Arrays are used to store a list of objects of the same type.

```java
// Declaring an array to store marks
int[] marks;

// Allocate memory 
marks = new int[3]

// We can declare and allocate memory in one line
int[] marks = new int[3];

// Initialise the array
marks = { 75, 80, 90 }
```