This question already has answers here:
Java: When is a static initialization block useful?
(13 answers)
Closed 5 years ago.
Why is this declaration wrong? This declaration leads to identifier expected error
class Abc{
static ArrayList<Integer> p;
p = new ArrayList<Integer>(); // identifier expected error
}
You have a freestanding assignment statement in your class body. You can't have step-by-step code there, it has to be within something (an initializer block, a method, a constructor, ...). In your specific case, you can:
Put that on the declaration as an initializer
static ArrayList<Integer> p = new ArrayList<>();
Wrap it in a static initialization block
static {
p = new ArrayList<Integer>();
}
More in the tutorial on initializing fields.
This is the right way to do it :
import java.util.ArrayList;
public class Abc {
static ArrayList<Integer> p;
static {
p = new ArrayList<Integer>(); // works
}
}
Related
This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 3 years ago.
I am trying to insert String values (using a Scanner) into an ArrayList.
I am getting the error:
non-static method add(E) cannot be referenced from a static context.
I assume the add() method is the problem - what other methods can I use to insert into an ArrayList that is static?
import java.util.*;
public class Solution {
private static List<String> strings;
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
for(int i = 0; i < 5; i++){
String s = scanner.nextLine();
List.add(s);
}
}
}
You try to add a string to List interface (add() method is not static) but should add it to your instance List<String> strings:
strings.add(s);
Also, you should initialize strings
private static List<String> strings = new ArrayList<>();
otherwise, you will get NullPointerException.
This question already has answers here:
Java: When is a static initialization block useful?
(13 answers)
Static Initialization Blocks
(14 answers)
Closed 4 years ago.
Is there any difference in when static class member initialisation is done between the following two situations:
(1)
static ArrayList<String> x = new ArrayList<String>();
(2)
static ArrayList<String> x;
static
{
x = new ArrayList<String>();
}
As far as I understand it these are effectively equivalent and both guarantee that x is initialised once and once only, and before any class method or constructor can modify it.
First approach is less error prone, for example you can have a static block calling x.get(0); which will produce NullPointerException`
This question already has answers here:
Java instance variable declare and Initialize in two statements
(5 answers)
Closed 6 years ago.
This is a part of code i was working on .. but the compiler showed an error on line 1. (Syntax error on token";", , expected). Why is that error coming??
public class variable
{
int[] nums;
nums= new int[7];
}
You have to initialize the Array in same line as the declaration
public class variable
{
int[] nums = new int[7];
}
or you have to initialize it in a method or constructor:
public class variable
{
int[] nums;
public variable(){
nums= new int[7];
}
}
Hint: read about Java naming conventions. Class names should start with uppercase character.
You should use assignment inside a method or a constructor. Or you can instantiate it class level but you have to initialize it same line with declaration.
Eg: Class level instantiation.
public class Variable {
int[] nums = new int[7];
}
Use inside a method.
public class Variable {
int[] nums;
public void method(){
nums = new int[7];
}
}
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I would like to store reference to variable in some class, and make operations on it inside this class. Operations should modify original variable.
In particular following code should print 1 instead of 0.
class Test {
private Long metric;
public Test(Long m) {
this.metric = m;
++this.metric;
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Long metric = 0L;
Test test = new Test(metric);
System.out.println(metric);
}
}
How to achieve this behaviour?
You can replace Long with AtomicLong which is mutable. You'll lose autoboxing features though.
The problem in your code is that Integer is an immutable class.
Every time that you change the value you are really building a new instance of Integer.
Doing the same with mutable objects will work.
For example
class Test {
private StringBuilder metric;
public Test(StringBuilder m) {
this.metric = m;
this.metric.append(" Xter");
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
StringBuilder b = new StringBuilder("Hello ");
Test test = new Test(metric);
System.out.println(b.toString());
// Will print Hello Xter
}
}
As already metioned, the primitive wrapper classes are inmutable.
Since your metric is private in Test, and you want to use its value in the calling method main, you should use the java bean guidelines and use a getter for it:
public Long getMetric(){return this.metric;}
And on main:
metric=test.getMetric();
System.out.println(metric);
This question already has answers here:
What is an initialization block?
(10 answers)
Closed 7 years ago.
I read that an initializer block is "an unnamed code block that contains th code that initializes the class?
For example :
class A {
final int x;
final int y;
final String n;
{
x = 10;
y = 20;
}
public A(String name ) {
/* etc... etc */
I have never seen this type of code used, so I was wondering where it may be helpful. Why don't we just initialize variables in constructor ?
thanks
I think it can sometimes be helpful to initialize a variable immediately when it is defined.
public class Stooges {
private ArrayList<String> stooges = new ArrayList<>();
{ stooges.add("Lary"); stooges.add("Curly"); stooges.add("Moe"); }
// ... etc. other methods.
}
That initializer is now common to all constructors, so it avoids code duplication. You could use a private method and call similar code from within all constructors, but this way avoid even remembering to insert a method call. Less maintenance!
There could be other examples. If the initializer code calls a method that throws an exception, then you can't just assign it. You have to catch the exception.
A common use for this is the static initializer block:
class A {
static boolean verbose;
final int x;
final int y;
final String n;
static {
verbose = doSomethingToGetThisValue();
}
public A(String name ) {
/* etc... etc */
This is useful because your static variables might be used by a static method before an instance of the class is ever created (and therefore before your constructor is ever called).
See also this SO answer.