In Java, is declaring/initializing primitives the same as declaring/initializing new objects? Primitives can be initialized with a literal, but what is the format for objects.
CodePudding user response:
It's not quite the same but very similar. Both follow the rule:
datatype variablename = value;
Examples:
int i = 0;
Car c = new Car();
Primitive types have literals like numbers (int, double...), boolean (true/false) or a character (char). Objects are objects of a class. A class is a template for something and while initializing that template a new object of that class is created. In the example above c
is an object of the class Car
.
The class has to exist. The are may classes delivered by Java like String
:
String name = new String("John Doe");
String name = "John Doe";
But you can make your own classes, e.g..
public class MyClass {
private int i;
public MyClass(int i) {
this.i = i;
}
}
You can read up on classes e.g. here. Classes are one of the main concepts of Object-oriented programming (OOP).
CodePudding user response:
Nope.
You use new
to initialize an Object
and as you stated you use a literal
to initialize a primitive
.
I suggest checking out https://docs.oracle.com/javase/tutorial/java/index.html for a helpful guide.