what is the use of making a string static - java

If I am not wrong, how many ever same Strings are created, only in only place it is stored by using String interning. If so, what is the use of making a Sting static if it is already being stored in only one place in memory which is nothing but acting as if it was a static variable. Thanks.

Static Strings can be accessed outside the class without creating the class's variable. Example of this is:
public class Stuff {
public static final String foo = "foo";
}
Here is an example of calling the variable foo (while still retaining it's contents of foo):
public class Application {
public static void main(String[] args) {
System.out.println(Stuff.foo);
}
}
As mentioned, I did not have to initialize Stuff in Application.

If you want to access it staticly outside of a class without initializing the class, then you make it static

You may want a class to access that String value but you do not want to initialize the class which holds the String. This is useful if one class is using the String but not using the rest of the class that holds the String.

Related

How to handle static in java

I got into programming a bit obliquely with Bukkit and thus didn't learn some things properly. But since I've been doing real stuff for a while now I wanted to ask how to deal with static.
I know that you should avoid static as most as possible.
Should you then call external functions like this?
//Another Class
public void exampleMethodInAnotherClass() {
system.out.prinln("Hi :D");
}
//Main
public static void main(String[] args) {
new AnotherClass().exampleMethodInAnotherClass();
}
//OR
public static void exampleMethodInAnotherClass() {
system.out.println("Hi :D");
}
public static void main(String[] args) {
AnotherClass.exampleMethodInAnotherClass();
}
Now it's about the type of function that you use if the function is too much used in your code like System.out.println then make it static *(static function are mostly common in maths and helper classes).
OH the static keyword , My most hero in the programming!
I know that you should avoid static as most as possible.
no that's not true in the most cases the programmer that are student or new in the programming think it's best Idea that we have use static key but it's important to know the why we use static.
after you use static key the variable imidediately going to memory and you can accsess it directly by calling the refrence! and it's the package and class with the variable name but the static method is in the memory and if you change it from some where in your code the data change , see some example :
public class Test {
static String MESSAGE= "";
public static setMessage(String message){
MESSAGE = message;
}
public static void showMessage(){
System.out.println(MESSAGE);
}
}
----------------
Calling from another class
public static void showMessage(){
System.out.println(Test.MESSAGE);
}
if you run the program and change the message with the showMessage method you can get the message and if you need you can call the MESSAGE by reference Like ClassName.MESSAGE or create object from your class with new Keyword but your MESSAGE variable is static and in your memory after running your code so the use new keyword to call it not nesssasery and you can call it directly ! remember using the static variable in mini or script cases or test is good idea but if you create Enterprise project using static method or variable without knowledge about it it's bad idea! because , I most use static keyword for method or variable I need always return same result or work straight work I need! like show the time , convert date or etc... but don't use for changing the data The example I share it's good ref for know the problem.
Good ref for know the static internal work it's here

Why is it that static methods can access private data?

I am coming from a C++ background, so I am used to the main function not being able to access private data members of an instance.
However, the case with Java is different as main is a part of the public class, and can thus access the private data.
Why is it that a static method is given access to private data even though it does not belong to the calling instance? Is there any way I can avoid this from happening?
Here's a little snippet to explain what I mean:
public class Main
{
private int x = 5;
public static void main(String[] args) {
Main ob = new Main();
System.out.println(ob.x);
}
}
I want x to be inaccessible from main and that I have to use an accessor method for the same.
There is no way to protect "a class from itself". Private means that the current class (and only the current class) can access the field.
If you had a private field that no method could access, you could never read or update its value and thus render it unneccessary. By declaring a field private, you prohibit anybody outside your current class to access the field.
Read about visibility here: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Why am I being forced to change methods and varibles to static when calling them from my main method? [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Cannot make a static reference to the non-static method
(8 answers)
Closed 5 years ago.
For some reason when I'm trying to call methods using a main method or try changing variables declared outside the main method I get forced into having to change everything to static. This is fine in places but when it comes to needing to change values later in the code for example using a Scanner for input the main method just takes it to a whole new level trying to make me change the Scanner library etc.
This example shows what happens if I try calling a method.
This example shows what happens when I try alter the value of a variable declared outside my main method.
I have never faced an issue like this before when writing java code I've tried recreating the classes/ project files etc but nothing works. I've tried looking everywhere for a solution but I can't seem to find one probably due to the fact that I don't know what to search for. I've probably made myself look like a right idiot with my title haha! Any suggestions people?? Thanks in advance!
Maisy
It can be a bit confusing to get out of "static land" once you are in your main() method. One easy way is to have another object contain your "real" (non-static) top level code and then your main method creates that object and starts it off.
public static void main() {
MyEngine engine = new MyEngine();
// core logic inside of start()
engine.start();
}
I hope that this was clear enough for you. Good luck Maisy!
When calling methods form a main you have to instantiate the class they are in, unless it's a static function
this is because that a class is a sort of template and there is nothing saved about it before it get instantiated
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
}
public method method(){}
}
in the example above i instantiated a TestClass and then called on the testClass instance
there is some functions and variables on classes you might want static, because a static on a class is shared between ALL instances, and can be called on the class, say you want to know how many instances were created then something like this can be done.
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
System.out.print(TestClass.instances +""); // note that i call on
//the class and not on an instance for this static variable, and that the + ""
//is to cast the int to a string
}
public static int instances = 0; // static shared variable
public TestClass(){instances++;} // constructor
public method method(){}
}
You need to do some Object Oriented Programming tutorial and to learn some basic.
As answer for your problem to call without using static you have to create an instance of the main Class
let suppose the following class Foo
public class Foo{
private int myVarInteger;
public int getMyVarInteger(){ return this.myVarInteger;}
public void setMyVarInteger(int value){this.myVarInteger = value;}
public static void main(String[] args){
Foo myClassInstanceObject = new Foo();
// now we can access the methods
myClassInstanceObject.setMyVarInteger(5);
System.out.println("value ="+myClassInstance.getMyVarInteger());
}
}

Need help to get two classes to assist each other

i'm currently just fooling around with different classes to test how they work together, but im getting an error message in NetBeans that i cant solve. Here's my code:
class first_class.java
public class first_class {
private second_class state;
int test_tal=2;
public void test (int n) {
if (n>2) {
System.out.println("HELLO");
}
else {
System.out.println("GOODBYE");
}
}
public static void main(String[] args) {
state.john();
TestingFunStuff.test(2);
}
}
class second_class
public class second_class {
first_class state;
public int john () {
if (state.test_tal==2) {
return 4;
}
else {
return 5;
}
}
}
Apparently i can't run the method "john" in my main class, because "non static variable state cannot be referenced from a static context" and the method "test" because "non static method test(int) cannot be referenced from a static context".
What does this mean exactly?
Screenshot of the error shown in netbeans: http://imageshack.us/photo/my-images/26/funstufffirstclassnetbe.png/
It means state must be declared as a static member if you're going to use it from a static method, or you need an instance of first_class from which you can access a non-static member. In the latter case, you'll need to provide a getter method (or make it public, but ew).
Also, you don't instantiate an instance of second_class, so after it compiles, you'll get a NullPointerException: static or not, there needs to be an instance to access an instance method.
I might recommend following Java naming conventions, use camelCase instead of under_scores, and start class names with upper-case letters.
The trick here to get rid of the error message is to move the heavy work outside of main. Let's assume that both lines are part of a setup routine.
state.john();
TestingFunStuff.test(2);
We could create a function called setup which contains the two lines.
public void setup() {
state.john();
TestingFunStuff.test(2);
}
Now the main routine can call setup instead, and the error is gone.
public static void main(String[] args) {
setup();
}
However, the other members are correct in that your instantiation needs some cleanup as well. If you are new to objects and getting them to work together might I recommend the Head First Java book. Good first read (note first not reference) and not all that expensive.
Classes can have two types of members by initialization: static and dynamic (default). This controls the time the member is allocated.
Static is allocated at class declaration time, so is always available, cannot be inherited/overridden, etc. Dynamic is allocated at class instantiation time, so you have to new your class if you want to access such members...
It is like BSS vs heap (malloc'd) memory in C, if that helps..

Pass argument to a static constructor in Java?

I'm trying to initialize a static class, with an argument, and then run some more static code in that class.
I'm aware of the static block, but it seems it can't take any arguments.
Is there a way to pass arguments to a static constructor?
If not, what is the recommended technique to initialize a Static class using an argument?
Edit:
A static class to my understanding is a class which cannot be instantiated (in c# they're called static classes, if Java has a different term for them, sorry for not being aware of it) - it's accessed through it's class name rather than an object name.
What I'm trying to achieve (very simplified) is a class which receives a dictionary as String, parses it, and has methods manipulate it like GetRandomEntry.
Here's an elaborated snippet of my code:
public class QuestionsRepository {
private static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
//...
staticĀ 
{
// need to receive and parse dictionary here
}
//...
Taking the relevant parts of a code snippet is never easy, hope i have chosen wisely (:
Another detail that may be relevant - I'm a c# programmer, usually. Just Started learning Java lately.
Thanks.
I think you would need to initialize the static fields of the class according to some input. You can do it in the following way by calling the static method of another class:
class ClassToInitialize {
static {
staticField = ParamPassClass.getParameter();
}
private static String staticField;
ClassToInitialize() {
System.out.println("This is the parameter: " + staticField);
}
}
class ParamPassClass {
private static String parameter;
static String getParameter() {
return parameter;
}
static void setParameter(String parameter) {
ParamPassClass.parameter = parameter;
}
}
class Main {
public static void main(String args[]) {
ParamPassClass.setParameter("Test param");
new ClassToInitialize();
}
}
Java doesn't have static constructors. It only has static initializers and static initializers do not take any arguments. It is executed when the class is first loaded, and there is no way to call it yourself.
You either need to use actual objects, or add some way of configuring the class (eg through a static method).
you should mention the member class with a static qualifier, otherwise there is no such a thing as a static class
Here you can find the explanation of using the word 'static' in this context.
Now you should just call its constructor and pass all the arguments you want,
the only restriction that you have on a static member class is that it can't refer the non-static fields of its outer class, it resembles a static methods on class that can't refer the non-static fields of class.
I didn't understand why do you mention a static initialization block here, could you please clarify a little?
Be aware also that in java there is no such a thing as static constructor....
Hope this helps
You can have a static method public static void setUp(Arg1 arg1, Arg2 arg2...) which sets up all your static fields and invoke it when your program starts.
You have to make sure this method will be called only once [or only when you want to reset these fields]
It is not possible to pass arguments directly to the static initializes (JLS:static initializers).
It would be nice if you could share more information about your goals.
You could use an enum to initialize a singleton with a string parameter like this
import java.util.*;
class Data {
static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
}
public enum QuestionsRepository
{
repository("primary=red,green,blue;secondary=cyan,yellow,magenta");
QuestionsRepository(String dictionary) {
String[] rules = dictionary.split(";");
for (String rule:rules) {
String[] keyValuePair = rule.split("=",2);
Data.easyDefinitions.put(keyValuePair[0],keyValuePair[1].split(","));
}
}
}

Categories

Resources