writing a static method to set counter java? - java

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

Related

how does this code give new id for each thing object. id should be equal to 1 all the time

class Thing {
public static int count = 0;
public int id = 0;
public Thing() {
id = count;
count++;
}
public void ID() {
System.out.println("This object has id: " + id);
}
}
public class wth {
public static void main(String[] args) {
Thing thing1 = new Thing();
Thing thing2 = new Thing();
Thing thing3 = new Thing();
thing1.ID();
thing2.ID();
thing3.ID();
}
}
Shouldn't this code print 1
1
Here is what I understand of the code:
First of all, the thing1 object is created and the constructor Thing runs thus making id=0 and count=1. Then thing2 is created and again the constructor runs making id=1 and count=2.
Now thing1.ID() runs printing the value of id which should be 1 but instead its 0 please explain how is it 0.
public static int count=0;
This line means that the variable count is linked to the class, not the object. So every time a new Thing is created, the incrementation of this variable is applied across all the objects instantiating the class, including new instances that are made.
You can find more info in the official doc/tutorial here.
This code illustrates the way static works. count is shared among all objects of the class, so it gets incremented each time a new Thing object is instantiated.
Note: This will break in concurrent environments: if you run this from multiple threads, some objects may get the same id. A better implementation would use AtomicInteger:
class Thing{
public static AtomicInteger count = new AtomicInteger(0);
public int id;
public Thing(){
id=count.incrementAndGet();
}
...
}
count is static, which is why it gets incremented each time you create a new instance of Thing but id isn't. That means that each instance of Thing, being thing1and thing2 will each have their own id.
In your question:
value of id which should be 1 but instead its 0 please explain how is
it 0.
What I understood, you asking for first time you create object it's value should be 1 and next time increment by 1. If it is asked for,
Reason:
When you create first object(thing1) you are calling default constructor(Thing()), which you have implemented. And in the first line you assigning count variable value to id variable which is 0. Then you increment count by one. It is not affecting to id variable first time. Then, you call the ID() method, it will print, value that it hold 0.
Solution:
public Thing() {
id = count;
count++;
}
move the count++; to first line. Should be:
public Thing() {
count++;
id = count;
}
Output become:
This object has id: 1
This object has id: 2
This object has id: 3
Because of static each time you create new object count will increment.
If you want to get outputt as 1 every time:
First you want to know about static keyword:
Attributes and methods(member of a class) can be defined as static.
static members do not belongs to an individual object.
static members are common to all the instances(objects of the same class).
static members are stores in static memory(a common memory location which can by everybody).
The static modifier indicates that the count variable(attribute) are common to all the Thing in the whole class rather than to an individual object.
To answer your question:
public static int count = 0;
As I mention above this count variable common for all the objects. That means when you create a different objects it's value not changed.
remove the static modifier, should be:
public int count = 0;
When you removed static modifier count variable become individual for all the objects that you are creating. And for each object it will print as follows:
This object has id: 0
This object has id: 0
This object has id: 0
If you move the count++; to first line.
public Thing() {
count++;
id = count;
}
Output become:
This object has id: 1
This object has id: 1
This object has id: 1

Why there is need of return statement

I have very silly doubt that why we use return statement in method . Without using return statement in method we can also get required value
as example
package testing;
public class ReturnMethod {
static int a = 10;
static int b = 5;
static int c;
static int d;
public static void add() {
c = a + b;
}
public static int returnAddValue() {
d = a + b;
return d;
}
public static void main(String[] args) {
add();
System.out.println("c: " + c);
int value = returnAddValue();
System.out.println("value: " + value);
}
}
In above example in both the cases i am getting output
c: 15
value: 15
So i am having doubt when to use return statement and why is neccessary
With return statement, the return value is not necessary to be saved in any global, external or member variable.
However, without return statement you have to prepare kind of outer variable value to track that.
If you assign the result of a method to a static variable (and, indeed, pass in the "parameters" of the method by setting static variables), you have problems when that method is called by two threads concurrently, since the variables are shared for all invocations of the method:
Thread t1 = new Thread(() -> {a = 1; b = 2; add(); }); t1.start();
Thread t2 = new Thread(() -> {a = 3; b = 4; add(); }); t2.start();
t1.join(); t2.join();
You don't know which of these threads run first, or even if they run at the same time; so you don't know what the value of a or b is when you call add(), and nor do you know whether the value in c afterwards is the result of the invocation in the first or second thread (or a mixture of the two).
The value stored in c afterwards could be any of 3, 5 or 7 (or any other value, if there is another thread which is also invoking add() concurrently outside this code.
This problem of thread interference just completely goes away if you keep values localized to the stack, by passing a and b as method parameters, and receiving the result as a return value.
Even if your code is single-threaded, it's simply ugly to have to write:
a = 1;
b = 2;
add();
int result = c;
rather than
int result = add(1, 2);
You should use a return statement, when you need the method to return a value.
In your case, both methods work.
But you can, and should use returning methods, when you don't want a field of your class to be changed by another class.
For example, you want money to be only seen, and not changed, when you are making a bank-account related software. So, you make money private, and make a method which returns the money. In this way, other classes can only see money, but not change it.
First, your functions are different, as you see
public static **void** add()
public static **int** returnAddValue()
First one does not return anything, because it has void as return type and the second one has int as return type.
First one works, because c is a global variable.
You typically would use return when you don't store the result in a (static) variable of your class.
public class ReturnMethod {
static int a = 10;
static int b = 5;
public static void add() {
int c = a + b;
}
public static int returnAddValue() {
int d = a + b;
return d;
}
public static void main(String[] args) {
add();
//not possible to access c here
//System.out.println("c: " + c);
int value = returnAddValue();
System.out.println("value: " + value);
}
}
In that modified example, there would be no way for you to access the result of the add() method.
You should probably read about Scopes in Java.
You have a class variable c & d. These variables are associated with the class and stored in heap. If you assign a value back to it and you can access it without a explicit return statement. But if you have declared d inside the method then return statement is required to give the value back to the caller.
The reason that you are able to access the value of class variable c is that it has been initialized as static. Had this not been the case the information in the c variable would be lost as soon as the add method ends. The reason methods have return value is that they user can get the updated value , if there are any manipulation in the object data. In this case there is a very small, what if there is series of manipulation with the data. In that case the final value has to be returned to the calling object which without return statement is not possible.
Its totally depends upon our requirement whether to return a value from our method or update instance variable. Some time we just want to process a value and get back the result in and result will be used in different manner, in this case we need to return value from method.
For example
java.lang.Math.sqrt(double a) method return a value and we use returned value as per our need OR requirement. Can you think if this method does not returned any value then what it should update, I think this method useless if it does not returned any value.
The variable C in your code snippet is accessed in the class throughout, and will stay until the object of the class exists. So you can print the value of Variable C outside the method.
However, if you had declared a local variable in the method add(), then print statement System.out.println("c: " + c); will print the default value for variable c. That is zero in this case.

Why an instance variable can be assigned and not be referenced before its declaration in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java static class initialization
in what order are static blocks and static variables in a class executed?
When I run this code the answer is 1, I thought it would be 2.
What is the order of initialization and the value of k in each step?
public class Test {
static {k = 2;}
static int k = 1;
public static void main(String[] args) {
System.out.println(k);
}
}
Edit 1: As a follow up to "k is set to default value" then why this next code doesn't compile? Theres an error "Cannot reference a field before it's defined".
public class Test {
static {System.out.println(k);}
static int k=1;
public static void main(String[] args) {
System.out.println(k);
}
}
Edit 2: For some unknow to me reason it^ works when instead of "k" its "Test.k".
Thanks for all the answers. this will sufice :D
They are executed in the order that you write them. If the code is:
public class Test {
static int k = 1;
static {k = 2;}
public static void main(String[] args) {
System.out.println(k);
}
}
then the output becomes 2.
The order of initialization is: ..the class variable initializers and static initializers of the class..., in textual order, as though they were a single block.
And the values (for your code) are: k = 0 (default), then it's set to 2, then it's set back to 1.
You can check that it's actually set to 2 by running the following code:
private static class Test {
static {
System.out.println(Test.k);
k = 2;
System.out.println(Test.k);
}
static int k = 1;
public static void main(String[] args) {
System.out.println(k);
}
}
Short answer
When the initialization of the class starts, k will have initial value of 0.
The static block (since it precedes the assignment in the declaration) is then executed, and k will be assigned 2.
Then the initializer in the declaration is executed, and k will be assigned 1.
Long explanation
Let us use this example, since your example is a bit simple:
class TestInitOrder {
static {
System.out.println(TestInitOrder.stat1);
System.out.println(TestInitOrder.stat2);
System.out.println(TestInitOrder.str);
System.out.println(TestInitOrder.str2);
str = "something";
System.out.println(TestInitOrder.str);
System.out.println(TestInitOrder.str2);
System.out.println(TestInitOrder.lazy);
System.out.println(TestInitOrder.second);
}
private static final int stat1 = 10;
static final String str2 = "sdfff";
static String str = "crap";
private static int stat2 = 19;
static final Second second = new Second();
static final int lazy;
static {
lazy = 20;
}
static {
System.out.println(TestInitOrder.str2);
System.out.println(TestInitOrder.stat2);
System.out.println(TestInitOrder.str);
System.out.println(TestInitOrder.lazy);
System.out.println(TestInitOrder.second);
}
public static void main(String args[]) {
}
}
class Second {
public Second() {
System.out.println(TestInitOrder.second);
}
}
According to Java Language Specification, from section 4.12.5:
Every variable in a program must have a value before its value is used:
Each class variable, instance variable, or array component is initialized with a default value when it is created
(The following lines from the specification specify the default value for all the types, basically some form of 0, such as 0, 0.0d, null, false, etc.)
So before the class is initialized (due to one of these reasons), the variables will hold an initial value.
According to the detailed initialization procedure (only the interesting steps are quoted here, and emphasis mine):
6.
[...] Then, initialize the final class variables and fields of interfaces whose values are compile-time constant expressions (§8.3.2.1, §9.3.1, §13.4.9, §15.28).
[...]
9.
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
Let us look at step 6, with the 4 final class variables: stat1, str2, second, lazy.
Since 10 is constant expression, and so is "sdfff", and due to the order of execution, it is not possible to observe the initial value for str2 and stat1. In order to make an observation, the earliest you can do is in step 9.
The case of second demonstrate that when the right hand side is not a compile-time constant expression, so its initial value is visible.
The case of lazy is different, since the assignment is done in static block, and hence happen in step 9 - so it is possible to observe its initial value. (Well, the compiler checks carefully that lazy is assigned exactly once).
After the initialization of final class variables with compile-time constant expression comes the execution of static blocks and the rest of the initializers.
As you can see from the example, the static blocks and initialization happens according to textual order - demonstrated with the use of str variable - it is first printed out as null, then something, then crap.

Default values and initialization in Java

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);
}
}

how avoid set a global variable in recursive class

I have a global variable in a recursive class, each time I call it, the variables are created. The variable at begin is: int count = 0, then in the method I increase: count ++, the problem is when call again the class, the variable is reset to zero. I need the variable "count" remains in 1, to again increase in each call to 2,3,4.... etc
I try with this: private static int count = 0; but not work..
Search the code for all references to your count variable. Most likely, you are re-setting to 0 somehow. For example:
private class MyClass {
private static int count = 0;
public MyClass() {
count = 0; //Bad line
}
public void incrementCount() {
count++;
}
}
If you have something like that, then every time you create a new MyClass object, you would be resetting count to 0 for all MyClass objects.
But you really need to add your class code to your question. Otherwise we can't help.

Categories