Introduction to Java

Introduction to Java

24 January 2023

24 January 2023


Table of Contents
(Click on the links below to directly jump on the topic)

Introduction to Java

Java is a general-purpose, object-oriented programming language developed by Sun Microsystems (now owned by Oracle) in the mid-1990s. It is designed to be platform-independent, meaning that code written in Java can run on any device or operating system that supports the Java Virtual Machine (JVM). This is achieved through the use of bytecode, which is a form of machine code that can be executed by the JVM.

One of the key features of Java is its automatic memory management, which is performed through the use of a garbage collector. This eliminates the need for developers to manually manage memory allocation and deallocation, reducing the risk of memory leaks and other issues.

Java is also known for its strong support for object-oriented programming (OOP) principles, including encapsulation, inheritance, and polymorphism. This allows for the creation of complex, modular code that is easy to maintain and extend.

The Java Development Kit (JDK) includes tools for developing, debugging, and deploying Java code, including the Java compiler (javac), the Java interpreter (java), and the Java Debugger (jdb). It also includes the Java Standard Library, a collection of pre-written classes and methods that can be used to perform common tasks such as input/output, networking, and string manipulation.

Java has a wide range of applications, including web development, mobile app development, desktop applications, and enterprise software. It is also used in the development of video games, artificial intelligence, and big data technologies. Popular frameworks and libraries that are used in the Java ecosystem include Spring, Hibernate, and Apache Struts.

In summary, Java is a popular and widely-used programming language that is known for its platform independence, automatic memory management, and strong support for object-oriented programming principles. Its wide range of libraries and frameworks makes it versatile and suitable for a variety of applications.


First Java Program

A "Hello World!" program is a simple program that displays the message "Hello, World!" on the screen. It is often used as the first program for learning a new programming language, as it demonstrates the basic syntax of the language and the process of running a program.

Here is an example of a "Hello World!" program in Java:

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

Here's what the code does:

  1. The first line declares a class called "HelloWorld". A class is a blueprint for an object, and the class name should start with a capital letter.

  2. The next line is the main method, which is the entry point of the Java program. It must be declared as "public static void" and it must have the parameter "String[] args".

  3. The next line is the statement "System.out.println("Hello, World!");", which prints the string "Hello, World!" to the console. The "System.out" is an object of the PrintStream class, and the "println" method is used to print a line of text to the console.

  4. The last line closes the main method and the class.

To run the program, the code should be saved with the file name HelloWorld.java. Then you can compile the code using the command "javac HelloWorld.java" and run the program using the command "java HelloWorld" on the command line. The program will display the message "Hello, World!" on the console.

In summary, the "Hello, World!" program is a simple program that is used to introduce beginners to a new programming language. The Java version of the program declares a class called "HelloWorld" and defines a main method, which is the entry point of the program.


Java JDK, JVM, JRE

Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), the Java compiler (javac), the Java interpreter (java), and other tools necessary for developing, debugging, and deploying Java code.

The JDK includes several important tools for Java development, such as:

  • Java Compiler (javac): This tool is used to convert the source code written in Java into bytecode, which can be executed by the JVM.

  • Java Interpreter (java): This tool is used to execute the compiled bytecode on the JVM.

  • Java Debugger (jdb): This tool is used for debugging Java programs, allowing developers to step through the code, inspect variables, and set breakpoints.

  • Java Doc: This tool generates API documentation in HTML format from the source code.

  • Java Archiver (jar): This tool is used to package Java classes and resources into a single archive file, known as a JAR file.

  • Java Web Start (javaws): This tool is used to launch Java applications over the web.

The JDK also includes the Java Standard Library, a collection of pre-written classes and methods that can be used to perform common tasks such as input/output, networking, and string manipulation.

The JDK can be downloaded from the Oracle website for various platforms, including Windows, Linux, and macOS. Once the JDK is installed, developers can set the JAVA_HOME environment variable to the location of the JDK, and add the JDK's bin directory to the system's PATH variable, in order to access the JDK's tools from the command line.

In summary, the Java Development Kit (JDK) is a complete package that includes the Java Runtime Environment (JRE), additional tools for developing Java applications, and the Java Standard Library. It includes important tools such as the Java compiler, the Java interpreter, the Java Debugger and more, making it a complete software development environment for Java. It can be downloaded from the Oracle website and installed on various platforms, allowing developers to write, compile, and run Java code on their system.

Java Runtime Environment (JRE) is a software environment that allows users to run Java applications and applets. It includes the Java Virtual Machine (JVM), the Java class libraries, and other supporting files. The JRE is a subset of the Java Development Kit (JDK), and it is necessary to run Java programs on a user's system.

The JRE includes the following components:

  • Java Virtual Machine (JVM): This is the virtual machine that interprets and executes Java bytecode.

  • Java Class Libraries: These are a collection of pre-written classes and methods that can be used to perform common tasks such as input/output, networking, and string manipulation.

  • Java Plug-in: This is a web browser plug-in that allows users to run Java applets within a web browser.

  • Java Web Start: This is a tool that allows users to launch Java applications over the web.

  • JavaFX: This is a Java-based platform for creating and delivering rich internet applications (RIAs) that can run across a wide variety of devices.

The JRE can be downloaded from the Oracle website for various platforms, including Windows, Linux, and macOS. Once the JRE is installed, users can run Java programs by double-clicking on the Java file, or by running the command "java" in the command line.

In summary, the Java Runtime Environment (JRE) is a software environment that allows users to run Java applications and applets on their system. It includes the Java Virtual Machine (JVM), the Java class libraries, and other supporting files. It is a subset of the Java Development Kit (JDK) and it can be downloaded and installed on various platforms, allowing users to run Java programs on their system. The JRE also includes tools such as Java Plug-in and Java Web Start, and it is necessary for running Java Applications and applets on the user's system.

Java Virtual Machine (JVM) is the virtual machine that runs Java bytecode. It is responsible for interpreting the bytecode and executing the corresponding Java code on the host system. The JVM is platform-specific, meaning that different versions of the JVM are available for different operating systems. The JVM is also responsible for performing tasks such as memory management, security, and garbage collection.

The JVM is platform-specific, meaning that different versions of the JVM are available for different operating systems. When a Java program is compiled, it is translated into Java bytecode, which is a machine-independent form of code. This bytecode can then be executed by the JVM on any platform that has a JVM installed.

The JVM has several components, including:

  • Class loader: Responsible for loading and linking the Java classes needed by a program.

  • Execution engine: Interprets and executes the bytecode instructions.

  • Memory area: Consists of several regions where different types of data are stored, such as heap, stack, method area, etc.

  • Garbage collector: Responsible for managing memory allocation and deallocation, and for freeing up memory that is no longer being used by the program.

  • Security manager: Responsible for enforcing Java's security policies, such as preventing unauthorized access to system resources.

The JVM also provides a platform for the execution of multiple Java programs, in a context called execution engine. Each program runs in its own instance of the JVM, and the JVM provides a layer of abstraction between the program and the underlying hardware.

In addition, JVM also provides support for dynamic class loading, which means that classes can be loaded and unloaded during runtime. This feature allows for the Java platform to support dynamic and extensible systems.

The JVM also provides a rich set of standard libraries, including the Java Standard Library, which contains a collection of pre-written classes and methods that can be used to perform common tasks such as input/output, networking, and string manipulation.

In summary, the Java Virtual Machine (JVM) is a virtual machine that interprets and executes Java bytecode. It is responsible for performing important tasks such as memory management, security, and garbage collection, and it provides a platform for the execution of multiple Java programs. It also allows for dynamic class loading and provides support for a rich set of standard libraries, which makes Java an easy-to-use and extensible programming language.

The JDK is necessary for developers who want to write and compile Java code. It includes the JRE, which is necessary to run Java code, and additional tools such as the Java compiler and Java Debugger. The JRE, on the other hand, is necessary for users who just want to run Java applications and applets on their system.

In summary, the JDK is a complete package that includes the JRE and additional tools for developing Java applications. The JRE is a subset of the JDK and is necessary to run Java programs. The JVM is a virtual machine that is included in the JRE and is responsible for interpreting and executing Java bytecode.


Java Variables

In Java, a variable is a named storage location in memory that holds a value. Variables are used to store data and are fundamental to any programming language. Java variables have a data type, a name, and a value.

Java supports two types of variables:

1. Primitive Variables: These are the basic data types of Java such as int, boolean, char, double, etc. Primitive variables are stored in the stack and their values are stored directly in the memory.

For Eg:

int age = 20;
boolean isStudent = true;
char grade = 'A';
double salary = 30000.50;

In the above example, "age", "isStudent", "grade", and "salary" are all primitive variables with their respective data types.

2. Reference Variables: These are variables that hold a reference or memory address to an object of a class. Reference variables are stored in the heap and their values are stored in the form of a reference.

For example:

String name = new String("John Doe");
Dog myDog = new Dog();

In the above example, "name" and "myDog" are reference variables. The variable "name" holds a reference to an object of the String class, and "myDog" holds a reference to an object of the Dog class.

Java also supports the use of final and static keywords with variables.

  • final variables are constants that cannot be reassigned.
final double PI = 3.14; 
  • static variables are class variables that belong to the class and can be accessed without creating an instance of the class.
static int counter = 0;

In summary, Java variables are named storage locations in memory that hold a value. They have a data type, a name, and a value. Java supports two types of variables: Primitive variables and Reference variables. Additionally, there are keywords such as final and static that can be used to modify the behavior of variables.


Java Datatypes

Java has several data types, which can be broadly classified into two categories: primitive data types and reference data types.

1. Primitive Data Types: These are the basic data types of Java such as int, boolean, char, double, etc. Primitive variables are stored in the stack and their values are stored directly in the memory.

a) int: This is a data type used to store whole numbers (integers). It can store values from -2147483648 to 2147483647.

int age = 20;

b) boolean: This is a data type used to store true or false values.

boolean isStudent = true;

c) char: This is a data type used to store a single character. It must be enclosed in single quotes.

char grade = 'A';

d) double: This is a data type used to store decimal numbers. It is a double-precision floating-point value and supports values with decimal places.

double salary = 30000.50;

e) float: This is a data type used to store decimal numbers. It is a single-precision floating-point value and supports values with decimal places.

float pi = 3.14f;

f) byte: This is a data type used to store 8-bit signed integers. It can store values from -128 to 127.

byte age = 20;

g) short: This is a data type used to store 16-bit signed integers. It can store values from -32768 to 32767.

short number = 200;

h) long: This is a data type used to store 64-bit signed integers. It can store values from -9223372036854775808 to 9223372036854775807

long number = 200;

2. Reference Data Types: These are objects of classes, which are stored in the heap. Reference variables are stored in the stack and their values are stored in the form of a reference.

String name = new String("John Doe");
Dog myDog = new Dog();

Java also provides several built-in classes, which can be used to represent common data types such as:

a) String: This is a class used to represent a sequence of characters.

String name = "John Doe";

b) Date: This is a class used to represent a date and time.

Date now = new Date();

c)  Array: This is a class used to represent an array of elements.

int[] numbers = new int[5];

d) Enumeration: This is a class used to represent a set of named values.

enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

e) Wrapper classes: These are classes that wrap around primitive types and provide additional functionality. They include:

  • Integer
  • Character
  • Float
  • Double
  • Boolean
  • Byte
  • Short
  • Long
Integer num1 = new Integer(20);
Character ch = new Character('A');

In summary, Java has several data types, including primitive data types such as int, boolean, char, double and reference data types such as objects of classes, built-in classes such as String, Date and Array, Enumeration and Wrapper classes. Primitive data types are stored in the stack and their values are stored directly in the memory, while reference data types are objects of classes that are stored in the heap.


Java Operators

Java operators are special symbols in Java that perform specific operations on one, two, or three operands, and then return a result.

Java supports the following types of operators:

1. Arithmetic operators: These operators perform basic arithmetic operations such as addition, subtraction, multiplication, division, and modulus.

int a = 10, b = 20;
int sum = a + b; // 30
int difference = b - a; // 10
int product = a * b; // 200
int quotient = b / a; // 2
int remainder = b % a; // 0

2.Comparison operators: These operators compare two values and return a boolean value.

int a = 10, b = 20;
boolean isEqual = (a == b); // false
boolean isNotEqual = (a != b); // true
boolean isGreater = (a > b); // false
boolean isLess = (a < b); // true

3. Logical operators: These operators perform logical operations such as AND, OR, and NOT. They are used to combine multiple conditions.

boolean isStudent = true;
boolean isEligible = false;
boolean result = isStudent && isEligible; // false
result = isStudent || isEligible

Java Input and Output

Java provides several ways for handling input and output (I/O) operations. Some of the most commonly used techniques for handling I/O in Java include:

1. The Java I/O Streams: Java I/O streams are used to read and write data from and to various sources such as files, network connections, and in-memory data. There are two types of streams in Java: InputStream and OutputStream. InputStream is used for reading data, and OutputStream is used for writing data.

import java.io.*;
public class ReadWriteFile {
    public static void main(String[] args) {
        try {
            //Writing to a file
            OutputStream os = new FileOutputStream("example.txt");
            os.write("Hello World!".getBytes());
            os.close();
            
            //Reading from a file
            InputStream is = new FileInputStream("example.txt");
            int size = is.available();
            for (int i = 0; i < size; i++) {
                System.out.print((char)is.read());
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, the OutputStream class is used to write the string "Hello World!" to a file named "example.txt". Then the InputStream class is used to read the contents of the same file and print it to the console.

The OutputStream class is an abstract class that represents an output stream of bytes. The FileOutputStream is a subclass of OutputStream, it writes bytes to a file. In this example, we are using the write method of the OutputStream class to write the bytes of the string "Hello World!" to the file.

The InputStream class is an abstract class that represents an input stream of bytes. The FileInputStream is a subclass of InputStream, it reads bytes from a file. In this example, we are using the read method of the InputStream class to read the bytes of the file into a buffer and then convert the buffer to a string using the new String() constructor.

It's worth noting that these classes are considered low-level and that the BufferedReader and BufferedWriter classes are more efficient for reading and writing text files, because they buffer the data before reading or writing it.

 

2. The Java Scanner Class: The Scanner class is used to read input from various sources such as the keyboard, a file, or a network connection. The Scanner class provides several methods for reading different types of data, such as nextInt() for reading integers and nextLine() for reading strings.

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a line of text: ");
    String input = scanner.nextLine();
    System.out.println("You entered: " + input);
    scanner.close();
  }
}

This example creates a new Scanner object and associates it with the standard input stream (System.in). Then it prompts the user to enter a line of text, reads the line using the nextLine() method, and prints the line to the console.

The Java BufferedReader and BufferedWriter Classes: The BufferedReader and BufferedWriter classes are used to read and write text files. BufferedReader reads text from a character-input stream and BufferedWriter writes text to a character-output stream.

import java.io.*;
public class Main {
  public static void main(String[] args) {
    try {
      BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
      BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
      String line;
      while ((line = reader.readLine()) != null) {
        writer.write(line);
        writer.newLine();
      }
      reader.close();
      writer.close();
      System.out.println("File copied successfully!");
    } catch (IOException e) {
      System.out.println("An error occurred: " + e.getMessage());
    }
  }
}

This example creates a BufferedReader object that reads from the file "input.txt" and a BufferedWriter object that writes to the file "output.txt". It then reads each line of the input file using the readLine() method and writes each line to the output file using the write() and newLine() methods. Finally, it closes the reader and writer to release the resources.

It is important to note that the files must exist in the same directory of the running program otherwise it will throw FileNotFoundException, also, if the output file already exists, it will be overwritten.

 

3. The Java FileReader and FileWriter Classes: The FileReader and FileWriter classes are used to read and write text files. FileReader reads characters from a file and FileWriter writes characters to a file.
 

import java.io.*;
public class ReadWriteTextFile {
    public static void main(String[] args) {
        try {
            //Writing to a file
            FileWriter fw = new FileWriter("example.txt");
            fw.write("Hello World!");
            fw.close();
            
            //Reading from a file
            FileReader fr = new FileReader("example.txt");
            int c = fr.read();
            while (c != -1) {
                System.out.print((char)c);
                c = fr.read();
            }
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, the FileWriter class is used to write the string "Hello World!" to a file named "example.txt". Then the FileReader class is used to read the contents of the same file and print it to the console.

The FileWriter is used to create a new file if it doesn't exist or to truncate the contents of an existing file before writing to it.

The FileReader reads a file character by character and returns -1 when the end of file is reached.

It's worth noting that these classes are considered low-level and that the BufferedReader and BufferedWriter classes are more efficient for reading and writing text files, because they buffer the data before reading or writing it.

  1. The Java PrintWriter Class: The PrintWriter class is used to write text to a file or to a network connection. The PrintWriter class provides several methods for formatting and printing data, such as println() for writing a line of text and printf() for formatting and writing text.
     

    import java.io.*;
    public class Main {
      public static void main(String[] args) {
        try {
          PrintWriter writer = new PrintWriter("output.txt");
          writer.println("Hello, World!");
          writer.close();
          System.out.println("File written successfully!");
        } catch (IOException e) {
          System.out.println("An error occurred: " + e.getMessage());
        }
      }
    }

     

This example creates a new PrintWriter object and associates it with the file "output.txt". Then it writes the string "Hello, World!" to the file using the println() method. Finally, it closes the writer to release the resources.

It's worth noting that the PrintWriter class also provides methods such as print() and printf() which can be used to write different types of data to the output stream. Additionally, PrintWriter class has a constructor that takes a boolean parameter called "autoFlush", if set to true, output will be flushed automatically when a newline is printed.

 

4. The Java DataInputStream and DataOutputStream Classes: The DataInputStream and DataOutputStream classes are used to read and write binary data. DataInputStream reads binary data from an input stream and DataOutputStream writes binary data to an output stream.
 

import java.io.*;
public class ReadWriteBinaryFile {
    public static void main(String[] args) {
        try {
            //Writing to a file
            DataOutputStream dos = new DataOutputStream(new FileOutputStream("example.dat"));
            dos.writeInt(42);
            dos.writeDouble(Math.PI);
            dos.close();
                        //

In general, the most common classes to use for input are Scanner, BufferedReader and for output are System.out.println, PrintWriter, BufferedWriter.


Java Expressions

Java expressions are statements that can be evaluated to a single value. They can be used in various parts of a Java program, such as in variable assignments, method calls, and control structures. There are several types of expressions in Java, including:

Arithmetic expressions: These are expressions that perform mathematical operations, such as addition, subtraction, multiplication, and division.

For example:
int x = 1 + 2;
double y = 3.14 * x;

Comparison expressions: These are expressions that compare two values and return a boolean value (true or false).

For example:
if (x == y) {
    System.out.println("x and y are equal");
}

Logical expressions: These are expressions that use logical operators, such as AND (&&) and OR (||), to combine multiple boolean expressions.

For example:
if (x > 0 && y < 10) {
    System.out.println("x is positive and y is less than 10");
}

Conditional expressions: These are expressions that use the ternary operator (?), to conditionally evaluate one of two expressions based on a boolean condition.

For example:

int max = (x > y) ? x : y;

Method invocation expressions: These are expressions that invoke a method, such as:

System.out.println("Hello");

Object creation expressions: These are expressions that create new objects, such as:
 

String s = new String("Hello");

Array access expressions: These are expressions that access an element of an array, such as:

int[] arr = {1, 2, 3};
int x = arr[0];

Cast expressions: These are expressions that change the type of a value, such as:

double x = 3.14;
int y = (int)x;

These are some of the common types of expressions in Java. They can be used in various ways to perform different operations in your Java program.

A block in Java is a group of statements enclosed in curly braces {}. Blocks can be used to group statements together, and can also be used to define the scope of variables.


Java  Blocks

A block in Java is a group of statements enclosed in curly braces {}. Blocks can be used to group statements together, and can also be used to define the scope of variables.

One common use of blocks is to define the scope of variables. Variables declared inside a block are only accessible within that block.

For example:
{
    int x = 5;
    System.out.println(x);
}
System.out.println(x); // this will result in a compile-error

In this example, the variable x is only accessible within the block, and attempting to access it outside the block will result in a compile-error.

Another use of blocks is in control structures such as if-else statements, while loops, and for loops. The statements inside the block will only be executed if the condition of the control structure is true.

For example:
if (x > 0) {
    x = x - 1;
}

In this example, the block containing the statement x = x - 1 will only be executed if the condition x > 0 is true.

Blocks can also be used in methods to group statements together and improve code readability.

For example:

public void exampleMethod() {
    int x = 0;
    {
        int y = 5;
        x = x + y;
    }
    System.out.println(x);
}

In this example, the block containing the variable y and the statement x = x + y improves the readability of the code and makes it clear that these statements are related.

Additionally, blocks can be used in anonymous inner classes, where a class is defined and instantiated all in one line.


Thread t = new Thread(new Runnable() {
    public void run() {
        System.out.println("Running in a new thread");
    }
});

Here, the block after new Runnable() is defining an anonymous inner class that implements the run method and is passed as an argument to Thread constructor, which is then invoked by calling the start method on it.

In short, blocks are used in Java to group statements together, define the scope of variables, and control the flow of execution in a program. They can be used in various parts of a Java program to improve code readability and organization.


Java Comments

In the Java programming language, a comment is a piece of text that is ignored by the compiler and is intended for the developer to read and understand the code. There are two types of comments in Java: single-line comments and multi-line comments.

Single-line comments start with two forward slashes (//) and continue until the end of the line.

For example:

// This is a single-line comment
Multi-line comments start with a forward slash and an asterisk (/) and end with an asterisk and a forward slash (/).

For example:

/* This is a
multi-line comment
that can span multiple lines */

Additionally, Java also supports the "javadoc" comment format, which starts with /** and ends with */.
These comments are used for generating API documentation, and are typically placed immediately before a class, interface, or method definition.

For example:

/**
* This is a javadoc comment
* it is used for generating API documentation
* @author John Doe
*/

It is worth noting that comments in Java are ignored by the compiler, they are meant to be used by the developer and other developers who will read the code. Comments should be used to describe the purpose of the code, and to explain any complex or non-obvious parts of the code.




Related Articles

Ask Us Anything !