Global variable of String type - java

I have the following global variable of String type.
static public String rev="hello"
I can read it without any issue from an object of another class. Is there anyway I can update it with another string from an object of another class? I know Java string is immutable. I tried with the following way using StringBuilder:
static public StringBuilder rev=new StringBuilder("hello");
static public void setRev(StringBuilder s)
{
rev=rev.delete(0,rev.length());
rev.append(s);
}
From another class:
MainActivity.setRev(stringBuilderVar);
But it did not work.

The syntax for updating a field is the same for static and non-static fields. Simply use an assignment statement:
class Global {
public static String greeting;
}
public class Other {
public static void main(String[] args) {
String newGreeting = "hello";
Global.greeting = newGreeting;
}
}
That said, once your programs get bigger, you'll likely want to use non-static fields instead.

Related

How to run a code chunk from LeetCode in the local IDE?

All Leetcode questions don't seem to have main methods, I wonder how I could run the code in a local IDE(say, eclipse)? For instance, I was trying to run this one:
Q: Write a method/function to replace all the space in String s to "%20".
The code:
public class ReplaceSpace {
public String replaceSpace(String s) {
StringBuilder res = new StringBuilder();
for(Character c : s.toCharArray()) {
if(c == ' ')
res.append("%20");
else
res.append(c);
}
return res.toString();
}// that'll work in the Leetcode editor
public static void main(String[] args) {
String s = "We are happy.";
System.out.print(s.replaceSpace); //reports "cannot be resolved to a type" error
}
}
Also, if anyone could explain a little why Leetcode editor could run code without the main method it would be great.
To test the code in your local IDE, simply provide your own main. The pre-written code usually contains non-static methods. This gives you two ways to test your code.
Add static
public class ReplaceSpace
{
public static String replaceSpace(String s)
{
...
}
public static void main(String[] args)
{
System.out.println (replaceSpace("We are happy"));
}
}
Create object
public class ReplaceSpace
{
public String replaceSpace(String s)
{
...
}
public static void main(String[] args)
{
ReplaceSpace rs = new ReplaceSpace();
System.out.println (rs.replaceSpace("We are happy"));
}
}
replaceSpace is a method of ReplaceSpace class and not String class. String is the return type for replaceSpace method. You're trying to call the replaceSpace method on the String class object.
In order to run the code, you need to instantiate an object of ReplaceSpace class and then call the replaceSpace method on its object by passing the string which you want to replace as a parameter. Like so:
public static void main(String[] args) {
ReplaceSpace rs = new ReplaceSpace();
String replacedString = rs.replaceSpace("We are happy.");
System.out.println(replacedString);
}
Another way is to make the replaceSpace method static and call the method without an object instantiation.
As to how Leetcode runs the code behind the scenes, they don't need to use main methods to run your code. They just have unit tests written for your function with exhaustive test cases to test your solution rather than running your code via main methods.

cannot resolve method error for method practicing

public class MainForm {
String varpass = "This is a string that has to be passed.";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void place1 (){
//=======================================Method calls from another class========================================
//Calls from another class. It is non-static and thus requires it to be instantiated. EG. class var = new class();
Methods call = new Methods();
System.out.println(call.t1());
//Calls from another class. It is non-static void and thus requires it to be instantiated and be called straight.
call.t3();
//Calls from another class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(Methods.t2());
//Calls from another class. It is static void and thus does not require it to be instantiated.
Methods.t4();
//Trying to call a variable that was sent.
Methods.getvar(varpass);
call.getvar(varpass);
//=======================================Method calls from current class========================================
MainForm mcall = new MainForm();
//Calls from within the same class. It is static and thus does not require it to be instantiated. EG. class var = new class();
System.out.println(mcall.t1());
mcall.t3();
System.out.println(t2());
t4();
}
public static void main(String[] args) {
MainForm place = new MainForm();
place.place1();
}
}
public class Methods {
String var1 = "This is a public String variable";
String getVar = "Initial";
public String t1(){
String text = "This is a non-static method being called.";
return text;
}
public static String t2(){
String text = "This is a static method being called.";
return text;
}
public void t3(){
System.out.println("This is a non-static void method and cannot return.");
}
public static void t4(){
System.out.println("This is a static void method and cannot return.");
}
public void getvar(String varsent){
String msg = "getver() Variables are varsent("+varsent+"), getVar("+getVar+"), getVar(";
getVar = varsent;
msg = msg + getVar+")";
System.out.println(msg);
}
}
Here is the errors below
Methods.getvar(varpass);
call.getvar(varpass);
top one is giving non-static cannot be referenced from a static context
bottom one is saying cannot resolve method 'println(void)'
You can tell im using this as practice to call methods.
Here im trying to pass a variable varpass that contains a string. I want it pass that variable to getvar in Methods. in that getvar it takes a variable in Methods displays it before altering it then again after alter.
Im trying to understand how this works. Any insight would be appreciated.
This line
Methods.getvar(varpass);
is a static call. You try to call the static Method getvar from your Methods class. This method however is not static and therefor requires an instance of Method.
This line
call.getvar(varpass);
works fine. It in fact is the solution to the first line, where you reffere a non-static method from a static context
You cannot refer to a non-static variable/field from a static method, because a non-static field may vary between instances of a class. To solve it, make varpass static:
static String varpass = "This is a string that has to be passed.";
The second error results from the definition of getvar:
public void getvar(String varsent);
Since it does not return anything, it cannot be used in a System.out.println() as there is no definition of println accepting void (It doesn't know what to print).
Also, Methods.getvar(varpass) should be Methods.getvar(MainForm.varpass), because there is no local variable with that name.

Static field initiation in to unmodifiable set

I have a static field which is initialized by a config property in the static block. My code will run for Fingbugs warning which encounters a warning like mentioned below.
Field is a mutable collection
A mutable collection instance is assigned to a final static field, thus can be changed by malicious code or by accident from another package. Consider wrapping this field into Collections.unmodifiableSet/List/Map/etc. to avoid this vulnerability.
Class A{
private static String uri;
static{
uri= Properties.getpropery("SOME_PROPERTY"); /// Here i am getting the Findbugs warning
}
}
How can I make as Unmodified Set and pass this as String literal in later stages?
I think this is a bug in Findbugs. Try marking the field as private for now, perhaps that helps to solve it. If this does not help fixing it, my gut feeling of it being a bug just got a bit bigger.
As you can tell the exception is somewhat off because it's not a Collection and no changes can be made outside this class because it has the private access modifier and it is a String which are immutable by nature in Java.
Let's take a look at this example;
public class Class1 {
private static String STRING_VALUE = "I'm secure!";
private static List<String> COLLECTION = Arrays.asList("I'm Secure!");
public static void main(String[] args) {
Class2.changeStatic(STRING_VALUE);
System.out.println(STRING_VALUE); // I'm secure!
Class2.changeStatic(COLLECTION);
System.out.println(COLLECTION.get(0)); // I'm unsecure!
}
}
public class Class2 {
public static void changeStatic(String secureString) {
secureString = "I'm unsecure!";
}
public static void changeStatic(List<String> unsecureList) {
unsecureList.set(0, "I'm unsecure!");
}
}
As you can see, there is no way of changing the string value of Class1 outside of the class itself. In the case of a collection this is possible because the elements are held in a mutable container.
Because changing the elements in the Collection is possible outside the class/package they suggest wrapping it in an unmodifiable Collection which do not delegate the modifications to the wrapped list but instead throw an Exception:
public class Class1 {
private static List<String> COLLECTION = Collections.unmodifiableList(Arrays.asList("I'm Secure!"));
public static void main(String[] args) {
Class2.changeStatic(COLLECTION);
}
}
public class Class2 {
public static void changeStatic(List<String> unsecureList) {
unsecureList.set(0, "I'm unsecure!"); // throws a java.lang.UnsupportedOperationException
}
}

Java final class with constant

I must define a class which all it does is hold constants.
public static final String CODE1 = "100";
public static final String CODE2 = "200";
Now I want use these values in other classes. Is it better to use this class as a static class or instantiate it ?
Thanks.
Note : I know enums but in this context, I must use a class.
Just to use the values, you certainly shouldn't instantiate the class. Just because you can access static members as if they were instance members doesn't mean it's a good idea.
If the class really only contains constants - and if you're sure that's a good idea, rather than those constants appearing within classes which are directly related to them - you should make it a final class with a private constructor, so that no-one can pointlessly instantiate it:
public final class Codes {
public static final String CODE1 = "100";
public static final String CODE2 = "200";
// Prevent instantiation
private Codes() {
}
}
Don's answer suggesting using an enum is a very good idea too - it means you can use Code in your API everywhere that you don't need the exact string representation, which prevents you from accidentally using non-code values.
Jons answer is correct, although I want to show you a solution with an enum.
There is a disadvantage in accessing its String value as you have to call Code.CODE1.text() instead of Code.CODE1.
public enum Code {
CODE1("100"), CODE2("200");
private String text;
Codes(String text) {
this.text = text;
}
public String text() {
return text;
}
}
java language spec and JVM spec allow you to do anything you wanted, whether instantiate a class or use final or use other way....
Just use Eclipse and try !
while there is some good practice, Jon Skeet's answer is one good practice.
Java Language is not support global variable
public class ComonFun {
public static final String CODE1 = "100";
public static final String CODE2 = "200";
public static String CODE1(){
return CODE1;
}
public static String CODE2(){
return CODE2;
}
}
implement
public class Main {
public static void main(String[] args) {
System.out.println(ComonFun.CODE1());
System.out.println(ComonFun.CODE2());
}
}
i think that you need simply to declare an interface, you won't need to specify the clause "public static final". and it can be usuable throgh the hall project.
Use them as static, don't go for instantiation.
Even use static import as a benefit.
package coma;
import static coma.ImportStatments.*;
public class UsingClass {
public static void main(String[] args) {
System.out.println(CODE1);
}
}
And the class with final variables would look like this:
package coma;
public class ImportStatments {
public static final String CODE1 = "100";
public static final String CODE2 = "200";
}

Java passing variables from method in one class into different class

I've got this int variable inside the class StringSplit whose value I need to pass to another class called EndStatement to print out; can't really pass it as a parameter though I think. How can I best get the variable to where I need it? Can someone help with a hint? I've read the Java tutorials but don't quite get them. Variables and passing them around seem to be one of my Achilles' heels in Java programming.
EDIT TO ADD: parseCommands can call several different Statement classes e.g. EndStatement or PrintlnStatement depending on the first element of an Array parsed from a String which serves as a keyword to a HashMap called commandHash. The Statement classes implement the Directive interface which only has a method called execute with the parameterString[] parts. (EndStatement implements Directive). Expanded the parseCommands method to show what's going on.
public class StringSplit
{
public void parseCommands(String fileName)
{
//FileReader and BufferedReader to read a file with the code
//to execute line by line into an ArrayList myString
int lineCounter=0; //need to get this variable's value into class EndStatement
for (String listString: myString)
{
lineCounter++;
String[] parts=listString.trim.split("[\\s]+", 2)//split String into 2 parts
//to get commands
Directive directive= commandHash.get(parts[0])//parts[0] is the hashmap keyword
}
public class EndStatement implements Directive
{
public void execute(String[] parts)
{
//need to get lineCounter here--how?
System.out.print(lineCounter +"lines processed.");
}
public static void main (String[]args)
StringSplit ss = new StringSplit();
ss.parseCommands(args[0]);
}
This is my first time answering a question but I think I'm right.
In StringSplit you want to declare linceCounter in a data field.
public class StringSplit
{
public void parseCommands(String fileName)
{
lineCounter=0; //this is the variable I need to pass into a different class
for (String listString: myString)
{
lineCounter++;
//more code here
}
}
public int getLineCounter()
{
return lineCounter;
}
private int lineCounter; //this is what I call a data field, you should declare these as private as oppose to public to comply with encapsulation
}
Then in your main method call getLinceCounter, then pass what it returns to EndStatment.
Does this make sense? Did I understand your question right?
public class StringSplit
{
private int lineCounter=0;
public void parseCommands(String fileName)
{
for (String listString: myString)
{
lineCounter++;
//more code here
}
}
public int getLineCounter() {
return lineCounter;
}
}
public class EndStatement implements Directive
{
StringSplit ss = new StringSplit();
public void execute(String[] parts)
{
//need to get lineCounter here--how?
System.out.print(ss.getLineCounter() +"lines processed.");
}
public static void main (String[]args)
{
ss.parseCommands(args[0]);
}
}
I think you mix some terms. There is no such thing as passing variables from one class to another. I assume that what you want to do is simply be able to access (set/get) your variable outside StringSplit class. In order to do that you must declare lineCounter outside parseCommands method as StringSplit's property. Currently lineCounter is local to parseCommands method and as such cannot be visible/accessed outside that method not mentioning to be able to access it from outside a class/object. Do that:
public class StringSplit
{
public int lineCounter = 0;
...
Now you'll be able to access lineCounter from different methods of the same class and from methods outside your class. Making lineCounter public gives others full access to it. As 'Jon' has pointed out it may be dangerous sometimes but for this example case is acceptable. You may see how writing from outside can be prevented using 'Nurlan's' private field with member used to provide read acces only.

Categories