This question already has answers here:
Is this a valid way to count instances of objects?
(2 answers)
Closed 9 years ago.
class Clasa {...}
class Test {
public static void main(String[] args){
Clasa x = new Clasa();
System.out.println(x.getNo());//displays 1
Clasa[] y = new Clasa[10];
for(int i = 0; i<4; i++)
y[i]=new Clasa();
System.out.println(y[0].getNo()); //displays 5
}
}
How can I replace those three dots, so GetNo() method call to return the number of instantiated objects of class Clasa. Test class should not be changed.
Add a static variable which acts as a counter and increment it inside the constructor and getNo returns the value of the static variable.
Static variable have their values kept across all instances of a class
class Clasa {
private static int nbInstances = 0;
public Clasa () {
nbInstances++;
}
public int getNo() {
return nbInstances;
}
}
I agree with Brian , on that the above code is not considering the GC. So I would like to replace your code with the below code snippet
package com.instance.main;
import com.instance.target.Clasa;
public class Test{
public static void main(String[] args) {
Clasa targetClass;
Object[] object=new Object[10];
for(int i=0;i<object.length;i++){
object[i]=new Clasa();
}
System.out.println("Number of Instantiate Object {Before Calling GC}: "+Clasa .getNumberOfInstatiateObj());
/* Here I am trying to deallocate the memory of Object at index no 9, so that GC called this unused object to deallocate it from memory*/
for(int i=0;i<object.length;i++){
if(i==8){
object[i]=object[i+1];
object[i+1]=null;
System.runFinalization();
System.gc();
}
}
}
}
just put the above code beneath the main method and also you have to modify your Clasa code from the below code
package com.instance.target;
class Clasa {
private static int nbInstances = 0;
public Clasa () {
nbInstances++;
}
public int getNo() {
return nbInstances;
}
public void finalize(){
nbInstances --;
System.out.println("Number of Instantiate Object {After Calling GC}: "+nbInstances );
}
}
After modifying your code by following the above steps , your code will give you your desired output.
Please let me correct if I am wrong some where.
Hi Dany I modified my code , so according to the above code ,you have to create your class under different package which written in the class code . And let me know if you are getting problem still.
Related
I cant understand whats wrong with my code. In this code i getting errors like this when im trying to assign a value to a variable within a class. Also System.out.println doesnt work in this classes:
1.Identifier expected
2.Unexpected token
3.Unknown class "windows"
public static void main(String[] args) {
}
class building{
int apart_num;
apart_num = 3;
}
class apartments{
double area;
int lightbulb;
int windows;
windows = 4;
}
interface construct_building{
}
interface construct_apartments{
}
You are declaring an instance member on one line :
int apart_num;
and then assign a value to it :
apart_num = 3;
The problem is that this is done outside a method, those statement can't be separated, you can't assign a variable previously declare outside a block statement so.
Do it in a one line (declaration and assignation) :
class building{
int apart_num = 3;
}
or with a constructor
class building{
int apart_num;
public building(){
apart_num = 3;
}
}
or in a block statement
int windows;
{ //a block statement
windows = 4;
}
Then, if this code is not a class, you need to do it.
public MyClass{
public static void main(String[] args){ ... }
...
class Building { //inner class (will exist only inside of a MyClass instance
}
static class Apartment { // a nested class, exist whitout a MyClass instance
}
}
class Level { //A class that have nothing to do with MyClass and that can not be public.
}
Where MyClass is the name of the file (MyClass.java)
Ok im doing a project for school and I would post all of that code but I dont think its necessary. I just want to see if it's possible to do it in a very simple way so I can apply it into the bigger code. For the bigger code im using Android studio's to create an app.
So my problem is that I have a void method, I cant change it to any other value in the bigger code I think, but i'm trying to add numbers a public variable inside the method. Then later in another method trying to return the new value. Here is my code that im testing right now.
public class test{
public static void main(String [] args){
other h = new other();
int num = h.getV();
System.out.println(num);
}
}
public class other{
public int book = 0;
public void g(){
book++;
book++;
}
public int getV(){
return (book);
}
}
It prints out 0, but I want it to print out 2. Also public void g() can't change value types.
You should probably call g() first before calling getV(). g() increments, and getV() returns the value of the variable named book.
public class test{
public static void main(String [] args){
other h = new other();
h.g();
int num = h.getV();
System.out.println(num);
}
}
public class other{
public int book = 0;
public void g(){
book++;
book++;
}
public int getV(){
return (book);
}
}
You're creating a new other object called h storing an int called book that's equal to 0 initially.
g() will add one to the current value of book twice whenever its used so +2
getV() will print out whatever the current value of book in h is
since you never called h.g() in your main method, book in h is still 0 so that's what you're retrieving
I've recently started using java and I am trying to make a program that checks to see if an array can be changed to ascending order by returning true/false.
That is the gist of it however I am having problems with the main class. The error I am getting is that the main method is not found in class.
public static boolean solution (int[] A){
int count = 0;
.......
.......
.......
for(int i=0; i<A.length; i++)
{
if(A[i] != B[i]) count++;
}
if(count > 2) return false;
return true;
}
}
Since I am doing this as my java summer homework I am abit confused as to where I should add the main method. I know it is supposed to be
public static void main (String args[])
However if I were to add that from the start of the code after the class I get errors. Is it because I cannot have
public static boolean and public static void main
in the same class?
Thanks.
You can have public static boolean and public static void main in the same class. A main method can be added anywhere within a class as long as you define it as its own standalone method, don't declare inside another method. For Example:
public class Example{
public void method1(){
....
}
public void method2(){
....
}
public static void main(String[] args){
....
}
}
oke if you are using an ide like intellij you must also configure which class has the main method in you project.
You CAN have a main method and other static methods in the same class. In fact you can have any type of method in the class. The reason your program cannot "find a main method" is because there either isn't one there, or your run configuration is off.
A java program starts, with some exceptions of the initializer blocks, at the main method. So you MUST have it in at least one class in your program.
From what it sounds like you want to test if the array is already in ascending order. Since all arrays that are not empty, can be sorted.
public class Example{
public static void main(String[] args){
int[] test = {1,2,3,4,5};
System.out.println(solution(test));
}
public static boolean solution (int[] a){
//returns true if in a
for (int i = 0; i < a.length-2; i++) {
if (a[i] > a[i + 1])
return false;
}
return true;
}
}
If your cannot find main method error continues. It is probably your run configuration
If you are getting an error, based on the way you phrased your question, it sounds like you have a method with the exact same method signature.
You can not have:
public static void main(String[] args)
{
}
public static boolean main(String[] args)
{
return false;
}
If this is what you have, you should probably rename the second method.
Im not sure how to exactly explain this problem, but Im pretty sure Im making a very simple mistake that can be corrected quite quickly.
Also, I thought it would be more convenient if this was shown off as a screenshot. The first two tabs are my interface and error catching classes.
As you can see, the code for methods to use in my Queue ADT seems to be out of scope. So I can move on and complete this bit of coursework, can someone explain to me why it is out of scope?
Thanks for any help!
You declare those variables in main method, so only main local scope know them. Move the declaration to class level
public class QueueProgram {
private static int queuesize = 10;
public static void main(String[] args) {
}
}
Note I declared queuesize as static since the main uses it. Another option is to create getters and setters and call them with an instance of QueueProgram
public class QueueProgram {
private int queuesize = 10;
public int getQueuesize() {
return queuesize;
}
public void setQueuesize(int size) {
queuesize = size;
}
public static void main(String[] args) {
QueueProgram program = new QueueProgram();
program.getQueuesize(); // return 10;
program.setQueuesize(5);
program.getQueuesize(); // now it is 5;
}
}
Alright, so in my driver class, I want to call my arraylist from another class and print it out. However, when I attempt to call the method, it says that the variable cannot be resolved to a variable. Does anyone have any idea how I can get it "to be resolved".
Here's my code:
Driver:
public static void showing(){
OtherClass.initializeStrings();
System.out.println(OtherClass.showLists(mouseTypes));
}
Other Class:
static ArrayList <String> mouseTypes;
public static void initializeStrings(){ //initialize the strings outside the main
Strings = new ArrayList <String>();
Strings.add("goodbye");
Strings.add("hello");
Strings.add("hi");
}
public static void main(String[] args) {
OtherClass.initializeStrings();
Driver.showing();
}
public static void showLists(ArrayList list){
for (int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
Any help is appreciated.
Use .showLists(OtherClass.mouseTypes).
However, that breaks both the Single Responsibility Principle, and Encapsulation. Fix it.
Also, you have done a very bad copy-paste job, you have two main methods...