Why can't I access a variable declared in a switch? - java

this is my code :
there is a probléme "can't acces to variable j"
public static void main(String args[]) {
char digit = 'a';
for (int i = 0; i < 10; i++){
switch (digit){
case 'x' : { int j = 0; System.out.println(j); }
default : { int j = 100; System.out.println(j); }
}
}
int i = j;
System.out.println(i);
}

Each variable has scope. Scope is a restriction regarding where some variable can be accessed.
When you declare a variable in any type of block {}, that variable can only be accessed within that block of code.
You'll have to declare (and possibly initialize) the variable outside the block so its scope is greater, either at the method level or as a static variable (or instance if you were working with instance methods).

Related

For loop iterator with methods in java

I am try to execute one simple for loop with iteration done by method. Its return value is not assigned
public class DefaultC {
public static void main(String[] args) {
int i = 1;
for(i= 10;i<=50; i=method(i)){
System.out.println(i);
}
}
static int method(int i){
return i++;
}
}
++i increments and then returns i.
i++ returns i and then increments it.
static int method(int i){
return i++;
}
This method is doing post-increment, which means it will return the value of i as it is which is being passed as the method argument, after that it increments the value of i which is now not useful at all since the scope of the variable i is only up to this method.
Try doing pre-increment instead.
return ++i;
EDIT: As per OP's comment
#Prashant by i++ it works, but why i = method(i) cant?
for(i= 10;i<=50; i++){ <-- Here post increment happens
System.out.println(i); <-- At this point value is already being incremented so you can utilize it.
}
Where as
for(i= 10;i<=50; i=method(i)){ <-- Here post increment happens inside method and the value it returns is still `10` not `11`
System.out.println(i); <-- At this point value is same as the previous loop
}
The reason i++ works but increment(i) doesn't is because of the difference in the variable you are incrementing.
i++ is incrementing a local variable, so you see the changes to its value;
increment(i) is copying i to a new variable, which happens also to be named i, and increments that, and after taking its value for the return statement.
The variable local to the loop is left unchanged by the ++, just as int j = i; j++; doesn't change the value of i.
In Java, method parameters​ are always passed by value.
But it is also important to note that even if Java did pass method parameters by reference, there is still a semantic difference between i++ and i = i++ (which is like the i = increment(i) case). The other answer have already covered why i = i++ doesn't work.
i++ returns the value of i and later it do increment.
What you need to do is, to use ++i;
Given Example shows how,
public class DefaultC {
public static void main(String[] args) {
int i = 1;
for(i= 10;i<=50; i=method(i)){
System.out.println(i);
}
}
static int method(int i){
return ++i;
}
}
Here ++i will do increment first and returns later

Custom variable scope

Is it allowed to just place some curly braces without any if/for/etc statements to limit the variable scope?
An example:
public void myMethod()
{
...
{
int x;
x = 5;
}
...
}
I may want to do this, so I know for sure I won't access/change the variable outside the scope and that it will be destroyed beforehand
Yes, it's allowed. Just try and see for youtself
The curly braces { .. } limit the scope of variables to the block.
However, changes can be made to global variables falling into the scope of { .. } block.
int x = -1;
double y = 5;
{
x = 10;
y = 100;
char c = 'A';
}
System.out.println(x + " " + y); // 10 100.0
System.out.println(c); // Compile time error and out of scope
{
c = 'B'; // Compile time error and out of scope
}

Arithmetic operation on primitive class variables [duplicate]

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

My return value returns an error

I have a method called RandomInt, that returns a random number. However, when I try to return the value, it gives me an error, stating that the variable cannot be found. I can't use it as a parameter either, because when I call it in another method, it'll return 0. Any help?
public static int randomInt(int low, int high) {
for (int i = 0; i < 10; i++) {
double x = Math.random();
int e = (int) x * high / low;
}
return e;
}
In Java, the scope of a variable is bound by { } characters (in Javascript this is not the case). That means if a variable is declared in a set of {} (curly brackets), it cannot be referenced outside of these brackets.
This is the case in your code. The variable e is declared in the loop, so you can not use it in the function's return statement. I would suggest declaring e right before the lop.
In java whenever a variable is declared, it have a certain scope. When you declare a variable inside a loop, it is only accessible inside that loop. Because the variable you are returning is declared inside the for loop, this is why it is giving an error. Try declaring a variable outside the loop and then access that in the for loop. You code will look like this :
public static int randomInt(int low, int high)
{
int e = 0;
for (int i = 0; i < 10; i++)
{
double x = Math.random();
e = (int) x * high / low;
}
return e;
}
A method can return only one value (in your case one int), but it can be a composite value (array or object). In this case, you are better off having a loop call your method a bunch of times, and do whatever it needs to do with the result.
Technically, int e's scope is inside the loop body since it is declared inside there. The following code will generate 10 random numbers, and return the last one (as the last one overwrites the 9th, which overwrites the 8th, ...):
public static int randomInt(int low, int high){
int e;
for(int i=0;i<10;i++){
double x=Math.random();
e=(int)x*high/low;
}
return e;
}
You're declaring the variable e inside the loop, then trying to reference it from outside that loop. The below should work:
public static int randomInt(int low, int high)
{
int e;
for (int i=0;i<10;i++)
{
double x=Math.random();
e=(int)x*high/low;
}
return e;
}

I don't understand the program

I wanted a program which could list all the contents available in a directory. I found a nice code in java2's.com,
http://www.java2s.com/Code/Java/File-Input-Output/ListingtheDirectoryContents.htm
And here is the code,
import java.io.File;
import java.util.Arrays;
public class Dir {
static int indentLevel = -1;
static void listPath(File path) {
File files[];
indentLevel++;
files = path.listFiles();
Arrays.sort(files);
for (int i = 0, n = files.length; i < n; i++) {
for (int indent = 0; indent < indentLevel; indent++) {
System.out.print(" ");
}
System.out.println(files[i].toString());
if (files[i].isDirectory()) {
listPath(files[i]);
}
}
indentLevel--;
}
public static void main(String args[]) {
listPath(new File(".\\code"));
}
}
What I don't understand is the variable n in the first for loop. If it is not defined anywhere, then why is the program not showing any error?
int i, n;
would declare two ints.
In the code
int i = 0, n = files.length;
declares and initialises them.
It's declared right there, as an int. The comma separates the multiple variable declarations.
n is defined in the for loop in the same way as i.
int x,y;
Would define two variables x and y both as ints. the comma in the for with assignments just looks more complex.

Categories

Resources