Different ways to create an object in Java
Source:
Medium In this tutorial, we will learn different ways to create an object in Java. A Java object is an instance of a Java class. Each object has a state, a behavior, and an identifier. Fields (variables) store the state of an object, while methods (functions) show the action of an object. Classes serve as “blueprints” from which object instances are created at runtime.
Creating an Object in Java
Object creation is the process of allocating memory to store data in class fields (also called variables). This process is often called creating an instance of a class. There are four different ways to create objects in Java:
- using the new keyword
- method newInstance()
- clone() method
- deserializing an object
Now let's look at each of the mentioned methods in detail.
Keyword new
This is the most common way to create an object in Java.
The new keyword creates an instance of a class by allocating memory for a new instance of the specified type. After new comes the constructor - a special method responsible for creating an object and initializing the fields of the created object. An object is created with the
new operator and initialized with a constructor. Here is an example of creating a Java object with the
new operator :
Date today = new Date();
This expression generates a new
Date object (
Date is a class inside the
java.util package ). This single clause in the code performs three operations: declaration, instantiation, and initialization.
Date today is a variable declaration that informs the compiler that
today will refer to an object of type
Date . The new operator instantiates the
Date class (creating a new
Date object in memory), and
Date() initializes the object. Consider the example below:
public class Person {
private String name;
private int uid;
public Person() {
this.name = "Michael Cole";
this.uid = 101;
}
public Person(String name, int uid) {
super();
this.name = name;
this.uid = uid;
}
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person("John Bodgan", 102);
System.out.println("Name: " + p1.getName() + " UID: " + p1.getUid());
System.out.println("Name: " + p2.getName() + " UID: " + p2.getUid());
}
}
From this code, we create a
Person object using the new keyword :
- The p1 object calls a non-parameterized constructor with the variable name value set to “Michael Cole” and the UID set to 101.
- The p2 object calls the parameterized constructor, where it passes the value “John Bodgan” and 102 to the constructor. These values are then assigned a variable name and UID.
Using the newInstance() method
The newInstance() method in Java is used to dynamically create an instance of an object of a given class. There are two standard uses of the
newInstance() method :
- newInstance() method from java.lang.Class API
- newInstance() method from java.lang.reflect.Constructor API
Using newInstance() from the Class API
To create an object of a class at runtime, we must call the
newInstance() method from the Class API, which returns an object of that class.
The newInstance() method of
the java.lang.Class class does not take any parameters or arguments and can be called a no-argument constructor for that class. Let's look at some example code to create an object of the
Person class using the
newInstance() method of the java.lang.Class class :
public class Person {
private String name;
private int uid;
public Person() {
this.name = "Carl Max";
this.uid = 101;
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Class c = Class.forName("com.medium.option2.Person");
@SuppressWarnings("deprecation")
Person p = (Person) c.newInstance();
System.out.println("Name: " + p.getName());
System.out.println("UID: " + p.getUid());
}
}
Class.forName (the fully qualified name of the class) loads a class named
Person , then
newInstance() creates a new object of type
Person and returns a reference to it.
Now, using the Person reference to
p , we can call its
getters() and
setter() to perform certain actions. Please note:
- Both Class.forName() and newIstance() throw exceptions that must be handled either using try and catch blocks or the throws keyword .
- The newInstance() method from the Class API has been deprecated since Java 9.
Using newInstance() from the Constructor API
The newInstance() method of the
Constructor class (
java.lang.reflect.Constructor ) is similar to the
newInstance() method of the Class class , except that it accepts parameters for parameterized constructors. Let's demonstrate this approach by creating an object of the
Person class using the
newInstance() method of the java.lang.reflect.Constructor class :
public class PersonTwo {
private String name;
private int uid;
public PersonTwo() {
this.name = "Maya Kumari";
this.uid = 101;
}
public PersonTwo(String name) {
this.name = name;
this.uid = 102;
}
public PersonTwo(String name, Integer uid) {
this.name = name;
this.uid = uid;
}
public static void main(String[] args) {
try {
Class.forName("com.medium.option2.PersonTwo");
Constructor c1 = PersonTwo.class.getConstructor();
PersonTwo p1 = (PersonTwo) c1.newInstance();
System.out.println("Name: " + p1.getName());
System.out.println("UID: " + p1.getUid());
Constructor c2 = PersonTwo.class.getConstructor(String.class);
PersonTwo p2 = (PersonTwo) c2.newInstance("James Gunn");
System.out.println("Name: " + p2.getName());
System.out.println("UID: " + p2.getUid());
Constructor c3 = PersonTwo.class.getConstructor(String.class, Integer.class);
PersonTwo p3 = (PersonTwo) c3.newInstance("Mark Brown", 103);
System.out.println("Name: " + p3.getName());
System.out.println("UID: " + p3.getUid());
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
In the above code, first we need to load the class using the
Class.forName() method . Next, we will call the
getConstructor() method to match the data types of the passed parameters. Finally, in
the newInstance() method we pass the required parameter (
null if there is no argument).
The newInstance() method will return a new object of the
PersonTwo class by calling the appropriate constructor.
Using the clone() method
The clone() method is part of the
Object class and is used to create a copy of an existing object. It creates an object of the class without calling any class constructor. To clone a method, the corresponding class must have implemented the
Cloneable interface , which is a marker interface. Now we will create an object of the
Person class and then clone it into another object of the
Person class :
public class Person implements Cloneable {
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
private String name;
private int uid;
public Person(String name, int uid) {
super();
this.name = name;
this.uid = uid;
}
public static void main(String[] args) {
Person p1 = new Person("Ryan", 101);
try {
Person p2 = (Person) p1.clone();
System.out.println("Name: " + p2.getName());
System.out.println("UID: " + p2.getUid());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
Note. The cloned object will reference the same original object via the
p2 reference . However, the cloned object will have a separate memory assignment. This means that any changes made to the
Person object referenced by
p2 will not change the original
Person object referenced by
p1 . This is because the
clone() method creates a shallow copy of objects.
Using Object Deserialization
Object deserialization is the process of extracting an object from a series of byte streams. Serialization does the opposite. Its main purpose is to retrieve a stored object from the database/network back into memory. If we want to serialize or deserialize an object, we need to implement the
Serializable interface (token interface). Consider the example below:
public class PersonDriver {
public static void main(String[] args) {
Person p1 = new Person("Max Payne", 101);
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream("link to text file");
ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
outputStream.writeObject(p1);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream("link to text file");
ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
Person p2 = (Person) inputStream.readObject();
System.out.println("Name: " + p2.getName());
System.out.println("UID: " + p2.getUid());
inputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Here we first serialize the
Person object by reference
p1 into a text file.
The writeObject() method will write the object's byte stream to a text file. Then, using object deserialization, we extract the
Person object back into
p2 . Similarly,
the readObject() method will read an object from the object's input stream. Finally, we will print the data from the
Person object to the console.
Conclusion
In this article, we learned about the different ways to create an object in Java. First, we looked at creating objects using the
new keyword , which is the most common way. We then learned
the newInstance() method from the
Class and
Constructor classes , which is another popular way to create objects. We then used the
clone() method , which creates a shallow copy of the existing object instead of creating a new object. Lastly, we used the concept of object serialization and deserialization to create objects in Java.
String to Int in Java - how to convert a string to an integer
Source:
FreeCodeCamp Today you will learn how to convert a string to an integer in Java using two methods of the Integer class - parseInt() and valueOf() . This will help you when performing mathematical operations using the value of a string variable.
How to convert a string to an integer in Java using Integer.parseInt
This option assumes that the
parseInt() method takes a string to convert to an integer as a parameter:
Integer.parseInt(string_varaible)
Before looking at an example of its use, let's see what happens when you add a string value and an integer without any conversion:
class StrToInt {
public static void main(String[] args) {
String age = "10";
System.out.println(age + 20);
}
}
In this code, we have created a variable
age with the string value “10”. When we added the number 20 to an integer value, we erroneously received 1020 instead of the correct answer of 30. This can be corrected using the
parseInt() method :
class StrToInt {
public static void main(String[] args) {
String age = "10";
int age_to_int = Integer.parseInt(age);
System.out.println(age_to_int + 20);
}
}
Here, to convert the age variable to an integer, we passed it as a parameter to the
parseInt() method -
Integer.parseInt(age) - and stored it in a variable called
age_to_int . Now when added to another integer we get the correct addition:
age_to_int + 20 .
How to convert a string to an integer in Java using Integer.valueOf
The valueOf() method works the same as the
parseInt() method . It takes as a parameter a string that needs to be converted to an integer. Here's an example:
class StrToInt {
public static void main(String[] args) {
String age = "10";
int age_to_int = Integer.valueOf(age);
System.out.println(age_to_int + 20);
}
}
In the above code you can see the same thing as in the previous section:
- We passed a string as a parameter to valueOf() : Integer.valueOf(age) . It was stored in a variable called age_to_int .
- We then added 10 to the created variable: age_to_int + 20 . The result was 30 instead of 1020.
Conclusion
In this article, we discussed converting strings to integers in Java. To convert a string to an integer, two methods of the
Integer class were used -
parseInt() and
valueOf() . Happy coding!
GO TO FULL VERSION