Open-source News

Ubuntu's Real-Time Kernel Approaching GA Status

Phoronix - Tue, 01/10/2023 - 23:50
Last year with the release of Ubuntu 22.04 LTS there was a beta real-time kernel offering from Canonical...

How to use methods in Java

opensource.com - Tue, 01/10/2023 - 23:25
How to use methods in Java sethkenlon Tue, 01/10/2023 - 10:25

A method in Java (called a "function" in many other programming languages) is a portion of code that's been grouped together and labeled for reuse. Methods are useful because they allow you to perform the same action or series of actions without rewriting the same code, which not only means less work for you, it means less code to maintain and debug when something goes wrong.

A method exists within a class, so the standard Java boilerplate code applies:

package com.opensource.example;

public class Example {
  // code here
}

A package definition isn't strictly necessary in a simple one-file application like this, but it's a good habit to get into, and most IDEs enforce it.

By default, Java looks for a main method to run in a class. Methods can be made public or private, and static or non-static, but the main method must be public and static for the Java compiler to recognize and utilize it. When a method is public, it's able to be executed from outside the class. To call the Example class upon start of the program, its main method must be accessible, so set it to public.

Here's a simple demonstration of two methods: one main method that gets executed by default when the Example class is invoked, and one report method that accepts input from main and performs a simple action.

To mimic arbitrary data input, I use an if-then statement that chooses between two strings, based on when you happen to start the application. In other words, the main method first sets up some data (in real life, this data could be from user input, or from some other method elsewhere in the application), and then "calls" the report method, providing the processed data as input:

package com.opensource.example;

public class Example {
  public static void main(String[] args) {
    // generate some data
    long myTime = System.currentTimeMillis();
    String weather;

    if ( myTime%2 == 0 ) {
      weather = "party";
    } else {
      weather = "apocalypse";
    }

    // call the other method
    report(weather);
  }

  private static void report(String day) {
    System.out.printf("Welcome to the zombie %s\n", day);
  }
}

Run the code:

$ java ./Example.java
Welcome to the zombie apocalypse
$ java ./Example.java
Welcome to the zombie party

Notice that there are two different results from the same report method. In this simple demonstration, of course, there's no need for a second method. The same result could have been generated from the if-then statement that mimics the data generation. But when a method performs a complex task, like resizing an image into a thumbnail and then generating a widget on screen using that resized image, then the "expense" of an additional component makes a lot of sense.

More on Java What is enterprise Java programming? An open source alternative to Oracle JDK Java cheat sheet Red Hat build of OpenJDK Free online course: Developing cloud-native applications with microservices Fresh Java articles When to use a Java method

It can be difficult to know when to use a method and when to just send data into a Java Stream or loop. If you're faced with that decision, the answer is usually to use a method. Here's why:

  • Methods are cheap. They don't add processing overhead to your code.
  • Methods reduce the line count of your code.
  • Methods are specific. It's usually easier to find a method called resizeImage than it is to find code that's hidden in a loop somewhere in the function that loads images from the drive.
  • Methods are reusable. When you first write a method, you may think it's only useful for one task within your application. As your application grows, however, you may find yourself using a method you thought you were "done" with.
Functional vs. object-oriented programming

Functional programming utilizes methods as the primary construct for performing tasks. You create a method that accepts one kind of data, processes that data, and outputs new data. String lots of methods together, and you have a dynamic and capable application. Programming languages like C and Lua are examples of this style of coding.

The other way to think of accomplishing tasks with code is the object-oriented model, which Java uses. In object-oriented programming, methods are components of a template. Instead of sending data from method to method, you create objects with the option to alter them through the use of their methods.

Here's the same simple zombie apocalypse demo program from an object-oriented perspective. In the functional approach, I used one method to generate data and another to perform an action with that data. The object-oriented equivalent is to have a class that represents a work unit. This example application presents a message-of-the-day to the user, announcing that the day brings either a zombie party or a zombie apocalypse. It makes sense to program a "day" object, and then to query that day to learn about its characteristics. As an excuse to demonstrate different aspects of object-oriented construction, the new sample application will also count how many zombies have shown up to the party (or apocalypse).

Java uses one file for each class, so the first file to create is Day.java, which serves as the Day object:

package com.opensource.example;

import java.util.Random;

// Class
public class Day {
    public static String weather;
    public int count;

// Constructor
  public Day() {
    long myTime = System.currentTimeMillis();

    if ( myTime%2 == 0 ) {
      weather = "paradise";
    } else {
      weather = "apocalypse";
    }
  }

// Methods
  public String report() {
      return weather;
  }

  public int counter() {
    Random rand = new Random();
    count = count + rand.nextInt(100);

    return(count);
    }
}

In the Class section, two fields are created: weather and count. Weather is static. Over the course of a day (in this imaginary situation), weather doesn't change. It's either a party or an apocalypse, and it lasts all day. The number of zombies, however, increases over the course of a day.

In the Constructor section, the day's weather is determined. It's done as a constructor because it's meant to only happen once, when the class is initially invoked.

In the Methods section, the report method only returns the weather report as determined and set by the constructor. The counter method, however, generates a random number and adds it to the current zombie count.

This class, in other words, does three very different things:

  • Represents a "day" as defined by the application.
  • Sets an unchanging weather report for the day.
  • Sets an ever-increasing zombie count for the day.

To put all of this to use, create a second file:

package com.opensource.example;

public class Example {
  public static void main(String[] args) {
    Day myDay = new Day();
    String foo = myDay.report();
    String bar = myDay.report();

    System.out.printf("Welcome to a zombie %s\n", foo);
    System.out.printf("Welcome to a zombie %s\n", bar);
    System.out.printf("There are %d zombies out today.\n", myDay.counter());
    System.out.printf("UPDATE: %d zombies. ", myDay.counter());
    System.out.printf("UPDATE: %d zombies. ", myDay.counter());
  }
}

Because there are now two files, it's easiest to use a Java IDE to run the code, but if you don't want to use an IDE, you can create your own JAR file. Run the code to see the results:

Welcome to a zombie apocalypse
Welcome to a zombie apocalypse
There are 35 zombies out today.
UPDATE: 67 zombies. UPDATE: 149 zombies.

The "weather" stays the same regardless of how many times the report method is called, but the number of zombies on the loose increases the more you call the counter method.

Java methods

Methods (or functions) are important constructs in programming. In Java, you can use them either as part of a single class for functional-style coding, or you can use them across classes for object-oriented code. Both styles of coding are different perspectives on solving the same problem, so there's no right or wrong decision. Through trial and error, and after a little experience, you learn which one suits a particular problem best.

Learn the definition of a method in Java, how to use methods, and when to use methods in this handy tutorial.

Image by:

Pixabay. CC0.

Java What to read next This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License. Register or Login to post a comment.

Linux Preparing To Disable Drivers For Microsoft's RNDIS Protocol

Phoronix - Tue, 01/10/2023 - 20:33
With the next Linux kernel cycle we could see upstream disable their driver support for Microsoft's Remote Network Driver Interface Specification (RNDIS) protocol due to security concerns...

More AMD Zen 4 Tuning Ongoing For GCC 13 Compiler

Phoronix - Tue, 01/10/2023 - 18:44
GCC compiler expert Jan Hubicka at SUSE began working on AMD Zen 4 compiler tuning patches that began landing in December for the GCC 13 compiler that will debut as stable in a few months. It looks like the work isn't over on Znver4 tuning with another patch being sent out today for fine-tuning the latest AMD CPU microarchitecture...

CentOS Hyperscale SIG Caps Off A Busy 2022

Phoronix - Tue, 01/10/2023 - 18:32
Established two years ago was the CentOS Hyperscale SIG for a group of engineers from Facebook, Twitter, and other hyperscalers in making optional changes to CentOS Stream to better suit the Linux distribution to their internal needs...

Microsoft's Dozen Up To A 98.5% Pass Rate For Vulkan 1.0

Phoronix - Tue, 01/10/2023 - 18:16
Microsoft's Dozen "dzn", which was merged to Mesa last year as Vulkan implemented on Direct3D 12, is onto a 98.5% pass rate for its Vulkan 1.0 coverage...

A guide to strings in MySQL

opensource.com - Tue, 01/10/2023 - 16:00
A guide to strings in MySQL HunterC Tue, 01/10/2023 - 03:00

Strings are one of the most common data types you will use in MySQL. Many users insert and read strings in their databases without thinking too much about them. This article aims to give you a bit of a deep dive into how MySQL stores and displays your string variables so that you can have better control over your data.

You can break strings into two categories: binary and nonbinary. You probably think about nonbinary strings most of the time. Nonbinary strings have character sets and collations. Binary strings, on the other hand, store things such as MP3 files or images. Even if you store a word in a binary string, such as song, it is not stored in the same way as in a nonbinary string.

I will focus on nonbinary strings. All nonbinary strings in MySQL are associated with a character set and a collation. A string's character set controls what characters can be stored in the string, and its collation controls how the strings are ordered when you display them.

Character sets

To view the character sets on your system, run the following command:

SHOW CHARACTER SET;

This command will output four columns of data, including the character set:

  • Name
  • Brief description
  • Default collation
  • Maximum size of each character in the character set

MySQL used to default to the latin1 character set, but since version 8.0, the default has been utf8mb4. The default collation is now utf8mb4_0900_ai_ci. The ai indicates that this collation is accent insensitive (á = a), and the ci specifies that it is case insensitive (a = A).

Different character sets store their characters in various-sized chunks of memory. For example, as you can see from the above command, characters stored in utf8mb4 are stored in memory from one to four bytes in size. If you want to see if a string has multibyte characters, you can use the CHAR_LENGTH() and LENGTH() functions. CHAR_LENGTH() displays how many characters a string contains, whereas LENGTH() shows how many bytes a string has, which may or may not be the same as a string's length in characters, depending on the character set. Here is an example:

SET @a = CONVERT('data' USING latin1);

SELECT LENGTH(@a), CHAR_LENGTH(@a);

+------------+-----------------+
| LENGTH(@a) | CHAR_LENGTH(@a) |
+------------+-----------------+
|     4      |       4         |
+------------+-----------------+

This example shows that the latin1 character set stores characters in single-byte units. Other character sets, such as utf16, allow multibyte characters:

SET @b = CONVERT('data' USING utf16);

SELECT LENGTH(@b), CHAR_LENGTH(@b);

+------------+------------------+
| LENGTH(@b) | CHAR_LENGTH(@b)  |
+------------+------------------+
|       8    |        4         |
+------------+------------------+Collation

A string's collation will determine how the values are displayed when you run a SQL statement with an ORDER BY clause. Your choice of collations is determined by what character set you select. When you ran the command SHOW CHARACTER SET above, you saw the default collations for each character set. You can easily see all the collations available for a particular character set. For example, if you want to see which collations are allowed by the utf8mb4 character set, run:

SHOW COLLATION LIKE 'utf8mb4%';

A collation can be case-insensitive, case-sensitive, or binary. Let's build a simple table, insert a few values into it, and then view the data using different collations to see how the output differs:

CREATE TABLE sample (s CHAR(5));

INSERT INTO sample (s) VALUES
 ('AAAAA'), ('ccccc'),  ('bbbbb'), ('BBBBB'), ('aaaaa'), ('CCCCC');

SELECT * FROM sample;

+-----------+
| s         |
+-----------+
| AAAAA     |
| ccccc     |
| bbbbb     |
| BBBBB     |
| aaaaa     |
| CCCCC     |
+-----------+

With case-insensitive collations, your data is returned in alphabetical order, but there is no guarantee that capitalized words will come before lowercase words, as seen below:

SELECT * FROM sample ORDER BY s COLLATE utf8mb4_turkish_ci;

+-----------+
| s         |
+-----------+
| AAAAA     |
| aaaaa     |
| bbbbb     |
| BBBBB     |
| ccccc     |
| CCCCC     |
+-----------+

On the other hand, when MySQL runs a case-sensitive search, lowercase will come before uppercase for each letter:

SELECT * FROM sample ORDER BY s COLLATE utf8mb4_0900_as_cs;

+-----------+
| s         |
+-----------+
| aaaaa     |
| AAAAA     |
| bbbbb     |
| BBBBB     |
| ccccc     |
| CCCCC     |
+-----------+

And binary collations will return all capitalized words before lowercase words:

SELECT * FROM sample ORDER BY s COLLATE utf8mb4_0900_bin;

+-----------+
| s         |
+-----------+
| AAAAA     |
| ccccc     |
| bbbbb     |
| BBBBB     |
| aaaaa     |
| CCCCC     |
+-----------+

If you want to know which character set and collation a string uses, you can use the aptly named charset and collation functions. A server running MySQL version 8.0 or higher will default to using the utf8mb4 character set and utf8mb4_0900_ai-ci collation:

SELECT charset('data');

+-------------------+
| charset('data')   |
+-------------------+
| utf8mb4           |
+-------------------+

 SELECT collation('data');

+--------------------+
| collation('data')  |
+--------------------+
| utf8mb4_0900_ai_ci |
+--------------------+

You can use the SET NAMES command to change the character set or collation used.

To change from the utf8mb4 character set to utf16, run this command:

SET NAMES 'utf16';

If you would also like to choose a collation other than the default, you can add a COLLATE clause to the SET NAMES command.

For example, say your database stores words in the Spanish language. The default collation for MySQL (utf8mb4_0900_ai_ci) sees ch and ll as two different characters and will sort them as such. But in Spanish, ch and ll are individual letters, so if you want them sorted in the proper order (following c and l, respectively), you need to use a different collation. One option is to use the utf8mb4_spanish2_ci collation.

SET NAMES 'utf8mb4' COLLATE 'utf8mb4_spanish2-ci';

More on data science What is data science? What is Python? How to become a data scientist Data scientist: A day in the life Use JupyterLab in the Red Hat OpenShift Data Science sandbox Whitepaper: Data-intensive intelligent applications in a hybrid cloud blueprint MariaDB and MySQL cheat sheet Latest data science articles Storing strings

MySQL allows you to choose between several data types for your string values. (Even more so than other popular databases such as PostgreSQL and MongoDB.)

Here is a list of MySQL's binary string data types, their nonbinary equivalents, and their maximum length:

  • binary: char (255)
  • varbinary: varchar (65,535)
  • tinyblob: tinytext (255)
  • blob: text (65,535)
  • mediumblob: mediumtext (16,777,215)
  • longblob: longtext (4,294,967,295)

One important thing to remember is that unlike the varbinary, varchar, text, and blob types, which are stored in variable length fields (that is, using only as much space as needed), MySQL stores binary and char types in fixed length fields. So a value such as char(20) or binary(20) will always take up 20 bytes, even if you store less than 20 characters in them. MySQL pads the values with the ASCII NUL value (0x00) for binary types and spaces for char types.

Another thing to consider when choosing data types is whether you want spaces after the string to be preserved or stripped. When displaying data, MySQL strips whitespace from data stored with the char data type, but not varchar.

CREATE TABLE sample2 (s1 CHAR(10), s2 VARCHAR(10));

INSERT INTO sample2 (s1, s2) VALUES ('cat       ', 'cat       ');

SELECT s1, s2, CHAR_LENGTH(s1), CHAR_LENGTH(s2) FROM sample2;

+---------+---------+-----------------------------------+
| s1      | s2      | CHAR_LENGTH(s1) | CHAR_LENGTH(s2) |
+---------+---------+-----------------------------------+
| cat     | cat     |        3        |       10        |
+---------+---------+-----------------------------------+Wrap up

Strings are one of the most common data types used in databases, and MySQL remains one of the most popular database systems in use today. I hope that you have learned something new from this article and will be able to use your new knowledge to improve your database skills.

Learn how MySQL stores and displays your string variables so that you can have better control over your data.

Image by:

Opensource.com

Databases What to read next This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License. Register or Login to post a comment.

Pages