Friday, December 9, 2022

Quiz yourself: Defining the structure of a Java class

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

Test your knowledge of Java classes, such as their valid names, the use of variables inside a method, and the number of allowable import statements.

Which of the following statements are correct about a Java class? Choose two.

A. A Java class must have a name shown in the source code.
B. A Java class may have several local variables with the same name inside the same method.
C. A Java class may have several import statements.
D. An underscore character “_” is a valid Java class name.

Answer. Not all classes have an explicit name shown in the source code. For example, Java provides anonymous classes, such as the following:

Runnable r = new Runnable(){ public void run(){
  System.out.print("Do nothing!");
  }
};
r.run();

The run method of the Runnable interface is abstract, and yet you can see that there is a real object because you instantiated it and can invoke the run method. This shows that some concrete class, which implements the Runnable interface, exists. The variable r is a reference to an instance of that class, but the class name is not known in the source code. Therefore, option A is incorrect.

Variables are visible only within the scope in which they were defined. However, since a block bounded by curly braces defines a scope, you can create two sibling scopes inside one method. If you do this, two variables with the same name can coexist without a problem, such as in the following:

void twoVars() {
  { int i = 0; }
  { int i = 1; } // OK
}

In view of this, option B is correct.

Option C discusses multiple import statements. Having multiple import statements is not merely permitted—in most cases, it’s necessary to have many import statements to provide access to classes in different packages. It’s also typical to have multiple import statements providing access to each of several classes in the same package, rather than using wildcards.

Even repeating import statements for the same class or package is syntactically valid, though it would probably trigger a request during code review to tidy up the code.

The following is completely legal:

import java.util.*;
import java.util.*;

public class MyClass { // OK
}

By the way, if a class defines more than one package statement—whether specifying the same package name or a different package name—compilation would fail. Thus, the following would not compile:

package a.b.c;
package a.b.c; // NOT OK

public class MyClass {
}

Because option C asks only if multiple import statements are permitted, option C is correct.

As for option D, through Java 8 the single underscore character was a valid identifier and could be used as a class name, a method name, or a variable name.

In Java 8, a warning during compilation indicated that this character was reserved for future language changes. However, the warning did not prevent its use. But then, beginning with Java 9, the single underscore character was defined as a keyword and therefore is no longer valid as an identifier.

This change was described in the Java 9 summary of changes, which stated that the underscore character was not a legal name and warned that if you use the underscore character (_) as an identifier, your source code cannot be compiled.

By the way, it is still legal to use a double underscore (__) as an identifier, such as for a class name, a method name, or a variable name. You can also start a variable name with a single underscore.

public class MyClass {
    int __; // Double underscore is OK
}

Because the single underscore is a keyword and is not a legal identifier on its own any longer, option D is incorrect.

Conclusion. The correct answers are options B and C.

Source: oracle.com

Wednesday, December 7, 2022

Quiz yourself: Acceptable and unacceptable types for Java switch statements


Core Java, Oracle Java, Java Exam Prep, Java Certification, Java Tutorial and Materials, Java Quiz, Java Guides

Which switch expressions will compile successfully? Choose two.

A. var s = 1L;
switch (s) {
  case 1: {}
  default: {}
}

b. var s = 0;
switch (s>0) {
  case true: {}
  case false : {}
}

C. var s = Integer.MAX_VALUE;
switch (s+1) {
  case 0: case 1: {}; break;
  case 2: case 3, 4: {}
  case Integer.MAX_VALUE, Integer.MIN_VALUE : {}
}

D. var s = 's';
final var a = 0;
switch (s) {
  default: {break;}
  case a: {}
  case 'a': {}
}

Answer. A switch statement works with the following primitive types and their wrappers:

☉ byte
☉ short
☉ char
☉ int

In addition, you are allowed to switch on an enum or String (since Java 5). However, Boolean, long, float, and double types are prohibited. Given that a local variable declared using var takes its type from the right side of the assignment, option A attempts to switch on a long value. This is not permitted, and option A is incorrect.

As a side note, there’s a preview feature in Java 17 and Java 18 that expands the syntax, behavior, and acceptable argument types for switch significantly. Notably, you will be permitted to switch on arbitrary object types; however, at the time of writing, even though it’s permitted to switch on a wrapper such as a Double or Boolean, it remains prohibited to switch on the corresponding primitive types, and autoboxing happens. (Of course, this describes a preview feature that’s not relevant for the Java 17 exam, and it’s possible the details will change before the final release.)

In view of the previous discussion, option B—which attempts to switch on an expression of the Boolean primitive type—is also incorrect.

In option C, the switch type is presented as an Integer. This is acceptable; autounboxing will result in it being treated as an int. The arithmetic operation that adds one to the max value (2,147,483,647) will cause an overflow to the most negative value (-2,147,483,648), which is Integer.MIN_VALUE. However, that overflow does not throw an exception. Also, the question asks only if the code will compile, which it will, not if the programming logic is sound. From this, you can see option C is correct.

Option D is tricky, and two aspects demand attention.

First, one of the case expressions is a variable (specifically the int variable named a). If you ignore the preview features, Java requires that the case keyword must be followed by a constant expression, and most variables are not acceptable. However, in this example, closer inspection shows that a is, in fact, a constant expression because it’s declared as final. So, the code is acceptable from this perspective.

The second point is that you have executed the switch statement using an expression of char type, but the case expression for case a is an int. However, this is not a problem because the value of the expression a fits in the range of the char type (which is from 0 to 65,535) and the type of a is not long, float, or double—any of which would cause failure, even if they were constant expressions with a value in the acceptable range. Therefore, in this case, the expression is acceptable and option D compiles without errors. Therefore, option D is correct.

Conclusion. The correct answers are options C and D.

Source: oracle.com

Friday, December 2, 2022

Quiz yourself: What you can and can’t do with Java records

Java records are implicitly final. What does that mean in practice?


What can you declare in the body block of a Java record? Choose two.

Oracle Java, Java Exam, Java Prep, Java Preparation, Java Tutorial and Mateirals, Java Gudies, Java Materials

A. An instance variable
B. An instance method
C. An instance initialization block
D. A no-argument constructor

Answer. One of the goals of records is to approximate immutable data-carrier types. To this end, all the data elements of a record are implicitly final. Note that the record does not prevent mutation of a mutable object referred to through a final reference, however; therefore a record only approximates an immutable data carrier.

Option A is incorrect: You may not declare your instance variables in the body of a record. An example of the record syntax looks like the following:

record Car(int seats, String color) {}

Given this code, execution of new Car(5, "Red") results in an immutable object that has storage for an int value named seats and a String reference value named color. You might observe that the elements named seats and color are fields, which are commonly called instance variables.

However, for two reasons, option A is not a correct answer to this exam question. First, and most importantly, those fields are not declared in the body block of the record. Instead, they are outside the curly braces. The second, weaker, objection is that of nomenclature. Although reflection reports these as private final fields if you invoke getDeclaredFields on the Car.class object, the Java Language Specification does not refer to them this way. Rather it considers these fields to be record components.

Note that although you cannot declare instance fields in a record using the syntax used for a class, you can define class variables (that is, static variables) in a Java record.

Option B is correct: You can declare custom instance methods in a record. The record type automatically creates accessor methods for the record components, but it’s possible to define these explicitly if desired.

It’s also possible to replace the implementations of other autogenerated methods such as equals(Object o) and hashCode().

Beyond that, you can define arbitrary methods (both instance and static) according to your needs. Further, you can declare nested classes, interfaces, and other records inside a Java record.

Option C is incorrect: A record may not have an instance initialization block, but it does provide a somewhat related syntax known as a compact constructor. The compact constructor lets you interact with the initialization values prior to their being assigned to their final storage locations.

The compact constructor can also throw an exception if the construction is to be rejected.

Notably, the compact constructor cannot assign values to the final storage locations for the record components—that must be done by autogenerated code that is invoked after the compact constructor.

Option D is correct: You may declare your own constructors. A constructor with an argument type sequence matching the type sequence of the record components is called the canonical constructor. The canonical constructor is not usually coded explicitly, and if it isn’t, it will be generated automatically. The canonical constructor must assign values to the record components.

Constructors with other argument type sequences must delegate, using the this(...) delegation mechanism, in such a way that they ultimately call the canonical constructor. Since the canonical constructor must assign the record component values, noncanonical constructors cannot do this, since that would constitute multiple assignments to a final variable.

In other words, the first line of any noncanonical constructor must be an invocation of this(...), and the last element in the resulting chain must invoke the canonical constructor, as follows:

Copy code snippet
Copied to ClipboardError: Could not CopyCopied to ClipboardError: Could not Copy
record Time(int hrs, int min) {
    Time() {        // no-arg, noncanonical constructor
        this(0);    // delegates to the constructor below
    }
    Time(int hrs) { // another noncanonical constructor
                    // delegates to the autogenerated canonical constructor
        this(hrs, 0);
    }
}

Conclusion. The correct answers are options B and D.

Source: oracle.com

Wednesday, November 30, 2022

How to Perform Right-Click using Java in Selenium?

While automating a website for testing there is always required to perform some right-click or other user actions on the page.  These user actions are one of the most commonly used actions during automation, so selenium provides a way to perform these user actions by the Actions class.

How to Perform Right Click using Actions Class


When a user performs a right click using the mouse on a particular element to perform some actions is called a right click. We are daily using this user action mostly on File Explorer, For example, to rename a file or delete a file we perform right-click and select an option.

Oracle Java Certification, Oracle Java Prep, Java Tutorial and Materials, Oracle Java Material, Oracle Java Selenium

Right Click in Selenium


Let’s see how to perform the right click using Selenium. Selenium Webdriver API does not support the user’s actions like Mouse hover, right-click, context-click, and double-click. That is where the Actions class came to use, The actions provided by this class are performed by an API called Advanced user interaction in selenium webdriver.

Action class present in the package,

“org.openqa.selenium.interactions package”

Let’s see how to use the Actions class to Right Click an element:

Instantiate an object for the Actions class 

Actions action = new Actions(driver);

After creating the object we have to locate the web element

WebElement element=driver.findElement(locator);

Using the “ContextClick() method” from the Actions class to perform the Right click. Context Click methods navigate the mouse pointer to the middle of the web Element and then perform the right-click action in that web element.

action.contextClick(webElement).perform();

Example


In this example, we are navigating to the URL “https://demoqa.com/buttons” and performing the Right click on the “Right click” button. 

public class Java {

public void oraclejavacertified()
{

ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://demoqa.com/buttons");
WebElement element
= driver.findElement(By.id("rightClickBtn"));
Actions action = new Actions(driver);
action.contextClick(element).perform();

Thread.sleep(5000);
driver.close();
}

Code Explanation


Initially, we opened the browser and navigated to the URL

ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(“https://demoqa.com/buttons”);

After that, we locate the web element where we have to perform the “Right Click”. Then, We initialize the Action class and performed “Right click” on the web element.

 Actions action=new Actions(driver);
 action.contextClick(element).perform();

Output

    
Right-click is performed and the result will be displayed.

Oracle Java Certification, Oracle Java Prep, Java Tutorial and Materials, Oracle Java Material, Oracle Java Selenium

Source: geeksforgeeks.org

Monday, November 28, 2022

Java Modules – Service Interface Module

Java Modules, Oracle Java, Oracle Java Career, Java Skill, Java Jobs, Java Tutorial and Material, Java Certification, Java Interface

Service Provider Interface, a feature of Java 6, makes it possible to find and load implementations that adhere to a specified interface. In this article, we’ll introduce Java SPI’s components and demonstrate how to use it in a real-world scenario. a well-known collection of programming classes and interfaces that give users access to a particular feature or functionality of an application. Applications are now more extendable thanks to the introduction of the Service Provider Interface. It provides us with a way to improve particular product features without changing the main application. All we have to do is plug in a new implementation of the service that adheres to the established requirements. The program will load the new performance and use it by means of the SPI protocol.


◉ Service Provider Interface: Service Provider Interface is referred to as SPI. It is a subset of everything that may be API-specific in circumstances where a library offers classes that an application (or API library) calls and that typically alter what the application is able to do.

◉ Service Provider: A particular service implementation is referred to as a “provider” as well. By putting the provider configuration file in the resources directory META-INF/services, it can be located. It must be accessible through the classpath of the application.

◉ ServiceLoader: A class that implements the well-known interface or subclasses it is referred to as a service provider (or simply a provider). When an application chooses, a ServiceLoader is an object that finds and loads service providers deployed in the run time environment.

A particular application of the SPI. One or more concrete classes that implement or extend the service type are present in the service provider. A provider configuration file that we place in the resource directory META-INF/services allows us to configure and identify a service provider. The fully-qualified name of the SPI is contained in both the file name and its content, which is the name of the SPI implementation. The Service Provider is installed using extensions, a jar file that is added to the application classpath, the classpath for Java extensions, or a custom classpath. 

Now Let’s see the Example.

Example


In this example, we will implement a service interface module in java using the classic classics library module. this program implementation will have access to the getBook() method.

<!-- We're including all the
dependencies here in this program -->
<dependency>
<groupId>org.library</groupId>
<artifactId>library-service-provider</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>

Then we will create a class that will implement the SPI library.

package org.library;

// Inheriting the class
public class ClassicsLibrary implements Library {

public static final String Classic_Library
= "Classic_Example";
private final Map<String, Book> books;

// ClassicsLibrary() method declaration
public ClassicsLibrary()
{
books = new TreeMap<>();
Book Example_1
= new Book("It's 2022", "Mr. Sinha", "Des");
Book Example_2 = new Book("It's EG2 book Name",
"Mis Sinha", "Des");

books.put("It's 2022", Example_1);
books.put("It's EG2 book Name", Example_2);
}

@Override public String getCategory()
{
return Classic_Library;
}

@Override public Book getBook(String name)
{
return books.get(name);
}
}

It should be evident how to use the Java SPI to develop readily expandable or replacement modules now that we have investigated the mechanism through a set of stated steps. Although the Yahoo exchange rate service was used in our example to demonstrate the capability of connecting to other external APIs, production systems don’t need to rely on third-party APIs to develop fantastic SPI applications.

Source: geeksforgeeks.org

Wednesday, November 23, 2022

Quiz yourself: If/else statements, boolean operations, and side effects

Quiz yourself, Oracle Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Guides, Java Guides


Given the NineOneOne class

public class NineOneOne {
    static boolean emergency;
    public static void main(String[] args) {
        if (!emergency());
            say1(); // line n1
            if (emergency());
        else if(emergency())
            say2();
    }
    static boolean emergency() {
        return emergency ^= true;
    }
    static void say1() {
        System.out.print("say1 ");
    }
    static void say2() {
        System.out.print("say2 ");
    }
}

What is the outcome if you try to compile and run the code? Choose one.

A. There is a compilation error due to unreachable code at line n1.
B. Compilation succeeds and there is no output.
C. say1
D. say2
E. say1 say2

Answer. This question addresses several aspects. The primary one is perhaps attention to detail, which of course can be a particularly critical skill in debugging code that you did not write. Additional aspects include boolean operations, side effects, and the if/else construction.

The “attention to detail” aspect of this question is rather extreme, and it’s not common to find this level of trickiness in exam questions. Did you notice the semicolons at the end of both lines that start with if? Another matter of detail, albeit related to the first, is that the indentation is inappropriate (and it’s not our intention to turn you into a Python fan!). However, from a syntactic perspective, the code is valid. Furthermore, there is no unreachable code. This tells you that option A is incorrect; the code will compile.

As a side note, unreachable code is typically not considered to be a compilation error in situations where entire blocks of code subordinate to an if or a case are unreachable. These special cases are intended to permit the equivalent of conditional compilation and can be useful in situations such as debugging and testing because they allow entire chunks of code to be enabled, disabled, or swapped out. Therefore, the following does not elicit any complaint from the compiler:

if (false) {
  System.out.println("Debugging");
  // more code
}

By contrast, swapping the if for a while, as in the following code, is rejected by the compiler as unreachable:

while (false) { // error: unreachable statement
  System.out.println("Debugging");
  // more code
}

Moving to the other options: You should analyze the Boolean variable called emergency. The variable is not initialized explicitly, but it’s an instance field, so it is reliably initialized to false during the object’s allocation phase.

Quiz yourself, Oracle Java Career, Java Skills, Java Jobs, Java Prep, Java Preparation, Java Tutorial and Materials, Java Guides, Java Guides
Notice that the emergency() method inverts the value of the emergency field each time it is called. This is performed by the exclusive OR (XOR) assignment operator (^=), and the code returns the resulting value each time it is called.

Now that you know what’s going on with the emergency field and method, look at the body of the code that calls that method. The first two if tests do nothing conditional, because they end in semicolons. However, they serve to invert (to true) and then reinvert (back to false) the value of the emergency variable.

The indentation of the code is misleading, but once you’ve spotted the semicolons at the end of those first two if statements, you’ll recognize that the method say1() will be invoked no matter what value the emergency() method returns.

At the second if statement, the value returned from the emergency() method is false, so control goes to the else branch and the third if—and with it, the third call to emergency(). That third call returns true, which invokes the say2() method.

Because both the say1() and say2() methods are invoked, say1 say2 is printed to the console. This means option E is correct and options A, B, C, and D are incorrect.

Conclusion. The correct answer is option E.

Source: oracle.com