In Java, the default value for a String variable is null. When a String the variable is declared but not assigned a value, it automatically takes the null value.
Here’s an example:
public class Main {
static String str; // Declaring a String variable without assigning a value
public static void main(String[] args) {
System.out.println(str); // Output: null
}
}
In the above example, the str variable is declared but not initialized with any value. Therefore, its default value is null.
How to initialize string to default value in Java?
By default the value of the instance variable is null. If your has declared any local variable user has to assign some value or manually provide a default value.
public class Main {
public static void main(String[] args) {
String str=null; // Declaring a String variable without assigning a value
System.out.println(str); // Output: null
}
}
what is the default value of string array in java
public class Main {
public static void main(String[] args) {
String[] strArray = new String[3]; // Declaring and initializing a String array
System.out.println(strArray[0]); // Output: null
System.out.println(strArray[1]); // Output: null
System.out.println(strArray[2]); // Output: null
}
}
null null null
default value of static string in Java
The default value of the static string is also null.
Printing the default value of Object
public class Student {
private int id;
private String name;
private int age;
private String gender;
// Constructor
public Student(int id, String name, int age, String gender) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
}
public Student(int id, int age) {
this.id = id;
this.age = age;
}
// Method to print student details
public void printDetails() {
System.out.println("Student Details:");
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Gender: " + gender);
}
// Main method to test the Student class
public static void main(String[] args) {
// Create a student object
Student student = new Student(1, "Ram", 20, "Male");
Student student1 = new Student(2, 20);
// Print student details
student.printDetails();
// Print student details
student1.printDetails();
}
}
Output
Student Details: ID: 1 Name: Ram Age: 20 Gender: Male Student Details: ID: 2 Name: null Age: 20 Gender: null
Default value of String ArrayList
In Java, the default value of a String ArrayList (or any ArrayList for that matter) is an empty ArrayList. When you create an ArrayList without adding any elements to it, it will be empty by default.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList stringList = new ArrayList<>();
System.out.println(stringList); // Output: []
}
}
Output
[]
The default value for a String variable is null