add_action('wp_footer', function () { echo ''; }, 99); add_action('wp_footer', function () { echo ''; }, 99); Core Java Archives - javatechig.com https://javatechig.com/category/core-java/ Mon, 24 Aug 2026 10:36:43 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.7 Save Bitmap Image in BlackBerry Java https://javatechig.com/core-java/save-bitmap-image-blackberry-java/ https://javatechig.com/core-java/save-bitmap-image-blackberry-java/#respond Fri, 02 Jan 2026 18:16:00 +0000 https://javatechig.com/?p=7751 Overview This post explains how to save a bitmap image file to the filesystem in BlackBerry Java applications. The example uses BlackBerry’s native APIs to encode a Bitmap object into PNG format and write it to device storage. This approach is common when building legacy BlackBerry Java apps requiring image persistence. BlackBerry Java uses classes …

The post Save Bitmap Image in BlackBerry Java appeared first on javatechig.com.

]]>
Overview

This post explains how to save a bitmap image file to the filesystem in BlackBerry Java applications. The example uses BlackBerry’s native APIs to encode a Bitmap object into PNG format and write it to device storage. This approach is common when building legacy BlackBerry Java apps requiring image persistence.

BlackBerry Java uses classes such as PNGEncodedImage, FileConnection, and the system graphics APIs. It’s important to handle file I/O and encoding properly to avoid errors and ensure compatibility across devices.

Concepts

Bitmap and EncodedImage

  • Bitmap represents raw pixel data.
  • PNGEncodedImage encodes a Bitmap into PNG format (lossless compression).
    • BlackBerry devices include APIs to encode to PNG using PNGEncodedImage.encode().

File Connections

  • BlackBerry uses javax.microedition.io.file.FileConnection (JSR-75) to access the filesystem.
  • Ensure proper permissions are granted for file read/write.

Saving a Bitmap Image

The following example shows how to save a bitmap as a PNG file on the BlackBerry filesystem (such as SDCard or device storage).

Steps

  1. Create or obtain a Bitmap object.
  2. Encode bitmap data as PNG using PNGEncodedImage.
  3. Open a file using FileConnection.
  4. Write the encoded byte data to the output stream.
  5. Close all resources properly.

Example Code

import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.PNGEncodedImage;

public class ImageSaver {

    public static boolean saveBitmapToFile(String path, Bitmap bitmap) {
        FileConnection fileConn = null;
        OutputStream out = null;

        try {
            // Open or create the file
            fileConn = (FileConnection) Connector.open(path, Connector.READ_WRITE);
            if (!fileConn.exists()) {
                fileConn.create();
            }

            // Encode bitmap to PNG bytes
            PNGEncodedImage pngImage = PNGEncodedImage.encode(bitmap);
            byte[] imageData = pngImage.getData();

            // Open output stream and write data
            out = fileConn.openOutputStream();
            out.write(imageData);
            out.flush();

            return true;

        } catch (Exception e) {
            System.out.println("Error saving bitmap: " + e.toString());
            return false;

        } finally {
            try {
                if (out != null) out.close();
                if (fileConn != null) fileConn.close();
            } catch (Exception ignored) {}
        }
    }
}

Usage Example

Bitmap myBitmap = Bitmap.getBitmapResource("example.png");
String savePath = "file:///SDCard/BlackBerry/pictures/saved_image.png";

boolean success = ImageSaver.saveBitmapToFile(savePath, myBitmap);
if (success) {
    System.out.println("Image saved to " + savePath);
}

File Paths

Common storage paths on BlackBerry devices:

  • Internal memory:
    file:///store/home/user/…
  • SDCard storage:
    file:///SDCard/BlackBerry/pictures/…

Always confirm the target path exists and the application has appropriate permissions.

Error Handling and Best Practices

  • Handle exceptions when opening file connections and writing data.
  • Use try/finally to ensure streams and connections are closed.
  • Avoid writing large images on UI thread — run this code in a background thread if needed.
  • Always check that bitmap is not null before encoding.

Summary

This document shows how to encode and save a Bitmap as a PNG image file on legacy BlackBerry devices using Java APIs such as PNGEncodedImage and FileConnection. While the BlackBerry platform is legacy, understanding this pattern remains useful when maintaining enterprise applications built on BlackBerry Java.

The post Save Bitmap Image in BlackBerry Java appeared first on javatechig.com.

]]>
https://javatechig.com/core-java/save-bitmap-image-blackberry-java/feed/ 0
Insertion Sort in Java – Example & Step‑by‑Step Guide https://javatechig.com/core-java/insertion-sort-example-in-java/ https://javatechig.com/core-java/insertion-sort-example-in-java/#respond Wed, 31 Dec 2025 12:30:00 +0000 https://javatechig.com/?p=7349 Insertion sort is a simple comparison‑based sorting algorithm ideal for small or nearly sorted datasets. It builds a sorted portion of the array one element at a time by inserting each new element in its correct position. While not as efficient as merge or quick sort for large arrays, insertion sort remains fundamental for understanding …

The post Insertion Sort in Java – Example & Step‑by‑Step Guide appeared first on javatechig.com.

]]>
Insertion sort is a simple comparison‑based sorting algorithm ideal for small or nearly sorted datasets. It builds a sorted portion of the array one element at a time by inserting each new element in its correct position. While not as efficient as merge or quick sort for large arrays, insertion sort remains fundamental for understanding sorting logic and optimization.

This updated guide on javatechig.com explains how insertion sort works, provides clear Java code examples, analyzes time and space complexity, and discusses best practices for real‑world usage.

What Is Insertion Sort?

Insertion sort iterates through the array and constructs a sorted portion on the left side. For each element, it finds the correct position in the sorted part by shifting larger elements to the right.

Key characteristics:

  • Comparison‑based sorting
  • Stable (doesn’t change the relative order of equal elements)
  • In‑place sorting (no significant extra memory)
  • Ideal for small datasets or mostly sorted data

Time and Space Complexity

ScenarioTime Complexity
Best Case (sorted)O(n)
Average CaseO(n²)
Worst Case (reverse)O(n²)
Space ComplexityO(1)

Insertion sort performs well on small datasets or partially sorted collections due to low overhead and simple inner loops.

Java Implementation: Arrays

Code Example

public static void insertionSort(int[] arr) {
    for (int i = 1; i < arr.length; i++) {
        int key = arr[i];
        int j = i - 1;

        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }

        arr[j + 1] = key;
    }
}

public static void main(String[] args) {
    int[] data = {9, 5, 1, 4, 3};
    insertionSort(data);

    System.out.println("Sorted Array:");
    for (int num : data) {
        System.out.print(num + " ");
    }
}

This standard implementation shifts elements greater than the key to the right, then places the key in its correct spot.

How It Works (Visual Explanation)

  1. Start from index 1 (first unsorted element).
  2. Compare the key with prior elements.
  3. Shift larger elements to the right.
  4. Insert the key where sorted order demands.
  5. Repeat until entire array is processed.

Generic Insertion Sort (Any Comparable Type)

You can generalize insertion sort for any type that implements Comparable.

Java Example

public static > void insertionSort(T[] array) {
    for (int i = 1; i < array.length; i++) {
        T key = array[i];
        int j = i - 1;

        while (j >= 0 && array[j].compareTo(key) > 0) {
            array[j + 1] = array[j];
            j--;
        }
        array[j + 1] = key;
    }
}

This version works for String[], Integer[], or custom object arrays as long as they implement Comparable.

Sorting Collections with Insertion Logic

Although Java provides Collections.sort() and List.sort(), understanding insertion sort helps when:

  • Implementing custom comparators
  • Writing algorithms for educational purposes
  • Optimizing specialized data structures

Best Use Cases

Insertion sort is useful when:

  • Dataset is small (e.g., <50 items)
  • Array is nearly sorted
  • Stability is important (equal elements remain in order)
  • Simplicity and readability matter more than speed

Drawbacks & When Not to Use

Avoid insertion sort for:

  • Large unsorted datasets
  • Performance‑critical systems
  • Data requiring divide‑and‑conquer performance benefits

In such cases, prefer merge sort, quick sort, or TimSort used by Java’s built‑in sorting.

Common Mistakes

Forgetting the Inner Shift Loop

Without shifting, the algorithm doesn’t rearrange elements properly.

Ignoring Generics

Generic implementation requires Comparable — always use the constraint to ensure robust sorting.

Best Practices (2026 Updated)

  • Use built‑in sort for production unless algorithm learning is the goal
  • Prefer generic methods for reusable sorting logic
  • Understand when insertion sort excels (small/partially sorted data)
  • Document algorithm choice when optimizing code

The post Insertion Sort in Java – Example & Step‑by‑Step Guide appeared first on javatechig.com.

]]>
https://javatechig.com/core-java/insertion-sort-example-in-java/feed/ 0
Searching Arrays and Collections in Java – Methods and Examples https://javatechig.com/core-java/search-arrays-and-collections-in-java/ https://javatechig.com/core-java/search-arrays-and-collections-in-java/#respond Sat, 15 Nov 2025 15:09:00 +0000 https://javatechig.com/?p=7620 Efficiently searching arrays and collections is a foundational skill in Java development. Whether you are looking for a specific element, checking for existence, or finding the index of a match, Java provides a range of APIs and patterns — from traditional loops to modern Streams — to address these needs. This tutorial covers common techniques …

The post Searching Arrays and Collections in Java – Methods and Examples appeared first on javatechig.com.

]]>
Efficiently searching arrays and collections is a foundational skill in Java development. Whether you are looking for a specific element, checking for existence, or finding the index of a match, Java provides a range of APIs and patterns — from traditional loops to modern Streams — to address these needs.

This tutorial covers common techniques for searching in both arrays and collections, including primitive arrays, object arrays, List, Set, and advanced search patterns.

H2: Searching in Arrays

Java’s Arrays utility class provides methods for searching arrays.

H3: Using Arrays.binarySearch() (Sorted Arrays)

The Arrays.binarySearch() method performs a binary search on a sorted array.

int[] numbers = {10, 20, 30, 40, 50};
int index = Arrays.binarySearch(numbers, 30);
System.out.println("Index: " + index);

Key Points:

  • The array must be sorted before calling binarySearch.
  • Returns the index of the found element.
  • If not found, returns a negative insertion point.
int missing = Arrays.binarySearch(numbers, 25);
System.out.println(missing); // Negative value

This negative value indicates where the key would be inserted.

H3: Searching Object Arrays

For an array of objects such as String[]:

String[] names = {"Alice", "Bob", "Charlie"};
int idx = Arrays.binarySearch(names, "Bob");

The array must be sorted lexicographically for correct results.

H3: Linear Search with Loop

If the array is not sorted or you need a custom condition, use a simple loop:

String[] names = {"Alice","Bob","Charlie"};
String target = "Charlie";
int index = -1;

for (int i = 0; i < names.length; i++) {
    if (names[i].equals(target)) {
        index = i;
        break;
    }
}

System.out.println("Found at index: " + index);

This pattern works for any array type and custom matching.

H2: Searching in Collections

Java Collection types (List, Set, Map) offer flexible search operations.

H3: Searching a List

Using List.indexOf()

List list = Arrays.asList("Java", "Python", "C++");
int pos = list.indexOf("Python");
System.out.println("Position: " + pos);

indexOf() returns the first matching index or -1 if not found.

Using List.contains()

boolean found = list.contains("Java");
System.out.println(found); // true

contains() tests for existence without index.

H3: Searching with Streams (Java 8+)

Streams provide expressive and flexible search patterns:

List list = Arrays.asList("Java", "Python", "C++");

// Find first match
Optional result = list.stream()
    .filter(s -> s.startsWith("P"))
    .findFirst();

result.ifPresent(System.out::println);

This allows arbitrary conditions without manual loops.

H3: Searching a Set

Sets don’t preserve order and don’t have indexes, but you can check existence:

Set set = new HashSet<>(list);
boolean exists = set.contains("C++");

Use streams when you need more complex filters:

boolean match = set.stream().anyMatch(s -> s.endsWith("++"));

H3: Searching Maps

Maps store key-value pairs.

Map map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);

boolean hasKey = map.containsKey("Bob");
boolean hasValue = map.containsValue(30);

To find entries by condition:

map.entrySet().stream()
   .filter(e -> e.getValue() > 28)
   .forEach(System.out::println);

H2: Searching Primitive Arrays

Primitive arrays like int[] or double[] require slightly different handling.

H3: Using Arrays.binarySearch()

As shown earlier:

double[] values = {1.2, 3.4, 5.6};
int pos = Arrays.binarySearch(values, 3.4);

Always ensure the array is sorted.

H3: Manual Search with Loop

int[] nums = {5, 9, 1, 7};
int target = 9;
int idx = -1;

for (int i = 0; i < nums.length; i++) {
    if (nums[i] == target) {
        idx = i;
        break;
    }
}

Manual loops are simple and effective for small arrays.

H2: Advanced Search Patterns

H3: Custom Comparator with Binary Search

When searching sorted arrays of custom objects:

Person[] people = {...};
Arrays.sort(people, Comparator.comparing(Person::getName));

int index = Arrays.binarySearch(
        people,
        new Person("John", 0),
        Comparator.comparing(Person::getName)
);

This allows binary search on custom fields.

H3: Finding All Matches with Streams

Using streams to collect all matches:

List allMatches = list.stream()
   .filter(s -> s.length() > 3)
   .collect(Collectors.toList());

This returns a new list of found elements.

H2: Performance Considerations

  • Arrays.binarySearch() has O(log n) complexity but requires a sorted array.
  • Linear search (loop) has O(n) complexity, suitable for small or unsorted inputs.
  • Streams may introduce overhead for large collections but are expressive and parallelizable.

Choose technique based on performance needs and data size.

H2: Best Practices (Senior Engineering Insight)

From real enterprise experience:

  • Use binarySearch for large sorted datasets to improve performance.
  • Prefer Streams for expressive filtering and modern code.
  • Avoid repeated searches inside loops — cache results where possible.
  • When dealing with custom objects, define clear equals()/hashCode() implementations.

These practices help build efficient, maintainable search logic throughout your applications.

Summary

Searching arrays and collections in Java can be done using:

  • Arrays.binarySearch() for sorted arrays
  • Traditional loops for simple linear scanning
  • List.indexOf() and contains() for collections
  • Streams for flexible, expressive, and complex conditions
  • Custom comparators for advanced object searches

Each method has use cases and performance characteristics that you can choose based on your requirements.

The post Searching Arrays and Collections in Java – Methods and Examples appeared first on javatechig.com.

]]>
https://javatechig.com/core-java/search-arrays-and-collections-in-java/feed/ 0
Convert Array to List in Java – Methods and Examples https://javatechig.com/core-java/convert-array-to-list-in-java/ https://javatechig.com/core-java/convert-array-to-list-in-java/#respond Sun, 26 Oct 2025 15:07:00 +0000 https://javatechig.com/?p=7618 Converting an array to a List is a common requirement in Java development — whether you are adapting legacy code, collecting API results, or working with collections APIs that expect List types. Java offers multiple ways to perform this conversion depending on the data type, desired mutability, and target use case. This tutorial explains all …

The post Convert Array to List in Java – Methods and Examples appeared first on javatechig.com.

]]>
Converting an array to a List is a common requirement in Java development — whether you are adapting legacy code, collecting API results, or working with collections APIs that expect List types. Java offers multiple ways to perform this conversion depending on the data type, desired mutability, and target use case.

This tutorial explains all major approaches, their behavior, and best practices with clear code examples.

1. Using Arrays.asList()

The simplest way to convert an array to a List is the Arrays.asList() method from java.util.Arrays.

Example

String[] array = {"Java", "Python", "C++"};
List list = Arrays.asList(array);
System.out.println(list);

Key Characteristics:

  • Returns a fixed-size list backed by the original array
  • You cannot add or remove elements (UnsupportedOperationException)
  • Modifications to the list update the underlying array

When to Use

Use this when you need a view of the array as a list without structural changes.

2. Creating a Modifiable List

If you need to add or remove elements, wrap the result in an ArrayList:

String[] array = {"Java", "Python", "C++"};
List list = new ArrayList<>(Arrays.asList(array));
list.add("Go");
System.out.println(list);

This produces:

[Java, Python, C++, Go]

This approach creates a separate, modifiable list that does not affect the original array.

3. Using List.of() (Immutable List)

Java 9 introduced List.of() for quick immutable list creation:

String[] array = {"Java", "Python", "C++"};
List list = List.of(array);

Notes:

  • Returns an immutable list
  • Attempts to modify (add/remove) will throw UnsupportedOperationException
  • Better semantic clarity when you do not intend to mutate the list

4. Using Java Streams (Java 8+)

Java Streams provide a fluent and functional conversion:

String[] array = {"Java", "Python", "C++"};
List list = Arrays.stream(array)
                          .collect(Collectors.toList());

Better suited when:

  • You plan to apply filtering, mapping, or other transformations
  • You want a new mutable list as a result

Example with transformation:

List upperCaseList = Arrays.stream(array)
                                   .map(String::toUpperCase)
                                   .collect(Collectors.toList());

5. Converting Primitive Arrays

Methods like Arrays.asList() do not work as expected with primitive arrays (e.g., int[]). Instead, the primitive array is treated as a single object.

Incorrect Example

int[] array = {1, 2, 3};
List list = Arrays.asList(array);

This produces a list with one element (int[]) — not the values 1, 2, 3.

Correct Conversion

Use IntStream to box primitive values:

int[] array = {1, 2, 3};
List list = IntStream.of(array)
                              .boxed()
                              .collect(Collectors.toList());

Use similar patterns for other primitives like long[] or double[].

6. Manual Loop Conversion

For full control or custom logic, convert using a loop:

String[] array = {"Java", "Python", "C++"};
List list = new ArrayList<>();
for (String s : array) {
    if (s != null && !s.isBlank()) {
        list.add(s);
    }
}

This approach enables validation or filtering during conversion.

7. Conversion with Utility Libraries

Popular third-party libraries provide convenience methods:

Guava

String[] array = {"Java", "Python", "C++"};
List list = Lists.newArrayList(array);

Apache Commons

String[] array = {"Java", "Python", "C++"};
List list = new ArrayList<>(Arrays.asList(array));

These utilities can make code more expressive, especially in large codebases.

Mutability Considerations

Conversion MethodMutable ListBacked by Array
Arrays.asList()NoYes
List.of()NoNo
Stream + CollectYesNo
New ArrayList(…)YesNo
Manual LoopYesNo

Choose based on whether you need to add, remove, or change values.

Performance Notes

  • Arrays.asList() is fast and memory-efficient because it wraps the array
  • Streams and manual loops create new collections, which cost more memory
  • For large arrays, prefer collectors and buffering strategies to manage performance

Best Practices (Senior Engineering Insight)

  • Use immutable lists when data should not change
  • Wrap with ArrayList when you need mutability
  • Use Streams for transformation and functional pipelines
  • Always handle primitive arrays with streams and boxing

These practices produce safer, more maintainable Java code.

Summary

Converting an array to a List in Java is straightforward but requires careful choice of method based on mutability and performance needs:

  • Arrays.asList() — Quick, fixed-size view
  • new ArrayList<>(...) — Modifiable collection
  • List.of() — Immutable list
  • Streams — Flexible and powerful
  • Manual loop — Custom conversion logic

Each approach has its place depending on requirements.

The post Convert Array to List in Java – Methods and Examples appeared first on javatechig.com.

]]>
https://javatechig.com/core-java/convert-array-to-list-in-java/feed/ 0
Convert String to long in Java – Methods and Examples https://javatechig.com/core-java/convert-string-to-long-in-java/ https://javatechig.com/core-java/convert-string-to-long-in-java/#respond Sun, 26 Oct 2025 15:04:00 +0000 https://javatechig.com/?p=7616 Converting a String to a primitive long or a Long object in Java is a common task, especially when processing numeric input from the user, reading values from files, or parsing network responses. Java provides standard APIs that perform this conversion reliably with built-in error handling. In this tutorial you will learn how to convert …

The post Convert String to long in Java – Methods and Examples appeared first on javatechig.com.

]]>
Converting a String to a primitive long or a Long object in Java is a common task, especially when processing numeric input from the user, reading values from files, or parsing network responses. Java provides standard APIs that perform this conversion reliably with built-in error handling.

In this tutorial you will learn how to convert a Java String to the long type and the Long wrapper class in a safe, efficient way.

When You Need to Convert a String to long

Typical scenarios include:

  • Parsing numerical IDs entered as text
  • Reading numeric values from configuration or properties
  • Processing numerical input in command-line, GUI, or web applications

Method 1: Using Long.parseLong(String)

Long.parseLong() converts a numeric string directly into a primitive long. This is the simplest and most common method.

Example

String numberStr = "1234567890";
long result = Long.parseLong(numberStr);
System.out.println("Converted long: " + result);

Notes

  • Accepts only valid numeric representations
  • Throws NumberFormatException if the string contains non-digit characters

Method 2: Using Long.valueOf(String)

Long.valueOf() returns a Long object rather than a primitive. It is useful when working with collections or APIs that expect wrapper types.

Example

String numberStr = "9876543210";
Long resultObj = Long.valueOf(numberStr);
long primitive = resultObj.longValue();
System.out.println("Converted Long object: " + resultObj);

Notes

  • Internally uses Long.parseLong() and wraps the result
  • Preferred when you need an object rather than a primitive

Handling Invalid Input Safely

When parsing user input or external data, always catch exceptions to avoid runtime crashes.

Example with Exception Handling

String input = "12ab34";

try {
    long value = Long.parseLong(input);
    System.out.println("Parsed value: " + value);
} catch (NumberFormatException e) {
    System.err.println("Invalid number: " + input);
}

Best Practices

  • Validate input before parsing when possible
  • Provide user-friendly error messages or fallbacks
  • Avoid parsing unchecked strings without try/catch

Converting With a Default Value

To avoid exceptions and provide a default when parsing fails:

public static long toLongOrDefault(String str, long defaultValue) {
    try {
        return Long.parseLong(str);
    } catch (NumberFormatException e) {
        return defaultValue;
    }
}

// Usage
long val = toLongOrDefault("abc", 0L);

This pattern is useful in configuration parsing and batch processing.

Converting a String with Radix/Base

If you have numeric strings in non-decimal formats (e.g., hex), use:

String hexStr = "1A3F";
long hexValue = Long.parseLong(hexStr, 16);
System.out.println("Hex value: " + hexValue);

This supports bases from 2 to 36.

Avoiding NullPointerException

Always check for null before conversion:

String str = null;

if (str != null) {
    long val = Long.parseLong(str);
} else {
    // handle null value
}

Passing a null string to parseLong() causes NullPointerException.

Summary of Methods

MethodReturnsThrows if invalidNotes
Long.parseLong(String)longYes (NumberFormatException)Fastest for primitives
Long.valueOf(String)LongYes (NumberFormatException)Useful when object type needed
Custom fallbacklongNo (handled)Provides default values

Best Practices (Senior Engineering Insight)

  • Always guard parsing with try/catch for robust applications
  • Use helper methods for repeated parsing logic
  • Validate input formats where possible before conversion
  • Avoid parsing unchecked external input directly in business logic

These practices help prevent unhandled exceptions and improve application stability.

The post Convert String to long in Java – Methods and Examples appeared first on javatechig.com.

]]>
https://javatechig.com/core-java/convert-string-to-long-in-java/feed/ 0
Struts2 Localization and Internationalization – Example and Setup https://javatechig.com/core-java/struts2-localization-internationalization/ https://javatechig.com/core-java/struts2-localization-internationalization/#respond Sat, 18 Oct 2025 12:46:00 +0000 https://javatechig.com/?p=7591 Modern web applications often need to support multiple languages and regional formats. In Struts2, this capability is referred to as Localization (l10n) and Internationalization (i18n). Localization adapts texts and formats for a specific locale, while Internationalization enables your app to support that adaptability in the first place. In this guide, we’ll show how to configure …

The post Struts2 Localization and Internationalization – Example and Setup appeared first on javatechig.com.

]]>
Modern web applications often need to support multiple languages and regional formats. In Struts2, this capability is referred to as Localization (l10n) and Internationalization (i18n). Localization adapts texts and formats for a specific locale, while Internationalization enables your app to support that adaptability in the first place.

In this guide, we’ll show how to configure Struts2 for localization and internationalization with message bundles, locale selection, and practical examples.

What Is Localization & Internationalization?

  • Internationalization (i18n)
    The process of making your application capable of supporting multiple locales without extensive code changes.
  • Localization (l10n)
    The process of adapting your app to a particular language or region (e.g., English, Hindi, Spanish).

Struts2 natively supports i18n/l10n using resource bundles (properties files) and configurable locale resolvers.

How Struts2 i18n Works

Struts2 localization works by:

  1. Providing localized resource bundles (.properties)
  2. Configuring Struts2 and result pages to use these bundles
  3. Passing locale parameters from the UI
  4. The framework resolves the appropriate bundle for the current locale

Project Setup

Ensure your web project includes standard Struts2 dependencies. If you’re using Maven, add:


    org.apache.struts
    struts2-core
    ${struts2.version}

Also include a locale interceptor in your stack (default stack includes it).

Resource Bundles (Message Properties)

Create localized message property files under src/main/resources:

  • Global Messages (default)
    GlobalMessages.properties
  • Spanish locale
    GlobalMessages_es.properties

Example — GlobalMessages.properties:

welcome.message=Welcome to Struts2 Internationalization!
label.username=Username
label.password=Password

Example — GlobalMessages_es.properties:

welcome.message=¡Bienvenido a la Internacionalización de Struts2!
label.username=Nombre de usuario
label.password=Contraseña

These files contain key/value pairs for UI text.

struts.xml Configuration

Struts2 automatically uses message bundles when configured properly. Put this in your struts.xml:


This tells Struts2 to load GlobalMessages*.properties as the resource bundle.

Interceptor Stack

Struts2 uses the i18n interceptor by default in the defaultStack. But if you override stacks, ensure it’s present:


    
    
        
        
    



This interceptor listens for locale changes (via parameters like request_locale).

Passing Locale from UI

On your JSP or HTML page, add language switch links:

English |
Español

When clicked, Struts2 captures request_locale and switches the locale accordingly.

Consume Resource Bundles in JSP

In Struts2 JSPs, use tag to display localized text:




Struts2 will automatically resolve the correct message based on the current locale.

Action Example

Your Struts2 Action can also use localized text:

public class LoginAction extends ActionSupport {

    public String execute() {
        String welcome = getText("welcome.message");
        addActionMessage(welcome);
        return SUCCESS;
    }
}

getText() fetches the localized message from the current resource bundle.

Changing Locale Programmatically

Sometimes you need to change the locale via logic (user selection on a form). You can do:

public String changeLanguage() {
    Locale locale = new Locale(selectedLang);
    ActionContext.getContext().setLocale(locale);
    return SUCCESS;
}

Then pass selectedLang from a drop-down (e.g., en, es, hi).

Formatting Dates and Numbers

Struts2 integrates with conversion and formatting based on locale. You can format numbers and dates transparently in JSP:



This respects current locale formats.

Best Practices (Senior Engineering Insight)

✔ Always centralize messages in resource bundles — avoid hardcoded strings.
✔ Use key naming conventions (e.g., label.*, msg.*) for clarity.
✔ Support fallback locales by providing default messages.
✔ Keep property files encoded in UTF-8 to avoid encoding issues.
✔ Load only required bundles to keep memory usage optimal.

Common Localization Issues & Fixes

Missing keys throw exceptions:
Provide default messages or include fallback resource bundles.

Language switch doesn’t persist:
Use Session or cookie to store request_locale parameters.

Encoding issues with special characters:
Ensure .properties files are saved in UTF-8 and Struts2 is configured accordingly.

Summary

Struts2 localization and internationalization allow your application to support multiple languages seamlessly. You define message bundles (.properties), configure resource paths in struts.xml, and use Struts2 tags to render localized content. With clean resource organization and proper locale resolution (via request_locale), you can deliver accurate text and formatting to users worldwide.

The post Struts2 Localization and Internationalization – Example and Setup appeared first on javatechig.com.

]]>
https://javatechig.com/core-java/struts2-localization-internationalization/feed/ 0
Making BlackBerry Applications Portable Across Multiple Devices https://javatechig.com/core-java/blackberry-application-portability-multiple-devices/ https://javatechig.com/core-java/blackberry-application-portability-multiple-devices/#respond Tue, 07 Oct 2025 17:58:18 +0000 https://javatechig.com/?p=7740 1. Introduction Building portable BlackBerry Java applications that work consistently across multiple devices requires careful handling of UI layout, screen resolution, and font scaling. Unlike modern platforms, BlackBerry devices vary significantly in screen size, resolution, and aspect ratio—especially across legacy JDE 4.5+ devices, which are still widely used in enterprise environments. This post explains how …

The post Making BlackBerry Applications Portable Across Multiple Devices appeared first on javatechig.com.

]]>
1. Introduction

Building portable BlackBerry Java applications that work consistently across multiple devices requires careful handling of UI layout, screen resolution, and font scaling. Unlike modern platforms, BlackBerry devices vary significantly in screen size, resolution, and aspect ratio—especially across legacy JDE 4.5+ devices, which are still widely used in enterprise environments.

This post explains how to handle UI portability in BlackBerry Java applications, with a focus on dynamic font resizing to support multiple screen widths such as Pearl, Curve, Torch, and Storm devices.

2. Key Challenge: Screen Resolution Differences

BlackBerry devices differ mainly in:

  • Screen width and height
  • DPI (dots per inch)
  • Font rendering behavior
  • Available UI real estate

Example Device Differences

DeviceScreen Width
PearlSmall
CurveMedium
TorchLarge
StormTouch + Wide

Because of this variation, hardcoded UI dimensions or fixed fonts often break layouts, especially for:

  • Labels
  • ChoiceFields
  • Custom UI components

3. Why Font Scaling Is Critical

Consider a business application containing:

  • Labels
  • ChoiceFields with dynamic values
  • Localized text (variable length)

If text exceeds screen width:

  • UI gets clipped
  • Fields overlap
  • Application looks broken

To avoid this, font size must be calculated dynamically based on screen width and content length.

4. Dynamic Font Calculation Strategy

The recommended approach is:

  1. Calculate available row width based on screen resolution
  2. Measure text width using Font.getAdvance()
  3. Reduce font height dynamically until content fits
  4. Apply the calculated font before rendering

This approach ensures:

  • UI consistency across devices
  • No clipped text
  • Better readability

5. Customizing ChoiceField Rendering

Below is a custom paint implementation for dynamically resizing text in a ChoiceField.

Custom paint() Method

protected void paint(Graphics graphics) {

    Resolutions r = new Resolutions();
    Font labelFont = r.getFont();
    Font font = r.getFont();

    int width = r.CustomRowWidth - 3;
    int calcWidth = 0;

    while (width < (font.getAdvance(label) + maxWidth(font))) {

        calcWidth = labelFont.getAdvance(label) + maxWidth(font);
        int height = font.getHeight() - 2;

        FontFamily fontFamily = Font.getDefault().getFontFamily();
        font = fontFamily.getFont(Font.PLAIN, height);
    }

    graphics.setFont(font);
    this.setFont(font);

    if (mFontColor != -1) {
        graphics.setColor(mFontColor);
    }

    super.paint(graphics);
}

6. Calculating Maximum Choice Width

The maxWidth() method determines the longest string among all available choices in the ChoiceField. This ensures font scaling accounts for worst-case content length.

public int maxWidth(Font font) {

    int max = -1;

    for (int i = 0; i < this.getSize(); i++) {
        String choice = (String) this.getChoice(i);
        int width = font.getAdvance(choice);

        if (width > max) {
            max = width;
        }
    }
    return max;
}

7. Best Practices for BlackBerry UI Portability

  • Avoid hardcoded font sizes
  • Calculate UI dimensions dynamically
  • Always consider smallest screen first (Pearl)
  • Test on multiple simulators and real devices
  • Handle localization text expansion

8. Applicability in Real Projects

This approach is particularly useful for:

  • Enterprise BlackBerry applications
  • Legacy app maintenance
  • Multi-device deployments
  • Apps targeting JDE 4.5 – 7.x

Understanding these UI techniques remains valuable when maintaining or upgrading existing BlackBerry Java applications.

The post Making BlackBerry Applications Portable Across Multiple Devices appeared first on javatechig.com.

]]>
https://javatechig.com/core-java/blackberry-application-portability-multiple-devices/feed/ 0
Java String Length & Trim Example – Guide with Code https://javatechig.com/core-java/string-length-and-trim-string-in-java/ https://javatechig.com/core-java/string-length-and-trim-string-in-java/#respond Sat, 20 Sep 2025 12:27:00 +0000 https://javatechig.com/?p=7347 In Java, handling string length and whitespace cleanup are fundamental tasks for text processing, validation, and UI formatting. This updated guide on javatechig.com explains how to determine the length of a string and how to remove leading and trailing whitespace using modern, best-practice approaches with clear examples in Java. Understanding Strings in Java In Java, …

The post Java String Length & Trim Example – Guide with Code appeared first on javatechig.com.

]]>
In Java, handling string length and whitespace cleanup are fundamental tasks for text processing, validation, and UI formatting. This updated guide on javatechig.com explains how to determine the length of a string and how to remove leading and trailing whitespace using modern, best-practice approaches with clear examples in Java.

Understanding Strings in Java

In Java, String objects store immutable sequences of characters. Operations like calculating length and trimming whitespace are foundational in parsing, input validation, and data normalization.

Java strings are widely used in:

  • User input processing
  • File handling
  • Text formatting
  • Database and network responses

Getting the Length of a String (length())

Java’s String.length() method returns the number of characters in a string.

Example

String text = "Hello World";
int size = text.length();
System.out.println("Length: " + size); // Output: Length: 11

Notes

  • Counts all characters, including spaces
  • Returns 0 for an empty string ("")
  • Does not count null; calling on a null reference throws NullPointerException

Removing Whitespace Using trim()

The trim() method returns a new string with leading and trailing whitespace removed.

Example

String raw = "   Java Rocks   ";
String trimmed = raw.trim();

System.out.println("Before: '" + raw + "'");
System.out.println("After: '" + trimmed + "'");

Output:

Before: '   Java Rocks   '
After: 'Java Rocks'

What trim() Removes

  • Space ' '
  • Horizontal tab \t
  • Newline \n
  • Carriage return \r

Using isEmpty() with length()

A string is empty when its length is zero.

String s = "";
boolean empty = s.isEmpty(); // true

Match with length:

s.length() == 0 // true

isEmpty() is a clearer intent for readability.

Handling null Safely

Calling length() or trim() on null throws an exception. Always check for null:

if (str != null && !str.isEmpty()) {
    // safe to call length() or trim()
}

Or use Objects.requireNonNullElse():

String safe = Objects.requireNonNullElse(str, "");

Practical Examples

Cleaning User Input

When reading from command line or forms:

String userInput = scanner.nextLine().trim();

This helps remove accidental input spaces.

Normalizing File Paths

String path = "  /usr/local/bin/  ";
path = path.trim();

Trimmed paths avoid incorrect comparisons.

Logging and Reporting

String message = "  Error occurred  ";
logger.info(message.trim());

Ensures consistent log formatting.

Tips and Best Practices

Prefer isEmpty() for Readability

string.isEmpty() expresses intent better than string.length() == 0.

Always Null-Check Before Access

NullPointerException is a common pitfall; guard against null references.

Consider strip() (Java 11+)

Java 11 adds String.strip() which removes Unicode whitespace:

String s = "\u2002Hello\u2002";
s = s.strip(); // removes Unicode spaces

This is more comprehensive than trim() for international applications.

Common Mistakes

Assuming length() Excludes Spaces

length() counts all characters, including whitespace.

Using trim() for Internal Spaces

trim() only removes leading/trailing spaces, not spaces within the string:

String s = "  Hello World  ";
s.trim(); // "Hello World", internal space remains

Use replaceAll("\\s+", " ") for internal normalization.

Summary of Methods

MethodPurpose
length()Returns number of characters
trim()Removes leading/trailing whitespace
isEmpty()Checks for empty string
strip()Unicode whitespace removal (Java 11+)

The post Java String Length & Trim Example – Guide with Code appeared first on javatechig.com.

]]>
https://javatechig.com/core-java/string-length-and-trim-string-in-java/feed/ 0
Struts2 Login Application Tutorial – Complete Setup and Example https://javatechig.com/core-java/struts2-login-application-tutorial/ https://javatechig.com/core-java/struts2-login-application-tutorial/#respond Fri, 22 Aug 2025 13:17:00 +0000 https://javatechig.com/?p=7604 Building a login feature is one of the most fundamental tasks when developing web applications with Struts2. This tutorial walks you through creating a login application using Struts2 from scratch — including project setup, configuration, form processing, validation, and session handling. You will learn how Struts2 handles requests, binds form parameters to action properties, performs …

The post Struts2 Login Application Tutorial – Complete Setup and Example appeared first on javatechig.com.

]]>
Building a login feature is one of the most fundamental tasks when developing web applications with Struts2. This tutorial walks you through creating a login application using Struts2 from scratch — including project setup, configuration, form processing, validation, and session handling.

You will learn how Struts2 handles requests, binds form parameters to action properties, performs validation, and navigates to views using results.

Overview – How Struts2 Works

Struts2 uses the MVC (Model-View-Controller) pattern:

  • Controller: Intercepts requests via FilterDispatcher (or StrutsPrepareAndExecuteFilter)
  • Model: POJOs bound to form input
  • View: JSP pages rendered with Struts2 tags
  • Action: Handles business logic and returns result strings

Struts2 interceptors handle request preparation, parameter binding, validation, and result invocation.

Project Setup

Required Libraries

You can bootstrap a Struts2 project using Maven or manually place the required JARs. When using Maven, include:

<dependencies>
    <dependency>
        <groupId>org.apache.struts</groupId>
        <artifactId>struts2-core</artifactId>
        <version>2.5.22</version>
    </dependency>
</dependencies>

Use the latest stable Struts2 version available in Maven Central.

Web Descriptor (web.xml)

Configure the Struts2 filter to handle requests:

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
</welcome-file-list>

This filter intercepts all incoming requests and dispatches them through the Struts2 framework.

Create the Login Form (JSP)

login.jsp

Place this JSP under the web content folder:

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <s:form action="login">
        <s:textfield name="username" label="Username" />
        <s:password name="password" label="Password" />
        <s:submit value="Login" />
    </s:form>

    <s:if test="hasActionErrors()">
        <ul>
            <s:actionerror />
        </ul>
    </s:if>
</body>
</html>

This form submits to the login action with username and password fields.

Define the LoginAction

LoginAction.java

Create an action class with getters and setters for form parameters:

public class LoginAction extends ActionSupport {

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String execute() {
        if ("admin".equals(username) && "password123".equals(password)) {
            return SUCCESS;
        } else {
            addActionError("Invalid username or password");
            return INPUT;
        }
    }
}

The execute() method checks credentials and returns either SUCCESS or INPUT (to redisplay the login form on failure).

Map the Action in struts.xml

struts.xml

Create or update your Struts2 configuration:

<struts>
    <package name="default" namespace="/" extends="struts-default">

        <action name="login" class="com.javatechig.LoginAction">
            <result name="success">welcome.jsp</result>
            <result name="input">login.jsp</result>
        </action>

    </package>
</struts>

This defines the login action with two possible results: success and input.

Add the Welcome Page

welcome.jsp

This page displays after successful login:

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Welcome</title></head>
<body>
    <h2>Welcome, <s:property value="username" />!</h2>
    <s:form action="logout">
        <s:submit value="Logout" />
    </s:form>
</body>
</html>

Parameters from LoginAction are automatically available in the view.

Enabling Validation (Optional)

Struts2 supports annotation or XML validation.

Using XML Validator

Create a file named LoginAction-validation.xml next to your action class:

<validators>
    <field name="username">
        <fieldvalidator type="requiredstring">
            <message>Username is required</message>
        </fieldvalidator>
    </field>
    <field name="password">
        <fieldvalidator type="requiredstring">
            <message>Password is required</message>
        </fieldvalidator>
    </field>
</validators>

Struts2 will invoke this validator before execute() and return input on validation errors.

Session Management

After a successful login, you may want to store the user in a session. Modify the action:

Map<String, Object> session = ActionContext.getContext().getSession();
session.put("USER", username);

Then in JSP:

<s:property value="#session.USER" />

Use the session judiciously and clear it on logout.

Strongly Typed Tags and UI

Struts2 tag library helps to build forms, property displays, and error messages without manual HTML.

Examples:

  • <s:form> for forms
  • <s:textfield> and <s:password> for inputs
  • <s:submit> for submit button
  • <s:actionerror> to display action errors

These tags reduce boilerplate and integrate with the Struts2 type converters and interceptors.

Best Practices (Senior Engineering Insight)

From extensive enterprise experience:

  • Avoid storing plain passwords — use hashing & secure credential validation
  • Use validation interceptors instead of manual checks where possible
  • Encapsulate business logic outside actions (service layer)
  • Namespace your actions for modular modules
  • Use site-wide templates (tiles or layouts) for consistent UI

These practices lead to maintainable and secure Struts2 applications.

Common Issues and Fixes

Login does not submit:
✔ Check that the form action matches the action name in struts.xml

Validation not triggered:
✔ Ensure validator config matches action class name (ActionClass-validation.xml)

Session values not available in JSP:
✔ Verify session interceptor is enabled (default stack includes it)

Summary

This tutorial showed how to build a login application using Struts2, including:

  • Project and filter setup
  • Login form creation
  • Struts2 action with business logic
  • Result mapping for success and failure
  • Optional validation rules
  • Session management for logged-in users

Struts2 simplifies request handling and form processing using conventions and a flexible interceptor stack. With proper architecture, you can extend this login pattern into a full authentication module.

The post Struts2 Login Application Tutorial – Complete Setup and Example appeared first on javatechig.com.

]]>
https://javatechig.com/core-java/struts2-login-application-tutorial/feed/ 0
Sort Array Ascending & Descending with Comparator in Java https://javatechig.com/core-java/sort-array-ascending-or-descending-using-comparator-in-java/ https://javatechig.com/core-java/sort-array-ascending-or-descending-using-comparator-in-java/#respond Fri, 22 Aug 2025 12:36:00 +0000 https://javatechig.com/?p=7357 Sorting arrays is a fundamental operation in software development. In Java, you can use the Comparator interface to define custom sorting logic for arrays of objects. This gives you full control over ascending or descending order based on specific attributes. This updated guide on javatechig.com shows how to sort arrays using Comparator, including object sorting, …

The post Sort Array Ascending & Descending with Comparator in Java appeared first on javatechig.com.

]]>
Sorting arrays is a fundamental operation in software development. In Java, you can use the Comparator interface to define custom sorting logic for arrays of objects. This gives you full control over ascending or descending order based on specific attributes.

This updated guide on javatechig.com shows how to sort arrays using Comparator, including object sorting, lambda syntax, and best practices aligned with modern Java standards.

Why Use Comparator for Sorting

The Comparator interface allows you to:

  • Sort by custom criteria
  • Switch between ascending/descending easily
  • Sort complex objects (not just primitives)
  • Maintain reusable comparison logic

Unlike natural ordering (Comparable), Comparator gives external sorting rules without modifying the class.

Sorting Primitive Arrays

Ascending Order (Wrapper Arrays)

Java’s Arrays.sort() can sort primitives directly:

int[] numbers = {5, 1, 9, 3, 7};
Arrays.sort(numbers); // ascending

For descending on primitives, convert to wrapper type:

Integer[] nums = {5, 1, 9, 3, 7};
Arrays.sort(nums, Collections.reverseOrder());

Sorting Object Arrays with Comparator

Assume you have an array of custom objects:

class Person {
    String name;
    int age;

    // Constructor, getters
}

Sort Ascending by Age

Comparator<Person> byAgeAsc = Comparator.comparingInt(Person::getAge);
Arrays.sort(personArray, byAgeAsc);

This sorts the array by increasing age.

Sort Descending by Age

Comparator<Person> byAgeDesc = Comparator.comparingInt(Person::getAge).reversed();
Arrays.sort(personArray, byAgeDesc);

You can chain comparators as needed.

Sorting by Multiple Attributes

To sort first by age, then name:

Comparator<Person> composite = Comparator
        .comparingInt(Person::getAge)
        .thenComparing(Person::getName);

Arrays.sort(personArray, composite);

This ensures deterministic ordering with multiple fields.

Lambda‑Based Sorting

Ascending by Name

Arrays.sort(personArray, (p1, p2) -> p1.getName().compareTo(p2.getName()));

Descending by Name

Arrays.sort(personArray, (p1, p2) -> p2.getName().compareTo(p1.getName()));

The lambda approach is concise and readable.

Sorting with List instead of Array

When working with lists:

List<Person> list = Arrays.asList(personArray);

list.sort(Comparator.comparing(Person::getAge));

Or for descending:

list.sort(Comparator.comparing(Person::getAge).reversed());

Lists offer more flexibility than arrays for dynamic-sized data.

Using Streams for Sorting

Java Streams offer a functional approach:

Ascending

Person[] sorted = Arrays.stream(personArray)
    .sorted(Comparator.comparing(Person::getAge))
    .toArray(Person[]::new);

Descending

Person[] sortedDesc = Arrays.stream(personArray)
    .sorted(Comparator.comparing(Person::getAge).reversed())
    .toArray(Person[]::new);

Streams allow chaining additional operations like filtering.

Common Mistakes & Fixes

Using == for Comparison

For object attributes, always use comparison methods (compareTo), not ==.

Not Handling Nulls

When sorting, null elements can cause exceptions.

Fix with null‑safe comparator:

Comparator<Person> safeSort = Comparator.nullsLast(
        Comparator.comparing(Person::getAge));

This places null elements after non‑null.

Performance Considerations

  • Arrays.sort() uses dual‑pivot quicksort for primitives and TimSort for objects
  • Sorting large arrays repeatedly is expensive — avoid redundant sorts
  • For frequent updates, consider data structures like TreeSet

Best Practices (2026 Updated)

  • Prefer Comparator.comparing() with method references
  • Use reversed() cleanly for descending order
  • Leverage thenComparing() for multi‑level sort
  • Use List.sort() and Streams for modern codebases
  • Always handle nulls explicitly in real‑world data

Example Summary

Use CaseMethod
Ascending primitivesArrays.sort()
Descending primitivesCollections.reverseOrder()
Object sortComparator.comparing()
Multi‑attributethenComparing()
Streamsstream().sorted()

The post Sort Array Ascending & Descending with Comparator in Java appeared first on javatechig.com.

]]>
https://javatechig.com/core-java/sort-array-ascending-or-descending-using-comparator-in-java/feed/ 0