I am currently trying to create a multithread that will display all the even numbers, then odd numbers, from 0 - 30. My question is, how can I use my x variable to set what i is equal to?
import java.util.*;
class multiThread implements Runnable {
multiThread(int a) {
int x = a;
}
public void run() {
try {
for(int i=x; i<=30;i=i+2) {
System.out.println(i);
}
}catch(Exception e){
}
}
}
Use int x variable as a class variable like this,
private int x;
This int x local variable can't access on for loop block
The variable 'int x' is define in function 'multiThread(int a)',
So you can only use it belong its own scope.
I think you'd better define the variable 'int x' in class scope.
Related
public class Practice {
int x;
static int y;
void functionA() {
int y = 0;
System.out.println("inside non static method functionA()");
x = 10;
y = 30;
System.out.println(x);//10
System.out.println(y);//30
functionZ();
System.out.println(x);//10
System.out.println(y);//30
}
static void functionZ() {
System.out.println("inside static method functionZ()");
System.out.println("y: " + y);//prints 0, thought it was supposed to be 30?
}
public static void main(String[] args) {
Practice s = new Practice();
s.functionA();
}
}
Can someone explain why upon execution, inside functionZ(), y is printed as 0 and not 30? Before z is invoked, in functionA we've already set the value to 30. And since there is supposed to only be one copy of a static variable across all instances of an object, shouldn't it be 30?
Inside your functionA you defining a local variable y:
void functionA() {
int y = 0;
...
While you are in that function all access to y will go into this variable, so you set it to 30. This did however not impact the static variable y, which still has the value 0 and it is accessed from the static method functionZ.
To emphasize you want to access the static variable y rather than the local variable y, use the qualified identifier Practice.y.
There is a huge difference in global variable and local variable.
Global variables have the scope in the entire class.
Where as local variable have the the limited scope only within the method or the block in which it is declared.
Here you have declared static int y; which is global variable and can be accessed by functionZ().
Whereas the variable int y=0; declared in functionA() is a local variable, can only be accessed within the functionA() method itself. Meaning other methods DO NOT even know that variable even exists.
Lets say you remove static int y; and in funtionZ() method you will get an error beacuse it doesnt find any variable y
class Myclass {
public static void main(String[] args) {
int x; // Declared in main method
if (true) {
for (int i = 0; i < 5; i++) {
x = 5;// initialized inside loop
}
}
System.out.println(x);// accessing outside for loop
}
}
This gives an error: variable x might not have been initialized
System.out.println(x);
^
1 error;
However, below code working fine
class Myclass {
public static void main(String[] args) {
int x; // Declared in main method
if (true) {
x = 5;// initialized in if block
for (int i = 0; i < 5; i++) {
// x=5;
}
}
System.out.println(x);// accessing outside if loop
}
}
Here in both the code, the only difference is that in 1st case, the variable is initialized in "for loop" while in 2nd case it is initialized in "if block". then why it is making difference. Kindly explain to me as I am not able to find the real reason.
The problem is that the compiler doesn't know thatx will be initialized when you access it. That's because the compiler doesn't check whether the loop body will actually be executed (there might be rare cases where even such a simple loop might not run).
The same would be true for your if-block if the condition wouldn't be always true, i.e. if you'd use a boolean variable like this:
int x;
boolean cond = true;
if( cond ) {
x = 5;
}
//The compiler will complain here as well, as it is not guaranteed that "x = 5" will run
System.out.println(x);
You as a human would say "but cond is initialized to true and will never change" but the compiler doesn't know for sure (e.g. because of possible threading issues) and thus it will complain. If you'd make cond a final variable then the compiler would know that cond would not be allowed to change after initialization and thus the compiler can inline the code to effectively have if(true) again.
In this code:
public static void main (String[] args)
{
int x; // Declared in main method
if(true)
{
for(int i=0;i<5;i++)
{
x=5;// initialized inside loop
}
}
System.out.println(x);//accessing outside for loop
}
x will only be set if the loop runs. The compiler considers it a possibility that that will never happen.
In the other case: if(true) the compiler recognizes as "This will happen"
If you want to avoid this, change
int x;
to
int x = 0; // or use another default variable
It is accessible still there is a chance that the program will never access the for block. Since compiler does not meet any other initialization of the var outside the for loop it gives you an error. In order to compile it you have to initialize the variable with a default value :
class Myclass {
public static void main (String[] args) {
int x = 0; // Declared in main method and init with a default value.
if(true) {
for(int i=0;i<5;i++) {
x=5;// Reinitialized inside loop
}
}
System.out.println(x); // No problems here.
}
}
In java for loop evaluated at run-time so compiler ignores check for variable initialization inside loop, that is the reason "x" have to initialized with value.
If you change the condition in the if block from true to false you would get the same error that variable 'x' might not have been initialized. When you do if(true) the compiler can understand that the code inside if block will always run and hence the variable x would always be initialized.
But when you initialize the variable inside the for loop, it may happen that the for loop is never run and variable is left uninitialized.
public static void main(String[] args) {
int x; // Declared in main method
if(false)
{
x=5; //compile error
for(int i=0;i<5;i++)
{
//x=5 initialized inside loop
}
}
System.out.println(x);
}
To avoid this scenario initialize the variable as int x = 0;
i made a small program for summing two numbers
if i used a void type method it will be like this
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
getSum(x,y);
}
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
} }
here if i used a method that returns a value i will get same output!
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
int r = getSum(x,y);
System.out.println("sum = " + r);
}
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}}
so i'm confused what is the benefit of returning a value if i can finish my program with a void type method?
The point is not to get the result but the way we get the result
consider
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
}
will print the output to the screen after calculation
but when we use return
as you have done it later
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}
this function will respond back the sum. that sum can be stored in a variable
can be used afterwards
like in recursion
In small programs, you won't get the difference but while writing the big programs you have to make several functions which are being called several times and you may need the output of one function into other.
In that case, you will require return so that the output of one function can be used into other.
Hope this helps!!
I think the answer is that, if you're calling getSum() method with a return type in any other class.. you would get a returned value which can be used for further processing. .
Where as in void that's not possible... Hope this helps... Reply if any doubts..
I can understand why you have this question.
First of all, you should know that in real development, we do not use console logs.
System.out.Println();
This is used only for debugging and that too in very rare cases.
The whole point of a function is to take some input and convert to something else.
So,
public static int getSum(int x, int y) {
return x+y;
}
public static void main(String[] args) {
System.out.Println(getSum(5,10));
}
This is the better solution.
Best Regards,
Rakesh
When you use the keyword void it means that method doesn't return anything at all. If you declare a return type different to void at the method statement instead, that method must return obligatorily a valid value to the declared return type using the keyword return followed by a variable/value to send back to the class that called the method.
Defining methods here you have the java documentation for a method declaration
Answering your question, in small programs that work with primitive values it doesn't really matter but in complex program when you usually need to return specifics object types, i.e an ArrayList or actually an instance of a class you created you can't simply put it into a System.out.println and send it to the console, mostly you'll want to get something from a method and that something usually can be a more complex object than an integer or a string, the way to get that something is through the return type defined by the method's statement.
A common use of return types is when your method is static and it can't interact with the non-static instance variables of the class, this type of static methods usually get values from their arguments, do a certain kind of progress and then return a result that the method's caller can use.
Returning a value enables you to use that value in whichever way you want, including printing it or assigning it to variable for further processing. If on the other hand you print the value in the method and not return anything, i.e. making the method of type void, then that's all you can do with that method.
The question is from the famous SCJP 6 book
Given:
public class Dark {
int x = 3;
public static void main(String[] args) {
new Dark().go1();
}
void go1() {
int x;
go2(++x);
}
void go2(int y) {
int x = ++y;
System.out.println(x);
}
}
What is the result?
A. 2
B. 3
C. 4
D. 5
E. Compilation fails
F. An exception is thrown at runtime
The answer according to the book is:
✓ E is correct. In go1() the local variable x is not initialized.
My questions is why go1() cannot use instance variable x initialized as 6 on line 4 here?
Because the local variable x exists. If int x; were commented out, it will run fine and use the instance variable.
In Java all the local variables should be initialized if not it will give an error. But you shouldn't initialize parameters of a method.
if you don't have int x then this will be ok. because at that case compiler will use the local variable which is assigned for class level.
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.