Intiize the Custom object with empty string in java - java

I have adresss object with n filed .. while using it i want to intize 1 or 2 filed rest filed i want as - ""
instead of null.
one way is manually adresss.setABC(" ") but do we have way to do it implictily ?

Use the Builder design pattern to create the Objects. Set only the mandatory attributes while creating the Objects. Rest all other fields will be null when not set. Please check https://howtodoinjava.com/design-patterns/creational/builder-pattern-in-java/ on Builder design pattern.

Class variables (or member variables) of each data type has default values. For example,
int number; // number will have default value: 0
float ratio; // default value: 0.0
boolean success; // default value: false
String name; // default: null
Object obj; // default: null
If you want to change this to some other value, you can change the member variable declaration or change the value in your class' constructor.
String name = "";
Declaring the above statement as class variable will ensure that the value is empty instead of null. Another way is to set it in class constructor,
public Address(){
this.name = "";
}

Related

How to store int and string value in bean class?

I know this is very basic question yet I am unable to get the perfect answer. I have one bean named Order in which there is one object product_size such as
public Class Order{
private String product_size;
}
Setter and Getter methods are defined respectively in that class. The problem is that product_size may contain string variable such as S or Integer value such as 7.
I am unable to store the Integer value in that bean object.
I have done with only one bean instance and I am check that if value is string it should be added in bean object Simply else Integer.toString() method will convert the int value to String.
Example is given below-
String str; // it is dynamic let there are two values in this 'S' and 8
if (str instancof String){
order.setProduct_Size(str);
}else{
order.setProduct_Size(Integer.toString(str));
}

How to access dynamiclly variables from another Java Class?

My question similar to others but it's little bit more tricky for me
I have a Class DummyData having static defined variables
public static String Survey_1="";
public static String Survey_2="";
public static String Survey_3="";
So, i call them DummyData.Survey_1 and it returns whole string value. Similarly do with DummyData.Survey_2 and DummyData.Survey_3
But the problem is when i call them Dynamically its not return their value.
I have a variable data which value is change dynamically like (data=Survey_1 or data=Survey_2 or data=Survey_3)
I use #Reflection to get its value but failed to get its value
I use methods which I'm mentioning Below help me to sort out this problem.
Field field = DummyData.class.getDeclaredField(data);
String JsonData = field.toString();
and
DummyData.class.getDeclaredField("Survey_1").toString()
but this return package name, class name and string name but not return string value.
What I'm doing can some help me??
Getting the value of a declared field is not as simple as that.
You must first locate the field. Then, you have to get the field from an instance of a class.
Field f = Dummy.class.getDeclaredField(“field”);
Object o = f.get(instanceOfDummy);
String s = (String) o;
Doing the simple toString() of the Field will actually invoke the toString() method of the Field object but won't access the value
You must do something like this:
Field field = SomeClass.class.getDeclaredField("someFieldName");
String someString = (String) field.get(null); // Since the field is static you don't need any instance
Also, beware that using reflection is an expensive and dangerous operation. You should consider redesigning your system

Creating several objects of the same class

I need to create 10 objects from my Variable Class but I'm getting errors.
Here is my code:
for(n=1;n<10;n++){
variableTab[n]= "variable" +""+n;
Variable variableTab[n] = new Variable();
//System.out.println(variableTab[n]);
}
And the errors I have:
Type mismatch: cannot convert from Variable to Variable[]
Syntax error on token "n", delete this token
Duplicate local variable variableTab
I don't know where is the problem because variableTab[] is a String Tab.
You are trying to assign data to an object that hasn't been created yet. Also, you shouldn't start at index 1. Arrays begin at index 0, so essentially, you are robbing yourself of extra space and making things harder on yourself by doing that. This also means that you are creating 9 objects, not 10. Use the implementation below.
Variable [] variableTab = new Variable [10];
for(n=0;n<10;n++){
variableTab[n]= "variable" +""+n;
//System.out.println(variableTab[n]);
}
Update per comments:
If you are trying to store the name of a object, you need to create a member variable to store that name in.
public class Variable {
private String name; //This will be used to store the unique name of the object
//Default constructor for our class
Variable () {
name = "";
}
//Constructor to initialize object with specific name
Variable (String name) {
this.name = name;
}
//We need a way to control when and how the name of an object is changed
public setName (String name) {
this.name = name;
}
//Since our "name" is only modifiable from inside the class,
//we need a way to access it from the program
public String getName () {
return name;
}
}
This would be the proper way to setup a class. You can then control the data for each class in a more predictable way, since it is only able to be changed by calling the setName method, and we control how the data is retrieved from other sections of the program by creating the getName method.
You might want to initialize your object first. If it is an array of objects that you're trying to create, do it this way:
Variable[] variableTab = new Variable[n];
You're trying to assign values to something that hasn't been created yet!
You're code should look like:
for(n=0;n<10;n++){
Variable variableTab[n] = new Variable();
variableTab[n]= "variable" +""+n;
//System.out.println(variableTab[n]);
}
Basically, you're trying to assign a value to something that doesn't exist yet.

How do I handle null value returned by a query for fields with no value in them and datatype as integer

I have a table to which I had to add to fields of datatype integer, recently.
I use hibernate and my database in PostgreSQL.
My query to get the object corresponding to the table now returns null for the fields that were recently added. I am trying to check if they are null and to set 0 if the value is null.
I am unable to find a way to do this....can anybody help....
The hibernate query returns a pojo corresponding to my table and I want to check if one of the attributes in that pojo is null, but that attribute is an integer, and that is my trouble.
If you want it 0 if null then you just can give this value in the declaration,
Integer a=0;
If you use annotation then use can try default value. like
#Column(name="col_name", columnDefinition=" default '0' ")
Another way can be the setter method, If the field is private and you have public setter method then check null in that setter
public void setA(Integer a)
{
if(a==null)
{
this.a=0;
}else this.a=a
}
I suggest using int in your POJO instead of Integer. This way null doesn't get into the database. If you have to use Integer, make sure you give it an initial value of 0, and if you have any setters, ensure you check that the incoming argument is not null.
So either do:
public class MyPOJO {
private int intVal = 0;
...
}
or:
public class MyPOJO {
private Integer intVal = 0;
...
public void setIntVal(Integer intVal) {
if(intVal != null) {
this.intVal = intVal;
}
}
...
}
I tried all the answers like setting nullable=true and columnDefinition=" default '0' " but nothing seemed to work. So I altered the default value of the column as 0, this resolved the issue.
NOTE: Please be careful about possible loss of information while modifying the default value.

Convert Field Type to the corresponding instance type

I have a class, in which I have a field called say batman
String batman
And I have method in this class, which does the following:
for(Field field : obj.getClass().getFields()) {
if(field.getName().equals(fieldName)) // here fieldName is batman
//now need to call Strings method like split etc
}
I need to convert the field to String and call methods. Is it possible to do so?
Thanks in advance.
First of all u can use Field batmanField = obj.getClass().getDeclaredField(fieldName); instead foreach. For get field value u can use String batmanValue = batmanField.get(obj);
You can use the Field#get(Object obj) method to get the value of the field represented by the Field you are working with, on the specified object obj.
if (field.getName().equals(fieldName)) {
String batmanValue = (String) field.get(obj);
..
}
This will give you the value of the batman field. Then you can use the String specific methods.

Categories