-1

Will Java private fields have garbage values without initialization? If I only define a class, without creating an instance of it, will their fields have default values?

public class PokedexAdapter extends RecyclerView.Adapter<PokedexAdapter.PokedexViewHolder> {
    public static class PokedexViewHolder extends RecyclerView.ViewHolder {
        private LinearLayout containerView;
        private TextView textView;

        PokedexViewHolder(View view) {
            
        }
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Dat Pham
  • 7
  • 3
  • 2
    No. Primitive fields will have default values of 0, 0.0, or false. Object variables will have default value of null. Visibility won't make a difference. – Old Dog Programmer Aug 17 '23 at 20:36
  • If I only define a class, without creating an instance of it, will their fields have default values, Old Dog Programmer? – Dat Pham Aug 17 '23 at 20:48
  • 2
    Link to Java 8 specification on default values: https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.5 – mortalis Aug 17 '23 at 20:49
  • @DatPham If I only define the concept of Dog, without actually having any dogs around, what will they eat? Your question makes no sense - if there are no instances, there aren't any fields to hold a value at all. – rzwitserloot Aug 17 '23 at 22:07

2 Answers2

0

variables objects not initialized are null so there is no data ( no pointer to memory data ). primary types like int default to 0

Dam
  • 986
  • 1
  • 14
  • 20
0

No, Java private fields will not have garbage values without initialization.

Like Old Dog Programmer said:

No. Primitive fields will have default values of 0, 0.0, or false. Object variables will have default value of null. Visibility won't make a difference.

However, it's a good practice to explicitly initialize private fields to appropriate values to avoid any confusion or unintended behavior in your code.

Diego Borba
  • 1,282
  • 8
  • 22
  • If I only define a class, without an instance one, does its fields have default values, Diego? – Dat Pham Aug 17 '23 at 20:46
  • You mean, have values even if you don't instantiate any object? – Diego Borba Aug 17 '23 at 20:50
  • Yes, Diego. If I only define a class, without creating an instance of it, will their fields have default values? – Dat Pham Aug 17 '23 at 20:51
  • 2
    Class definition is an abstraction, a prototype, its fields don't have values, unless they are static fields. An object is a concrete instance which have values, default or assigned at run time. – mortalis Aug 17 '23 at 20:52
  • 1
    @mortalis answered for me haha – Diego Borba Aug 17 '23 at 20:54
  • Given it is specified what will happen, there is no good reason to explicitly initialize private fields if you're going to initialize them to the same value as the default. – Mark Rotteveel Aug 18 '23 at 09:22