0% found this document useful (0 votes)
4 views13 pages

Java Questions

The document consists of a series of Java programming questions and their corresponding answers, covering topics such as data types, control structures, exception handling, and object-oriented programming concepts. It includes questions about specific Java methods, syntax errors, and the purpose of various programming constructs. The answers provide explanations and code snippets to illustrate the concepts discussed.

Uploaded by

Mamta Sharma
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)
4 views13 pages

Java Questions

The document consists of a series of Java programming questions and their corresponding answers, covering topics such as data types, control structures, exception handling, and object-oriented programming concepts. It includes questions about specific Java methods, syntax errors, and the purpose of various programming constructs. The answers provide explanations and code snippets to illustrate the concepts discussed.

Uploaded by

Mamta Sharma
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

1) The size of double datatype in java is ___________bit.

2) ______________________ is a special method that every Java application must


have.
3) What is a byte code?
4) Name one front end and one Back-end application to create Web Applications.
5) __________loop run at least once.
6) Once the class is defined, we can create________ of the class and access its
members.
7) State TRUE or FALSE
binary()method is used to arrange an array of integers in ascending order.
8) Predict the output
double[]Qty = {46, 42, 13, 6.5, 87.5}; [Link](Qty[3]);
9) Java is case sensitive language. Justify the statement.
10) A ___________ in java is a group of related classes.
a. Method b. Package c. Constructor d. Variable
11) Which component is used to compile, debug and execute java program?
a. JVM b. JDK c. IDE d. JRE
12) ___________method takes a String as parameter and returns the equivalent
integer
13) Give the output of the following code segment
14) public class Main { public static void main(String[] args)
{ int day = 4;
switch (day) {
case 6:
[Link]("Today is Saturday");
break;
case 7
: [Link]("Today is Sunday");
break;
default: [Link]("Looking forward to the Weekend");
}}}
15) Find error and rewrite the correct code
i == 0;
while (i < 5) {
[Link](i)
i++;
16) Complete the code in JAVA using a loop to print "Yes" 5 times:
______ (int i = 0; i < 5; _______ )
{
______(”Yes”);
}
17) [Link] a single line Java code using String methods to perform the following
tasks
String cl = ‘‘class xii’’;
i. Convert the characters to capital letters.
ii. Find the total length of string.
iii. Add a word ‘‘toppers” at the end of original string.
b. What is the purpose of a constructor?
18) a. Name the user defined method in the code given below. Also predict the
output
static int myMethod(int x)
{ return ( 5 + x); }
public static void main(String[] args) {
[Link](myMethod(3)); }
b. Explain any two access modifiers.

Answers

1. The size of double datatype in java is 64-bit.


2. public static void main(String[] args) is a special method that
every Java application must have.
3. Bytecode is the intermediate, platform-independent code produced by the Java
compiler that runs on the JVM.
4. Web Application Components:
o Front-end: HTML / CSS / JavaScript.
o Back-end: Java (Servlets/JSP) / Python / PHP.
5. do-while loop runs at least once.
6. Once the class is defined, we can create objects of the class and access its members.
7. FALSE. The binarySearch() method is used to search for an element, while
[Link]() is used for ascending order.
8. Output: 6.5.
9. Justification: Java is case-sensitive because it treats identifiers with different
capitalization as distinct. For example, myVar and myvar are two different variables.
10.A Package in java is a group of related classes. (Option b) .
[Link] (Java Development Kit) is the component used to compile, debug, and execute
java programs. (Option b) .
[Link]() method takes a String as parameter and returns the
equivalent integer.
[Link]: Looking forward to the Weekend (Since day = 4 does not
match case 6 or case 7, the default block executes).
[Link] Correction:
o Error: i == 0; (Comparison instead of assignment) and missing semicolons.
o Correct Code:

int i = 0; // (Corrected assignment)


while (i < 5) {
[Link](i); // (Added semicolon)
i++;
}
******************************
1) Name any two primitive data types in Java.
2) In Java = = is a/an _________ operator. (a) Arithmetic (b) Relational (c)
Assignment (d) Logical
3) (iv) Alternate of if else is : (a) switch.. case (b) while (c) for (d) do while
4) (vii) __________ method of a String Class returns the count of characters present
in a String
(a) indexOf() (b) indexAt() (c) length() (d) isEmpty()
5) The __________ block is examined during execution to detect any exceptions that
may be thrown by any statements or any calls to methods within the block.
6) JVM stands for ___________.
7) The ___________ statement evaluates the test after executing the body of a loop.
8) if ((percentage > = 40)&& (percentage < 60))
{[Link]("PASSED with II Division");} Consider the above statement, &&
will check for both the conditions to be : (a) True (b) False (c) Any of the above (d)
None of the above
9) __________ can be used for Multi-line Comment entry.
(a) // (b) /* .... */ (c) ## (d) $$
10) All Java Statements must end with __________.
(a) / (b) * (c) ; (d) &
11) An error situation that is unexpected in the program execution and causes it to
terminate unexpectedly is called _________.
12) What is the purpose of comments in Java ?
13) The following code has some error(s). Rewrite the correct code underlining all
the corrections.
Int x,y
x=10;
For (x=20, x<10; x--)
Y = y-2;
[Link](y);
};
14) Explain Syntax error with the help of a valid example.
15) Write a code in Java to print the squares of numbers from 1 to 5 by using for
loop.
16) Mention any two main points of difference between while and do-while
statements. Also give the syntax of both.

Answers

1. Any two primitive data types: int and char.


2. In Java == is a/an: (b) Relational operator.
3. Alternate of if else is: (a) switch.. case.
4. Method of a String Class that returns the count of characters: (c) length().
5. The block examined during execution to detect exceptions: The try block.
6. JVM stands for: Java Virtual Machine.
7. Statement that evaluates the test after executing the body of a loop: The do-
while statement.
8. The && operator will check for both conditions to be: (a) True.
9. Used for Multi-line Comment entry: (b) /* .... */.
[Link] Java Statements must end with: (c) ;.
[Link] unexpected error that causes a program to terminate: An Exception.
[Link] of comments: To make the code more readable and explain the logic for
humans; they are ignored by the compiler.
[Link] Correction:
o <u>int</u> x, y; (Changed Int to lowercase and added ;)
o x = 10;
o <u>for</u> (x = 20; x < 10; x--) (Changed For to lowercase and
used ; as separators)
o <u>y</u> = y - 2; (Changed Y to lowercase to match declaration)
o [Link].<u>println</u>(y); (Changed displayln to
println)
o } (Removed unnecessary ; after the brace)
[Link] Error: An error that occurs when the code violates the grammatical rules of
Java, such as a missing semicolon.
o Example: int x = 10 (Missing the ; at the end).
[Link] code to print squares of numbers 1 to 5:

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


[Link](i * i); }

16. Differences between while and do-while:

 Evaluation: while checks the condition before the loop body (entry-controlled),
while do-while checks it after (exit-controlled).
 Execution: while may run 0 times, but do-while always runs at least once.
 Syntax:
o while(condition) { //code }
o do { //code } while(condition);

******************************
1) If a=20 and b=30 What will be the value of a%=b?
2) b. Identify the valid variable names from the following
Total marks , int , marks$ , marks4
3) What is the need of JVM?
4) Which member function of the Integer wrapper class allows access to the int
value held in it?
5) Sagar has declared an array whose last element is having an index/position as 10.
What would be the size of this array?
6) Rema wants to input the price of shoes as 999.99 .What should be the datatype
and size of the column price in the table?
7) What is an exception in java?
8) How can you write multiline comments in java program?
9) What is the purpose of wait () method in java threads?
10) What are the two ways to create a thread in java?
11) What is the difference between the following two java statements?
(a) int x=5;
(b) integer y= new integer(50);
12) What do we mean by scope of a project?
13) What will be the value of rem after the execution of the following code
snippet? why?
code =2;
switch(code)
{case 1: rem= 8;
case 2: rem= 9;
case 3: rem= 10; break;
case 4: rem= 11; break;}
14) Consider the following code
int x = 1;
while(x<=5);
x = x +1;
(a)Name the coding error shown in the above code.
(b) What is the reason of the error?
(c)Write correct java code.
15) What are String Class Methods in Java? Consider the statement
String name = ‘‘Hello World’’.
Write a single line Java code using String methods to perform the following :
(a) Convert the name to lowercase.
(b) Replace “Hello” by “Welcome” in the given string.
(c) Check whether the name contains ‘‘Sin’’ in it or not
(d) Add a new string ‘‘jackpot” at the end of original string
16) Write a code in java using a for loop to display all odd numbers between 1 to
10. Is for loop an entry controlled loop or exit control loop?
17) What is the need of a constructor in OOP? Explain all features of a constructor.

Answers

1. Value of a %= b: The value is 20. Since 20 divided by 30 gives a remainder of 20,


the modulus operator returns 20.
2. Valid Variable Names: The valid names are marks$ and marks4.
o Total marks is invalid due to the space.
o int is invalid because it is a reserved keyword.
3. Need of JVM: JVM (Java Virtual Machine) is required to provide a runtime
environment that can execute Java bytecode. It is what makes Java platform-
independent.
4. Integer Wrapper Member Function: The intValue() method allows access to
the primitive int value.
5. Array Size: The size would be 11. Since array indexing starts at 0, an element at
index 10 is the 11th element.
6. Datatype for Price: The datatype should be DECIMAL or NUMERIC.
7. Exception in Java: An exception is an unexpected error event that occurs during
program execution and disrupts the normal flow of instructions.
8. Multiline Comments: You can write them using the /* ... */ syntax.
9. Purpose of wait(): It is used in multithreading to make the current thread wait until
another thread invokes the notify() or notifyAll() method for that object.
[Link] ways to create a thread:
o By extending the Thread class.
o By implementing the Runnable interface.
[Link] between statements:
o (a) int x=5;: Declares a primitive integer variable.
o (b) integer y= new integer(50);: Creates an object of the Integer
wrapper class (Note: the class name should be capitalized as Integer).
[Link] of a Project: It defines the specific goals, deliverables, tasks, and deadlines that
constitute the boundary of the project.
[Link] of rem: The value will be 10.
o Why? Since code = 2, it matches case 2. Because there is no break
statement after case 2, it "falls through" to case 3, where rem becomes 10
and then hits a break.
[Link] Loop Error:
o (a) Name of error: Logical error / Syntax error.
o (b) Reason: The semicolon ; immediately after while(x<=5) creates an
empty loop body, causing an infinite loop because x is never incremented inside
the loop.
o (c) Correct Code:

int x = 1;
while(x <= 5) {
x = x + 1;
}

[Link] name = "Hello World":


o (a) [Link]();
o (b) [Link]("Hello", "Welcome");
o (c) [Link]("Sin");
o (d) name + "jackpot"; or [Link]("jackpot");
[Link] numbers 1 to 10:

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


if (i % 2 != 0) {
[Link](i);
}
}

The for loop is an entry controlled loop.

[Link] in OOP: A constructor is needed to initialize an object immediately


upon creation.
o Features: It has the same name as the class, no return type (not even void),
and is called automatically when an object is created.

**************************

1) Predict the output :


String myStr = "Welcome Users";
[Link]("New String:"+[Link]());
2) __________ statement in Java, allows to use a prebuilt class and its associated
methods from a package. 1(a) include (b) public (c) extend (d) import
3) The _______ blocks follow a try block. It contains the exception handler-specific
code that is executed when the exception occurs.
4) NeGP stands for ___________ .
5) What is a Compiler ?
6) Name any two Primitive datatypes in Java.
7) A ___________ is a group of statements written to perform a specific task.
8) (a) Method (b) Class (c) Comment (d) Variable
9) Predict the output of the given Java code :
String first_name = "Priyank";
String last_name = "Arora"
[Link](first_name.length()+last_name.length());
10) What will be the output of the following code if value of variable a is 1 ?
switch (a) {
case 0 : [Link]("Blue");
case 1 : [Link]("Red");
case 2 : [Link]("Orange"); break;
case 3 : [Link]("Black");
default : [Link]("transparent"); break; }
11) __________ members of a class cannot be accessed outside the class.
12) Name the method that is used to concatenate a string at the end of another
string in Java.
13) What is a Bytecode ?
14) Which of the following is/are not a keyword in JAVA ?
break, While, for, switch, Display
15) What is the purpose of using try and catch statements in JAVA ?
16) Explain any two methods of String class in Java with suitable example.
17) Rewrite the following program code using switch statement :
if (color == 10)
{ [Link]("Red"); }
else if (color == 20) {
[Link] ("Orange");
} else if (color == 30)
{ [Link] ("Green");
} else { [Link] ("Invalid"); }
18) Why is Java considered as an Object Oriented Programming language ? Explain
data members and member methods with the help of an example.
19) (i) ‘Java is a platform independent language’, justify the statement.
(ii) Give two relational operators and two logical operators in Java.
20) Write the output of following code:
(i) class production { int inp = 50; void change(int inp)
{ [Link]("Change"+[Link]); inp=inp+100; } public static void
main(String args[]) { production po=new production(); [Link]("before
change"+[Link]); [Link](500); [Link]("after change"+[Link]); } }
(ii) What are the two ways to write comments in Java ?

Answers

1. datatypes: int and boolean.


2. Group of statements for a specific task: (a) Method.
3. Predict the output: 12 (Priyank is 7 + Arora is 5).
4. Output if variable Predict the output: New String:WELCOME USERS.
5. Statement to use a prebuilt class: (d) import.
6. Blocks that follow a try block: The catch blocks.
7. NeGP stands for: National e-Governance Plan.
8. Compiler: A program that translates the entire source code written in a high-level
language into machine code or bytecode at once.
9. Two Primitive a is 1: Orange.
o Why? Since there is no break after case 1, it sets the text to "Red" and then
falls through to case 2, which sets it to "Orange" before hitting a break.
[Link] not accessed outside the class: Private members.
[Link] to concatenate: concat() or the + operator.
[Link]: An intermediate code generated by the Java compiler that is platform-
independent and executed by the JVM.
[Link] a keyword: While (it must be lowercase while) and Display.
[Link] of try and catch: To handle exceptions (runtime errors) so the program
doesn't crash unexpectedly.
[Link] String methods:
o toLowerCase(): Converts string to lowercase. Example:
"JAVA".toLowerCase() results in "java".
o length(): Returns the number of characters. Example: "Hi".length() is
2.
[Link] using switch:

switch (color) {
case 10: [Link]("Red"); break;
case 20: [Link]("Orange"); break;
case 30: [Link]("Green"); break;
default: [Link]("Invalid");
} [cite: 48, 49, 50]
[Link] Java is OOP: Because it organizes software design around data, or objects,
rather than functions and logic.
o Data members: Variables that hold the state (e.g., int age).
o Member methods: Functions that define behavior (e.g., void walk()).
[Link] Independent: "Write Once, Run Anywhere." Java code is compiled into
bytecode, which can run on any system with a JVM.
[Link]:
o Relational: ==, !=.
o Logical: &&, ||.
[Link] of code:
o before change 50.
o Change 50.
o after change 50.
o (Note: The value doesn't change because inp in the method is a local variable,
not the class variable).
[Link] ways to write comments: Single-line (//) and Multi-line (/* ... */)

***************************
1) Rohit wrote int x = 5; x += 3; in his Java program. What is the new value of x?
2) Name any two primitive data types supported by Java?
3) Which keywords are used to handle exceptions in Java?
a) throw, catch b) try, catch c) exception, catch d) final, catch
4) String myString = "Hello World";
[Link]([Link](6));
What will be the output?
a) W b) o c) r d) l
5) Which of the following is a correct way to declare a String variable in Java?
a) String name = "John"; b) string name = "John"; c) Str name = "John";
d) String name == "John";
6) Differentiate between [Link]() and [Link]() in Java.
7) Which of the following is the correct syntax to define a user-defined method in
Java?
a) void methodName() { /* code */ } b) methodName void() { /* code */ }
c) function methodName() { /* code */ } d) define methodName() { /* code */ }
8) The bytecode runs on the _______________________.
9) Which of the following is an invalid variable name in Java?
a)_temp b)total#value c)$price d)username
10) What is the output of the expression 10 % 3?
11) Give the output of the following code segment
int n = 3;
for (inti = n; i>= 1; i--) {
[Link](i * i + " ");
}
12) What are comments in Java programs and why are they important?
13) Nitya is creating a Java program to calculate the area of a rectangle. She writes
the following code:

a) What does the method calculateArea() do in this program?

b) How is the object of the class created?

c) What will be the output of the program?

14) Write a Java code using String methods to perform the following tasks:
String str = "java programming";
i. Convert all characters to lowercase.
ii. Find the total number of characters in the string.
iii. Append the word "rocks" at the end of the string.
iv. Replace the word "java" with "Python".
15) What are multithreaded programs in Java? What are the two ways by which
these threads can be created?
16) a) Define arrays.
b) Write a program to:
i) Create a string array Names containing five names.
ii) Display each name using a while loop.
c) What happens if a program tries to access an array element using an index that
is outside the valid range?

Answers

1. New value of x: The new value is 8 (5 + 3).


2. Two primitive data types: int and boolean (or char, float).
3. Keywords used to handle exceptions: (b) try, catch.
4. Output of [Link](6): (a) W.
o Explanation: In "Hello World", index 0 is 'H', index 5 is the space, and index 6
is 'W'.
5. Correct way to declare a String variable: (a) String name = "John";.
o Note: Options (b) and (c) use incorrect case or abbreviations, and (d) uses a
comparison operator.
6. Difference between print() and println(): print() displays text on the
same line, while println() moves the cursor to a new line after printing.
7. Correct syntax to define a user-defined method: (a) void methodName()
{ /* code */ }.
8. The bytecode runs on the: JVM (Java Virtual Machine).
9. Invalid variable name: (b) total#value.
o Reason: Variable names cannot contain special characters like '#' except for '$'
or '_'.
[Link] of 10 % 3: 1.
o Reason: 10 divided by 3 leaves a remainder of 1.
[Link] of the code segment: 9 4 1.
o Reason: The loop starts at 3 and goes down to 1, squaring each number (3^2,
2^2, 1^2).
[Link] are comments and why are they important?: Comments are non-executable
notes in the code. They are important for explaining logic, making the program easier
to read, and helping in debugging.
[Link] Program Answers:
o (a) Function of calculateArea(): It calculates the area of the rectangle by
multiplying the length and width variables and returning the result.
o (b) Object creation: An object is created using the new keyword: Rectangle
r1 = new Rectangle();.
o (c) Output: Area: 50.
[Link] methods for str = "java programming":
o i. [Link]();.
o ii. [Link]();.
o iii. [Link]("rocks"); or str + "rocks";.
o iv. [Link]("java", "Python");.
[Link] programs: Programs that allow multiple parts (threads) to run
concurrently within a single process.
o Two ways to create: Extending the Thread class or implementing the
Runnable interface.
[Link] Section:
o (a) Define arrays: An array is a collection of similar data types stored in
contiguous memory locations.
o (b) Program (names and while loop):

String[] Names = {"Amit", "Sita", "Rohan", "Nitya",


"Karan"}; [cite: 152]
int i = 0; [cite: 153]
while(i < [Link]) { [cite: 153]
[Link](Names[i]); [cite: 153]
i++; [cite: 153]
}

o (c) Invalid index access: The program will throw an


ArrayIndexOutOfBoundsException and terminate unexpectedly.

********************

You might also like