I have been playing with this piece of code for sometime and it puzzles me why this method call seems to be returning a number although it was not initially set to 0
public class MainProg {
public static void main(String[] args) {
FixedCapacitySizeOfStrings s = new FixedCapacitySizeOfStrings(3);
System.out.println("(" + s.size() + " left on stack)");
}
}
This is the API code
public class FixedCapacitySizeOfStrings {
private String[] a;
private int N;
public FixedCapacitySizeOfStrings(int cap) {
a = new String[cap];
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N; //why is this line doing the right thing?? N was never initialized to 0
}
public void push(String item) {
a[N++] = item;
}
public String pop() {
return a[--N];
}
}
Primitive instance variables are by default initialized to 0. This includes int, long, double, float, short, byte and char. (And all non-primitive instance variables are initialized to null)
Note that it's only about instance variables (fields) - local variables are not initialized.
Instance variables are initialized to default value by the compiler,if you don't provide any initialization
These are the default values for different types of instance variables.
data type Default value
boolean false
char \u0000
int,short,byte / long 0 / 0L
float /double 0.0f / 0.0d
any reference type null
For more details on default initialization.
When you are inside of methods, variables must be initialized explicitly. Outside of methods 0 is implicitly the default value integers are initialized to.
So, even though your integer N is not being assigned within FixedCapacitySizeOfStrings its value is implicitly zero as it's declared as an instance variable (class variable.)
However, your test case complains because the integer s wasn't explicitly set to any value, and is being declared within a method.
FixedCapacitySizeOfStrings s = new FixedCapacitySizeOfStrings(3);
it will call the constructor, but before constructor it is called the initialisation code part, which is now empty and private int N; takes the 0 value. Than System.out.println("(" + s.size() + " left on stack)"); will return the 0 value.
it gives s.size()=0 because N is Instance variable and as you know it has default value if you want to correct value then write as
public int size() {
return N=a.length;
}
above give the correct result...
Related
I am pretty new to coding, I want to write a static method to set a count value to 1000.
I tried doing things like
public static int setCounter(){
return 1000;
}
When try to use this method in another to increment the count
such as someVariable = symbolic constant + setCounter()++;
return someVariable, it gives me an unexpected type error, required variable, found value. What am i doing wrong?
edit*
edit*
private String getTicketNumber(){
ticketNumber = TICKET_PREFIX + resetCounter()++;
return ticketNumber;
public static int resetCounter(int counter){
counter = 1000;
}
i want to call this counter to increment it in another method
An static property is associated with the definition of the class, and there is only ever one definition of the class. An instance is created whenever you use the new keyword on the class. All instances are keep their own private data from the static class. When using a class instance you can access the static variables but not the other way around.
You use the term constant, but I think you might have a bit of a misunderstanding of what that implies. Constants are often declared as static final values that are immutable (they can never be changed). You should not be able to modify a constant. A static value can be mutable if you so desire, and this is what we would sometimes refer to as a stateful singleton.
Consider these two examples... one modifies an instance variable, the other a static variable.
class InstanceFoo {
int i = 1000;
int resetCounter() {
i = 1000;
return i;
}
int getAndIncrement() {
return i++;
}
}
class StaticFoo {
static int i = 1000;
static int resetCounter() {
i = 1000;
return i;
}
static int getAndIncrement() {
return i++;
}
}
In the first example you need to use an instance to access the variables.. i.e. you need to instantiate it with new:
InstanceFoo foo = new InstanceFoo();
System.out.println(foo.resetCounter()); // 1000
System.out.println(foo.getAndIncrement()); // 1000
System.out.println(foo.getAndIncrement()); // 1001
System.out.println(foo.getAndIncrement()); // 1002
System.out.println(foo.resetCounter()); // 1000
In the second you access the static value. Statics can be referred to by to the class definition:
System.out.println(StaticFoo.resetCounter()); // 1000
System.out.println(StaticFoo.getAndIncrement()); // 1000
System.out.println(StaticFoo.getAndIncrement()); // 1001
System.out.println(StaticFoo.getAndIncrement()); // 1002
System.out.println(StaticFoo.resetCounter()); // 1000
In your example you are trying to increment the counter by doing resetCounter()++. This will not work for a separate reason entirely from being static or instance. Primitive values in Java (like ints, doubles, floats, etc) are pass by value, not pass by reference.
In a very simplistic sense, this means that once you return a primitive from a method like resetCounter, you are actually passing a copy of the value. You then incremented the copy, but the value associated with the class remains the same (because you incremented only the copy of the variable). You need to call the postfix operator ++ on the variable itself, not the value returned by the method. i.e. If I have
class StaticFoo {
static int i = 1000;
static int get() {
return i;
}
}
System.out.println(StaticFoo.get()++); // prints 1000 and adds 1. the copy is then destroyed
System.out.println(StaticFoo.get()++); // prints 1000 and adds 1, the copy is then destroyed
System.out.println(StaticFoo.i); // prints 1000
System.out.println(StaticFoo.i++); // prints 1000 and now a postfix is applied to the static variable
System.out.println(StaticFoo.i++); // prints 1001 and another postfix is applied to the static variable
System.out.println(StaticFoo.get()); // prints 1002 because two postifx operators were applied to StaticFoo.i.
Hope this helps you get started.
I think that you are assigning value to a non compatible data type varaiable.
See my code for reference:
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
int a = 10 + setCounter();
System.out.println(a);
}
public static int setCounter(){
return 1000;
}
}
edit*
private String getTicketNumber(){
ticketNumber = TICKET_PREFIX + resetCounter()++;
return ticketNumber;
public static void resetCounter(int counter){
counter = 1000;
}
i want to call this counter to increment it in another method
We have Integer class in JAVA, but I couldn't find any equivalent class in C#? Does c# have any equivalent? If not, how do I get JAVA Integer class behavior in c#?
Why do I need this?
It is because I'm trying to migrate JAVA code to c# code. If there is an equivalent way, then code migration would be easier. To addon, I need to store references of the Integer and I don't think I can create reference of int or Int32.
C# has a unified type system, so int can be implicitly boxed into an object reference. The only reason Integer exists in Java is so that it can be converted to an object reference and stored in references to be used in other container classes.
Since C# can do that without another type, there's no corresponding class to Integer.
Code migration won´t work out of the box for any type of language without any manual changes. There are things such as a class Integer that simply does not exist within (C# why should it anyway, see recursives answer), so you´d have to do some work on your own. The nearest equivalent to what you´re after is Int32 or its alias int. However you may of course write your own wrapper-class:
public class Integer
{
public int Value { get; set; }
public Integer() { }
public Integer( int value ) { Value = value; }
// Custom cast from "int":
public static implicit operator Integer( Int32 x ) { return new Integer( x ); }
// Custom cast to "int":
public static implicit operator Int32( Integer x ) { return x.Value; }
public override string ToString()
{
return string.Format( "Integer({0})", Value );
}
}
The beauty of C# is that it has a unified type system. Everything derives from object, even primitive types. Because of this, all keywords are simply aliases for a corresponding class or struct. Java does not use a unified type system, so a separate Integer class is required to wrap the int primitive. In C# int is synonym for the Int32 struct.
What you're looking for has been right in front of you the whole time. Start using the dot notation directly on the int keyword (i.e. int.whatever()) to access the all goodness of the .NET version of the Javian Integer class.
I did some testing with Nullable types in a console application and it appears that they do not behave as you wish. For example:
static void Main(string[] args)
{
int? x = 1;
Foo(ref x);
Console.WriteLine(x);//Writes 2
}
private static void Foo(ref int? y)
{
y += 1;
var l = new List<int?>();
l.Add(y);
l[0] += 1;//This does not affect the value of x devlared in Main
Console.WriteLine(l[0]);//Writes 3
Console.WriteLine(y);//writes 2
Foo2(l);
}
private static void Foo2(List<int?> l)
{
l[0] += 1;
Console.WriteLine(l[0]);//writes 4
}
But if you roll your own generic class to wrap primitive/value types for use within your application you can get the behavior you are expecting:
public class MyType<T>
{
public T Value { get; set; }
public MyType() : this(default(T))
{}
public MyType(T val)
{
Value = val;
}
public override string ToString()
{
return this.Value.ToString();
}
}
static void Main(string[] args)
{
var x = new MyType<int>(1);
Foo(x);
Console.WriteLine(x);//Writes 4
}
private static void Foo(MyType<int> y)
{
y.Value += 1;
var l = new List<MyType<int>>();
l.Add(y);
l[0].Value += 1;//This does affect the value of x devlared in Main
Console.WriteLine(l[0]);//Writes 3
Console.WriteLine(y);//writes 3
Foo2(l);
}
private static void Foo2(List<MyType<int>> l)
{
l[0].Value += 1;
Console.WriteLine(l[0]);//writes 4
}
int, int? and System.Int32 are all struct and thus value types and does not compare to Java's Integer wrapper class which is a reference type.
System.Object class though a reference type can cause issue as boxing creates immutable object. In short, you can't alter a boxed value.
int a = 20;
Object objA = a; //Boxes a value type into a reference type, objA now points to boxed [20]
Object objB = objA; //Both objA & objB points to boxed [20]
objA = 40; //While objB points to boxed [20], objA points to a new boxed [40]
//Thus, it creates another ref type boxing a 40 value integer value type,
//Boxed values are immutable like string and above code does not alter value of previous boxed value [20]
Console.WriteLine($"objA = {objA}, objB={objB}");
//Output: objA = 40, objB=20
What exactly corresponds to Java's Integer is a custom generic wrapper class.
int a = 20;
Wrapper<int> wrapA = new Wrapper<int>(a);
Wrapper<int> wrapB = wrapA; //both wrapA and wrapB are pointing to [20]
wrapA.Value = 40; //Changing actual value which both wrapA and wrapB are pointing to
Console.WriteLine($"wrapA = {wrapA}, wrapB={wrapB}");
//Output: wrapA = 40, wrapB=40
Console.ReadKey();
Implementation of the wrapper class is given below:
public class Wrapper<T> where T : struct
{
public static implicit operator T(Wrapper<T> w)
{
return w.Value;
}
public Wrapper(T t)
{
_t = t;
}
public T Value
{
get
{
return _t;
}
set
{
_t = value;
}
}
public override string ToString()
{
return _t.ToString();
}
private T _t;
}
As pointed out in other answers, C# has a unified type system so everything derives from object. If you need to handle null values then use int? to specify that the integer object can be null.
c# have a integer type called int link is here
https://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx
Newbie question:
I have two classes:
class A {
public static void main(String...args){
B b = new B()
System.out.println(B.firstVar); // 0
}
}
class B {
public int firstVar;
}
Why does it print 0 when no value was assigned to firstVar ?
0 value is the default value for the int type.
here are some other default values:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
First thing There are two error in your code
One is missing semicolon:
B b = new B()
Second is trying to use non-static member with class name
System.out.println(B.firstVar);
It should be
System.out.println(b.firstVar);
Answer to your question: When a constructor is called it initializes member variable/ properties of class to respective type default values.
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
That's why even without initialization it prints 0
Note: Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable.
When you don't set anything to the variable, it is assigned a zero by default (in case of int)
Thats the way Java initilializes variables.
For example int is initialized with 0 and Objects with null
Object obj; // obj is null
int i; // i is 0
double d; //d is 0
Based on my reference, primitive types have default values and Objects are null. I tested a piece of code.
public class Main {
public static void main(String[] args) {
int a;
System.out.println(a);
}
}
The line System.out.println(a); will be an error pointing at the variable a that says variable a might not have been initialized whereas in the given reference, integer will have 0 as a default value. However, with the given code below, it will actually print 0.
public class Main {
static int a;
public static void main(String[] args) {
System.out.println(a);
}
}
What could possibly go wrong with the first code? Do class variables behave different from local variables?
In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.
In the second code sample, a is class member variable, hence it will be initialized to the default value.
Read your reference more carefully:
Default Values
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.
. . .
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.
These are the main factors involved:
member variable (default OK)
static variable (default OK)
final member variable (not initialized, must set on constructor)
final static variable (not initialized, must set on a static block {})
local variable (not initialized)
Note 1: you must initialize final member variables on every implemented constructor!
Note 2: you must initialize final member variables inside the block of the constructor itself, not calling another method that initializes them. For instance, this is not valid:
private final int memberVar;
public Foo() {
// Invalid initialization of a final member
init();
}
private void init() {
memberVar = 10;
}
Note 3: arrays are Objects in Java, even if they store primitives.
Note 4: when you initialize an array, all of its items are set to default, independently of being a member or a local array.
I am attaching a code example, presenting the aforementioned cases:
public class Foo {
// Static and member variables are initialized to default values
// Primitives
private int a; // Default 0
private static int b; // Default 0
// Objects
private Object c; // Default NULL
private static Object d; // Default NULL
// Arrays (note: they are objects too, even if they store primitives)
private int[] e; // Default NULL
private static int[] f; // Default NULL
// What if declared as final?
// Primitives
private final int g; // Not initialized. MUST set in the constructor
private final static int h; // Not initialized. MUST set in a static {}
// Objects
private final Object i; // Not initialized. MUST set in constructor
private final static Object j; // Not initialized. MUST set in a static {}
// Arrays
private final int[] k; // Not initialized. MUST set in constructor
private final static int[] l; // Not initialized. MUST set in a static {}
// Initialize final statics
static {
h = 5;
j = new Object();
l = new int[5]; // Elements of l are initialized to 0
}
// Initialize final member variables
public Foo() {
g = 10;
i = new Object();
k = new int[10]; // Elements of k are initialized to 0
}
// A second example constructor
// You have to initialize final member variables to every constructor!
public Foo(boolean aBoolean) {
g = 15;
i = new Object();
k = new int[15]; // Elements of k are initialized to 0
}
public static void main(String[] args) {
// Local variables are not initialized
int m; // Not initialized
Object n; // Not initialized
int[] o; // Not initialized
// We must initialize them before use
m = 20;
n = new Object();
o = new int[20]; // Elements of o are initialized to 0
}
}
There are a few things to keep in mind while declaring primitive type values.
They are:
Values declared inside a method will not be assigned a default value.
Values declared as instance variables or a static variable will have default values assigned which is 0.
So in your code:
public class Main {
int instanceVariable;
static int staticVariable;
public static void main(String[] args) {
Main mainInstance = new Main()
int localVariable;
int localVariableTwo = 2;
System.out.println(mainInstance.instanceVariable);
System.out.println(staticVariable);
// System.out.println(localVariable); // Will throw a compilation error
System.out.println(localVariableTwo);
}
}
Yes, an instance variable will be initialized to a default value. For a local variable, you need to initialize before use:
public class Main {
int instaceVariable; // An instance variable will be initialized to the default value
public static void main(String[] args) {
int localVariable = 0; // A local variable needs to be initialized before use
}
}
Local variables do not get default values. Their initial values are undefined without assigning values by some means. Before you can use local variables they must be initialized.
There is a big difference when you declare a variable at class level (as a member, i.e., as a field) and at the method level.
If you declare a field at the class level they get default values according to their type. If you declare a variable at the method level or as a block (means any code inside {}) do not get any values and remain undefined until somehow they get some starting values, i.e., some values assigned to them.
All member variables have to load into the heap, so they have to be initialized with default values when an instance of class is created.
In case of local variables, they don't get loaded into the heap. They are stored on the stack until they are being used. This is before Java 7, so we need to explicitly initialize them.
In Java, the default initialization is applicable for only instance variable of class member.
It isn't applicable for local variables.
In the first case you are declaring "int a" as a local variable(as declared inside a method) and local varible do not get default value.
But instance variable are given default value both for static and non-static.
Default value for instance variable:
int = 0
float,double = 0.0
reference variable = null
char = 0 (space character)
boolean = false
I wrote following function to return a default representation 0 or false of a primitive or Number:
/**
* Retrieves the default value 0 / false for any primitive representative or
* {#link Number} type.
*
* #param type
*
* #return
*/
#SuppressWarnings("unchecked")
public static <T> T getDefault(final Class<T> type)
{
if (type.equals(Long.class) || type.equals(Long.TYPE))
return (T) new Long(0);
else if (type.equals(Integer.class) || type.equals(Integer.TYPE))
return (T) new Integer(0);
else if (type.equals(Double.class) || type.equals(Double.TYPE))
return (T) new Double(0);
else if (type.equals(Float.class) || type.equals(Float.TYPE))
return (T) new Float(0);
else if (type.equals(Short.class) || type.equals(Short.TYPE))
return (T) new Short((short) 0);
else if (type.equals(Byte.class) || type.equals(Byte.TYPE))
return (T) new Byte((byte) 0);
else if (type.equals(Character.class) || type.equals(Character.TYPE))
return (T) new Character((char) 0);
else if (type.equals(Boolean.class) || type.equals(Boolean.TYPE))
return (T) new Boolean(false);
else if (type.equals(BigDecimal.class))
return (T) BigDecimal.ZERO;
else if (type.equals(BigInteger.class))
return (T) BigInteger.ZERO;
else if (type.equals(AtomicInteger.class))
return (T) new AtomicInteger();
else if (type.equals(AtomicLong.class))
return (T) new AtomicLong();
else if (type.equals(DoubleAdder.class))
return (T) new DoubleAdder();
else
return null;
}
I use it in hibernate ORM projection queries when the underlying SQL query returns null instead of 0.
/**
* Retrieves the unique result or zero, <code>false</code> if it is
* <code>null</code> and represents a number
*
* #param criteria
*
* #return zero if result is <code>null</code>
*/
public static <T> T getUniqueResultDefault(final Class<T> type, final Criteria criteria)
{
final T result = (T) criteria.uniqueResult();
if (result != null)
return result;
else
return Utils.getDefault(type);
}
One of the many unnecessary complex things about Java making it unintuitive to use. Why instance variables are initialized with default 0 but local are not is not logical. Similar why enums dont have built in flag support and many more options. Java lambda is a nightmare compared to C# and not allowing class extension methods is also a big problem.
Java ecosystem comes up with excuses why its not possible but me as the user / developer i dont care about their excuses. I want easy approach and if they dont fix those things they will loose big in the future since C# and other languages are not waiting to make life of developers more simple. Its just sad to see the decline in the last 10 years since i work daily with Java.
I have commented between codes:
public class Main {
public static void main(String[] args) {
// This is local variable.
// Look! you have declared it within the "body of a method".
// Local variables must be initialized.
int a;
System.out.println(a);
}
}
Now the next one
public class Main {
//This is NOT a local variable. It is NOT in a method body!
//Look! you have defined it as class member ( or a property).
//Java is more generous with local variables and initiates them.
//(ex: int with 0, boolean with false, String(or any object) with null, ...)
static int a;
public static void main(String[] args) {
System.out.println(a);
}
}
I know here is no pointer in Java. But how do I change a value in the calling scope? For instance, I want to write a function that takes an integer num, set the integer to 0 if it's greater than 21, otherwise do nothing.
In the main, my code is as follow:
int a=34;
KillOver21(a);
System.out.print(a);
I expect an 0.
Java is pass by value, so a copy of the parameter a is sent to the method, so modification to a in the method will not affect the original argument a in main
The max you can do is return int from KillOver21(a) method
int z = KillOver21(a); // This will return 0
System.out.print(z);
But you can achieve something like that with custom objects, say you have a class
class AHolder {
public int a;
}
then you can expect AHolder instance to change
public static void main(String [] args) {
AHolder a = new AHolder();
a.a = 34;
killOver21(a);
System.out.println(a.a);
}
public static void killOver21(AHolder b) {
if(b.a > 21) {
b.a = 0;
}
}
Since in the latter (even if its Pass by Value) , the reference is copied and both reference point to same object. So changes made inside the killOver21 method actually changes the object.
It is simply not possible, Java supports pass by value. int a's value will be copied to the function.
You could use Object instead of primitive where the reference value will be copied to your function by which you can get the actual object and modify it.
Fundamentally impossible in Java, period. int are immutable, and passed by value. You would need to create a mutable int type:
class MutableInt {
private int value;
public MutableInt(int value) { this.value = value; }
public getValue() { return this.value; }
public setValue(int value) { this.value = value; }
}
Then:
void KillOver21(MutableInt m) {
if(m.getValue() > 21) { m.setValue(0); }
}
However, be aware the mutable types that represent concepts that are defined by their value rather than their identity are generally an extremely bad idea. But, this is the only way to achieve what you're trying to achieve. Again, I caution you with the strongest words: what you're doing is a bad idea. You should find another way.
Doc, it hurts when I do this.
Then don't do that!
The simpliest way (quick&dirty) is to put value within an array
int holder[] = new int[]{ a};
KillOver21(holder)
System.out.printf( "value=[%d]", holder[0] );
void KillOver21(int holder[] ) {
holder[0] = 0;
}