## Java questions and its answers

Start with the following pseudo-code which calculates the sum of the elements of an array. We want an algorithm that determines whether the sum of the elements of an array of positive numbers exceeds 100. In addition, we want an efficient algorithm: the algorithm should access as few elements of the array as possible. Produce an accurate pseudo-code and explain your solution. You can explain the code in any form you like, as long as your explanations are clear.
Entries:
Table of positive numbers: table

Variables :
Integer: iterator = 0;

Outings:
Number: sum = 0;

AS ITERATOR < the length of the table MAKE
sum = sum + table [iterator];
iterator = iterator + 1;
ENDS AS

Hint 1: Your algorithm must return either True or False.
Hint 2: your algorithm must work even if the array is zero long.
Clue 3: Imagine being given this problem. You are given a large table (containing, say, a million elements) and asked to determine, as quickly as possible, if the sum of the non-negative values in the table exceeds 100. What would you do? Explain exactly what you would do in this situation.

We have to write a pseudocode that tells whether the sum of elements of positive numbers exceeds 100 or not and our algorithm should access minimum elements of the array.

Pseudocode:
boolean isSumGreaterThan100( int[] arr ) {
int  sum = 0;
for ( int i = 0; i < arr.length ; ++ i ) {
If ( arr [ i ] > 0 ) {
sum += arr [ i ];
}
If ( sum > 100 ) {
return true;
}
}
return false;
}

In this algorithm we start adding the positive elements in the sum variable until the value of the sum variable is less than 100. Once it becomes greater than 100 the algorithm returns true and gets terminated.

We want to display numbers from 0 to 100 on the screen (including 0 but excluding 100), displaying "Fizz" when the number is divisible by 3 and "Buzz" when the number is divisible by 5.
...
2
3 Fizz
4
5 Buzz
6 Fizz
...
A student offered us the following solution. It is incorrect. Explain the error and offer a corrected version.
Entries:
Maximum value: 100;

Variables :
Integer: iterator = 0;

Outputs: on screen

AS ITERATOR < 100 DONE
displays the iterator value on the screen
IF iterator is divisible by 3 THEN
displays "Fizz" on the screen
IF NOT IF iterator is divisible by 5 THEN
displays "Buzz" on the screen
END SI
iterator = iterator + 1
ENDS AS

In the given pseudocode the error is in the AS statement. When the value of the iterator is greater than or equal to 100 then it should be done.

Here is the correct pseudocode:

Entries:
Maximum value = 100
Variables:
Integer: iterator  = 0
Output: on Screen

As iterator >= 100 DONE
Display the iterator value on screen
If iterator is divided by 3 THEN
Display “Fizz” on the screen
Else if iterator is divided by 5 THEN
Display “Bizz” on the screen
END SI
Iterator += 1
END AS

Please create a class and its methods for calculating the area and perimeter of the circle. You must have 3 methods: 1 constructor receiving a radius, the method for calculating the area and the method for calculating the perimeter. The class must be named Circle.
If the code of your solution is not valid Java, if it does not compile, a score of zero may be assigned. To pass this course, you must be able to write functional and correct Java code.
Hint 1: Your class does not have to include a method called hand. The main method is required to run a program, but is not required to compile a class. All Java classes must be able to compile without errors, but in a software project, there may be only one main function (or even none) and thousands of classes.
Hint 2: Your code must contain a manufacturer. A constructor in Java is a function that has the name of the class. In this case, since your class is named Circle, the constructor must be named Circle.
Hint 3: Apart from the main method which you can omit, your code should not need the static keyword.
Warning: You must submit your work as a PDF document, not as a set of Java files. To facilitate correction, make sure that your code can be copied and pasted from the PDF document. Do not use screen captures.

Circle.java

public class Circle {
throw new IllegalArgumentException("Radius can't be less than zero");
}
}

public double getArea() {
}

public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
Explanation:
In the above java code, the class name is Circle, which has one private double variable which stores the radius of the circle. We made radius as private because it can be used in this class only. The Constructor of this class takes a parameter radius and assigns this value to the private member variable radius. The getArea method doesn’t take any parameter and return the area of the circle of given radius. The getParemeter method is the same as the getArea method and it returns the parameter of the circle.

A programmer wants to represent the value 10.000000000000001 in Java. He has written the following program. Execute the program and explain the result. A two-line explanation may suffice.

class Main {
public static void main(String[] args) {
double x = 10.000000000000001;
System.out.println(x);
x =  10.000000000000006;
System.out.println(x);
x =  10.000000000000008;
System.out.println(x);
}
}

The output of this program shows 10.0 . It didn’t show as 10.00000000000000001 because the compiler followed the 32 bit precision so it showed at most 15 digits after the decimal.

What will be the value of 'a' after the following lines of code and why?
int i = 3;
int a = i++;

int i = 3;
int a = i ++;
The value of a will be 3. Because i is followed by a post-increment operator, which first assigns the value of i in a then increments the value of i by one.

What will be the value (of the string variable) displayed by the System.out.println(string) line in the code below and why? Give a concise answer in a few sentences.

public class TestMethode {
public static void test(String test) {
test = test + test;
}
public static void main(String[] args) {
String chain = "test";
test(chain);
System. out. println(chain);
}
}

The value of the string variable displayed by the System.out.println() line in the code will be “chain”. Because in java the object is passed by reference and when the string object is passed in the test() method it doesn't change the object value, it refers to a new object. So, the old string object will remain unchanged.

What will be the value of the integer variable at the end of the next code and why?
boolean a = false;
boolean b = false;

int integer = (! a && (b | ! a)) ? 10 : 20;

The value of the integer will be 10. Because the expression of the ternary operator will be true so that the first expression will be assigned the integer variable.

Explain in detail the difference between the following two implementations. Your explanation should include a sample code illustrating the difference between the two pieces of code.

First code:
public class Bonhomme {
public static String name;
public Bonhomme(String n) {
name = n;
}
}

Second code:
public class Bonhomme {
public String name;
public Bonhomme(String n) {
name = n;
}
}

In the first code the String value name is static type which means it belongs to the Class. We can access a static member variable from the non-static method but we can’t access the non-static member from the static method. So, that both the code will compile successfully.
Sample Example:

public class Vehicle {
public static int speed;
public int numbeOfVachile;

public static int getSpeed() {
return speed;
}
}

Write a Java program that calculates the sum of numbers from 1 to 1,000,000 (including 1 and 1,000,000) but omitting numbers that are divisible by three and numbers whose hundredth digit is 2 or 3 (for example 1200 or 3312). Explain your solution. Work submitted without sufficient explanation may be given a score of zero, with no right to retake it. You must justify all the qualifiers used (private, public, protected, static): you cannot use the keyword "static" without justifying it.
Please note: you must submit your work as a single PDF file (not as a Java file).

Hint: the operators / and % are useful for this problem.
Hint: can the sum be represented by a variable of type int? Be sure to discuss this in your solution.

To make the correction easier, make sure your code can be copied and pasted from the PDF document. Do not use screen captures.
The course includes several examples with solutions. However, the solutions of graded papers are never passed on in this course: if you have any questions about your results, you can ask the teacher. Be sure to ask specific questions, and take the time to review the marker's feedback. (Hint: if you ask for the solutions to your graded work, you are indicating that you have not read the instructions correctly).
If the code of your solution is not valid Java, if it does not compile, a score of zero may be assigned. To pass this course, you must be able to write functional and correct Java code.

public class Solution {
public long getSum() {
long sum = 0;
for(int i=0; i<=1000000; ++i) {
if(sum % 3 == 0 || isHundredthDigit2or3(i)) {
continue;
}
sum += i;
}
return sum;
}

private boolean isHundredthDigit2or3(int number) {
int hundredthDigit = number % 1000;
return hundredthDigit == 2 || hundredthDigit == 3;
}
}

We are calculating the sum in getSum() method which calculates the sum of integers from 1 to 1,000,000 omitting the numbers which are divisible by 3 and whose hundredth palace digit is 3 or 3.  For omitting the numbers which have hundredth place digit is 2 or 3, we made a isHundredthDigit2or3(int number) helper method, which is a private method because we are only using this method in the class and this method return whether the number hundredth place digit is 2 or 3 is or not. For checking the divisibility of a number by 3, we just use number % 3 == 0, if any of these conditions are matched, we skipped that number from adding into sum.
The sum variable is very large and can’t fit in the integer type so we make it long type. In the last we return the sum variable.

Write a Java program that displays all 4-character strings on the screen in lexicographical order (also called the dictionary order). It should display one 4-character string per line. Only characters a, b, c, d are allowed within strings, but you can reuse the same character more than once within a string. Within the same string, the character 'b' must always be immediately followed by the character 'a'. A single string cannot contain both the 'd' and the 'a' character. Your program must end with the number of strings displayed on the screen. Your program receives nothing as input. The code of your program must not contain pre-calculated strings: it must generate them at runtime. Your program should not contain more than 200 short lines of code.
Explain your solution. Work submitted without sufficient explanation may be given a score of zero, with no right to retake it. You must justify all the qualifiers used (private, public, protected, static): you cannot use the keyword "static" without justifying it.
There are several ways to solve this problem. Perhaps the simplest way is to have several nested loops.
Hint: The result of your program must be the same every time you run it.
Hint: a character in Java has the type char.
Hint: a string in Java has the type String. This type is immutable.
Hint: given a string of characters s, the 3rd character can be accessed with the syntax s.
Hint: a string can be created from two characters c1 and c2 with the syntax Character.toString(c1) + Character.toString(c2).
Hint: the total number of channels displayed is a mathematically determined value, it will be the same for all correct solutions of this problem.
If the code of your solution is not valid Java, if it does not compile, a score of zero may be assigned. To pass this course, you must be able to write functional and correct Java code.
Comment: Some students find it difficult to understand the instruction: "the character 'b' must always be immediately followed by the character 'a'". You should be able to understand this logical constraint. For example, you shouldn't wonder for a long time if a string can end with the 'b' character. The answer comes directly from the instruction.

Here is the code of the given problem:

public class Solution {
public static void main(String[] args) {
String s = "abcd";
for(int i=0; i<4; ++i) {
for(int j=i; j<4; ++j) {
for(int k = j; k<4; ++k) {
for(int l =k; l<4; ++l) {
String res = s[i] + s[j] + s[k] + s[l];
int posOfb = res.find('b');
if(posOfb != -1) {
int posOfa = res.find('a');
if(posOfa - posOfb != 1) {
continue;
}
}
System.out.println(res);
}
}
}
}
}
}

In this solution we simply use four for loop in which the first loop starts from 0 to 4 and the other loop from position of current for loop to 4 and third loop from start of second loop to 4 and so on to get the dictionary order of string. Then after getting the string we check if the position of “b” is followed by “a'' or not if it is not followed then we skip and if it is follow then we print the current string.

Write a Java program that displays all 4-character strings on the screen in lexicographical order (also called the dictionary order). It should display one 4-character string per line. Only characters a, b, c, d are allowed within strings, but you can reuse the same character more than once within a string. Within the same string, the character 'b' must always be immediately followed by the character 'a'. A single string cannot contain both the 'd' and the 'a' character. Your program must end with the number of strings displayed on the screen. Your program receives nothing as input. The code of your program must not contain pre-calculated strings: it must generate them at runtime. Your program should not contain more than 200 short lines of code.
Explain your solution. Work submitted without sufficient explanation may be given a score of zero, with no right to retake it. You must justify all the qualifiers used (private, public, protected, static): you cannot use the keyword "static" without justifying it.
There are several ways to solve this problem. Perhaps the simplest way is to have several nested loops.
Hint: The result of your program must be the same every time you run it.
Hint: a character in Java has the type char.
Hint: a string in Java has the type String. This type is immutable.
Hint: given a string of characters s, the 3rd character can be accessed with the syntax s.
Hint: a string can be created from two characters c1 and c2 with the syntax Character.toString(c1) + Character.toString(c2).
Hint: the total number of channels displayed is a mathematically determined value, it will be the same for all correct solutions of this problem.
If the code of your solution is not valid Java, if it does not compile, a score of zero may be assigned. To pass this course, you must be able to write functional and correct Java code.
Comment: Some students find it difficult to understand the instruction: "the character 'b' must always be immediately followed by the character 'a'". You should be able to understand this logical constraint. For example, you shouldn't wonder for a long time if a string can end with the 'b' character. The answer comes directly from the instruction.

The complete code is:

import java.io.*;

class Main {
public static void main(String[] args) throws IOException {
File FichierALire = new File("partie1.txt");
// Nous avons les fichiers partie1.txt,
// partie2.txt et partie3.txt.
int mat[][] = new int;

for(int i=0; i< sArr.length; ++i) {
int triplet = Integer.parseInt(sArr[i]);
int value = triplet % 10;
triplet /= 10;
int col = triplet % 10;
triplet /= 10;
row = triplet;

mat[row][col] = value;
}

} catch (FileNotFoundException exception) {
System.out.println(" Fichier introuvable!");
}
}
}

In the code first we take the whole line from bufferedreader line the split the triplet using String.Spit(“ “) method and stored in the sArr and then for every triplet of the sArr we extract the row value, col value and the sudoku value then stored in the corresponding row and column of the matrix. Matrix is a 2 - D array of  9 rows and 9 columns.

What are the interfaces in Java for? Use the previous question (2) as a basis for discussion. Maximum 5 sentences.

Interfaces help to achieve abstraction, it is a blueprint of a class. The interface has some static constants and the abstract method. The method signature should be the same in all the classes which implement the interface but the definition of the methods should be according to the class. In the previous question Shape is an interface which has an abstract method called resize and the resize method definition is different in both class Circle and Square.

Share:

## Computer Science Graph Question and Answer

### Question 1. Consider the above graph G = (V, E) representing air flight network. Where V represents set of vertices of graph, each vertex represents an airport, and E represents set of edges, edge represents flight routes from one airport to another. The weights (numbers) on each edge represents distance from one airport to another.

A. Represent the given air flight network using adjacency matrix and adjacency list.

B. Discuss the advantages and disadvantages of representing the above flight network using adjacency matrix and adjacency list when considering that following operations are to be performed on flight network.
1. Add airport in flight network
2. Remove airport from flight network
3. Add route in flight network
4. Remove route from flight network
1. Adding airport in flight network

If we will add an airport then we have to add one node in the graph, for adding a node in adjacency matrix we have to create a new matrix of size greater than one of previous matrix which takes O( n * n ) time complexity and if we have to add a new node in adjacency list then we have to just increase the size of adjacency list by one so the Time Complexity in this case will be just O( 1 ).

2. Removing airport from flight network

Removing the airport from the flight network will take the same performance as adding an airport from adjacency matrix and adjunct list respectively. In this case we have to reduce the size of adjacency matrix and adjacency list instead of increase.

3. Adding route in flight network

To add a route between two airports, we have to add an edge between the two airports of the graph. Adding a new edge in adjacency matrix representation of matrix, we have to just modify one variable of the matrix, i.e. if we have to add edge between node A and node B and the distance between A and B is C then we have to change the value of matrix[A][B] to C from 0. Which takes O(1) Time complexity. To an edge in adjacency list representation of the graph we need to add a new node in node A as well as node B, which takes O(n) Time complexity in the worst case.

4. Removing route from flight network

Removing an edge from the graph takes the same time complexity as adding in the graph. In the adjacency matrix we have to change matrix[A][B] from C to 0 and in the adjacency list we have to remove node A from node B and node B from node A.

C. Traverse the given flight network using breadth first traversal (BFS) and depth first traversal (DFS).

There may be multiple arrangements of nodes in the BFS or DFS traversal of a graph.
We are starting traversal from node A of graph.

One of the BFS traversal of the graph:
A
B-> F-> D
C-> E
One of the DFS traversal of the graph:
A -> B -> D -> E -> C -> F

D. Discuss any two differences obtained/observed when traversing the flight network using breadth first traversal and depth first traversal techniques.

In BFS traversal the traverse proceeds level by level, first the start node is traversed then its adjacent nodes are traversing and so on until all nodes of the graph are visited.

In DFS traversal follow first a path from the starting node to ending node then another path from start to end until all nodes are visited.

Share: