×

Java Class Name

How to write a class name?

The following considerations should be made while writing class names.

  • The name of the current class shouldn't be based on a preset or existing class.
  • Java keywords shouldn't be used as class names.
  • The class name should begin with a capital letter and end with a tiny letter (mixed case).
class Example

Every word in the name should start with a capital letter, and the other characters should be small.

class Main

It is advised to keep interface names short and descriptive.

It is preferable to avoid acronyms when writing class names.

Example

Main.java

public class Main {
   public void Method1 ( ) {
      System . out . println ( " In  Method1 " ) ;   
   }
   public void Method2 ( ) {
      System . out . println ( " In Method 2 " ) ;   
   }
   public static void main ( String args [ ] ) {
      Main o1 = new Main ( ) ;
      o1 . Method1 ( ) ;
      o1 . Method2 ( ) ;
   }
}

Output

This is sample method
This is demo method

There are four methods on the Class API that can be used to get the name of a class: getSimpleName(), getName(), getTypeName(), and getCanonicalName ().

GetSimpleName() Method

There are two categories of names in Java: qualified and simple. A qualified name is a list of simple names separated by dots, whereas a simple name is an individual identifier.

GetSimpleName(), as its name implies, returns the underlying class's simple name, which is the name specified for it in the source code.

package com.baeldung.className;
public class RetrieveClassName {}

RetrieveClassName: would be its short name.

assertEquals("RetrieveClassName",RetrieveClassName.class.getSimpleName())); 

Primitive types and arrays can also be given short names. For primitive types like int, boolean, and float, that will just be their names.

Additionally, the method will return an array's type in its simplest form, followed by opening and closing braces for each dimension ([]):

RetrieveClassName[] n = new RetrieveClassName[];
assertEquals("RetrieveClassName[]", n.getClass().getSimpleName());

Finding Additional Names

We should now examine how we might discover a class's name, type name. These names seek to provide more details about the class than getSimpleName() does.

The canonical name as specified in the Java Language Specification is always returned by the getCanonicalName() function.

In terms of the other ways, the results may vary slightly depending on the use cases. We'll explore what that means for various object and primitive types.

Primitive Types 

Since primitive types are the most basic, let's start with them. The results of the three methods getName(), getTypeName(), and getCanonicalName() for primitive types are identical to those of getSimpleName().

Object Types

We'll see how these techniques function with object types in a moment. They all return the class's canonical name, which is normally how they behave.

Most of the time, this is a qualified name that also includes the class simple name and all of the class package simple names.

Inner Classes

The majority of these method calls behave as we've seen in the previous section, but there are a few outliers.

One of them is inner classes. When used to inner classes, the getName() and getTypeName() methods act differently than the getCanonicalName() method.

The canonical name of the class, which is the canonical name of the enclosing class plus the simple name of the inner class separated by a dot, is still returned by the getCanonicalName() method.

Anonymous Classes

They lack a canonical name as well as a simple name, as we have already shown. Consequently, getCanonicalName() returns nothing. When invoked on an anonymous class, getCanonicalName() will return null rather than an empty string, in contrast to getSimpleName().

The canonical name of the calling class, a dollar amount, and a number denoting the anonymous class's position among all other anonymous classes formed in the calling class are returned by the getName() and getTypeName() functions, respectively.

Arrays

Finally, let's look at how the aforementioned three approaches deal with arrays.Each method will adjust its typical result to reflect the fact that we are working with arrays. The results of the getTypeName() and getCanonicalName() functions will have bracketed pairs appended to them.To distinguish the inner class portion from the remainder of the name, the first call utilises a dollar sign in place of a dot.


Related Topics

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.