Trending February 2024 # How Does Swift Extension Works With Examples? # Suggested March 2024 # Top 4 Popular

You are reading the article How Does Swift Extension Works With Examples? updated in February 2024 on the website Eastwest.edu.vn. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested March 2024 How Does Swift Extension Works With Examples?

Introduction to Swift extension

Syntax

The syntax flow for the swift extension is as follows :

extension Struct_Enum_Extnsion_Type { } Where, extension – It signifies that swift extension is used for performing the swift programming followed by any class name. { Adding functionality helps in making the extension type more enhancing. } How does Swift extension work?

Swift extension has a working pattern which improvises and enhances the entire feature by providing some of the enhanced functionalities to the data structure and its values.

Sometimes the source code does not exist within the repository for access then at that time, the swift extension comes as a savior, which behaves almost like categories of objective C.

It has the property to add some computed instance properties that help in getting instance values and another type of property as well.

It provides many other types of new initializers for support as well.

Initializers present as part of extension helps in many ways as it helps in extending another type of data and customized type of initializer or parameter.

It also helps in making another type of initializers, instance method, and type methods inclined and used with repetition of Int types in the methods indicating to get a return type.

Some extensions which help in mutating have the capacity to modify the self and its type of properties which embarks the change and modification by a mutation on the original implementation.

The addition of subscripts is also possible using the extension as it helps in making the old type of properties added with the new subscript.

Swift extensions also can inherit the properties for the old type into a new type using a type of extension at the time of implementation.

Extensions also get created using conforming protocols with the extension in the methods being implemented within the codebase.

Extensions also help in code separation as they can differentiate the code and give it an edge by segregating and providing enhanced code in the Swift programming language.

Examples

Different examples are mentioned below:

Example #1

This program demonstrates the Swift extension, which inherits the computed instance and type properties with all types of extensions, specifically int type with various manipulation as shown in the output.

import Foundation import Glibc extension Int { var no_add: Int {return self + 150 } var no_sub: Int { return self - 50 } var no_mul: Int { return self * 20 } var no_div: Int { return self / 30 } } let no_of_addition = 12.no_add print("Addition_includes (no_of_addition)") let no_of_division = 68.no_div print("Division_includes (no_of_division)") let no_of_multiplication = 82.no_mul print("Multiplication_includes (no_of_multiplication)") let no_of_subtraction = 125.no_sub print("Subtraction_includes (no_of_subtraction)") let miscellaneous = 12.no_add + 26.no_sub print("Miscellaneous_makes (miscellaneous)")

Output:

Example #2

This program demonstrates the instance class or the method class, which inherits the properties of a swift extension within the subclasses as well as all the properties as shown in the output.

import Foundation import Glibc extension Int { for _ in 1..<self { analyse_and_summarize() } } } print("Control_under_first_sub_block..") }) print("Control_under_first_sub_block..") })

Example #3

This program demonstrates the usage of swift extension for the nested type of data structure, enum, or enhanced classes, as shown in the output.

import Foundation import Glibc extension Int { enum vehicles { case car case truck case bus case scooter case blend } var print: vehicles { switch self { case 0: return .car case 1: return .truck case 2: return .bus case 3: return .scooter default: return .blend } } } func result(numb: [Int]) { for k_0 in numb { switch k_0.print { case .car: print(" Porsche_xl ") case .truck: print(" Mahindra_vi ") case .bus: print(" Volvo+0 ") case .scooter: print(" pep++ ") default: print(" autorick_shaw ") } } } result(numb: [0, 1, 3, 4, 6, 5])

Output:

Example #4

This program demonstrates the mutation of the instances, which means that the value can transform themselves according to the requirement within the method as shown in the output for computing the cube area.

import Foundation import Glibc extension Double { mutating func cube() { let val_p = 3.256 self = val_p * self * self * self } } var cube_try_0 = 2.11 cube_try_0.cube() print("Cube_area of a cube is: (cube_try_0)") var cube_try_1 = 3.66 cube_try_1.cube() print("Cube_area of a cube is: (cube_try_1)") var cube_try_2 = 256.12 cube_try_2.cube() print("Cube_area of a cube is: (cube_try_2)")

Example #5

This program demonstrates the protocol extension with some added constraints on the set of declared array and collection conforming to the type and properties of the entire set using the extension as shown in the output.

import Foundation import Glibc extension Collection where Element: Equatable { for Element in self { if Element != self.first { return false } } return true } } let eql_cllcn_no = [213, 108, 206, 105, 150] let spillted_no = [300, 300, 300, 300, 300] print(eql_cllcn_no.equal_all_condn()) print(spillted_no.equal_all_condn())

Output:

Conclusion

It plays a very significant and powerful role in a swift programming language as it helps programmers and provides them with the ability to manipulate the elements according to the accessibility. It helps in enhancing the code and making the code in an understandable and readable format. It helps in managing the codebase with the usage of the swift extension.

Recommended Articles

We hope that this EDUCBA information on “Swift extension” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

You're reading How Does Swift Extension Works With Examples?

How Does Xml Works In Prolog With Examples?

Introduction to Prolog XML

The prolog XML is a part of the document declaration and data management in a structure using tags. It is one of the markup languages which is based on the document-oriented concept. It is a declared document from start to end in format for usability and productivity. It is an optional part of the programming language to display and exchange data in a tag structured or format.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of Prolog XML

Given below is the syntax:

Explanation:

The XML contains the attribute and elements for empty elements.

The XML mode creates case-sensitive language.

The XML supports predefined entities such as a “less than”, “greater than”, etc.

The XML mode includes underscore and colon in a namespace.

The XML provides white space mode to preserve.

The basic prolog xml syntax shows below.

The basic with standalone syntax shows below.

url: local/url/ name

It converts into prolog file syntax shows below.

xml( [version = "1.0", standalone = "no"]

It converts into prolog file syntax shows below.

xml( [version="1.0", standalone="no"], [ namespace( element( [], [ h. element( i. [] ) j. ] ) k. ) l. ] ). How does XML Works in Prolog?

Create a file with the “pl” extension.

Example:

main.pl

Insert data into the prolog file.

Then, save the object with value into a pl file.

The following commands can use for the “prolog XML” data of the list.

First, write xml version and standalone value in the prolog file.

xml( [version="1.0", standalone="no"],

Then, write down the document type with the required link and information.

Write the namespace for store elements.

Write the elements of the required data, such as an image.

element( svg, [width=”250″, height=”250″], [ element( circle, [cx=”20″, cy=”20″, r=”18″,], [] ) ] )

Open prolog console or interpreter.

Set the directory path of the “pl” file.

Use the given prolog file.

[main].

You can use the prolog console directly for programming.

Use the “prolog XML” syntax in the prolog console.

xml( [version="1.0", standalone="no"], [ element( svg, [width="250", height="250"], [ element( circle, [cx="20", cy="20", r="18",], [] ) ] ) ) ] ).

Combine the working procedure of the “prolog if” function.

Use the “main.pl” file.

Use the given prolog console with the required directory path.

[main]. xml( [version="1.0", standalone="no"], [ namespace( element( [], [ element( [] ) ] ) ) ] ).

Use the command for “prolog XML” in the prolog console.

The prolog console displays the below data for prolog XML.

xml([version = [49, 46, 48], standalone = [110, 111]], [doctype(public([104, 116, 116, 112, 58, 47, 47, 119, 119, 119, 46, 101, 100, 117, 99, 98, 97, 46, 99, 111, 109, 47])), namespace(element([], [element([])]))]). Examples of Prolog XML

Different examples are mentioned below:

Example #1

The basic prolog XML with empty element example and output shows below.

Use the following command in prolog pl file.

Code:

xml( [version="1.0", standalone="no"]).

Use the following command in prolog console.

Code:

| ?- listing.

Output:

Example #2

The basic example and the output shows below.

Code:

xml( [version="1.0", standalone="no"], [ element( svg, [width="500", height="500"], [ element( circle, [cx="25", cy="25", r="24",], [] ) ] ) ) ] ).

Output:

Example #3

The basic example and the output shows below.

Use the following command in prolog pl file.

Code:

xml( [version="1.0", standalone="no"], [ element( svg, [width="500", height="500"], [ element( circle, [cx="25", cy="25", r="24",], [] ) ] ) ) ] ).

Use the following command in prolog console.

Code:

| ?- listing.

Output:

Example #4

With the standalone example and output shows below.

Use the following command in prolog pl file.

Code:

xml( [version="1.0", standalone="yes"], [ element( svg, [width="500", height="500"], [ element( circle, [cx="25", cy="25", r="24",], [] ) ] ) ) ] ).

Use the following command in prolog console.

Code:

| ?- listing.

Output:

Example #5

With empty element example and the output shows below.

Use the following command in prolog pl file.

Code:

xml( [version="1.0", standalone="yes"], [ namespace( element( [], [ element( [] ) ] ) )

Use the following command in prolog console.

Code:

| ?- listing.

Output:

Example #6

With the encoding example and output shows below.

Use the following command in prolog pl file.

Code:

xml( [version="1.0", encoding="UTF-8", standalone="no"]).

Use the following command in prolog console.

Code:

| ?- listing.

Output:

Conclusion

It is used for declaring data from start to end in format for usability and productivity. It exchanges the data in the prolog data structure simplification and maintain of the application. It creates attractive, sorted, and elegant prolog applications.

Recommended Articles

We hope that this EDUCBA information on “Prolog XML” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Linux Ping Command Works With Examples

Introduction to Linux Ping

In the Linux ecosystem, the ping is used to check whether the host is reachable or not over the internet protocol. It is working on the ICMP protocol i.e. Internet Control Message Protocol. Ping command utility is cross-platform. Primarily, it is working packet level. Widely, the ping command is also known as the Packet Internet Groper.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of Ping Command:

ping [option] hostname or IP address

ping: We can use the ping keyword in the syntax or command. It will take the two-argument as an option and hostname or IP address. As per the input argument, the ping command will provide the end result of whether the IP or hostname is reachable or not.

option: We can provide the different flags as options that are compatible with the ping command.

hostname or IP address: As per the requirement, we can pass the different hostname or the IP address.

How does Linux Ping Command work?

The ping is widely used to check the host or IP address availability or reachability.

While the source machine is using the ping command, the ping command will follow the below steps:

It is trying to connect the destination host or IP address.

It is calculating the amount of time it is taking from the destination host to the sender or source host.

It is also calculating the average packet loss between the source and destination host.

The ping command is working on the ICMP protocol. It is also known as the Internet Control Message Protocol. With the help of the same protocol, the ping command is sending the series of ECHO REQUEST messages or packets to the destination address and waiting for the reply from destination packages. The destination packets are also replying in the ICPM protocol. If the sources machine will receive the packet or message response from the destination machine. Then only we can say the connection or connectivity is established in between the source or destination servers.

Examples of Linux Ping

Given below are the examples mentioned:

Example #1

Ping Command

Code:

Explanation:

Output:

Example #2

Ping Command – With “-c” Option

By default, the ping command is continuously printing the echo-response on the screen unless and until we do not interrupt it screen. To avoid this condition, we can use the “-c” option with the ping command. It is useful to send the limited ECHO REQUEST packets.

Code:

Explanation:

By default, we are getting the ping response. But we need a limited response or reply from the destination server then we need to use the “-c” option with the response value.

Output:

Example #3

Ping Command – With “i” Option

In ping command, we are having the functionality to send the packets in a specific interval of time.

Note: The default interval time is 1 second.

Code:

Explanation:

As per the above ping command, we are able to send the packets or response to the destination server or host in a specific interval of time i.e., two sec.

Output:

Example #4

Ping Command – With “-f” Option

Sometimes we need to test the network load or network response on the high load. In ping command, we are having the functionality to check the high performance on the network level.

Code:

Explanation:

In ping command, we are sending the huge amount of load in the network via the “-f” option. We can also test the load-carrying capacity of the network.

Output:

Example #5

Ping Command – With “-b” Option

In ping command, we are having the functionality to enable the broadcast.

Code:

ping -b 192.168.1.1

Explanation:

As per the above command, we are able to broadcast in the Linux environment with the help of ping command.

Output:

Example #6

Ping command – With “-s” Option

In the Linux environment, we can test the ping response in different packets sizes. We can define the packet size with the help of “-s” option in the ping command.

Code:

Explanation:

In general, the ping command is using 64 bytes for the source and destination communication. Sometimes due to high traffic or latency, the packets may drop and the necessary packets are not able to reach the source machine. To avoid this condition, we need to use the “-s” option to increase the bytes size in the ping command.

Output:

Example #7

Ping Command – With “-l” Option

In Ping command, we are having the functionality to send the packages at the same time without waiting for the reply from the destination host or IP address.

Code:

Explanation:

Output:

Example #8

Ping Command – With “-v” Option

In the ping command, we are having the functionality to get the verbose output.

Code:

Explanation:

As per the above ping command, we are able to get the ping command output in the verbose mode.

Output:

Example #9

Ping Command – With “-W” Option

In the ping command, we are having the functionality to define the time to wait for response value. The ping command will wait for the destination response at the curtain time period.

Code:

Explanation:

As per the below screenshot, we are waiting for a response from chúng tôi We have defined the waiting time is 10 sec.

Output:

Conclusion

We have seen the uncut concept of “Linux Ping Command” with the proper example, explanation and command with different outputs. The ping command utility is widely used in the multiple platforms. It is the best way to check the connectivity in between the source and destination machine.

Recommended Articles

We hope that this EDUCBA information on “Linux Ping” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Linux Regular Expression

Linux Inode

Linux Network Command

Linux Alias Command

How A Class Is Works In Scala With Examples?

Introduction to Scala Class

Scala Class is basically a user defined blueprint having methods and fields into a single unit from which object can be created. Class is just like a home for the various methods and global variables defined that are used within its scope. We can create an object from the class using the new keyword (by initialing it calling ) using that for calling the methods inside a class. There are fields in a class providing the class state and there are methods defined inside the class that implements the behavior of a class. With the help of Object-defined, we can use all the functionalities defined in a Class.

Start Your Free Software Development Course

Class Declaration

A class in scala is defined with the Keyword Class, followed by the name of the class. Starting with opening the curly braces it contains the body of the class ending with the braces closed thereafter. The class can have some optional parameters also with any superclass extension or trait defined. The public is the default modifier used for the class.

class Class_name{ } Example Class Animal { }

Output:

Defined class Animal

How does Class Work in Scala?

After the declaration of class in scala, we have all the methods and variables that we need to use. So we need to create an object when an object of a class is created the class is known to be instantiated. Once that is done we will be able to take the values and use the method used in the class.

We can create more than one instance for a class, the new keyword is used to define objects in Scala, once that object is created we can access the methods inside the class and can implement it in our code.

Let’s see how to call the class methods with objects.

| defAn() | { | println(“hello”) | } | } defined class Animal

Here we have declared a class named with Animal with a method An inside it.

e: Animal = [email protected]

Then Here in the vale, we are making a new object which can access the methods of the CLASS.

hello

So memory is allocated and a reference is returned invoking the class constructor whenever a new object is created using the new operator. We can create anonymous objects also, anonymous objects are those which doesn’t have any reference.

So constructors are basically called up in a Scala Class when an object is instantiated. Scala Constructors being of two types primary and auxiliary have the same body as that of class so anything inside the class will be the part of that Constructor. So if no constructors are defined scala will automatically take this primary constructor whenever an object is created and that the constructor is called as Default constructor.

Few Points that we need to check about this default class constructor is:-

If values defined inside are var then we can change the value for that.

If the values defined are val inside then it will be considered as final and the values cannot be changed.

If there is nothing defined (val,var) it will have restricted visibility.

We can also use the access modifier while defining the values inside so that will work accordingly as per the definition of the access modifiers.

Let us check this with an example:

| println(“hello”) | } defined class Animals

This will define a class with primary constructor Animals and whenever the object is created the resulted value is called.

hello b: Animals = [email protected]

The auxiliary constructor comes up with a different signature list. The auxiliary constructor comes up with a constructor call this.

classNo_Distinct(i : Int , j:Int) { vark :Int = 0 println("Hello") println(i) println(j) println(k) defthis(i:Int ,j:Int,k:Int)   { this(i,j)        this.k = k } }

If we will call this by creating the object, the Auxiliary Constructor will call both and will do what the method has in it.

Output:

Val o = new No_Distinct(3,4,0)

So from this, we see how Scala Class is useful and helpful in the object-oriented programming model.

Conclusion

Here from the above article, we came across the Scala Class and the feature it exhibits. Having a Class is a very important concept for the Scala Object-Oriented Programming model. Here with the help of Examples, we got to know about the methods a class can have with the functionalities it adheres.

Recommended Articles

We hope that this EDUCBA information on “Scala Class” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How The Ps Command Works In Docker With Examples?

Introduction to Docker ps

The ‘docker ps’ is a Docker command to list the running containers by default; however, we can use different flags to get the list of other containers that are in stopped or exited status. We can also manipulate the output as per our requirement using flags. Docker has used the naming convention of ps from Linux; ps means ‘process status’ in Linux, and containers are actually running as a process on the Linux server; that’s why ‘docker ps’ is used to list the containers.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

docker ps [OPTIONS]

Options:

-a, –all: It is used to show all containers

-f, –filter: It is used to filter the list as per the condition applied

–format: It is used to manipulate the output using a GO template that means how the output should look like

-n, –last: It shows last created containers including all states

-l,  –latest: It is used to show the latest created container regardless of the state

–no-trunc: It shows output without truncating the data

-q, –quiet: It only displays the numeric ID of the containers

-s, –size: It shows the total file size of the container

Command:

docker ps --help

How does the ps command work in Docker? Examples of Docker ps

We are going to learn different options used in the ‘docker ps’ command by taking scenarios, but before that, let’s create few containers using the below commands that we will use to perform and test the ‘docker ps’ command options:

docker run -d –name test-con1 alpine

Example #1

List the running containers only.

Solution: We can use the ‘docker ps’ command simply to get the list of the running containers as it shows only the running containers by default.

docker ps

Explanation: As per the above snapshot, we can see that only one container is running right now.

Example #2

List all containers whether it is running or not.

Solution: We have to use the ‘-a’ or ‘–all’ option with the ‘docker ps’ command as below: –

docker ps –all

Explanation: In the above snapshot, we can see that there are 5 containers because if you see the first snapshot where containers were created, I have run the same command twice.

Example #3

Use the ‘-f’ or ‘–filter’ option to filter out the specific container.

Let’s filter out the container based on its container ID as below: –

docker ps -a -f “id=35”

Note: – In the above snapshot, we have used the ‘-a’ flag as well to list the container even if it is not running. It is recommended to use the ‘-a’ flag with a filter. We can also use the short ID, but it must be unique.

We can also filter the containers based on their name as below: –

docker container ls -a -f “name=test”

Note: – we can use a few keywords of the container name, and it will output the containers if the Docker daemon finds any container having those keywords in the name.

docker container ls -a -f “name=con”

We can use labels to filter the containers if containers have labels on them, so let’s create two more containers having labels on them.

docker run -d –label env=prod ubuntu sleep 3600

docker ps -f “label=type=web”

Explanation: In the above snapshot, we can see that we can list the containers which have a specific label; for ex., the first and the second commands show all the containers which have label “env” and “type” respectively on it regardless of the value and the third command shows all the container which has label “type” and the value of the label “type” must be “web”.

We can also filter the containers based on their image name, image ID, tags, and layers.

docker ps -a -f ancestor=3fd9065eaf02

Example #4

Format the output of the ‘docker ps’ command using the GO template with the format option.

Let’s display only the container ID as below: –

docker ps -a –format {{.ID}}

We can output more than one field; just we need to add that field as below: –

docker ps -a  --format "{{.ID}} {{.Names}}"

We can use the ‘t’ to make some space and also provide any symbol in between to make the output pretty as below: –

We can output the fields that are not visible by default as well and use the ‘table’ directives to show the headers in the output as shown below: –

docker ps -a --format "table {{.ID}} t {{.Names}} t {{.Labels}} t {{.Size}}"

In the above snapshot, we can now see the field headers as well.

Example #5

If we have a situation where we want to display the last n number of containers that are created, we can use the ‘-n’ option as below: –

docker ps -n 2

Note: – It includes stopped containers as well, so there is no need to specify the ‘-a’ flag.

Example #6

Solution: We can use the ‘-l’ option to list the lastest created container as below: –

docker ps -l

Example #7

Sometimes data of few columns get truncated because of screen size. List the containers without truncating the columns’ data.

Solution: We can use the ‘–no-trunc’ option to show all columns’ data as below: –

docker ps -n 2 --no-trunc

Note:- We can use this option with other options as well, like format, filter, etc.

Example #8

Show only the container ID of the containers.

Solution:  We can use the ‘–quiet’ or ‘-q’ option to list only container ID as below: –

docker ps -a –quiet

Example #9

Show the size of the container without using the ‘format’ option.

Solution: We have separate options ‘–size’ or ‘-s’ to list the size of the container.

docker ps -a -s

Advantages

This command is very useful while doing troubleshooting, mostly useful with the ‘filter’ option.

It helps to output the list of containers as per our need using the ‘format’ option that we can use for reporting purposes.

It has multiple options that can be used together to filter and format the list of containers.

Rules and regulations for using a ps?

The filter option only shows the running container if we filter based on labels, even if we use the ‘-a’ option.

The output of ‘-n’ and ‘-l’ options show the container whether it is running or not, so no need to specify the ‘-a’ flag with these.

We can use the ‘–no-trunc’ option with almost all the other options available in this command.

Conclusion – Docker ps

The ‘docker ps’ command is easy to use as compared to the ‘docker container ls’ as both commands have the same options and give us the same output, but ‘docker container ls’ is lengthy, so I prefer the ‘docker ps’ command over the ‘docker container ls’.

Recommended Articles

This is a guide to Docker ps. Here we discuss How the ps command works in Docker and Examples, along with the solution and explanation. You may also have a look at the following articles to learn more –

How Does Assertion Work With Advantages & Examples

Introduction to Java Assertion

In Java, Assertion is a statement that ensures or tests the correctness of the assumptions made in a program. It is done with the help of the assert statement. When the written assumption is executed, it is considered as true. If it is false, an assertion error will be thrown by the Java Virtual Machine.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The main reasons why Assertions are used are:

To confirm whether an unreachable code is reachable.

To confirm, the default case in the switch is not reached.

After the invocation of a method.

To check the state of an object.

Below is the syntax of the Java Assertion statement.

assert expression; assert expr1 : expr2;

Any of these syntaxes can be used based on the requirement.

How does Assertion work in Java?

As already mentioned, assert can be written in two forms.

The syntax asserts expression; is used in order to test the expressions of Boolean form. If the particular expression is false, the program gets terminated by throwing an AssertionError. Unlike the normal exceptions, these errors are disabled during runtime.

However, the syntax asserts expr1: expr2; it is used in cases where the program has some extra information that helps diagnose certain failures.

Similar to the uncaught exceptions in Java, assertion errors are commonly labeled in stack trace along with the file as well as line number from which the exception is thrown.

Even though these are the main pros of Assertion, there are certain situations where Assertions should not be used. They are:

Error message replacement.

Argument checking in public methods

Command-line arguments.

Note:  Before compiling the code, make sure that assertion is enabled.

Syntax

java –ea programname

Or

java –enable assertions programname Steps to use Eclipse Java Assertion

In Eclipse, it can be done using the below steps.

Step 1: Select Run Configurations.

Similarly, assertions can be disabled using the syntax given below. Java –da programname

Examples to Implement Java Assertion Example #1

Java program to check whether a particular value is higher than 20.

Code:

class AssertionExample{ public static void main( String args[] ){ int val = 14; System.out.println("The given value is: "+ val); } }

Output:

On executing the code, the message “The given value is 14” gets displayed.

It can be clearly seen that assertion is not checked here since the value is greater than 20 is not checked.

In order to enable assertion, -ea has to be set before compiling. For that, perform the steps mentioned in NOTE.

If you again try to run the code, it can be clearly seen that an AssertionError has been thrown since the value is less than 20.

Example #2

Java program to check whether a particular user input value is higher than 20.

Code:

import java.util.Scanner; class AssertionExample{ public static void main( String args[] ){ Scanner sc = new Scanner( chúng tôi ); System.out.print("Enter a number to check assertion "); int val = sc.nextInt(); System.out.println("The given value is: "+ val); } }

Output:

The user will be asked to input a number on executing the code. In the below result, the number 13 is given as input. Since it is less than 20, an AssertionError has been thrown.

At the same time, when a value which is greater than 20 is given, no errors are thrown, and the message gets displayed.

Example #3

Java program to check the number of days in a week.

Code:

class AssertionExample { public static void main(String args[]) { String[] days = {" Monday " , " Holiday " , " Saturday " , " Tuesday " , " Wednesday " , " Sunday " , " Thursday " , " Friday " }; assert days.length==7 : "7 days are present in a week, Your input is wrong"; System.out.println("There are " + days.length + "  days in a week"); } }

Output:

On executing the code, an assertion error is thrown as the number of days in a week is 7, and the string input given contains more than that.

Let us remove Holiday from the input values and see what the output will be.

Yes. The line gets printed as the assertion value satisfies the input value.

Advantages of using Assertion in Java

Efficient detection and correction of bugs.

Boilerplate code will be removed and helps in creating a readable code.

Execution time won’t be affected since it gets removed automatically during runtime.

Quick bug detection and correction.

Code optimization and refactoring is done with high confidence in order to function correctly.

In addition to the above points, below are the important points that have to be known while studying Assertions.

An assertion in Java is introduced in the version JDK 1.4

Assert is the keyword used in order to implement assertion.

Enabling and disabling of assertion can be done at runtime with the help of corresponding syntaxes.

Even though assertion compliments the exception, it does not replace the exception.

It does not replace the unit testing even if it helps in the validation of conditions.

Never use assertion for arguments or parameters validation of a method that is public.

Conclusion

Java Assertion is a statement that checks the trueness of a particular condition. It is commonly used in testing during software development. Moreover, they are used with certain Boolean expressions. In this article, several aspects such as syntax, working, pros, cons, and examples of Assertion is explained in detail.

Recommended Articles

Update the detailed information about How Does Swift Extension Works With Examples? on the Eastwest.edu.vn website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!