PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   20-10-2021

Numbers

! Java provides wrapper classes for each primitive data types.
 
/**
 * All of the numberic wrapper classes are subclasses of ...
 * the abstract class Number.
 * 
 * Effective Java (Item 49): 
 * Prefer primitive types to boxed primitives. 
 */

package com.minte9.basics.numbers;

public class Numbers {
    public static void main(String[] args) {

        Number no = Double.valueOf(22.33);

        System.out.println(no.shortValue()); // 22
    }
}
... 8 lines
 

Autoboxing

! Java compiler makes automatic convertions to primitives and vice-versa.
 
/**
 * Primitives types cannot be used in Collections or Generics.    
 * Java compiler makes automatic convertions to primitives. 
 * 
 * Unboxing is the automatic conversion of objects into their ...
 * coresponding primitives
 */

package com.minte9.basics.numbers;

import java.util.List;
import java.util.ArrayList;

public class Autoboxing {
    public static void main(String[] args) {
        
        List<Integer> li = new ArrayList<>();

        for (int i=10; i<20; i++) { 
            li.add(i); 
            // autoboxing (i is primitive)
        }

        System.out.println(li.get(0).getClass().getName());
            // java.lang.Integer

        int b = li.get(0); 
            // unboxing (element is Integer)
        
        System.out.println(b); 
            // 10
    }
}

... 18 lines
 

Questions     github Basics
Strings

        A B C D E F
🔔
1/2