I had to make a program which was able to print symbols based off an array with numbers, with the numbers corresponding to the amount of symbols to print.
I got this to work; here is the code:
class printChart {
int[] values;
void barChart(int[] values){
for (int i=0;i<values.length;i++){
int number = values[i];
for (int j=0;j<number;j++){
System.out.print("*");
}
System.out.println();
}
}
void demo(){
barChart(new int[] {2,5,0,4,3});
}
public static void main(String[] args){
new printChart().demo();
}
}
My question is as follows: How does Java know that the {2,5,0,4,3} array should be assigned to the variable values? I'm assuming it's because I set void barChart to pass along int[] values, but I'd like to know more about the inner workings and what's going on exactly.
In Java, everything is pass-by-value and it is also important to know what the value is.
This method
void demo(){
barChart(new int[] {2,5,0,4,3});
}
Do the same as this one
void demo(){
int[] arr = new int[] {2,5,0,4,3};
barChart(arr);
}
In the first one, there is created new array with 2,5,0,4,3 values and its reference is copied to parameter values in barChart method.
In second one, there is created new array with 2,5,0,4,3 values and its reference is copied to variable arr. Then the value of arr (which is reference to array) is copied to parameter values in barChart method.
And this is how it works and why barChart method knows the values.
Also good point by Ćukasz, the second line does not do anything in your program, therefore you can change this :
class printChart {
int[] values;
void barChart(int[] values){
to this
class printChart {
void barChart(int[] values){
I'm not so sure what your question is, but let me tell you bit what you've done.
You've implemented a method(function) named void barChart(int[] value)
To run this method you must need to pass a one dimensional Array of Integer values to it.
Now comes the interesting part.
You've created a class Variable int[] values; in code line 2.
Also you've have created the lokal variable "value" in the method void barChart(int[] value).
What you've done is called overshadowing. The method "barChart()" only uses the lokal value which is passed to it when it is called.
You never used the class variable once, hence you could delete it.
Now if you want to use the class variable you could either:
a) Change the name of the variable (class or local)
b) In the method "barChart" write a this.value instead of just value. This will ensure that you are using the class variable and not the local one.
Related
I'm a Java beginner and I don't understand how to make it. When I write in my code something like in the example, my IDE underlines it and says it's wrong when I only started writing my code. Can anybody help me guys?
Example:
public class ArrayUtils {
public static int[] lookFor(int[] array) {
int[] array = {};
}
}
The variable named array is already passed in as a parameter. Which means that you cannot create a new int[] named array inside the java method. Try naming it something else.
Syntax with {} means initialization of your array like int[] array = {1,2,3}.
But you can't initialize the variable with the same name as parameter's name.
You can assign a new array to the variable:
public static int[] lookFor(int[] array) {
array = new int[6]; // assign to variable new array with length 6
array = new int[]{1,3,5}; // assign to variable new array with initialized values
}
Note: in first case all 6 values will be zero
Update: as it was mentioned by #ernest_k reassigning method parameters is a bad practice. To avoid it method parameter usually marked as final int[] lookFor(final int[] array)
The following code:
public static void main(String[] args) {
int first = 1;
int second = 2;
sum(first,second);
System.out.println(sum);
}
public static int sum(int a, int b){
int sum = a+b;
return sum;
}}
will return error and I need to write
int x = sum(first,second);
System.out.println(sum);
and define that method as integer x and print x.
But for array,
public static ArrayList<String> removeLast(ArrayList<String> list) {
//code
return list;
}
public static void main(String[] args) {
//code
removeLast(persons);
System.out.println(persons);
}
will print the returned value of array without defining as another array as the was with the previous one.
I am sorry if the question has already been asked as I couldn't find it. And I am just learning Java.
Arrays are passed by (value of) reference, therefore, any change that happens to the array inside the method, will actually change the array passed in to it. On the other hand ints are passed by value. Change an int inside a method, and it won't change the int passed into the method.
For this reason, the return statement in your array method is completely unnecessary. Your code will still change the array, even if you omit the return statement.
But there's another misconception that needs to be pointed out: when you sum two ints, you are creating a new value in memory, which exists as long as the method is executed. When the sum method is done, the sum int doesn't exist anymore. To retain its value, you need to return it from within the method, and assign it to a variable where you call the code.
Because Java is pass by value, but the value of reference types (including arrays) is a reference to the Object (in this case, a List). You might use a variadic function and (in Java 8+) an IntStream to implement it like
public static int sum(int... arr) {
return IntStream.of(arr).sum();
}
Then you can call sum with as many (or few) int arguments as you like.
Will print the returned value of array without defining as another
array as the was with the previous one ?
Whatever #yeedle mentioned above is correct, but one point to add as below:
ArrayList class (actual type of persons object) has overridden the toString() method such that it
could print the array details when you invoke
System.out.println(persons);.
You need to know that for your objects (created for your custom
classes like Product, Employee, etc..), you need to override
toString() method (inherited from java.lang.Object) to print the
values like how you wanted, otherwise simply using
System.out.println(object); will print the hashcode of the
object (like #HA5431 etc..).
You can look here and here
I consider myself an intermediate Java programmer having been at it for a year and a half and having some experience in other languages. However I have run into an issue that I feel I need an experts help on.
As I understand it arrays when created by java exist somewhat outside of where they were created i.e. if you create an array called s in one class and another called s in a second class then try to use both those classes as part of a program you will run into problems with them overwriting each other.
However this brings me to an interesting dilemma. What if one wanted to create a unique array on-demand for an infinite number of sets of user input. i.e. is it possible to have the user enter a string value for use as the array name or have a generic value that then gets a number or letter appended to it. This is more a theoretical issue (there being other ways to accomplish the same thing) but any insight would be greatly appreciated.
i.e. is it possible to have the user enter a string value for use as
the array name or have a generic value that then gets a number or
letter appended to it.
The user should not need to care about your array names. The name of an array should neither be visible to the user, nor should it affect your application in any way.
If you want to allow the user to create collections of elements that he can store under a FriendlyName you could use a (Hash)map for that:
Map<String, Integer[]> userDefinedArrays = new HashMap<>();
userDefinedArrays.put("NameTheUserSelectsForThisArray", new Integer[]{1,2,3});
The "Key" of this map will be the FriendlyName provided by the user - he still does not know, that the actual map is called userDefinedArrays - or even someMapThatHoldsSomeThingsTheUserWantToUse.
The name of a actual variable needs to be set during designtime and is fixed (at least in java)
if you create an array called s in one class and another called s in a second class then try to use both those classes as part of a program you will run into problems with them overwriting each other.
No! Each Variable declared exists inside it's own scope! You can change the value of an array inside it's scope, and also reuse the same name inside different scopes - it doesn't matter. If you try to redeclare a variable already existing withing the current scope your compiler will warn you! - you simple can not do that.
Example:
class MyApplication{
public static void Main(String[] args){
Integer[] arr1;
Integer[] arr1; //Compiler error!
}
}
but:
class MyApplication{
public static void Main(String[] args){
Integer[] arr1;
Integer[] arr2;
}
}
or
class MyApplication{
public static void Main(String[] args){
foo();
bar();
}
public static void foo(){
Integer[] arr1;
}
public static void bar(){
Integer[] arr1;
}
}
is fine. arr1 just exists within the scope of either foo() or bar().
As I understand it arrays when created by java exist somewhat outside of where they were created i.e. if you create an array called s in one class and another called s in a second class then try to use both those classes as part of a program you will run into problems with them overwriting each other.
I think maybe you are misunderstanding. This will not happen unless you do it intentionally like yshavit points out in your comments. A member of a class named S in the class Cat, will not point to a member named S in the Dog class. You would have to go out of your way to do this.
In short, this will not happen by accident most of the time if you are instantiating your classes without passing references between them when you do.
What if one wanted to create a unique array on-demand for an infinite number of sets of user input.
You may want to use an ArrayList
ArrayList<String[]> myList = new ArrayList<String[]>();
Or a hashmap
Map<Integer,String[]> myMap = new HashMap<Integer,String[]>();
Which one you use depends on what you are using it for. If you need faster access to arbitrary elements use a map. If you plan to access them iteratively, an ArrayList will work fine.
is it possible to have the user enter a string value for use as the array name or have a generic value that then gets a number or letter appended to it. This is more a theoretical issue (there being other ways to accomplish the same thing) but any insight would be greatly appreciated.
In this case you want to use the hashmap solution, You can choose the key type of a map in java quite easily.
You will want to read this
http://docs.oracle.com/javase/6/docs/api/java/util/Map.html
or this, to get started.
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
Two different class you're talking about is ClassOne & ClassTwo in my example. As you told, there is some kind of conflict while keeping the field name same. I've used arr for both classes. The reason to make MyArray super class is just code reuse. Why I used abstract MyArray class & why I used public static field isn't our matter of discussion. In TestApp, I've used arr of both classes ClassOne & ClassTwo without any problem.is it possible to have the user enter a string value for use as the array nameIMHO it may be possible using Reflection API or Dynamically Typed Language can do it. I'm not much sure about that.
class ClassOne extends MyArray {
public static int[] arr = new int[5];
}
class ClassTwo extends MyArray {
public static int[] arr = new int[5];
}
abstract class MyArray {
public static void setValue(int arr[], int index, int value) {
arr[index] = value;
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
public class TestApp {
public static void main(String[] args) {
ClassOne.setValue(ClassOne.arr, 1, 30);
ClassTwo.setValue(ClassTwo.arr, 1, 50);
ClassOne.printArray(ClassOne.arr);
ClassOne.printArray(ClassTwo.arr);
ClassTwo.printArray(ClassOne.arr);
ClassTwo.printArray(ClassTwo.arr);
}
}
I am trying to get getIntArrayString to accept parameters given to it, unlike abc.getAverage which uses the field testArray.
edit: Forgot to ask the question.
how would I be able to send parameters such as test1 to getIntArrayString()?
private int testArray;
public static void main(String[] args)
{
int[] testArray = new int[]{2,4,6,8,9};
ArrayHW abc = new ArrayHW(testArray);
System.out.printf(abc.getAverage());
int[] test1= new int[]{3,4,5,6,7};
System.out.printf("Array Values: %s\n",ahw.getIntArrayString());
int[] test1= new int[]{3,4,5,6,7}
System.out.printf("Array Values: %s\n",ahw.getIntArrayString());
}
I'm assuming you have a method named getIntArrayString inside another class. If you want to send the values of test1, the method getIntArrayString must have a parameter of test1's datatype. For example,
public int getIntArrayString(int [] x)
{
}
You should review your knowledge of methods.
Having two variables called testArray may seem a little confusing, but it's not syntactiacally wrong. However, it's less confusing to read your code if you don't, and even better if you remove any unused variables.
You are not posting any error messages, but I suppose you can't compile because you haven't declared any variable "ahw", and ahw.getIntArrayString() produces a compiler error.
In general, in order to be able to send a parameter of type int[] to a method it would be declared like this:
public String getIntArrayString(int[] intArray) { ... }
And you would call it like this
System.out.println(x.getIntArrayList(test1));
where test1 is an int array as declared in your own code.
I'm doing a task for a course in Java programming and I'm not sure how the following thing is working? The method below takes the value from an array and a integer. The integer should be added to the array and then be used outside the method in other methods and so on, but how could this work when the method has no return for the new content of the array? There is a void in the method? Have I missed something? Preciate some help? Is there something about pointers?
public static void makeTransaction(int[] trans, int amount);
Arrays in Java are objects. If you modify the trans array inside the method, the changes will be reflected outside of it1. Eg:
public static void modify(int[] arr)
{
arr[0] = 10;
}
public static void main(...)
{
int x = {1, 2, 3};
System.out.println(x[0]); // prints 1
modify(x);
System.out.println(x[0]); // now it prints 10
}
Note that native arrays can't be dynamically resized in Java. You will have to use something like ArrayList if you need to do that. Alternatively you can change the return type to int[] and return a new array with the new element "appended" to the old array:
public static int[] makeTransaction(int[] trans, int amount)
{
int[] new_trans = Arrays.copyOf(trans, trans.length + 1);
new_trans[trans.length] = amount;
return new_trans;
}
1 It is also worth noting that as objects, array references are passed by value, so the following code has no effect whatsoever outside of the method:
public void no_change(int[] arr)
{
arr = new int[arr.length];
}
You can't add anything to an array. Java arrays have a fixed length. So indeed, what you want to do is impossible. You might make the method return an int[] array, but it would be a whole new array, containing all the elements of the initial one + the amount passed as argument.
If you want to add something to an array-like structure, use an ArrayList<Integer>.
Do you have to keep the method signature as is?
Also, can you be a bit more specific. When you say "the integer should be added to the array", are you referring to the amount argument? If so, then how is that amount added? Do we place it somewhere in the array or is it placed at the end, thus extending the array's length?
As far as pointers go, Java's pointers are implicit, so if you don't have a strong enough knowledge of the language, then it might not be so clear to you. Anyways, I believe that Java methods usually will pass objects by reference, and primitives by value. But, even that isn't entirely true. If you were to assign your object argument to new object, when the method terminates, the variable that you passed to the method is the same after the method executed as it was before. But, if you were to change the argument's member attributes, then when the method terminated those attributes values will be the same as they were inside of the method.
Anyways, back to your question, I believe that will work because an array is an object. So, if you were to do the following:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
}
// static int i;
/**
* #param args
*/
public static void main(String[] args)
{
int[] trans = {0,1,3};
makeTransaction(trans, 10);
for(int i = 0; i<trans.length; i++)
{
System.out.println(trans[i]);
}
}
The output of the array will be:
10
1
3
But, watch this. What if I decided to implement makeTransaction like so:
public static void makeTransaction(int[] trans, int amount)
{
trans[0] = amount;
trans = new int[3];
}
What do you think that the output will be? Will it be set to all zero's or will be the same as it was before? The answer is that the output will be the same as it was before. This ties in to what I was saying earlier.
I might've assigned that pointer to a new object in memory, but your copy of the pointer inside of the main method remains the same. It still points to the same place in memory as it did before. When the makeTransaction method terminates, the new int[3] object that I created inside of it is available for garbage collection. The original array remains intact. So, when people say that Java passes objects by reference, it's really more like passing objects' references by value.