0% found this document useful (0 votes)
4 views

Java Practical Workbook New

Uploaded by

omobsdaniel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Practical Workbook New

Uploaded by

omobsdaniel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

SCIENTIFIC PROGRAMMING LANGUAGE

USING OOJAVA

WORKBOOK

FOR

COMPUTER SCIENCE

DEPARTMENT OF COMPUTER SCIENCE

Name:__DANIEL OMOGBAI OSHIONE_______ ______

Mat. No:___21/8947_____________________ ____________________

Level: __300_____________________________________________________________

1
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

CREATING, COMPILING AND EXECUTING A JAVA PROGRAM USING NETBEAN IDE


➢ On getting to Netbean, click on New Project or Press Ctrl+Shift+N

Fig. 1.1: Netbean IDE view

➢ Then click on Java Application and click on Next button

Fig. 1.2: New Project dialog box

2
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

➢ Type in your Project name which is also the same as the Class name e.g. Displayname and
click on Finish button.

Fig. 1.3: Name and Location


➢ Type in your program codes in the TODO code application logic here line
➢ Save, Compile and Run your program

Fig. 1.4: Source code view

3
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

ii) BASIC STRUCTURE (COMPONENTS) OF OOJAVA PROGRAM


// Comment line i.e. single line, multi-line or JavaDoc (Document line) Comments
Import packages (Optional)
Class Name {
Main Method {
Object/Instance
Executable Statements
} // close main method
} // close of Public Class or end of program.

EXPLANATION OF THE SOURCE CODES OF FIRST JAVA PROGRAM


Now that we have understood how to run a java program, lets have a closer look at the program we
have written above.

i) public class FirstJavaProgram {


This is the first line of our java program. Every java application must have at least one class definition
that consists of class keyword followed by class name. When I say keyword, it means that it should
not be changed, we should use it as it is. However the class name can be anything.
I have made the class public by using public access modifier, I will cover access modifier in a separate
post, all you need to know now that a java file can have any number of classes but it can have only
one public class and the file name should be same as public class name.

ii) public static void main(String[ ] args) {


This is our next line in the program, lets break it down to understand it: public: This makes the main
method public that means that we can call the method from outside the class.
static: We do not need to create object for static methods to run. They can run itself.
void: It does not return anything.
main: It is the method name. This is the entry point method from which the JVM can run your
program.
(String[] args): Used for command line arguments that are passed as strings.

iii) System.out.println ("This is my first program in Java"); This method prints the contents inside
the double quotes into the console and inserts a newline after.

SAMPLE JAVA PROGRAM

4
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

Fig 1.5: Program to display a line of text

5
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

OUTPUT

Fig. 1.6: Program output to display a line of text

6
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

MODULE 1

WEEK 1 2

WORK TO DO
1. Run the java program below

/*
* WELCOME TO THE WORLD OF JAVA PROGRAMMING LANGUAGE
* Displays The Welcome Message above! to the output window
*
*/
public class WelcomeMessage // class definition header
{
public static void main( String[] args )
{
System.out.println( WELCOME TO THE WORLD OF JAVA PROGRAMMING LANGUAGE
!!! ); // this line prints the message text
} // end main method
} // end class/program WelcomeMessage

2. Write and run a Java program to display your Full Names, Matric No and Course of Study
(Attach a print copy of all source codes and output)

7
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

Week 3-4

WORK TO DO
1. List and explain the two classes of data types in OO Java and their types
2. List and explain the three (3) permissible styles of comments in the Java Programming language.
3. Key in and run the sample program below:
public class Variables {
public static void main(String[ ] args) {
int a;
double b;
char c;
a = 2;
b= 3.4;
c= e
System.out.println (a);
System.out.println (b);
System.out.println (c);
}
}
1. Key in the program below and answer the questions that follow by test running the program.
/*
* HelloWorldGUI.java
import javax.swing.JOptionPane;
public class HelloWorldGUI {
public static void main(String[] args) {
String msg = "Hello World";
String ans ="";
JOptionPane.showMessageDialog(null, msg );
// accept the users name
ans = JOptionPane.showInputDialog( null, "Enter your Name Please");
// say hello to the user
JOptionPane.showMessageDialog(null, "Hello " + ans );

} // end main method

} // end of class HelloWorldGUI

2. (a) Describe the output of the program. (b) Re-run the program and click on the ok button without
entering a name. What is the output presented?

3. Write and run a Java program to add three (3) variables and also find their average. (N.B. Attach
a print copy of the output for all programs).

8
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

WEEK 4

AIMS AND OBJECTIVES


Be able to:
a. Working with operators

APPARATUS
PC in a networked laboratory loaded with OO-JAVA Compiler and PowerPoint package and
connected to Internet.

WORK TO DO
1. Write short notes on each of the following : (i) Abstraction (ii) Encapsulation
(iii) Inheritance (iv) Polymorphism
2. (a) Run the sample program below and debug where applicable, attach the print out of codes and
output.
public class Operators {
static int a=3, c = 56;
static boolean state;
static double b = 24.6;
public static void main(String[ ] args) {
double args = (a-3+c*a)/c;
System.out.println (args + is cool);
System.out.println (state + is bad);
double x = b/2;
System.out.println (x + is the result);
}
}

2 (b) Write a Java program using the JOptionPane to read in two (2) numbers, multiply them and
display the result.

3. (b) Consider the program segment below:


import java.io.*;
import java.util.*;
public class Nd1 {
public static void main(String[] args)throws IOException {
Scanner in = new Scanner(System.in);
String name = in.nextLine();
int age = in.nextInt();

// Dispaly output
System.out.println(" My name is : "+ name);
System.out.println("My age is : "+ age);
}
}
9
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

From the program segment above, identify, list and comment on the following features.
i. System objects
ii. User Defined Objects
iii. Methods
iv. Class Name

3. Write a program to compute: Given that A = 5, B = 7 and C = 2, find the value of G = A + B


% C and K = (A + B) % C

4. Write a program in JAVA to compute Area of a circle

5. Write a simple program to calculate the Volume of a Cylinder.

6. Solve the following using JAVA syntax (i) y3 (ii) square root of 12.25 (iii) 2πr (v) !(6<=4) in
a single program.

Print the source code and the output screen

10
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

WEEK 5 – 6

AIMS AND OBJECTIVES


Be able to:
a. Understand the concept developmental techniques of program development
b. Know what an insatiable class is.
c. Know the difference between public and private data
d. Know the difference between local variables and instance variables
e. Understand parameter parsing
f. Understand method return types

APPARATUS
PC in a networked laboratory loaded with OO-JAVA Compiler and PowerPoint package and
connected to Internet.

WORK TO DO
1. Using program segments, illustrate the differences between local and instance methods.

2. Explain Parameter Passing.

3. Write and run the JAVA program below to illustrate IF.ELSE Statement

// Working with IF.ELSE Statement


public class IFELSE
{
public static void main(String[ ] args) {
int a = 5;
if (a >=4)
{
System.out.println (a is greater than 4);
}
else
{
System.out.println (a is less than 4);
System.out.println (a);
}
}
}

4. Write a Java program using the Scanner class to read in a student age and indicate if the
Student is a teenager or an adult.

11
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

// Program to display Multiplication Table with table size range

public class Multiplicationtable3 {

public static void main(String[] args) {

int tableSize = 15;


printMultiplicationTable(tableSize);
}
public static void printMultiplicationTable(int tableSize) {
// first print the top header row

System.out.format(" ");

for(int i = 1; i<=tableSize;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("
=============================================================");
for(int i = 1 ;i<=tableSize;i++) {
// print left most column first
System.out.format("%4d x",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
}

12
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

WEEK 7

AIMS AND OBJECTIVES


Be able to:
i. Understand the concept developmental techniques of program development
ii. Know what an insatiable class is.
iii. Know the difference between public and private data
iv. Know the difference between local variables and instance variables
v. Understand parameter parsing
vi. Understand method return types

APPARATUS
PC in a networked laboratory loaded with OO-JAVA Compiler and PowerPoint package and
connected to Internet.

WORK TO DO
1. Write and run the JAVA program below to illustrate IF.ELSE Statement
// Working with SWITCH.CASE STATEMENT
public class IFELSE
{
public static void main(String[ ] args) {
int a = 5;
switch (a)
{
case 1:
System.out.println (a is 1);
break;
case 3:
System.out.println (a is 3);
break;
case 5:
System.out.println (a is 1);
break;
default:
System.out.println (Wrong input);
}
}
}
2. Write and run the JAVA program below to illustrate IF.ELSE Statement
// Working with NESTED IF. STATEMENT
public class IFELSE
{
public static void main(String[ ] args) {
int a = 5, b=9;
if (a>=4)
{
13
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

If (b<8)
{
System.out.println (a is greater than 4 and b is less than 8);
}
else
{
System.out.println (a is greater than 4 and b is greater than 8);
}
}
else
System.out.println (a is less than 4);
}

14
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

WEEK 8

AIMS AND OBJECTIVES


Be able to:
i. Understand the concept developmental techniques of program development
ii. Know what an insatiable class is.
iii. Know the difference between public and private data
iv. Know the difference between local variables and instance variables
v. Understand parameter parsing
vi. Understand method return types

APPARATUS
PC in a networked laboratory loaded with OO-JAVA Compiler and PowerPoint package and
connected to Internet.

WORK TO DO
1. Write a program to compute addition of 10-100 using any of function suitable

2. Write program to compute sum of all even numbers between 5 and 120

3. Write a JAVA program, to output the sum of odd numbers from 1 to 1000, using For Loop
Statement.

4. Write a JAVA program to solve simultaneous equation involving two unknowns x and y NESTED
IF.

Print the source codes and the output screen

15
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

WEEK 9

AIMS AND OBJECTIVES


Be able to:
a. Apply the do and while statement and write simple programs to implement.
b. Develop algorithms for solving simple repetitive problems counter controlled and
sentinel-controlled algorithms.
c. Applies a JTextArea and a JScrollPane class to display the numbers
d. Understand the concepts of recursion and write simple recursive methods
e. Describe and manipulate character type data.
f. Differentiate between string and string buffer classes.
g. Differentiate between equivalence and equality for string objects.
h. Show how objects are passed to and returned from methods.

APPARATUS
PC in a networked laboratory loaded with OO-JAVA Compiler and PowerPoint package and
connected to Internet.

WORK TO DO
1. Run the program below and print the output.
// RecursiveNos.java
public class RecursiveNos
{
public void display1To10( int startNumber )
{
if( startNumber == 10 ) {
System.out.printf("\n%d ", startNumber );
}
else {
System.out.printf("\n%d ", startNumber );
// number display1To10( startNumber + 1);
}
}
}
2. Write a simple program to list all odd and even numbers respectively between 1 – 100
3. Compute nCr using function subprogram
4. Write a recursive JAVA program to calculate the factorial of any N numbers.
5. Write a JAVA program that will calculate the area and circumference of a circle.
6. Write a JAVA program using method overload functions to multiply and add two numbers.

Print the source codes and the output screen

16
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

WEEK 10

AIMS AND OBJECTIVES


Be able to:
• Give the general format of Arrays.
• Write Array statement.
• Write program regent to illustrate multi input box manipulation, and pointers in methods.

APPARATUS
PC in a networked laboratory loaded with OO-JAVA Compiler and PowerPoint package and
connected to Internet.

WORK TO DO
1. (a) Write a simple Java program to declare an array named Governor which can store five (5)
integers and create this array to store the following numbers: {23,45,66,27,87} .

(b) Describe the syntax for declaring an array in Java.

(c) Describe the syntax for creating an array in Java with sample program segment.

(d) Describe String concatenation in Java with sample program segment.

2. Enter the program below and print the outputs displayed.


// StringConstructors.java
// String class constructors.

public class StringConstructors


{
public static void main( String args[] )
{
char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a' , 'y' };
String s = new String( "hello" );
// use String constructors
String s1 = new String();
String s2 = new String( s );
String s3 = new String( charArray );
String s4 = new String( charArray, 6, 3);
System.out.printf(
"s1 = %s\ns2 = %s\ns3 = %s\ns4 = %s\n",
s1, s2, s3, s4 ); // display strings
} // end main
} // end class StringConstructors

4. Enter the program below and produce its output.


// StringMiscellaneous.java
// This application demonstrates the length, charAt and getChars
// methods of the String class.

public class StringMiscellaneous


{
17
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

public static void main( String args[] )


{
String s1 = "hello there";
char charArray[] = new char[ 5 ];
System.out.printf( "s1: %s", s1 );

// test length method


System.out.printf( "\nLength of s1: %d", s1.length() );

// loop through characters in s1 with charAt and display reversed


System.out.print( "\nThe string reversed is: " );

for ( int count = s1.length() - 1; count >= 0; count-- )


System.out.printf( "%s ", s1.charAt( count ) );

// copy characters from string into charArray


s1.getChars( 0, 5, charArray, 0 );
System.out.print( "\nThe character array is: " );
for ( char character : charArray )
System.out.print( character );
System.out.println();
} // end main
} // end class StringMiscellaneous

Print the source codes and the output screen

18
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

ANSWERS PAGE
WEEK 1-2 NO. 2:
public class StudentDetails{
public static void main(String [] args){
String name = "Daniel Omogbai Oshione";
String matric = "\n21/8947";
String CourseOfStudy = "\nComputer Science";

System.out.println(name + matric + CourseOfStudy);


}
}
OUTPUT:
Daniel Omogbai Oshione
21/8947
Computer Science

WEEK 3-4 :
1a. Primitive Data Types:
• These are basic data types built into the Java language.
• Examples include int, double, char, boolean, etc.
• They store simple values directly.

b. Reference Data Types:

• These are more complex types that hold references to objects.


• Examples include classes, interfaces, arrays, and enumerations.
• They point to memory locations where the actual data is stored.

2. Single Line Comments: denoted by "//", used for commenting on a single line.

• Multi-line Comments: enclosed between "/" and "/", used for commenting out multiple lines
or sections of code.
• Documentation Comments: enclosed between "/**" and "*/", used for generating
documentation and can be processed by tools like javadoc.

3a. The output of the code is a separate window displaying a message box telling user to insert
their names.

b. If i click on the OK button without a typing my name the output is just “HELLO”

4. Program to add 3 variables and find their average :

public class Calculation{

19
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

public static void main(String[] args) {

int a = 2;

int b = 4;

int c = 6;

int sum = a + b + c;

System.out.println("The sum in: " + sum);

float avg = sum/2;

System.out.println("\n The average is: " + avg);

} }

OUTPUT:

The sum in: 12

The average is: 6.0

WEEK 4:

1a. (i) Abstraction: Abstraction is the process of representing essential features without including
the background details. In programming, it involves creating classes, objects, and methods that
focus on the necessary characteristics and behavior of an entity, while hiding the implementation
details.

(ii) Encapsulation: Encapsulation is the concept of bundling data and methods that operate on the
data within a single unit, such as a class. It helps in restricting access to certain components of an
object, thus preventing unauthorized access and modification of data.

(iii) Inheritance: Inheritance is a fundamental principle of object-oriented programming (OOP) that


allows a new class to inherit properties and behavior from an existing class. This promotes
reusability, as the new class can extend and modify the functionality of the existing class.

(iv) Polymorphism: Polymorphism refers to the ability of different classes to be treated as instances
of the same class through a common interface. It allows a single method to have different forms,
such as method overloading and method overriding, based on the context in which it is used. This
promotes flexibility and extensibility in OOP.

2a. Debugged:

public class Operators {

static int a=3, c = 56;

20
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

static boolean state;

static double b = 24.6;

public static void main(String[ ] args) {

double argu = (a-3+c*a)/c;

System.out.println (argu + "\nis cool");

System.out.println (state + "\nis bad");

double x = b/2;

System.out.println (x + "\nis the result");

} }

OUTPUT:

3.0

is cool

false

is bad

12.3

is the result

2b. program to receive input and multiply two numbers using JOptionPane:

import javax.swing.JOptionPane;

public class Multiplication {

public static void main(String[] args) {

String num1 = JOptionPane.showInputDialog("Enter the first number:");

String num2 = JOptionPane.showInputDialog("Enter the second number:");

double number1 = Double.parseDouble(num1);

double number2 = Double.parseDouble(num2);

double result = number1 * number2;

JOptionPane.showMessageDialog(null, "The result of multiplying " + number1 + " and " +


number2 + " is: " + result);

}}

21
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

3a. Identified features in the program segment provided:

System Objects:

System.out: This object is used to access the standard output stream and is used to display the
output to the console.

System.in: This object is used to access the standard input stream and is used to accept input from
the console.

User Defined Objects:

Scanner: The 'Scanner' object is a user-defined object used to read input from various sources, such
as files, strings, and the console. In this program, it is used to read input from the standard input
stream (System.in).

Methods:

main: This is the entry point of the program and is a predefined method in Java. It is called when
the program is executed and contains the code to be executed.

Class Name:

Nd1: This is the name of the main class in the program. In Java, the main class name must match
the source file name and contains the code for the program's functionality.

3b.

public class ComputeValues {

public static void main(String[] args) {

int A = 5;

int B = 7;

int C = 2;

int G = A + B % C;

int K = (A + B) % C;

System.out.println("The value of G is: " + G);

System.out.println("The value of K is: " + K);

}}

OUTPUT:

The value of G is: 6

The value of K is: 0


22
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

4. Program to calculate area of a circle:

// Program to compute the area of a circle

public class AreaOfCircle {

public static void main(String[] args) {

double radius = 18.0;

double PI = 22/7;

double area = PI * radius * radius;

System.out.println("The area of the circle is: " + area);

}}

OUTPUT:

The area of the circle is: 972.0

5. Program to calculate volume of a cylinder:

// Program to calculate the volume of a cylinder

public class CylinderVolume {

public static void main(String[] args) {

final double PI = 22/7;

double radius = 6.0;

double height = 2.0;

double volume = PI * radius * radius * height;

System.out.println("The volume of the cylinder is: " + volume);

}}

OUTPUT:

The volume of the cylinder is: 216.0

6. public class ExpressionSolver {

public static void main(String[] args) {


23
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

int y = 3;

double squareRoot = Math.sqrt(12.25);

double radius = 8.0; // Assuming r is 8.0

double result = 2 * Math.PI * radius;

boolean comparison = !(6 <= 4);

System.out.println("y raised to the power of 3: " + Math.pow(y, 3));

System.out.println("Square root of 12.25: " + squareRoot);

System.out.println("2πr: " + result);

System.out.println("!(6<=4): " + comparison);

}}

OUTPUT:

y raised to the power of 3: 27.0

Square root of 12.25: 3.5

2πr: 50.26548245743669

!(6<=4): true

WEEK 5-6

1. public class MethodExample {

// Instance method

public void instanceMethod() {

System.out.println("This is an instance method");

public static void main(String[] args) {

MethodExample obj = new MethodExample();

obj.instanceMethod(); // Calling the instance method

localMethod(); // Calling the local method }

// Local method

public static void localMethod() {


24
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

System.out.println("This is a local method");

}}

2. Explain Parameter Passing: Parameter passing refers to the way that arguments are passed to a
method. In Java, parameters can be passed to methods in two ways: by value and by reference.

3. OUTPUT:

A is greater than 4.

4. Write a Java program using the Scanner class to read in a student age and indicate if the
Student is a teenager or an adult.:

import java.util.Scanner;
public class StudentDetails{
public static void main (String [] args){
Scanner scan = new Scanner (System.in);
System.out.println("Enter your age: ");
int age = scan.nextInt();
if (age >= 18) {
System.out.println("You are an adult");
}
else{
System.out.println("You are teenager");
}}}

OUTPUT:
Enter your age:

19

You are an adult

WEEK 8

1. Program to compute addition of 10-100 using any of function suitable:

public class AdditionProgram {


25
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

public static void main(String[] args) {


int sum = 0;
for (int i = 10; i <= 100; i++) {
sum += i;
}
System.out.println("The sum of numbers from 10 to 100 is: " + sum);
}}
OUTPUT:

The sum of numbers from 10 to 100 is: 5005.

2. Program to compute sum of all even numbers between 5 and 120:

public class EvenNumberSum {


public static void main(String[] args) {
int sum = 0;
for (int i = 6; i <= 120; i += 2) {
sum += i;
}
System.out.println("The sum of all even numbers between 5 and 120 is: " + sum);
}}
OUTPUT:
The sum of all even numbers between 5 and 120 is: 3654.

3. JAVA program, to output the sum of odd numbers from 1 to 1000, using For Loop Statement:

public class OddNumberSum {


public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 1000; i += 2) {
sum += i;
}
System.out.println("The sum of all odd numbers between 1 and 1000 is: " + sum);
}}
OUTPUT:

The sum of all odd numbers between 1 and 1000 is: 250000.

4. JAVA program to solve simultaneous equation involving two unknowns x and y NESTED IF:

public class StudentDetails {


public static void main(String[] args) {
double a1 = 2, b1 = 4, c1 = 22; // coefficients of the first equation: 2x + 4y = 22
double a2 = 6, b2 = -1, c2 = 16; // coefficients of the second equation: 6x - y = 18
double determinant = a1 * b2 - a2 * b1; // Calculate the determinant
if (determinant != 0) {
double x = (c1 * b2 - c2 * b1) / determinant;
double y = (a1 * c2 - a2 * c1) / determinant;

26
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

System.out.println("The solution for the system of equations is: x = " + x + ", y = " +
y);
} else {
System.out.println("The system of equations either has no solution or infinitely
many solutions."); }}}
OUTPUT:
The solution for the system of equations is: x = 3.3076923076923075, y = 3.8461538461538463.

WEEK 9

1. public class RecursiveNos {

public void display1To10(int startNumber) {

if (startNumber <= 10) {

System.out.printf("%d ", startNumber);

display1To10(startNumber + 1);

}}

public static void main(String[] args) {

RecursiveNos recursiveNos = new RecursiveNos();

System.out.println("Printing 1 to 10 using recursion:");

recursiveNos.display1To10(1);

}}

OUTPUT:

Printing 1 to 10 using recursion:

1 2 3 4 5 6 7 8 9 10

2. Program to list all odd and even numbers respectively between 1 – 100:

public class OddEvenNumbers {

public static void main(String[] args) {

System.out.println("Even numbers between 1 and 100:");

for (int i = 1; i <= 100; i++) {

27
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

if (i % 2 == 0) {

System.out.print(i + " ");

}}

System.out.println("\nOdd numbers between 1 and 100:");

for (int i = 1; i <= 100; i++) {

if (i % 2 != 0) {

System.out.print(i + " ");

}}}}

OUTPUT:

Even numbers between 1 and 100:

2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66
68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100

Odd numbers between 1 and 100:

1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67
69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99

3. Compute nCr using function subprogram :


public class nCrCalculator {
public static int factorial(int n) {
return (n == 0 || n == 1) ? 1 : n * factorial(n - 1);
}
public static int nCr(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n - r));
}
public static void main(String[] args) {
int n = 5, r = 2;
System.out.println("nCr of " + n + " and " + r + " is: " + nCr(n, r));
}}
OUTPUT:
nCr of 5 and 2 is: 10.

4. Write a recursive JAVA program to calculate the factorial of any N numbers:

public class FactorialCalculator {


public static int factorial(int n) {
return (n == 0 || n == 1) ? 1 : n * factorial(n - 1);
28
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

public static void main(String[] args) {


int n = 5;
System.out.println("Factorial of " + n + " is: " + factorial(n)); }}
OUTPUT:
Factorial of 5 is: 120.

5. Write a JAVA program that will calculate the area and circumference of a circle.
public class CircleCalculator {
public static double calculateArea(double radius) {
return Math.PI * Math.pow(radius, 2);
}
public static double calculateCircumference(double radius) {
return 2 * Math.PI * radius;
}
public static void main(String[] args) {
double radius = 5.0;
System.out.println("Area of the circle: " + calculateArea(radius));
System.out.println("Circumference of the circle: " + calculateCircumference(radius));
}}
OUTPUT:
Area of the circle: 78.53981633974483
Circumference of the circle: 31.41592653589793

6. Write a JAVA program using method overload functions to multiply and add two numbers:

public class Calculator {


public static int add(int a, int b) {
return a + b;}

public static double add(double a, double b) {


return a + b;}

public static int multiply(int a, int b) {


return a * b;}

public static double multiply(double a, double b) {


return a * b;}

public static void main(String[] args) {


int num1 = 5, num2 = 3;
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + add(num1, num2));
System.out.println("Product of " + num1 + " and " + num2 + " is: " + multiply(num1, num2));

29
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

double doubleNum1 = 5.5, doubleNum2 = 3.0;


System.out.println("Sum of " + doubleNum1 + " and " + doubleNum2 + " is: " +
add(doubleNum1, doubleNum2));
System.out.println("Product of " + doubleNum1 + " and " + doubleNum2 + " is: " +
multiply(doubleNum1, doubleNum2));
}}
OUTPUT:
Sum of 5 and 3 is: 8
Product of 5 and 3 is: 15
Sum of 5.5 and 3.0 is: 8.5
Product of 5.5 and 3.0 is: 16.5

WEEK 10

1a. Write a simple Java program to declare an array named Governor which can store five (5)
integers and create this array to store the following numbers: {23,45,66,27,87} :

public class ArrayExample {

public static void main(String[] args) {

int[] Governor = {23, 45, 66, 27, 87};

}}

(b) Describe the syntax for declaring an array in Java:

datatype[] arrayName;

(c) Describe the syntax for creating an array in Java with sample program segment:

datatype[] arrayName = new datatype[size];

int[] numbers;

int[] numbers;

String[] names;

(d) Describe String concatenation in Java with sample program segment:

public class StringConcatenationExample {

public static void main(String[] args) {


30
OBJECT ORIENTED JAVA PROGRAMMING LANGUAGE COM 121

String firstName = "Daniel";

String lastName = "Omogbai";

String fullName = firstName + " " + lastName;

System.out.println("Full Name: " + fullName);

}}

OUTPUT:

Full Name: Daniel Omogbai

2. OUTPUT:
s1 =

s2 = hello

s3 = birth day

s4 = day

3. OUTPUT:

s1: hello there

Length of s1: 11

The string reversed is: e r e h t o l l e h

The character array is: hello

31

You might also like