×

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is therefore extended by all Java classes. In order to inherit the class, we do not need to write the following statement.

Class Main extends object

Internally, the subclass inherits all of the Object class's methods. As a result, we can argue that Java's Object class is the universe's superclass. The java.lang package contains the class.

Java Object Class: Any object of any kind may be referenced by a variable of type Object belonging to the Cosmic Superclass.

Two objects that point to the same memory are tested using the Object class' equals() function.

If we wish to define an object's equality on our own, we must override the equals() method.

Replace the default function toString()method to print the class's representation.

The Java compiler calls the function toString() function every time an object is concatenated to a String with the "+" operator.

To print the class name and an object's memory location, the Object class provides the function toString()method.

Trace debugging is made easy with the function toString()technique.

MethodDescription
ObjectClone()It makes an object's copy.
boolean equals(Object obj)Determines whether two objects are equal. This  technique compares the references of two variables rather than the contents of two objects.
String toString()It returns a string representation of the object when you call string function
int hashCode()Integer is returned within the range

Compare objects in Java

The super class of all Java classes is the Java Object class. By default, every Java class implements the Object class. The equals() and hashCode() methods for comparing two Java objects are provided by the Java Object class. This section explains the operation of the equals() and hashCode() methods.

Program to compare to objects of class

Compare.java

// importing required packages 
// import util package to take the user input during run time using scanner class
import java.util.*;
import java.io.*;
// class 
public class Compare  
{    
// Main section of the program where execution of the program starts
public static void main(String args[])     
{    
// creating object for Scanner class with name sc
System.out.println(" Enter the strings which need to be compared ");
Scanner sc = new Scanner ( System . in ) ;
// Accessing the object of the Scanner class to take the inputs from the user
// Storing the inputs in string variable s1
String s1 = sc . next ( ) ;
// Storing the inputs in string variable s2
String s2 = sc . next ( ) ;
// Storing the inputs in string variable s3
String s3 = sc . next ( ) ;
// Checking the reference ids of two strings s1 and s2
System.out.println( " Are s1 and s2 strings are equal "+ s1.equals(s2) ) ;  
// Checking the reference ids of two strings s2 and s1
System . out . println  ( " Are s2 and s1 strings are equal "+ s2.equals(s1) ) ;  
// Checking the reference ids of two strings s2 and s3
System . out . println ( " Are s3 and s2 strings are equal "+ s2.equals(s3) ) ;   
}    
}  

Output

Cosmic Superclass in Java

ToString()

To return a string representation of an object, use the function toString() { [native code] } function. The function toString() function is internally called by the Java compiler whenever any object is printed. If not, the function toString()  function that was user-implemented or modified is invoked.To represent  the object in string  the function toString () is used .

Program to convert into strings

ConvertStrings.java

 // importing the necessary package
import java.util.*;
public classConvertStrings  
{    
int c; 
// default constructor for the program
ConvertStrings()     
{     
// Creating Scanner classs object to read the inputs
Scanner sc=new Scanner(System.in);
// storing the value in integer variable a
int a=sc.nextInt();
// storing the value in integer variable b
int b=sc.nextInt();
System.out.println("The sum of integers is: ");    
// caluclating the sum of a and b
c=a+b;    
System.out.println("The sum is: "+c);            
}         
// Main section of the code where execution of the program starts
public static void main(String args[])     
{     
// creating object for the Main class with name o1
Main o1 = new Main();      
System.out.println(o1.toString());     
}      
}   

Output

Cosmic Superclass in Java

Object Clone

The most crucial activity in Java is making a copy or clone of an object. A reference copy, as the name suggests, creates a duplicate of a reference variable referring to an object. For instance, if we create a reference copy of a Byke object that already has a myByke variable referring to it, the original object will still exist.A copy of an object is made of the actual object. Therefore, if we cloned our byte object once again, we would make a copy of the object and a second reference variable that pointed to it.A shallow duplicate of an object is a brand-new object with the same instance variables as the original object. A shallow clone of a Set, for instance, shares objects with the original Set by pointers and has the same members as the original Set. It's sometimes claimed that shallow copies employ reference semantics. references are replicated just superficially. As a result, the reference is the same for both the original and the object. the process of creating a new reference to the same memory location. Keep in mind that any modifications we make to the data in the cloned object also affect the original.

Advantages  of object cloning

• Object. Despite these design issues, clone() is still a frequently used and straightforward technique of cloning objects.

• Long, repetitive codes are not required.

• Only use abstract classes with 4- or 5-line clone() methods. It is the easiest and most efficient way to duplicate stuff, especially if we're integrating it to an old or older project.

Simply constructing a parent class, including Cloneable implementation, and supplying the definition of the clone() function will suffice to finish the task.

• Using clone is the easiest way to duplicate an array ().

Disadvantages  of object cloning

• To utilise the Object.clone() function while implementing a Cloneable interface, declare the clone() method, solve the CloneNotSupportedException, and afterwards call Object.clone().

• Despite the fact that it lacks methods, we still have to create a cloneable interface. We merely need to make use of it to let the JVM know that we can clone() our object.

We must provide our own clone() and call Object.clone() indirectly from it since Object.clone() is protected.

We have really no control about how an object is created since Object.clone() does not invoke any function Object().

Program for cloning objects

Clone.java

class Clone implements Cloneable {  
int id ;  
String s ;  
Clone ( String s , int id ) 
{  
this . id = id ;  
this. s = s ;  
}  
public Object clone ( ) throws CloneNotSupportedException
{  
return super . clone ( ) ;  
}  
public static void main ( String args [ ] )
{  
try  {  
Clone s1=new Clone ( "Rohith" ,9 ) ;  
Clone s2 = (Clone)s1 . clone ( ) ;  
System . out . println ( " Name is " + s1 . s+ "  and rollno is " + s1 . id );  
System . out . println ( " Name is " + s2 . s + " and rollno is " + s2 . id ) ;  
} catch ( CloneNotSupportedException c )
{
}  
}  
}

Output

Cosmic Superclass in Java

Hashcode

The hash code for the supplied inputs is returned by the Java Integer class function hashCode(). Java's hashCode() function comes in two varieties that may be distinguished by their respective parameters.

hashCode() Technique

The Java Integer Class's hashCode() function finds the hash code for a specified Integer. In the class Object, it overrides hashCode. This function by default produces a random, instance-specific number.

 hashCode(int value)

A hash code is generated for a given int value using the built-in Java Integer Class function hashCode(int value). Integer and this technique work together. hashCode().

Code for hashcode program

import java.io.*;
import java.util.*;
public class IntegerHashCode {  
    public static void main ( String[] args )  
    {  
        
        Integer r = new Integer ( "113" ) ;           
        int hashValue = r . hashCode ( ) ;  
        System . out . println ( "Hash code Value for object is: " + hashValue ) ;  
    }  
}  

Output

Cosmic Superclass in Java

HashCode2.java

import java.util.Scanner;  
public class HashCode2{  
    public static void main(String[] args) {  
      System.out.print("Enter the desired input value: ");  
      Scanner sc = new Scanner(System.in);         
        Integer i = sc.nextInt();  
        sc.close();  
        int h = Integer.hashCode(i);  
        System.out.println("Hash code Value for object is: " + h);  
        }  
}  

Output

Cosmic Superclass in Java

Related Topics

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

Java throw

Java throw Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either...

3 minutes read.