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

Java Programming Practice QuestionsFrom Beginer to advanced

The document contains a comprehensive set of practice questions for Year 13 Cambridge Computer Science, covering various programming concepts such as variables, casting, operators, string manipulation, user input, control statements, loops, arrays, and methods. Each section includes multiple programming tasks that require the implementation of specific functionalities using programming constructs. The exercises are designed to enhance students' understanding and application of fundamental programming principles.

Uploaded by

mukasaiz83
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Programming Practice QuestionsFrom Beginer to advanced

The document contains a comprehensive set of practice questions for Year 13 Cambridge Computer Science, covering various programming concepts such as variables, casting, operators, string manipulation, user input, control statements, loops, arrays, and methods. Each section includes multiple programming tasks that require the implementation of specific functionalities using programming constructs. The exercises are designed to enhance students' understanding and application of fundamental programming principles.

Uploaded by

mukasaiz83
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

YEAR13 CAMBRIDGE COMPUTER SCIENCE PRACTICE QUESTIONS PAPER4

Variables

1. Create a program that asks the user to enter their name, age, and favorite subject. Store
these values in appropriate variables and then print a summary message.

2. Write a program that calculates the area of a rectangle. Ask the user to input the length
and width, store these values in variables, and then compute and print the area.

3. Implement a program that converts a given temperature in Celsius to Fahrenheit. Ask the
user for the Celsius temperature, store it in a variable, and print the converted
temperature. (F = (9/5 × °C) + 32.)

4. Create a program that takes three numbers as input from the user, stores them in
variables, and prints the sum, average, and product of these numbers.

5. Write a program that takes the radius of a circle as input, stores it in a variable, and then
calculates and prints area. (Area=PI*R^2)

6. Implement a program that calculates the simple interest. Ask the user for the principal
amount, rate of interest, and time period, store these values in variables, and print the
interest.

7. Create a program that asks the user to enter a student's name, their marks in three
subjects, and then calculates and prints the student details, total marks and percentage.

8. Write a program that takes the user's birth year as input, stores it in a variable, calculates
their age, and prints a message with their age.

9. Create a program that takes the user's first name and last name as input, stores them in
variables, and prints the full name.
Casting

1. Write a program that reads an integer from the user, casts it to a double, and prints both
the original integer and the casted double value.

2. Create a program that takes a double input from the user, casts it to an integer, and prints
both the original double and the casted integer value.

3. Implement a program that reads a string input representing a number, casts it to an


integer, and prints both the original string and the casted integer value.

4. Create a program that reads an integer input from the user, casts it to a float, and prints
both the original integer and the casted float value.

5. Implement a program that reads a float input from the user, casts it to an integer, and
prints both the original float and the casted integer value.

6. Write a program that reads a double input from the user, casts it to a long, and prints both
the original double and the casted long value.

7. Create a program that reads a string input representing a floating-point number, casts it to
a double, and prints both the original string and the casted double value.

8. Implement a program that reads an integer input from the user, casts it to a short, and
prints both the original integer and the casted short value.

9. Write a program that reads a long input from the user, casts it to an int, and prints both
the original long and the casted int value.

Operators

1. Write a program that takes two integers as input and performs addition, subtraction,
multiplication, division, and modulus operations on them. Print the results of each
operation.

2. Create a program that takes two double values as input and compares them using
relational operators (>, <, >=, <=, ==, !=). Print the results of each comparison.

3. Create a program that takes two integers as input and uses the assignment operators (+=, -
=, *=, /=, %=) to perform various operations. Print the results of each assignment
operation.

4. Implement a program that takes a double value as input and demonstrates the use of the
compound assignment operators (+=, -=, *=, /=, %=). Print the results of each operation.
5. Write a program that reads two strings and concatenates them using the + operator. Print
the concatenated string.

6. Create a program that demonstrates the use of the ternary operator. Take an integer input
and use the ternary operator to determine if it is positive, negative, or zero. Print the
result.

7. Implement a program that demonstrates operator precedence by performing a series of


mixed operations on integer inputs. Print the results and explain the order of operations.

8. Write a program that takes an integer input and uses the increment (++) and decrement (--
) operators to demonstrate their effects. Print the results before and after applying these
operators.

String Manipulation

1. Write a program that takes a string input from the user and prints its length using the
length () method.

2. Create a program that takes a string input and converts it to uppercase using the
toUpperCase () method. Print the original and converted strings.

3. Implement a program that takes a string input and extracts a substring from it using the
substring () method. Print the original string and the extracted substring.

4. Write a program that reads a string input and checks if it contains a specific word using
the contains () method. Print the result of the check.

5. Create a program that takes two string inputs and compares them using the equals() and
compareTo() methods. Print the results of each comparison.

6. Implement a program that reads a string input and replaces all occurrences of a specified
character with another character using the replace() method. Print the original and
modified strings.

7. Create a program that takes a string input and trims leading and trailing whitespace using
the trim () method. Print the original and trimmed strings.

8. Implement a program that reads a string input and reverses it. Print the original and
reversed strings.

9. Write a program that takes a string input and counts the number of vowels in it. Print the
total count of vowels.
Getting Input from the User

1. Write a program that prompts the user to enter their full name and then prints a welcome
message including their name.

2. Create a program that asks the user to enter three integers and then calculates and prints
the sum and average of these numbers.

3. Write a program that prompts the user to enter their age and then prints a message
indicating whether they are a minor, an adult, or a senior citizen.

4. Create a program that reads a series of space-separated words from the user and prints
each word on a new line.

5. Implement a program that asks the user to enter a sentence and then prints the number of
words in the sentence.

6. Write a program that prompts the user to enter their date of birth in the format
DD/MM/YYYY and then prints their age in years.

If Statement

1. Write a program that reads an integer from the user and prints whether it is positive,
negative, or zero using if-else statements.

2. Create a program that asks the user to enter their age and then prints a message indicating
if they are eligible to vote (18 and older) or not.

3. Implement a program that takes three numbers as input from the user and prints the
largest and smallest of the three using if-else statements.

4. Write a program that asks the user to enter a character and checks if it is an uppercase
letter, lowercase letter, digit, or special character using if-else statements.

5. Create a program that reads a student's marks in three subjects and prints their grade (A,
B, C, D, or F) based on the average marks using if-else-if statements.

6. Implement a program that asks the user to enter their age, height (in centimeters), and
weight (in kilograms). Based on these inputs, print a health message categorizing their
health status as underweight, normal weight, overweight, or obese.

7. Write a program that reads an integer representing a month number from the user and
prints the corresponding month name (e.g., 1 for January, 2 for February, etc.) using if-
else statements.
8. Create a program that asks the user to enter their exam scores for Math and English.
Determine if the student has passed both subjects (score >= 60) and print a congratulatory
message if they have.

9. Implement a program that reads a user's age and gender. Based on these inputs, print a
message indicating whether they are eligible for military service based on the criteria for
their country.

10. Write a program that prompts the user to enter their blood pressure (systolic and
diastolic). Determine if their blood pressure is normal, high, or low based on predefined
ranges and print an appropriate message.

Switch Statement

1. Create a program that reads an integer representing a day of the week from the user. Use
a switch statement to print the corresponding day name (e.g., 1 for Monday, 2 for
Tuesday, etc.).

2. Write a program that asks the user to enter a month number. Use a switch statement to
print the number of days in that month (considering leap years for February).

3. Implement a program that reads a character representing a grade level (A, B, C, D, or F)


from the user. Use a switch statement to print a message indicating the corresponding
grade description (e.g., A for Excellent, B for Good, etc.).

4. Create a program that prompts the user to enter a mathematical operation (+, -, *, /). Use
a switch statement to perform the operation on two numbers entered by the user and print
the result.

5. Write a program that reads a character representing a vowel (a, e, i, o, u) from the user.
Use a switch statement to print a message indicating whether the input character is a
vowel or not.

6. Write a program that prompts the user to enter a day number (1-7) representing a day of
the week. Use a switch statement to print a message indicating whether it is a weekday or
weekend day.

7. Implement a program that reads a character representing a direction (N, S, E, W) from the
user. Use a switch statement to print a message indicating the corresponding cardinal
direction (North, South, East, West).

8. Create a program that asks the user to enter a grade level (freshman, sophomore, junior,
senior). Use a switch statement to print a message indicating the corresponding year in
college (1st, 2nd, 3rd, 4th).
For Loop

1. Write a program that uses a for loop to print the numbers from 1 to 10.

2. Create a program that calculates and prints the factorial of a given number using a for
loop.

3. Implement a program that reads an integer n from the user and prints the sum of the first
n natural numbers using a for loop.

4. Write a program that asks the user to enter a number and prints a multiplication table for
that number up to 10 using a for loop.

5. Create a program that reads an integer representing the number of terms in the Fibonacci
sequence from the user. Use a for loop to generate and print the Fibonacci sequence.

6. Implement a program that calculates and prints the sum of all even numbers between two
given integers using a for loop.

7. Write a program that prompts the user to enter a positive integer n and prints the sum of
the squares of all integers from 1 to n using a for loop.

8. Write a program that asks the user to enter a number and prints its prime factors using a
for loop.

While Loop and Do While Loop

1. Create a program that uses a while loop to print the numbers from 1 to 10.

2. Write a program that prompts the user to enter a positive integer n and prints all the
factors of n using a while loop.

3. Implement a program that reads an integer n from the user and prints the sum of the digits
of n using a while loop.

4. Create a program that reads an integer input from the user and prints the reverse of the
number using a while loop.

5. Write a program that asks the user to enter a number and then prints its multiplication
table up to 10 using a while loop.

6. Implement a program that calculates and prints the factorial of a given number using a
while loop.
7. Create a program that reads a string input from the user and prints each character of the
string in reverse order using a while loop.

8. Write a program that prompts the user to enter a number and then prints the sum of its
digits using a while loop.

1D Arrays

1. Write a program that initializes an array of integers and calculates and prints the sum of
all elements in the array.

2. Create a program that reads an array of integers from the user and prints the largest and
smallest elements in the array.

3. Implement a program that initializes an array of doubles and calculates and prints the
average of all elements in the array.

4. Write a program that initializes an array of strings and prints each element of the array on
a new line.

5. Create a program that reads an array of characters from the user and prints them in
reverse order.

6. Implement a program that initializes an array of integers and finds and prints the sum of
all even elements in the array.

7. Write a program that initializes an array of integers and checks if a given number exists
in the array. Print a message indicating the result.

8. Create a program that reads an array of strings from the user and prints the length of each
string in the array.

9. Implement a program that initializes an array of doubles and finds and prints the product
of all elements in the array.

10. Write a program that initializes an array of integers and prints the frequency of each
element in the array.
2D Arrays

1. Generate a program that initializes a 2D array of integers and prints each element of the
array.

2. Create a program that reads a 2D array of characters from the user and prints each
element of the array on a new line.

3. Implement a program that initializes a 2D array of doubles and calculates and prints the
average of all elements in the array.

4. Write a program that initializes a 2D array of integers and prints the sum of each row of
the array.

5. Create a program that reads a 2D array of integers from the user and prints the largest and
smallest elements in the array.

6. Implement a program that initializes a 2D array of strings and prints each row of the array
on a new line.

7. Write a program that initializes a 2D array of characters and prints the number of vowels
in each row of the array.

8. Generate a program that reads a 2D array of doubles from the user and prints the sum of
each column of the array.
9. Create a program that initializes a 2D array of integers and checks if a given number
exists in the array. Print a message indicating the result.

10. Implement a program that reads a 2D array of integers from the user and prints the
product of each column of the array.

Methods and Procedures

1. Write a method sum that takes two integers as parameters and returns their sum.
2. Write a method isEven that takes an integer as a parameter and returns true if the number
is even and false otherwise.
3. Write a method celsiusToFahrenheit that takes a temperature in Celsius as a parameter
and returns the equivalent temperature in Fahrenheit. Use the formula fahrenheit =
(celsius * 9/5) + 32 to convert the temperature.
4. Write a method maxOfThree that takes three integers as parameters and returns the
largest of the three.
5. Write a method reverseString that takes a string as a parameter and returns the reversed
string.
6. Write a method countVowels that takes a string as a parameter and returns the number of
vowels in the string.
7. Write a method factorial that takes a positive integer as a parameter and returns its
factorial.
8. Write a method findSmallest that takes an array of integers as a parameter and returns the
smallest element.
9. Write a method removeDuplicates that takes an array of integers as a parameter and
returns a new array with duplicates removed.

Linear Search

1. Write a program that initializes an array of integers and performs a linear search to find a
specific element entered by the user. Print the index of the element if found, otherwise
print a message indicating its absence.

2. Write a program that initializes an ArrayList of integers and performs a linear search to
find a specific element entered by the user. Print the index of the element if found,
otherwise print a message indicating its absence.

3. Create a program that reads an ArrayList of strings from the user and performs a linear
search to find a specific string entered by the user. Print the index of the string if found,
otherwise print a message indicating its absence.

4. Write a program that initializes a HashMap with student names as keys and their
corresponding scores as values. Perform a linear search to find a specific student's score
entered by the user. Print the score if found, otherwise print a message indicating its
absence.

5. Create a program that reads a HashMap of strings from the user, where each string is
associated with its length. Perform a linear search to find a specific string length entered
by the user. Print the string if found, otherwise print a message indicating its absence.

Binary Search

1. Write a program that initializes an array of integers and performs a binary search to find a
specific element entered by the user. Print the index of the element if found, otherwise
print a message indicating its absence.

2. Create a program that reads an array of strings from the user and performs a binary search
to find a specific string entered by the user. Print the index of the string if found,
otherwise print a message indicating its absence.

3. Write a program that initializes an ArrayList of integers and performs a binary search to
find a specific element entered by the user. Print the index of the element if found,
otherwise print a message indicating its absence.
4. Write a program that initializes a HashMap with student names as keys and their
corresponding scores as values. Perform a binary search to find a specific student's score
entered by the user. Print the score if found, otherwise print a message indicating its
absence.

5. Create a program that reads a HashMap of strings from the user, where each string is
associated with its length. Perform a binary search to find a specific string length entered
by the user. Print the string if found, otherwise print a message indicating its absence.

Sorting Algorithms

1. Write a program that initializes an array of integers and sorts it using the bubble sort and
insertion sort algorithm. Print the sorted array.

2. Implement a program that initializes an ArrayList of doubles and sorts it using bubble
and insertion sort algorithm. Print the sorted ArrayList.

3. Write a program that initializes a HashMap with student names as keys and their
corresponding scores as values. Sort the HashMap by scores in ascending order and print
it.

ALGORITHMS USING METHODS

10. Write a method bubbleSort that takes an array of integers as a parameter and sorts it using
the bubble sort algorithm.
11. Write a method binarySearch that takes a sorted array of integers and a target integer as
parameters and returns the index of the target in the array. If the target is not found,
return -1.
12. Write a class Stack with methods push, pop, and peek to implement a stack data structure
using an array.
13. Write a class Queue with methods enqueue, dequeue, and peek to implement a queue data
structure using an array.
14. Write a class LinkedList with methods add, remove, and find to implement a linked list
data structure.
15. Write a class BinaryTree with methods insert, search, and inOrderTraversal to implement
a binary tree data structure.

ADVANCED METHODS

16. Write a superclass Vehicle with attributes make and model, and a subclass Car with an
additional attribute numberOfDoors. Implement constructors, getters, and setters for both
classes.
17. Write a superclass Animal with a method makeSound, and subclasses Dog and Cat that
override the makeSound method.

Guidelines:

o Define a class Animal with a method makeSound ().


o Define subclasses Dog and Cat that override makeSound to return appropriate
sounds (e.g., "Bark" for Dog, "Meow" for Cat).
o Demonstrate polymorphism by creating instances of Dog and Cat and calling
makeSound.

18. Write a class Classroom with attributes String className and ArrayList<Student>
students, and methods addStudent, removeStudent, and getStudentCount.

Guidelines:

o Define a class Student with attributes String name and int id.
o Define a class Classroom with attributes String className and
ArrayList<Student> students.
o Implement methods addStudent (Student student), removeStudent (int id), and
getStudentCount ().
o Ensure addStudent adds a student to the list, removeStudent removes a student by
ID, and getStudentCount returns the number of students.
19. Write a class Dictionary with a method addWord to add a word and its meaning, a
method getMeaning to retrieve the meaning, and a method removeWord to remove a
word.

Guidelines:

o Define a class Dictionary with an attribute HashMap<String, String> words.


o Implement methods addWord(String word, String meaning), getMeaning(String
word), and removeWord(String word).
o Ensure addWord adds a key-value pair to the HashMap, getMeaning retrieves the
value by key, and removeWord removes the key-value pair.

Recursion

1. Implement a program that calculates the factorial of a given number using recursion.

2. Write a program that calculates the nth term of the Fibonacci sequence using recursion.

3. Generate a program that finds the sum of digits of a positive integer using recursion.

4. Create a program that reverses a string using recursion.


5. Implement a program that calculates the power of a given base raised to a non-negative
exponent using recursion.

6. Generate a program that calculates the sum of all even numbers between two given
integers using recursion.

7. Implement a program that calculates the product of two positive integers without using
the multiplication operator (*), using recursion.

8. Write a program that calculates the sum of the elements in an array using recursion.

9. Write a recursive method fibonacci that takes an integer n as a parameter and returns the
n-th Fibonacci number.

OBJECT ORIENTED PROGRAMMING


Project 1: Student Management System
Description: Develop a Student Management System to manage student information, including
their grades and attendance records.
Student Class:
Attributes:
1. name: Name of the student.
2. id: Unique identifier for the student.
3. grades[]: Array of grades for different courses. Each grade is stored with its
corresponding course.
4. attendance[]: Array of attendance records for different courses. Each attendance
record is stored with its corresponding course.
Methods:
calculateGPA (): Calculates the GPA (Grade Point Average) based on the grades
obtained in different courses. It computes the weighted average of grades using credit
hours.
1. Input: None.
2. Output: GPA (float).
RegularStudent Subclass:
Inherits from Student class.
Additional Attributes:
isRegular: Boolean indicating if the student is a regular student or not.
Additional Methods: None.
TransferStudent Subclass:
Inherits from Student class.
Additional Attributes:
previousSchool: Name of the previous school attended by the student.
transferCredits: Number of credits transferred from the previous school.
Additional Methods: None.

School Class (Containment):


Attributes:
students[]: Array of students enrolled in the school.
courses[]: Array of courses offered by the school.
Methods:
enrollStudent(student): Adds a student to the school's student list.
Input: Student object.
Output: None.
recordAttendance(student, course, status): Records attendance for a student in a
specific course.
Input: Student object, course name, attendance status (e.g., present/absent).
Output: None.

Project 2: Library Management System


Description: Create a Library Management System to manage books, members, and
borrowing/returning books.
Book Class:
Attributes:
title: Title of the book.
author: Author of the book.
available: Boolean indicating the availability status of the book.
Methods:
borrowBook(member): Allows a member to borrow a book from the library. It
updates the availability status of the book and adds the book to the member's
borrowed books list.
Input: Member object.
Output: None.
returnBook(member): Allows a member to return a borrowed book to the
library. It updates the availability status of the book and removes the book from
the member's borrowed books list.
Input: Member object.
Output: None.
searchBook(keyword): Searches for a book by title or author in the library's
collection.
Input: Keyword (title or author name).
Output: List of books matching the search criteria.
FictionBook Subclass:
Inherits from Book class.
Additional Attributes:
genre: Genre of the fiction book.
Additional Methods: None.
NonFictionBook Subclass:
Inherits from Book class.
Additional Attributes:
subject: Subject of the non-fiction book.
Additional Methods: None.
Library Class (Containment):
Attributes:
books[]: Array of books available in the library.
members[]: Array of members registered with the library.
Methods:
addBook(book): Adds a new book to the library's collection.
Input: Book object.
Output: None.
registerMember(member): Registers a new member with the library.
Input: Member object.
Output: None.

Project 3: Employee Payroll System


Description: Develop an Employee Payroll System to manage employee information, salaries,
and payroll calculations.
Employee Class:
Attributes:
name: Name of the employee.
id: Unique identifier for the employee.
position: Job position of the employee.
salary: Monthly salary of the employee.
Methods:
calculateSalary(): Calculates the monthly salary for an employee based on their position
and working hours.
Input: None.
Output: Monthly salary (float).
assignDepartment(department): Assigns an employee to a specific department within
the company.
Input: Department name.
Output: None.
FullTimeEmployee Subclass:
Inherits from Employee class.
Additional Attributes:
benefits: List of benefits provided to the full-time employee (e.g., health insurance,
retirement plan).
Additional Methods: None.
PartTimeEmployee Subclass:
Inherits from Employee class.
Additional Attributes:
hoursWorked: Number of hours worked by the part-time employee.
Additional Methods: None.
Company Class (Containment):
Attributes:
employees[]: Array of employees working for the company.
departments[]: Array of departments within the company.
Methods:
hireEmployee(employee): Hires a new employee and assigns them to a
department within the company.
Input: Employee object.
Output: None.
calculatePayroll(): Calculates the total payroll for all employees in the company.
Input: None.
Output: Total payroll amount (float).

Project 4: Online Banking System


Description: Create an Online Banking System to manage customer accounts, transactions, and
balance inquiries.
Account Class:
Attributes:
accountNumber: Unique account number associated with the account.
balance: Current balance in the account.
transactionHistory[]: Array of transactions made on the account.
Methods:
processTransaction(transaction): Processes transactions such as deposits,
withdrawals, and transfers for the account.
Input: Transaction details.
Output: None.
calculateInterest(): Calculates the interest accrued on the account balance.
Input: None.
Output: Interest amount (float).
SavingsAccount Subclass:
Inherits from Account class.
Additional Attributes:
interestRate: Annual interest rate for the savings account.
Additional Methods: None.

CheckingAccount Subclass:
Inherits from Account class.
Additional Attributes:
overdraftLimit: Maximum overdraft limit allowed for the checking account.
Additional Methods: None.

Bank Class (Containment):


Attributes:
accounts[]: Array of accounts held by the bank.
customers[]: Array of customers registered with the bank.
Methods:
openAccount(customer): Opens a new account for a customer.
Input: Customer object.
Output: None.
processTransaction(transaction): Processes a transaction initiated by a
customer.
Input: Transaction details.
Output: None.

Project 5: Hospital Management System


Description: Develop a Hospital Management System to manage patient records, appointments,
and medical staff.
Patient Class:
Attributes:
name: Name of the patient.
id: Unique identifier for the patient.
medicalHistory[]: Array of medical history records for the patient.
Methods:
scheduleAppointment(doctor, date): Allows patients to schedule appointments
with doctors.
Input: Doctor object, appointment date.
Output: None.
updateMedicalHistory(record): Allows doctors to update a patient's medical
history.
Input: Medical history record.
Output: None.
Outpatient Subclass:
Inherits from Patient class.
Additional Attributes:
nextAppointmentDate: Date of the next scheduled appointment for the
outpatient.
Additional Methods: None.
SpecialistDoctor Subclass:
Inherits from Doctor class.
Additional Attributes:
subSpecialization: Sub-specialization of the doctor.
Additional Methods: None.
Hospital Class (Containment):
Attributes:
patients[]: Array of patients admitted to the hospital.
doctors[]: Array of doctors employed by the hospital.
appointments[]: Array of appointments scheduled at the hospital.
Methods:
admitPatient(patient): Admits a patient to the hospital.
Input: Patient object.
Output: None.
scheduleAppointment(patient, doctor, date): Schedules an appointment
between a patient and a doctor.
Input: Patient object, doctor object, appointment date.
Output: None.

You might also like