Error doing Array Initialization at Class Level [duplicate] - java

This question already has answers here:
Why can't I do assignment outside a method?
(7 answers)
Closed 7 years ago.
I am new to Java and started doing Arrays, however I am getting Compilation error with the below code. Pls help
public class TestingArrays {
int[] ank = new int[]{1,2,3,4,5};
int[] ans = new int[5];
ans[0] = 2;
}
If I comment the line //ans[0] = 2; then the error is gone, please explain

This is a class definition. You are allowed to declare and initialize members and methods. You are not allowed to write code as you would in a function body. Your code would work if you modify like this (Constructor):
public class TestingArrays {
int[] ank = new int[]{1,2,3,4,5};
int[] ans = new int[5];
TestingArrays() {
ans[0] = 2;
}
}
Or even like this (Initialization block) :
public class TestingArrays {
int[] ank = new int[]{1,2,3,4,5};
int[] ans = new int[5];
{
ans[0] = 2;
}
}

Do the initialization in a constructor or instance initializer.
TestingArrays() {
ans[0] = s;
}
You cannot have statements within the class body such as setting a value to a field.

Related

unable to use constructor in java [duplicate]

This question already has answers here:
java generics: can't create a simple print array method
(2 answers)
Closed 2 years ago.
I have started learing java generics and this is my priority queue implementation:
public class MinPQ<Key> implements Iterable<Key> {
private Key[] pq; // store items at indices 1 to n
private int n; // number of items on priority queue
private Comparator<Key> comparator; // optional comparator
public MinPQ(Key[] keys) {
n = keys.length;
pq = (Key[]) new Object[keys.length + 1];
.....
.....
}
}
And this is my main class :
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] ar = {1,2,3};
MinPQ<Integer> pq = new MinPQ<Integer>(ar);
}
}
But here I get an error stating "The constructor MinPQ(int[]) is undefined" can someone please help me find the issue here ?
You can't use primitive types with generics. Just change:
int[] ar = {1,2,3};
to:
Integer[] ar = {1,2,3};
or box it with
IntStream.of(ar).boxed().toArray(Integer[]::new)
Basically you're trying to pass an int[] to a constructor which requires Integer[], because of MinPQ<Integer> declaration. So, in tehory it should work if you declared it as MinPQ<int> - but as stated at the beginning we can't use primitive types for generics.

static variable declaration in class java [duplicate]

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

Beginner Java methods [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 5 years ago.
public class Test {
int[] a1 = {1, 3, 5, 7, 2};
int[] a2 = new int[a1.length + 10];
public static int[] Array(){
for(int i = 0; i < a1.length; i++){
a2[i] = a1[i];
}
a1 = a2;
}
public static void main(String args[]){
System.out.println(a1.toString);
}
}
I am trying to create a method "Array" that will take in arrays a1 and a2 and add + 10 to the length of a1. My problem is that I don't know how to correctly name the method and how to call it in the main in order to print.
I have tried passing a1 and a2 in the constructor for Array but it doesn't work. I have also tried printing directly in the main() and it doesn't work either. What am I missing?
No idea what are you trying to do but in Java you can't change the size of array once it is declared but if you want to work with array with can change size then you should use arraylist not array and one more thing setting b = awould not work btw here is a code which swaps elements from one array to other but once again you can't change size of array in java: I return b back but you don't need to return an array back because an array variable(name of array) refers to a memory location.
public static int[] extendLength(int [] a, int [] b){
for(int i = 0; i < a.length; i++){
b[i] = a[i];
}
return b;
}
public static void main(String args[]){
int[] a1 = {1, 3, 5, 7, 2};
int[] a2 = new int[a1.length + 10];
int [] res = extendLength(a1,a2);
for(int i = 0; i < a2.length;i++)
System.out.println(a2[i]);
}
Long story short, the way you have your program set up, your variables will also need to be static; otherwise, your static methods will not be able to access them.
Static fields and methods are essentially singular to the class; therefore without a director to which object contains the field, asking a static method to manipulate a non-static field is very ambiguous.
I'm seeing a number of other problems in this program as well; namely, you're treating toString as a field (it's a method), your array method is missing a return statement, and your alignment is all over the place. This probably isn't an appropriate question to bring to Stack Overflow; I would encourage you to look at a tutorial, like the one at Tutorials Point, before bringing your question here.

Syntax error while compiling arrays in java [duplicate]

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

Why is this void method not working as I would expect? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
Assuming that the Given array is instantiated as follows:
int[] given = {1, 2, 3, 4, 5};
These methods should change the array and show the print results.
public int[] change(int[] given) {
out.println(Arrays.toString(given)); //before-changes
whatIsGoingOn(given); //make changes
out.println(Arrays.toString(given));//after changes
return given; //return the supposedly changed array
}
//Make changes:
public void whatIsGoingOn(int[] given) {
given = new int[5];
given[0] = 200;
}
I BELIVE THE PROBLEM to be with the void method, overriding the original values of the int[] given but the new initialization and declarations never make it out.
I Would expect the array to be:
{200, 0, 0, 0, 0};
But Java prints out:
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
But in the case where I returned a newly changed array in the whatIsGoingOnMethod, I get my wanted results:
{1, 2, 3, 4, 5}
{200, 0, 0, 0, 0}
If the void method just does something and its not really being "applied" as I would like to expect. I'd appreciate an illuminating explanation for this.
This Question is ALREADY ANSWERED THANKS!!!
I need to freeze it.
With given = new int[5]; you are changing what the local variable given points to, not the object that it used to point to. The local is later out of scope. The array is never modified.
Youre creating a whole new array, and assigning the variable that used to refer to the original to the new array. Youre modifying the new array, and never touching the old one.
The appropriate fix would be similar to what follows:
public static void main(String[] args)
{
int[] original = new int[5];//already allocating memory, initializing to default value, etc.
setFirstTo20(original);
System.out.println(original[0]);//still 20!
}
public static void setFirstTo20(int[] given)
{
for (int i : given)
System.out.println(i);//for debugging, before change
given[0] = 20;
for (int i : given)
System.out.println(i);//after change
//heres whats happening to you
given = new int[5];
given[0] = 40;
for (int i : given)
System.out.println(i);//show new changes to NEW array
}
Obviously you should get rid of the extraneous code if you intend for this or similar methods to be used in actual classes.
Because the argument given of function whatIsGoingOn is passed by value.
To change it in a void function, you have to wrap it in an object like this:
class ArrayRef {
public int[] array;
}
public int[] change(int[] given) {
out.println(Arrays.toString(given)); //before-changes
ArrayRef ref = new ArrayRef();
ref.array = given; //set a reference to the given array
whatIsGoingOn(ref); //make changes
given = ref.array; //get the changed array
out.println(Arrays.toString(given));//after changes
return given; //return the supposedly changed array
}
//Make changes:
public void whatIsGoingOn(ArrayRef ref) {
ref.array = new int[5];
ref.array[0] = 200;
}
Arrays such as int[] are reference types. This means that when you do the assignment given = new int[5], you are chainging the array referenced within whatIsGoingOn() and not affecting the array referenced within change().
To do what you want it to, you need to loop though the array and change the individual elements within the array.
for(int i = 0; i < given.length; i++) {
given[i] = 0;
}
given[0] = 200;
change following lines of whatIsGoingOn method from
given = new int[5];
given[0] = 200;
to
Arrays.fill(given,0);
given[0] = 200;
It still holds reference to original array .No need to return anything.
Void quite simply will return nothing. Replace void with int[] to achieve your expected results. Also replace
public void whatIsGoingOn(int[] given) {
given = new int[5];
given[0] = 200;
}
with
public int[] whatIsGoingOn(int[] given) {
given = new int[5];
given[0] = 200;
return given;
}
the final result should be
public int[] change(int[] given) {
out.println(Arrays.toString(given)); //before-changes
given = whatIsGoingOn(given); //make changes
out.println(Arrays.toString(given));//after changes
return given; //return the supposedly changed array
}
//Make changes:
public int[] whatIsGoingOn(int[] given) {
given = new int[5];
given[0] = 200;
return given;
}

Categories