BaşlayınÜcretsiz Başlayın

Wrappers with null

Unlike primitives, a wrapper variable can be uninitialized and has a value of null. A primitive variable that is not initialized is automatically set to its default value (0 in the case of ints). Since wrappers can have null values, this allows us to test if it has been set before using it (unlike primitives). In this exercise, we see the difference between uninitialized primitives and wrapper objects.

Bu egzersiz

Data Types and Exceptions in Java

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • Declare a variable of type int called x but do not set its value.
  • Declare a variable of type Integer called y but do not set its value.
  • Display (print) the value of x even though you did not initialize its value.
  • Test if y is null.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

public class NullWithWrappers {

	// Declare a primitive integer called x
	static ____ ____;
	// Declare a wrapper Integer called y
	static ____ ____;

	public static void main(String[] args) {
       	// Display x value
		System.out.____(____);
		System.out.println(y);

		// Check if y has been initialized and is null
		if (____ ____ ____) {
			System.out.println("y is not initialized so take corrective steps here");
		}
	}
}
Kodu Düzenle ve Çalıştır