Java Development Notes

Notes

Java Resources

Java Versions

Commonly used JDK versions:

  • JDK 8 (LTS - Long Term Support)
  • JDK 5 (LTS)
  • JDK 11 (LTS, released in 2018)
  • Java 21 (LTS, released on 19 September 2023)

Java Version Nomenclature

Java version nomenclature has evolved over the years, transitioning from a straightforward numerical system to a more structured and predictable format.

Current Versioning Scheme

Beginning with Java 7, the nomenclature was further streamlined, dropping the "2" from the platform name.

Version Number Structure

The version number structure is typically in the form of MAJOR.MINOR.SECURITY, for example:

  • Java 8 Update 131: Denoted as 1.8.0_131.
  • Java 11.0.2: The second security update for Java 11.

Checking JDK Version

You can check the JDK version using the following command in the terminal:

java -version

Java Platforms

Java platforms include:

  • SE (Standard Edition)
  • EE (Enterprise Edition)
  • ME (Micro Edition)

Java Code Example

Sample Java code:

class Pokemon {
int level;
static int count;
}

public class Main {
public static void main(String[] args) {
Pokemon p1 = new Pokemon();
p1.level = 10;
Pokemon.count = 5;
}
}

Understanding jpackage and JAR

In the Java ecosystem, JAR (Java ARchive) and jpackage are essential tools for application packaging and distribution. A JAR file is a package file format that aggregates multiple Java class files, associated metadata, and resources (like text and images) into a single file, making it easier to distribute and deploy Java applications and libraries. On the other hand, jpackage, introduced in JDK 14, is a tool for packaging self-contained Java applications. It creates native installers for a variety of platforms (Windows, macOS, and Linux), bundling the application with a private JRE, ensuring that the application can run without requiring a separate JRE installation. Together, these tools streamline the process of preparing Java applications for distribution, enhancing portability and ease of use.

Java Packaging Tool

The packaging tool, jpackage, empowers users to generate installable packages tailored for both modular and non-modular Java applications. These platform-specific packages, compatible with Linux, macOS, and Windows, afford users a familiar avenue to install and launch their applications seamlessly. By leveraging jpackage, developers can streamline the distribution process, enhancing user accessibility and overall experience.

jpackage --input . --name Exam --main-jar Exam2.jar

Jar Files

Jar files are a type of zip file used for packaging Java classes and resources.

To create a jar file:

jar cvfm fileName.jar Manifest.txt *.class images/*.png

Viewing Jar Contents

To view the contents of a jar file:

java vtf fileName.jar

Running Jar Files

To execute a jar file:

java -jar fileName.jar

The Power and Flexibility of Gradle

Gradle is a powerful and flexible build automation tool widely used in software development, especially for Java projects. It manages project dependencies, compiles code, runs tests, and packages applications. Built on a robust and extensible model, Gradle supports multiple languages and platforms, including Java, Groovy, Kotlin, Scala, and Android, making it a versatile choice for diverse development environments. It combines the best features of Ant and Maven, utilizing a Groovy-based domain-specific language (DSL) for writing build scripts, which allows for highly customizable and readable configurations. With its incremental build capabilities and sophisticated caching mechanisms, Gradle significantly improves build times and efficiency. Additionally, its deep integration with popular development tools like IntelliJ IDEA, Visual Studio Code, and Android Studio, as well as its compatibility with continuous integration systems, makes Gradle an essential tool for modern development workflows.


your-project/
├── build.gradle
├── settings.gradle
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── src/
    ├── main/
    │   ├── java/
    │   │   └── com/
    │   │       └── yourcompany/
    │   │           └── MainClass.java
    │   └── resources/
    └── test/
        ├── java/
        └── resources/


Build and Run a Project

Open a terminal, navigate to the project directory, and use Gradle to build the project:

gradle build

Gradle will compile the Java files, run any tests, and create a JAR file in the build/libs/ directory. Gradle automates the entire build process, including dependency management, compilation, testing, and packaging. This provides a significant advantage over manually compiling with javac, especially for larger projects with multiple dependencies and complex build requirements.

Run the Application

./gradlew run

Java Array Tutorial

//Decaration
int[] numbers;
String[] names;

// Declaration and initialization in one step
int[] numbers = new int[5];

// Declaration and then initialization
String[] names;
names = new String[3];

numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";

int[] numbers = {10, 20, 30, 40, 50};
String[] names = {"Alice", "Bob", "Charlie"};
int firstNumber = numbers[0]; // 10
String firstName = names[0]; // "Alice"
int lengthOfNumbers = numbers.length; // 5
int lengthOfNames = names.length; // 3
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}
for (int i = 0; i < names.length; i++) {
    System.out.println(names[i]);
}
// for-each loop
for (int number : numbers) {
    System.out.println(number);
}

for (String name : names) {
    System.out.println(name);
}

//Multidimensional Arrays
int[][] matrix = new int[3][3];
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
int value = matrix[1][2]; // 6
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

//Using System.arraycopy to copy arrays:
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[5];

System.arraycopy(source, 0, destination, 0, source.length);

for (int num : destination) {
    System.out.println(num);
}

//Using Arrays.sort to sort arrays:
import java.util.Arrays;

int[] numbers = {5, 3, 1, 4, 2};
Arrays.sort(numbers);

for (int num : numbers) {
    System.out.println(num);
}

//Using Arrays.binarySearch to search sorted arrays:
import java.util.Arrays;

int[] numbers = {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(numbers, 3); // 2
System.out.println("Index of 3: " + index);
  

Read Input in Java

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String inputString = scanner.nextLine();
        System.out.println("You entered: " + inputString);

        System.out.print("Enter an integer: ");
        int inputInt = scanner.nextInt();
        System.out.println("You entered: " + inputInt);

        System.out.print("Enter a double: ");
        double inputDouble = scanner.nextDouble();
        System.out.println("You entered: " + inputDouble);

        scanner.close();
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BufferedReaderExample {
    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        try {
            System.out.print("Enter a string: ");
            String inputString = reader.readLine();
            System.out.println("You entered: " + inputString);

            System.out.print("Enter an integer: ");
            int inputInt = Integer.parseInt(reader.readLine());
            System.out.println("You entered: " + inputInt);

            System.out.print("Enter a double: ");
            double inputDouble = Double.parseDouble(reader.readLine());
            System.out.println("You entered: " + inputDouble);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class ConsoleExample {
    public static void main(String[] args) {
        java.io.Console console = System.console();

        if (console != null) {
            String username = console.readLine("Enter your username: ");
            char[] password = console.readPassword("Enter your password: ");

            System.out.println("Username: " + username);
            System.out.println("Password: " + String.valueOf(password));
        } else {
            System.out.println("No console available");
        }
    }
}

import javax.swing.JOptionPane;

public class JOptionPaneExample {
    public static void main(String[] args) {
        String inputString = JOptionPane.showInputDialog("Enter a string:");
        System.out.println("You entered: " + inputString);

        String inputIntString = JOptionPane.showInputDialog("Enter an integer:");
        int inputInt = Integer.parseInt(inputIntString);
        System.out.println("You entered: " + inputInt);

        String inputDoubleString = JOptionPane.showInputDialog("Enter a double:");
        double inputDouble = Double.parseDouble(inputDoubleString);
        System.out.println("You entered: " + inputDouble);
    }
}
  
  • Scanner: Easiest and most versatile for standard input.
  • BufferedReader and InputStreamReader: Efficient for reading text, suitable for larger input or when more control over reading is required.
  • Console: Secure input, suitable for command-line applications requiring password input.
  • JOptionPane: Ideal for GUI applications needing user input.

Java Applet

/*
In the past, Java applets were embedded into web pages using HTML <applet> tags. 
Let's use a simple "Hello, World!" applet as an example to demonstrate how it was done:
*/

/* Hello World Applet Example

First, let's create a Java applet class named `HelloWorldApplet`: */

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorldApplet extends Applet {
    public void paint(Graphics g) {
        g.drawString("Hello, World!", 20, 20);
    }
}

//Embedding the Applet in HTML

//Next, we create an HTML file (`index.html`) to embed the applet using the <applet> tag:
/*
    <applet code="HelloWorldApplet.class" width="200" height="200">
        Your browser does not support Java applets.
    </applet>
*/
/*
In this HTML file:
- We include the <applet> tag to embed the applet.
- The code attribute specifies the name of the Java class file 
  containing the applet (`HelloWorldApplet.class`).
- The width and height attributes specify the dimensions of the applet's display area.
*/
  


See also


Comments

Popular posts from this blog

Neat-Flappy Bird (Second Model)

Exploring Memory Components: A Metaphorical Journey

The Evolution of Programming Language Syntax