shadowing static variable ( global variable) - java

Why in the next code I get pro.x=11?. it should be 22. Please somebody throws a light.
public class Pro {
static int x=11;
public static void main(String[] args) {
Pro pro=new Pro();
pro.call(5);
System.out.println(Pro.x);
System.out.println(pro.x);
}
public void call(int x){
x=22;
}
}

you are not setting the static/global variable to 22, but rather the value of the argument passed. Considering it's a primitive value, call by value is used and not call by reference.
Edit: In fact as pointed out in comments, java doesn't have have call by reference, but rather call by value of a reference.
If you just wisht to change the global variable, no argument is necessary for your function, you can do it this way:
public class Pro {
static int x=11;
public static void main(String[] args) {
Pro pro=new Pro();
pro.call();
System.out.println(Pro.x);
System.out.println(pro.x);
}
public void call(){
Pro.x=22;
}
}

Related

I need to use an object created in one static method in another static method but have issue calling it

(This is a repost of a previous question I have where I modified the code so it is much easier to understand.)
public class LaptopSaleApp{
public static void main(String[] args){
selectLaptop();
selectSupportOptions(laptopOrder);//This parameter cannot be resolved into a variable
}
public static void selectLaptop(){
LaptopSalesOrder laptopOrder = new LaptopSalesOrder("Dell Latitude", 1399.00);
}
public static void selectSupportOptions(LaptopSalesOrder laptopOrder){
laptopOrder.setBasicIndicator(true);
}
}
I need two static methods here. The object has to be declared in the first method, and then is used in the second method for the setBasicIndicator setter. I then need to call both methods in my main to run the program, but I don't know what to put in the parameters for the method in the main.
You can't quite do this if the object is declared in the first method.
Here's what you should do:
public static void main(String[] args){
LaptopSalesOrder laptopOrder = selectLaptop();
selectSupportOptions(laptopOrder);
}
public static LaptopSalesOrder selectLaptop(){
return new LaptopSalesOrder("Dell Latitude", 1399.00);
}
public static void selectSupportOptions(LaptopSalesOrder laptopOrder){
laptopOrder.setBasicIndicator(true);
}

Why should one specify attribute values inside a constructor when it is simpler to specify them in the declaration?

I've just started learning about constructors and know that they're used to initialize objects. But i noticed that objects can be given initial values in the declaration (as in example 2) without having to specify them separately in a constructor.
Both examples below give the same result so what is the benefit of first declaring the attribute and then specifying the value in a constructor instead of right away in the declaration?
Example 1:
**public class Main {
int x;
public Main() {
x = 5;
}**
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Example 2:
**public class Main {
int x = 5;**
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
In your example, where you always want to set the value to a pre-defined value, a constructor is not required. It can be initialized at the time the attribute is defined. However, in most cases, it is not so simple - value of a class attribute is usually passed in at the time an instance is created. In such cases, a constructor is a good way to initialize the attributes of a class.
public class Main {
int x;
public Main(int x) {
this.x = x;
}
public static void main(String[] args) {
Main myObj = new Main(6);
System.out.println(myObj.x);
}
}

Method Overloading with varargs

I am a bit confused about this topic, reason being in this code:
public class File
{
public static void main(String[] args)
{
numbers();
}
static void numbers(int...x)
{
System.out.println("Integers");
}
static void numbers(byte...x)
{
System.out.println("Byte");
}
static void numbers(short...x)
{
System.out.println("Short");
}
}
The output of this code is "Byte", and the reason is the most specific type is chosen, since among byte, short and int the most specific type is byte, that's why it is chosen.
But if I modify my code to-
public class File
{
public static void main(String[] args)
{
numbers(1, 4);
}
static void numbers(int...x)
{
System.out.println("Integers");
}
static void numbers(byte...x)
{
System.out.println("Byte");
}
static void numbers(short...x)
{
System.out.println("Short");
}
}
The output is "Integers", and I'm unable to figure out why? I know in case of arithmetic instructions byte and short are implicitly promoted to int, but here we are calling a method with values which is within the range of byte and short, then how the method with int arguments is invoked?
And also, if I comment out the method with int arguments, then the code shows an error of no suitable method found. Why???
1 and 4 are integer literals. So the int... version is called.
There are no byte or short literals, but if you were to call Numbers((byte)2, (byte)3); the byte... version would be called.

Trouble understanding why I cannot modify variable outside a method?

public class test {
public static void main(String[] args) throws Exception {
final int num = 111;
new Thread() {
#Override
public void run() {
num = 222;
}
}.start();
}
}
I want to change the value of num however I can only do that if I set it to final which would not let me modify this. In other languages such as C we can use pointers but Java cannot?
Java has neither closure nor pointers.
A solution would be to make the num static in the class :
public class test {
static int num = 111;
public static void main(String[] args) throws Exception {
new Thread() {
#Override
public void run() {
num = 222;
}
}.start();
}
}
Another solution would be to use an object like AtomicInteger. You can't change the value of the variable but you can change the content of the value :
public class test {
public static void main(String[] args) throws Exception {
final AtomicInteger num = new AtomicInteger(111);
new Thread() {
#Override
public void run() {
num.set(222);
}
}.start();
}
}
Why this isn't allowed
main is a method. As with other programming languages, when a method returns, all of the variables declared in its body go out of scope, and accessing them has undefined behavior. Under some circumstances, the memory location where they used to be will no longer be valid.
Obviously this is a problem. If you try to change num after main has returned, you might overwrite a portion of the stack that doesn't belong to num anymore. Java's response to this difficult situation is to introduce restrictions on how you can share variables: they must be final. Java can then safely locate them in such a way that reading them will produce consistent results even after the function has returned.
The C equivalent to this problem is storing and using the address of a local variable outside of its scope, something that all C programmers are taught to never do.
To get around it, declare num as a member of test, create an instance, and pass that to it. This removes the dependancy on a local variable, and thus removes the final restriction.
public class test
{
int num = 111;
public static void main(String[] args) throws Exception
{
test t = new test();
(new Thread(t) {
test mytest;
Thread(test t)
{
mytest = t;
}
#Override
public void run() {
mytest.num = 222;
}
}).start();
}
}
Well, you can access it if you declare variable outside the function. Like this:
public class test {
private static int num = 111;
public static void main(String[] args) throws Exception {
new Thread() {
#Override
public void run() {
num = 222;
}
}.start();
}
}
You are creating new Thread() { class as inner class. You can't access outer class variables without declaring them as final.
You can't change final variable references.
There are two ways you can do this,
1) Make num as static
2) Wrap num inside an object (You can update state of the object even though you define reference as final).
NOTE: Both are not thread safe.
Yep you can't win here! You need to set it final to be able to access it, but then you will not be able to modify it. You'll need to look at a different approach.

compiling in bluej?

class box {
double ht,wdt,len;
box(double h,double w,double l) {
ht=h;
wdt=w;
len=l;
}
double volume() {
return ht*wdt*len;
}
}
class boxme {
public static void main(String args[]) {
box mybox= new box(1,2,3);
System.out.print("The volume is "+mybox.volume());
}
}
// For this code to be run in bluej,i still need to give the arguments after the object creation (though I have already given them in my code).The same code works well in cmd but shows this difference when attempted in bluej.Please provide a reason and solution to bring out an equivalence between bluej and cmd?? //
When you have two different classes and you want to use the methods in the other class, you have to create an instance of that class.
Right-click on the second class and run the public static void main(String args[]) function.
And please note the name of the class must start with an upper case letter and the fields must be private scoped for security, Objects should be always in lower case.
public class Box {
private double ht,wdt,len;
public Box(double h,double w,double l) {
ht=h;
wdt=w;
len=l;
}
public double volume() {
return ht*wdt*len;
}
}
public class boxme {
public static void main(String args[]) {
Box mybox= new Box(1,2,3);
System.out.print("The volume is "+mybox.volume());
}
}
You don't need to create an object while running it in BlueJ explicitly, since you already have the main function defined.
Right click on the class and run the public static void main(String args[])
function.

Categories

Resources