what does the static modifier do in java - java

In this book, there is this example of how to use static variables and methods. I dont understand what is going on. explain why there has to be static in front of the methods and variables. There are two seperate classes called Virus and VirusLab. The VirusLab.java takes in a command line argument and makes the amount of Virus objects, then spits out the number of Virus objects. Thanks
Virus:
public class Virus {
static int virusCount = 0;
public Virus() {
virusCount++;
}
public static int getVirusCount() {
return virusCount;
}
}
VirusLab:
public class VirusLab {
public static void main(String[] args) {
int numViruses = Integer.parseInt(args[0]);
if (numViruses > 0) {
Virus[] virii = new Virus[numViruses];
for (int i = 0; i < numViruses; i++) {
virii[i] = new Virus();
}
System.out.println("There are " + Virus.getVirusCount()
+ " viruses.");
}
}
}

A web search would have given you hundreds of links to explain 'static' keyword in Java.
Please refer to the following documentation: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Also, please refer a text book for your further learning, that will help a lot.

I will keep it pretty short
You need static variables if you want that variable to be shared
across all the objects of your class,so that if one of the object
changes its value it would be reflected in other objects as well,which
is what is exactly done in above example.

A static variable is one which is not associated with an instance of a class.
This means you don't have to create a new instance of the class to access the variable from another class. Consider this:
public class Login {
public static String loggedInUser
public void setLoggedInUser(String name){
this.loggedInUser = name;
}
}
To access the String loggedInUser in another class, you wouldn't have to say
Login login = new Login();
String username = login.loggedInUser;
You'd just have to say
String username = Login.loggedInUser;
This can be useful in accessing variables outside of the class they were set in.
Hope that helps.

try reading this answer I gave in a previous question:
Accessing Static variables
and make google and wikipedia ur friend they'll save u time coming on here posting questions ,waiting and refreshing ur page to check if any answers were given.

Related

How to deal with an unitialized constructor in an if statement (Java)

I've run into a problem where I attempt to define a constructor in the first part of a switch/case statement, and then I can't run the code because the program can't get the definition later.
The idea behind passing the constructor information from a switch/case function is that the user chooses what to do, but for some options, one must be done before the other is possible (e.g. Create password and Check password).
If I try doing it this way, it throws a VarMayNotHaveBeenInitialized error (I get the sense the answer is in a try/catch statement, but I don't know enough about them to be sure). I've included some code that is what I've been essentially trying to do below. (The two classes are to best simulate the project I'm working on.)
Any help is appreciated! : )
TestMain.java:
package exitTest;
public class TestMain {
InitializeTest init;
public static void main(String[] args) {
while (true) {
String x = InitializeTest.askQuestion();
switch (x) {
case "set":
InitializeTest init = new InitializeTest();
break;
case "get":
if (init != null) {
init.showExample();
} else {
System.out.println("Error: init not initialized.");
} break;
}
}
}
}
InitializeTest.java:
package exitTest;
import java.util.Scanner;
public class InitializeTest {
static Scanner in = new Scanner(System.in);
public InitializeTest thing1;
public String example;
public static String askQuestion() {
System.out.println("set for set example\nget for check example");
String action = in.nextLine();
return action;
}
public InitializeTest() {
System.out.println("Input string:");
String example = in.nextLine();
}
void showExample() { System.out.println(example); }
}
You include the type when you're declaring variables, not when simply assigning to an existing one. When you write
InitializeTest init = new InitializeTest();
That makes a new init variable, unrelated to the previous one, which stores the newly constructed object. That new variable shadows the existing one, but it gets released after the switch block is over (variables in Java are block-scoped).
To put it to an analogy, it's as though you wanted to tell your friend Alice a secret. But when you went to her house, her neighbor whose name is also Alice happened to be there instead. If you tell that Alice your secret, then your friend doesn't find out. Even though the two happen to share a name, they don't share any memory.

Java: Accessing different variables in a different class to be used within a conditional statement

I have done some research on the forums and found this to be most applicable my question but the solution doesn't work: accessing a variable from another class
So I am trying to access two variables in my "LibraryCard" class:
private int limit;
private int booksBorrowed;
I found that if I want to access them in my second class "Student" I have to add a get method in my "LibraryCard" class:
public int getlimit()
{
return this.limit;
}
public int getbooksBorrowed()
{
return this.booksBorrowed;
}
After accessing these 2 variables I need to use them in an if statement in my "Student" class:
Which i have implemented this way
public boolean finishedStudies()
{
if ( (this.booksBorrowed = 0) && (this.booksBorrowed >= this.limit)) {
return true;
}
else
return false;
}
When i try to compile it BlueJ says it cannot find variable booksBorrowed and limit
I am very new to Java and Programming in general, help would be greatly appreciated.
You have the create an instance of your LibraryCard class inside your Student class and then you can access the two variables by invoking the getters on that instance:
LibraryCard card = new LibraryCard();
int limit = card.getlimit();
int booksBorrowed = card.getbooksBorrowed();

Increment the number by 1 whenever i call the funtion in java

I am trying to print the number increment by 1 whenever i call the function, but i am not able to get the solution, below is my code
The blow is the function
public class Functions<var> {
int i=0;
public int value()
{
i++;
return i;
}
}
I am calling the above function here
import Java.Functions;
public class Increment {
public static void main(String[] args)
{
Functions EF = new Functions();
System.out.println(EF.value());
}
}
Whenever i run the program , i am getting only the output as 1 , but i want the output to be incremented by 1 . Could you please help. Thanks in Advance.
I believe your answer is with the scope of your variables and your understanding of them. You only call the method once in your given examples, so 1 is arguably the correct answer anyway. Below is a working example which will persist during runtime one variable and increment it every time a function is called. Your methods don't seem to follow the common Java patterns, so I'd recommend looking up some small example Hello, World snippets.
public class Example{
int persistedValue = 0; // Defined outside the scope of the method
public int increment(){
persistedValue++; // Increment the value by 1
return persistedValue; // Return the value of which you currently hold
// return persistedValue++;
}
}
This is due to the scope of "persistedValue". It exists within the class "Example" and so long as you hold that instance of "Example", it will hold a true value to your incremented value.
Test bases as follows:
public class TestBases {
static Example e; // Define the custom made class "Example"
public static void main(String[] args) {
e = new Example(); // Initialize "Example" with an instance of said class
System.out.println(e.increment()); // 1
System.out.println(e.increment()); // 2
System.out.println(e.increment()); // 3
}
}
If your desire is out of runtime persistence (the value persisting between application runs) then it would be best to investigate some method of file system saving (especially if this is for your Java practice!)
Your main problem is to increment the number value 1.
But you are calling your function only once. Even though you call the function many times you will get the value 1 only because it is not static variable so it will every time initialize to 0.
So please check below answer using static context.
Functions.java
public class Functions{
static int i=0;
public int value()
{
i++;
return i;
}
}
Increment.java
public class Increment{
public static void main(String []args){
Functions EF = new Functions();
System.out.println(EF.value());
System.out.println(EF.value());
System.out.println(EF.value());
}
}
Output:
1
2
3
If you design multi-threaded application, it will be better to use AtomicInteger.
The AtomicInteger class provides you an int variable which can be read and written atomically.
AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.incrementAndGet();

Calling static methods/fields

I'm currently stuck on a project. Here's what I should do:
Copy the Employee.java file from the java1_Lesson14 project to the java1_Project14 project. First, use what you've learned about encapsulation to protect your data.
Use a call to the System.out.println() method to display in the console the names and values of all of the instance variables in each instance of the Employee class. Also print to the console the value of any static variables.
Note that, if you access a static variable via an instance, Eclipse will warn you that this is not optimal behavior. Use the correct form for accessing and displaying any static information.
I think I did the encapsulation part right. The problem now is the warnings messages I'm getting from Eclipse.
On e2.setTopSalary(199000) I get the following message: "The static method setTopSalary(int) from the type Employee should be accessed in a static way."
And on System.out.println("e2 Top Salary is " + e2.topSalary): "The static field Employee.topSalary should be accessed in a static way."
Can anyone give me a light on how do I fix this?
public class Employee {
private static int topSalary = 195000;
private int hoursPerWeek;
public static void setTopSalary (int s) {
if (s > topSalary)
topSalary = s;
}
public void addMoreHours() {
hoursPerWeek++;
}
public static void main(String[] args) {
Employee e1, e2;
e1 = new Employee();
e2 = new Employee();
Employee.setTopSalary(199000);
e2.setTopSalary(199001);
e1.hoursPerWeek = 40;
e2.hoursPerWeek = 45;
System.out.println("Employee Top Salary is " + Employee.topSalary);
System.out.println("e2 Top Salary is " + e2.topSalary);
System.out.println("e1 working hours per week are " + e1.hoursPerWeek);
System.out.println("e2 working hours per week are " + e2.hoursPerWeek);
}
}
The static keyword means that all instances of the class still refer to one instance of the field. That field is effectively per-class.
You call it as follows:
Employee.setTopSalary(12000);
and access fields by:
System.out.println(Employee.topSalary);
Employee is the class name.

Java method help [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Static method in java
Ok, so I'm working on a project for a class I'm taking.. simple music library. Now I'm having some issues, the main issue is I'm getting "non-static method cannot be referenced from a static context"
Here is a function I have
public void addSong() {
Scanner scan = new Scanner(System.in);
Song temp = new Song();
int index = countFileLines(Main.databaseFile);
index = index + 2;
temp.index = index;
System.out.print("Enter the artist name: ");
temp.artist.append(scan.next());
}
Now thats in a class file called LibraryFunctions. So I can access it with LibraryFunctions.addSong();
Now I'm trying to run this in my main java file and its giving me the error, I know why the error is happening, but what do I do about it? If I make addSong() a static function then it throws errors at me with the Song temp = new Song() being static. Kind of ironic.
Much help is appreciated on this!
Follow these simple rules:
If it's a static method call it with ClassName.methodName()
If it's a non-static method call it with classInstance.methodName()
If you want to call it as LibraryFunctions.addSong(), it needs to have the signature public static void addSong().
More info:
Only static methods can be called without instantiating a class first.
You can also try:
LibraryFunctions lf = new LibraryFunctions();
lf.addSong();
Well you have two options really:
Change addSong() to static and reference Song through it's static members if possible.
Create a new instance of LibraryFunctions and then use the non-static method addSong()
I take that your class Song is a non static nested class? e.g.
class LibraryFunctions {
class Song {
// ...
}
}
If so you can either make it a static nested class, or lift the Song class into a separate class.
In terms of structure, may I suggest that the LibraryFunctions class file be turned into a MusicLibrary class? That way, in your main application code, you can instantiate a MusicLibrary every time the code runs. It will also make it easier to separate static functions and instance functions, which would probably solve your issue right now.
public class MusicManager {
public static void main(String[] args) {
MusicLibrary myMusic = new MusicLibrary();
myMusic.addSong();
// other stuff
}
}
Then MusicLibrary:
public class MusicLibrary {
public MusicLibrary() {
}
public void addSong() {
Scanner scan = new Scanner(System.in);
Song temp = new Song();
int index = countFileLines(Main.databaseFile);
index = index + 2;
temp.index = index;
System.out.print("Enter the artist name: ");
temp.artist.append(scan.next());
}
}
And finally, I would put the class Song outside of MusicLibrary so that you can reuse it later.
Another added benefit of this is that you can make MusicLibrary implement Serializable and save the library to a file. Plus you could place an array of MusicLibraries inside of a MusicLibrary and have playlists. All kinds of options.

Categories