JAVA.LANG.PACKAGES

SNEHAL MANE
13 min readMay 31, 2021

--

Java.lang package contains the classes that are fundamental to the design of the Java programming language. Object is the ultimate superclass of all Java classes and is therefore at the top of all class hierarchies. Class is a class that describes a Java class. There is one Class object for each class that is loaded into Java. Boolean, Character, Byte, Short, Integer, Long, Float, and Double are immutable class wrappers around each of the primitive Java data types. These classes are useful when you need to manipulate primitive types as objects. They also contain useful conversion and utility methods.

String and StringBuffer are objects that represent strings. String is an immutable type, while StringBuffer can have its string changed in place. In Java 1.2 and later, all these classes (except StringBuffer) implement the Comparable interface, which enables sorting and searching algorithms. The Math class (and, in Java 1.3, the Strict Math class) defines static methods for various floating-point mathematical functions. This blog will take you through some important methods available in java.lang package using simple and practical example.

SOME IMPORTANT JAVA.LANG.PACKAGES

  1. Object
  2. Math
  3. Wrapper classes
  4. String
  5. String Buffer

OBJECT

Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a Class does not extend any other class then it is direct child class of Object and if extends other class then it is an indirectly derived. Therefore the Object class methods are available to all Java classes. Hence Object class acts as a root of inheritance hierarchy in any Java Program.

Declaration

Following is the declaration for java.lang.Object class –

public class Object

Constructor & Description

Object()

This is the Single Constructor.

Class methods

Method & Description

  1. protected Object clone()

This method creates and returns a copy of this object.

2. boolean equals(Object obj)

This method indicates whether some other object is “equal to” this one.

3. protected void finalize()

This method is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

4. Class<?> getClass()

This method returns the runtime class of this Object.

5. int hashCode()

This method returns a hash code value for the object.

6. void notify()

This method wakes up a single thread that is waiting on this object’s monitor.

7. void notifyAll()

This method wakes up all threads that are waiting on this object’s monitor.

8. String toString()

This method returns a string representation of the object.

9. void wait()

This method causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

10. void wait(long timeout)

This method causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

11. void wait(long timeout, int nanos)

This method causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

Source : https://www.tutorialspoint.com/java/lang/java_lang_object.htm

EXAMPLE

public static void main(String[] args)

{

Student s = new Student();

//by to string method

System.out.println(s.toString());

}

MATH

Java Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc. In this article, we will learn about the Java Math class, its basic methods and constructors provided by Java programming language.

Math class declaration

Following is the declaration for java.lang.Math class

public final class Math

extends Object

What is NaN value in Math class?

Nan is produced if a floating-point operation has some input parameters that cause the operation to produce some undefined result

For example, 0.0 divided by 0.0 Finding out the square root of a negative number

  1. The numerical comparison operators <, <=, >, and >= always return false if either or both operands are NaN.(§15.20.1)
  2. The equality operator == returns false if either operand is NaN.
  3. The inequality operator != returns true if either operand is NaN.

Class Methods

Method & Description

  1. static double abs()

This method returns the absolute value of the argument.

2. static acos(a)

This method returns the arc cosine of a value; the returned angle is in the range 0.0 through pi.

3. static asin(a)

This method returns the arc sine of a value; the returned angle is in the range -pi/2 through pi/2.

4. max(a, b)

This method returns the greater of two long values.

5. min( a, b)

This method returns the smaller of two double values.

6. static double nextAfter(double start, double direction)

This method returns the floating-point number adjacent to the first argument in the direction of the second argument.

7. static float nextUp(float f)

This method returns the floating-point value adjacent to f in the direction of positive infinity.

8. static double random()

This method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

9. static long round(double a)

This method returns the closest long to the argument.

10. static double sqrt(double a)

This method returns the correctly rounded positive square root of a double value.

11. static double toRadians(double angdeg)

This method converts an angle measured in degrees to an approximately equivalent angle measured in radians.

12. static double sin(double a)

This method returns the hyperbolic sine of a double value.

13. static double cos(double a)

This method returns the trigonometric cosine of an angle

14. static double log(double a)

This method returns the natural logarithm (base e) of a double value.

15. static double log10(double a)

This method returns the base 10 logarithm of a double value.

17. static double pow(double a, double b)

This method returns the value of the first argument raised to the power of the second argument.

Source : https://www.tutorialspoint.com/java/lang/java_lang_math.htm

The complete example program of java.lang.Math class is listed below.

import java.lang.Math;

public class MathClass {

public static void main(String[] args) {

double x = 28;

double y = 4;

System.out.println(“Maximum number of x and y is: “ + Math.max(x, y));

System.out.println(“Square root of y is: “ + Math.sqrt(y));

System.out.println(“Power of x and y is: “ + Math.pow(x, y));

System.out.println(“Logarithm of x is: “ + Math.log(x));

System.out.println(“Logarithm of y is: “ + Math.log(y));

System.out.println(“return the logrithn of log10 of x is: “ + Math.log10(x));

}

}

The above program generates the following output.

Wrapper class

Each of Java’s eight primitive data types has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. The wrapper classes are part of the java.lang package, which is imported by default into all Java programs.

The wrapper classes in java servers two primary purposes.

  1. To provide a mechanism to ‘wrap’ primitive values in an object so that primitives can do activities reserved for the objects like being added to ArrayList, Hashset, HashMap etc. collection.
  2. To provide an assortment of utility functions for primitives like converting primitive types to and from string objects, converting to various bases like binary, octal or hexadecimal, or comparing various objects.

The following two statements illustrate the difference between a primitive data type and an object of a wrapper class:

int x = 85;

Integer y = new Integer(45);

The first statement declares an int variable named x and initializes it with the value 25. The second statement instantiates an Integer object. The object is initialized with the value 33 and a reference to the object is assigned to the object variable y.

Below table lists wrapper classes in Java API with constructor details.

As explain in above table all wrapper classes (except Character) take String as argument constructor. Please note we might get NumberFormatException if we try to assign invalid argument in the constructor. For example to create Integer object we can have the following syntax.

Integer intObj = new Integer (25);

Integer intObj2 = new Integer (“25”);

Here in we can provide any number as string argument but not the words etc. Below statement will throw run time exception (NumberFormatException)

Integer intObj3 = new Integer (“Two”);

The following discussion focuses on the Integer wrapperclass, but applies in a general sense to all eight wrapper classes.

The most common methods of the Integer wrapper class are summarized in below table. Similar methods for the other wrapper classes are found in the Java API documentation.

Method

  1. parseInt(s)

returns a signed decimal integer value equivalent to string s

2. toString(i)

returns a new String object representing the integer i

3. byteValue()

returns the value of this Integer as a byte

4. doubleValue()

returns the value of this Integer as a double

5. floatValue()

returns the value of this Integer as a float

6. intValue()

returns the value of this Integer as an int

7. shortValue()

returns the value of this Integer as a short

8. longValue()

returns the value of this Integer as a long

9. int compareTo(int i)

Compares the numerical value of the invoking object with that of i. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value. Returns a positive value if the invoking object has a greater value.

10. static int compare(int num1, int num2)

Compares the values of num1 and num2. Returns 0 if the values are equal. Returns a negative value if num1 is less than num2. Returns a positive value if num1 is greater than num2.

11. boolean equals(Object intObj)

Returns true if the invoking Integer object is equivalent to intObj. Otherwise, it returns false.

Autoboxing: Converting a primitive value into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer class. The Java compiler applies autoboxing when a primitive value is:

  1. Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  2. Assigned to a variable of the corresponding wrapper class.

Unboxing: Converting an object of a wrapper type to its corresponding primitive value is called unboxing. For example conversion of Integer to int. The Java compiler applies unboxing when an object of a wrapper class is:

  1. Passed as a parameter to a method that expects a value of the corresponding primitive type.
  2. Assigned to a variable of the corresponding primitive type.

To create a wrapper object, use the wrapper class instead of the primitive type. To get the value, you can just print the object. Since you’re now working with objects, you can use certain methods to get information about the specific object.

For example, the following methods are used to get the value associated with the corresponding wrapper object

public class main{

public static void main(String[] args) {

//creating wrapper object

Integer myInt = 9;

//by int method

System.out.println(myInt.intValue());

//toString() method

String myString = myInt.toString();

System.out.println(myString.length());

}

Another useful method is the toString() method, which is used to convert wrapper objects to strings.In the above example, we convert an Integer to a String, and use the length() method of the String class to output the length of the "string".

Source : https://www.w3resource.com/java-tutorial/java-wrapper-classes.php

STRING

In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example:

Char[] ch = {‘j’, ‘a’, ‘v’, ‘a’, ‘s’, ‘t’, ‘i’, ’n’, ‘g’}

String s = new String(ch);

is same as:

String s = new String(ch);

Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

Method & Description

  1. char charAt(int index)

returns char value for the particular index

2. int length()

returns string length

3. static String format(String format, Object… args)

returns a formatted string.

4. static String format(Locale l, String format, Object… args)

returns formatted string with given locale.

5. String substring(int beginIndex)

returns substring for given begin index.

6. String substring(int beginIndex, int endIndex)

returns substring for given begin index and end index.

7. boolean contains(CharSequence s)

returns true or false after matching the sequence of char value

8. static String join(CharSequence delimiter, CharSequence… elements)

returns a joined string.

9. static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

returns a joined string.

10. boolean equals(Object another)

checks the equality of string with the given object.

11. boolean isEmpty()

checks if string is empty

12. String concat(String str)

concatenates the specified string.

13. String replace(char old, char new)

replaces all occurrences of the specified char value.

14. String replace(CharSequence old, CharSequence new)

replaces all occurrences of the specified CharSequence.

15. static String equalsIgnoreCase(String another)

compares another string. It doesn’t check case.

16. String[] split(String regex)

returns a split string matching regex.

17. String[] split(String regex, int limit)

returns a split string matching regex and limit

18. String intern()

returns an interned string.

19. int indexOf(int ch)

returns the specified char value index

20. int indexOf(int ch, int fromIndex)

returns the specified char value index starting with given index.

21. int indexOf(String substring)

returns the specified substring index.

22. int indexOf(String substring, int fromIndex)

returns the specified substring index starting with given index.

23. String toLowerCase()

returns a string in lowercase.

24. String toLowerCase(Locale l)

returns a string in lowercase using specified locale.

25. String toUpperCase()

returns a string in uppercase.

26. String toUpperCase(Locale l)

returns a string in uppercase using specified locale.

27. String trim()

removes beginning and ending spaces of this string.

28. static String valueOf(int value)

converts given type into string. It is an overloaded method.

Source : https://www.javatpoint.com/java-string

String Example

public static void main(String args[]){

String s = “java”;

//toCharArray method()

char[] arr ;

arr =s.toCharArray();

}

String constant pool

  1. A string constant pool is a separate place in the heap memory where the values of all the strings which are defined in the program are stored.
  2. When we declare a string, an object of type string is created in the stack, while an instance with the value of the string is created in the heap.
  3. Object creation is optional in SCP, First JVM will check that is the object already exists or not if it exists then it will reuse that object.

Importance of SCP:-

  1. For the large number of object there is no need to create new objects only one object can be there and rest are reference.
  2. So it provides us reusability and memory utilization

STRING BUFFER

The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. Following are the important points about StringBuffer −

  1. A string buffer is like a String, but can be modified.
  2. It contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
  3. They are safe for use by multiple threads.
  4. Every string buffer has a capacity.

Class Declaration

Following is the declaration for java.lang.StringBuffer class –

public final class StringBuffer

extends object

Implements Serialization, CharSequence

Class constructors

Constructor & Description

  1. StringBuffer()

This constructs a string buffer with no characters in it and an initial capacity of 16 characters.

2. StringBuffer(CharSequence seq)

This constructs a string buffer that contains the same characters as the specified CharSequence.

3. StringBuffer(int capacity)

This constructs a string buffer with no characters in it and the specified initial capacity.

4. StringBuffer(String str)

This constructs a string buffer initialized to the contents of the specified string.

Class methods

Method & Description

  1. StringBuffer append(boolean b)

This method appends the string representation of the boolean argument to the sequence

2. int capacity()

This method returns the current capacity.

3. char charAt(int index)

This method returns the char value in this sequence at the specified index.

4. int codePointAt(int index)

This method returns the character (Unicode code point) at the specified index

5. int codePointBefore(int index)

This method returns the character (Unicode code point) before the specified index

6. int codePointCount(int beginIndex, int endIndex)

This method returns the number of Unicode code points in the specified text range of this sequence

7. StringBuffer delete(int start, int end)

This method removes the characters in a substring of this sequence.

8. void ensureCapacity(int minimumCapacity)

This method ensures that the capacity is at least equal to the specified minimum.

9. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

This method characters are copied from this sequence into the destination character array dst.

10. int indexOf(String str)

This method returns the index within this string of the first occurrence of the specified substring.

11. StringBuffer insert(int offset, boolean b)

This method inserts the string representation of the boolean argument into this sequence.

12. int lastIndexOf(String str)

This method returns the index within this string of the rightmost occurrence of the specified substring.

13. int length()

This method returns the length (character count).

14. int offsetByCodePoints(int index, int codePointOffset)

This method returns the index within this sequence that is offset from the given index by codePointOffset code points.

15. StringBuffer replace(int start, int end, String str)

This method replaces the characters in a substring of this sequence with characters in the specified String.

16. StringBuffer reverse()

This method causes this character sequence to be replaced by the reverse of the sequence.

17. void setCharAt(int index, char ch)

The character at the specified index is set to ch.

18. void setLength(int newLength)

This method sets the length of the character sequence.

19. CharSequence subSequence(int start, int end)

This method returns a new character sequence that is a subsequence of this sequence.

20. String substring(int start)

This method returns a new String that contains a subsequence of characters currently contained in this character sequence

21.String toString()

This method returns a string representing the data in this sequence.

22. void trimToSize()

This method attempts to reduce storage used for the character sequence.

Source :https://www.tutorialspoint.com/java/lang/java_lang_stringbuffer.htm

EXAMPLE

Import java.io.*;

class StringBuffer{

public static void main(String[] args)

{

//by reverse() method

//to reverse the string

StringBuffer s = new StringBuffer(“String Buffer”);

s.reverse();

System.out.println(s);

}

}

Difference between String, StringBuffer and StringBuilder

Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. There are many differences between StringBuffer and StringBuilder. The StringBuilder class is introduced since JDK 1.5.

SOME OTHER IMPORTANT POINTS

1. Cloneable

A class implements the Cloneable interface to indicate to the clone method in class Object that it is legal for that method to make a field-for-field copy of instances of that class.

2. SecurityManager

The security manager is an abstract class that allows applications to implement a security policy

3. Exceptions

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

4. Errors

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions

5. ClassLoader

The class ClassLoader is an abstract class. Applications implement subclasses of ClassLoader in order to extend the manner in which the Java Virtual Machine dynamically loads classes.

--

--

SNEHAL MANE

Student Of Vishwakarma Institute Of Technology, Pune.