Maker Pro
Custom

Basic Java Constructs for Beginners

January 01, 2019 by Daniel Hertz
Share
banner

Learn the important basic constructs for the programming language, Java, which can be run on any platform.

This article should serve as a cheat-sheet and introduce you to the basic constructs of the Java programming language so you can quickly get started.

If you haven't already, get started with Java by learning the most important concepts for beginners.

Variables and Casting

Java is a strongly typed language, meaning you have to define a variable’s type before compiling your program and variables can’t change the assigned type. A variable declaration looks like this:

[access_modifier] [static] [final] type name [= value];

For example:

public int user_age = 38;
static string location;

Storing Values in Variables With Different Types

Even though variables can’t change their type, you can store a value in a variable with a different type. This can happen implicitly, if the value is of a smaller size than the receiving variable, or you have to explicitly cast the value to fit into the variable:

recieving_variable = (type_of_recieving_variable) value;

For example:

// Implicit casting
double d = 20.5;
d = 180; // An integer is smaller than a double

// Explicit casting
int a;
a = (int) -12389.77213;

Extracting a Numeric Value From a String

However, casting is only possible for primitive data-types and will often lead to a loss of information (for example when casting a floating point number to an integer).

You can also try to extract a numeric value from a String by using the standard functions:

int i = Integer.parseInt(“872100003”);
double d = Double.parseDouble(“9999.99”);
float f = Float.parseFloat(“-762.982”);

However, this method might throw an exception when you try to parse a non-numeric value.

Methods

To declare a method use the following syntax:

[access_modifier] [static] return_type name([param1[, param2[, param3[, ...]]]])
{
    [return return_value;]
}

If your method doesn’t return a value, use “void” as the return_type. Parameters are entirely optional but they have to consist of a type and a name and have to be separated by commas. Some examples:

public static void main(int[] args)
{ }

int calculateResult(int a, float second, char mod)
{
    return 0;
}

private void procedureA()
{ }

Overloading Constructors

Methods can be overloaded by using the same name for multiple methods with different parameter lists. They can be overridden in a subclass by using the same signature. Abstract methods are possible—refer to this intro to Java to learn more about them.

The constructor is a special method and it’s the only one that’s not allowed to have any return type (not even void). Constructors are typically defined as public methods and they must have the same name as the class they’re declared in. You can overload the constructor with different parameter lists:

public class Tree
{
    // Default constructor without parameters
    public Tree()
    { }

    public Tree(int height, int age)
    { }

    public Tree(int height, int age, String name)
    { }
}

if-statements

If-statements can be used to program alternative paths and for decision-making. The definition is pretty straight-forward:

if(condition)
{
    // Do something if the condition was met
}
else if(alternative_condition)
{
    // (optional) condition was false and alternative_condition was true
}
else
{
    // (optional) Do something when both conditions were not met
}

The conditions can be any Boolean value. For example, the result of a comparison or any variation of logical conjunctions and disjunctions of Boolean values looks like:

if(a < 1230)
{ }
else if(b == ‘a’ && x <= 29)
{ }
else if((b == ‘c’ && x == 23) || (b == ‘d’ && x > 29))
{ }
else
{ }

switch-statements

These can be used to replace long if-else-clauses and to handle different cases. For example:

int a = Integer.parseInt(input);

switch(a)
{
    case 0:
        // a was zero
        break;

    case 1:
        // a was one
        break;

      default:
        // a was any other value
        break;
}

while-loops

The code inside of one a while-loop will be executed as long as a certain condition is met. The condition can be any Boolean value. For example:

int a = 100;

while(a > 0)
{
    // Do something

    a = a - 1;
}

for-loops

These can be used just like while-loops and both are fully interchangeable. However, this type of loop can be initialized with a variable that gets changed with every iteration of the loop and therefore you can simplify the while-loop example from above:

for(int a = 0; a > 0; a = a - 1)
{
    // Do something
}

However, because you can use both loops in the same way, you can also make the for-loop behave like a while-loop:

int a = 100;
   	 
for(;;)
{
        // Do something

        a = a - 1;
       	 
        if(a == 0)
            break;
}

Use This as a Cheat Sheet to Get Started!

I hope this article helped you to understand the basic constructs of the Java programming language and will serve you as a handy cheat-sheet you can come back to if you quickly need to look something up.

Related Content

Comments


You May Also Like