Basic Java: Fundamentals of Java

Java is a versatile and powerful language to build desktop, web and mobile applications. It’s high level, object oriented, platform independent and easy to learn for beginners. Java was developed by James Gosling and released by Sun Microsystems in 1995.

Here are some of the key features of Java that makes it a powerful and favorite language for developers around the world:

  • Simple and easy to learn
  • Object-oriented
  • Platform independent
  • Secure
  • Multi-threading support
  • Distributed
  • Robust
  • Portability
  • Versatility
  • High performance
  • Dynamic and extensible
  • Rich standard library
  • Scalable
  • Open-source community
  • Automatic garbage collection

These are some key features of Java that makes Java a reliable, secure and powerful choice for developers whether building small projects or large enterprise systems. I have explained all these features in previous tutorial if you haven’t read it. Now we will see basic Java concepts with examples, and quizzes.

Basic Java Topics

Basic Java or Fundamental Java

1. Java character Set:

Java supports a rich character set to represent alphabets, digits, and special symbols. The character set includes:

  • Letters: A-Z (uppercase), a-z (lowercase)
  • Digits: 0-9
  • Special Characters: {, }, +, -, etc.
  • Whitespace Characters: Space, tab (\t), newline (\n), etc.

Example:

public class CharacterSetExample {
    public static void main(String[] args) {
        char letter = 'A';
        char digit = '5';
        char specialChar = '@';
        System.out.println("Letter: " + letter);
        System.out.println("Digit: " + digit);
        System.out.println("Special Character: " + specialChar);
    }
}

The output of the given basic Java program will be:

Letter: A
Digit: 5
Special Character: @

In this example, we have assigned the character ‘A’, digit ‘5’, and a special character ‘@’ to variables named letter, digit, and specialChar, respectively. Then, we have printed these values on the console using the System.out.println() statement.

2. Java Tokens:

Tokens are the smallest elements (or units) of a Java program that are identified by Java compiler. In simple words, a Java program is a group of tokens, comments, and white spaces. For example:

int age = 35; // 'int' is a keyword, 'age' is an identifier, and '25' is a literal.

In this example, we have declared a variable named age of type int and assigned a value 35 to it. Here, int is a keyword, age is an identifier, and 35 is a literal.

Java has five main types of tokens:

  • Keywords
  • Identifiers
  • Literals
  • Operators
  • Separators

Let’s understand one by one with the help of examples.

3. Reserved Keywords:

Java has the list of 50 reserved keywords, which have special meanings and cannot be used as identifiers as variable, method, or class names. Reserved keywords are predefined words in Java with specific meanings. These keywords are the backbone of Java’s syntax and structure.

Some commonly used reserved keywords or reserved words are as follows:

  • Data Types: int, float, double, char
  • Control Flow: if, else, switch, while
  • Modifiers: public, private, static, final
  • Others: class, void, return

For example:

public class KeywordExample {
    public static void main(String[] args) {
        int number = 10; // 'int' and 'public' are keywords
        System.out.println("Number: " + number);
    }
}

In this example, the reserved keywords are class, public, static, void, and int.

Here is the full list of 50 reserved keywords in Java.

abstractcontinuefornewswitch
assertdefaultgotopackagesynchronized
booleandoifprivatethis
breakdoubleimplementsprotectedthrow
byteelseimportpublicthrows
caseenuminstanceofreturntransient
catchextendsintshorttry
charfinalinterfacestaticvoid
classfinallylongstrictfpvolatile
constfloatnativesuperwhile

4. Identifiers in Java

Identifiers are names used to identify elements in a Java programming, such as variables, methods, classes, objects, parameters, packages, etc. An identifier in Java is a sequence of letters, digits, and underscore characters.

Basic Rules for Identifiers in Java

There are some basic rules for the identifier in Java that you should follow while naming:

  • Must begin with a letter, an underscore (), or a dollar sign ($).
  • After the first character, identifiers can include letters, digits, or underscore/dollar sign.
  • Cannot use spaces, special symbols (except and $), or Java keywords.
  • Case-sensitive: area, Area, and AREA are treated as distinct identifiers.
  • Should be meaningful to improve code readability and maintainability.

Examples of Valid Identifiers

  • Student
  • num1
  • _name
  • $price
  • lengthAndBreadth

Examples of Invalid Identifiers

  • 123num (starts with a digit)
  • length@width (contains @, which is not allowed)
  • int (a reserved keyword)
  • area length (contains a space)

Identifiers are Case-Sensitive

Java treats identifiers as case-sensitive. This means that area, Area, and AREA are three different identifiers.

Best Practices for Naming Identifiers

  • Use camelCase for variables and methods. For example, studentName, calculateSum.
  • Use PascalCase for class names. For example, StudentRecord.
  • Avoid using $ or _ unless required. For example generated code.
  • Always use meaningful and descriptive names. For example, areaOfRectangle instead of aor.

4. Java Comments

In Java or any other programming languages, comments are used to explain the code to improve its readability and help developers to understand the logic. They are ignored by the Java compiler because JVM does not execute the comments in the program. Therefore, they have no effect on the execution of the program. You can also use comments to disable a portion of the code temporarily during debugging.

Types of Comments in Java

There are three basic types of comments in Java. They are as:

  • Single-line comments
  • Multi-line comments
  • Documentation comments

1. Single-Line Comments:

A single-line comment, also known as inline comment is used to write the brief explanation about the code. It starts with a double slash symbol “//” and after this, whatever you will write till the end of the line is considered as a comment. For example:

// Declaring a variable of type int and assigning a value 5 to it.
   int num = 5; // This is a single-line comment.

2. Multi-line Comments:

A multi-line comment is used to write a longer explanation or to comment out blocks of code. It is generally used to comment the code in several lines.

Multi-line comment starts with / * and end with * /. Whatever you will write in between / * and * /, will be treated as a comment by Java and everything will ignore by Java compiler until it finds this */. For example:

/* This is a multi-line comment
   It spans multiple lines
   Useful for larger explanations */

3. Documentation Comments:

A documentation comment is used to generate documentation using Java’s Javadoc tool. This type of comment starts with / * * and end with * /. An example of documentation comment is as:

/**
 * This class demonstrates documentation comments.
 * @author John Doe
 * @version 1.0
 */
public class DocumentationComment {
    /**
     * This is the main method.
     * @param args Command-line arguments
     */
    public static void main(String[] args) {
        System.out.println("Documentation comment example");
    }
}

Best Practices for Using Comments

There are the following key points while using comments in Java program that you should keep in mind. They are:

  • Use comments whenever necessary to explain complex logic or algorithms.
  • Avoid over-commenting about the code.
  • Try to write self-explanatory code instead.
  • Keep comments relevant.
  • Update comments whenever the code changes to prevent confusion.
  • Use Javadoc comments for public APIs and methods to make the code easier to document.

5. Escape Sequences

Escape Sequence in Java is a special type of character literal used to control printed or displayed output. It allows you to format text output or include special symbols without breaking the code syntax.

Escape sequence consists of a backslash () followed by one or more character or a combination of digits that together form a sequence. It is useful when you want to insert a special character that is not easily displayed directly (like newlines, tabs, quotes, etc.).

Common Escape Sequences in Java

1) Newline or Line feed (\n):

  • Moves the cursor to the beginning of the next line.

Example:

System.out.println("Hello\nWorld");
// Output:
// Hello
// World

2) Tab (\t):

  • Inserts a horizontal tab, which adds space between characters.

Example:

System.out.println("Hello\tWorld");
// Output: Hello   World

    3) Carriage Return (\r):

    • Moves the cursor to the beginning of the current line (overwrites text).

    Example:

    System.out.println("Hello\rWorld");
    // Output: World (Hello is overwritten by World)

    4) Single Quote (\’):

    • Used to insert a single quote character (‘).

    Example:

    System.out.println("It\'s a sunny day.");
    // Output: It's a sunny day.

    5) Double Quote (\”):

    • Used to insert a double quote character (“).

    Example:

    System.out.println("He said, \"Hello!\"");
    // Output: He said, "Hello!"

    6. Backslash (\\):

    • Used to insert a backslash character (\).

    Example:

    System.out.println("C:\\Users\\Name");
    // Output: C:\Users\Name

      7) Backspace (\b):

      • Moves the cursor one position back.

      Example:

      System.out.println("Hello\bWorld");
      // Output: HellWorld (the 'o' is erased)

      8) Form Feed (\f):

      • Moves the cursor to the next page (rarely used in modern applications).

      Example:

      System.out.println("Hello\fWorld");
      // Output: Hello (moves to the next page and prints World)

      9) Unicode Character (\u):

      • Inserts a Unicode character based on its code point (4 hexadecimal digits).

      Example:

      System.out.println("\u0048\u0065\u006C\u006C\u006F");
      // Output: Hello (Unicode for 'Hello')

      Here, we have explained about basic Java or fundamental Java in which we have discussed some important topics, such as Java character sets, tokens, reserved keywords, identifiers, comments, and escape sequences. In the next tutorial, we will learn about other basic Java topics such as data types, variables, operators, and control statements.

      Please Share Your Love.

      Leave a Reply

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