Variables in Java: What are they and how are they used
Source:
Hackernoon There are four different types of variables in Java, depending on where they are declared in the program. Today you will learn examples and differences of each type. 1. Instance variables or
Instance fields are variables declared inside a class without the
static keyword , but outside a method, constructor, or block of code. Such variables can be declared anywhere within the class. You can declare them with or without an access modifier, such as
public ,
private ,
protected or
default (not a keyword).
public class MyClass {
private String instanceField1;
public MyClass(){}
public int anotherInstanceField2;
public void setInstanceField(String parameterVariable) {...}
boolean instanceField3;
public static void main(String[] args) {
System.out.println("field 1 value: " + instanceField1);
System.out.println("field 2 value: " + anotherInstanceField2);
System.out.println("field 3 value: " + instanceField3);
}
}
If an instance field is not assigned a value at declaration time, it is assigned a default value of zero if it is a primitive type, such as (
int ,
boolean ,
long ,
float ), or
null if it is not a primitive type, such as (
String ,
Integer ,
AnyClass ). They are called fields or instance variables because they belong to the instance of any object created from the class in which they are declared.
public Main {
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
obj1.anotherInstanceField2 = 11;
obj2.anotherInstanceField2 = 33;
System.out.println(obj1.anotherInstanceField2);
System.out.println(obj2.anotherInstanceField2);
}
}
Thus, each instance field is unique to its object, as seen in the above snippet. In it,
obj1 and
obj2 have unique values assigned to their respective instance fields.
2. Class fields or
static fields are fields declared with the
static keyword . They are declared inside the class, but outside the method, constructor, or block of code. They can also be declared at any position within a class, with or without an access modifier, such as
public ,
private ,
protected , or
default (not a keyword).
public class MyClass {
public static String staticField;
public MyClass(){}
}
class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.staticField
MyClass.staticField = "I am a static field";
System.out.println(MyClass.staticField);
}
}
Static fields can only be accessed through their classes and not from any object as shown in the code snippet above. 3.
Parameters or
Argument variables are variables declared inside a method construct between the opening and closing curly braces of the method signature. They are used to pass values or objects to a method.
public class MyClass {
public String instanceField;
public MyClass(){}
public void setInstanceField(String parameterVariable) {
instanceField = parameterVariable;
}
}
class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.setInstanceField("From a parameter variable");
System.out.println(obj.instanceField);
}
}
4.
Local variables are variables declared inside a method or any block of code, for example, inside a block of
if statements ,
for loop ,
while loop , block of
switch statements , and so on.
public Main {
public static void main(String[] args) {
MyClass obj1 = new MyClass();
int id = 1;
if (id > 1) {
String tempName = "Austin";
}
}
}
In this code you can notice the use of reference with some variables, while the local variable
id was not mentioned as a reference variable. Any non-primitive variable is a reference variable. For example,
obj1 is a variable of type
MyClass and
tempName is a variable of type
String , and here both types are not primitive types. In this case,
id is a variable of type
int , which is a primitive data type. Therefore, it is a non-reference variable.
5 Things You Should Know About Serialization and Deserialization in Java
Source:
Devgenius With this tutorial, you will improve your knowledge of how serialization and deserialization work. Serialization in Java helps convert an existing object into a byte stream. Conversely, deserialization makes a byte stream an object. Using serialization and deserialization in Java, information about objects can be transferred from one JVM to another.
#1 Serialization
Before going into detail, let's take a look at the
SerializeUtils.java and
Person.java classes . Here they will help us perform serialization and deserialization using specific examples.
SerializeUtils.java
package com.techteam.serialization;
import java.io.*;
public class SerializeUtils {
public static <T> void serialize(T input, String fileName) throws IOException {
FileOutputStream file = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(input);
out.close();
file.close();
}
public static <T> T deserialize(String fileName) throws IOException, ClassNotFoundException {
FileInputStream file = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(file);
T result = (T) in.readObject();
return result;
}
public static void externalSeialize(Externalizable e, String fileName) throws IOException {
FileOutputStream file = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(file);
e.writeExternal(out);
out.close();
file.close();
}
public static void externalDeseialize(Externalizable e, String fileName) throws IOException, ClassNotFoundException {
FileInputStream file = new FileInputStream (fileName);
ObjectInputStream in = new ObjectInputStream (file);
e.readExternal(in);
in.close();
file.close();
}
}
Person.java
package com.techteam.serialization;
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
As mentioned, serialization helps convert an object into a stream of bytes. This means that all the information about the object is also converted into a byte stream, such as method, properties and data. Here is an example of how an object is serialized:
package com.techteam.serialization;
import java.io.IOException;
public class SerializationMain {
public static void main(String[] args) throws IOException {
Person p = new Person();
p.setId(1);
p.setName("Tech team members");
p.setAge(20);
SerializeUtils.serialize(p, "/person.txt");
}
}
After the serialization process we have a file with the following content:
#2 Deserialization
If in the previous example we created a stream of bytes by serializing an object, now let's see how we get back to the object using deserialization:
package com.techteam.serialization;
import java.io.IOException;
public class DeserializationMain {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person p = SerializeUtils.deserialize("/person.txt");
System.out.println("Person data:");
System.out.println(p.getId());
System.out.println(p.getName());
System.out.println(p.getAge());
}
}
Here is the data after the deserialization process:
#3 Serial Version UID
SerialVersionUID means a unique identification number for each version of the serialization and deserialization process. This number is used to ensure that both serialized and deserialized objects use compatible classes. For
Person.java, I would like to increase the serialVersionUID to 2. Let's look at the output after deserializing the person.txt file.
#4 Keyword Transient
During the process of serialization and deserialization, sometimes we don't need to serialize all the information about an object. By using a transient process for variables, we can ignore those variables from the object being serialized. The example below will help understand this more clearly:
package com.techteam.serialization;
import java.io.IOException;
import java.io.Serializable;
public class PersonWithTransient implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private transient int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
PersonWithTransient p = new PersonWithTransient();
p.setId(2);
p.setName("Tech team members(transient)");
p.setAge(50);
SerializeUtils.serialize(p, "/person_transient.txt");
PersonWithTransient deserializeP = SerializeUtils.deserialize("/person_transient.txt");
System.out.println("Person without transient data:");
System.out.println(deserializeP.getId());
System.out.println(deserializeP.getName());
System.out.println(deserializeP.getAge());
}
}
In the above code, we have used the transient keyword for the
age variable . And this is what we got after the serialization and deserialization process.
#5 Externalizable Interface
In Java, when we want to customize the serialization and deserialization process, we can use a transition process to ignore the variables that we don't need for the serialization and deserialization process. Another way to simplify and improve performance is to use the
Externalizable interface instead of the Serializable interface . Let's look at an example:
package com.techteam.serialization;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class PersonExternalizable implements Externalizable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(this.name);
out.writeInt(this.age);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.name = in.readUTF();
this.age = in.readInt();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
PersonExternalizable p = new PersonExternalizable();
p.setId(3);
p.setName("Tech team members(Externalizable)");
p.setAge(30);
SerializeUtils.externalSeialize(p, "/person_externalizable.txt");
PersonExternalizable deserializeP = new PersonExternalizable();
SerializeUtils.externalDeseialize(deserializeP, "/person_externalizable.txt");
System.out.println("Person data:");
System.out.println(deserializeP.getId());
System.out.println(deserializeP.getName());
System.out.println(deserializeP.getAge());
}
}
As you can see, when using
Externalizable we can easily write custom logic, ignore variables and get better performance than using
Serializable . Now let's look at the output:
Conclusion
Hopefully, through this article, you have gained a clear understanding of how serialization and deserialization work in Java, and the above examples can help you in practice in the future.
GO TO FULL VERSION