Friday, April 28, 2023

Java Concurrency: Condition

Oracle Java Certification, Java Skills, Java Certification Exam, Oracle Java Learning, Java Jobs, Java

Previously we checked on ReentRantLock and its fairness. One of the things we can stumble upon is the creation of a Condition. By using Condition we can create mechanisms that allow threads to wait for specific conditions to be met before proceeding with their execution.

The condition provides the following methods:

public interface Condition {
 
    void await() throws InterruptedException;
 
    void awaitUninterruptibly();
 
    long awaitNanos(long nanosTimeout) throws InterruptedException;
 
    boolean await(long time, TimeUnit unit) throws InterruptedException;
 
    boolean awaitUntil(Date deadline) throws InterruptedException;
 
    void signal();
 
    void signalAll();
}

The closest we came to that so far is the wait Object Monitor method.

A Condition is bound to a Lock and a thread cannot interact with a condition and its methods if it does not have a hold on that lock.

Also Condition uses the underlying lock mechanisms, for example signal and signalAll will use the underlying Queue of the threads that is maintained by the Lock and will notify them to wake up.

One of the obvious things to implement using Conditions is a BlockingQueue. Worker threads processing data and publisher threads dispatching data. Data are published on a queue, worker threads will process data from the queue and then they should wait if there is no data in the queue.

For a worker thread, if the condition is met the flow is the following:

◉ Acquire the lock
◉ Check the condition
◉ Process Data
◉ Release the lock

If the condition is not met, the flow would slightly change to this:

◉ Acquire the lock
◉ Check the condition
◉ Wait until the condition is met.
◉ Re-acquire the lock
◉ Process Data
◉ Release the lock

The publisher thread whenever it adds a message it should notify the threads waiting on the condition.

The workflow would be like this.

◉ Acquire the lock
◉ Publish data
◉ Notify the workers
◉ Release the lock

Obviously this functionality already exists through the BlockingQueue interface and the LinkedBlockingDeque and ArrayBlockingQueue implementation.

We will proceed with an implementation for the shake of the example.

Let’s see the Message Queue:

package com.gkatzioura.concurrency.lock.condition;
 
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public class MessageQueue<T> {
 
    private Queue<T> queue = new LinkedList<>();
    private Lock lock = new ReentrantLock();
    private Condition hasMessages = lock.newCondition();
 
    public void publish(T message) {
        lock.lock();
        try {
            queue.offer(message);
            hasMessages.signal(); 
        } finally {
            lock.unlock();
        }
    }
 
    public T receive() throws InterruptedException {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                hasMessages.await();
            }
            return queue.poll();
        } finally {
            lock.unlock();
        }
    }
 
}

Now let’s put it into action:

MessageQueue<String> messageQueue = new MessageQueue<>();
 
    @Test
    void testPublish() throws InterruptedException {
        Thread publisher = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                String message = "Sending message num: " + i;
                log.info("Sending [{}]", message);
                messageQueue.publish(message);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
 
        Thread worker1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    String message = messageQueue.receive();
                    log.info("Received: [{}]", message);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
 
        Thread worker2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    String message = messageQueue.receive();
                    log.info("Received: [{}]", message);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
 
        publisher.start();
        worker1.start();
        worker2.start();
 
        publisher.join();
        worker1.join();
        worker2.join();
    }

That’s it! Our workers processed the expected messages and waited when the queue was empty.

Source: javacodegeeks.com

Wednesday, April 26, 2023

Quiz yourself: Unmodifiable Map objects created from Java’s Map.of methods

Oracle Java, Oracle Java Tutorial and Materials, Java Career, Java Jobs, Java Tutorial and Materials


Given the following map

var m = Map.of(1,2,3,4);

Which code fragment is guaranteed to print 37 to the console? Choose one.

A. m.forEach((x, y) -> System.out.print(x + y));
 
B. for (var v : m) {
System.out.print(v.getKey() + v.getValue());
}
 
C. for (var v : m.keySet()) {
System.out.print(v + m.get(v));
}
 
D. for (var t : m.entrySet()) {
System.out.print(t.getKey() + t.getValue());
}
 
E. None of the above
 
Answer. This question investigates concepts related to the Map interface and the unmodifiable Map objects created from the Map.of methods.

Look at the effect of the Map.of(1,2,3,4) method call. It creates a Map<Integer, Integer> with two key-value pairs. The keys for these pairs are 1 and 3, and the corresponding values are 2 and 4. Note that the Map.of methods that take arguments in this form treat those arguments as a key, a value, a key, a value, and so on. The keys and values, of course, will be autoboxed to provide Integer objects.

Since you have two pairs in this Map—1-2 and 3-4—it’s a simple observation of arithmetic that adding the key-value pairs will give the results 3 and 7, which seems at least promising for producing the desired output.

Now, look at the code of each option in turn.

Option A has a call to m.forEach. Java 8 added a forEach method to many types from the Collections API (for example, java.util.Map or java.util.List). The method allows you to perform some action on each element or entry from the collection. The map.forEach method in this case accepts a BiConsumer<Integer, Integer> as its argument, and the accept method of that argument will be called with a key and value pair from each key-value pair. So, you can see that code potentially can print 37. Hold on to that thought.

Option B attempts to use the Map in an enhanced for loop. However, this will fail because java.util.Map itself does not implement the Iterable interface required for this usage. From this, you can determine that option B will not compile and is therefore incorrect.

Option C extracts a keySet from the Map, which gives you a set of the keys. A Set does implement the Iterable interface; therefore, you can use it in an enhanced for loop. The body of the loop extracts the matching value, adds that value to the key, and prints it. Again, you can see that this code might print 37. Hold on to this thought too. Option D iterates over a Set of Map.Entry objects. This is also valid and given that the code prints the sum of the key and the value each time through the loop, it also might print 37 to the console. Yes; hold this thought as well.

At this point, you might have noticed that options A, C, and D were described as might being able to print 37, but the question asks for a single answer. When you work on questions for an exam of this kind, it’s important to pick the correct number of options. In the Java exam software, if a question asks for a single answer, you will be presented with radio buttons, and it’s impossible to select more than one. This tells you to look a bit harder.

In fact, options A, C, and D are all incorrect, and they all have the same problem: The iteration of a Map in Java does not provide a predictable order. This means that you cannot be certain that the code will process the 1-2 pair first and the 3-4 pair second. Consequently, any of these three options might equally print 37 or 73. Because this does not satisfy the question’s query, you can see that option E is correct.

To make this official, the documentation for the unmodifiable maps produced by the Map.of() factory methods explains that “The iteration order of mappings is unspecified and is subject to change.”

As a final observation, it’s interesting that the TreeMap method sorts its keys. This can be done by the keys’ natural order or by using a supplied Comparator. If the question’s code used a map that guarantees order in that way, then options A, C, and D would be correct. To make this change, declare and initialize the Map using the following:

var m = new TreeMap<>(Map.of(1,2,3,4));

Finally, you should always assume exam-style questions are based on behavior that you can rely on, as specified in the documentation. If you test this question’s code using most reasonably recent versions of Java, you will find that options A, C, and D will print 37—but that’s luck. Professional-grade programmers don’t depend on luck!

Conclusion. The correct answer is option E.

Source: oracle.com

Monday, April 24, 2023

Curly Braces #10: The best way to measure Java developer productivity

Oracle Java, Java Prep, Java Tutorial and Materials, Java Guides, Java Learning, Java Certification, Java Learning

Hint: It’s not found by counting the number of lines of code written each day.


How do you measure programmer productivity? Some managers measure productivity by counting the number of software lines of code (usually abbreviated as either LoC or SLoC) written each day. I recall, decades ago, a friend’s father telling me his company required programmers to write at least five lines of code per day, on average. At the time, the figure seemed low, but the key is on average. As every professional programmer will explain, you don’t write code every day. You also participate in planning, meetings, testing, meetings, design, meetings, bug fixing, and meetings.

LoC is not considered to be the best measurement of programmer progress, and it’s certainly not an indication of quality. It’s even debatable what LoC is: Do you include comments? Most say no. Others feel that since it’s frowned upon to not document your code, comments should be counted. Andrew Binstock recently made a similar argument while discussing the value of comments in code.

What about lines that consist of only braces? What about if statements split with line feeds? Do you count switch statement conditionals? Perhaps you should, because, after all, good structure counts, right?

Then there are advancements in Java such as lambdas, where the goal is to reduce the amount of code needed to achieve something that required more code in the past. No developer should be penalized for using modern constructs to help write fewer lines of more-effective code, right?

There are times I marvel at how many lines of code I’ve written for whatever project I’m working on. Additionally, common sense says that as you learn a new programming language, the more code you write, the more proficient you get. Looking at it this way, using LoC for progress can be rationalized.

However, it’s hard to get past the fact that elegant code is often more concise—and easier to maintain—than poorly written brute-force code. You don’t want to incentivize developers to be overly verbose or inefficient to achieve a desirable LoC metric.

Bill Gates once said, “Measuring programming progress by lines of code is like measuring aircraft building progress by weight.” Indeed, I’ve worked with folks who have valued lines of code removed more than new lines of code added. The most rewarding tasks often involve improving a system design so much that multiple screens-worth of code can be removed.

Given this, here are a few alternatives that can measure programmer progress.

Problems solved


Even when the goal is to track developer productivity using actual numbers, developers often have ample opportunity to make a positive impression with their problem-solving skills. Effective problem-solving requires both thought and research. If you can consistently provide meaningful, and timely, solutions to even the thorniest of problems, management will know you’ve put the time and effort into being prepared.

On a developer team, a person who can solve tricky problems has as much value as someone else who cranks out lots of fast code that implements that solution. Yet who gets the credit? Often, it’s the coder, not the problem solver.

Another issue is that problem-solving can fall into the perception-beats-reality category. Some people are louder and bolder than others, some are good at building on the suggestions of others, and simply overhear solutions, to put it nicely.

A “problems solved” metric probably won’t fly.

Agile measurements


You know the value of Agile development practices. Regardless of whether it’s Scrum, Scaled Agile Framework (SAFe), Kanban, or Scrum at Scale, each method uses iterative development with feedback loops to measure developer progress and effectiveness for meeting user needs and providing business value. Each of these practices also measures progress in terms of completed user stories instead of LoC, using measurements such as the following:

◉ Burn-down charts. These track the development progress not only at the sprint level but also for epics and releases over a longer period. By setting the assignee to a specific developer, you can track individual developer progress compared to the team. There are all sorts of reasons an individual’s performance may vary, such as vacationing during a sprint, attending meetings, or working on special assignments. However, teams that use this metric typically couple it with an individual developer’s capacity (which considers vacation time, sick leave, and special assignments) against their assigned workload.

◉ Velocity. This is the average amount of work a Scrum team completes during a sprint, and it can be a good measure for a team. However, velocity can also be used to track individual productivity as long as you compare apples to apples. You also need to use consistent measurements such as story points or hours instead of simply stories closed.

◉ Software quality. This includes defect tracking charts such as those shown in Figure 1, which measures rates of defects per release, team, and developer. However, realize that more-productive developers may also generate more defects as they complete more stories in a given time frame compared to others. Therefore, leverage tools that track defects to stories over time, essentially turning the measurement into a percentage, to get a more accurate view.

Oracle Java, Java Prep, Java Tutorial and Materials, Java Guides, Java Learning, Java Certification, Java Learning
Figure 1. Software defect tracking chart

Also, bear in mind that rates of defects change over the lifetime of a project. Defects will ramp up early in the development cycle, and then they will plateau and drop off rapidly if they are fixed efficiently. I once had a manager who gained an accurate view of top performers on our development team not by measuring the number of defects but by tracking when the counts plateaued, how quickly the defects were resolved, and how often defects were reopened (indicating an ineffective fix was implemented).

In fact, user satisfaction, business value, and software quality are important measurements that counting LoC completely misses.

Customer and corporate satisfaction


Measuring software product success is a challenging metric, but it can be achieved. For example, you can measure sales, downloads, or user feedback to indicate how well the product satisfies the needs of its users. Measuring customer satisfaction assesses how well the software has met the requirements you originally defined. Then, by tracking the completion of individual features along with the developers who worked on them, you can get an accurate feel for how well individuals or entire development teams contributed to this satisfaction compared to others.

There are other soft measurements for developer productivity and effectiveness, such as the satisfaction of other developers and of the developer’s manager. Someone who is easy to work with yet average in terms of productivity and software quality will often be valued higher than someone who is above average yet hard to work with or just negative overall. This, once again, is a measurement that LoC will never tell you.

Hits of code


Borrowing from Gates’ statements on aircraft weight, there is an alternative measurement of programmer productivity that involves counting how many times a section of code has been modified. The theory is that the more you modify a body of code, the more effort is going into that part of the system. This is a measurement of hits of code (HoC) instead of lines of code, and I find this intriguing.

HoC, described nicely by Yegor Bugayenko in 2014, measures overall effort per developer for specific parts of the system being built or enhanced.

Beyond comparing the developer effort, HoC helps you gain an understanding of which parts of your system are getting the most attention—and then you can assess if that’s in line with what the business or customer needs. Further, you can measure the effort against your estimates to determine if you planned properly or if you need to assign more developers to work in an area with high HoC—both of which are reasons HoC could be a more valuable unit of measurement than LoC.

In his essay, Bugayenko shows how HoC is more objective than LoC and is more consistent, because it’s a number that always increases and takes the complexity of the codebase into account.

Whether it’s measuring HoC, using expanded Agile metrics, leveraging consistent soft-skills considerations, or valuing developers who have good ideas and problem-solving skills, there are many alternatives to measuring with LoC. Using even a small combination of these alternatives may finally slay the LoC-ness monster.

Source: oracle.com

Friday, April 21, 2023

Methods To Convert InputStream to String In Java

Oracle Java Certification, Oracle Java String, Java Prep, Java Preparation, Java Career, Java Skills, Java Jobs, Java

In Java, an InputStream is a common way to read data from a source, such as a file or network connection, in a stream-oriented way. Often times, it is necessary to convert an InputStream to a String to perform further processing on the data or to display it to the user.

1. What is InputStream


InputStream is an abstract class in Java that provides a common interface for reading data from different input sources, such as files, network connections, and other input streams. The primary purpose of InputStream is to provide a unified way to access input data regardless of its origin.

The InputStream class provides several methods for reading data from the input source, including read(), read(byte[]), and skip(). Subclasses of InputStream implement these methods to provide specific behavior for reading data from a particular type of input source.

Some common subclasses of InputStream in Java include FileInputStream (for reading data from a file), ByteArrayInputStream (for reading data from an in-memory byte array), and BufferedInputStream (for buffering input data to improve performance).

In general, an InputStream is used to read data from a source, while an OutputStream is used to write data to a destination. Together, they provide a powerful and flexible way to handle input/output operations in Java.

2. Methods For Converting an InputStream to a String in Java


Some of the most common methods for converting an InputStream to a String in Java include:

◉ Using a BufferedReader and StringBuilder: This method involves reading the data from the InputStream using a BufferedReader, which allows for efficient reading of character data, and appending the data to a StringBuilder to build the String. This method works well for text-based data and is relatively efficient.

Here’s an example:

public static String convertStreamToString(InputStream inputStream) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    return sb.toString();
}

In this example, we first create a BufferedReader to read the data from the InputStream, and a StringBuilder to accumulate the data into a String. We then read each line of the InputStream using the readLine() method of the BufferedReader, append it to the StringBuilder, and add a newline character for each line. Finally, we return the accumulated String by calling the toString() method of the StringBuilder.

◉ Using a Scanner and String: This method involves reading the data from the InputStream using a Scanner, which provides a high-level interface for reading data from a variety of sources, and then converting the data to a String using the String constructor. This method works well for simple text-based data and is easy to use.

Here’s an example:

public static String convertStreamToString(InputStream inputStream) {
    Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
    return scanner.hasNext() ? scanner.next() : "";
}

In this example, we create a Scanner to read the data from the InputStream. We use the useDelimiter() method to specify that we want to read all the data until the end of the stream is reached (\\A is a regular expression that matches the beginning of the input). We then read the data using the next() method of the Scanner and return it as a String.

◉ Using a ByteArrayOutputStream and String: This method involves reading the data from the InputStream into a byte array using a ByteArrayOutputStream, and then converting the byte array to a String using the String constructor. This method works well for binary data or data that does not have a specific character encoding.

Here’s an example:

public static String convertStreamToString(InputStream inputStream) throws IOException {
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) != -1) {
        result.write(buffer, 0, length);
    }
    return result.toString("UTF-8"); // replace "UTF-8" with the correct character encoding
}

In this example, we create a ByteArrayOutputStream to read the data from the InputStream and accumulate it into a byte array. We then read the data from the InputStream in chunks of 1024 bytes using a buffer, and write each chunk to the ByteArrayOutputStream. Finally, we convert the byte array to a String using the toString() method of the ByteArrayOutputStream, specifying the correct character encoding as a parameter.

3. What to Consider When Converting an InputStream to String


When converting an InputStream to a String in Java, there are a few things to consider:

1. Character encoding: InputStream is a stream of bytes, so it’s important to know the character encoding of the InputStream in order to properly convert it to a String. If the character encoding is not specified or known, the platform’s default character encoding will be used, which may not be what you expect. It’s a good practice to always specify the character encoding when converting an InputStream to a String.

2. Input size: If the InputStream is very large, it may not be practical to load the entire stream into memory and store it as a String. In this case, you might want to consider processing the stream in smaller chunks, or using a different data structure, such as a byte array or a database.

3. Performance: Different methods of converting an InputStream to a String have different performance characteristics. For example, using a BufferedReader and StringBuilder may be slower than using a ByteArrayOutputStream for large input streams, but may be faster for smaller input streams. It’s important to consider the performance requirements of your application when choosing a method for converting an InputStream to a String.

4. Error handling: It’s important to handle exceptions and errors that may occur during the conversion process, such as IOException and NullPointerException. You should also handle cases where the InputStream is null or empty.

By considering these factors, you can ensure that your code for converting an InputStream to a String is robust, efficient, and error-free.

Source: javacodegeeks.com

Thursday, April 20, 2023

Secrets To Landing Your First Job As A Oracle Java SE 8 Programmer

oracle certified associate java se 8 programmer exam questions, oracle certified associate java se 8 programmer, oracle certified associate java se 8 programmer syllabus, oracle certified associate java se 8 programmer dumps, java se 8 certification,

Java is a popular programming language that has been in use for over two decades. It has become one of the most popular programming languages in the world, powering applications and systems in various industries. Becoming an Oracle Certified Java SE 8 Programmer is a valuable investment for anyone seeking a career in the tech industry.

Java is a widely used programming language in the tech industry, and becoming a certified Java SE 8 programmer can be a game-changer for your career. Whether just beginning or looking to advance your skills, getting certified in Java SE 8 can help you stand out in a crowded job market and enhance your earning potential.

Career Growth Opportunities for Oracle Certified Java SE 8 Programmer

Becoming a certified Java SE 8 programmer can open up opportunities if you must advance your tech industry career. Java is one of the most popular programming languages in the world, and many companies are looking for skilled Java developers to help them build and maintain their software systems.

Here are some of the career growth opportunities available to Java SE 8 certified professionals:

1. Job Opportunities for Java SE 8 Programmer

A Java SE 8 certification can make you stand out to potential employers and increase your chances of landing a job. Many companies require their developers to have a Java certification, and having one can demonstrate your expertise and commitment to the field.

With a Java SE 8 certification, you can pursue a variety of job roles, such as:

  • Java Developer
  • Software Developer
  • Web Developer
  • Mobile Application Developer
  • Technical Lead
  • Software Architect

2. Salary Increases

Becoming a certified Java SE 8 programmer can also lead to salary increases. According to Payscale, the average salary for a Java developer with a Java SE 8 certification is around $92,134 annually in the United States.

Additionally, having a certification can demonstrate to employers that you have the skills and knowledge required to excel in your role, making you a more valuable asset to the company.

3. Advancement Opportunities

Once you have a Java SE 8 certification, you can continue to advance your career by pursuing more advanced certifications, such as the Java SE 8 Programmer II certification.

4. Entrepreneurial Opportunities

If you want to begin your own business, having a Java SE 8 certification can give you an edge in the tech industry. With your knowledge and expertise, you can develop your software systems or consult with other businesses to help them build and maintain their systems.

5. Continuous Learning

Becoming a certified Java SE 8 programmer is a one-time accomplishment and a continuous journey of learning and development. The tech industry constantly evolves, and staying up-to-date with the latest products and trends is essential to a successful career.

With a Java SE 8 certification, you can continue to learn and develop your skills by pursuing further education, attending conferences and workshops, and staying up-to-date with the latest developments in the industry.

The Future of Java SE 8 Programmer in the Job Market

Java is one of the most popular programming languages in the world, and it has been around for more than two decades. It is used in various applications, from mobile apps to web development to large-scale enterprise systems. But what does the future hold for Java programming in the job market?

1. High Demand for Java SE 8 Programmer

Java programming is expected to remain in high demand in the job market for the foreseeable future. Many companies continue to use Java for their software systems, and a large community of developers is skilled in the language.

Employment of software developers, including Java developers, is projected to grow 21 percent from 2019 to 2029, much faster than the average for all occupations. This growth is driven by the increasing use of software in nearly all industries and the need for developers to create and improve new applications.

2. Emergence of New Technologies

While Java programming is expected to remain in high demand, the job market is also likely to see the emergence of new technologies that could impact the industry. A growing interest in machine learning, artificial intelligence, and blockchain technologies could affect the job market for Java developers.

However, many of these new technologies are still in their early stages, and it is still being determined how they will impact the job market in the long term. Nonetheless, Java developers who stay up-to-date with the latest developments in the industry will be better positioned to adapt to new technologies and remain competitive in the job market.

3. Need for Skilled Developers

As the demand for Java developers continues to grow, the need for skilled developers also increases. Employers seek developers who understand the language and can create efficient and effective software systems.

This means that Java developers who can demonstrate their expertise and stay up-to-date with the latest developments in the industry will be in high demand. It is also essential for Java developers to continue to develop their soft skills, such as communication and teamwork, as these skills are becoming increasingly important in the tech industry.

4. Remote Work Opportunities

The COVID-19 pandemic has accelerated the remote work trend, and many tech companies are now offering remote work opportunities to their employees. This has opened up new opportunities for Java developers who may live in a different location than their employer.

Java programming is well-suited for remote work, as many Java projects are collaborative and can be worked on from anywhere with an internet connection. This means that Java developers who can work effectively remotely will have more opportunities to find work in the job market.

Conclusion

In conclusion, becoming a certified Java SE 8 programmer can open up a world of opportunities in the tech industry. From job opportunities to salary increases to advancement opportunities and even entrepreneurial opportunities, there are many ways in which a Java SE 8 certification can help you build a successful career.

Moreover, continuous learning and development are essential for staying relevant in the tech industry. Pursuing further education and staying up-to-date with the latest trends and products can help you maintain a successful career as a Java SE 8 certified professional.

Wednesday, April 19, 2023

Quiz yourself: Interface methods and assignment compatibility in Java

Quiz Yourself, Oracle Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Certified

What does it mean when a method has no modifiers—and a semicolon instead of a body?


Given these four Java types

package bot;
interface Command {
    String execute();
}

package bot;
public class Engine {
    public static void run(Command c) {
        System.out.println(c.execute());
    }
}

package bot;
import bot.command.AboutCommand;
public class Main {
    public static void main(String[] args) {
        AboutCommand ac = new AboutCommand();
        Engine.run(ac);
    }
}

package bot.command;
public class AboutCommand {
    String execute() {
        return "Chat Bot";
    }
}

What is the result? Choose one.

A. The code successfully compiles and prints Chat Bot.
B. The Command interface fails to compile.
C. The Engine class fails to compile.
D. The Main class fails to compile.
E. The AboutCommand class fails to compile.

Answer. This question investigates the accessibility of interface methods, interface implementation, and assignment compatibility. For this quiz question, look at each of the types that are declared and observe the key characteristics of the sample code.

Starting with the Command interface, notice that the type declaration has no modifier. This gives the interface package-level access, which means that it is accessible only within the bot package.

Next, the execute method is declared with no modifiers and has a semicolon in place of a body. This is valid, and if a method is declared this way in an interface, it will be implicitly public and abstract. From this you can determine that the interface is accessible and valid; therefore, option B is incorrect.

The Engine class is public, so it is accessible anywhere in the same module (or in the same JVM if the code is running without modules). The class declares a single method called run. This method is public, so it’s also accessible anywhere. The method is also static, so no instances of Engine need to be created to use the method. The method takes a single argument of type Command. The Engine class is in the same package as the Command interface, so it is accessible. The body of the run method simply calls the execute method of the Command argument. Command declares that the method, and the usage (the argument type sequence, which is empty), is valid. Because there is no reason for this code to fail, you can determine that option C is incorrect.

Notice that the AboutCommand class is in a different package from the Command interface. In addition, although it has the word Command in its name, this class does not contain the code implements Command. There are two immediate conclusions that can be drawn from this.

◉ Because AboutCommand doesn’t reference Command, it’s not a problem that it’s in a different package.
◉ While AboutCommand is not assignment-compatible with Command, this does not cause a problem here. (It does have consequences in other code, however.)

Also notice that the execute method in AboutCommand has package access and would not be a valid override of the execute method in Command. This isn’t a problem, however, since this method does not attempt such an override.

From these observations, you can see the AboutCommand class compiles successfully and option E is incorrect.

Finally, look at the Main class. It’s in the package bot, so it has access to the Command type. It imports the public type bot.command.AboutCommand, so it has access to that too. The main method has a valid signature line, and that signature is consistent with a program entry point. However, the body of the method has a problem. The argument type for the Engine.run method must be assignment-compatible with Command. However, as noted earlier, AboutCommand does not implement Command; therefore, it is not assignment-compatible with that type. That means the code Engine.run(ac); will fail to compile and option D is correct.

Because the Main class does not compile, option A must be incorrect.

Conclusion. The correct answer is option D.

Monday, April 17, 2023

What is JavaOne?

JavaOne, Oracle Java, Oracle Java Career, Oracle Java Skill, Oracle Java Job, Oracle Java Prep, Oracle Java Preparation, Oracle Java Tutorial and Materials

JavaOne is a technology conference held annually by Oracle Corporation for Java developers and enthusiasts. The conference provides an opportunity for Java developers to come together and learn about the latest Java technologies, tools, and best practices. In this article, we will explore the history, purpose, and highlights of JavaOne.

History of JavaOne


JavaOne started in 1996 as the Java Developer Conference (JDC), an independent event organized by JavaSoft, a subsidiary of Sun Microsystems. The event was renamed JavaOne in 1997 when Sun Microsystems took over the organization. JavaOne quickly became the premier event for Java developers, attracting thousands of attendees every year.

In 2010, Oracle Corporation acquired Sun Microsystems, and JavaOne became an Oracle-sponsored event. Oracle has continued to organize JavaOne since then, although the conference has undergone several changes over the years.

Purpose of JavaOne


The purpose of JavaOne is to provide a forum for Java developers to learn, network, and share their experiences. The conference offers a variety of technical sessions, hands-on labs, and keynote speeches on topics such as Java development tools, cloud computing, and mobile development. Attendees can also meet with Java experts and get their questions answered.

JavaOne is also a platform for Oracle to showcase its Java-related products and services. The conference provides an opportunity for Oracle to engage with its Java user community and gather feedback on its Java offerings.

Highlights of JavaOne


JavaOne has many highlights, including keynote speeches by industry leaders, technical sessions by Java experts, and product demos by Oracle and other companies. Some of the most notable highlights of JavaOne include:

Keynote speeches


JavaOne features keynote speeches by industry leaders, such as James Gosling (the creator of Java), Mark Reinhold (Chief Architect of the Java Platform), and Thomas Kurian (President of Product Development at Oracle). These speeches provide insights into the future of Java and the latest trends in software development.

Technical sessions


JavaOne offers a wide range of technical sessions, covering topics such as Java development tools, cloud computing, and mobile development. These sessions are presented by Java experts and provide attendees with in-depth knowledge and practical skills.

Hands-on labs


JavaOne also offers hands-on labs, where attendees can get hands-on experience with the latest Java technologies and tools. These labs are led by Java experts and provide attendees with practical skills that they can use in their own projects.

Product demos


JavaOne features product demos by Oracle and other companies, showcasing the latest Java-related products and services. These demos provide attendees with a first-hand look at the latest innovations in Java technology.

Conclusion


JavaOne is a premier technology conference for Java developers and enthusiasts. The conference provides a forum for learning, networking, and sharing experiences. With its keynote speeches, technical sessions, hands-on labs, and product demos, JavaOne offers a unique opportunity for Java developers to stay up-to-date with the latest Java technologies and best practices.

Friday, April 14, 2023

Bigtable Pagination in Java

Consider a set of rows stored in Bigtable table called “people”:

Oracle Java Prep, Oracle Java Preparation, Java Guides, Java Learning, Java Career, Java Jobs, Java Skills

My objective is to be able to paginate a few records at a time, say with each page containing 4 records:

Page 1:

Oracle Java Prep, Oracle Java Preparation, Java Guides, Java Learning, Java Career, Java Jobs, Java Skills

Page 2:

Oracle Java Prep, Oracle Java Preparation, Java Guides, Java Learning, Java Career, Java Jobs, Java Skills

Page 3:

Oracle Java Prep, Oracle Java Preparation, Java Guides, Java Learning, Java Career, Java Jobs, Java Skills

High-Level Approach


A high level approach to doing this is to introduce two parameters:

◉ Offset — the point from which to retrieve the records.
◉ Limit — the number of records to retrieve per page

Limit in all cases is 4 in my example. Offset provides some way to indicate where to retrieve the next set of records from. Bigtable orders the record lexicographically using the key of each row, so one way to indicate offset is by using the key of the last record on a page. Given this, and using a marker offset of empty string for the first page, offset and record for each page looks like this:

Page 1 — offset: “”, limit: 4

Oracle Java Prep, Oracle Java Preparation, Java Guides, Java Learning, Java Career, Java Jobs, Java Skills

Page 2 — offset: “person#id-004”, limit: 4

Oracle Java Prep, Oracle Java Preparation, Java Guides, Java Learning, Java Career, Java Jobs, Java Skills

Page 3 — offset: “person#id-008”, limit: 4

Oracle Java Prep, Oracle Java Preparation, Java Guides, Java Learning, Java Career, Java Jobs, Java Skills

The challenge now is in figuring out how to retrieve a set of records given a prefix, an offset, and a limit.

Retrieving records given a prefix, offset, limit


Bigtable java client provides a “readRows” api, that takes in a Query and returns a list of rows.

import com.google.cloud.bigtable.data.v2.BigtableDataClient
import com.google.cloud.bigtable.data.v2.models.Query
import com.google.cloud.bigtable.data.v2.models.Row
 
val rows: List<Row> = bigtableDataClient.readRows(query).toList()

Now, Query has a variant that takes in a prefix and returns rows matching the prefix:

import com.google.cloud.bigtable.data.v2.BigtableDataClient
import com.google.cloud.bigtable.data.v2.models.Query
import com.google.cloud.bigtable.data.v2.models.Row
 
val query: Query = Query.create("people").limit(limit).prefix(keyPrefix)
val rows: List<Row> = bigtableDataClient.readRows(query).toList()

This works for the first page, however, for subsequent pages, the offset needs to be accounted for.

A way to get this to work is to use a Query that takes in a range:

import com.google.cloud.bigtable.data.v2.BigtableDataClient
import com.google.cloud.bigtable.data.v2.models.Query
import com.google.cloud.bigtable.data.v2.models.Row
import com.google.cloud.bigtable.data.v2.models.Range
 
val range: Range.ByteStringRange = 
    Range.ByteStringRange
        .unbounded()
        .startOpen(offset)
        .endOpen(end)
 
val query: Query = Query.create("people")
                    .limit(limit)
                    .range(range)

The problem with this is to figure out what the end of the range should be. This is where a neat utility that the Bigtable Java library provides comes in. This utility given a prefix of “abc”, calculates the end of the range to be “abd”

import com.google.cloud.bigtable.data.v2.models.Range
 
val range = Range.ByteStringRange.prefix("abc")

Putting this all together, a query that fetches paginated rows at an offset looks like this:

val query: Query =
    Query.create("people")
        .limit(limit)
        .range(Range.ByteStringRange
            .prefix(keyPrefix)
            .startOpen(offset))
 
val rows: List<Row> = bigtableDataClient.readRows(query).toList()

When returning the result, the final key needs to be returned so that it can be used as the offset for the next page, this can be done in Kotlin by having the following type:

data class Page<T>(val data; List<T>, val nextOffset: String)

Source: javacodegeeks.com

Wednesday, April 12, 2023

Quiz yourself: Using the stream methods dropWhile and takeWhile in Java

Quiz Yourself, Oracle Java Certification, Oracle Java Tutorial and Materials, Java Guides, Java Learning, Java Skills, Java Jobs


Given the following method fragment

Collection<Integer> c = Set.of(1,2,3,4,5,6,7); // line 1
var r = c.stream()
  .dropWhile(e -> e < 5)
  .takeWhile(e -> e < 7)
  .count(); // line 2
System.out.println(r);

Which statement is correct? Choose one.

A. Line 1 will cause an error.

B. Replacing the second statement with the following code would produce the same output:

var r = c.stream()
   .takeWhile(e -> e < 7)
   .dropWhile(e -> e < 5)
   .count(); // line 2

C. Replacing the second statement with the following code would produce the same output:

var r = c.stream()
  .filter(e -> !(e < 5))
  .filter(e -> e < 7)
  .count(); // line 2

D. The code may print 0.

E. The code may print 7.

F.     The code always prints 2.

Answer. This question explores some foundational concepts for collections and streams and, in particular, the Stream API’s dropWhile and takeWhile methods. These methods were added in Java 9 and are legitimate territory for the Java 11 and Java 17 exams.

Consider the behavior of the dropWhile and takeWhile methods. Both take a single argument of type Predicate and both methods are intermediate operations that return a new stream.

The dropWhile method, when applied to an ordered stream, starts at the beginning of the stream and tests, in order, data items of the stream it’s reading from. If elements pass the test, they are dropped. So far, this behavior seems similar to that of the filter method, except the behavior removes items that pass the test rather than keeping items that pass the test. However, as soon as an item fails the test, dropWhile becomes a simple pass-through, and all subsequent items will continue down the stream without being tested. The documentation describes this as “dropping the longest prefix of elements.”

Therefore, if an ordered stream contains the following (with the parade of items progressing towards the right, so that 1 is the head of the stream)

10 9 8 7 6 5 4 3 2 1

and you apply dropWhile(e -> e < 5), the output of the dropWhile will be a stream such as the following

10 9 8 7 6 5

If you apply the same dropWhile to this sequence

10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1

the result will be a stream such as the following

10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5

Notice that the result still contains the second occurrences of 1 through 4 (and if more of these occurred later, they too would be present in the result).

The behavior of the takeWhile operation has parallels to this, except that the resulting stream ends as soon as any item in the stream fails the test specified in the predicate. So, if you start with this stream

10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1

and apply takeWhile(e -> e < 7) to it, the result is a stream like the following

6 5 4 3 2 1

Therefore, if you chain the dropWhile(e -> e < 5) and takeWhile(e -> e < 7) operations, and apply them to an ordered stream that looks like the following

7 6 5 4 3 2 1

the dropWhile(e -> e < 5) would yield

7 6 5

and then the takeWhile(e -> e < 7) would operate on that stream and produce

6 5

If you then count the elements, you’d get the value 2.

This is all very nice, except for two problems. First, the order of items drawn from most Set objects is not guaranteed and typically does not match the order in which the items were added to the set. The second problem is you don’t have an ordered stream and as mentioned, the discussion above applies only to ordered streams.

Consider why these two things are true. A set, from a math perspective, has the task of rejecting duplicate elements, but it does not have the task of maintaining user-defined order. (Note that some of Java’s Set implementations do maintain user-defined order, for example, the TreeSet. But the order in this case still isn’t the order in which items were added; it’s literally an ordering that applies to the elements.) The documentation for the Set interface describes the effect of Set.of and Set.copyOf with the following caveat:

The iteration order of set elements is unspecified and is subject to change.

Shortly, you’ll see why this is critical and contradicts the discussion above.

Some stream objects are considered to be ordered and others are not. If you have a source of data that has a meaningful (user-controllable) order, such as the elements of a List or the computations of Stream.iterate (which calculates the next element of a stream from the predecessor), the stream starts out ordered.

Meanwhile, the documentation for dropWhile states

If this stream is unordered, and some (but not all) elements of this stream match the given predicate, then the behavior of this operation is nondeterministic; it is free to drop any subset of matching elements (which includes the empty set).

The documentation for takeWhile has an equivalent statement.

In this quiz question, you have an unordered stream; therefore, you have no basis for making reliable predictions about what it will do. (If you try this code, it will behave consistently, but “It always works for me!” is not a sound way to create production quality code. You must be able to guarantee that it will still work when implementations change, and for that, you must take seriously the limitations called out in the documentation.)

If you don’t even know that this code will behave consistently, you cannot claim to have other code that will behave the same way, nor can you assert that it will always do anything in particular. For this reason, options B, C, and F are all incorrect.

This leaves you to consider whether line 1 compiles, and if so, what the code might possibly output.

Option A claims the code will not compile. There are three ways that might seem like a tempting option.

◉ Can you put primitives into the argument for Set.of? Yes, you can because they will be autoboxed to Integer type. Further, this is consistent with the variable type (Collection<Integer>) to which the result is assigned.

◉ The assignment of the Set.of<Integer> created the variable of type Collection<Integer>. This succeeds because Set is a subinterface of Collection, and the generic types are both Integer.

◉ There would be an exception at runtime if you call Set.of with duplicate values in the argument list. In this case, the arguments are all distinct, so there’s no problem.

From this you know that there are no errors, and option A is also incorrect.

Option D is correct. The documentation for takeWhile working on an unordered stream states “…it is free to take any subset of matching elements (which includes the empty set).” Therefore, it clearly is permissible for the operation to result in zero surviving elements, which would produce a count of 0.

If you ignore the restrictions of dropWhile and takeWhile and simply consider that you don’t know the iteration order of the elements taken from Set.of, you can still see how unexpected results might be achieved. Imagine that the stream elements from the set arrive in the following order:

6 5 4 3 2 1 7

In this case, the dropWhile(e -> e < 5) part will be false on the first element, and none of the elements will be dropped. After that, the takeWhile(e -> e < 7) part will also be false on the first element (which is still 7). Therefore, zero elements will proceed downstream to the count() operation, and therefore 0 would be printed. Because 7 can’t be printed, you can see that option E is incorrect.

Conclusion. The correct answer is option D.

Source: oracle.com

Friday, April 7, 2023

Quiz yourself: String manipulation and local and instance variables


Imagine that your colleague from the IT department is working on a new chatbot application implementing—among some others—the Command design pattern. The bot’s command objects are created once upon startup and reused through the life of the application. Below is the partial code of the application, in particular, the AboutCommand interface, which must return the text Copyright (c) 2023, http://mycompany.com.

Quiz Yourself, String Manipulation, Local Instance Variables, Oracle Java Tutorial and Materials, Java Career, Java Skills, Java Jobs, Java Certification, Java String, Oracle Java Tutorial and Materials

public interface Command {
  String execute(Context c);
}
public class AboutCommand implements Command {
  private String url;
  public AboutCommand(String s) {
    url = s;
  }
  public String execute(Context c) {
    url = url.substring(0, url.lastIndexOf("/")); // line 2
    url = url.substring(0, url.lastIndexOf("/")); // line 3
    return "Copyright (c) 2023, " + url; // line 4
  }
}
public class ChatBot {
  public static final String HOME_PAGE = "http://mycompany.com/botapp/index.html";
  private final Command about;
  ChatBot() {
    about = new AboutCommand(HOME_PAGE);
    … // create some more commands
  }
}

Which statement is correct? Choose one.

A. The code is compilable and works as expected.

B. The code is not compilable. To fix the code, the final modifier on the variable HOME_PAGE must be removed.

C. The code is incorrect. To fix it, modify lines 2 and 3 like this:
url.substring(0, url.lastIndexOf("/")); // line 2
url.substring(0, url.lastIndexOf("/")); // line 3

D. The code is incorrect. To fix it, modify lines 2 and 3 like this:
var url = this.url.substring(0, this.url.lastIndexOf("/")); // line 2
url = this.url.substring(0, this.url.lastIndexOf("/")); // line 3

E. The code is incorrect. To fix it, modify lines 2 and 3 like this:
var url = this.url.substring(0, this.url.lastIndexOf("/")); // line 2
url = url.substring(0, url.lastIndexOf("/")); // line 3

Answer. This question investigates aspects of string manipulation, local and instance variables, and logical thinking.

To begin with, option A is incorrect. While the first call of the execute() method will return the required text, the method has side effects. Specifically, it modifies the instance variable. Therefore, a second call will return only Copyright (c) 2023, http:. A third call will throw java.lang.StringIndexOutOfBoundsException.

To correct this, you could either recalculate the message each time without changing the value of the field named url, or you could calculate the message once and store the result for future use. The latter would be more efficient. Let’s investigate the other options to see if any achieve this result.

Option B is incorrect and entirely irrelevant to the problem you have. At no point does any of the code shown in the question attempt to reassign the HOME_PAGE constant, so the final modifier cannot be the cause of any problems.

Option C is also incorrect. It avoids reassigning the url field, which seems like a step forward. However, strings are immutable, so line 4 will return the initial unchanged value. Line 2 will create a new string containing the text http://mycompany.com/botapp, but that string is immediately abandoned because the reference to it (which is carried as the return value of the lastIndexOf method) is not stored anywhere. Line 3 simply repeats the process, and the new string is abandoned again. Therefore, the result will be Copyright (c) 2023, http://mycompany.com/botapp/index.html.

Quiz Yourself, String Manipulation, Local Instance Variables, Oracle Java Tutorial and Materials, Java Career, Java Skills, Java Jobs, Java Certification, Java String, Oracle Java Tutorial and Materials
In addition, option D is incorrect. It introduces a new local variable, String url. Line 2 creates a new string (as in option C) by removing the /index.html part from the original text. This new string is stored in the local variable called url. However, line 3 simply repeats the behavior of line 2, because it reads its starting value from the field called url, not the value created by line 2. Consequently, this version produces the message Copyright (c) 2023, http://mycompany.com/botapp.

Option E is correct. Lines 2 and 3 both store the result of their operations, and line 3 uses the result of line 2 as its starting point. As a result, the code cuts off two elements from the url: /index.html first and then /botapp. Critically, this code does not modify the instance variable, so each subsequent run of the execute() method will return the desired text: Copyright (c) 2023, http://mycompany.com.

To be clear, this is not an efficient approach to coding this problem. It would be better to calculate the result once and store it for reuse. The following code, used as a constructor for the AboutCommand class, would achieve that:

public AboutCommand(String s) {
  url = s.substring(0, s.lastIndexOf("/"));
  url = url.substring(0, url.lastIndexOf("/"));
  url = "Copyright (c) 2023, " + url;
}

Given this initialization, the execute method would simply look like the following:

public String execute(Context c) {
  return url;
}

There’s a final note to mention here. Were you wondering about that constructor argument Context c? In quiz questions, you should assume that there’s enough code surrounding what’s shown, or enough context, to allow the code to work if it can work. If there’s a problem you are expected to recognize, it’ll be in the code you are shown, not in something that’s not shown.

The Java 17 exam objectives include some notes about the assumptions of this kind that you are expected to make. The notes are present for the Java 8 exam too, but for some reason, possibly simple oversight, they weren’t included for the Java 11 version.

Conclusion. The correct answer is option E.

Source: oracle.com

Wednesday, April 5, 2023

What is Oracle Java SE? Understanding the Most Popular Programming Language

Oracle Java SE, Oracle Java Tutorial and Materials, Java Certification, Java Career, Java Skills, Java Jobs

Java is one of the most popular programming languages in the world, and for good reason. It is a versatile and efficient language that can be used to create applications, games, and even entire operating systems. In this article, we will explore Oracle Java SE, the latest version of Java, and what it can do.

What is Java?


Java is an object-oriented programming language that was developed in the mid-1990s by Sun Microsystems, which was later acquired by Oracle Corporation. Java is widely used to create web applications, mobile applications, and enterprise software. It is also used in the creation of games and other interactive content. Java is platform-independent, which means that it can run on any operating system that has a Java Virtual Machine (JVM) installed.

What is Oracle Java SE?


Oracle Java SE is the latest version of Java that is offered by Oracle Corporation. It is a comprehensive development kit that includes everything needed to develop and run Java applications. Oracle Java SE includes a compiler, a runtime environment, and a set of libraries that are used to create Java applications. The current version of Oracle Java SE is version 17.

What are the features of Oracle Java SE?


Oracle Java SE includes a wide range of features that make it a powerful and versatile programming language. Some of the key features of Oracle Java SE include:

Object-oriented programming

Java is an object-oriented programming language, which means that it is designed around objects and their interactions. This makes it easy to create complex applications and systems that are modular and easy to maintain.

Garbage collection

Java includes a garbage collector that automatically frees up memory that is no longer being used. This makes it easier to write applications that are memory-efficient and reduces the risk of memory leaks.

Exception handling

Java includes a robust exception handling mechanism that makes it easy to handle errors and unexpected events. This helps to make Java applications more robust and reliable.

Multithreading

Java supports multithreading, which means that it is possible to create applications that can perform multiple tasks simultaneously. This makes it possible to create applications that are more responsive and efficient.

Security

Java includes a number of security features that help to make it a safe and secure programming language. For example, Java applets run in a sandboxed environment that prevents them from accessing resources on the user's computer.

How is Oracle Java SE used?


Oracle Java SE is used in a wide range of applications and systems. It is commonly used to develop enterprise applications, web applications, mobile applications, and games. Java is also used in the development of Android applications, which makes it one of the most widely used programming languages in the world.

How do I get started with Oracle Java SE?


To get started with Oracle Java SE, you will need to download and install the Java Development Kit (JDK). The JDK includes everything you need to start developing Java applications, including the Java compiler and runtime environment. Once you have installed the JDK, you can use an integrated development environment (IDE) such as Eclipse or NetBeans to start writing Java code.

What are the advantages of using Oracle Java SE?


There are many advantages to using Oracle Java SE for software development. Some of the key advantages include:

Portability

Java is a platform-independent programming language, which means that Java applications can run on any operating system that has a Java Virtual Machine (JVM) installed. This makes it easy to develop applications that can run on multiple platforms.

Robustness

Java includes a number of features that make it a robust and reliable programming language. For example, the exception handling mechanism makes it easy to handle errors and unexpected events, while the garbage collector helps to prevent memory leaks.

Security

Java includes a number of built-in security features that make it a safe and secure programming language. Java applets, for example, run in a sandboxed environment that prevents them from accessing resources on the user's computer without their explicit permission. This helps to protect users from potential security threats, such as malware and viruses.

Large community and resources

Java has a large and active community of developers and users, which means that there are many resources available for learning and development. There are numerous online communities, forums, and blogs where developers can get help with their code and stay up to date on the latest developments in the Java ecosystem. Additionally, there are many libraries and frameworks available that can help speed up the development process and make it easier to build high-quality applications.

High demand and job opportunities

Java is one of the most widely used programming languages in the world, which means that there is a high demand for developers with Java skills. This translates into a wide range of job opportunities and career paths for developers who are skilled in Java. From web development and enterprise software to mobile app development and gaming, there are many different industries and applications where Java is used.

Conclusion


In conclusion, Oracle Java SE is a powerful and versatile programming language that is widely used in software development. With its object-oriented design, garbage collection, exception handling, multithreading, and security features, Java is a reliable and efficient language that can be used to create a wide range of applications and systems. For developers who are interested in learning Java, there are many resources available, including online communities, forums, and blogs. And with its high demand and job opportunities, Java is a great language for developers who want to build a career in software development.