Passing an object to a method example

With this example we are going to demonstrate how to pass an object to a method. In short, we have created a class and a method to pass the object of the class:

  • We have created a class, Character with a char field.
  • We have created another class, PassObject, that has a static method, void setCh(Character y). The method gets a Character object and changes its char field to 'z'.
  • We create a new instance of Character class and set its char field to 'a'.
  • Then we use the setCh(Character y) method of PassObject class to change again the field of Character object.
  • In both ways the field of Character object is changed.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;

class Character {
    char ch;

public class PassObject {

    static void setCh(Character y) { = 'z';

    public static void main(String[] args) {

  Character x = new Character(); = 'a';

  System.out.println("1: " +;


  System.out.println("2: " +;


1: a
2: z

This was an example of how to pass an object to a method in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button