You are reading the article How Compareto Works In Java With Examples updated in November 2023 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 December 2023 How Compareto Works In Java With Examples
Introduction to compareTo JavacompareTo() 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 #1Java 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 #2Java 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 #3Java 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 #4Java 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 #5Java 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.
ConclusioncompareTo() 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 ArticlesThis 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 –
You're reading How Compareto Works In Java With Examples
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() FunctionBelow are mentioned the examples:
Example #1his 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 #2This 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 #3This 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 #4This 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 #5This 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 #6This 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 #7This 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:
Conclusionsha1() 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 ArticlesThis 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 Linux Time Works With Examples?
Introduction to Linux Time
In the Linux operating system, the time will run the special program with a specific or compatible input argument. When the command or the job will finish the execution, the time command will give the below timing statistics
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Elapsed Time: It is the passed time between the invocation of the process or job and the termination of the process.
User CPU Time: It is the addition of the tms_utime time and tms_cutime time values.
System CPU Time: It is the addition of the tms_stime time and tms_cstime time values.
Syntax:
time [ OPTION ] [ COMMAND ]
time : We can use the “time” keyword in the syntax or command. It will take different arguments like options and commands. As per the provided arguments, it will print the time options in different types like Elapsed Time, User CPU Time, and System CPU Time.
OPTION : We can provide the different flags as the option that is compatible with the “time” command.
COMMAND: As per the condition or requirement, we can provide or use a different command with the time keyword.
How Linux Time Works?Linux is a multi-user support operating system. It will support multiple servers or applications. While running these servers or applications, they are generating a huge amount of data. Once the data will generate parallel the time will also increase while doing the reading or writing operations on it. The time command will consider the different compatible options with the command. As per the inputs, it will give the detailed information of time in terms of the Elapsed Time, User CPU Time, and System CPU Time.
Below are the lists of options that are compatible with the time command.
Sr No Option Description
1 C It will give the information of the name and the command line arguments being timed (in terms of the command)
2 D It will give information about the average size of the processes in the unshared data area. The information will be in Kilobytes.
3 E This process will use the wall clock time. It will be in hours: minutes: seconds format.
4 I It will get the Number of file system inputs by the process.
5 K It will consider the average of data, stack, and text memory use of the process. It will be in Kilobytes.
6 M Due to the process lifetime, we can set the maximum resident of the process. It will be in Kilobytes.
7 O The process will consider the number of file system outputs.
8 P It is the addition of user and system time divide by total running time. We will get the percentage of the CPU that the job got.
9 S In terms of process, it will be the total number of CPU-seconds used by the system. The value will be in seconds.
10 U In terms of user mode, the total number of CPU-seconds that the process used. The value will be in seconds.
11 W It will give the memory information of the number of times the process was swapped.
12 X It will give information on the average amount of shared text in the process. The value will be in Kilobytes.
13 Z It will give the system page size information. The value will be in bytes.
14 e It will be the wall clock time used by the process. The value will be in seconds.
15 k It will give the information of the number of signals delivered to the process.
16 p It will give the process information of the average unshared stack size. The value will be in Kilobytes.
17 r The process will receive the number of socket messages.
18 s The process will be sent the number of socket messages.
19 t It will give the information of the average resident set size of the process. The value will be in Kilobytes.
20 x It will give the exit status of the command.
ExamplesLets us discuss examples of Linux time.
Example #1In the Linux environment, we can run the simple time command and get the basic information of the Elapsed Time, User CPU Time, and System CPU Time.
Command :
timeExplanation :
As per the above command, we are running the simple time command. It will give the basic information of the Elapsed Time, User CPU Time, and System CPU Time.
Output :
Example #2In the time command, we are having the functionality to use the different Linux commands.
Command :
We are using the wget command with the time command. Time command will calculate the elapsed time, user and CPU time for execution of the command.
Output :
Example #3 – Redirect Time Command OutputIn the time command, we are able to redirect the time command output to a different file.
Command :
Explanation :
As per the above command, we are redirecting the time command output to the “time.txt” file. It will use for further analysis.
Output :
Example #4 – With Option “-p”In time command, we are able to print the time in POSIX format
Command :
Explanation :
In the above command, we are able to print the time command output in POSIX format. As per the requirement, we can use the different options with the time command.
Output :
ConclusionWe have seen the uncut concept of “Linux Time” with the proper example, explanation, and command with different outputs. As per the requirement, we can use the time command with different Linux command and get detail time information in terms of the Elapsed Time, User CPU Time, and System CPU Time.
Recommended ArticlesWe hope that this EDUCBA information on “Linux Time” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
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 #1Code:
.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 #2Code:
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 #3Code:
.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 #5Code:
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 #6Code:
*{ 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 #7Code:
.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 #8Code:
.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.
ConclusionIn 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 ArticlesWe hope that this EDUCBA information on “CSS calc()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
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 #1Simple 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 #2SQL 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 #3SQL 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; ConclusionDECODE 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 ArticlesWe hope that this EDUCBA information on “SQL DECODE()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Top New Java 8 Features With Examples
Introduction to Java 8
Oracle rolled out a fresh release of Java on March 18, 2014. Java 8 is a landmark release, introducing numerous new and valuable features. Let’s delve into the features of Java 8 to familiarize ourselves with them. It includes new functionality, upgrades, and bug fixes to increase efficiency in designing and operating Java programs.
Start Your Free Software Development Course
Top New Java 8 Features with ExamplesBelow are the top features of Java 8 that make Java 8 more understanding and more valuable:
1. New Date/Time APIThe old Date-Time API of Java had significant drawbacks. In place of it, there is a fresh Date-Time API in Java 8. We take a look at the drawbacks below:
Tough to Handle Timezone: Programmers needed many lines of code to tackle timezone issues.
Low-Quality Design: The earlier API had relatively few direct functions for date operations. Java 8 API offers many functions for date operations.
Absence of Thread Safe Property: chúng tôi lacked thread-safe property. Hence programmers had to face concurrency issues while employing data. Java 8 Date-Time API is immutable and without setter methods.
In Java 8, the package chúng tôi introduces a new Date-Time API. There are two significant classes contained in chúng tôi package:
Zoned: Specialized API to handle different time zones.
Local: Simplified API without the complexity of managing time zones.
2. Nashorn JavaScriptThe earlier version of Java contained the Rhino JavaScript engine. In Java 8, Rhino is replaced by a superior JavaScript engine, Nashorn. The latter offers two to ten times superior performance when benchmarked against its predecessor. This is possible as it directly compiles the lines of code in memory and passes the bytecode to the Java Virtual Machine. Nashorn employs the invoke dynamics feature of Java 7 to enhance performance.
3. Optional ClassSimply put, Optional serves as a container object that stores non-null objects. One primary use of the Optional object is to represent null having an absent value. This important class has different utility methods to help code handle values as ‘not available’ or ‘available’ rather than to check null values. The class was added in Java 8 and is analogous to the Optional class in Guava.
4. Base64The new version of Java contains an inbuilt encoder and a decoder for Base64 encoding. Programmers can employ three kinds of Base64 encoding.
MIME: The output is formatted according to the MIME format, where it is divided into lines, each containing a maximum of 76 characters. The line separator consists of a carriage return followed by a line feed. There is no line separator at the termination of the encoded output.
URL: Mapping of Output is done to a group of characters present in A-Za-z0-9+_. The output is filename as well as the URL safe.
Simple: Mapping of Output is done to a group of characters present in A-Za-z0-9+_. The encoder does no addition of any line feed in the output. The decoder does accept any character differing from A-Za-z0-9+_.
5. StreamsThe Stream is a fresh abstract layer present in this new version of Java. You can process data declaratively, similar to SQL statements, by using a stream.
Understanding Stream
Stream, simply put, is a representation of a sequence of objects emanating from a source that has support for aggregate operations. Below are specific properties of a stream.
Iterations are Automatic: Explicit iterations are mandatory in Collections. In Stream, it internally iterates over the supplied source elements.
Pipelining: Most of the stream operation’s output is of the stream type. Thus, the output can be pipelined. The particular operations are termed intermediate operations. They accept input, do the necessary processing, and give the output to the target.
Some Aggregate Operations supported by Stream:
Match
Find
Reduce
Limit
Map
Filter
6. Functional InterfacesThey display individual functionality. The new version of Java has numerous functional interfaces which can be employed in large measure in lambda expressions.
7. Default MethodsIn Java 8, there is a fresh paradigm of interfaces having default method implementation. The inclusion of this feature is for backward compatibility purposes. It is now possible to use old interfaces to harness the lambda expression capability of the new version of Java.
For instance: the ‘Collection’ and ‘List’ interfaces lack the ‘forEach’ method declaration. The addition of such a method would cause the collection framework implementations to break. However, introducing default methods solves this issue by providing default implementations of the forEach method in List/Collection. As a result, the class implementing these interfaces no longer needs to implement these methods separately.
8. Method ReferencesThis prominent feature of Java 8 points to relevant methods using their respective names. A “::” symbol describes method references. The latter can be used to refer to the following types of methods.
Constructors Employing the New Operator
Instance Methods
Static Methods
9. Lambda ExpressionsBelow is a typical lambda expression.
We take a look at the significant parts of a lambda expression.
Return Keyword: The compiler returns the value if the body consists of a single expression. Curly braces signify that the expression returns some value.
The parenthesis around the parameter: If only a single parameter exists, the parenthesis can be omitted.
Type Declaration: Parameter-type declaration is not needed. From the parameter’s value, the compiler determines the necessary action.
Miscellaneous Features of Java 8: The JDBC-ODBC Bridge has been taken off. So. this has been the PermGen memory space. The ‘jjs’ command invokes the Nashorn engine while the ‘jdeps’ command analyzes the class files.
ConclusionNow that you have a theoretical knowledge of Java 8’s new features, it is necessary to implement them. In other words, you have to do the coding that exploits the many useful and valuable features of the new version of Java. Only then will you be truly proficient in Java 8?
Recommended ArticlesThis is a guide to Java 8 Features. Here we discuss the basic concept and top 9 features in Java 8 with a brief explanation for better understanding. You can also go through our other related articles to learn more –
Update the detailed information about How Compareto Works In Java With 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!