Showing posts with label COBOL. Show all posts
Showing posts with label COBOL. Show all posts

Friday, 16 January 2015

A Simple Example with a Class and 1 Object

As I am a retired COBOL programmer, I don’t know anything about Object Oriented programming so please forgive me if this example seems a bit elementary. Classes are templates for real-life objects. In the example below, a Rectangle class is created. Each object in this class (i.e. each rectangle) has a width and a height. These are called instance variables. An object called my_rectangle is created in the Rectangle class and its width and height are supplied. Finally, a variable called area is created, calculated and displayed:
 
Java > cat Rectangle.java
class Rectangle
  {
  double width;
  double height;
  }
class RectangleExample
  {
  public static void main(String args[])
    {
    Rectangle my_rectangle = new Rectangle();
    double area;
    my_rectangle.width = 3;
    my_rectangle.height = 4;
    area = my_rectangle.width * my_rectangle.height;
    System.out.println("Area = " + area);
    }
  }
Java > javac Rectangle.java
Java > java RectangleExample
Area = 12.0
Java >

Saturday, 11 May 2013

Java Modulus Operator

Many programming languages have a modulus operator, which allows you to calculate the remainder left over after a division. If I remember correctly, COBOL actually used the word REMAINDER to allow you to do this. In Java, you use the percent symbol as shown below:

UBUNTU > cat prog26.java
public class prog26
{
public static void main (String args[])
  {
  System.out.println
  ("17/5 = " + (int) 17/5 + " remainder " + 17%3);
  System.out.println
  ("15/2 = " + (int) 15/2 + " remainder " + 15%2);
  }
}
UBUNTU > javac prog26.java
UBUNTU > java prog26
17/5 = 3 remainder 2
15/2 = 7 remainder 1
UBUNTU > 

If you have a Java book on Amazon, which you would like to advertise here for free, please write to me at international_dba@yahoo.co.uk.