How to get value of function outside in separate value? - java

public void setAcc(String a)
{
m_acc.setText(a);
}
I want to get value of variable a is a separate variable outside this function.
The values of a is coming from another Controller Class.

Declare a variable outside of the method and change that variable inside the method.
private String acc;
public void setAcc(String a)
{
this.acc = a;
m_acc.setText(a);
}
...
System.out.println(acc); //prints the value of a

Related

How do i increase size by the value provided as parameter

So this code currently just displays a number that is inputed by the user i.e if 65.2 is inputed as a parameter in the main it displays 65.2. But i need to make a method called update that allows the size variable to be updated by the variable put in as a parameter
public class Population {
// creates a private double variable called size
private double size;
// creates a constructor that uses x as the parameter to get the value of size
Population(double x) {
this.size = x;
}
// makes the size variable public by creating a public method so that it can be sent to the main also returns the value of size
public double getSize() {
return size;
}
public void update() {
}
and this is my main
public class Main {
public static void main(String args[]) {
Population popSize = new Population(65.2);
System.out.print(popSize.getSize());
}
}
To update a private member of a class you must do it inside the class itself. So, if you want to use a method to update the private member then you must pass it as parameter.
A method will be in following format <access modifier of the method> <return type> <method name>(<parameter type> parameterName,....)
So if you want to use update method with a parameter to update size in the class Population then your update method should be like
public void update(double x){
this.size = x;
}
In the above example the access modifier is public so this method is accessible everywhere and the return type of the method is void so this method doesn't return anything, you have a single parameter with type double and name x. Inside the method you can do anything you want, in the above example you just assign the passed value to the size, but if you want to do some calculations you can do that.
So, to use the update method you can do as follows.
public static void main(String args[]) {
Population popSize = new Population(65.2);
popSize.update(82.3);
System.out.print(popSize.getSize());
}
The above code will print 82.3 since you have updated the instance variable.

How to access global non static variable from static method

I have main method in my java program, I want to store values in global variable because i want to access that values from different methods of the class, however I am not convinced to use static global variable, as the values in the variable keep on changing, so am afraid values which are declared as static may not change as it is defined on the class level, so I am looking for non static global variable. Can someone give an idea, how to achieve this.
I suggest you make a separate class with with variables you want to store, with proper getter and setter methods. That way you keep the code more clean and maintainable and you follow the Separation of concerns principle, which tells us that every class should have it's own purpose.
EG:
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
public class MyClass {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName()); //Prints out name value
}
}
Since Java promotes the use of classes rather than global variables, I would highly recommend you to use a class for storing the data. That way, you do not need to use static methods or static variables.
One example of this is shown below:
import java.util.*;
public class Main{
public static void main(String[] args) {
int initialValue = 1;
Holder holder = new Holder(initialValue);
int currentValue = holder.getValue();
System.out.println("Value after initial creation: " + currentValue);
System.out.println("Set value to 10");
holder.setValue(10);
currentValue = holder.getValue();
System.out.println("New value is " + currentValue);
}
}
Holder class:
public class Holder {
private int val;
public Holder(int value){
setValue(value);
}
public void setValue(int value){
this.val=value;
}
public int getValue(){
return this.val;
}
}
To start a java class uses the "main" static method present in all normal java programs.
HOWEVER, the "constructor" method (really just "constructor") is named after the "main class" name and is where you initialise variables whether you call a declared method in the class or retrieve a static variable from the starter method "main".
The main method does not require any passer method to obtain a static variable from it to either set a global static variable in the class because it is only 1 step in hierarchy "scope" in the class (this is why some frameworks pass variables to global without typing of the method but rather instead using "void" on the method declaration) BUT you cannot put a non static method call in a static section of code such as the main method.
The way you remove static context from a variable is to make another variable with the same name in a non static context and cast the static variable to the non static instance.
e.g. for a global String primitive type variable from main method at construction time globally declare
static String uselessRef1 = ""; // declared globally initialised
// following is declared inside the static method main
uselessRef1 = args[1]; // static argument 1 from the main method args[] array
// following is declared in global scope code or in the constructor code
String uselessRef1b = (String)uselessRef1; // (String) cast removes the static context of the String type and copies to non static version of the type
While committed inline in the global declarations not in the constructor they are deemed to be loaded in the class constructor in sequence.
NB: You can put or make a static method in a non-static class but not the make a non static method in a static class.
import.javax.swing.*;
public class ExampleStaticRemoval{
static String uselessRef1 = ""; // declared globally initialised
String uselessRef1b = "";
ExampleStaticRemoval(){
// following is declared in global scope code or in the constructor code
uselessRef1b = (String)uselessRef1; // (String) cast removes the static context of the String type and copies to non static version of the type
printOut();
}// end constructor
// program start method
public static void Main(String[] args){
new ExampleStaticRemoval();
// static global class variable uselessRef1 is assigned the local method value
// MUST BE OUTSIDE AT TOP TO BE GLOBAL
uselessRef1 = args[0] +" "+args[1]; // join static arguments 0 and 1 from the main method args[] array
}// end main
public void printOut(){
JOptionPane.showConfirmDialog(null,uselessRef1b, uselessRef1b, 0);
}//end method
} // end class

Getting Null when calling variable from another class

I have done a lot of google regarding this and tried many things and have never gotten through. So I have this variable in Class A and I want to print that variable in Class B but the value of the variable in Class A goes through a method before it is called.
public class TestSubject extends javax.swing.JFrame {
static String a;
private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {
a = "hello"; }
}
Here I declare the variable and clicks a button to set the variable value to 'hello'. I tested if the variable did indeed get the value by having another button printing the variable 'a' in the same class.
public class TestSubject2 extends javax.swing.JFrame {
TestSubject test = new TestSubject();
private void okActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(test.a);
}
}
So here I try print the variable a from class 'TestSubject'.
So what I have tried:
I have tried to use both non-static and static.
I have tried to use a return method
class TestSubject { //purposely left the extend but you get what I mean
public String getString() {
return a; } }
Class TestSubject2 {
TestSubject test = new TestSubject();
private void okActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(test.getString());
}
}
However, if I were to explicitly give 'a' a value like:
static String a = "hello";
It would print out properly in the other class using the first method.
I made sure I click the buttons sequentially so the values are being inputted.
So what I want to know is how can I call a variable from another class.

Can "new" be used inside the constructor of the class to call another constructor in Java?

I know that this(...) is used to call one constructor of a class from another constructor. But can we use new for the same?
To be more clear on the question, is Line-2 is valid? If it is (as the compiler did not complaint), why the output is null not Hello?
class Test0 {
String name;
public Test0(String str) {
this.name= str;
}
public Test0() {
//this("Hello"); // Line-1
new Test0("Hello"){}; // Line-2
}
String getName(){
return name;
}
}
public class Test{
public static void main(String ags[]){
Test0 t = new Test0();
System.out.println(t.getName());
}
}
It is valid but it's creating a completely separate instance of Test0 (more specifically an instance of an anonymous subclass of Test0) inside that constructor, and it's not being used anywhere. The current instance still has the field name set to null.
public Test0() {
// this creates a different instance in addition to the current instance
new Test0("Hello"){};
}
Note that if you call the new operator with the no-argument constructor, you would get a StackOverflowError.
What you're trying to do is accomplished by the code you commented out:
public Test0()
{
this("Hello");
}
Line 2 is valid statement. That is why compiler didn't show up any errors. But there you are creating an anonymous object. It will vanish soon after you exit from the constructor. Therefore the value is still null becuase nothing was assigned to that.
new Test0("Hello"){};
Above line will create an anonymous instance of Test0 class and assigned the value of Hello to the name variable. But since you are not referring the created anonymous instance, it will get disappear from the immediate after line. So still you haven't assigned a value to the name variable of the instance that calls the particular code segment. Therefore name is null
In the memory it is like
Because you create a new instance of Test0 with name "hello" but never use it.
public Test() {
new Test0("hello") // nothing is referencing this new object
}
You simply creating an object inside another constructor but it will have no effect on the instance being created by the first constructor call.
You can do this but the result of this new usage will be gone at the end of the constructor. Especially, t.name will be null.
Use this("Hello").
Name is the instance variable. Instance variables are object-specific.
With new Test0("Hello"); you are creating a new instance of Test0.
If you would like to have t.getName() return "Hello" [I mean field value independent of object], change the name field to static:
static String name;
You can display output by using new keyword through below code..Since u have used public Test0(){new Test("Hello){};" here {} braces are not important..so when test0() constructor is called...Inside this constructor test0(args); is being called bt in first constructor u didnot displayed output..where will be your "Hello" will get displayed..so just edit
`
public test0(String str)
{
this.name=str;
System.out.println(str);
}`
And you will have ur desired output..See my below code..
class test01{
public test01(String str)
{System.out.println(str);
}
public test01(){
new test01("Print");
}
}public class Const {
public static void main(String args[])
{test01 t = new test01();
//System.out.println(t.getName());
}}
The output of this code will give u required String

How to jump to another method?

Is there any function in java that lets you jump to another method?
This is an example how it should work:
if (boolean expression(){
jump to public void something;
if (boolean expression) {
jump to public void something2;
} else{
jump to public void 3;
}
This is needed for a program that checks 3 numbers, and they have different methods linked to them.
If by jump, you mean calling a method:
if (boolean expression(){
something();
if (boolean expression(){
something2();
}
else{
something3();
}
Simply invoke it, in your example
if (boolean expression(){
something();
} else if (boolean expression(){
something2();
} else{
something3();
}
instead of jump to public void something just call something()
There is no syntax called "jump to" although you can easily call a method by firstly making a method.
public void myMethod(){
// do something
}
now when you have done this, you call it from another method by invoking it's name myMethod();. You might know that a method can either return a variable or return nothing (void) if you give it a return-type you MUST return a variable with the same type as your method.
For example:
public int oneplusone(){
int integer = 1 + 1;
return integer;
}
and a void would be like this:
public void oneplusone(){
int integer = 1 + 1;
System.out.println(integer);
}
When you've specified your method you need to call it by invoking its name from another place in your program. Final example:
public class Snippet(){
public static void main(String args[]){ // THIS IS THE MAIN METHOD OF YOUR PROGRAM!
Snippet snippet = new Snippet();
System.out.println(snippet.oneplusone());
}
public int oneplusone(){
int integer = 1 + 1;
return integer;
}
}
I suggest you should check out thenewboston java tutorials explaning java for beginners. Good luck!
if you have the mothod call in the class just call the method like
something(int i);
if your method is in another class make sure you have an object of that class if the method isn't static and call your method
Foo foo = new Foo();
foo.something(10);

Categories

Resources