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

Cat 1

Java programming questions

Uploaded by

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

Cat 1

Java programming questions

Uploaded by

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

CAT 1 - GROUP A

Paper 1 - Question 1

a) Briefly explain the meaning of the following terms as used in java programming. Give a
java code example for each case.
i) Class - A class is a template or blueprint for creating objects. It defines state (variables) and
behavior (methods) that an object will have.

public class Car {


String brand = "Toyota";
public static void main(String[] args) {
Car myCar = new Car();
System.out.println(myCar.brand);
}
}
Car is the class

ii) Variable - A variable is a container for data used to store values during program execution.

public class Variable {


public static void main(String[] args) {
int age = 25;
String name = "Alice";
System.out.println("Name: " + name + ", Age: " + age);
}
}
In the above code, age and name is the variable.

iii) Syntax Error - A syntax error occurs when code does not follow the rules of the Java
language, such as missing semicolons or incorrect syntax.
public class Syntax {
public static void main(String[] args) {
System.out.println("Hello, world!")
}
}
The above code is missing a semicolon as its syntax error.

b) Write java code statements to accomplish the following.


i) Declares two variables: Max and Min
- int Max, Min;
ii) Initializes the two variables with values 6 and 4 respectively
- Max = 6;
- Min = 4;
iii) Determines which value is larger among the two
- int larger = (Max > Min) ? Max : Min;
iv) Prints results
- System.out.println("The larger value is: " + larger);
v) Declare and initialize array
- int[] numbers = {1, 2, 3, 4, 5};

c) Give six characteristics of the Java programming language.

- Platform Independence: Java bytecode can run on any platform with a JVM (Java
Virtual Machine).
- Object-Oriented Language: Everything in Java revolves around objects and classes,
promoting code reuse and modular design.
- Security: Java provides built-in security features like bytecode verification and a security
manager.
- Rich API: Java comes with an extensive set of APIs for handling I/O, networking, and
data structures.
- Robust IDEs: Development tools like Eclipse and IntelliJ make it easier to develop, test,
and debug Java code.
- Omnipresent: Java is widely used across platforms, from web development to mobile
apps and backend services.

d) Write a simple Java program to explain the working for do...while loop, write the
expected output of your program.

public class Count {


public static void main(String[] args) {
int count = 0;
do {
System.out.println("Count: " + count);
Count++;
} while (count < 5);
}
}
Output :-
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

e) With a well written Java Program explain the difference between method overloading
and method overriding [6 Marks]
Method overloading occurs when multiple methods in the same class have the same name but
different parameters

class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int sum1 = calculator.add(5, 10);
System.out.println("Sum of two integers: " + sum1);
int sum2 = calculator.add(5, 10, 15);
System.out.println("Sum of three integers: " + sum2);
}
}

Method overriding allows a subclass to provide a specific implementation of a method that is


already defined in its superclass.

class Vehicle {
void start() {
System.out.println("Vehicle is starting");
}
}
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car is starting");
}
}

f) Briefly explain the following java code [4 marks]


public class Compute {
public static void main(String[] args) { int a,b,results,diff;
a = 10;
b = 5;
sum = a + b;
diff = a – b;
System.out.println(“sum is " + results); System.out.println(“diff is " + diff); }}

- The class in this code is Compute.


- There are four declared integer variables i.e a, b, results and diff and have values
10. 5, a+b and a-b respectively.
- a+b is stored in results while a-b is stored in diff.
- The program prints results using System.out.println(“sum is " + results);
- The program prints diff using System.out.println(“diff is " + diff);
Paper 4 - Question 1

a) Briefly explain the following terms in the context of Java programming. Write a sample
java code statement for each case
i) Variable - A variable is a container for data used to store values during program execution.

public class Variable {


public static void main(String[] args) {
int age = 25;
String name = "Alice";
System.out.println("Name: " + name + ", Age: " + age);
}
}
In the above code, age and name is the variable.

ii) Assignment operator - assigns the value on the right-hand side to the variable on the left-
hand side. Denoted by =
E.g int number = 10;
iii) Array - An array is a collection of elements of the same type, stored in a single memory
location.
E,g int[] numbers = {1, 2, 3, 4, 5};
iv) Syntax error - A syntax error occurs when code does not follow the rules of the Java
language, such as missing semicolons or incorrect syntax.

public class Syntax {


public static void main(String[] args) {
System.out.println("Hello, world!")
}
}
The above code is missing a semicolon as its syntax error.
(b) Briefly explain the following three versions of Java platform
- Java Standard Edition - Used for developing desktop applications and core Java programs. It
provides general-purpose programming
- Java Enterprise Edition - Used for building large-scale, distributed, and multi-tier applications.
It was created to extend the Java SE by adding a set of specifications that define capabilities
commonly used by enterprise applications.
- Java Micro Edition - Designed for developing applications for embedded devices and mobile
phones. It provides a subset of Java SE with additional libraries that help the device to operate on
limited resources and small footprints.

(c) State and explain four features of java programming language


- Dynamic- Java is more dynamic compared to C and C++. It can adapt to its evolving
environment. It allows programmers to link new class libraries, objects, and methods
dynamically. Java programs can have a large amount of run-time information that one can use to
resolve accesses to objects.
- Platform Independent - Java’s platform independence means that Java programs compiled on
one machine or operating system can be executed on any other machine or operating system
without modifications.
-Object-Oriented - Everything in Java is treated as an object, allowing for easy maintenance
and reusability of code.
- Robust - Java has strong memory management, exception handling, and type checking to
minimize errors.
- Multithreaded - Java supports multiple threads, enabling programs to perform multiple tasks
simultaneously.
d). Write a java class named employee that requests the user to enter the cost of an item
and computes a discount to be awarded. The discount is set at 5% of all purchased items (5
Marks).
public class Employee {
public static void main(String[] args) {
int cost = 100;
double discount = cost * 0.05;
System.out.println("Discount awarded: " + discount);
}
}
(e) Briefly explain the purpose of using interfaces in java programming
Multiple Inheritance: Java does not support multiple inheritance using classes, but interfaces
allow a class to implement multiple interfaces.
Abstraction: Interfaces define methods without providing implementations, ensuring that
subclasses provide their own logic.
Loose Coupling: Interfaces reduce dependencies between different parts of code, making it
easier to maintain and update.
Standardization: They ensure that different classes follow the same structure if they implement
the same interface.
(f). Write a java class that calculates the area of a triangle and print results
(Area=1/2*base*height)
public class Triangle {
public static void main(String[] args) {
int base = 10;
int height = 5;
double area = 0.5 * base * height;
System.out.println("The area of the triangle is: " + area);
}
}
(g). Write a java class that reads the elements of the following array known as students and
prints results
public class Students {
public static void main(String[] args) {
String[] students = {"Otieno", "Ann", "Job", "James"};
System.out.println("List of students:");
for (String student : students) {
System.out.println(student);
}
}
}
Paper 7 - Question 1
a) What are the basic characteristics of the HyperText Transfer Protocol? [4 marks]
- Stateless Protocol - Each request from a client to a server is independent; the server does not
retain information about previous requests.
- Request-Response Model - HTTP follows a client-server model where the client sends
requests and the server responds with the requested resources.
- Text-Based Communication - HTTP requests and responses are sent in plain text, making
them easy to read and understand.
- Media Independent - HTTP is media independent as long as both the client and server know
how to handle the contents in the data.
- It is connectionless- HTTP is also considered connectionless because network connections are
controlled at the transport layer, not at the application layer.
b) What are the benefits provided by JSP over Servlet? [4 marks]
- Simpler to Write and Maintain - JSP allows embedding Java code directly into HTML,
which is more intuitive for web developers compared to writing complete Java classes in
servlets.
- Separation of Concerns - With JSP, the Java code can be separated from HTML, making the
code cleaner.
- Maintainability - With JSP, changes to the presentation layer can often be made without
modifying the underlying Java code, making it easier to update web pages.
- Pre-Compiled Performance - JSPs are compiled into servlets by the server at runtime,
offering performance similar to servlets.
- Built-in Support for Web Elements- JSP has implicit objects like request, response, and
session, reducing the need to manually initialize these objects as in servlet.
- Support for Expression Language - JSP supports Expression Language, which allows for
easier access to data stored in JavaBeans, request parameters, and session attributes without
needing verbose Java code.
c) Write a program that uses JSP declaration tag to define a method which returns the
cube
of given number and calling this method from the JSP expression tag [5 marks]
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
d) Using codes as examples, describe the steps of creating a JavaFX application [7 marks]
1. Set up the JavaFX Environment: Ensure needed JavaFX libraries are added.
2.Create Main Class: This is where we should extend our Application.
3. Override the start Method: It is here that you will be setting up your UI.
4. Create UI Components: This will involve the use of the various kinds of controls, such as
Button, Label, Textfield e.t.c.
5. Setup Layout: Using the layout managers, set up your UI elements.
6. Create a Scene: Using the layout, create a Scene object and set it on the primary stage.
7. Launch the Application

// Step 1
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
//Step 2
public class HelloWorldApp extends Application {
//Step 3
@Override
public void start(Stage primaryStage) {
// Step 4
Label helloLabel = new Label("Hello, World!");
//Step 5
StackPane root = new StackPane();
root.getChildren().add(helloLabel);
//Step 6
Scene scene = new Scene(root, 300, 200);
primaryStage.setTitle("Hello World");
primaryStage.setScene(scene);
primaryStage.show();
}
//Step 7
public static void main(String[] args) {
launch(args);

Members

- Mireille Velma 22/05672


- Antony Kiragu 22/05697
- Victor Kyalo 22/05753
- Lloyd katiku 22/07351
- Munene Nicholas 22/05380
- Hellen kivuva 22/06076
- Winnie Nyakio 22/07047

You might also like