Basic Concepts of Java

Mannan Ul Haq
0

Java Syntax:

Let's begin by analyzing and breaking down a simple Java code snippet:

class MyFirstApplication
{
    public static void main(String[] args)
    {
        System.out.println("Hello, World!");
    }
}

Explanation of the code:


1. class MyFirstApplication { }: This line defines a class named MyFirstApplication. In Java, every application must contain a main class that wraps all the program's logic.

Note: In Java, the name of the file should match the name of the public class in that file. This is a rule of the Java language, and Java will return a compilation error if you try to compile a .java file where the filename and the public class name do not match. If your .java file doesn't contain any public classes, or more than one class, then the file name does not need to match the name of the classes in the file. Here, I am not using a Public class so there will be no issue. Don't worry if you did not understand this, we will learn about classes in detail in the later tutorials.

2. public static void main(String[] args) { }: This line defines the main method, which is the entry point for any Java application. The JVM (Java Virtual Machine) calls the main method when the program starts.

  • The keyword `public` denotes that this method can be accessed from anywhere—within this class, from other classes in the same package, subclasses, and elsewhere in your application.
  • The `static` keyword allows the main method to be called without creating an instance of the class. This is necessary because main() is called by the JVM before any objects are made. The method must be static to be accessible.
  • The keyword `void` implies that this method does not return any value.
  • The parameters `String[] args` are an array of strings passed to the main method, which can be used for handling command-line arguments.

3. System.out.println("Hello, World!");: This line of code prints the string "Hello, World!" to the console. `System.out` corresponds to the standard output stream in Java, and `println` is a method that prints the argument passed to it and moves the cursor to a new line.

Note: Every Java statement ends with a semicolon ;.


Output in Java:

In Java, 'System.out.println()' and 'System.out.print()' methods are used to display output to the console. These methods belong to the 'PrintStream' class which is accessible through the 'out' static member field of the 'System' class. They play an integral role in interacting with users, providing feedback, and displaying information in Java console applications.

1. `System.out.println()`:

The 'System.out.println()' method is used to print text or data to the console followed by a new line. It automatically appends a newline character after the output, meaning each subsequent output appears on a new line.

Example:

System.out.println("Hello World!");
System.out.println("Welcome to CodeTechMentor!");
System.out.println(123);

Output:

Hello World!
Welcome to CodeTechMentor!
123

2. `System.out.print()`:

The 'System.out.print()' method is similar to 'System.out.println()', but it does not append a newline character after the output. Consequently, consecutive outputs will appear on the same line.

Example:

System.out.print("Hello, ");
System.out.print("this is ");
System.out.print("a single line output.");

Output:

Hello, this is a single line output.


Comments in Java:

Comments in Java provide explanatory text within the source code for understanding the functionality of the code better. They are completely ignored by the Java compiler and do not influence the execution of the program. There are two types of comments in Java:

Single-line comments:

Single-line comments start with `//` and continue until the end of the line. Anything following `//` on the same line is considered a comment.

// This is a single-line comment
System.out.println("Hello, World!"); // This line of code prints "Hello, World!" to the console

Multi-line comments:

Multi-line comments begin with `/*` and end with `*/`. They can span multiple lines and are often used for longer explanations or temporarily disabling blocks of code.

/* This is a multi-line comment
   It can span multiple lines
   System.out.println("This line is commented out."); */
System.out.println("Hello, World!");


Data Types in Java:

In Java, every variable has a data type, which decides the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

There are two types of data types in Java:

1. Primitive Data Types: These include byte, short, int, long, float, double, char, and boolean. They are called "primitive" because they are the built-in data types. The size and type of variable values are defined and have no additional methods.

2. Non-Primitive Data Types: These are created by the programmer and are not defined by Java (except for String). Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot. They include Classes, Interfaces, and Arrays.


Here's a detailed breakdown of these data types:

Data Type Size (in bytes) Description
byte 1 The `byte` data type can store whole numbers from -128 to 127.
short 2 The `short` data type can store whole numbers from -32,768 to 32,767.
int 4 The `int` data type can store whole numbers from -2,147,483,648 to 2,147,483,647.
long 8 The `long` data type can store whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
float 4 The `float` data type can store fractional numbers from 3.4e−038 to 3.4e+038. Sufficient for storing 6 to 7 decimal digits.
double 8 The `double` data type can store fractional numbers from 1.7e−308 to 1.7e+308. Sufficient for storing 15 decimal digits.
boolean 1 bit The `boolean` data type is used to store only two possible values: `true` and `false`. This data type is used for simple flags that track true/false conditions.
char 2 The `char` data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c'.
String (non-primitive) Varies The `String` data type is used to store a sequence of characters (text). String values must be surrounded by double quotes.



Variables in Java:

A variable is a named storage location that holds a value of a specific data type. Variables need to be declared before they can be used. The syntax for declaring a variable is: `data_type variable_name = value;`.

int num = 10;
System.out.println(num);

In this example, we declare a variable called `Num` of type `int` and assign it the value `10`. Later, we use `System.out.println()` to display the value of `Num`, which will output `10` to the console.


You can also declare a variable without assigning the value immediately and assign the value later:

int num;
num = 20;
System.out.println(num);


Please note that in Java, if you assign a new value to a variable that already has a value, the previous value will be overwritten:

int x = 5;  // x is assigned the value 5
x = 10;     // The value of x is updated to 10
System.out.println(x);  // Outputs 10

Other Data Types in Java:

Java supports a variety of data types to accommodate different types of data. Here's a demonstration of different common data types in Java:

int Num = 10;               // Integer (whole number without decimals)
double Float = 12.66;    // Floating-point number (with decimals)
char Letter = 'A';         // Character
String Text = "Hello";     // String (text)
boolean Bool = true;       // Boolean (true or false)

These data types allow you to work with a wide range of data in your Java programs.

NOTE: The float and double data types have the ability to store fractional numbers. It is important to remember that when assigning values to these data types, you must use an "F" suffix for floats and you can also use a "D" suffix for doubles but it is not compulsory. (alert-success)

 

float myFloat = 3.14F; // Note: The "F" suffix indicates a float value
System.out.println(myFloat);

double myDouble = 123.456D; // In java, you don't need a "D" suffix, though it's allowed.
System.out.println(myDouble);



Identifiers in Java:

Identifiers are names given to different entities such as variables, methods, classes, packages and interfaces. Identifiers in Java are user-defined names that help to identify and refer to these entities within the code. The rules for naming identifiers in Java are as follows:

  • Identifiers can include letters, digits, and underscores (_), and dollar signs ($).
  • The first character of the identifier must be a letter, an underscore, or a dollar sign. They cannot start with a digit.
  • Identifiers are case-sensitive (`age` and `Age` are different).
  • Names cannot contain whitespaces or special characters like !, #, %, etc.
  • Reserved keywords (e.g., `int`, `float`) cannot be used as identifiers.


White-Space in Java:

In Java, whitespace refers to spaces, tabs, and newlines used for formatting and separation of code elements. Whitespace is generally ignored by the compiler and serves the purpose of enhancing code readability. Here are some examples of Whitespace:


Whitespace Explanation   Representation
New Line     To Insert a new Line   \n
Tab     To Insert a Tab   \t
Space     To Insert a Space   Empty Space
Double Quote     To Insert a Double Quote Character   \"
Backslash     To Insert a Backslash Character   \\


The use of whitespace improves the organization and readability of your code.


Displaying Variables in Java:

Using System.out.println():

In Java, the `+` sign is used for concatenating strings and variables to create a single combined string. When you use the `+` sign to concatenate a variable with a string, Java automatically converts the variable to its string representation before combining it with the other string.

Example:

String name = "John";
int age = 30;

System.out.println("My name is " + name + " and I am " + age + " years old.");

Output:

My name is John and I am 30 years old.

Using System.out.print():

The System.out.println() method is similar to System.out.print(), but it does not add a newline character after the output. Consecutive outputs will appear on the same line.

int x = 10;
int y = 5;

System.out.print("The value of x is: ");
System.out.println(x);
System.out.print("The value of y is: ");
System.out.println(y);

Output: 

The value of x is: 10
The value of y is: 5


Type Conversion in Java:

Type conversion, also known as type casting, is the process of converting one data type into another in Java. Java supports two types of type conversions: Widening Casting and Narrowing Casting.

1. Widening Casting (Automatic Conversion):

Widening Casting occurs when the compiler automatically converts a smaller data type into larger data tpe (byte -> short -> char -> int -> long -> float -> double), ensuring that no data loss or precision loss occurs. This conversion is considered safe and doesn't require any narrowing casting operator.

Example of Widening Casting:

int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt);      // Outputs 9
System.out.println(myDouble);   // Outputs 9.0

In this example, the `myInt` variable of type `int` is converted into a `double`. Since there is no loss of data or precision (integers can be accurately represented as floating-point numbers), the conversion is performed automatically.

2. Narrowing Casting (Manual Conversion):

Narrowing conversion, occurs when you manually convert larger data type into smaller (double -> float -> long -> int -> char -> short -> byte), using casting operators. Explicit conversions are necessary when there may be a potential loss of data or precision during the conversion.

Example of Narrowing Casting:

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


User Input in Java:

In Java, getting user input from the console involves using the 'java.util.Scanner' class. The Scanner class provides methods to read input of various types from the console.

Before you can use it, you'll need to create an instance of the Scanner class. Here's how you can create a `Scanner` object and use it to get user input:

// import the Scanner class
import java.util.Scanner;

class Main
{
    public static void main(String[] args)
    {
        // create a scanner object
        Scanner input = new Scanner(System.in);

        // get user input
        System.out.println("Enter your name:");
        String name = input.nextLine();

        // display the input back to the user
        System.out.println("Your name is: " + name);
    }
}

In the above code, we first import the `Scanner` class. In the `main` method, we create a `Scanner` object named `input`. The `System.in` parameter is used to tell Java that this is a command-line input. We then use `System.out.println()` to prompt the user to enter their name.

The `input.nextLine()` method is used to read the user's input. This method reads a line of text, which ends with a line break. The input is then stored in the `name` variable.

Finally, we use `System.out.println()` again to display the user's input back to them.

The `Scanner` class has a variety of methods to read different types of input:

  • `nextByte()`: Reads a byte value from the user
  • `nextShort()`: Reads a short value from the user
  • `nextInt()`: Reads an integer value from the user
  • `nextLong()`: Reads a long value from the user
  • `nextFloat()`: Reads a float value from the user
  • `nextDouble()`: Reads a double value from the user
  • `nextBoolean()`: Reads a boolean value from the user
  • `next()`: Reads a single word from the user
  • `nextLine()`: Reads a line of text from the user

Remember to close the scanner object at the end of your program using the `input.close()` statement to prevent resource leaks.

// import the Scanner class
import java.util.Scanner;

class Main
{
    public static void main(String[] args)
    {
        // create a Scanner object
        Scanner input = new Scanner(System.in);

        // get integer input
        System.out.println("Enter an integer:");
        int intValue = input.nextInt();

        // get float input
        System.out.println("Enter a float:");
        float floatValue = input.nextFloat();

        // get double input
        System.out.println("Enter a double:");
        double doubleValue = input.nextDouble();

        // get character input
        System.out.println("Enter a character:");
        char charValue = input.next().charAt(0); // read the next string and take its first character

        // print the inputs
        System.out.println("Your integer is: " + intValue);
        System.out.println("Your float is: " + floatValue);
        System.out.println("Your double is: " + doubleValue);
        System.out.println("Your character is: " + charValue);

        // don't forget to close the scanner
        input.close();
    }
}

Also, always ensure to handle exceptions or provide instructions to the user about the type of input you are expecting in order to prevent input mismatch exceptions. For instance, if you try to use `nextInt()` and the user enters a non-integer value, your program will crash.

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !