Skip to main content
OCA Java Programmer 1Z0-803

Java read or write to object fields

By November 10, 2013September 12th, 2022No Comments

In previous videos we have seen that we can you fields within our class as variables. This variables become object or reference variables when inside instances of the class. We can populate these fields directly if they have the correct access modifier such as public.  Often though we add more control setting the modifier to private and controller reading and writing to fields via methods known as getters and setters or accessors and modifiers. For this tutorial we concentrate on direct read and write access to the fields.

Direct Access

In is simplest form we can read and write to the fields without much effort or coding

package oca;
public class Rw {
  static String name;
  public static void main(String[] args) {
    name = "test";
    System.out.println(name);
  }
}

Here we can see that we declare the name variable outside of the main method. In the main method we set the value to test , writing to the field. We then print the field value with println, reading the variable. As the field names is accesses from a static method, in this case main, then the field must also have the modifier static.

We can also declare fields with a method. Fields declared within any method are local to that method or code block and not accessible outside of that block

public static void main(String[] args) {
 String result;
 int l;
 int w;
}

Here the three variables are defined in the main method. We can set up a simple calculation in the method to determine the area by combining the length and width. Initially we will hard card the values and then look out how we can pass values to the fields at run time.

public static void main(String[] args) {
 String result;
 int l = 2;
 int w = 5;
 result = String.valueof(l * w);
 System.out.println("Area = " + result);
}

We have written to the result field by reading values from the l and w fields. Additionally we have converted or cast the the calculated result from an integer to a string with the method valueof from the String object. String is part of the package java.lang and is implicitly imported.

If we would like something a little more dynamic we can import objects from the package java.io.This way our source class file would sasrt something similar to this:

package readwrite;
import java.io.*;
public class ReadWrite {

We can now read and write to other entities other than fields. We could use files or standard input. For our example we will read in the values of the l and w from standard input using a BufferedReader object. The final code is shown below.

package readwrite;
import java.io.*;
public class ReadWrite {

    public static void main(String[] args) {
        String result;
        int l = 0;
        int w = 0;
        String sl = "";
        String sw = "";
        BufferedReader br;
        br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the length");
        try {
            sl = br.readLine();
        } catch (IOException e) {
            System.out.println("Error in input");
            System.exit(2);
        }
        System.out.println("Enter the width");
        try {
            sw = br.readLine();
        } catch (IOException e) {
            System.out.println("Error in input");
            System.exit(2);
        }
        try {
            l = Integer.parseInt(sl);
            w = Integer.parseInt(sw);

        } catch (NumberFormatException e) {
            System.out.println("Unable to convert");
            System.exit(2);
        }

        result = String.valueOf(l * w);
        System.out.println("result is: " + result);     
    }   
}

Having created the BufferedReader object, br ,we can use the method readline() to capture input the user supplies. This way our program beomes more dynamic. This though could introduce issues if the input is not readable to we add try and catch blocks to manage errors or exceptions . In the same way we implement try and catch when converting out data as the user may not have typed integer values. Any value types to standard input will be read as a String and we will need to covert it to integers to be able to run the mathematical operations.

The video steps you through the process and I hope it is useful.