Author: saqibkhan

  • Overview

    Java DOM parser is an API (Application Programming Interface) that has classes, interfaces and methods to parse XML documents by creating DOM tree structure.

    The Document Object Model (DOM) is an official recommendation of the World Wide Web Consortium (W3C). It defines an interface that enables programs to access and update the style, structure, and contents of XML documents.

    When to use Java DOM Parser?

    You should use a DOM parser when −

    • You need to know a lot about the structure of a document.
    • You need to move parts of an XML document around (you might want to sort certain elements, for example).
    • You need to use the information in an XML document more than once.

    What is the result of Parsing?

    When you parse an XML document with a DOM parser, you will get a tree structure that contains all of the elements of your document. The DOM provides a variety of functions you can use to examine the contents and structure of the document.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Advantages

    Following are some advantages of Java DOM parser −

    • DOM is a very simple API to use.
    • Easy to access and modify any part of the document since entire document is loaded into memory.
    • Java code written for one DOM-compliant parser should run on any other DOM-compliant parser without having to do any modifications.

    Disadvantages

    Following are some of the disadvantages of Java DOM parser −

    • Consumes more memory
    • Not suitable for large documents.
    • Not applicable for small devices like PDAs and cellular phones.

    DOM Interfaces

    Here are the most commonly used DOM interfaces −

    InterfaceDescription
    DocumentRepresents the XML or HTML document.
    Nodeprimary data type of the Document Object Model (DOM)
    NodeListan ordered collection of nodes.
    Elementrepresents an element in XML document.
    Attrrepresents an attribute of an Element object.
    Textrepresents textual content of an element or attribute, inherited from ‘CharacterData’ interface.

    DOM Methods

    Here are the most commonly used DOM methods −

    MethodDescription
    Document.getDocumentElement()returns the root element of the document.
    Document.getElementsByTagName()returns a NodeList of all elements within the given tag name.
    Node.getFirstChild()returns the first child of a given Node.
    Node.getLastChild()returns the last child of a given Node.
    Node.getNextSibling()returns the root element of the document.
    Node.getPreviousSibling()returns the root element of the document.
    Node.getAttribute(attrName)returns the attribute with the requested name for a given node.
    Node.getNodeName()returns the name of the node.
    Node.getTextContent()returns the text content of the current node and its descendants.
    NodeList.getLength()returns the number of nodes in the NodeList.
    NodeList.item(int index)returns the indexth node from the NodeList.
  • Parsers

    Java has various XML parsers that support object type and event type standards. We can read, create, query and modify the XML documents using these APIs. APIs provide interfaces that represent the XML documents, methods to retrieve and modify the elements and attributes in XML documents.

    XML Parsers

    XML Parsers are the software libraries or packages that help client applications to interact with XML documents through interfaces. They are used to check the syntax of XML and validate it according to the DTD or XML schema. Parsers can be either document based or event based.

    Types of XML parsers

    Following are the two main types of XML parsers −

    • DOM (Document Object Model)
    • SAX (Simple API for XML)

    DOM (Document Object Model)

    DOM is proposed by W3C (World Wide Web Consortium). It is a tree based API and creates the entire XML document into a parse tree inside the main memory. Hence, it consumes more memory. DOM API provides interfaces to access, add and modify the documents that are independent of programming languages. DOM is suitable for small documents as it consumes more memory. We can both read and create documents using DOM APIs.

    DOM parser image

    SAX (Simple API for XML)

    SAX is an event based API. It will not load the entire document. Instead, it loads small parts of XML file. SAX is a read-only API, we cannot create XML documents using SAX. It is used to process large XML documents as it consumes less memory.

    SAX parser image

    Java XML Parsers

    The JAXP (Java API for XML Processing) APIs provide the standard interfaces to process XML documents in Java applications. It has interfaces that support both DOM and SAX standards.

    The below table describes various XML parsers and their relative classes or interfaces in java.

    ParserDescriptionClass/Interface
    DOM ParserDOM parser represents an XML file as tree structure inside main memory. DOM provides interfaces to access and modify XML documents.DocumentBuilder
    SAX ParserSAX parser parses an XML document based on events and is used only for reading. The entire file is not loaded into the main memory.SaxParser
    JDOM ParserJDOM parser is an open source API that supports DOM, SAX, XSLT and XPath. It integrates with both DOM and SAX.DOMBuilder, SAXBuilder, StAXEventBuilder, StAXStreamBuilder, StAXStreamWriter
    StAX ParserStAX parser is a JAVA based streaming API and it is a pull-parsing model to read and write XML documents.XMLEventReader, XMLEventWriter
    DOM4J ParserDOM4J parser is a java based library that uses Java Collections framework to efficiently access and modify XML documents.DOMReader, DOMWriter, SAXReader, SAXWriter
    XPath ParserXPath parser parses the XML document based on expressions to access and modify nodes.XPath
  • Overview

    Java XML is simply working with an XML document from a Java program. Imagine, we have a file “products.xml” where we have product details such as name, brand and price.

    Now, we want to update prices for some products using Java programming. Before writing such java programs to access XML documents, we should know basics of XML.

    What is XML?

    XML stands for EXtensible Markup Language. It is a text-based markup language which is used to store and transport data. It is self-descriptive and both human-readable and, machine-readable. Following are some notable points on XML −

    • XML is a markup language.
    • XML is a tag based language like HTML.
    • XML tags are not predefined like HTML.
    • You can define your own tags which is why it is called extensible language.
    • XML tags are designed to be self-descriptive.
    • XML is W3C Recommendation for data storage and data transfer.

    XML Document

    An XML document is the collection of elements that define data in a well structured and organized manner. An XML document has two sections, namely, document prolog and document elements.

    Syntax

    Following is the syntax of an XML document −

    <?xml ?><root_element><element></element>
    	...
    </root_element>

    Where,

    • <?xml ?> is the XML declaration statement. If included, it must be kept in the first line.
    • <root_element> is the root element and it is the parent of all other elements.
    • <element> is the sub element of the root element.

    Example

    Following example shows Employee details with <Employee> as the root element and <name><role><salary> as sub elements. Data for each element is enclosed between opening and closing tags.

    <?xml version="1.0" ?><Employee><name>Kiran</name><role>developer</role><salary>25,000</salary></Employee>

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Elements in XML

    An element is the building block of an XML document. It consists of an opening tag, content and a closing tag. In an xml document, there should always be a root element, inside which we can write many sub elements. Elements can also have any number of attributes inside them.

    Syntax

    Following is the syntax of an XML element −

    <root><child><subchild>.....</subchild></child></root>

    Where,

    • <root> is the root element of the XML document.
    • <child> is the child element and its parent is the root element.
    • <subchild> is the sub child and its parent is the child element.

    Example

    Let us see an example where DOB(date of birth) is further structured into date, month and year. Here, <DOB> is the root element and <date><month><year> are child elements.

    <DOB><date>27</date><month>March</month><year>2000</year></DOB>

    Tags in XML

    Tags in XML are self-explanatory and user defined. These are enclosed in less than (<) and greater than (>) symbols. XML is case sensitive and hence opening and closing tags should have same name.

    Example

    In the following example, we have written an address element with opening and closing tags.

    <address>Hyderabad</address>

    Now, let us see some incorrect ways of writing XML tags:

    <Address></address><ADDRESS></address>

    Since, XML is case sensitive unlike HTML, it throws the error: Opening and ending tag mismatch.

    Attributes in XML

    Elements in XML can have attributes. Attributes are name-value pairs that provide further specific information about a particular element. An element can have any number of attributes.

    Syntax

    Following is the syntax for XML attributes −

    <element_name attribute_name="value" >content</element_name>

    Where,

    • element_name is the name of the element.
    • attribute_name is the name of the attribute.
    • value is the value of the corresponding attribute.

    Example

    Now, let’s look at the following example where we have four attributes, name, class, marks and DOB for the ‘Student’ element.

    <Student name="Kiran" class="8" marks="50" DOB="27-03-2000"></Student>

    Using sub elements to replace attributes

    Instead of attributes, sub elements can also be used in elements to achieve the same purpose as of attributes. The same student example can also be written as follows:

    <Student><name>Kiran</name><class>8</class><marks>50</marks><DOB>27-03-2000</DOB></Student>

    It is always a best practice to use sub elements instead of attributes. Because, sub elements can further be extended whereas attributes cannot be extended.

    In the above example, If we further want the date of birth as date, month and year then it can be done by using sub elements for DOB element as follows :

    <Student><name>Kiran</name><class>8</class><marks>50</marks><DOB><date>27</date><month>03</month><year>2000</year></DOB></Student>

    XML Declaration

    XML declaration describes the basic format information such as version, encoding and standalone status about the entire XML document. If an XML declaration is included in the document, it must be written in the first line.

    By default, if declaration is not mentioned, XML parser considers the document is in version 1.0

    Syntax

    Following is the syntax of XML declaration −

    <?xml
    	version="version_number"
    	encoding="encoding_type"
    	standalone="standalone_status"
    ?>

    Where,

    • XML declaration starts with the character sequence <?xml and ends with the character sequence ?>
    • version is the version number of the XML used
    • encoding is the character encoding used for the content of XML document
    • standalone is a boolean attribute whose default value is set to ‘no’. This tells whether the XML document is standalone or uses information from external source to parse the document such as DTD(Document Type Definition). The default value is set to ‘no’.

    Example

    Following example uses XML 1.0 version with encoding type UTF-16 and it is standalone.

    <?xml
    	version="1.0"
    	encoding="UTF-16"
    	standalone="yes"
    ?>

    XML Comments

    Comments in XML are used to explain the document’s purpose and details. It is always a best practice to include comments in the document because it makes the task simpler to the one who is reading the document for the first time. XML follows the same syntax as of HTML.

    Syntax

    Following is the syntax for both single line and multi line XML comments −

    <!-- comment here -->

    Example

    Let us say we have collected the information of departments in a college in the year 2015. These records might be changed over the years. So, mentioning this in the comments helps the one who is editing to know when these details have been collected.

    <?xml version = "1.0" encoding = "UTF-8" ?><!-- Following information is collected in the year 2015 --><college><Department><name>CSE</name><code>CS</code><faculty_strength>25</faculty_strength></Department><Department><name>ECE</name><code>EC</code><faculty_strength>20</faculty_strength></Department></college>

    XML Namespaces

    XML namespaces are used to resolve name conflicts in the XML document. When two or more XML fragments are added, then there is a chance that these XML code fragments might use some tags with same name. Then, this confuses the XML parser. To avoid these kind of name conflicts, XML Namespaces are used.

    Example

    Assume we have created an XML element holding the information about a coffee table −

    <table><shape>Oval</shape><material>Wood</material><seat_count>3</seat_count><cost>15000</cost></table>

    Suppose we have created another element which holds information about a dining table as −

    <table><shape>Rectangle</shape><material>Marble</material><seat_count>6</seat_count><cost>25000</cost></table>

    When the above two XML code fragments are added together (in a single file), there will be a name conflict. Though the name of both the elements is same the information provided by them varies. There are two ways to resolve these name conflicts in XML. They are −

    • Using Prefix
    • Using namespace declaration

    Using Prefix

    We can differentiate the elements by adding prefix to them. To resolve the above name conflict, we can add the prefix ‘c’ to the element holding the info about the coffee table and similarly we can add the prefix ‘d’ for the other element (dining table).

    Example

    Let us take the same table example and try to resolve the name conflict using prefixes.

    <!-- Coffee Table --><c:table><shape>Oval</shape><material>Wood</material><seat_count>3</seat_count><cost>15000</cost></table><!-- Dining Table --><d:table><d:shape>Rectangle</d:shape><d:material>Marble</d:material><d:seat_count>6</d:seat_count><d:cost>25000</d:cost></d:table>

    Drawbacks of Using Prefixes

    While using prefixes there still might be a chance where two elements have same prefix along with the name. In such cases the conflict prevails.

    Suppose if we add another element providing info about a dressing table, to differentiate, we need to use the prefix ‘d’. This again brings a conflict between dining table and dressing table. Hence, using prefix can solve the conflict to some extent but not completely.

    Using “namespace” Declaration

    XML namespace declaration is used to resolve name conflicts effectively. A new attribute named ‘xmlns’ is used.

    Syntax

    Following is the syntax for XML namespace −

    <element-name xmlns:prefix="URI">

    Where,

    • element-name: Element name on which the namespace is used.
    • xmlns: A compulsory keyword to declare namespace.
    • prefix: Namespace prefix
    • URI: Namespace identifier

    Example

    The following example uses XML namespace declaration for three table tags. Now, the conflict between dining table and dressing table is resolved by differentiating them in their namespace URI.

    <!-- Coffee Table --><h:table xmlns:h="/coffee"><c:table><shape>Oval</shape><material>Wood</material><seat_count>3</seat_count><cost>15000</cost></table><!-- Dining Table --><d:table xmlns:h="/dining"><d:shape>Rectangle</d:shape><d:material>Marble</d:material><d:seat_count>6</d:seat_count><d:cost>25000</d:cost></d:table><!-- Dressing Table --><d:table xmlns:h="/dressing"><d:brand>Trevi Furniture</d:brand><d:material>Engineered wood</d:material><d:cost>15000</d:cost></d:table>
  • MathContext 

    Introduction

    The java.math.MathContext class provides immutable objects which encapsulate the context settings and describes certain rules for numerical operators, such as those implemented by the BigDecimal class.

    The base-independent settings are −

    • precision − the number of digits to be used for an operation; results are rounded to this precision.
    • roundingMode − a RoundingMode object which specifies the algorithm to be used for rounding.

    Class declaration

    Following is the declaration for java.math.MathContext class −

    public final class MathContext
       extends Object
    
      implements Serializable

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for java.math.MathContext class −

    • static MathContext DECIMAL128 − A MathContext object with a precision setting matching the IEEE 754R Decimal128 format, 34 digits, and a rounding mode of HALF_EVEN, the IEEE 754R default.
    • static MathContext DECIMAL32 − A MathContext object with a precision setting matching the IEEE 754R Decimal32 format, 7 digits, and a rounding mode of HALF_EVEN, the IEEE 754R default.
    • static MathContext DECIMAL64 − A MathContext object with a precision setting matching the IEEE 754R Decimal64 format, 16 digits, and a rounding mode of HALF_EVEN, the IEEE 754R default.
    • static MathContext UNLIMITED − A MathContext object whose settings have the values required for unlimited precision arithmetic.

    Class constructors

    Sr.No.Constructor & Description
    1MathContext(int setPrecision)This constructor, constructs a new MathContext with the specified precision and the HALF_UP rounding mode.
    2MathContext(int setPrecision, RoundingMode setRoundingMode)This constructor, constructs a new MathContext with a specified precision and rounding mode.
    3MathContext(String val)This constructor, constructs a new MathContext from a string.

    Class methods

    Sr.No.Method & Description
    1boolean equals(Object x)This method compares this MathContext with the specified Object for equality.
    2int getPrecision()This method returns the precision setting.
    3RoundingMode getRoundingMode()This method returns the roundingMode setting.
    4int hashCode()This method returns the hash code for this MathContext.
    5String toString()This method returns the string representation of this MathContext.
  • BigInteger 

    Introduction

    The java.math.BigInteger class provides operations analogues to all of Java’s primitive integer operators and for all relevant methods from java.lang.Math.

    It also provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations. All operations behave as if BigIntegers were represented in two’s-complement notation.

    Semantics of arithmetic operations and bitwise logical operations are similar to those of Java’s integer arithmetic operators and Java’s bitwise integer operators respectively. Semantics of shift operations extend those of Java’s shift operators to allow for negative shift distances.

    Comparison operations perform signed integer comparisons. Modular arithmetic operations are provided to compute residues, perform exponentiation, and compute multiplicative inverses. Bit operations operate on a single bit of the two’s-complement representation of their operand.

    All methods and constructors in this class throw NullPointerException when passed a null object reference for any input parameter.

    Class declaration

    Following is the declaration for java.math.BigInteger class −

    public class BigInteger
       extends Number
    
      implements Comparable&lt;BigInteger&gt;

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for java.math.BigInteger class −

    • static BigInteger ONE − The BigInteger constant one.
    • static BigInteger TEN − The BigInteger constant ten.
    • static BigInteger ZERO − The BigInteger constant zero.

    Class constructors

    Sr.No.Constructor & Description
    1BigInteger(byte[] val)This constructor is used to translate a byte array containing the two’s-complement binary representation of a BigInteger into a BigInteger.
    2BigInteger(int signum, byte[] magnitude)This constructor is used to translate the sign-magnitude representation of a BigInteger into a BigInteger.
    3BigInteger(int bitLength, int certainty, Random rnd)This constructor is used to construct a randomly generated positive BigInteger that is probably prime, with the specified bitLength.
    4BigInteger(int numBits, Random rnd)This constructor is used to construct a randomly generated BigInteger, uniformly distributed over the range 0 to (2numBits – 1), inclusive.
    5BigInteger(String val)This constructor is used to translate the decimal String representation of a BigInteger into a BigInteger.
    6BigInteger(String val, int radix)This constructor is used to translate the String representation of a BigInteger in the specified radix into a BigInteger.

    Class methods

    Sr.No.Method & Description
    1BigInteger abs()This method returns a BigInteger whose value is the absolute value of this BigInteger.
    2BigInteger add(BigInteger val)This method returns a BigInteger whose value is (this + val).
    3BigInteger and(BigInteger val)This method returns a BigInteger whose value is (this & val).
    4BigInteger andNot(BigInteger val)This method returns a BigInteger whose value is (this & ~val).
    5int bitCount()This method returns the number of bits in the two’s complement representation of this BigInteger that differ from its sign bit.
    6int bitLength()This method returns the number of bits in the minimal two’s-complement representation of this BigInteger, excluding a sign bit.
    7BigInteger clearBit(int n)This method returns a BigInteger whose value is equivalent to this BigInteger with the designated bit cleared.
    8int compareTo(BigInteger val)This method compares this BigInteger with the specified BigInteger.
    9BigInteger divide(BigInteger val)This method returns a BigInteger whose value is (this / val).
    10BigInteger[ ] divideAndRemainder(BigInteger val)This method returns an array of two BigIntegers containing (this / val) followed by (this % val).
    11double doubleValue()This method converts this BigInteger to a double.
    12boolean equals(Object x)This method compares this BigInteger with the specified Object for equality.
    13BigInteger flipBit(int n)This method returns a BigInteger whose value is equivalent to this BigInteger with the designated bit flipped.
    14float floatValue()This method converts this BigInteger to a float.
    15BigInteger gcd(BigInteger val)This method returns a BigInteger whose value is the greatest common divisor of abs(this) and abs(val).
    16int getLowestSetBit()This method returns the index of the rightmost (lowest-order) one bit in this BigInteger (the number of zero bits to the right of the rightmost one bit).
    17int hashCode()This method returns the hash code for this BigInteger.
    18int intValue()This method converts this BigInteger to an int.
    19boolean isProbablePrime(int certainty)This method returns true if this BigInteger is probably prime, false if it’s definitely composite.
    20long longValue()This method converts this BigInteger to a long.
    21BigInteger max(BigInteger val)This method returns the maximum of this BigInteger and val.
    22BigInteger min(BigInteger val)This method returns the minimum of this BigInteger and val.
    23BigInteger mod(BigInteger m)This method returns a BigInteger whose value is (this mod m).
    24BigInteger modInverse(BigInteger m)This method returns a BigInteger whose value is (this-1 mod m).
    25BigInteger modPow(BigInteger exponent, BigInteger m)This method returns a BigInteger whose value is (thisexponent mod m).
    26BigInteger multiply(BigInteger val)This method returns a BigInteger whose value is (this * val).
    27BigInteger negate()This method returns a BigInteger whose value is (-this).
    28BigInteger nextProbablePrime()This method returns the first integer greater than this BigInteger that is probably prime.
    29BigInteger not()This method returns a BigInteger whose value is (~this).
    30BigInteger or(BigInteger val)This method returns a BigInteger whose value is (this | val).
    31BigInteger pow(int exponent)This method returns a BigInteger whose value is (thisexponent).
    32static BigInteger probablePrime(int bitLength, Random rnd)This method returns a positive BigInteger that is probably prime, with the specified bitLength.
    33BigInteger remainder(BigInteger val)This method returns a BigInteger whose value is (this % val).
    34BigInteger setBit(int n)This method returns a BigInteger whose value is equivalent to this BigInteger with the designated bit set.
    35BigInteger shiftLeft(int n)This method returns a BigInteger whose value is (this << n).
    36BigInteger shiftRight(int n)This method returns a BigInteger whose value is (this >> n).
    37int signum()This method returns the signum function of this BigInteger.
    38BigInteger subtract(BigInteger val)This method returns a BigInteger whose value is (this – val).
    39boolean testBit(int n)This method returns true if and only if the designated bit is set.
    40byte[ ] toByteArray()This method returns a byte array containing the two’s-complement representation of this BigInteger.
    41String toString()This method returns the decimal String representation of this BigInteger.
    42String toString(int radix)This method returns the String representation of this BigInteger in the given radix.
    43static BigInteger valueOf(long val)This method returns a BigInteger whose value is equal to that of the specified long.
    44BigInteger xor(BigInteger val)This method returns a BigInteger whose value is (this ^ val).
  • BigDecimal 

    Introduction

    The java.math.BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.

    The toString() method provides a canonical representation of a BigDecimal. It gives the user complete control over rounding behavior.

    Two types of operations are provided for manipulating the scale of a BigDecimal −

    • scaling/rounding operations
    • decimal point motion operations

    This class and its iterator implement all of the optional methods of the Comparable interfaces.

    Class declaration

    Following is the declaration for java.math.BigDecimal class −

    public class BigDecimal
       extends Number
    
      implements Comparable&lt;BigDecimal&gt;

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for java.math.BigDecimal class −

    • static BigDecimal ONE − The value 1, with a scale of 0.
    • static int ROUND_CEILING − Rounding mode to round towards positive infinity.
    • static int ROUND_DOWN − Rounding mode to round towards zero.
    • static int ROUND_FLOOR − Rounding mode to round towards negative infinity.
    • static int ROUND_HALF_DOWN − Rounding mode to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round down.
    • static int ROUND_HALF_EVEN − Rounding mode to round towards the “nearest neighbor” unless both neighbors are equidistant, in which case, round towards the even neighbor.
    • static int ROUND_HALF_UP − Rounding mode to round towards “nearest neighbor” unless both neighbors are equidistant, in which case round up.
    • static int ROUND_UNNECESSARY − Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.
    • static int ROUND_UP − Rounding mode to round away from zero.
    • static BigDecimal TEN − The value 10, with a scale of 0.
    • static BigDecimal ZERO − The value 0, with a scale of 0.

    Class constructors

    Sr.No.Constructor & Description
    1BigDecimal(BigInteger val)This constructor is used to translates a BigInteger into a BigDecimal.
    2BigDecimal(BigInteger unscaledVal, int scale)This constructor is used to translate a BigInteger unscaled value and an int scale into a BigDecimal.
    3BigDecimal(BigInteger unscaledVal, int scale, MathContext mc)This constructor is used to translate a BigInteger unscaled value and an int scale into a BigDecimal, with rounding according to the context settings.
    4BigDecimal(BigInteger val, MathContext mc)This constructor is used to translate a BigInteger into a BigDecimal rounding according to the context settings.
    5BigDecimal(char[ ] in)This constructor is used to translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor.
    6BigDecimal(char[ ] in, int offset, int len)This constructor is used to translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor, while allowing a sub-array to be specified.
    7BigDecimal(char[ ] in, int offset, int len, MathContext mc)This constructor is used to translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor, while allowing a sub-array to be specified and with rounding according to the context settings.
    8BigDecimal(char[ ] in, MathContext mc)This constructor is used to translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor and with rounding according to the context settings.
    9BigDecimal(double val)This constructor is used to translates a double into a BigDecimal which is the exact decimal representation of the double’s binary floating-point value.
    10BigDecimal(double val, MathContext mc)This constructor is used to translates a double into a BigDecimal, with rounding according to the context settings.
    11BigDecimal(int val)This constructor is used to translates an int into a BigDecimal.
    12BigDecimal(int val, MathContext mc)This constructor is used to translates an int into a BigDecimal, with rounding according to the context settings.
    13BigDecimal(long val)This constructor is used to translate a long into a BigDecimal.
    14BigDecimal(long val, MathContext mc)This constructor is used to translates a BigInteger into a BigDecimal.
    15BigDecimal(String val)This constructor is used to the string representation of a BigDecimal into a BigDecimal.
    16BigDecimal(String val, MathContext mc)This constructor is used to translates the string representation of a BigDecimal into a BigDecimal, accepting the same strings as the BigDecimal(String) constructor, with rounding according to the context settings.

    Class methods

    Sr.No.Method & Description
    1BigDecimal abs()This method returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale().
    2BigDecimal abs(MathContext mc)This method returns a BigDecimal whose value is the absolute value of this BigDecimal, with rounding according to the context settings.
    3BigDecimal add(BigDecimal augend)This method returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).
    4BigDecimal add(BigDecimal augend, MathContext mc)This method returns a BigDecimal whose value is (this + augend), with rounding according to the context settings.
    5byte byteValueExact()This method converts the BigDecimal to a byte, checking for lost information.
    6int compareTo(BigDecimal val)This method compares the BigDecimal with the specified BigDecimal.
    7BigDecimal divide(BigDecimal divisor)This method returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() – divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.
    8BigDecimal divide(BigDecimal divisor, int roundingMode)This method returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale().
    9BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)This method returns a BigDecimal whose value is (this / divisor), and whose scale is as specified.
    10BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)This method returns a BigDecimal whose value is (this / divisor), and whose scale is as specified.
    11BigDecimal divide(BigDecimal divisor, MathContext mc)This method returns a BigDecimal whose value is (this / divisor), with rounding according to the context settings.
    12BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode)This method returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale().
    13BigDecimal[ ] divideAndRemainder(BigDecimal divisor)This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands.
    14BigDecimal[ ] divideAndRemainder(BigDecimal divisor, MathContext mc)This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands calculated with rounding according to the context settings.
    15BigDecimal divideToIntegralValue(BigDecimal divisor)This method returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down.
    16BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc)This method returns a BigDecimal whose value is the integer part of (this / divisor).
    17double doubleValue()This method converts the BigDecimal to a double.
    18boolean equals(Object x)This method compares the BigDecimal with the specified Object for equality.
    19float floatValue()This method converts the BigDecimal to a float.
    20int hashCode()This method returns the hash code for this BigDecimal.
    21int intValue()This method converts the BigDecimal to an int.
    22int intValueExact()This method converts the BigDecimal to an int, checking for lost information.
    23long longValue()This method converts the BigDecimal to a long.
    24long longValueExact()This method converts the BigDecimal to a long, checking for lost information.
    25BigDecimal max(BigDecimal val)This method returns the maximum of this BigDecimal and val.
    26BigDecimal min(BigDecimal val)This method returns the minimum of this BigDecimal and val.
    27BigDecimal movePointLeft(int n)This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left.
    28BigDecimal movePointRight(int n)This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right.
    29BigDecimal multiply(BigDecimal multiplicand)This method returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).
    30BigDecimal multiply(BigDecimal multiplicand, MathContext mc)This method returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings.
    31BigDecimal negate()This method returns a BigDecimal whose value is (+this), and whose scale is this.scale().
    32BigDecimal negate(MathContext mc)This method returns a BigDecimal whose value is (-this), with rounding according to the context settings.
    33BigDecimal plus()This method returns a BigDecimal whose value is (+this), and whose scale is this.scale().
    34BigDecimal plus(MathContext mc)This method returns a BigDecimal whose value is (+this), with rounding according to the context settings.
    35BigDecimal pow(int n)This method returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision.
    36BigDecimal pow(int n, MathContext mc)This method returns a BigDecimal whose value is (thisn).
    37int precision()This method returns the precision of this BigDecimal.
    38BigDecimal remainder(BigDecimal divisor)This method converts this BigDecimal to a byte, checking for lost information.
    39BigDecimal remainder(BigDecimal divisor, MathContext mc)This method returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings.
    40BigDecimal round(MathContext mc)This method returns a BigDecimal rounded according to the MathContext settings.
    41int scale()This method returns the scale of this BigDecimal.
    42BigDecimal scaleByPowerOfTen(int n)This method returns a BigDecimal whose numerical value is equal to (this * 10n).
    43BigDecimal setScale(int newScale)This method returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal’s.
    44BigDecimal setScale(int newScale, int roundingMode)This method returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value.
    45BigDecimal setScale(int newScale, RoundingMode roundingMode)This method returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value.
    46short shortValueExact()This method converts the BigDecimal to a short, checking for lost information.
    47int signum()This method returns the signum function of this BigDecimal.
    48BigDecimal stripTrailingZeros()This method returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.
    49BigDecimal subtract(BigDecimal subtrahend)This method returns a BigDecimal whose value is (this – subtrahend), and whose scale is max(this.scale(), subtrahend.scale()).
    50BigDecimal subtract(BigDecimal subtrahend, MathContext mc)This method returns a BigDecimal whose value is (this – subtrahend), with rounding according to the context settings.
    51BigInteger toBigInteger()This method converts the BigDecimal to a BigInteger.
    52BigInteger toBigIntegerExact()This method converts the BigDecimal to a BigInteger, checking for lost information.
    53String toEngineeringString()This method returns a string representation of this BigDecimal, using engineering notation if an exponent is needed.
    54String toPlainString()This method returns a string representation of this BigDecimal without an exponent field.
    55String toString()This method returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.
    56BigDecimal ulp()This method returns the size of an ulp, a unit in the last place, of this BigDecimal.
    57BigInteger unscaledValue()This method returns a BigInteger whose value is the unscaled value of this BigDecimal.
    58static BigDecimal valueOf(double val)This method translates a double into a BigDecimal, using the double’s canonical string representation provided by the Double.toString(double) method.
    59static BigDecimal valueOf(long val)This method translates a long value into a BigDecimal with a scale of zero.
    60static BigDecimal valueOf(long unscaledVal, int scale)This method translates a long unscaled value and an int scale into a BigDecimal.
  • Clock 

    Introduction

    The java.time.Clock class provides access to the current instant, date and time using a time-zone.

    Class declaration

    Following is the declaration for java.io.Clock class −

    public abstract class Clock
       extends Object
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class constructors

    Sr.No.Constructor & Description
    1protected Clock()This creates a Clock.

    Class methods

    Sr.No.Method & Description
    1boolean equals(Object obj)This method checks if this clock is equal to another clock.
    2static Clock fixed(Instant fixedInstant, ZoneId zone)This method obtains a clock that always returns the same instant.
    3abstract ZoneId getZone()This method gets the time-zone being used to create dates and times.
    4int hashCode()This method gets a hash code for this clock.
    5int instant()This method gets the current instant of the clock.
    6long millis()This method gets the current millisecond instant of the clock.
    7static Clock offset(Clock baseClock, Duration offsetDuration)This method obtains a clock that returns instants from the specified clock with the specified duration added.
    8static Clock system(ZoneId zone)This method obtains a clock that returns the current instant using best available system clock.
    9static Clock systemDefaultZone()This method obtains a clock that returns the current instant using the best available system clock, converting to date and time using the default time-zone.
    10static Clock systemUTC()This method obtains a clock that returns the current instant using the best available system clock, converting to date and time using the UTC time-zone.
    11static Clock tick(Clock baseClock, Duration tickDuration)This method obtains a clock that returns instants from the specified clock truncated to the nearest occurrence of the specified duration.
    12static Clock tickMinutes(ZoneId zone)This method obtains a clock that returns the current instant ticking in whole minutes using best available system clock.
    13static Clock tickSeconds(ZoneId zone)This method obtains a clock that returns the current instant ticking in whole seconds using best available system clock.
    14static Clock withZone(ZoneId zone)This method returns a copy of this clock with a different time-zone.

    Methods inherited

    This class inherits methods from the following classes −

    • Java.lang.Object
  • Examples of Logical Operators

    Following are various examples of Logical Operators using regular expression in java.

    Sr.NoConstruct & Matches
    1XYX followed by Y.
    2X|YEither X or Y.
  • Examples of Possessive Quantifiers

    A possessive quantifier is similar to greedy quantifier. It indicates the engine to start by checking the entire string.It is different in the sense if it doesn’t work, if match failed and there is no looking back. Following are various examples of Possessive Quantifiers using regular expression in java.

    Sr.NoConstruct & Matches
    1X?+X, once or not at all.
    2X*+X, zero or more times
    3X++X, one or more times.
    4X{n}+X, exactly n times.
    5X{n,}+X, at least n times.
    6X{n,m}+X, at least n but not more than m times
  • Examples of Reluctant Quantifiers

    A reluctant quantifier indicates the search engine to start with the shortest possible piece of the string. Once match found, the engine continue; otherwise it adds one character to the section of the string being checked and search that, and so on. This process follows until it finds a match or the entire string has been used up. Following are various examples of Reluctant Quantifiers using regular expression in java.

    Sr.NoConstruct & Matches
    1X??X, once or not at all.
    2X*?X, zero or more times
    3X+?X, one or more times.
    4X{n}?X, exactly n times.
    5X{n,}?X, at least n times.
    6X{n,m}?X, at least n but not more than m times