Trending March 2024 # How Decode() Function Works In Sql? Examples # Suggested April 2024 # Top 12 Popular

You are reading the article How Decode() Function Works In Sql? Examples updated in March 2024 on the website Hatcungthantuong.com. 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 April 2024 How Decode() Function Works In Sql? Examples

Introduction to SQL DECODE()

DECODE function in Standard Query Language (SQL) is used to add procedural IF – THEN – ELSE like statements to a query. It compares a given expression with each search value one by one and returns a result on the basis of outcomes received from the comparison. A decode function basically performs the task of CASE statements. However, we should keep in mind that DECODE is a built-in function in ORACLE SQL databases and hence it is supported only in ORACLE 9i and above versions of ORACLE/ PL SQL. It is not recognized and supported in other database management servers such as PostgreSQL, SQL Server, MySQL etc. So, now we can use CASE statements to perform IF-THEN-ELSE logic in these databases.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax and Parameters:

The basic syntax for writing DECODE function in SQL is as follows:

DECODE (expression , search_1, result_1[, search_2, result_2], ...,[,search_n,result_n] [, default]);

expression: expression argument is the value which is to be searched and compared with.

search_1, search_2, …. search_n: These are the values to be searched for and then compared with the expression argument.

result_1, result_2, … , result_n: These arguments hold the result to be returned when the given comparison returns true. For example, if expression = search_1 then result will be result_1.

default: default argument holds the default value. It is more or less like the ELSE statement in IF-THEN-ELSE.

We can use the DECODE function as a part of the SELECT statement, ORDER BY etc.

How DECODE() Function works in SQL?

The first step is comparison of expression and search_1, if the expression = search_1 is TRUE then result_1 is returned. If it’s FALSE then DEFAULT value is returned. The DECODE function automatically converts or casts the expression to the data type of the first search argument or search_1. And it finally converts back the data_type of result to the data_type of the expression.

The functionality of DECODE in ORACLE with following flowchart.

Example:

Code:

SELECT DECODE(1, 1, 'One') FROM dual;

Output:

The simple illustration of the above mentioned decode function is as follows:

Code:

IF 1 = 1 THEN result = 'One' ENDIF; Examples of SQL DECODE()

Given below are the examples mentioned:

Let us first create a ‘college_details’ table which contains college id, college name, location and fees for demonstration purposes.

We can use the following SQL CREATE TABLE statement to perform the task.

Code:

CREATE TABLE college_details( college_id integer NOT NULL, college_name character varying(255) NOT NULL, college_location character varying(255) NOT NULL, fees numeric NOT NULL );

Output:

Having created the table, let us now input some random data in it to work with in the subsequent exercises. We can use the following insert statements.

Code:

INSERT INTO college_details VALUES (10001, 'Indian Institute of Technology Roorkee', 'Roorkee,India', 10000); INSERT INTO college_details VALUES (10002, 'Indian Institute of Technology Bombay', 'Mumbai,India', 10000); INSERT INTO college_details VALUES (10004, 'California Institute of Technology', 'California ,USA', 60520); INSERT INTO college_details VALUES (10003, 'Massachusetts  Institute of Technology', 'Massachusetts,India', 51520); select * from college_details;

The data in the “college_details” table after performing the above mentioned INSERT operations looks something as shown below:

Output:

Example #1

Simple SQL query to illustrate use of DECODE function.

Code:

SELECT college_id, DECODE (college_id,   10003,'Massachusetts, USA', 10004, 'California, USA', 'India') FROM college_details;

Output:

In this example, we have performed a simple SQL task for categorizing colleges based on their location.

Simple illustration of above mentioned DECODE function is as follows:

Code:

IF college_id = 10003 THEN result = 'Massachusetts' ELSE IF college_id = 10004 THEN result = 'California' ELSE result = 'India' ENDIF; Example #2

SQL query to illustrate abbreviation of college names based on the available data using DECODE function.

SELECT college_id, DECODE(college_name,'Massachusetts  Institute of Technology', 'MIT','California Institute of Technology','CalTech','IIT') as college_name FROM college_details ORDER BY college_id;

Output:

In the above example, we have performed the following IF-THEN-ELSE logic statements and then ordered the entire result set by college_id.

Code:

IF college_name = 'Massachusetts  Institute of Technology' THEN result = 'MIT' ELSE IF college_name = 'California Institute of Technology' THEN result = 'Caltech' ELSE result = 'IIT' ENDIF; Example #3

SQL query to categories college fees into affordable and expensive for an Indian student, considering everything above $ 10000 as expensive.

Code:

SELECT college_id,fees, DECODE(fees,10000,'Affordable','Expensive') FROM college_details ORDER BY college_id;

Output:

In the above example, we have performed the following task using the DECODE function and have then ordered the result set by college_id.

Code:

IF fees = '10000' THEN result = 'Affordable' ELSE result = 'Expensive' ENDIF; Conclusion

DECODE function is used to perform procedural IF-THEN-ELSE logic in SQL. The function is a close relative of CASE statements. It is a built-in function in ORACLE / PL SQL database management servers.

Recommended Articles

We hope that this EDUCBA information on “SQL DECODE()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

You're reading How Decode() Function Works In Sql? Examples

How Calc() Function Works In Css? Examples

Introduction to CSS calc()

The calc() function contains a calculation that should be used as the property’s value. This function makes it easy to position an object with a set margin. The calc() function takes a specific expression as its argument, with the output of the expression being used as the value. The calc() is a native CSS method for doing basic maths correctly in CSS as a substitute for any longitudinal value or almost any number. This has four basic operators in math: add (+), subtract (-), multiply (*), and divide (/). Another case for the calc() function is to help ensure that form fields fit into the space available without extruding beyond the edge of the container while maintaining an acceptable margin.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

property_name: calc(expression) How does the calc() Function works in CSS?

The calc() function is better than the pre-processor, which can mix any unit. The calc() function makes simple calculations to specify the CSS property values. Users can multiply pixels by percentage.

To make the layout more versatile, it offers two key features such as:

Mixing percentages and absolute values.

Units of mixing sizes.

Examples of CSS calc()

Given below are the examples of CSS calc():

Example #1

Code:

.heading { position: absolute; left: 30px; width: calc(50% – 20%); height:calc(200px – 100px); background-color: #5E9BC6; padding-top:20px; text-align: center; } h2 { color:#F1DBED; }

Output:

We apply the calc() function to the height and width attributes, setting the width to 30% and the height to 100px. We are referring to the heading class for defining styles for the content.

Example #2

Code:

img { width: 100%; display: block; } .box { float: left; padding: 5px; box-sizing: border-box; width: calc(100% / 5); } @media (max-width: 900px) { .box { width: calc(100% / 4); } } @media (max-width: 550px) { .box { width: calc(100% / 3); } } @media (max-width: 400px) { .box { width: 100%; } }

Output:

The program explains how the boxes will get displayed in different screen resolutions. We have taken maximum widths as 900px, 550px, and 400px. When the screen gets smaller than 900px, 550px, and 400px, each box will have a specified width, as provided in the example.

Example #3

Code:

.heading { position: absolute; left: 40px; width: calc(300px – 50px); border: 2px dotted red; background-color: #5E9BC6; padding: 3px; text-align: center; }

Output:

The calc() function is applied to the width attribute, where the width will be set to 250px. The heading class is referred to for defining the styles for the content display.

Example #4

.input_txt { padding: 5px; display: block; width: calc(50% – 2em); } #box { width: calc(200% / 8); border: 1px dotted #5E9BC6; padding: 5px; }

Output:

Here, we are using the input type element of the HTML form. We apply the calc() function to the div and input elements. The width of the input type will be decreased to 2 times the size of the current width.

Example #5

Code:

img { display: block; } section { width: 250px; height: 150px; position: relative; background-color: #5E9BC6; } .box { position: absolute; } .box-horizontal { top: 15px; left: calc(50% – 20px); } .box-vertical { left: 15px; top: calc(50% – 20px); } .box-middle { left: calc(50% – 20px); top: calc(50% – 20px); }

Output:

The output shows a horizontal box, a vertical box, and middlebox. The horizontal box will be displayed on the left side by decreasing 20px from 50% with the help of the calc() function. The same scenario will be applied to vertical and middle elements.

Example #6

Code:

*{ box-sizing: border-box; } html, body{ height: 100%; padding: 50px; background: #00174f; } body{ }

Output:

Here, we are using a background image for the HTML body page. We position the image on the left side with a 10px decrease from 50% and a 10px decrease from 50% on the top side.

Example #7

Code:

.heading { margin: 0 auto; outline: solid 1px; width: 250px; height: 250px; background: linear-gradient(to left bottom, transparent calc(75% – 1em), #000 0, #000 calc(75% + 1em), transparent 0); }

Output:

The program creates a line with a gradient background for the HTML page on the left side of the bottom. It provides the inner background to the element and the opacity level for the element by using the calc() function.

Example #8

Code:

.heading { width: calc(200% / 8); border: 1px dotted #5E9BC6; padding: 5px; } .demo{ background:grey; font-size: 15px; }

Output:

We define the div element with a heading class. This class will use 1/8 of the available window width and specified styles.

Conclusion

In this article, we have seen some helpful featufeaturesSS. The calc() function will operate as a value across all places where a number value with or without specific units works. It seems time to use our examples to learn more about the CSS calc() function.

Recommended Articles

We hope that this EDUCBA information on “CSS calc()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Sha1() Function Works In Php With Examples

Introduction to PHP sha1()

PHP sha1() function is a very important function as part of PHP as it is a backed server-side scripting language that needs more emphasis on the security terms. PHP sha1() deals with the security and hashing function which calculates and computes a value of SHA-1 of the hash of the string. Internally PHP sha1() makes use of a subtype of the US Secure Hash Algorithm 1. Sha1() function produces a hash string with a value of 160 characters and then when this hash string is given as an input to the function it produces an output which is a highly secured message digest.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax sha1(string, raw)

Explanation: sha1() function makes use of two types of arguments like string and raw which is used for generating the string and calculating the length of the string with some value. raw is another argument or parameter which is optional in the sense if specified with the sha1() function then it passes the parameter with an optional value such as true or false and then it passes the remaining value to specify and describe the hex or binary value output format. If the optional value appears to be Raw 20 then it is a 20-character binary format otherwise it Is Default 40-character hex number with some specific value.

How does sha1() function work in PHP?

The SHA-1() function makes use of the US-Secure hash algorithm1 which is used in a way where the string is given as an input and then a message digest is given as an output. Input is fed to the signature algorithm which checks and verifies for the signature of the message. If a signature message is used as an input rather than the actual message, then it has a high chance of improving the efficiency of the overall algorithm.

This process will optimize and compress the message input and message output functionality compared to the normal hash string message as an input to the signature algorithm. Further if this algorithm is used by the verifier then a digital signature can be used by the creator of the digital signature.

sha_file() function is another subcomponent of the sha1() function which uses the hash of the file function.

This file function of the file name is used to calculate the hash of a file and one raw output will be given to it which will be used to return the message or the string with a value of whether true or false. Md5() algorithm within the function and crc32() with the function will also be used to generate the polynomial of the string. And will help in generating a more secured string with some refined digital signature.

Examples to Implement PHP sha1() Function

Below are mentioned the examples:

Example #1

his program represents the calculation of the SHA-1 hash of the string after passing one string value to get the hash of the string.

Code:

<?php $str = "welcome to educba"; echo sha1($str);

Output:

Example #2

This program represents the calculation of the SHA-1 hash of the string after passing one string value to get the hash of the string and then it prints the value of the sha1 string as shown in the output. The input of the string is given as “Welcome to Educba” and the output shows the string value.

Code:

<?php $str = "Welcome to Educba"; echo "The string: ".$str."n"; echo "TRUE - Represenation of Raw 20 character of binary format: ".sha1($str, TRUE)."n"; echo "FALSE - representation of 40 character of hex number: ".sha1($str)."n";

Output:

Example #3

This program represents the calculation of the SHA-1 hash of the string after passing one string value to get the hash of the string and then it prints the value of the sha1 string as shown in the output. The input of the string is given as “Welcome to Educba” and the output shows the string value. Followed by a test of the input string being fed as an output.

<?php $str = "educba"; echo sha1($str); if (sha1($str) == "49108e13b1505cd6147054cfd07fb52f4c9d2641") { echo "n!educba"; exit; }

Output:

Example #4

This program is also a part of the sha1() function associated function of CRC 32 algorithm which takes a string “Hello World ” as input and then echoes the value without and with the string of % u value as shown in the output.

Code:

<?php $str = crc32("Hello educba!"); echo 'Without %u: '.$str."n"; echo 'With %u: '; printf("%u",$str);

Output:

Example #5

This program makes use of the password_hash function as part of the sha1() function and helps in generating the password_hash with an output value as shown and makes use of hashing function by putting the cost parameter as 12 to get the optimized message digest as the final output to optimize and increase the overall efficiency of the program.

Code:

<?php $options = [ ]; echo password_hash("educba_is_a_laerning_portal", PASSWORD_BCRYPT, $options);

Output:

Example #6

This program makes use of the hash () function to generate the message digest of the given function which will be further used to convert into a digital signature for optimization.

Code:

<?php function lion($data = "", $width=182, $rounds = 4) { return substr( implode( array_map( function ($h) { return str_pad(bin2hex(strrev($h)), 16, "0"); }, str_split(hash("tiger192,$rounds", $data, true), 8) ) ), 0, 48-(192-$width)/4 ); } echo hash('tiger192,3', 'a-string'), PHP_EOL; echo lion('a-string'), PHP_EOL;

Output:

Example #7

This program illustrated the md5 algorithm to be fed as an input string which is also counted as one of the complementary parts of the sha1() algorithm.

Code:

<?php $str = 'apple'; if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') { echo " i want to have a green or red apple?"; }

Output:

Conclusion

sha1() function is a part of PHP string references which includes a lot of security and cryptographic algorithms which is very necessary for the backend services and the servers for continuing the overall security breaches related issues and password and user management related data as secured.

Recommended Articles

This is a guide to PHP sha1(). Here we discuss an introduction, Syntax, and working of sha1() in PHP along with different examples and code implementation. You can also go through our other related articles to learn more –

How Round Function Works In Lua Wth Examples

Definition of Lua Round

Lua provides us some round functions which is used to round off the numerical values. There is no function named as round rather we have some are options like the floor, ceil from the math library. Round functions help us to get the more accurate number without decimal included, it can move towards positive infinity or negative infinity depends upon the functions we have used to round off the value in Lua. The round function is used to round off the lng decimals numbers to some user-readable form an approx value. These round functions are available inside the lua inbuilt library, we do not require to use any external library for this. In the coming section of the tutorial, we will learn more about the round function in detail to understand and implement this while programming in Lua.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

1. ceil

math.ceil(your-_variable to be round off)

2. floor

math.floor(your-_variable to be round off)

As you can see in the above lines of syntax we have two options available for round off values in lua. Let’s take an practice example to understand it better see below;

Example:

math.ceil(10.6789) math.floor(10.6789)

In the coming section of the tutorial, we will discuss the internal working of round functions available in lua for better usage for beginners.

How Round Function Works in Lua?

As we already know that in Lua we have two options to round off values or numbers in lua without using any external library. Lua provides us Math library support to handle the rounding of values efficiently. We can use any method from the math library, just keep in mind we have to use the ‘math’ keyword to call them and use them. In this section we will see the internal working of round function in Lua see below;

1. Floor

This function is used to round off the value of a big decimal. This function is provided by the math library, which is very easy to use in the program, we do not require writing any import statement to use this, we can directly call the floor function on math. When we use floor function to round off any value it will give us the next number to negative infinity, suppose if you have one number say 0.5 it will give us 0 in this case, that means one number below, Let’s see its usage;

Method Signature:

math. floor(number) : As you can see in the method signature, it takes one parameter inside the function, which represents the value to be round off. It will always return us the number without decimal. Let’s take an simple example :

Example:

math.floor(10.4567) 2. Ceil

This function is also used to round off the value to the nearest value possible. This function is also provided by the math library in lua, for this function to use we do not require any import statement while using it in our program. When we use ceil method and pass the variable inside it, it will always give us the next value to positive infinity, which means a number greater. Let’s suppose we have one value which is to be round off, that is ‘0.5’ then in space of ceil it will return us 1 instead of 0 like in case of floor function above.

Method Signature:

math.ceil(number): As you can see in the method signature, it takes one parameter inside the function, which represents the value to be round off. It will always return us the number without decimal. Let’s take a simple example :

Example:

math.ceil(10.4567)

Points to be remembered while using round function in lua;

There is no function named as round function in lua, we have to use the math library to achieve it.

We have floor and ceil functions.

One will return us the value toward negative infinity and one will return us the value towards positive infinity.

Examples of Lua Round

In the below example we are doing a comparison among both functions what will they return if we try to pass the same value using different functions in lua. It will showcase the difference among them and now you decide which function to be used.

Example #1

In this example, we are using the floor method to round the values to next whole number. This is an sample example for beginners to start with rounding values in lua using math functions.

print("Demo to round values in lua ") val1 = math.floor(0.5) val2 = math.floor(20.45667) val3 = math.floor(13.6547) val4 = math.floor(0.789) val5 = math.floor(5.872) print("print result here ..") print("first value is ::" , val1) print("second value is ::" , val2) print("third value is ::" , val3) print("fourth value is ::" , val4) print("fifth value is ::" , val5)

Output:

Example #2

In this example, we are using ceil method to round the values to the next whole number. This is a sample example for beginners to start with rounding values in lua using math functions.

Code:

print("Demo to round values in lua ") val1 = math.ceil(0.5) val2 = math.ceil(20.45667) val3 = math.ceil(13.6547) val4 = math.ceil(0.789) val5 = math.ceil(5.872) print("print result here ..") print("first value is ::" , val1) print("second value is ::" , val2) print("third value is ::" , val3) print("fourth value is ::" , val4) print("fifth value is ::" , val5)

Output:

Conclusion

By using the round function, we can remove the decimal part of the numbers, it will return us the next whole number. These functions are very easy to use and implement in the program. By the use of this wean represent the value to the user in readable form and perform a calculation to get the result.

Recommended Articles

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

How Rank() Function Works In Postgresql ?

Introduction to PostgreSQL RANK()

The following article provides an outline of PostgreSQL RANK(). We can assign a rank to each row of the partition of a result set by using the RANK() function. The rank of the first row of a partition is 1. The rank is incremented in a fashion where the next row’s rank equals the number of rows tied to the rank. Since the values of the rank computation are determined internally by the OVER clause, no explicit parameters are required.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

RANK() OVER ( [PARTITION BY partition_exp, .... ] )

Explanation:

PARTITION BY clause: The rows of the partitions of the result set to which the PostgreSQL RANK() function is applied.

ORDER BY clause: Defines the order of rows in each partition to which the PostgreSQL RANK() function is applied.

How RANK() Function works in PostgreSQL?

To calculate the rank of the next row, the PostgreSQL RANK function adds the number of rows to the position assigned to the previous rank.

Because of this, the rank might not be sequential.

All of the partition rows with the same values get the same rank.

Examples of PostgreSQL RANK()

Now let’s create a new table of name ‘Grades’, which will have a column named’Grade’ using CREATE TABLE statement as follows:

Code:

CREATE TABLE Grades ( Grade VARCHAR(1) );

Now, insert some data into the ‘Grades’ table using the INSERT statement as follows:

Code:

INSERT INTO Grades(Grade) VALUES ('A'),('A'),('A'), ('B'),('B'), ('C'), ('D');

Illustrate the content of the Grades table with the help of the following snapshot and SQL statement.

Code:

SELECT Grade FROM Grades;

Output:

Now, with the help of the RANK() Function, we can assign a rank to the row of the Grade column in the result set of the Grades table as follows:

Code:

SELECT Grade, RANK () OVER ( ORDER BY Grade ) grade_rank FROM Grades;

Output:

From the above snapshot, we can see that the first three rows have the rank assigned as rank 1, which is the same for all rows whose value is ‘A’.

The rank of the fourth and fifth rows is assigned to rank 4 because of the PostgreSQL.

RANK() function calculated it as the previous rank summed with a total number of rows tied to that rank. Similarly, it assigns rank 6 and ranks 7 to the sixth and seventh rows, respectively.

Now let’s create tables of name ‘transaction’ and ‘invoices’ in order to understand the RANK function with the PARTITION BY clause.

Code:

CREATE TABLE transaction ( transaction_id serial PRIMARY KEY, transaction_data VARCHAR (256) NOT NULL ); CREATE TABLE invoices ( invoice_id serial PRIMARY KEY, transaction_id INT NOT NULL, invoice_data VARCHAR (256) NOT NULL, invoice_amount INT NOT NULL, FOREIGN KEY (transaction_id) REFERENCES transaction (transaction_id) );

Now insert some data in the transaction and invoices table by using the INSERT statement as follows:

Code:

INSERT INTO transaction (transaction_data) VALUES ('Purchase of Mobile'), ('Purchase of PC'), ('Purchase of Headphone'), ('Purchase of Mouse'), ('Purchase of Cable'); INSERT INTO invoices (invoice_data, transaction_id,invoice_amount) VALUES ('Purchase of Mobile', 1,30500), ('Purchase of Mobile', 1,30500), ('Purchase of Mobile', 1,20500), ('Purchase of PC', 2,15000), ('Purchase of PC', 2,12000);

Illustrate the result of the above statement with the help of the following snapshots and select statements:

Code:

select * from transaction;

Output:

Code:

select * from invoices;

Output:

Example #1

without PARTITION

Code:

SELECT invoice_id, invoice_data, invoice_amount, RANK () OVER ( ORDER BY invoice_amount DESC ) invoice_amount_rank FROM invoices;

Output:

In the above example, the entire table is considered a single PARTITION as we have not defined the Partition BY clause.

Example #2

with PARTITION BY

Code:

SELECT invoice_id, invoice_data, invoice_amount, transaction_data, RANK () OVER ( PARTITION BY i.transaction_id ORDER BY invoice_amount DESC ) invoice_amount_rank FROM invoices i INNER JOIN transaction t ON i.transaction_id = t.transaction_id;

Output:

In the above example, we have defined the PARTITION BY clause. In PostgreSQL, you can use the PARTITION BY clause to group invoices into partitions based on the transaction_id column. Also, we have an ORDER BY clause defined, which sorts invoices from high to low in each partition by their invoice_amount.

Here, you can use the RANK function in PostgreSQL to assign a rank to each transaction data, which will reset when the transaction data changes. This allows for clear visualization of the assigned ranks for each invoice.

Conclusion

From the above article, we hope you understand how to use the PostgreSQL RANK function and how the PostgreSQL RANK() function works to assign the rank and fetch the data. Also, we have added some examples of the PostgreSQL RANK() Function to understand it in detail.

Recommended Articles

We hope that this EDUCBA information on “PostgreSQL RANK()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Compareto Works In Java With Examples

Introduction to compareTo Java

compareTo() is a method in Java that compares the string given with the current string in a lexicographical manner. Comparison is done on the basis of the Unicode value of characters available in the string.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Following are the different conditions in the compareTo() method.

If string 1 is lexicographically larger than string 2, a positive number will be returned.

If string 1 is lexicographically smaller than string 2, a negative number will be returned.

If string 1 is lexicographically equal to string 2, ‘0’will be returned.

Below is the syntax of compareTo() method:

public int compareTo(String s2)

Here, s2 is the string that is used for comparison with the current string. An integer value will be returned on calling this method.

How compareTo works in Java?

compareTo() method can be used in three ways.

Examples of compareTo Java

Given below are the examples of compareTo Java:

Example #1

Java program to implement compareTo method that compares two strings.

Code:

public class compareToExample { public static void main(String args[]) { String s1 = "Happiness lies within you"; String s2 = "Happiness LIES WITHIN YOU"; String s3 = "Happiness lies within you"; System.out.println( " Compare s1 and s2 : "+ V1 ) ; System.out.println( " Compare s1 and s3 : "+ v2 ) ; System.out.println(" Compare s2 and s3 : "+ v3 ) ; }}

Output:

In this program, three strings are created s1, s2 and s3. Three variables, v1, v2 and v3, are also created for storing the comparison results of s1&s2, s1&s3, and s2&s3, respectively. It can be seen that a positive number is returned on comparing s1 & s2, and a negative number is returned on comparing s2 &s3. As both s1 and s3 are equal, 0 is returned in the second case.

Example #2

Java program to implement compareTo method that compares a string and an object.

Code:

public class compareToExample { public static void main(String args[]) { String s1 = "Happiness lies within you"; System.out.println( " Compare s1 and argument : "+ v2 ) ; } }

Output:

In this program, a string s1 and variable v1 are created first. Another string is passed as an argument in the compareTo() method, and it can be seen that a positive number is returned on comparing s1 and argument.

Example #3

Java program to find the length of a string using the compareTo method.

Code:

public class compareToExample { public static void main(String args[]) { String s1 = "Happiness lies within you"; String s2 = ""; System.out.println( " Length of s1 : "+ V1 ) ; System.out.println( " Length of s1 : "+ v2 ) ; } }

Output:

In this program, two strings are created, s1 and s2, where s2 is a null string. If the given string is compared with a nullstring, then the length of the non-empty string will be returned. If a comparison is done in reverse order, a negative value of the length will be returned.

Example #4

Java program to implement compareToIgnoreCase method that compares two strings.

Code:

public class compareToExample { public static void main(String args[]) { String s1 = "Happiness lies within you"; String s2 = "Happiness LIES WITHIN YOU"; String s3 = "Happiness lies within you"; System.out.println( " Compare s1 and s2 : "+ V1 ) ; System.out.println( " Compare s1 and s3 : "+ v2 ) ; System.out.println(" Compare s2 and s3 : "+ v3 ) ; } }

As already seen, compareToIgnoreCase ignores the case and compares the strings. As the three strings differ only in cases, 0 will be returned on calling this method.

Example #5

Java program to implement compareToIgnoreCase method that compares a string and an object.

Code:

public class compareToExample { public static void main(String args[]) { String s1 = "Happiness lies within you"; System.out.println( " Compare s1 and argument : "+ v2 ) ; } }

Output:

In this program, a string s1 and variable v1 are created first. Another string is passed as an argument in the compareToIgnoreCase() method, and it can be seen that 0 is returned as the case is ignored.

Conclusion

compareTo() is a Java method that compares the string given with the current string in a lexicographical manner. In this article, different aspects such as syntax, working, and examples of the compareTo() method is seen in detail.

Recommended Articles

This is a guide to compareTo Java. Here we discuss the introduction, how compareTo works in java? Along with examples, respectively. You may also have a look at the following articles to learn more –

Update the detailed information about How Decode() Function Works In Sql? Examples on the Hatcungthantuong.com 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!