I did not initialize a variable yet I still receive an output - java

Here is my code:
class Xyz{
public static void main(String args[])
{
first fobj = new first(10);
for(int i=0;i<5;i++){
fobj.add();
System.out.printf("%s",fobj);
}
}
}
class first{
public int sum=0;
public final int num;
first(int x){
num=x;
}
public void add(){
sum+=num;
}
public String toString()
{
return String.format("sum = %d" ,sum);
}
}
output:
sum=10
sum=20
sum=30
sum=40
sum=50
In the class first I didn't initialize a variable named "sum" but I still get output. Can someone explain that to me?
asgfafgalsdfkjsaflkasflaskfalskfajlskfaskfaslkjflaskfaslkflasjkf.

Instance members are automatically initialized to default values, JLS-4.12.5 Initial Values of Variables
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
...
For type `int`, the default value is zero, that is, 0.

In Java, all the member variables are automatically initialized to their default values at the time of object creation even if you don't do it yourself. Default value of int is 0.

Class and instance data members are automatically defaulted to the all-bits-off value for their type (0 in the case of int), even if you don't do it explicitly. Since sum is an instance data member, it's implicitly defaulted to 0.
This is covered by §4.12.5 of the Java Language Specification:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):
For type byte, the default value is zero, that is, the value of (byte)0.
For type short, the default value is zero, that is, the value of (short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '\u0000'.
For type boolean, the default value is false.
For all reference types (§4.3), the default value is null.

Related

Array of Class Operator Error: unexpected type required: variable found: value

I have an array of the BankAccount class and nested classes, including AccountInfoPrv with the method getAcctBalance(). The error occurs at the last line, where I call the BankAccount method getAccountInfoPrv() which then goes into the AccountInfoPrv class to call getAcctBalance(). It returns whatever value is there at index i, i've tested this without the operator in main method and it returns the value perfectly.. i'm not sure what i did wrong here.
Also, there is a lot of other code involved in this method but i tried to simply it with just this for loop.
public static void withdrawal(Scanner kybd, BankAccount[]
account, int num_accts)
{
double amountToWithdraw;
amountToWithdraw = kybd.nextDouble();
for(int i=0; i<num_accts; i++)
account[i].getAccountInfoPrv().getAcctBalance() -=
amountToWithdraw;
}
Expected to subtract withdrawal amount from the value of account[i] and set account[i] to the new value.
Output: Error: unexpected type
required: variable
found : value
What you are trying to do over here is modify the "Value" returned by the getter method. In order to perform any such operation on the value returned by getter method, you would
First need to store it into a variable,
and modify its value,
and then call the setter to set the updated value in the object.
i.e.
balance = account[i].getAccountInfoPrv().getAcctBalance();
balance -= amountToWithdraw;
account[i].getAccountInfoPrv().setAcctBalance(balance);
In case of non-primitive type, calling setter explicitly is not required as it would get updated via reference.
Here you try to change from a getter (the method) it is not allowed.
Try
account[i].getAccountInfoPrv().setAcctBalance(account[i].getAccountInfoPrv().getAcctBalance() - amountToWithdraw);

In Java, Variable got initialize without constructor, How it come possible? [duplicate]

This question already has answers here:
Default values and initialization in Java
(11 answers)
Closed 6 years ago.
I understand that, Constructors are used to initialize the instance variables.
Default constructor will create by compiler itself, if we did not create the same.
If we are creating the parameterized constructor then compiler won't create the default constructor.
I have written a code, to ignore the instance variable to be handled by constructor. But it got initialize without constructor. How it come possible to initialize variable without the constructor?
Please find the code snippet below for better understanding
public class ClassWithoutDefault {
int number;
String name;
//Intailizing name variable alone by using parameterized constructor
ClassWithoutDefault(String name){
this.name = name
}
void show(){
System.out.println("Name is"+name+"Number is"+number );
}
}
//Main class
public class ConstructorTest {
public static void main(String[] args) {
ClassWithoutDefault classWithoutDefault = new ClassWithoutDefault("Hari");
classWithoutDefault.show();
}
}
Output
Name is Hari
Number is 0
How the variable number got initialized as 0, without the constructor?. Could any one please help me to understand this?
Each member variable is assigned a default value (when an instance of a class is created), and if you don't assign it anything else, it retains that default value. The default value of primitive numeric types is 0.
Whenever a new object of a class is created, :
Strings are initialized by null.
Numbers are initialized by 0 (integers), or 0.0(floating-point).
booleans are initialized by false.
chars are initialized by \u0000
Arrays are initialized by the default values of their components.
Other Objects are initialized by null.
Hence, your number was initialized by 0.
When you create an object,first compiler copy that class file to memory and create the template of the object in the memory. And then it creates a copy according to that template and add it to your reference variable.
If you declared a static variable then that variable is created with the template,thats why static variables have the last updated value everytime. Because for all objects there is only one common variable in that name in the memory.
But when you create instance variable it is made with every object.
So when an object is created everytime, it is initialized to its Default Value.
//byte 0
//short 0
//int 0
//long 0
//float 0.0
//double 0.0
//char null
//boolean false
//Reference Type, class type - null

Initialising instance variables as null, "" or 0

When initialising variables with default values:
What is the difference between:
private static String thing = null;
and
private static String thing = "";
I'm not understanding which is better and why nor what is the best way to deal with other data types.
private static int number = 0;
private static double number = 0;
private static char thing = 0;
Sorry I struggle learning new languages.
Except for initializing String to an empty string
private static String thing = "";
the other assignments are unnecessary: Java will set all member variables of primitive types to their default values, and all reference types (including java.String) to null.
The decision to initialize a String to a null or to an empty string is up to you: there is a difference between "nothing" and "empty string" *, so you have to decide which one you want.
* The differences between "nothing" and "empty string" stem from the observation that no operations are possible on a null string - for example, its length is undefined, and you cannot iterate over its characters. In contrast, the length of an empty string is well-defined (zero), and you can iterate over its characters (it's an empty iteration).
When you make:
private static String ptNo = "";
you are creating a variable ptNo and making it to refer an object String "".
When you make:
private static String ptNo = null;
you are creating a variable, but it doesn't refer to anything.
null is the reserved constant used in Java to represent a void reference i.e a pointer to nothing.
In Java null and an empty are not the same thing.
From suns java tutorial
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it
is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
"" is an actual string with empty value.
null means that the String variable points to nothing.
As an example,
String a="";
String b=null;
a.equals(b) returns false because "" and null do not occupy the same space in memory.

Type casting the `Object` type variables

I need to call a function with the following signature.
createColumn (N name, V value, Serializer<N> nameSerializer, Serializer<V> valueSerializer)
I want to pass variables of type Object which might have been assigned values of integer or string, I want the type casting to be performed automatically..according to the values that I assigned to Object type variables instead of explicit cast like this:-
Object object1= "MY_AGE";
// string value assigned to to object type variable
Object object2= 31; // integer value assigned to object type variable
createColumn ((String)object1, (int)object2, ....); // Since the datatype of object1 & object2 would not be same everytime while I am calling this function in a for loop, I want that it should automatically cast according to the value I assign to it.* So I am seeking something like this, if possible:-
createColumn (object1, object2, ....);
You can call the following since you don't want to check at compile time that the types match,
createColumn(object1, object2, (Serializer)serializer1, (Serializer)serializer2);
EDIT: This compiles for me (with an "Unchecked" warning)
interface Serializer<T> { }
public static <N,V> void createColumn (N name, V value, Serializer<N> nameSerializer, Serializer<V> valueSerializer) {
}
public static void main(String[] args) throws NoSuchFieldException {
Object object1 = "hi";
Object object2 = 31;
Serializer<String> serializer1 = null;
Serializer<Integer> serializer2 = null;
createColumn(object1, object2, (Serializer) serializer1, (Serializer) serializer2);
}
As I understand your question is not about casting (which deals with compile-time declared types), but conversion (which deals with runtime type of objects).
Consider using String.valueOf() method for your Object arguments. For both Integer and String it will produce their String representation.
I don't think it is possible, you have given the variable a type object and i'm not aware of any way to determine if it is really an int or string unless you use some ugly logic to see what characters the value consists of but that isn't going to be fool proof unless the value will always be either an integer or a string.
Do you need to pass integers or can everything just be passed as a string?

What are java object fields initialized with?

Is it null for Object type?
class C {
int i;
String s;
public C() {}
}
Will s be always null?
What about simple types as int? What will that be? Zero or an arbitrary value?
What about local variables in methods?
public void meth() {
int i;
}
What is the unitialized value of i?
Relying on such default values, however, is generally considered bad
programming style.
Ok, what do you suggest we do?
class A {
String s = "";
int i = 0;
}
OR:
class A {
String s;
int i;
public A() {
// default constructor
s = "";
i = 0;
}
}
Which is better and why?
From suns java tutorial
It's not always necessary to assign a
value when a field is declared. Fields
that are declared but not initialized
will be set to a reasonable default by
the compiler. Generally speaking, this
default will be zero or null,
depending on the data type. Relying on
such default values, however, is
generally considered bad programming
style.
The following chart summarizes the
default values for the above data
types.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
String (or any object) null
Local variables are slightly
different; the compiler never assigns
a default value to an uninitialized
local variable. If you cannot
initialize your local variable where
it is declared, make sure to assign it
a value before you attempt to use it.
Accessing an uninitialized local
variable will result in a compile-time
error.
For member variables:
The default value for String is null. The default value for primitives is 0 (or 0.0 for floating point values).
For local variables:
You must explicitly initialise a local variable before using it.
As to the second part of your question:
You can always say String s = ""; in the member variable definition, or s = ""; in the constructor. Then you know it will have a non-null value. (Also, in your setter you'd need to ensure that someone doesn't try and set it back to null.)
Fields: Objects default to null; ints, longs and shorts to 0; Strings to null; booleans to false. It's all here.
The compiler will force you to initialise variables declared in methods, local variables, yourself.
Primitive fields are initialized to 0 / false. Objects are initialized to null . But frankly, you could have tried that one..
As for the setter-method question: The whole point of setters is that they can check if the object passed conforms to the requirements of the class. e.g.
public void setS(String s) {
if (s == null)
throw new IllegalArgumentException("S must not be null");
this.s = s;
}
Or, with Google Collections/Google Guava:
public void setS(String s) {
this.s = Preconditions.checkNotNull(s, "S must not be null");
}
Of course, you can define arbitrary constraints, e.g.:
/**
* Sets the foo. Legal foo strings must have a length of exactly 3 characters.
*/
public void setFoo(String foo) {
if (foo == null)
throw new IllegalArgumentException("Foo must not be null");
if (foo.length() != 3)
throw new IllegalArgumentException("Foo must have exactly 3 characters");
...
Of course in such a case you should always state the correct range of values for your properties in the JavaDoc of the setter and/or of the class.
JLS 4.12.5. Initial Values of Variables
Each class variable, instance variable, or array component is
initialized with a default value when it is created (§15.9, §15.10.2):
For type byte, the default value is zero, that is, the value of
(byte)0.
For type short, the default value is zero, that is, the value of
(short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is,
'\u0000'.
For type boolean, the default value is false.
For all reference types (§4.3), the default value is null.

Categories