I want to print "None" value for undeclared objects instead of null. Is it possible?
public class class1 {
class2 c2;
public static void main(String[] args) {
class1 c1=new class1();
System.out.println(c1.c2);
}
}
class class2{
public String toString(){
if(this==null){
return "None";
}else{
return "Correct";
}
}
}
Edit: I have added the code. This code prints:
null
But I want to print "None". What should I do?
The utility class Objects offers a lot of useful methods. There's for example Objects#toString(Object) and Objects#toString(Object, String).
final String s = Objects.toString(obj, "None");
After your edit: the this reference is never null, therefore this == null will always be false. You need to handle the null-check outside of your class. Normally, String.valueOf will be called when converting an object to a string. This method handles null references, not the class itself. You'd have to manually convert your object to a string first (with the utility described above).
You'd need to change your code:
public class Class1 {
Class2 c2;
public static void main(String[] args) {
Class1 c1 = new Class1();
System.out.println(Objects.toString(c1.c2, "None"));
}
}
class Class2 {
#Override
public String toString(){
return "Correct";
}
}
You can always create a wrapper around Objects#toString(Object,String) to avoid specifying the default value over and over again:
public final class MyObjects {
private MyObjects(){}
public static String toString(final Object obj) {
return Objects.toString(obj, "None");
}
}
Related
Say I have 3 different classes (Class1, Class2, Class3), and each class has a method called ".update(String x)".
Now I want to read a line in a .csv file, I separate the values by comma and get a list with each string value indexed , for example "Foo, bar, barz" becomes {"foo", "bar", "barz").
Is it possible in Java to make a list of objects (Obj1, Obj2, Obj3), one for each class and for each value on my list of strings, call the .update of each object with the according index of my list of strings as the parameter?
for example:
package Test;
import java.util.ArrayList;
import java.util.List;
class Class1{
private String string;
public void update(String s){
this.string = s;
}
public String str(){
return this.string;
}
}
class Class2{
private String string;
public void update(String s){
this.string = s;
}
public String str(){
return this.string;
}
}
class Class3{
private String string;
public void update(String s){
this.string = s;
}
public String str(){
return this.string;
}
}
public class Testing {
public static void main(String[] args) {
List<Object> object = new ArrayList<Object>();
Class1 class1 = new Class1();
Class2 class2 = new Class2();
Class3 class3 = new Class3();
object.add(class1);
object.add(class2);
object.add(class3);
String string_list[] = {"foo" , "bar", "barz"};
for(int i = 0 ; i < object.size(); i++) {
object.get(i).update(string_list[i]);
}
}
}
hence obj1.update("foo"), obj2.update("bar"), obj3.update("barz")
I keep getting a "cannot resolve method" error in the loop.
Error:(68, 26) java: cannot find symbol
symbol: method update(java.lang.String)
location: class java.lang.Object)
But when I change the object reference in the loop to an object and not a reference it works fine. Logically it seems correct, but it seems like an ArrayList list isn't the right data structure to hold objects? or maybe it is and I'm doing it wrong, anyone have any suggestions why it's not working and how I can fix it?
Thanks.
you can do that, but for that you need your list of objects to be of a type that declares the update() method. If you want the objects to be of different classes, you need to have some interface or abstract class that all three implement/extend, and that interface/abstract class should declare update method.
should be something like this:
public interface MyInterface {
public void update(String str);
}
public class Object1 implements MyInterface {
#Override
public void update(String str) {
...
}
}
/// same for object 2 and 3
String[] string_list = {"foo", "bar", "barz"}
MyInterface[] obj_list = {Obj1, Obj2, Obj3}
...
...
I want the pass-in variable "aaa" to be returned the value from the argument of the function. I really need my argument in the function to be defined as String, and want whatever change of the argument in the function to be return to the pass-in variable.
How do I make this happen in Java? If anyone could help I will appreciate!
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
aaa = "123";
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc(demo.aaa);
System.out.println(demo.aaa);
}
}
You cannot do it like this: String class in Java is immutable, and all parameters, including object references, are passed by value.
You can achieve the desired result in one of three ways:
Return a new String from a method and re-assign it in the caller,
Pass mutable StringBuilder instead of a String, and modify its content in place, or
Pass an instance of DeppDemo, and add a setter for aaa.
Here are some examples:
public class DeppDemo {
private String aaa;
private StringBuilder bbb = new StringBuilder();
public String abc() {
return "123";
}
public void def(StringBuilder x) {
x.setLength(0);
x.append("123");
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.aaa = demo.abc(); // Assign
demo.def(demo.bbb); // Mutate
System.out.println(demo.aaa);
}
}
It's really unclear what you're asking, but it sounds like you're trying to change the content of a variable passed into a function. If so, you can't in Java. Java doesn't do pass-by-reference.
Instead, you pass in an object or array, and modify the state of that object or array.
public class DeppDemo {
public void abc(String[] aaa) {
aaa[0] = "123";
}
public static void main(String[] args) {
String[] target = new String[1];
DeppDemo demo = new DeppDemo();
demo.abc(target);
System.out.println(target[0]);
}
}
But if you're asking how to update the aaa field using the aaa argument, then you need to qualify your reference to the field using this., since you've used the same name for both. Or change the name of the argument.
public class DeppDemo {
private String aaa;
public void abc(String aaa) {
this.aaa = aaa;
}
public static void main(String[] args) {
DeppDemo demo = new DeppDemo();
demo.abc("New value");
System.out.println(demo.aaa);
}
}
Consider the field bar of the local-inner class MyValue:
public class C {
public static void main(String x[]) {
class MyValue implements IValue {
String bar = "bar";
public String getValue() {
return "my value";
}
}
MyValue myValue = new MyValue();
D d = new D();
d.accessBar(myValue);
}
}
which implements the IValue interface:
interface IValue {
public String getValue();
}
How can I access the field bar from another function (outside of main), let's say in class D:
class D {
public void accessBar(IValue value) {
String info = value.getValue() + value.bar;
}
}
If you need to access the pass key of a ship and you only have the IShip interface, then IShip should have a getPassKey() method, basically. Even if you could cast to ShipAddress within the method, you shouldn't do so - you should make the parameter type for the calculatedInfo method suitable for all the operations the method requires.
You could access it via reflection, but that would be horribly brittle and I'd strongly recommend that you don't do that.
If we create a String like below and print the value:
String s=new String("demo");
System.out.println(s);
...the output is:
demo
Good. This is the expected output. But here String is a class. Remember that. Below is another example. For example, take a class like this:
class A
{
public static void main (String args[])
{
A a =new A();
A a1=new A("hi"); //we should create a Constructor like A(String name)
System.out.println(a1); //here O/P is address
}
}
My doubt is that I created the A instance in the same way I created the new String object, and I printed that object. So why does it not print the given String for the instance of A?
You need to override the Object#toString() in your class. By default, the toString() method of Object is called.
Also, to print the value, you just need to override the method as internally a call will be made to the toString() method when this statement is executed.
System.out.println(a1);
Sample overriden toString() method.
#Override
public String toString() {
// return a string value
return "The String representation of your class, as per your needs";
}
You have to override toString() method in your class the way you want to print something when call System.out.println();. In String class toString() method has override and you will get out put above due to that.
As pointed out already, you need to override the default toString() method inherited from the Object class. Every class automatically extends the Object class, which has a rather simple toString(), which can't know how to turn your particular object into a String. Why should it, especially if your class is arbitrarily complex? How is it supposed to know how to turn all your class's fields into a "sensible" string representation?
In the toString() of your class, you need to return the string that you want to represent your class with. Here is a simple example:
class A {
String foo;
public A(String foo) {
this.foo = foo;
}
public String toString() {
return foo;
}
}
public class sample {
public static void main(String[] args) {
A a = new A("Hello world!");
System.out.println(a);
}
}
String is a class whose purpose is to hold a string value and will return that value if referenced. When you use other classes, you will usually want to add other behavior. If you want to use the class to hold different values that you can set (on object creation or later in processing) you may want to use "setter" and "getter" methods for such values.
Here is an example:
public class Snippet {
private static final String C_DEFAULT_VALUE = "<default value>";
private String name;
private static Snippet mySnippet;
public Snippet() {
}
public Snippet(String value) {
setName(value);
}
/**
* #param args
*/
public static void main(String[] args) {
if (args != null && args.length > 0) {
mySnippet = new Snippet(args[0]);
} else {
mySnippet = new Snippet(C_DEFAULT_VALUE);
}
System.out.println(mySnippet.getName());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In preparing for an interview, someone mentioned knowing how to make a class/method in java read-only. I've been doing a bit of searching, but haven't found anything really concrete.
Maybe this question is simpler to answer than I'm making it out to be, but what would be a way to make a class or method read-only in java?
The following code will ensure that your class is always READ ONLY, but if you find any loop hole, please post it here.
import java.io.Serializable;
final public class ImmutableClass implements Cloneable,Serializable {
private static final long serialVersionUID = 6488148163144293060L;
private static volatile ImmutableClass instance;
private ImmutableClass() {
// no-op
System.out.println("instance created : " + this.hashCode());
}
/**
* Lazy Instantiation
*
* #return
*/
public static ImmutableClass getInstance() {
if (instance == null) {
synchronized (ImmutableClass.class) {
System.out.println("aquired lock");
if (instance == null) {
instance = new ImmutableClass() {
};
}
System.out.println("released lock");
}
}
return instance;
}
public Object readResolve() {
System.out.println("readResolve()");
return getInstance();
}
#Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
The Read-only class means, we are talking about "IMMUTABLE" concept.
The following example depicts the same:
public class ImmutableString {
static String upcase(String s) {
return s.toUpperCase(); // here local variable s vanishes
// it return the value to a new String object
}
public static void main(String[] args) {
String s = new String("abc");
System.out.println(s); //abc
String s1 = upcase(s);
System.out.println(s1); //ABC
System.out.println(s); //abc
}
}
Lets Say you want a read only version of an object,
case 1: if your class contains fields which are not pointers to any other objects eg:
public class Person{
private String name;
//Getters n Setters
}
in this case, you can return a copy of this class, write a constructor that accepts Person, any one who wants to get a Person object will have a copy of this object so any Setter operations wont effect the original object(Strings are immutable)
Case 2: in case your object contains a pointer to another object or list or map
in this case make classes implement an interface which has only read-only methods(Getters) and wherever you are returning the object, change it to return this interface, so client will have access to only read-only methods
eg:
class Person implements ReadOnly{
String name;
.. assume pointers also in here
// Getter n Setters
public PersonReadOnly(){
return this;
}
}
interface PersonReadOnly {
public String getName();
}
Simple rule: Don't have any public fields and No public setter methods.
For example, see class below:
final class AReadOnlyClass
{
private int anInt;
public int GetAnInt()
{
return anInt;
}
}