116

Being new to Java, I'm confused between the concepts of class and type. For example, should the object "Hello World!" belong to the type String or class String? Or maybe both?

Paul Bellora
  • 51,514
  • 17
  • 127
  • 176
user2236096
  • 1,347
  • 3
  • 11
  • 19
  • 1
    Not silly at all. I think a type is the general case. A class is a specific case of type as is interface which I've heard called a "pure" type. – Hovercraft Full Of Eels May 17 '13 at 03:06
  • 1
    +1 for what seems like a genuine question. – nico_c May 17 '13 at 03:13
  • I see a voting war going on between the negatives and the positives :-D – Thihara May 17 '13 at 03:13
  • 30
    Lately there seems to be an inclination to downvote any "beginner" style questions whether they're good or not. Its annoying, to say the least. – nico_c May 17 '13 at 03:16
  • 11
    Also to downvote any question that the voter doesn't understand ... – user207421 May 17 '13 at 03:17
  • 4
    I agree it's kind of rude to downvote as you say beginner questions, but whether is good or bad, all beginner questions have their answers just by searching the web. The problem and the reason people are downvoting is because this is leading to stack overflow :) – Marko Lazić May 17 '13 at 03:24
  • 15
    This is a great question - and the 3 votes to close are why we need to be able to vote to *keep open*. I still remember back when I was learning Java that the OO jargon was the biggest impediment. – Lawrence Dol May 17 '13 at 03:30
  • 2
    It's a not-bad question and surely doesn't warrant down-votes or close-votes, but I'm not sure I'd classify it as a "great" question. – Hovercraft Full Of Eels May 17 '13 at 03:43
  • 1
    It seems like the Java "camp" is more intolerant than for example C# where I don't see as many downvoted questions. I wonder why? – maba May 17 '13 at 05:28
  • 4
    @nickecarlo There used to be a point in the FAQ, which seems to be taken out during the last year or so -- "the question shows serious lack of research and doesn't show signs of effort done to resolve it before asking the question". I find it annoying that there's A TON of bullshit questions that Google could solve instead of people here actually wasting their time explaining "programming 101" to others. – TC1 May 17 '13 at 08:04
  • 1
    @TC1 is completely correct - if I didn't think it'd get removed for being rude, I'd comment on quite a lot of questions here with a "lmgtfy" link. These are distinctly _bad_ questions because they show no research effort - as such, they should be downvoted, unless we're accessing different versions of the downvote hover text – Matt Taylor May 17 '13 at 08:08
  • If you don't downvote you are eventually going to have a lot of questions like this, and all of us are going to miss that interesting one to help a fellow at need. Even with all comments and a proper answer, why didn't he accepted the correct offered answer? At least that, like a sign of good will – Marko Lazić May 17 '13 at 12:47
  • 3
    This is a legitimate question and shouldn't be closed unless a duplicate can be found. It was valid and clear from the beginning, but I tried to improve it with my edit. – Paul Bellora May 17 '13 at 15:41
  • 4
    @MattTaylor I am not very active on Stack Overflow, but still want to share my perspective. For me,as far as programming questions is concerned, Stack Overflow is almost the entire web, because it pops up all the times. How is this possible? Because, Stack Overflow seems to care to provide the answers to all valid questions, even simple ones. It does not say, "go see elsewhere for the answer.". Your comment goes in the opposite direction. Your comment says, if it is elsewhere, this is where you must look. I prefer the view point of Paul Bellora. –  Sep 13 '15 at 18:09
  • 2
    six years later, and this is the first hit on my google search and it provides a quick answer that is to the point. Thank you. – Darren Mar 13 '19 at 15:09

6 Answers6

133

A class is a type. An interface is a type. A primitive is a type. An array is a type.

Therefore, every type is also either a class (including an enum constant), an interface, a primitive, or an array.

There are two distinct categories of types: primitive types and reference types:

  • A variable of primitive type always holds a primitive value of that same type. Such a value can only be changed by assignment operations on that variable.
  • A variable of reference type always holds the value of a reference to an object. All objects, including arrays, support the methods of class Object. The reference types are class types (including enum types), interface types, and array types.

Every piece of data has a type which defines its structure, namely how much memory it takes up, how it is laid out, and more importantly, how you can interact with it.

Examples of primitive types:

  1. int
  2. float
  3. char
  4. boolean

Examples of class types:

  1. String
  2. Integer
  3. Boolean
  4. ArrayList
  5. StringBuilder

Examples of interface types:

  1. Collection
  2. List
  3. Map
  4. Serializable

Examples of array types:

  1. int[]
  2. String[]
  3. Integer[][][]

Basically, anything that you can refer to as a variable has a type, and classes are a kind of a type.

More info here: http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html

SOFe
  • 7,134
  • 4
  • 28
  • 57
Brandon
  • 9,047
  • 3
  • 25
  • 36
8

TLDR - Class is one of the Type in Java.

Note - To fully understand the answer, you must have a little idea about generics in Java.


To understand the difference let us first understand what a Type is in Java.

According to JLS SE 10 ,

There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3).

What is primitive Type ?

a) The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units (§3.1).

b) The floating-point types are float, whose values include the 32-bit IEEE 754 floating-point numbers, and double, whose values include the 64-bit IEEE 754 floating-point numbers.

c) The boolean type has exactly two values: true and false.

Now , let us come to what is reference type ?

There are four kinds of reference types: class types (§8.1), interface types (§9.1), type variables (§4.4), and array types (§10.1).

Let us discuss one by one.

If you see how in JLS , Class is defined like this :

A class declaration specifies a new named reference type.

There are two kinds of class declarations: normal class declarations and enum declarations.

ClassDeclaration:
NormalClassDeclaration 
EnumDeclaration
NormalClassDeclaration:
{ClassModifier} class TypeIdentifier [TypeParameters] [Superclass] [Superinterfaces] ClassBody

You see that [TypeParameters], this shows that class type includes those generic classes too.

class Example<T>{

}

The class type will be called Example

In short , a class type covers our enums , our regular (non generic) classes like String etc and our generic classes too.

Similarly , I hope interface and array types is also clear. By array Type we mean like int[], String[] etc.

Let us come to the last part - Type variables. What are they ?

A type variable is an unqualified identifier used as a type in class, interface, method, and constructor bodies.

Let us understand by the example in the JLS below it.

class Test {
    <T extends C & I> void test(T t) {  
        t.mI();           // OK
        t.mCPublic();     // OK 
        t.mCProtected();  // OK 
        t.mCPackage();    // OK

    } 
}

You see that your object in the method parameter is of type T. Yes , this T is Type variable and is/can be used as a reference . Yes it is. (Could not understand this strange example - Learn what is generic method in Java)

This completes the answer.

Number945
  • 3,732
  • 4
  • 34
  • 61
4

"Type" is the more inclusive category. Variables in Java can have three kinds of types: the 8 "primitive" types like int and float, interfaces, and classes. Values (as opposed to variables) can be primitive or class instances.

Lee Daniel Crocker
  • 12,296
  • 1
  • 24
  • 47
2

"Type" defines 'what type of data it is'

Ex: "hello world" is a String --> "hello world" is String type (String is not a premetive data unlike int .. so we can say "hello world" is a string class type)

10 is a int --> 10 is a integer data type.

Satya
  • 7,542
  • 9
  • 35
  • 39
1

This is a question about programming terminology, and as expected, there is yet another answer that could be considered valid.

The Java type system, as exposed by the reflection API, has two types: Class<T> class and Type interface, which the former implements. In this system, a class (an element that is described by an instance of Class<T>) is any type created with the keyword class or interface, any primitive type, any array thereof, and void. Everything else is just a Type.

So what is everything else? While a class in this context is everything the runtime sees and has access to when considering the capabilities of an object, a type, in general, is everything the compiler sees. This can be a parametrized type (like ArrayList<String> – remember that type erasure causes every ArrayList<T> to map to the same class at runtime), a generic type parameter created as a part of a method or class declaration, a wildcard type, and any array thereof. Those types are exposed by API methods in all places where type erasure is not in effect, like when traversing parameter types or base types.

IS4
  • 9,770
  • 2
  • 41
  • 69
0

Types are associated with compile-time entities such as variables and expressions, whilst classes are associated with run-time entities such as in-memory objects. Consider the language used in the specification 15.5. Expressions and Run-Time Checks

If the type of an expression is a reference type, then the class of the referenced object... An expression whose type is a reference type may be tested using instanceof to find out whether the class of the object referenced by the run-time value of the expression...

Robert Harper, author of Practical Foundations for Programming Languages, makes the following distinction

I do think it is important to distinguish carefully classes, which may be attached to objects, from types, which are static classifiers

Java generics are one example where this distinction is relevant. First consider the following snippet

String greeting = "Hello" + " " + "world!"; 
  • the compile-time type of the variable greeting is String
  • the compile-time type of the expression "Hello" + " " + "world!" is String
  • the run-time class of the instantiated object Hello world! referred to by variable greetings is String

It appears in the above case the distinction does not matter much, however let's try similar reasoning on the following snippet

List<String> greetings = List.of("Hello World!");
  • the compile-time type of the variable greetings is List<String>
  • the compile-time type of the expression new ArrayList("Hello World!") is List<String>
  • the run-time class of the instantiated object referred to by variable greetings is ImmutableCollections$List1

Now we see there is indeed a difference between type List<String> and class ImmutableCollections$List1. We see the compile-time type is "richer" in information where compiler is aware the element type is String whilst at run-time the element type information is lost due to type erasure.

Here is another demonstration of the difference between types and classes

jshell> /set feedback verbose
|  Feedback mode: verbose

jshell> List.of("Hi", "Hello")
$1 ==> [Hi, Hello]
|  created scratch variable $1 : List<String>

jshell> List.of(42, -11)
$2 ==> [42, -11]
|  created scratch variable $2 : List<Integer>

jshell> $1.getClass() == $2.getClass()
$3 ==> true
|  created scratch variable $3 : boolean

Note how types of expressions List.of("Hi", "Hello") and List.of(42, -11) are different, and yet the classes of corresponding instantiated objects are the same.

Mario Galic
  • 41,266
  • 6
  • 39
  • 76