Revision Of Java Concepts - Questions & Answers
EXERCISEPart A : Objective Type Questions
1. An ........................ is an identifiable entity with some characteristics and behaviour.
(a) Object
2. ........................ is the way of combining both the data and the functions that operate on that data under a single unit.
(b) Encapsulation
3. A ........................ is a group of objects that share common properties (characteristics), relationships and behaviours.
(b) class
4. The state or characteristics of an object is stored in ........................ .
(a) data variables
5. The ability of a message or data to be processed in more than a single form is also called ........................ .
(d) Polymorphism
6. The source code in Java has ........................ extension.
(b) .java
7. The tokens supported by Java are ........................ .
(d) All of these
8. ........................ are a predefined set of words that have special meanings within the compiler.
(b) Keywords
9. int, float, boolean, char, byte, short, long, and double are ........................ types.
(b) Primitive
10. The value of a ........................ can change any number of times during the course of the program.
(a) variable
11. An assignment operator can be used to assign ........................ to a variable.
(c) Both
12. In Java, when the + operator is used with Strings, it will perform ........................ of the strings.
(a) concatenation
13. Mathematical functions in Java are found in Math class in ........................ package.
(b) java.lang
14. A ........................ is a group of statements enclosed within curly braces {..}.
(a) block
15. Control structures are broadly categorised into ........................ .
(d) All of these
16. ........................ control structures are special control structures that execute a set of statement/s based on the result of a single condition.
(b) Conditional
17. The if statement consists of a ........................ expression followed by a statement or block.
(c) Boolean
18. When a complete if or if- else statement is written within another if statement, it is known as ........................ statement.
(b) Nesting if
19. The ........................ is a selective structure where the value of expression is matched with the list of constants.
(c) switch
20. The ........................ statement takes the control out of the switch block after the execution of the case block.
(a) break
21. The block following if statement is executed only when the condition is ........................ .
(b) true
22. Switch statement cannot handle ........................ point tests.
(a) floating
23. The ........................ loop will executes at least once though the condition is not fulfilled.
(a) do-while
ASSIGNMENT
Part A : Fill In The Blanks
1. Real-world object contains characteristics and behaviour.
2. A software object's state is stored in variables.
3. A software object's behaviour is exposed through methods.
4. Java programs can be of the following types : compiled and interpreted.
5. A blueprint for a software object is called a class.
Part B : Very Short Questions
1. Give two disadvantages of OOP approach.
1. OOP programs generally occupy more memory than procedural programs. 2. They can have a steeper learning curve and be overly complex for simple problems.
2. What is an instance?
An instance is a specific, identifiable object created from a class blueprint, possessing its own unique state and values.
3. What is the difference between a class and an object?
A class is a blueprint or template defining common properties and behaviours, whereas an object is an identifiable entity and a specific instance of that class.
4. State the main characteristics of OOP.
The main characteristics are Data Abstraction, Data Encapsulation, Inheritance, and Polymorphism.
5. What is inheritance? Write its benefits.
Inheritance is the process by which objects of one class acquire the properties of objects of another class. Its main benefit is code reusability.
6. What is bytecode?
Bytecode is the intermediate code generated by the Java compiler, which is platform-independent and executed by the Java Virtual Machine (JVM).
7. How is Java platform independent?
Java compiles source code into intermediate bytecode rather than machine-specific code, which allows it to run on any device equipped with a JVM.
8. Give an example of char and floating type constants.
char constant: 'A'
floating type constant: 3.14f
9. Define the term data type. List the different data types in Java.
A data type refers to the type of data a variable can hold, dictating its memory allocation. The two main categories are Primitive (int, float, boolean, char, byte, short, long, double) and Reference (arrays, classes, interfaces) data types.
10. What do you mean by scope of a variable?
The scope of a variable is the region or block of code within a program where the variable is declared, accessible, and valid.
11. Determine which of the following are valid literals with reasons and type.
(i) 0.5 (ii) 9.3e12 (iii) 27,822 (iv) 'a' (v) '\n' (vi) 8.15 PM" (vii) 20543
(i) Valid floating-point literal.
(ii) Valid floating-point literal in exponential notation.
(iii) Invalid, as commas are not allowed in numeric literals.
(iv) Valid character literal enclosed in single quotes.
(v) Valid character literal representing an escape sequence.
(vi) Invalid string literal, missing the opening double quote.
(vii) Valid integer literal.
12. What are expressions? In what direction are they evaluated?
Expressions are constructs made up of variables, operators, and method invocations that evaluate to a single value. They are generally evaluated based on operator precedence and associativity (mostly from left to right).
13. Which package supports the mathematical functions in Java?
The java.lang package supports mathematical functions via the Math class.
14. Write Java equivalent expressions for the following :
(i) Vol= 3.1459 r2 h/3
(ii) Fn = 0.5 if x <= 30 otherwise Fn=0
(iii) To compute the sum of x20 and x
(i) Vol = (3.1459 * r * r * h) / 3.0;
(ii) Fn = (x <= 30) ? 0.5 : 0.0;
(iii) double sum = Math.pow(x, 20) + x;
15. What is nested if ?
When a complete if or if-else statement is written within another if statement, it is known as nesting of the if statement.
16. In a concatenated if statement, how many blocks will get executed ?
In a concatenated (ladder) if-else statement, only one block gets executed – the one corresponding to the first true condition.
17. Rewrite the following program code using switch case.
char tickettype ;
if(tickettype == 'A')
System.out.println("AC ticket");
else if (tickettype== '2')
System.out.println("Second class Sleeper ticket");
else if (tickettype== 'U')
System.out.println("Unreserved ticket");
switch (tickettype) {
case 'A':
System.out.println("AC ticket");
break;
case '2':
System.out.println("Second class Sleeper ticket");
break;
case 'U':
System.out.println("Unreserved ticket");
break;
}
18. Give the output for the following code and remove errors (if any).
(i) Assuming the value of x is 10 and 15.
if (x ==10)
System.out.println( "true");
else
System.out.println("false");
Errors: None. Output if x=10: true. Output if x=15: false.
(ii) Assume the values of p is (a) 25 (b) 30 (c) 12
void main(){
int p;
p = 25; // code checking with first sample value
if(p % 5 ==0)
{
if(p % 15 ==0)
System.out.println("divisible by 15");
else
System.out.println("divisible by 5 only");
}
else
{
System.out.println("Not divisible by 5");
}
}
(a) If p=25: Output is "divisible by 5 only"
(b) If p=30: Output is "divisible by 15"
(c) If p=12: Output is "Not divisible by 5"
(iii) Assume the value of aNum is 3.
if (aNum >= 0)
if (aNum == 0) System.out.println("first string");
else System.out.println("second string");
System.out.println("third string");
Output:
second string
third string
19. (i) Complete the following program and run it by initializing the char with different values of variable ch.
public class Nestedif
{
public static void main(String args[])
{
char ch='#'; // variable initialized with a character
if((ch<=56 && ch>=48)||(ch<=91 && ch>=65)||(ch<=123 && ch>=97))
{
if((ch<=91 && ch>=65)||(ch<=123 && ch>=97))
{
if(ch<=91 && ch>=65)
System.out.println("________________");
else
System.out.println("________________");
}
else
{
System.out.println("________________");
}
}
else
{
System.out.println("________________");
}
}
}
Answer to fill the blanks:
First blank (Line 13): Upper case Alphabet
Second blank (Line 15): Lower case Alphabet
Third blank (Line 19): Number
Fourth blank (Line 23): Special Character
(ii) Complete the following program code to define the class, main() method and also intialise the value of a variable tickettype to A, 2 or U.
class ________________
{
public _______________
{
char tickettype= ________________ ;
if(tickettype== 'A')
System.out.println(" AC ticket");
else if (tickettype== '2')
System.out.println(" Second class Sleeper ticket");
else if (tickettype== 'U')
System.out.println(" Unreserved ticket");
}
}
Answer to fill the blanks:
First blank: Ticket (or any valid class name)
Second blank: static void main(String args[])
Third blank: 'A' (or '2' or 'U')
20. Define abstraction.
Abstraction refers to the act of representing essential features without including the background details or explanations.
21. int res = 'A';
What is the value of res?
65 (The ASCII value of 'A')
22. State the difference between while and do while loop.
A while loop evaluates the condition before executing the loop body (entry-controlled loop), so it may not run at all if false initially. A do-while loop evaluates the condition after executing the loop body (exit-controlled loop), guaranteeing at least one execution.
23. system.out.print ("BEST");
system.out.println("OF LUCK");
Choose the correct qption for the output of the above statements
(i) BEST OF LUCK
(ii) BEST
OF LUCK
(i) BEST OF LUCK
24. Write the return data type of the following function.
log()
double
25. What is the value of y after evaluating the expression given below?
y+ = ++y + y-- + --y; when int y=8
The value of y is 33.
26. Give the output of the following:
(i) Math.floor (-4.7)
(ii) Math.ceil(3.4) + Math.pow(2, 3)
(i) -5.0
(ii) 12.0
27. Convert the following if else if construct into switch case
if( var==1)
System.out.println("good");
else if(var==2)
System.out.println("better");
else if(var==3) System.out.println("best");
else
System.out.println("invalid");
switch (var) {
case 1:
System.out.println("good");
break;
case 2:
System.out.println("better");
break;
case 3:
System.out.println("best");
break;
default:
System.out.println("invalid");
}
28. Rewrite the following using ternary operator:
if (bill>10000)
discount = bill * 10.0/100;
else
discount = bill * 5.0/100;
discount = (bill > 10000) ? (bill * 10.0 / 100) : (bill * 5.0 / 100);
29. Give the output of the following program segment and also mention how many times the loop is executed:
int i;
for (i = 5; i > 10; i++)
System.out.println(i);
System.out.println(i*4);
Output: 20
The loop is executed 0 times.
30. Name any two basic principles of Object-oriented Programming.
1. Data Encapsulation
2. Inheritance
31. Write a difference between unary and binary operator.
A unary operator requires only one operand (e.g., ++), whereas a binary operator requires two operands (e.g., +).
32. Write the memory capacity (storage size) of short and float data type in bytes.
short: 2 bytes
float: 4 bytes
33. Identify and name the following tokens:
(i) public (ii) 'a' (iii) == (iv) { }
(i) Keyword
(ii) Literal (Character constant)
(iii) Operator (Relational operator)
(iv) Punctuator / Separator
34. Differentiate between if else if and switch-case statements.
The if-else-if construct can evaluate relational or logical expressions and ranges, whereas the switch-case only performs equality checks against constant integer or character values.
35. Write a Java expression for the following:
| x2+2xy |
Math.abs((x * x) + (2 * x * y))
36. Write the return data type of the following functions:
random( )
double
37. If the value of basic=1500, what will be the value of tax after the following statement is executed?
tax = basic>1200 ? 200 :100;
200
38. Give the output of following code and mention how many times the loop will execute?
int i;
for( i=5 ; i>=1; i--)
{
if(i%2 ==1)
continue;
System.out.print( i + " ");
}
Output: 4 2
The loop will execute 5 times.
39. Give the output of the following: Math.sqrt(Math.max(9,16))
4.0
40. Evaluate the following expression if the value of x=2, y=3 and z=1.
v=x+ --z+ y++ +y
v = 9
41. What are the various types of errors in Java?
Syntax errors, Logical errors, and Runtime errors.
42. What is meant by a package? Give an example.
A package is a mechanism used to encapsulate a group of classes, sub-packages, and interfaces together. Example: java.util.
Part C : Short Questions
1. What are the different types of programming approach?
Procedural Programming approach and Object-Oriented Programming (OOP) approach.
2. What can be called objects?
Any identifiable entity with some characteristics (state) and behaviour of its own can be called an object. Examples include a dog, a car, or a bank account.
3. Explain the details of a class.
A class is a blueprint or template from which individual objects are created. It acts as an object factory and contains data members (variables) representing characteristics and member functions (methods) representing behaviours. It is a user-defined data type.
4. Why are classes called Abstract Data types (ADT)?
Classes encapsulate all the required properties of objects into a single unit and hide the implementation details from the user. Because they use the concept of data abstraction, they are known as Abstract Data Types (ADT).
5. Write three main advantages of the OOP approach.
1. Data is hidden and secured from external methods (Encapsulation).
2. It provides the facility of reusability through inheritance.
3. It models complex real-world problems effectively by dividing programs into interacting objects.
6. The data structure for the Truck object is given below. What can be the methods for the object?
Colour Weight Model-Year
Methods for the Truck object could include: startEngine(), accelerate(), applyBrakes(), and loadCargo().
7. What is the state and behaviour of an object? Explain with example.
The state refers to the characteristics or attributes of the object, stored in variables. The behaviour refers to the operations or actions the object can perform, implemented as methods. Example: For a Car object, state = colour, model; behaviour = start(), stop().
8. What is method overloading? Explain with example.
Method overloading is a form of polymorphism where multiple methods in the same class share the same name but have different parameters. Example: A method Area() could be defined as Area(int side) for a square and Area(int length, int breadth) for a rectangle.
9. What is a compound statement or a block? Give an example.
A block is a group of statements enclosed within curly braces {}. Each statement inside is terminated by a semicolon. Example:
{
int a = 5;
System.out.println(a);
}
10. What is an if statement? Write its syntax.
An if statement is a conditional control structure that executes a block of code only if a specified boolean condition is true.
Syntax:
if (condition)
{
// Statements
}
11. What is nested if statement? Explain with the help of flowchart.
A nested if statement occurs when an entire if or if-else statement is written within another if statement's block. (Note: A flowchart illustrates evaluating an outer condition, and if true or false based on the block, subsequently evaluating the nested inner condition before proceeding).
12. Explain the term loop with an example.
A loop is a control structure that repeatedly executes a set of statements as long as a specified condition remains true. Example: A for loop printing numbers 1 to 5.
for(int i=1; i<=5; i++) { System.out.println(i); }
13. Explain different control structures with the help of flowchart.
Control structures guide the flow of execution in a program. They include Sequential (executing line by line), Conditional (if-else, switch, diverting execution based on a true/false condition branch), and Iteration/Looping (for, while, do-while, executing a branch repeatedly until a condition breaks).
14. What output does the following code produces?
int a = 1;
switch (a)
{
case 1:
System.out.println ("Ist Division");
case 2:
System.out.println ("IInd Division");
case 3:
System.out.println ("IIIrd Division");
default :
System.out.println ("fail");
}
Output:
Ist Division
IInd Division
IIIrd Division
fail
15. What will be the output of the following?
int num = 35;
if (num >= 60 && num <= 80)
System.out.println ("Good Performance");
else if (num >=50 && num <=60)
System.out.println ("Average Performance");
else
System.out.println ("Try to Improve yourself");
Output:
Try to Improve yourself
16. Write a program to convert seconds into corresponding number of hours, min and seconds. For example, 7266 sec. = 2hrs, 1 min, 6 sec.
public class TimeConverter {
public static void main(String[] args) {
int totalSeconds = 7266;
int hours = totalSeconds / 3600;
int remainingSeconds = totalSeconds % 3600;
int minutes = remainingSeconds / 60;
int seconds = remainingSeconds % 60;
System.out.println(hours + "hrs, " + minutes + " min, " + seconds + " sec.");
}
}
17. Write a program to check whether a given number is positive or negative. If positive, then find whether even or odd.
public class NumberCheck {
public static void main(String[] args) {
int num = 14;
if (num > 0) {
System.out.println("Positive Number");
if (num % 2 == 0) {
System.out.println("Even Number");
} else {
System.out.println("Odd Number");
}
} else if (num < 0) {
System.out.println("Negative Number");
} else {
System.out.println("Zero");
}
}
}
18. Write a menu driven program to display the pattern as per user’s choice.
Pattern 1
ABCDE
ABCD
ABC
AB
A
Pattern 2
B
LL
UUU
EEEE
For an incorrect option, an appropriate error message should be displayed.
import java.util.Scanner;
public class PatternMenu {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1 for Pattern 1, 2 for Pattern 2:");
int choice = sc.nextInt();
switch (choice) {
case 1:
for (int i = 5; i >= 1; i--) {
char ch = 'A';
for (int j = 1; j <= i; j++) {
System.out.print(ch++);
}
System.out.println();
}
break;
case 2:
String s = "BLUE";
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(s.charAt(i-1));
}
System.out.println();
}
break;
default:
System.out.println("Incorrect Option Selected!");
}
}
}
19. Using the switch-case statement, write a menu driven program to do the following:
(a) To generate and print Letters from A to Z and their Unicode
(b) Display the following pattern using iteration (looping) statement:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
import java.util.Scanner;
public class MenuProgram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1 for Unicode, 2 for Pattern:");
int choice = sc.nextInt();
switch (choice) {
case 1:
for (char c = 'A'; c <= 'Z'; c++) {
System.out.println(c + "\t" + (int)c);
}
break;
case 2:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
break;
default:
System.out.println("Invalid Choice");
}
}
}
Quick Navigation:
Quick Review Flashcards - Click to flip and test your knowledge!
Question
In Object-Oriented Programming, what element is emphasised over procedures and structures?
Answer
Data
Question
What term describes the building blocks of an OOP programme that contain both data and methods?
Answer
Objects
Question
How are methods and data related in an object-oriented approach?
Answer
Methods that operate on an object's data are tied together with that data.
Question
Concept: Object
Answer
Definition: An identifiable entity with its own characteristics and behaviour.
Question
What is the software representation of an object's 'characteristics'?
Answer
Data variables or fields
Question
In software, what determine the current 'state' of an object?
Answer
The values stored in its data variables.
Question
What software component acts as the interface between an object's data and the rest of the programme?
Answer
Methods
Question
Concept: Class
Answer
Definition: A blueprint or factory from which individual objects or instances are created.
Question
Which Java keyword is used to define a new class?
Answer
`class`
Question
Why is a class referred to as a 'User Defined Data Type'?
Answer
Because the programmer creates a new type with its own state and behaviour.
Question
In the context of message passing, what is a 'message' physically represented by in software?
Answer
A method call
Question
What are the three components of a message sent between objects?
Answer
The name of the method, the receiving object, and any necessary parameters.
Question
The process of wrapping data and member functions into a single unit is known as _____.
Answer
Data Encapsulation
Question
What is the primary purpose of 'Data Hiding' in encapsulation?
Answer
To protect data from direct access by external methods or the programme.
Question
Concept: Data Abstraction
Answer
Definition: Representing essential features without including background details or explanations.
Question
Classes are sometimes referred to as ADTs; what does this acronym stand for?
Answer
Abstract Data Types
Question
Concept: Inheritance
Answer
Definition: The process by which objects of one class acquire the properties of objects of another class.
Question
In inheritance, what is the term for the uppermost class that provides common properties to others?
Answer
Base class
Question
In inheritance, what are the classes that acquire properties from a base class called?
Answer
Derived classes
Question
What is the main facility provided by inheritance to improve software development efficiency?
Answer
Reusability
Question
Concept: Polymorphism
Answer
Definition: The ability of a function or method to take more than one form or exhibit different behaviours.
Question
What is 'method overloading'?
Answer
When methods with the same name in the same class behave differently based on their parameters.
Question
What is the smallest individual element of a Java programme that is meaningful to the compiler?
Answer
A token
Question
Name the six types of tokens supported by Java.
Answer
Keywords, Identifiers, Literals, Operators, Punctuators, and Variables.
Question
Which specific case must all Java keywords be written in?
Answer
Lowercase
Question
Java identifiers can consist of alphabets, numbers, and which two special characters?
Answer
Underscore `_` and Dollar sign `$`
Question
What is the restriction regarding the first character of a Java identifier?
Answer
It must begin with an alphabet, an underscore, or a dollar sign (not a digit).
Question
Why is 'Sum' and 'sum' considered different in Java identifiers?
Answer
Because Java is a case-sensitive language.
Question
Concept: Variable
Answer
Definition: A named location in memory that stores a value which can change during programme execution.
Question
A program element whose value remains unchanged during the course of the programme is called a _____.
Answer
Constant (or Literal)
Question
Which Java keyword is used to declare a variable as a constant?
Answer
`final`
Question
How are Java operators classified based on the number of operands they take?
Answer
Unary, binary, and ternary
Question
What is the purpose of a data type in Java?
Answer
It dictates the memory size, range of values, and default value for a variable.
Question
Name the two major categories of data types in Java.
Answer
Primitive Data Types and Reference Data Types.
Question
List the eight primitive data types supported by Java.
Answer
byte, short, int, long, float, double, char, and boolean.
Question
Which primitive data types are classified as 'floating point types'?
Answer
float and double
Question
What is the storage capacity of the `int` data type?
Answer
4 bytes (32 bits)
Question
What is the default value for the `long` data type?
Answer
0L
Question
What suffix is used to explicitly represent a `double` literal?
Answer
d or D
Question
What is the range of values for the `byte` data type?
Answer
-128 to 127
Question
How many bits of storage does the `char` data type use in Java?
Answer
16 bits (2 bytes)
Question
What is the default value of the `char` data type in Unicode?
Answer
"\u0000"
Question
What is the storage size of a `boolean` data type?
Answer
1 bit
Question
Why are reference data types also called 'derived data types'?
Answer
Because they are composed of primitive data types.
Question
Concept: Array
Answer
Definition: A named set of elements of similar type stored in contiguous memory locations.
Question
In an array, what are the individual elements referred to by to show their position?
Answer
Subscripts or indices
Question
Which operator is used to allocate memory for a new array or object in Java?
Answer
`new`
Question
What is the purpose of the dot (`.`) operator in Java?
Answer
To access or call member methods or variables of a class through an object.
Question
What package must be imported to use the `Scanner` class for input?
Answer
`java.util`
Question
In Java I/O, what does `System.in` represent?
Answer
The standard input stream, typically linked to the keyboard.
Question
Which `Scanner` method is used to input a single integer?
Answer
`nextInt()`
Question
Which `Scanner` method is used to input a decimal value of type `double`?
Answer
`nextDouble()`
Question
What does the `Math.sqrt(x)` function return?
Answer
The square root of x, provided x is a positive number.
Question
What is the return type of the `Math.random()` function?
Answer
A `double` value between 0 and 1.
Question
Concept: `Math.ceil(x)`
Answer
Definition: Returns the smallest whole number greater than or equal to x.
Question
What is the result of `Math.pow(2, 3)`?
Answer
8.0
Question
Which control structures execute statements based on a boolean condition?
Answer
Conditional Control Structures (e.g., `if-else`, `switch`)
Question
What happens if a single statement follows an `if` condition without curly braces?
Answer
Only that single statement is treated as part of the `if` block.
Question
What is the term for an `if` statement written inside another `if` statement?
Answer
Nesting (Nested `if` statement)
Question
In a `switch` statement, what happens if a `break` statement is omitted after a `case` block?
Answer
Control flows into the next `case` block automatically (fall-through).