How do you initialize in java

How to I initialize a variable I created in Java?

(Yes, as a rough performance test you can run each option through a for loop and compare the elapsed time, but it should be easy to see: all else being the same, creating an object n times is going to take more time than creating an object once). For example, assume that takes an inordinate amount of time to instantiate (say, 600 seconds), and that you’re planning on calling a lot (because performance issues are often not realized until projects scale ).

How to I initialize a variable I created in Java?

Thats because you only created a reference to an object without creating the object itself.

temperature tempTemp = new temperature(); 

now the reference is initialized to point to a real object.

temperature tempTemp; just creates local variable but not point/refer to any object or does not get assigned any value. Before invoking a method on an object, you need to get handle(reference) for the object.

temperature tempTemp = new temperature(); 

creates a local variable tempTemp and this variable refers/points to a temperature object and on the next line when tempString.split(» «); is executed, the split method is invoked on the object created on previous line.

Note that you can even initialize tempTemp variable with null, however that would result in NullPointerException in the next line.

Читайте также:  Css стиль создание меню

you only create the variable, but you still need to initialize it. In order to initialize it, you need to allocate it to an object such as

temperature tempTemp = new temperature(); 

Java — When Initializing object, instance variable not, When an object is created on line 3 the class has not finished initializing yet, and the have_instance variable has its default value, null. This value is assigned to the inst_Avail member variable of the object, so the value returned by instance.isInstAvail () in the main method will be null. An easy way to fix this is …

How to initialize objects in Java — with fields or with local variables?

Performance issue isn’t the biggest issue here.

Speaking about performance only, it depends on your use.

The first version can be better as you don’t create new SomeObject every method call.

The second one is better if you create a lot of A s and only call method few times. (As @Marko Topolnik suggested)

However, the biggest issue here is correctness . Using the same object in every call for method is different than using new SomeObject every call.

This issue is much more important than performance.

It depends.

Performance

If you want to evaluate performance differences between two abstract options as you have here; the best way is to exaggerate the scale of everything. For example, assume that SomeObject takes an inordinate amount of time to instantiate (say, 600 seconds), and that you’re planning on calling method() a lot (because performance issues are often not realized until projects scale ).

Well it’s obvious: option 1 will «perform» better over multiple method() calls, since option 2 results in a gigantic operation each time you want to call method. (Yes, as a rough performance test you can run each option through a for loop and compare the elapsed time, but it should be easy to see: all else being the same, creating an object n times is going to take more time than creating an object once).

But performance in itself in the exaggerated example is not necessarily a reason to favor option 1 in all cases.

Architecture

Option 2

It really comes down to the architecture of SomeObject . What is SomeObject ? It could be that SomeObject is an object you cannot keep open for the lifetime of A ; for example, it could be some kind of stream reader that locks down a resource while it is reading from the stream. In this case you might not want to have SomeObject «open» all the time blocking that resource; it should be disposed at the end of the method() call.

Option 1

Well, but perhaps SomeObject is something like a Service or Facade that exposes business logic. As you alluded to in your question it is «better for testing», and the full answer to that is, yes, it gives an easier hook for dependency injection, which is a key component to unit testing. (Although, typically it would be rewritten as private SomeObject a; , with a constructor like public a (SomeObject a) < this.a = a; >to follow the dependency injection / inversion of control paradigm. However, the end result is the same for the purpose of this question.)

In the case of a (well-designed) Service or utility function, you’d expect that it would handle object disposal itself (privately). The more utilized pattern in this case would be option 1, since it gives you one place to manage the dependency instead of within every method that uses it.

Your choice

Knowing the above should be enough to make an informed decision.

  • Option 1 — Services, Facades, utilities, etc.
  • Option 2 — Objects needing to be disposed; objects that implement Closable , like StreamReader , FileWriter , etc.

How is the performance/reliability picture for the following cases

They’re totally different, in the first case a is a class member, in the second a is known only in the scope of method . I’m not sure how much good is «comparing» the performance of these two codes.

But it’s good to note that the in the first code someObject is not created on each call of method . I don’t know how many times you are calling method , your question is hard to answer in it’s current revision.

How to check variable is initialized or not in Java?, If the variable is a class ( static) or instance variable, then it will either be explicitly initialized in the declaration, or default initialized 1. In the 3rd case, the default initial value is null for a reference type, …

How to initialize a local variable in Java only once

The following is a fairly close approximation:

class test < private static final String str = init(); private static String init() < System.out.println("in init()"); return "FOO"; >private void func() < System.out.println("in func()"); >public test() < for (int i=0; i> public static void main(String[] args) < test app = new test(); >> 

Note that str is initialized when the class is loaded, not when func() is called for the first time.

The final qualifier makes the variable constant through a single method call.

Since you want a single value per instance, you can use an instance member variable, outside the method.

private final String str = init(); private void func()

If you wanted a single value across all method calls for all instances, you could use a static member variable, outside the method.

private static final String str = init(); private void func()

Class — How to I initialize a variable I created in Java, creates a local variable tempTemp and this variable refers/points to a temperature object and on the next line when tempString.split(» «); is executed, the split method is invoked on the object created on previous line. Note that you can even initialize tempTemp variable with null, however that would result in NullPointerException in the next line.

How to initialize a variable in a Service class

You can use @PostConstruct :

@PostConstruct private void init() < //fill values into map here >

Spring Beans’ default scope is singleton, so you can use constructor and @PostConstruct as well as InitializingBean interfaces or static initializer. Some suggestion: dont use static variable if not necessary, it is not a good practice, easy to create memory leak etc. If you try to get the map before spring container initialize the bean, it will be empty and other problems can occure.

How do I initialize a Graphics object in Java?, For your class you have overriden the Paint method and in the main you are trying to invoke the paint method. Instead of paint you need to invoke the repaint or update method (if your class is in the hierarchy of java.awt.Container) and the event dispatching system of java invokes your overridden paint method …

Источник

Initializing Fields

As you have seen, you can often provide an initial value for a field in its declaration:

public class BedAndBreakfast < // initialize to 10 public static int capacity = 10; // initialize to false private boolean full = false; >

This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

Note: It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice. It is only necessary that they be declared and initialized before they are used.

Static Initialization Blocks

A static initialization block is a normal block of code enclosed in braces, < >, and preceded by the static keyword. Here is an example:

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

There is an alternative to static blocks — you can write a private static method:

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.

Initializing Instance Members

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

A final method cannot be overridden in a subclass. This is discussed in the lesson on interfaces and inheritance. Here is an example of using a final method for initializing an instance variable:

This is especially useful if subclasses might want to reuse the initialization method. The method is final because calling non-final methods during instance initialization can cause problems.

Previous page: Understanding Class Members
Next page: Summary of Creating and Using Classes and Objects

Источник

Оцените статью