Java Tutorial – Language Fundamentals for Beginners with Examples

Java Tutorial – Language Fundamentals for Beginners with Examples

In this tutorial we will cover Core Java Language Fundamentals and provide adequate examples to help facilitate your learning. We will cover core topics like, Primitives, Variables, Operators, Separators and Object-Oriented concepts.

What’s Covered

  1. Primitives
    1. Numeric Primitives
    2. char Primitive
    3. boolean Primitive
  2. Variables
  3. Java Variable Types
    1. Instance Variables
    2. Class Variables
    3. Local Variables
    4. Parameters
  4. Java Variable Declaration and Assignment
  5. Java Constants

Primitives

The Java programming language is strongly-typed, meaning all variables must be declared before they may be used. In Java there are eight (8) primitives types, each with their own format and size. Six out of the eight primitives are numeric, one is character, and the last one is boolean. Let’s look at the following example and see how to declare and assign variables in Java:

  • boolean is_active = false;

In the above example, we declare a boolean variable whose name is is_active and whose value has been assigned as false.

Numeric Primitives

A byte is 8 bits long so it can only have 256 possible values. However, since the byte primitive is a signed number it only supports values from -128 to 127. The first 128 numbers are for numbers ranging from -128 to -1, then 0 takes a spot and 1 through 127 take the remaining values.

We should use short when we know that data type is integer value and it will not exceed the 32k limit imposed by a short. The primitive int can store numbers ranging from -32,768 to 32,767 and uses two-bytes. This will save us two bytes of space as the short is only 16-bits as well as performance gains versus the primitive int and long especially when being used in arrays. However, most of the time the JIT compiler may be able to optimize this and the net effect on performance may be negligible.

If you need to use store longer values then use should use int. The primitive int can store numbers ranging from -2,147,483,648 to 2,147,483,647 so this primitive is probably so one that is used most often. Personally, I generally rely on using the primitive int for most of my applications.

When you are required to store huge values in your applications the primitive long must be used. This primitive can store values that range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. It uses eight bytes (64 bits) to store these extremely large values.

At this point, we have covered all of the primitives that can handle whole numbers or integers. If you need to store numbers with decimals points then you will need to rely on using float and double.

The floating-point types float and double are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985.

Rule of Thumb

As a general rule, you should consider the length and type of data you will be storing and use a primitive that is large enough to accomodate your storage requirements and yet small enough that you’re not arbitrarily wasting space.

char Primitive

The primitive char can store a single Unicode character such as ‘A’, ‘c’, or ‘$’. In addition using Unicode allows it to contain characters outside of those used in the English alphabet including characters like ‘ñ’, ‘ù’ or ‘ä’.

boolean Primitive

The primitive boolean can only store two possible values (true or false).

PrimitiveRangeDescription
byte-128 to 127Byte integer(8 bits)
short-32,768 to 32,767Short integer, Two-Bytes (16 bits)
int-2,147,483,648 ~ 2,147,483,647Integer, Four-Bytes (32 bits)
long-9,223,372,036,854,775,808
~ 9,223,372,036,854,775,807
Long Integer, Eight-Bytes (64 bits)
float14e-45 ~ 3.4028234e38Single Precision floating point (32 bits)
double4.9e-324 ~ 1.7976931348623157e308Double Precision floating point (64 bits)
char\u0000 ~ \uffffCharacter data type, 16-but Unicode character
booleantrue or falseBoolean data type, only supports true/false

Variables

Variables are used to hold data while the application is running. All computer programming languages have the concept of variables and use it to one degree or another in much the same way. A variable is used to store data coming from many different mediums like (keyboard, disk, mouse, internet, biometric sensors, state changes, or by interactions with other applications, etc). We will store the values read from these mediums into the variables, sometimes maniulate it in some way or interact with this data and make decisions based on this data and then often times write this data back out to other mediums like (disk, internet, database, console, printer, etc).

Java Variable Types

The Java programming language defines four types of variables:

  • Instance Variables (non-static fields)
  • Class Variables (static fields)
  • Local Variables
  • Parameters

    Instance Variables (non-static fields)

    Objects store their state in “non-static fields” or instance variables, that is, fields that do not have the static keyword. The values stored in instance variables are unique to each instance of a class. In other words, every instance of our class Customer contains four instance variables (non-static fields) and the values contained in each instance will be unique to that instance of the class.

    public class Customer {
      private String customerId;
      private String firstName;
      private String lastName;
      private int age;
        
      ...
    }
    

    Class Variables (static fields)

    Class variables are declared with the static keyword. Class variables (static fields) belong to the class and not to any individual instances of the class. The value that is stored in a class variable will be the same for all instances of that class. A variable declaring the Logger log for our class Customer would create a static field and all instances would share this same value.

    public class Customer {
      public static final Logger log 
               = LoggerFactory.getLogger(Customer.class);
        
      private String customerId;
      private String firstName;
      private String lastName;
      private int age;
        
      ...
    }
    

    Local Variables in Java

    Local variables in Java are declared inside methods. These local variables are only accessible within the body of the method in which they are declared. The local variable’s scope is from the opening curly brace ‘{‘ until the closing curly brace ‘}’ of that method. These variables are only visible to the method in which they are declared and may not be used anywhere else in the class. Other methods are not even aware that the variables exist.

    public void calculateRewards() {
      int rewardsPoints = 0;
      int currentYearlySales = 0;
    
      ...
    }
    

    Parameters

    Parameters in Java are declared within the parenthesis of the method itself, commonly called the method declaration. Additionally, parameters are always called variables and not fields. Parameters are used as a mechanism to pass values into the method being called. Some people may also refer to parameters as arguments, although I would argue that the latter has more to do with the value of the instance that is passed at runtime.

    In the example below, you will notice that I am passing two parameters, rewardPoints and Sales, to the showRewardAndSales method. These two parameters are then used in the method and finally displayed in the console using a System.out.println() statement.

    public void showRewardAndSales(int rewardPoints, int Sales) {
    
      ... // do something...
        
      System.out.println("Reward Points Earned..: " + rewardPoints);
      System.out.println("Current Yearly Sales..: " + Sales);    
    }
    

Java Variable Declaration and Assignment

In Java we declare variables by writing the type followed by the name of the variable followed by a semicolon.

Variable Declaration

In the following example I will declare all of the primitives available in Java.

byte myByte;
short myShort;
int myInt;
long myLong;
float myFloat;
double myDouble;
char myChar;
boolean myBoolean;

Declare Multiple Variables at Once

We can declare mutliple variables having the same type on the same line by using a comma as separator between each of the variables.

int x,y,z;
char mySeparator, myLineBreak, myPageBreak;
boolean isActive, isAlive;

Warning

I don’t recommend using the multiple declaration approach as I feel it reduces readability in the code.

Variable Assignment

In the following example I will declare all of the primitives available in Java.

byte myByte = 20;
short myShort = 100;
int myInt = 30293;
long myLong = 89303;
float myFloat = 192.75;
double myDouble = 10920.373;
char myChar = '|';
boolean myBoolean = false;

Java Constants

A constant is a variable whose value that cannot be changed once it has been assigned. In Java, we declare constants using the final keyword. When declaring constants, we use ALL CAPS in the constant name and use underscore (_) as word separators.

final int MAX_FILES = 25;
final double PI = 3.141592653589;

Java Constants using Static and Final

In general, I prefer to declare constants using both static and final. As explained earlier, using the static keyword will make the variable a class variable so only one variable is created per class. Using the final keyword tells Java that the reference address to the value of the variable may not be altered.

public class MyClass {
  private static final int MAX_FILES = 25;
  private static final double PI = 3.141592653589;
  
  ...
}

What the final keyword means is that once the value has been assigned to MAX_FILES and PI, it cannot be re-assigned a new value.

language_fundamentals

Core Java Related Tutorials

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *