This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
I have a class , it passes objects,primitive . can anyone please explain this
public class TestObj {
String name;
int age;
public TestObj(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public String toString() {
return "TestObj{" + "name=" + name + ", age=" + age + '}';
}
}
main class
public class Test {
public static void main(String[] args) {
Test t = new Test();
TestObj obj = new TestObj("James", 25);
System.out.println("************* Output ****************");
System.out.println(obj);
t.setName(obj);
t.setAge(obj);
System.out.println(obj);
String a = "Hai Test";
System.out.println(">> :: " + a);
t.setString(a);
System.out.println(":: " + a);
int x = 10;
System.out.println("------- " + x);
t.setInt(x);
System.out.println("------- " + x);
}
public void setInt(int y) {
y = 25;
}
public void setString(String x) {
x = "Did i changed my Data";
}
public void setName(TestObj obj1) {
obj1.setName("I got Changed");
}
public void setAge(TestObj obj1) {
obj1.setAge(35);
}
}
************* Output ****************
TestObj{name=James, age=25}
TestObj{name=I got Changed, age=35}
:: Hai Test
:: Hai Test
------- 10
------- 10
java is 'pass-by-value'. always. but when a parameter is an object, the value is a reference (an address of an object), not the object itself
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
i want to print all elements of my array list. Eclipse does not show an error, but it doesnt show the elements that i added in console. Can you please tell me what i did wrong?
The console shows:
Typ:Droide
ID:8282
NameR2D2
HumanoiderRoboter#15db9742
HumanoiderRoboter#6d06d69c
HumanoiderRoboter#7852e922
HumanoiderRoboter#4e25154f
Roboter Class:
public class Roboter {
protected String Name;
protected int ID;
protected String typ;
public Roboter(String Name, int ID, String typ) {
super();
this.Name = Name;
this.ID = ID;
this.typ = typ;
}
public void ausgebenNeu() {
System.out.println("ID:"+ID);
System.out.println("Name:"+Name);
System.out.println("Typ:"+typ);
}
HumanoiderRoboter Class:
import java.util.ArrayList;
public class HumanoiderRoboter extends Roboter {
String RoboterTyp;
public HumanoiderRoboter (String Name, int ID, String typ) {
super(Name, ID, typ);
}
public void ausgeben() {
ArrayList<HumanoiderRoboter> Sensoren = new ArrayList<HumanoiderRoboter>();
Sensoren.add(new HumanoiderRoboter("Sensor1", 4232, "Infrarotsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor2", 9232, "Lichtsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor3", 5777, "Touchssensor"));
Sensoren.add(new HumanoiderRoboter("Sensor4", 3321, "Gyrosensor"));
System.out.println("Typ:" + typ);
System.out.println("ID:" + ID);
System.out.println("Name" + Name);
for (Roboter ele : Sensoren) {
System.out.println(ele);
}
}
public static void main(String[] args) {
HumanoiderRoboter R2 = new HumanoiderRoboter("R2D2", 8282, "Droide");
R2.ausgeben();
}
}
Currently your problem is the HumanoiderRoboter doesn't overwrite the toString method which results the HumanoiderRoboter#4e25154f stuff. So if you overwrite the toString method it will print your object stuff you put in there:
...
#Override
public String toString() {
return "Typ: " + type + ", ID: " + id + ", Name: " + name;
}
...
Default toString method from Object looks like that:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So now if you do System.out.println(theObject) it will for example result something like this:
Typ: some, ID: 5, Name: NiceRoboter
And if you want the complete array as one String you can use the Arrays#toString method:
System.out.println(Arrays.toString(yourList.toArray()));
In your Roboter class override toString() method like this:
public class Roboter {
//-----member fields,methods
//Add this method
#Override
public String toString(){
return "{name:"+this.Name+"}";
}
}
Also read this link for naming convention to follow in Java https://www.geeksforgeeks.org/java-naming-conventions/
Override toString() method in Roboter class.
public class Test extends Roboter {
String RoboterTyp;
public Test(String Name, int ID, String typ) {
super(Name, ID, typ);
}
public void ausgeben() {
ArrayList<Test> Sensoren = new ArrayList<Test>();
Sensoren.add(new Test("Sensor1", 4232, "Infrarotsensor"));
Sensoren.add(new Test("Sensor2", 9232, "Lichtsensor"));
Sensoren.add(new Test("Sensor3", 5777, "Touchssensor"));
Sensoren.add(new Test("Sensor4", 3321, "Gyrosensor"));
System.out.println("Typ:" + typ);
System.out.println("ID:" + ID);
System.out.println("Name" + Name);
for (Roboter ele : Sensoren) {
System.out.println(ele);
}
}
public static void main(String[] args) {
Test R2 = new Test("R2D2", 8282, "Droide");
R2.ausgeben();
}
}
public class Roboter {
String Name;
int ID;
String typ;
public Roboter(String name, int iD, String typ) {
super();
Name = name;
ID = iD;
this.typ = typ;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getTyp() {
return typ;
}
public void setTyp(String typ) {
this.typ = typ;
}
#Override
public String toString() {
return "Roboter [Name=" + Name + ", ID=" + ID + ", typ=" + typ + "]";
}
}
Hi guys i am fairly new to Java but ive come across a problem that i cant seem to fix, the problem is in the 'WashingMachine' Class its not displaying the 'spinSpeed' details , any answers will be appreciated
here are my codes:
enter code here
package test;
public class Client {
private String Name;
private String PhoneNo;
Client () {
Name = null;
PhoneNo= null;
}
Client (String N, String P){
Name = N;
PhoneNo = P;
}
public void setName(String N){
Name = N;
}
public void setPhoneNo(String P) {
PhoneNo = P;
}
public String getName(){
return Name;
}
public String setPhoneNo() {
return PhoneNo;
}
public String toString() {
return "\nName: "+ Name + "\nPhoneNo:"+ PhoneNo.toString();
}
}
enter code here
package test;
public class Machine {
private String Make;
private double Price;
private Client Cust;
public Machine(String make, double price, Client cust)
{
Make = make;
Price = price;
Cust = cust;
}
#Override
public String toString() {
return "\n" +"Make of machine: " + Make + "\n" + "Price: " + Price + "\n" + Cust.toString();
}
public String getMake() {
return Make;
}
public double getprice() {
return Price;
}
public Client getcust() {
return Cust;
}
}
enter code here
package test;
public class WashingMachine extends Machine {
private int spinSpeed;
public WashingMachine (String make, double price, Client cust, int spinSpeed){
super(make, price, cust);
}
#Override
public String toString() {
return "WashingMachine [spinSpeed=" + spinSpeed + ", spinSpeed()=" + spinSpeed() + "]";
}
public int spinSpeed() {
return spinSpeed;
}
enter code here
package test;
import java.util.ArrayList;
public class MachinePurchaseTestVerC {
public static void main(String [] args) {
ArrayList<Machine> gadgets = new ArrayList<Machine> ();
Client mCust2 = new Client("Paul", "0487654321");
Client mCust3 = new Client("Chandra", "0487651234");
Client wCust1 = new Client("Catherine", "0412345678");
Client wCust4 = new Client("Mike", "0412348756");
gadgets.add(new WashingMachine("Bosch", 549.50, wCust1, 3500));
gadgets.add(new Machine("Samsung", 678.50, mCust2));
gadgets.add(new Machine("Electrolux", 449.25, mCust3));
gadgets.add(new WashingMachine("LG", 500.00, wCust4, 3200));
for(int i = 0; i<gadgets.size(); i++){
System.out.println(gadgets.get(i).toString());
System.out.println("----------------------------------");
}
}
}
In your WashingMachine class, you forgot to set the speed in your constructor
public WashingMachine (String make, double price, Client cust, int spinSpeed){
super(make, price, cust);
this.spinSpeed = spinSpeed;
}
hope that helps :)
this is a class called Doglist to add the object to an array.
public class DogList {
private int numItems;
private DogItem[] dogListArray;
private int position;
DogList () {
numItems=0;
position = 0;
dogListArray = new DogItem[10];
}
public void add (DogItem item) {
dogListArray[numItems++]= new DogItem(item.getName(),
item.getBreed(),
item.getWeight(),
item.getOwner1(),
item.getOwner2()
);
}
public String toString() {
String result = "";
for (int i=0; i<numItems; i++) {
result += dogListArray[i].toString() + "\n";
}
return result;
}
public DogItem searchForDogItem (DogItem gi) {
System.out.println("Here is your obj value: " + gi );
return null;
}//This is the one im having trouble with.
}
I have all the setters and getters in the DogItem class.
and this is from the UI where i get the dog info(name, breed, weight, owners1&2 names)
public void searchForItem (String name ) {
DogItem gi = new DogItem (name);
gi = gl.searchForDogItem(gi);
if (gi==null) {
msgTextField.setText("Dog Not Found");
} else {
nameTextField.setText(String.valueOf(gi.getName()));
breedTextField.setText(String.valueOf(gi.getBreed()));
weightTextField.setText(String.valueOf(gi.getWeight()));
owner1TextField.setText(String.valueOf(gi.getOwner1()));
owner2TextField.setText(String.valueOf(gi.getOwner2()));
}
}
Ill try and clear things up as i go.
this is the output i get
Here is your obj value: null null 0.0 null null
Ok so here is what it probably should look like instead. Just from what I saw wrong already. However you'd probably want to override the toString() method of DogItem.
Main method example of this:
public class Main {
public static void main(String[] args) {
DogItem dogItem = new DogItem("Spot", "Dalmation", "45", "Bob", "Sandy");
DogItem.add(dogItem);
DogItem result = DogItem.searchForItem("Spot");
if (result == null) {
System.out.println("Dog not found");
// GUI error output goes here
} else {
System.out.println("Here is your obj value: " + result);
// Where your GUI stuff goes
}
}
}
DogItem example of this:
public class DogItem {
private static DogItem[] dogListArray = new DogItem[100];
private static int numItems = 0;
private String name;
private String breed;
private String weight;
private String owner1;
private String owner2;
public DogItem(String name, String breed, String weight, String owner1, String owner2) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owner1 = owner1;
this.owner2 = owner2;
}
public static void add(DogItem dogItem) {
dogListArray[numItems++] = dogItem;
}
public static DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogListArray) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
#Override
public String toString() {
String result = name + ", " + breed + ", " + weight + ", " + owner1 + " " + owner2;
return result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getOwner1() {
return owner1;
}
public void setOwner1(String owner1) {
this.owner1 = owner1;
}
public String getOwner2() {
return owner2;
}
public void setOwner2(String owner2) {
this.owner2 = owner2;
}
}
These would be recommended changes from me though:
private static ArrayList<String> owners;
private static ArrayList<DogItem> dogsList;
public DogItem(String name, String breed, String weight, String owner) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owners.add(owner);
}
public void init() {
owners = new ArrayList<String>();
dogsList = new ArrayList<DogItem>();
}
public void addDog(DogItem dogItem) {
dogsList.add(dogItem);
}
public DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogsList) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
public void addOwner(String owner) {
owners.add(owner);
}
public String getOwner() {
return owners.get(owners.size() - 1);
}
I am trying to make a program in java oop in which I create some persons in the main (every person has a name, an age, a status: employed or not).
I want to search these persons by name and display all the details.
For example if a have a person named John and I find it by name, I want to list all the details (status, age and so on).
I tried to implement this method in Person class.
I don t know if is better to create a map which contains all the persons and the name and then to search in it.
Below is my code:
Person CLASS:
package app;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Person extends Employed {
Scanner scan = new Scanner(System.in);
private String name;
private int age;
private int kids;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getKids() {
return kids;
}
public void setKids(int kids) {
this.kids = kids;
}
public Person(){
System.out.println("************************************************************");
}
public void displayPerson(){
if(super.getPeriod()==0 && super.getUnemploymentBenefit()==0){
System.out.println(name + " is " + age + " years old, has " + kids + " kids and is employed" + "\nWorking Place: " + super.getWorkingPlace()
+ "\nSallary: " + df.format(super.getSallary()) + " EUR per year" + "\nWorking Time: " + super.getHours() + " hours per day");
}else
System.out.println(name + " is " + age + " years old, has " + kids + " kids and is unemployed" +"\nUnemployment Time: " + Math.round(super.getPeriod())
+ "\nUnemployment Benefit: " + df.format(super.getUnemploymentBenefit()) + " EUR per year");
}
public void searchMethod(){
System.out.println("Are you looking for someone?");
String s = scan.nextLine();
if(s==name) {
System.out.println("Here are all the details about the person you are looking for: ");
}
}
}
Employed CLASS:
package app;
import java.text.DecimalFormat;
public class Employed extends Unemployed {
DecimalFormat df = new DecimalFormat("0.000");
private String WorkingPlace;
private double sallary;
private double hours;
public String getWorkingPlace() {
return WorkingPlace;
}
public void setWorkingPlace(String WorkingPlace) {
this.WorkingPlace = WorkingPlace;
}
public double getSallary() {
return sallary;
}
public void setSallary(double sallary) {
this.sallary = sallary;
}
public double getHours() {
return hours;
}
public void setHours(double hours) {
this.hours = hours;
}
}
Unemployeed CLASS:
package app;
public class Unemployed{
private double period;
private double UnemploymentBenefit;
public double getPeriod() {
return period;
}
public void setPeriod(double period) {
this.period = period;
}
public double getUnemploymentBenefit() {
return UnemploymentBenefit;
}
public void setUnemploymentBenefit(double UnemploymentBenefit) {
this.UnemploymentBenefit = UnemploymentBenefit;
}
}
Program CLASS:
package app;
public class Program extends Person{
public static void main(String[] args) {
Person p1 = new Person();
p1.setName("John Doe");
p1.setAge(47);
p1.setKids(3);
p1.setWorkingPlace("IKEA");
p1.setSallary(12.500);
p1.setHours(12.5);
p1.displayPerson();
p1.searchMethod();
Person p2 = new Person();
p2.setName("Snow Tiffany");
p2.setAge(27);
p2.setKids(0);
p2.setPeriod(15.9);
p2.setUnemploymentBenefit(7.000);
p2.displayPerson();
}
}
First you should add a construtor.
Then you can create an object from class Person like this:
Person p1 = new Person("John Doe", 47,3, "IKEA", 12.500, 12.5);
String personInfo = p1.get(..) + p1.get(..);
System.out.println(personInfo);
Your code is a bit desorganized. Java classes should have constructors. Variables, in general, starts with lowerCase character.
/* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication3;
class Employee {
private String name;
private String address;
private int number;
public Employee(Employee emp) {
System.out.println("Constructing an Employee");
this.name = emp.name;
this.address = emp.address;
this.number = emp.number;
}
/*public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}*/
public void mailCheck() {
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
class Salary extends Employee {
private double salary; //Annual salary
public Salary(Salary obj) {
super(obj);
setSalary(obj.salary);
}
/*public Salary(String name, String address, int number, double Salary) {
super(name, address, number);
setSalary(Salary);
}*/
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if (newSalary >= 0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary / 52;
}
}
public class JavaApplication3 {
public static void main(String[] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta,UP", 3, 2000.00); // error why
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
}
}
If we removed the comments from the constructor, then it will be okay. Why?
Salary s = new Salary("Mohd Mohtashim", "Ambehta,UP", 3, 2000.00); you're calling a constructor that takes multiple parameters but it doesn't exist since you've commented it out .