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

Cosc Final Assignment

Uploaded by

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

Cosc Final Assignment

Uploaded by

chy.ronit123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Question 1) Write a Java program to calculate the average value of

array elements.

public class ArrayAverage {

public static void main(String[] args) {

int[] numbers = {1, 11, 111, 1111, 11111};

double average = calculateAverage(numbers);

System.out.println("The average value of the array elements is: " + average);


}

public static double calculateAverage(int[] array) {

int sum = 0;

for (int num : array) {


sum += num;
}

double average = (double) sum / array.length;

return average;
}
}

Question 2) Write a Java program to test if an array contains ‘4385’


value.

public class ArrayContains {

public static void main(String[] args) {

int[] numbers = {771, 77777, 77977, 77, 777};

int valueToFind = 777;


boolean containsValue = contains(numbers, valueToFind);

if (containsValue) {
System.out.println("The array contains the value: " + valueToFind);
} else {
System.out.println("The array does not contain the value: " + valueToFind);
}
}

public static boolean contains(int[] array, int value) {

for (int num : array) {


if (num == value) {
return true;
}
}

return false;
}
}

Question 3) Write a Java program to find the index of an element in


the below array. Choose any element of your choice:
public class FindElementIndex {

public static void main(String[] args) {

int[] numbers = {12, 34, 56, 78, 910, 112, 1314, 1516, 1718};

int valueToFind = 1516;

int index = findIndex(numbers, valueToFind);


if (index != -1) {
System.out.println("The index of element " + valueToFind + " is: " +
index);
} else {
System.out.println("Element " + valueToFind + " is not found in the
array.");
}
}

public static int findIndex(int[] array, int value) {

for (int i = 0; i < array.length; i++) {


if (array[i] == value) {
return i;
}
}

return -1;
}
}

Question 4) Write a Java program to test if a double number is an


integer. Pick any number of your choice.
public class DoubleIsInteger {

public static void main(String[] args) {

double number = 11;

boolean isInteger = isInteger(number);

if (isInteger) {
System.out.println("The number " + number + " is an integer.");
} else {
System.out.println("The number " + number + " is not an integer.");
}
}

public static boolean isInteger(double number) {

return number == (int) number;


}
}

Question 5) Write a Java program to round up integer division


results. Pick any number of your choice.

public class RoundUpIntegerDivision {

public static void main(String[] args) {

int numerator = 1111;


int denominator = 1;

int roundedUpResult = roundUpDivision(numerator, denominator);

System.out.println("The rounded-up result of dividing " + numerator + " by "


+ denominator + " is: " + roundedUpResult);
}

public static int roundUpDivision(int numerator, int denominator) {

return (int) Math.ceil((double) numerator / denominator);


}
}
Question 6) Write a Java method to find the smallest number among
three numbers. Data: • Input the first number: 25 • Input the
Second number: 37 • Input the third number: 29 • Expected Output:
o The smallest value is 25.0

import java.util.Scanner;

public class SmallestNumberFinder {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Input the first number: ");


double firstNumber = scanner.nextDouble();

System.out.print("Input the second number: ");


double secondNumber = scanner.nextDouble();

System.out.print("Input the third number: ");


double thirdNumber = scanner.nextDouble();

double smallest = findSmallest(firstNumber, secondNumber, thirdNumber);

System.out.println("The smallest value is " + smallest);


}

public static double findSmallest(double num1, double num2, double num3) {

double smallest = num1;

if (num2 < smallest) {


smallest = num2;
}

if (num3 < smallest) {


smallest = num3;
}

return smallest;
}
}
Question 7) Write a Java method to display the middle character of
a string. Note: a) If the length of the string is odd there will be two
middle characters. b) If the length of the string is even there will be
one middle character. Sample Data: • Input a string: 350 • Expected
Output: o The middle character in the string: 5 • Input a string:
3501 • Expected Output: o The middle character in the string: 50

import java.util.Scanner;

public class MiddleCharacterFinder {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Input a string: ");


String inputString = scanner.nextLine();

String middleCharacter = findMiddleCharacter(inputString);

System.out.println("The middle character in the string: " + middleCharacter);


}

public static String findMiddleCharacter(String str) {

int length = str.length();


int middle = length / 2;

if (length % 2 == 0) {
return str.substring(middle - 1, middle + 1);
} else {
return str.substring(middle, middle + 1);
}
}
}

Question 8) Write a Java program to get a number from the user


and print whether it is positive or negative. Sample Data • Input
number: 35 • Expected Output : o Number is positive
import java.util.Scanner;

public class PositiveOrNegative {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Input number: ");


double number = scanner.nextDouble();

if (number > 0) {
System.out.println("Number is positive");
} else if (number < 0) {
System.out.println("Number is negative");
} else {
System.out.println("Number is zero");
}
}
}

Question 9) Write a Java program that takes three numbers from


the user and prints the greatest number. Sample Data: • Input the
1st number: 25 • Input the 2nd number: 78 • Input the 3rd number:
87 • Expected Output : o The greatest: 87

import java.util.Scanner;

public class GreatestNumberFinder {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Input the 1st number: ");


int firstNumber = scanner.nextInt();

System.out.print("Input the 2nd number: ");


int secondNumber = scanner.nextInt();

System.out.print("Input the 3rd number: ");


int thirdNumber = scanner.nextInt();

int greatest = findGreatest(firstNumber, secondNumber, thirdNumber);

System.out.println("The greatest: " + greatest);


}

public static int findGreatest(int num1, int num2, int num3) {

int greatest = num1;

if (num2 > greatest) {


greatest = num2;
}

if (num3 > greatest) {


greatest = num3;
}

return greatest;
}
}
Question 10) Write a Java program to print the results of the
following operations. Test Data: a. -5 + 8 * 6 b. (55+9) % 9 c. 20 + -
3*5 / 8 d. 5 + 15 / 3 * 2 - 8 % 3

public class MathOperations {

public static void main(String[] args) {

int result1 = -5 + 8 * 6;
int result2 = (55 + 9) % 9;
int result3 = 20 + -3 * 5 / 8;
int result4 = 5 + 15 / 3 * 2 - 8 % 3;
System.out.println("a. -5 + 8 * 6 = " + result1);
System.out.println("b. (55 + 9) % 9 = " + result2);
System.out.println("c. 20 + -3 * 5 / 8 = " + result3);
System.out.println("d. 5 + 15 / 3 * 2 - 8 % 3 = " + result4);
}
}

Question 11) what is the difference between default constructor and


parameterized constructor? Illustrate with an example.
Default Constructor

• A default constructor is a constructor that does not take any parameters. If no


constructors are defined in a class, the Java compiler automatically provides a default
constructor with no parameters.
• It is used to create an object with default or initial values.
• Takes no parameters.
• Initializes instance variables with default values or predefined values within the
constructor.

Parameterized Constructor

• A parameterized constructor is a constructor that takes one or more arguments. It allows


initializing objects with specific values provided at the time of object creation.
• It is used to create an object with user-defined values.
• Takes one or more parameters.
• Initializes instance variables with values provided as arguments.
Question 12) what is inheritance? What are the various kinds of
inheritance in Java? Illustrate with a diagram (use any tool of your
choice to draw the diagram, do not copy paste the diagram) and
explain.
Inheritance is a fundamental concept in object-oriented programming that allows a new class to
inherit properties and behaviors from an existing class. This promotes code reusability and
establishes a hierarchical relationship between classes. The various kind of inheritance in java
are as presented below;

1. Single Inheritance: A class (subclass) inherits from one superclass only.


2. Multiple Inheritance: A class inherits from more than one superclass. Note that Java
does not support multiple inheritance through classes to avoid complexity and ambiguity.
Instead, it supports multiple inheritance through interfaces.

3. Multilevel Inheritance: A class inherits from another class, which itself is a subclass of
another class, creating a chain of inheritance.
4. Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.

5. Hybrid Inheritance: A combination of two or more types of inheritance. Since Java does
not support multiple inheritance with classes directly, hybrid inheritance is usually
implemented using interfaces.
Question 13) what is a class? How does it serve as a blueprint for
objects, and how objects are instances of classes?

A class in programming, particularly in object-oriented programming (OOP), is a blueprint or


template for creating objects.

It serves as a blueprint for objects as;

A class specifies what data (properties) and behaviors (methods) the objects created from it will
have. For example, if you have a car class, it might define attributes like color and make, and
methods like drive() and brake().

An object is an instance of a class. When you create an object from a class, you are creating a
specific instance of that class with its own set of attribute values. For example, you might create
a car object called mycar with the color set to zblack and the make set to BMW. Mycar is an
instance of the car class.

Question 14) Explain the concept of Object-Oriented Programming


(OOP) in Java. What are its main principles? Illustrate with an
example wherever necessary.
Object-Oriented Programming (OOP) in Java is a programming paradigm that uses "objects" to
design and structure software. It emphasizes the use of objects and classes to model real-world
entities and their interactions. Here are the main principles of OOP in Java:

1) Encapsulation:

Encapsulation involves bundling data (attributes) and methods (functions) into a single unit,
known as a class. It restricts direct access to some components, which helps protect the object's
state and ensures that data is accessed and modified only through defined methods.

2) Inheritance:

Inheritance allows a new class (subclass) to inherit characteristics and behaviors from an existing
class (superclass). This promotes code reuse and establishes a hierarchical relationship between
classes, where the subclass inherits the properties and methods of the superclass.

3) Polymorphism:

Polymorphism enables objects to be treated as instances of their parent class rather than their
actual class. It allows methods to perform different tasks based on the object’s actual class type,
even though they share the same name.

4) Abstraction:

Abstraction involves hiding the complex implementation details and exposing only the necessary
features of an object. It simplifies interactions with objects by focusing on high-level
functionality, rather than on the intricate details of the implementation.

Question 15) What is Java and how is it different from other


programming languages?
Java is a high-level, object-oriented programming language developed by Sun Microsystems in
1995 and maintained by Oracle Corporation. It is designed to be platform-independent, meaning
that Java code is compiled into bytecode, which runs on any device with a Java Virtual Machine
(JVM). This portability sets Java apart from many languages that are specific to certain operating
systems or hardware. Java is also strongly typed, requiring explicit type declarations for
variables, which helps prevent type-related errors. Unlike languages like C or C++, Java handles
memory management through automatic garbage collection, reducing issues like memory leaks.
Additionally, Java's robust exception handling framework enhances the reliability of applications
by managing runtime errors effectively.
Question 16) What is the significance of the static keyword in Java?
Give an example.
The Static keyword in Java is used to define class-level members that are associated with the
class itself rather than with instances of the class. This means that static variables and methods
are shared across all instances of the class and can be accessed without creating an object of the
class. For example, a static variable such as PI in a utility class can be used to store a constant
value that remains consistent across all instances. Similarly, a static method like square can
perform operations that do not depend on instance-specific data and can be called directly using
the class name. This is useful for utility functions or constants that are relevant to the class as a
whole but do not require object instantiation. The use of the static keyword thus facilitates the
sharing of data and methods across all instances, simplifies access to common resources, and
allows for utility functions to be called without needing to instantiate the class.

Question 17) what are the various types of variables and explain
each type.
The various types of variables are explained below;

1) Local Variables:

Local variables are declared within a method, constructor, or block and are only accessible
within that method, constructor, or block. They are created when the method or block is executed
and destroyed when it finishes. They are Limited to the method or block where they are declared.
They Must be initialized before use.

2) Instance Variables:

Instance variables are declared within a class but outside any method. They are associated with a
particular instance of a class and represent the state of the object. They are accessible to all
methods and constructors in the class. Each object of the class has its own copy of instance
variables.

3) Class Variables (Static Variables):

Class variables are declared with the static keyword within a class. They are shared among all
instances of the class and belong to the class itself rather than to any particular instance. They are
accessible to all methods, constructors, and static blocks in the class. There is only one copy of a
static variable, regardless of the number of instances
Question 18) What is the Java Virtual Machine (JVM) and why is it
important?

The Java Virtual Machine (JVM) is a critical component of the Java programming environment.
It is an abstract computing machine that enables Java programs to run on any device or operating
system that has a JVM implementation. The JVM is important because of the following points
presented below;

1) Allows Java programs to run on any device or operating system with a JVM, enabling the
"write once, run anywhere" capability.
2) memory allocation and deallocation through automatic garbage collection, reducing the
risk of memory leaks and optimizing resource use.
3) Provides a secure execution environment with features like bytecode verification and a
security manager to prevent the execution of malicious code.
4) Includes a Just-In-Time (JIT) compiler that translates bytecode into native machine code
at runtime, enhancing the performance of Java applications.
5) Supports a robust exception handling mechanism to manage and respond to runtime
errors effectively, ensuring program stability.
Ques&on 19) Case Diagram

You might also like