I've included my code below. Following some other examples, I even tried to dynamically load the class in order to force it to run the static block, but that doesn't solve my problem. The class is loaded and class.getName() is printed successfully, but still, when it gets to the last line in the main method it throws an error saying the array is null.
All the other answers address things which don't seem to apply here, like how using the "final" keyword can allow the compiler to skip static blocks. Any help is appreciated!
package helper;
public class StaticTest {
public static boolean [] ALL_TRUE;
private static void setArray(){
ALL_TRUE = new boolean[8];
for(int i=0;i<ALL_TRUE.length;i++){
ALL_TRUE[i] = true;
}
}
static {
setArray();
}
public static void main(String [] args){
ClassLoader cLoader = StaticTest.class.getClassLoader();
try{
Class aClass = cLoader.loadClass("helper.StaticTest");
System.out.println("aClass.getName() = " + aClass.getName());
} catch(ClassNotFoundException e){
e.printStackTrace(System.out);
}
System.out.println(StaticTest.ALL_TRUE[0]);
}
}
In case anyone else lands here, the problem was that I had checked the Netbeans option "Compile on Save" (under Build->Compiling). Somehow, compiling files immediately upon saving was preventing the static block from being run.
Again, thanks to everyone who chimed in to verify that the code itself worked as expected.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have an Android app that is recently published, and I'm receiving crash reports from Google Play Console. One of the crashes is strange. It happens in code similar to the following:
private final List<Item> items = new ArrayList<>();
public void addItem(Item item) {
items.add(item); // NullPointerException here!!
}
Apparently items is null when addItem is called, but it seems to me that it's impossible—I've initialized it at the declaration site. I can't imagine a situation in which this could happen, yet it happens a lot. Any idea?
Alright, psychic debugging time. The only way this could happen is if something is calling it as part of the object init, either during setup of other variables or an explicit init { ... } block.
You are almost certainly doing something like this elsewhere in the code:
import java.util.*;
class Main {
private static class Item { }
private final Item firstItem = setUpItemsAndReturnFirst();
private final List<Item> items = new ArrayList<>();
public void addItem(Item item) {
items.add(item); // NullPointerException here!!
}
private Item setUpItemsAndReturnFirst() {
Item first = new Item();
Item second = new Item();
addItem(first);
addItem(second);
return first;
}
public static void main(String args[]) {
new Main();
}
}
This contains your sample code, and will crash on that line with a NullPointerException, because setUpItemsAndReturnFirst() is being called before items is initialized when it's used to initialize firstItem.
I assume it's behind some sort of conditional, in your case, since it presumably doesn't crash every time or you'd never have released it. But this is the general idea.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to learn object oriented code in Java, and am following a tutorial. I am currently stuck trying to parse a string into my class. It is returning the following error:
Name cannot be resolved to a variable
I have a main file, called start.java, and the class I am trying to call is in a different file, called phone.java. Both are in a folder called src. Below is the start.java code (which is throwing the error)
package src;
public class Start {
public static void main(String[] args){
phone android = new phone(Name:"android 10");
System.out.println(android.getName());
}
}
And here is the class I am trying to call, in phone.java
package src;
public class phone{
private String name;
public phone(String name) {
this.name = name;
}
public String getName(){
return this.name;
}
}
Much thanks for your help
You need to remove the Name from new phone(Name:"android 10") and need to use new phone("android 10").
You just need to pass the value for the name, your constructor will bind it to the name variable.
Refer below code
public class Start {
public static void main(String[] args){
phone android = new phone("android 10");
System.out.println(android.getName());
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm new to this so sorry if i don't explain it great.
I have 2 class Interface and Depot.
I can call depot1.getName() and depot2.getName() in Instance class.
But I can't call them in Depot class as I am trying to check no instance of that class has the entered name:(tempname.equals(depot1.getName()) || tempname.equals(depot2.getName()))
Could it be because depot1 and depot2 haven't been created yet?
Here is getName
public String getName(){
return name;
}
I think it may have to do with the fact that depot2 may not exist so i tried:
(depot2 != null && tempname.equals(depot2.getName()))
but that still gives more erors and won't let me compile
I am getting the following error "cannot find symbol - variable depot1"
Can I use isInstance? https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isInstance%28java.lang.Object%29
Any help would be greatly appreciated, Thanks
Looks like your code don't have instance of depot1 create a instance using new like following snippet: This is not exact answer but it will help you.
package com.test;
class Depot
{
private String name;
public String getName()
{
return name;
}
public void setName( String name )
{
this.name = name;
}
}
public class Test
{
public static void main( String[] args )
{
Depot depot1 = new Depot();
depot1.setName( "depot1" );
Depot depot2 = new Depot();
depot2.setName( "depot2" );
// Rest of code
//(tempname.equals(depot1.getName()) || tempname.equals(depot2.getName()))
}
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to have only 5 instance of a class throughout the application life time. How can I achieve this? Please give sample code, if possible.
As Singletons shall be made with enums (See "Effective Java"):
public enum FiveInstance {
INSTANCE1, INSTANCE2, INSTANCE3, INSTANCE4, INSTANCE5;
public void anyMethod() {}
}
Greetz GHad
The Factory pattern could be your friend. One (fictional, not threadsafe and thus quite simple) example to illustrate the approach:
public static MartiniFactory {
private static int olives = 100; // you asked for '5' but 100 is more realistic
// for this example.
public static Drink createMartini() throws OutOfOlivesException {
if (olives > 0) {
olives--;
return new Martini(new Gin(4), new Vermouth(1), new Olive());
else {
throw new OutOfOlivesException();
}
}
// forgot to mention, only the factory (=bar) is able to create Martinis, so:
private class Martini {
Martini(Ingredient... ingredients) {
// ...
}
// ....
}
}
EDIT
The license example was not too good - so I moved it to a domain that expects, that objects created by the factory are not returned and destroyed without noticing the factory. The Bar can't create Martinis when there is no olive left and it definitly doesn't want the drink back after it has been consumed ;-)
EDIT 2
And for sure, only the factory can create Instances (=Drinks).
(No guarantee, that the added inner private class fulfills this requirement, don't have
an IDE at hand to do a quick test .. feel free to comment or edit)
class Sample
{
private static int i = 0;
private Sample()
{
}
public static Sample CreateInstance()
{
if(i <5)
{
i++;
return new Sample();
}
else
throw new Exception("Can not create more then 5 instance of this class");
}
}
Have a look at the static keyword.
public class FiveInstance {
private static int instanceCount = 0;
private FiveInstance(){
}
public static FiveInstance getNewInstance() throws InstanceExceededException{
if(instanceCount < 5){
instanceCount++;
return new FiveInstance();
}else{
throw new InstanceExceededException();
}
}
}
Create a private static member to count the instances of the class. Then, make sure every constructor of your class increment this static variable and test for overflow. If you have more than one constructor I suggest that you make one constructor implement this behaviour and the others should call it. The behavior of the constructor upon an attempt to create a sixth instance is up to you. Maybe you want to throw an Exception.
You can try following code but written in C#, you can get a basic idea how can it be done.
public class MultiTone
{
private static MultiTone _cache;
private static int _counter=5;
MultiTone()
{
}
public static MultiTone GetInstance()
{
if(_counter==0)
{
return _cache ?? (_cache = new MultiTone());
}
_counter--;
return new MultiTone();
}
}
And mind that this class is't intended to use in multi-threading environment.
I think you can't. You can force that if somebody want to create or destroy an instance has to use these static methods:
import java.util.*;
public class Fiveton {
public final static int MAX_INSTANCES = 5;
private static List<Fiveton> instances = new ArrayList<Fiveton>();
private Fiveton() { }
public static Fiveton getInstance() {
if (instances.size()>=MAX_INSTANCES) throw new RuntimeException("Hey! You've reached the maximum of instances: " + MAX_INSTANCES);
Fiveton instance = new Fiveton();
instances.add(instance);
return instance;
}
public static void destroy(Fiveton instance) {
instances.remove(instance);
}
}
The problem is method destroy. You can't be sure that someone is still referencing the destroyed object.
There is a pattern called a Multiton which deals with this, as an extension of Singleton. Nobody seems quite clear it it's a pattern in its own right or a variation on Singleton. Check out the link, it includes sample code.
Look at Object pool pattern. Its java implementation is greatly described in Grand Patterns in Java V1.
Short description from the book overview:
Object Pool
Manage the reuse of objects for a type
of object that is expensive to create
or only a limited number of a kind of
object can be created.
Create a static field called howMany which will be incremented each time that the constructor is called.
When howMany is => 5, deny creation of the object.