Accessing class string returns NULL - java

This is a debug oriented question, but i've been very confused why some of my objects are returning NULL values.
I have a GUI here that takes strings from the text field when a button is clicked,
public class USAdditionalGUI extends javax.swing.JFrame {
public String AreaCode; // declare Strings
public String Exchange;
public String LastFour;
public String State;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// On button click use getText() to collect the strings from the
//`enter code here` fields and store them into the declared strings.
AreaCode = jTextField3.getText();
Exchange = jTextField1.getText();
LastFour = jTextField2.getText();
State = jTextField4.getText();
}
The next class has get methods for each of the String varibles, and here lies the problem, I create an object to the GUI class and try to access the String information but it keeps coming up NULL when I print it out.
public class TRFUSAddressFormatting{
private String State;
private String areacode; // 3 digits
private String digitExchange; // 3
private String lastfour; // 4
USAdditionalGUI usobj = new USAdditionalGUI();
public String getState(){
State = usobj.State;
System.out.println(State); // Why does this print NULL!!?!?!
return State;
}
}
Am I accessing the string correctly?

when you declare strings, you need to initialize them or they will be null.
public class USAdditionalGUI extends javax.swing.JFrame {
public String AreaCode = ""; // declare Strings
public String Exchange = "";
public String LastFour = "";
public String State = "";
or whatever DEFAULT value you want to them
btw, I suggest you to declare them private and implement a get method to retrieve their information
public class USAdditionalGUI extends javax.swing.JFrame {
private String AreaCode = ""; // declare Strings
private String Exchange = "";
private String LastFour = "";
private String State = "";
public String getAreaCode(){
return AreaCode;
}
//and so

Variables/fields in your snippet ie, AreaCode, Exchange are instance variables of a class which are initialized to their default values when class's object is created. Objects' default value is null unless explictly initialized and primitives have their own default values like int -> 0 etc. Since Areacode, Exchange, LastFour, State above are of type String which are stored as objects on JVM Heap hence they are initiazed to null unless you explicitly initialize them yourself.

Related

Java nested POJO update based on dot annotation

I have a nested POJO structure defined something like this,
public class Employee {
private String id;
private Personal personal;
private Official official;
}
public class Personal {
private String fName;
private String lName;
private String address;
}
public class Official {
private boolean active;
private Salary salary;
}
public class Salary {
private double hourly;
private double monthly;
private double yearly;
}
I get updates from a service with dot annotaion on what value changed, for ex,
id change --> id=100
address change --> personal.address=123 Main Street
hourly salary change --> official.salary.hourly=100
This POJO structure could be 3-4 level deeps. I need to look for this incoming change value and update the corresponding value in POJO. What's the best way of doing it?
If you would like to create Java objects that allows you to edit fields. You can specify your object fields with the public/default/protected access modifiers. This will enable you to get and set fields such as personal.address or official.salary.hours
This approach is typically frowned upon as the object is no longer encapsulated and any calling methods are welcome to manipulate the object. If these fields are not encapsulated with getters and setters, your object is no longer a POJO.
public provides access from any anywhere.
default provides access from any package
protected provides access from package or subclass.
public class Employee {
public String id;
public Personal personal;
public Official official;
}
public class Personal {
public String fName;
public String lName;
public String address;
}
Here's a quick approach using reflection to set fields dynamically. It surely isn't and can't be clean. If I were you, I would use a scripting engine for that (assuming it's safe to do so).
private static void setValueAt(Object target, String path, String value)
throws Exception {
String[] fields = path.split("\\.");
if (fields.length > 1) {
setValueAt(readField(target, fields[0]),
path.substring(path.indexOf('.') + 1), value);
return;
}
Field f = target.getClass()
.getDeclaredField(path);
f.setAccessible(true);
f.set(target, parse(value, f.getType())); // cast or convert value first
}
//Example code for converting strings to primitives
private static Object parse(String value, Class<?> type) {
if (String.class.equals(type)) {
return value;
} else if (double.class.equals(type) || Double.class.equals(type)) {
return Long.parseLong(value);
} else if (boolean.class.equals(type) || Boolean.class.equals(type)) {
return Boolean.valueOf(value);
}
return value;// ?
}
private static Object readField(Object from, String field) throws Exception {
Field f = from.getClass()
.getDeclaredField(field);
f.setAccessible(true);
return f.get(from);
}
Just be aware that there's a lot to improve in this code (exception handling, null checks, etc.), although it seems to achieve what you're looking for (split your input on = to call setValueAt()):
Employee e = new Employee();
e.setOfficial(new Official());
e.setPersonal(new Personal());
e.getOfficial().setSalary(new Salary());
ObjectMapper mapper = new ObjectMapper();
setValueAt(e, "id", "123");
// {"id":"123","personal":{},"official":{"active":false,"salary":{"hourly":0.0,"monthly":0.0,"yearly":0.0}}}
setValueAt(e, "personal.address", "123 Main Street");
// {"id":"123","personal":{"address":"123 Main Street"},"official":{"active":false,"salary":{"hourly":0.0,"monthly":0.0,"yearly":0.0}}}
setValueAt(e, "official.salary.hourly", "100");
// {"id":"123","personal":{"address":"123 Main Street"},"official":{"active":false,"salary":{"hourly":100.0,"monthly":0.0,"yearly":0.0}}}

Final members with multiple constructor

I have a class like this.
public class AuditEvent {
private final String m_timeStamp;
private final String m_userName;
private int m_moduleId;
private int m_actionId;
private final String m_objectName;
private final String m_loggedInUserHostOrIP;
public AuditEvent() {
// No content
}
public AuditEvent(String timeStamp, String userName, String loggedInUserHostOrIP, String objectName) {
if (StringUtils.nullOrEmpty(timeStamp)) {
throw new IllegalArgumentException("The timeStamp field is not supplied");
}
if (StringUtils.nullOrEmpty(timeStamp)) {
throw new IllegalArgumentException("The userName field is not supplied");
}
if (null == objectName) {
throw new IllegalArgumentException("The objectName field is not supplied");
}
if (null == loggedInUserHostOrIP) {
throw new IllegalArgumentException("The loggedInUserHostOrIP field is not supplied");
}
m_timeStamp = timeStamp;
m_userName = userName;
m_loggedInUserHostOrIP = loggedInUserHostOrIP;
m_objectName = objectName;
}
But this gives an error that the final field m_userName may not have been initialized. It works if I don't have the empty constructor. Can anyone help me to solve this problem?
You have declared m_timeStamp as final but you have never initialized it in the empty constructor.
Every constructor should declare the variable if it's final, not just one. Or you can initialize it after declaring it, which will be valid aswell. eg
private final String m_timeStamp = "test";
Fill in all final fields in every constructor. Calling another constructor as follows helps:
public AuditEvent() {
this("" /*timeStamp*/, "" /*userName*/, "" /*loggedInUserHostOrIP*/, "" /*objectName*/);
}
A final field has to be initialized as the object is fully build and that the constructor has returned.
While here final fields are never valued :
public AuditEvent() {
// No content
}
So if you invoke this constructor and not the other one you violate the final constraints. Whereas the compilation error.
If the no arg constructor makes sense in your use case you could still define field initializers such as :
private final String m_timeStamp = "...";
private final String m_userName = "...";
Or as alternative chain the the no arg constructor to the args constructor :
public AuditEvent() {
this("...", "...", ...);
}
In java final variables must be initialized only once, before or inside constructor.

How to make the value of a String variable not change after once assigned? [duplicate]

This question already has answers here:
Declare final variable, but set later
(7 answers)
Closed 5 years ago.
How can I make sure that the value of String variable doesnot change after being assigned once? Assignment is not at the time of declaration.
More clarity :-
String x = y; (y is another string)
Even if y changes x should not change. How to make sure this?
What I have tried :-
Created a custom class:-
public class MyDs {
private final String unitName;
public MyDs(String iUnitName){
unitName = iUnitName;
}
public String getUnitName(){
return unitName;
}
}
in the main method :-
String iName = "xyz";
MyDs MyDsObj = new MyDs(iName);
But even after this, the value changes when the variable changes.
How can I solve this issue?
Your class be should be design as mentioned in below code
public class TestingClas {
private String name;
public void setName(String name) {
if (this.name == null && name != null)
this.name = name;
}
public String getName() {
return name;
}
}
Now use below code for testing purpose
TestingClas testingClas = new TestingClas();
testingClas.setName("Abdul Waheed");
testingClas.setName("You cannot change me any more now");
String updatedString = testingClas.getName();
updatedString variable will be having old value
as far as I understand ,you should design your class in a way that your variable should be final . with this approach you set it in constructor and then nothing can make it changes. even the referance it is holding is changed the value remains the same I mean a new object is created in heap and value of your final variable is kept same. below is a kind of design which makes the variable x set once and never be able to changed afterwards. Of course this is in instance scope, for class scope you can make your class singelton etc.
public class Test {
private final String x;
private String y;
public Test(String x){
this.x=x;
}
public String getY() {
return y;
}
public void setY(String y) {
this.y = y;
}
public String getX() {
return x;
}
}
Change your MyDs class to a singleton class
Making this a singleton class ensures that the final String unitName is updated only once and then it will cannot be altered again.
public class MyDs {
private final String unitName;
private static MyDs myDs;
public static MyDs getMyDsObject(String iUnitName) {
if (myDs == null) {
myDs = new MyDs(iUnitName);
}
return myDs;
}
private MyDs(String iUnitName) {
unitName = iUnitName;
}
public String getUnitName() {
return unitName;
}
}
Here the values "xyz" is stored in unitName and doesnot get updated again when you change to "zxy".
MyDs MyDsObj = MyDs.getMyDsObject("xyz");
Log.i("value", "" + MyDsObj.getUnitName());
MyDs MyDsObj1 = MyDs.getMyDsObject("zxy");
Log.i("value",""+MyDsObj.getUnitName());
Well, you question is not really clear (and the comment section is really chaty...), but if you want to only be able to set a value once but not during the initialisation, setters are not a bad choice. Just add a constraint.
public class MyClass{
private static final String DEFAULT_VALUE = new String("");
private String value = DEFAULT_VALUE;
public final void setValue(String value){
if(this.value != DEFAULT_VALUE) //use the reference on purpose
throw new IllegalArgumentException("This value can't be changed anymore");
this.value = value;
}
// Don't return `DEFAULT_VALUE` to prevent someone to gain access to that instance
public final String getValue(){
return this.value == DEFAULT_VALUE ? null : this.value;
}
}
This will be done at runtime, but this would do the trick.
Now, this is an immutable instance, with some mutable instance you might want to do a copy of it to be sure it can't be modifier using the original reference.

how can I return a String?

package book1;
import java.util.ArrayList;
public abstract class Book {
public String Book (String name, String ref_num, int owned_copies, int loaned_copies ){
return;
}
}
class Fiction extends Book{
public Fiction(String name, String ref_num, int owned_copies, String author) {
}
}
at the moment when i input values into the variable arguments and call them with this :
public static class BookTest {
public static void main(String[] args) {
ArrayList<Book> library = new ArrayList<Book>();
library.add(new Fiction("The Saga of An Aga","F001",3,"A.Stove"));
library.add(new Fiction("Dangerous Cliffs","F002",4,"Eileen Dover"));
for (Book b: library) System.out.println(b);
System.out.println();
}
}
i get a return value of this:
book1.Fiction#15db9742
book1.Fiction#6d06d69c
book1.NonFiction#7852e922
book1.ReferenceBook#4e25154f
how can i convert the classes to return a string value instead of the object value? I need to do this without changing BookTest class. I know i need to use to string to convert the values. but i don't know how to catch the return value with it. could someone please point me in the right direction on how to convert this output into a string value?
You need to overwrite the toString() Method of your Book class. In this class you can generate a String however you like. Example:
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.author).append(": ").append(this.title);
return sb.toString();
}
You need to override the toString() method in your Book or Fiction class. The method is actually declared in the Object class, which all classes inherit from.
#Override
public String toString(){
return ""; // Replace this String with the variables or String literals that you want to return and print.
}
This method is called by System.out.println() and System.out.print() when they receive an object in the parameter (as opposed to a primitive, such as int and float).
To reference the variables in the method, you'll need to declare them in the class and store them via the class's constructor.
For example:
public abstract class Book {
private String name;
private String reference;
private int ownedCopies;
private int loanedCopies;
public Book (String name, String reference, int ownedCopies, int loanedCopies) {
this.name = name;
this.reference = reference;
this.ownedCopies = ownedCopies;
this.loanedCopies = loanedCopies;
}
#Override
public String toString(){
return name + ", Ref:" + reference + ", OwnedCopies: " + ownedCopies + ", LoanedCopies: " + loanedCopies; // Replace this String with the variables or String literals that you want to return and print.
}
}
The classes you have defined, don't store any values. It is in other words useful to construct a new book. You need to provide fields:
public abstract class Book {
private String name;
private String ref_num;
private int owned_copies;
private int loaned_copies;
public String Book (String name, String ref_num, int owned_copies, int loaned_copies) {
this.name = name;
this.ref_num = ref_num;
this.owned_copies = owned_copies;
this.loaned_copies = loaned_copies;
}
public String getName () {
return name;
}
//other getters
}
Now an object is basically a set of fields. If you want to print something, you can access and print one of these fields, for instance:
for (Book b: library) System.out.println(b.getName());
In Java, you can also provide a default way to print an object by overriding the toString method:
#Override
public String toString () {
return ref_num+" "+name;
}
in the Book class.
Need to give your object Book a ToString() override.
http://www.javapractices.com/topic/TopicAction.do?Id=55
Example:
#Override public String toString()
{
return name;
}
Where name, is a string in the Class.
I am hoping that you have assigned the passed arguments to certain attributes of the classes. Now, once you are done with that, you can override the toString() method in Book to return your customized string for printing.

How to override Parent class using new object?

I am trying to generate custom XML message via class ParentMessage, I don't
know how to override the fields and the methods.
For this issue there is 3 class.
1 - ParentMessage (source code core), I don't have access to code.
2 - ChildMessage(My class core), I need to override ParentMessage class by creating new object of ParentMessage.
3 – Main(client class), use fields and methods of ChildMessage.
Thanks for any help.
abstract class ParentMessage extends Packet {
// this is source code, current fields library , I can't Change the method or have access to these fields.
public String element = "message";
public String type = "email";
public String body = "";
public String phone = "";
public String from = "";
public String to = "";
pubilc void sendMessage(String element, String type, String body){
// this current method library , I can't Change the method
//build xml format
//send message
//example of format XML message
//<message to='rotem#example.com/LIB'>
// <from>bob#example.com/LIB</from>
// <type>email</type>
// <body>some text body</body>
//</message>
}
}
//
abstract class ChildMessage {
// this my class I want to override the ParentMessage Fields and methods
// and make here the change code.
//example of custom XML message
public String element = "rootmessage"; //override the field
public String element2 = "element2"; //I add new field
public String element3 = "element3"; //I add new field
public String type = "web"; //override the field
public String body2 = "body2"; //I add new field
public String body3 = "body3"; //I add new field
public ParentMessage parentMessage = new ParentMessage();
pubilc void sendMessage(String type, String body, String body2, String body3){
//<rootmessage to='rotem#example.com/LIB'>
// <from>bob#example.com/LIB</from>
// <type>web</type>
// <body>some text body</body>
// <element2>
// <body2>some text body2</body2>
// </element2>
// <element3>
// <body3>some text body3</body3>
// </element3>
//</rootmessage>
//send message
}
}
//
public class Main {
// client class
public String from = "bob#example.com/LIB";
public String to = "rotem#example.com/LIB";
public String type = "android";
public String body = "some text body";
public String body2 = "some text body2";
public String body3 = "some text body3";
public static void main( String ... args ) {
public ChildMessage childMessage = new ChildMessage();
childMessage.sendMessage (type, body, body2, body3){};
}
}
First of all, in order to override methods of a class, your class must extend that class :
abstract class ChildMessage extends ParentMessage
Second of all, fields cannot be overridden. Only methods can.
a very simple example for you:
public abstract class Test1 {
public String element = "message0";
public String element1 = "message1";
}
public class Test2 extends Test1{
public String element = "message2";
public void printMe() {
System.out.println(element);
System.out.println(element1);
}
}
You will see it will print:
message2
message1
Do let me know if it is still not clear
To override a method, you need to have the exact same signature.
This:
public void sendMessage(String type, String body, String body2, String body3);
Does not override this:
public void sendMessage(String element, String type, String body);
because the former accepts 4 parameters and the latter only accepts 3. If you want to override the method, you have to remove the last parameter so that both accept 3 strings.
(However, since you're adding new arguments to the function, chances are you aren't really overriding it and are rather changing the behaviour altogether. Unfortunately I cannot really help you there because I do not know exactly what you are doing)

Categories

Resources