Java Series Part 7: Creating Multiplication Table using Classes, Object and Methods

Create a class called Multiplication table as below:

Ch7MultiplicationTable.java

package com.java.basic;

public class Ch7MultiplicationTable {
	
		void print() {
			for(int i=1; i<=10;i++) {
				System.out.printf("%d * %d = %d", 5, i, 5*i).println();
			}
			
		}		
		
		// making it generic to accept parameters that is print table of any number
		void print(int n) {
			for(int i=1; i<=10;i++) {
				System.out.printf("%d * %d = %d", n, i, n*i).println();
			}
			
		}		
		
		//adding more parameters
		void print(int n, int from, int to) {
			for(int i=from; i<=to;i++) {
				System.out.printf("%d * %d = %d", n, i, n*i).println();
			}
			
		}
}

Create a main class to create an instance of the class and call the print() method

Ch7aMultiplicationTable.java

package com.java.basic;

public class Ch7aMultiplicationTable {

	public static void main(String[] args) {

		// Create instance of Multiplication Table class
		Ch7MultiplicationTable table = new Ch7MultiplicationTable();
		table.print();
		table.print(4);
		table.print(9, 11, 20);
	}

}

OUTPUT

output

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s