This question already has answers here:
Uninitialized variables and members in Java
(7 answers)
Closed 5 years ago.
Couldn't find an explicit description of what's happening so thought i'd bring this up to the community.
public class Temp {
static int i;
int j;
int sum = i+j;
}
public class Main{
public static void main(String[] args){
Temp obj = new Temp();
obj.i = 1;
obj.j = 2;
System.out.println(obj.sum); //returns '0'
}}
Is it because both integers i and j were empty during instantiation that the 'sum' variable is empty?
Thanks in advance!
Temp obj = new Temp(); // creates an instance of object type Temp
Here, data members, i, j, and sum are initialized to 0
obj.i = 1; // assigns value of Temp data member, i to 1
obj.j = 2; // assigns value of Temp data member, j to 2
Note that the value of data member sum of Temp Object obj is still 0.
To make, sum = i + j, you need to initialize it to i + j when i and j are initialized.
Simply write obj.setSum() method to set the value of sum and obj.getSum() after that to retrive the updated value of it.
public class Temp {
static int i;
int j;
int sum = i+j;
public void setSum(){
sum = i + j;
}
public int getSum(){
return sum;
}
}
public class Main{
public static void main(String[] args){
Temp obj = new Temp();
obj.i = 1;
obj.j = 2;
obj.setSum();
System.out.println(obj.sum); //OR obj.getSum()
}
}
Is it because both integers i and j were empty during instantiation
that the 'sum' variable is empty?
Yes, i+j is assigned to 'sum' when the Object is instantiated. By default java assign 0 to int values when you don't assign a value.
You need to update the sum variable by directly assigning the value to it.
obj.i = 1;
obj.j = 2;
obj.sum = obj.i + obj.j.
A workaround is to create a getter method in your Temp class instead of the variable sum:
public class Temp {
static int i;
int j;
public int getSum() {
return i + j;
}
}
Then to print the sum :
System.out.println(obj.getSum());
When you create another class that will be use by the main method
numeric data fields are set to zero
Character fields are set to Unicode \u0000
Boolean fields are set to false
Fields that are object references are set to null or (empty) for example String data fields
Related
My question is how do I find the frequency of the numbers "8" and "88" in this array, using a method. It seems as what I put in the assessor method does not appear to work. For example, if "8" occurs three times in the array the output would be "3" and the same for "88".
If I am wrong please point me to the right direction. Any help with my question is greatly appreciate.
import java.util.Random;
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// initialize array
arr = new int[MAX_ARRAY_SIZE];
// randomly fill array with numbers
Random rand = new Random(1234567890);
for (int i = 0; i < MAX_ARRAY_SIZE; ++i) {
arr[i] = rand.nextInt(MAX_VALUE) + 1;
}
}
public void printArray() {
for (int i = 0; i < MAX_ARRAY_SIZE; ++i)
System.out.println(arr[i]);
}
public int countFrequency(int value) {
for (int i: MAX_VALUE) {
if (i == 8)
i++;
}
public static void main(String[] args) {
ArrayPractice ap = new ArrayPractice();
System.out.println("The contents of my array are: ");
ap.printArray();
System.out.println("");
System.out.println("The frequency of 8 is: " + ap.countFrequency(8));
System.out.println("The frequency of 88 is: " + ap.countFrequency(88));
}
}
}
You need to iterate over arr and increment a variable when an element matches value.
public int countFrequency(int value) {
int count = 0;
for (int num : arr) {
if (num == value) {
count++;
}
}
return count;
}
You have a hard-coded seed, so your random values won't be random on different runs. You are also hard-coding your frequency count against 8 (instead of value). But honestly, I suggest you revisit this code with lambdas (as of Java 8), they make it possible to write the array generation, the print and the count routines in much less code. Like,
public class ArrayPractice {
private int[] arr;
private final int MAX_ARRAY_SIZE = 300;
private final int MAX_VALUE = 100;
public ArrayPractice() {
// randomly fill array with numbers
Random rand = new Random();
arr = IntStream.generate(() -> rand.nextInt(MAX_VALUE) + 1)
.limit(MAX_ARRAY_SIZE).toArray();
}
public void printArray() {
IntStream.of(arr).forEachOrdered(System.out::println);
}
public int countFrequency(int value) {
return (int) IntStream.of(arr).filter(i -> i == value).count();
}
}
You need to iterate over the array and increment a counter variable when an element matches i
what you are doing is increment i instead of a counter:
if (i == 8)
i++;
} // if i is 8 then i becomes 9
A working example:
public int countFrequency(int i) {
int count = 0;
for (int num : arr) {
if (num == i) {
count++;
}
}
return count;
}
Solution:
public int countFrequency(int value) {
int counter = 0; // here you will store counter of occurences of value passed as argument
for (int i : arr) { // for each int from arr (here was one of your errors)
if (i == value) // check if currently iterated int is equal to value passed as argument
counter++; // if it is equal, increment the counter value
}
return counter; // return the result value stored in counter
}
Explanation:
Main problem in your code was countFrequency() method, there are few bugs that you need to change if you want to make it work correctly:
You passed value as argument and you didn't even use it in the body of method.
for (int i : MAX_VALUE ) - you meant to iterate over elements of arr array, (You can read it then as: For each int from arr array do the following: {...}.
if (i == 8) i++ - here you said something like this: Check if the current element from array (assuming that you meant MAX_VALUE is an array) is equal to 8, and if it is - increment this value by 1 (so if it were 8, now it's 9). Your intention here was to increment counter that counts occurences of 8.
You might want to consider making these improvements to countFrequency() method, to make it work properly.
Where is "int size " getting it's value from? I read code like 1000 times,but I still have no clue where is "size" initialized, I am new in java, but I don't understand this one,code is working fine any help would be nice. thanks in advance
public class Study {
public static void main(String[] args) {
Queue queue = new Queue();
for (int i = 0; i <= 20; i++)
queue.enqueue(i);
while (!queue.empty())
System.out.print(queue.dequeue() + " ");
}
}
class Queue {
private int[] elements;
private int size;
public Queue() {
elements = new int[8];
}
public void enqueue(int value) {
if (size >= elements.length) {
int[] temp = new int[elements.length * 2];
System.arraycopy(elements, 0, temp, 0, elements.length);
System.out.println(elements.length);
elements = temp;
}
elements[size++] = value;
}
public int dequeue() {
int v = elements[0];
// Shift all elements in the array left
for (int i = 0; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
size--;
return v;
}
public boolean empty() {
return size == 0;
}
public int getSize() {
return size;
}
}
Default value is 0 for int.
And size++ and size-- is doing the changes to its value.
For more information refer: Assignment, Arithmetic, and Unary Operators
size++ is equal to the statement size = size + 1, the same for size-- which does size = size - 1
All instance variables will be assigned a default value by the compiler if you haven't provided one.
Snippet from java doc
Default value will be zero or null depending the data types.
The link also has a grid which tells you about the default values for all data types.
Local variables are variables which are used inside a method:
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.
I'm testing the result of this code, to realise how the static object creating works.
Basically i understood everything till the last System.out.println(" " + a[0]); I ran the debugger, and i verified that in that point, all of the elements of the array have the same value on num variable.
Can anyone explain me why is it happen?
static class Numero {
private static int sn = 0;
private int num;
public Numero(int n) {
num = n;
++sn;
}
public void setNum(int n) {
num = n;
}
public String toString() {
return "num = " + num + " sn = " + sn;
}
}
public static void main(String[] args) {
Numero[] a = new Numero[3];
Numero x = new Numero(12);
for (int i = 0; i < a.length; i++) {
a[i] = x;
a[i].setNum(i);
System.out.println(" " + a[i]);
}
System.out.println(" " + a[0]);
}
Output:
num = 0 sn = 1
num = 1 sn = 1
num = 2 sn = 1
num = 2 sn = 1
This is because your Numero object is mutable. When you modify it in any way, all references to it are modified as well.
When you call a[i] = x:
You don't create a copy of x and put it in position i.
You do store a reference to x at position i.
So, by the end of your iteration, your array has stored three references to the same object (you can think of it as {x, x, x}). And since that object has changed throughout the loop (because a[i].setNum(i) is equivalent to x.setNum(i)), your last output prints the num value as 2.
You created a single Numero, so sn got incremented once, to 1. That same instance got assigned to each element of a; you saw different values for num because you printed it out at different times.
Making a static class essentially enforces the singleton design pattern. The class can only have static methods and static instance fields. Static instance fields hold the same value across all instances of the class, and you can think of it as all objects of that class sharing the same variable instead of having copies of it.
When you print a[0] in the loop, you get what you expect, but after the loop, that static ("shared") variable was changed by other objects, leaving num to be the value of 2, set by the last iteration of the for loop.
issue lies here
a[i] = x;
a[i] is pointing to X now , so whenever you call setNum method ,method belongs to X .so you will get same instance output always
I need to be able to input a list of numbers the last being -1 and have it print the reverse(not including -1) and then find the average. I have to use a function for finding the reverse. Im stuck because it cannot resolve my average which means I cannot run the program to see if there are other problems.
import java.util.Scanner;
public class Reverse {
public static void inReverse (int a) {
int number;
int[] value;
for (a = number - 2; a >= 0; a--) {
System.out.print(value[a] + " ");
}
}
public static double findAverage (int p, double average) {
int number;
for (p = number - 2; p >= 0; p--) {
average += value[p];
}
average = average / (number - 1);
return average;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] value;
int i, number, size;
size = 20;
System.out.println("Please enter the integers: ");
while (value[i - 1] != -1 && number < size) {
value[i] = input.nextInt();
i += 1;
number = i;
}
System.out.println("The values in reverse order are: ");
inReverse(i);
System.out.println(" ");
System.out.println("The average is " + average);
}
}
Your problem is that you have confused "local variables" with "fields".
Local variables are variables that you declare inside the body of a method. They can't be used before the declaration, and they can't be used once the method stops running - their values have ceased to exist.
Fields are variables that you declare inside your class, but outside any methods. These live inside each object of the class (or inside the class itself if you declare them as static), which means they keep their values from one method call to the next.
You have int number; and int[] value; declared inside different methods, which means they are local variables, and they are recreated each time those methods run. This isn't what you want. You either want to pass them from one method to the next, as parameters; or to have them as fields of your class.
I am just consfused on how to implement these two methods like how call them or use them? Since the first one is void how does it work?
someone please use and an array and implement this for me or help me understand how the first void method works?
public static void insertionsort(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int copyNumber = numbers[i];
int j = i;
while (j > 0 && copyNumber < numbers[j-1]) {
numbers[j] = numbers[j-1];
j--;
}
numbers[j] = copyNumber;
}
}
public int[] InsertionSort(int[] data){
int len = data.length;
int key = 0;
int i = 0;
for(int j = 1;j<len;j++){
key = data[j];
i = j-1;
while(i>=0 && data[i]>key){
data[i+1] = data[i];
i = i-1;
data[i+1]=key;
}
}
return data;
}
A function with return type does something (executes code) and returns some result back to the code that called that function. A function without return type executes some code but does not return a result ( because it is not needed in most cases )
Consider this two functions:
public static int withResult( int someParameter)
{
//execute some code here
int someReturnValue = //result of the code above
return someReturnValue;
}
public static void withoutResult( int someParameter)
{
//execute some code here which produces no result which could be of interest to the caller (calling code)
} //end the function without returning anything
You would call it like this:
int result;
result = withResult( 1234 );//executes the function and stores its return type in 'result'
withResult( 468 );//executes the function but does not store the return type anywhere ("throws it away")
withoutResult ( 1234 );//simply executes the function
result = withoutResult ( 5678 ); //this makes no sense because the function does not return anything
In java everything is passed by value, including references. In your void method, the value of a reference to the array is passed. So while you cannot assign a new int [] to numbers, you are able to change the ints in numbers.
The first method, returning void (i.e., not returning anything) is passed an array as a parameter. What is passed is a reference to an array that is declared and for which memory is allocated outside the method. The method sorts that information in place; when the method returns, the data in that array is then sorted.
int[] myArray = getArrayInfo(); // assume this gets data in an array
WhateverClass.insertionSort(myArray); // this will sort that data
// at this point, myArray will be sorted