Java Basics #1

Simple Java program:

public class Main {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}
Every line of code that runs in Java must be inside a class. In our example, we named the class Main. A class should always start with an uppercase first letter.

The main Method

The main() method is required and you will see it in every Java program.

Any code inside the main() method will be executed. You don't have to understand the keywords before and after main.


System.out.println()

Inside the main() method, we can use the println() method to print a line of text to the screen.


Java Comments

Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code.

Single-line comments start with two forward slashes (//).

Java Variables

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

  • String - stores text, such as "Hello". String values are surrounded by double quotes
  • int - stores integers (whole numbers), without decimals, such as 123 or -123
  • float - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  • boolean - stores values with two states: true or false.

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value.

type variable = value;

Where type is one of Java's types (such as int or String), and variable is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

Example:

String name = "John";

System.out.println(name);

Final Variables

However, you can add the final keyword if you don't want others (or yourself) to overwrite existing values (this will declare the variable as "final" or "constant", which means unchangeable and read-only).

Example:

final int myNum = 15;

myNum = 20;  // will generate an error

Other example:

int myNum = 5;

float myFloatNum = 5.99f;

char myLetter = 'D';

boolean myBool = true;

String myText = "Hello";


Display Variables

The println() method is often used to display variables.

To combine both text and a variable, use the + character.

String name = "John";

System.out.println("Hello " + name);

You can also use the + character to add a variable to another variable.

For numeric values, the + character works as a mathematical operator (notice that we use int (integer) variables here).

Java Identifiers

All Java variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

// Good

int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is

int m = 60;

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs
  • Names must begin with a letter
  • Names should start with a lowercase letter and it cannot contain whitespace
  • Names can also begin with $ and _ (but we will not use it in this tutorial)
  • Names are case sensitive ("myVar" and "myvar" are different variables)
  • Reserved words (like Java keywords, such as int or boolean) cannot be used as names

Java Data Types

As explained in the previous chapter, a variable in Java must be a specified data type.

Example:

int myNum = 5;               // Integer (whole number)

float myFloatNum = 5.99f;    // Floating point number

char myLetter = 'D';         // Character

boolean myBool = true;       // Boolean

String myText = "Hello";     // String


Primitive Data Types

A primitive data type specifies the size and type of variable values, and it has no additional methods.

There are eight primitive data types in Java.

Data TypeSizeDescription
byte1 byteStores whole numbers from -128 to 127
short2 bytesStores whole numbers from -32,768 to 32,767
int4 bytesStores whole numbers from -2,147,483,648 to 2,147,483,647
long8 bytesStores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float4 bytesStores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double8 bytesStores fractional numbers. Sufficient for storing 15 decimal digits
boolean1 bitStores true or false values
char2 bytesStores a single character/letter or ASCII values

Numbers

Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are byteshortint and long. Which type you should use, depends on the numeric value.

Floating point types represents numbers with a fractional part, containing one or more decimals. There are two types: float and double.


Java Type Casting

Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

  • Widening Casting (automatically) - converting a smaller type to a larger type size
    byte -> short -> char -> int -> long -> float -> double

  • Narrowing Casting (manually) - converting a larger type to a smaller size type
    double -> float -> long -> int -> char -> short -> byte

Widening Casting

Widening casting is done automatically when passing a smaller size type to a larger size type.

Example:

public class Main {
  public static void main(String[] args) {
    int myInt = 9;
    double myDouble = myInt; // Automatic casting: int to double
    System.out.println(myInt);      // Outputs 9
    System.out.println(myDouble);   // Outputs 9.0
  }

}


Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses in front of the value.

Example:

public class Main {
  public static void main(String[] args) {
    double myDouble = 9.78;
    int myInt = (int) myDouble; // Manual casting: double to int
    System.out.println(myDouble);   // Outputs 9.78
    System.out.println(myInt);      // Outputs 9
  }
}


Comments

Popular posts from this blog

Java Basics #3

Java Basics #4