Skip to content
Related Articles

Related Articles

Is there any equivalent to typedef of C/C++ in Java ?

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 09 Sep, 2022
Improve Article
Save Article

In one line, There is nothing in Java which is equivalent to typedef of C++. In Java, class is used to name and construct types or we can say that class is the combined function of C++’s struct and typedef. But that is totally different thing and not the equivalent of typedef anywhere. typedef: It is a keyword not a function that is used in C/C++ language to assign alternative names to existing data types. It is used with the user defined data types when the name of data types get little bit complicated that time the typedef keyword is used, unless it is unnecessary. Syntax of using typedef:

typedef existing_name alias_name;

C++




// C++ program to demonstrate typedef
#include <bits/stdc++.h>
using namespace std;
  
// After this line BYTE can be used
// in place of unshifted char
typedef unsigned char BYTE;
 
int main()
{
    BYTE b1, b2;
    b1 = 'a';
    cout << b1 ;
    return 0;
}
 
// This code is contributed by shubhamsingh10

C




// C program to demonstrate typedef
#include <stdio.h>
 
// After this line BYTE can be used
// in place of unshifted char
typedef unsigned char BYTE;
 
int main()
{
    BYTE b1, b2;
    b1 = 'a';
    printf("%c ", b1);
    return 0;
}

Output:

a

typedef with pointers: typedef will also work with the pointer in C/C++ language like renaming existing keywords. In case of pointers * binds in the right not the left side.

int* x, y;

In the above syntax, we are actually declaring x as a pointer of type int, whereas y will be declared as a plain integer But if we use typedef then we can declare any number of pointers in a single statement like below.

typedef int* IntPtr ;
IntPtr x, y, z;

typedef can be used for :

  • typedef can provide a simple name for a complicated type cast
  • typedef can also be used to give names to unnamed types. In such cases, the typedef will be the only name for said type

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!