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

Java Notes

Java, developed by James Gosling and released in 1995, is a high-level, object-oriented programming language that runs on the Java Runtime Environment (JRE), which includes the Java Virtual Machine (JVM) and core libraries. Key features of Java include platform independence, robustness, and multithreading, with a focus on both compiled and interpreted execution. The document also covers Java programming constructs such as variables, data types, operators, control flow statements, and type casting.
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 views36 pages

Java Notes

Java, developed by James Gosling and released in 1995, is a high-level, object-oriented programming language that runs on the Java Runtime Environment (JRE), which includes the Java Virtual Machine (JVM) and core libraries. Key features of Java include platform independence, robustness, and multithreading, with a focus on both compiled and interpreted execution. The document also covers Java programming constructs such as variables, data types, operators, control flow statements, and type casting.
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/ 36

Java Overview

 Java developed by James Gosling at Sun Microsystems and


released in 1995.
 Java is a high-level, class-based, object-oriented programming
language.
 The Java Runtime Environment, or JRE, is a software layer that
runs on top of a computer’s operating system software and
provides the class libraries and other resources that a
specific Java program requires to run.
 Java Runtime Environment (JRE) includes JVM, class libraries, and
other supporting files.
o JRE = JVM + Core Java API libraries
o JDK = JRE + development tools like compilers
 Java Virtual Machine (JVM): The JVM is like a translator. It
takes the Java code and translates it into instructions that
the computer's operating system can understand.
o JVM then interprets this bytecode and converts it into
machine code (specific to the computer you're running the
program on).
o Bytecode is an intermediate code generated by the
compiler and interpreted by JVM into machine code.
 Compilation: Source code → Bytecode(through compiler)
 Interpretation: Bytecode → Machine code (through JVM)

Java Features
 Here we list the basic features that make Java a powerful,
object-oriented, and popular programming language.
1. Platform Independence
2. Object Oriented
3. Both Compiled and Interpreted
4. Java is Robust
5. JAVA Language Security Features
6. Java is Multithreaded

 First Program:

Class Example
{
public static void main(String args[])
{
System.out.println(“Hello World”);
}
}

 Explanation

L /* Call this file “Example.java”.*/


1 Comment:

L class Example{
2
This line uses the keyword class to declare new class
followed by the class name.
The entire class definition will be between the opening
curly brace ({ ) and the closing curly brace ( }).

L // your program starts execution with a call to main()


3 Comment:

L public static void main (String args []) {


4
 This line shows the main method for the class.
 This is the line from where the program will start its
execution. All applications in Java start execution from
main().
 A root class must contain a main method.

Let us take a brief look at the attributes of main().

 Public: It is an access specifier that specifies that the


code can be called from anywhere.main() is declared
public because it is called from outside (by JVM).

 Static: The static keyword allows the main() method


to be called without creating an object of the class.
This is necessary because the JVM do not create an
object of the class.

 Void: It does not return a value.main()does not return


anything back to the caller, i.e., JVM.

 String args[]: It holds optional command line


arguments passed to the class through the java
command line.

L System.out.println ("This is a simple Java program");


5 print statement.

L }
6 closing of the main method.

L }
7 closing of the class.

Java Programming Constructs:

Variables:

 Variables are containers for storing data values.


 In other words, variable is a name refer to a memory
location used to store values.
 Java declares its variables in the following manner:
Primitive Data Types:

 Primitive data types are the basic building blocks of any


programming language.
 There are eight primitive data types in Java, as follows:

 Here’s the detailed table for Java's eight primitive data


types:
Data Default Size Size
Range
Type Value (Bytes) (Bits)
byte 0 1 8 -128 to 127 (inclusive)
short 0 2 16 -32,768 to 32,767 (inclusive)
int 0 4 32 -2,147,483,648 to 2,147,483,647
–9,223,372,036,854,775,808 to
long 0L 8 64 9,223,372,036,854,775,807
(inclusive)
1.401298464324817e–45f to
float 0.0f 4 32
3.402823476638528860e+38f
4.94065645841246544e–324 to
double 0.0d 8 64
1.79769313486231570e+308
Data Default Size Size
Range
Type Value (Bytes) (Bits)
char '\u0000' 2 16 0 to 65535
boolea
false true or false
n

Non-Primitive Data Types

Non-primitive data types are called reference types because


they refer to objects.

The main differences between primitive and non-


primitive data types are:

 Primitive types in Java are predefined and built into the


language, while non-primitive types are created by the
programmer (except for String).
 Non-primitive types can be used to call methods to
perform certain operations, whereas primitive types
cannot.
 Primitive types start with a lowercase letter (like int), while
non-primitive types typically starts with an uppercase
letter (like String).
 Primitive types always hold a value, whereas non-primitive
types can be null.

Examples of non-primitive types


are Strings, Arrays, Classes etc.

Identifier

 Identifiers are names given to variables, constants,


methods, classes, packages, and interfaces.

 Rules for Naming:

1. The first character of an identifier must be a letter, an


underscore, or a dollar sign ($).
2. Subsequent characters can be letter, an underscore, dollar
sign, or digit.
3. Digits cannot be the first character in an identifier.
4. White spaces are not allowed within identifiers.
5. Identifiers are case-sensitive. This means that Total_Price
and total_price are different identifiers.
6. Do not use Java’s reserved keywords. A few examples of
legal and illegal identifiers are shown below.

 Keywords:

 Java has a set of reserved words. They have specific


meanings and purposes, and it cannot be used as
identifiers (e.g., variable names, method names, class
names, packages names).

Literals

 Literal is a value assigned to variables or constant.


 Literals can be
o numeric
o boolean
o character
o string notations or
o null literals.

 Numeric Literals can be represented in


o binary,
o decimal,
o octal, or
o hexadecimal notations.

Binary literals are a Octal literals must be


combination of 0’s and 1’s. prefixed with a zero and
Binary literals must be only digits from 0 to 7 are
prefixed with 0b or 0B allowed.
(zerob or zeroB). For example,
For example,
int x = 011;//value in x is 9
int bin1 = 0b1010001; //
value in bin1 will be 81

Hexadecimal literals are Integer literals are of type


prefixed with 0x or 0X; the int, by default. To define
digits 0 through 9 and a them as long, we can place
through f (or A through F) a suffix of L or l after the
are only allowed. number.
Example: Example:
int y = 0x0001; //value in y long l = 2345678998L;
is 1
Floating literals are of type double, by default. To define
them as float literals, we need to attach the suffix F or f. For
double literals, D or d are suffixed at the end; however, it is
optional.
Example:
float f = 23.6F;
double d = 23.6;

 Boolean Literals: Boolean literals can only have two


values: true or false. By default, it takes the value false.
Examples:
booleanisJavaFun = true;
booleanisTired = false;

 char literals is single character is enclosed in single


quotes.
Example:
char sample = 'A';
char example = 'a';

 String literals: consist of zero or more characters within


double quotes.
Example:
String s = "This is a String Literal";

 Null Literal: Null literal is used to represent the null


reference (absence of a value for an object).
Example:
String name = null; // Null literal

Operators

 Operator in Java is a symbol that is used to perform


operations.
 An operator performs an action on one or more operands.
 Java provides below operators.
1) Binary Operator
2) Unary Operators
3) Ternary Operators

1. Binary Operator:
 Assignment Operator:
 Arithmetic Operator:
 Relational Operator:
 Logical Operator:
 Assignment Operator:

 Assignment Operator is used to assign a value to any


variable.
 It has right-to-left associativity, i.e. value given on the
right-hand side of the operator is assigned to the variable
on the left.
 Below are assignment operators available in Java.
1. =, Assign.
2. += , Add and assign.
3. -= , Subtract and assign.
4. *= , Multiply and assign.
5. /= , Divide and assign.
6. %= , Modulo and assign.

Example:

 Arithmetic Operator:

 Arithmetic Operators are used to perform simple


arithmetic operations.
1. * : Multiplication
2. / : Division
3. % : Modulo
4. + : Addition
5. – : Subtraction
 Relational Operator:

 Relational operators in Java return either true or false as


a Boolean type.
 Relational operators compare values and return Boolean
results:
1) == , Equal to.
2) != , Not equal to.
3) < , Less than.
4) <= , Less than or equal to.
5) > , Greater than.
6) >= , Greater than or equal to.

 Logical Operator:
 Logical Operators are primarily used in decision-making
and control flow, allowing multiple conditions to be
combined or negated.
o Logical AND (&&):
o Logical OR (||):
o Logical NOT (!):

1. Logical AND (&&):


 Returns true only if both conditions are true.
 If either condition is false, the result is false.

2. Logical OR (||):
 Returns true if at least one condition is true.
 If both conditions are false, the result is false.

3. Logical NOT (!):


 Reverses the boolean value of an expression.
 If a condition is true,makes it false, and vice versa.

Example:
2. Unary Operator:

 Unary operators, as the name suggest, are applied to only


one operand.
 They are as follows: ++, - -, !, and ~.

 Increment and Decrement Operators:


 Increment and decrement operators can be applied to all
integers and floating-point types. They can be used either
in prefix (– –x, ++x) or postfix (x– –, x++) mode.

Prefix Increment/Decrement Operation


int x = 2;
int y = ++x; // x = 3, y = 3

Postfix Increment/Decrement Operation


int x = 2;
int y = x++; // x == 3, y == 2

 Boolean logical not (!):


 Inverts the boolean value of an operand.

boolean flag = true;


System.out.println(!flag); // Output: false

 Bitwise logical not (~):


 Inverts all bits of the operand (works with integers).

int num = 5; // Binary: 00000000 00000000 00000000


00000101
int result = ~num; // Binary: 11111111 11111111 11111111
11111010 (Decimal: -6)
3. Ternary Operator:

 The ternary operator (? :) consists of three operands.


 The operator decides which value will be assigned to the
variable.
 It’s a one-liner replacement for the if -else statement
 We can use the ternary operator in place of if-else
conditions.

Syntax:
variable = (condition) ? expression1 : expression2

 The above statement states that if the condition is true,


expression1 gets executed, else the expression2 gets
executed and the final result stored in a variable.

Example:

package First_Package;
public class New_class {
public static void main(String[] args) {

int marks = 75;


String grade;

grade = (marks >= 40) ? "Pass" : "Fail";


System.out.println("Result: " + grade);
}
}
Precedence Rules and Associativity:

Operator Precedence:
 When various operators are used within the same
statement a problem arises that which operation should
be performed first. To solve this problem there is the
concept of operator precedence.
 Operator Precedence is a set of rules that defines the
priority for all the operators.
 Operators with higher precedence are evaluated first
before those with lower precedence.

Below is a table showing Java operators listed from highest to


lowest precedence:

 Operators in a row have same precedence.

Example:
a= 4+5/10;

Output:
a=4.5
Associativity:
 If we have operators which have same precedence in
the same statement, then we use associativity to figure
out which operation should be performed first.
 associativity determines the order of evaluation.
Operators can be left-associative or right-associative.

Example:
a= 5*5/10

Output:
a=2.5

Primitive Type Conversion and Casting

 Type casting is a process of converting value from one


data type to another data type.
 Two types of casting:
1) Widening Conversions
2) Narrowing Conversions

1. Widening Casting(automatically)- converting smaller


type to larger type.
byte -> short -> char -> int -> long -> float -
> double

 For example, a smaller box can be placed in a bigger box.


 Conversions that are implicit in nature are termed as
widening conversions.
Example:

byte b = 10; // byte variable


int i = b; // implicit widening byte to int

int i = 10; //int variable


double d = 20; //int literal assigned to a double
variable
d = i + d; //automatic conversion int to double

int value i is promoted to double and then the two


double values (i& d) are added to produce a double
result.

2. Narrowing Casting (manually)-converting larger type to


smaller type.

double -> float -> long -> int -> char -> short -
> byte

 Ex., consider the reverse of box example. A bigger box has


to be placed in a small box. Then the bigger box has to be
chopped so that the bigger box can be placed in the small
box. Casting is not implicit in nature.
Example:

inti = (int)(10.0/2.0);

Flow of Control

 Control flow statements are used to control the flow of


execution of a program based on certain conditions.
 The four categories of control flow statements available in
Java are:
1) Conditional statement
2) Loops
3) Exception
4) Branch.

1. Conditional Statements:

 The two conditional statements provided by Java are:


a) If…else
b) Switch-case

a) If…else:
 It is commonly used when you have multiple conditions to
evaluate.
 You can have n number of else if (){} statements in your
program, as per your requirement.
Syntax:

if (condition1)
{
// Lines of code
}
else if(condition2)
{
// Lines of code
}
………
else
{
// Lines of code
}

Example:

package First_Package;
public class First_Program {

public static void main(String[] args) {

int number=5;

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

}
}

 The if...else condition can also be nested as shown.

if (condition)
{
if (condition)
{
//Lines of code
}
}

b) Switch-case:
 Java has a shorthand for multiple if statement—the switch-
case statement.
 Here is how we can write the above program using a
switch-case:
Syntax:

switch (x)
{
case 0:
// Lines of code
doSomething0();
break;
case 1:
// Lines of code
doSomething1();
break;

...
case n:
// Lines of code
doSomethingN();
break;
default:
doSomethingElse();
}

Example:

package First_Package;
public class First_Program {

public static void main(String[] args) {

int day=3; // Input: day of the week (1 = Monday, 2 =


Tuesday, etc.)
switch (day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");

}
}
}
2. Loops:
 The purpose of loop statements is to execute Java
statements many times.
 There are three types of loops in Java—
a) For,
b) While, and
c) Do-while.

a) For Loop:

 The forloop groups the following three common parts


together into one statement:
a) Initialization
b) Condition
c) Increment or decrement

Syntax:

for(initialization; condition; increment/decrement)


{
//statement or code to be executed
}

Example:

b) While Loop:
 The while loop is used to repeatedly execute a block of
statements until the specified condition is true.
 Once the condition becomes false, the loop automatically
stops.

Syntax:

while (condition)
{
//code to be executed
Increment / decrement
}

Example:

c) Do-while Loop:

 A do-while loop is also used to repeatedly execute a block


of statements. But, in a do-while loop the condition is
evaluated at the end of the iteration. So the do-while will
execute at least once and after that depending upon the
condition.

Syntax:

do{
//code to be executed
}while (condition);

Example:

for-each Loop:
 The for-each loop in Java also called the enhanced for
loop which was introduced in Java 5.
 It provides an alternative approach to traverse the array
or collection in Java.
 The advantage of the for-each loop is that it makes the
code more readable.
 The drawback of the enhanced for loop is that it cannot
traverse the elements in reverse order.
 Here, you do not have the option to skip any element
because it does not work on an index basis.

Syntax:

for (type variableName: arrayName)


{
// Statements to repeat
}
Example:

package First_Package;
public class New_class {

public static void main(String[] args) {

int[] numbers = {10, 20, 30, 40, 50};

for (int num : numbers)


{
System.out.println(num);
}

}
}

3. Branching Mechanism:

 Java supports two types of branching statements


1) break
2) continue

a) break Statement:
 The break statement is used to jump out of a loop.
 In other words, break is used to exit from the loop or
switch case.
 When break statement is encountered inside a loop, the
loop is immediately terminated and the Program control
moves to the next statement after the loop.

Syntax:
break;

Example:
package First_Package;
public class First_Program {

public static void main(String[] args) {

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


{
if (i == 5)
{
break;
}
System.out.println("i = " + i);
}
System.out.println("Loop exited.");

}
}

b) Continue Statement:
 Continue statement is used to skip the current
iteration and continues with the next iteration in the
loop.
 We can use Java continue statement in all types of loops
such as for loop, while loop and do-while loop.

Syntax:
continue;
Example:
package First_Package;
public class First_Program {

public static void main(String[] args) {

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


{
if(i == 3)
{
continue;
}
System.out.println("i = " + i);
}
}

}
Okay, here are 10 MCQs for each major topic identified in your provided PDF.

Topic 1: Java Overview (Page 1)

1. Who developed Java and at which company?


a) Dennis Ritchie at Bell Labs
b) James Gosling at Sun Microsystems
c) Bjarne Stroustrup at Bell Labs
d) Guido van Rossum at CWI
Answer: b)
2. What does JRE stand for and what is its primary purpose?
a) Java Development Kit; to compile Java code.
b) Java Runtime Environment; to provide libraries and resources for a Java program
to run.
c) Java Virtual Machine; to translate bytecode to machine code.
d) Java API for XML; to parse XML documents.
Answer: b)
3. Which of the following correctly describes the composition of the JDK?
a) JDK = JVM + Compilers
b) JDK = JRE + Development tools (like compilers)
c) JDK = JRE - JVM
d) JDK = Core Java API libraries + Compilers
Answer: b)
4. What is the role of the Java Virtual Machine (JVM)?
a) To compile Java source code into bytecode.
b) To provide an editor for writing Java code.
c) To translate bytecode into machine-specific instructions.
d) To manage the file system for Java applications.
Answer: c)
5. What is "bytecode" in Java?
a) The source code written by the programmer.
b) Machine code that runs directly on the hardware.
c) An intermediate code generated by the compiler, interpreted by the JVM.
d) A library of pre-compiled Java classes.
Answer: c)
6. The process of converting Java source code into bytecode is called:
a) Interpretation
b) Execution
c) Compilation
d) Linking
Answer: c)
7. The process of converting bytecode into machine code is primarily done during:
a) Compile-Time
b) Runtime by the JVM
c) Linking-Time
d) Editing-Time
Answer: b)
8. According to the diagram, what component is responsible for loading bytecode into
memory during runtime?
a) Java compiler
b) Interpreter
c) Class loader (Bytecode loader)
d) Machine code generator
Answer: c)
9. What is the relationship: JRE = ?
a) JVM + Compilers
b) JVM + Development Tools
c) JVM + Core Java API libraries
d) JDK + Core Java API libraries
Answer: c)
10. The JVM acts like a:
a) Compiler only
b) Debugger only
c) Translator (interpreting bytecode)
d) Text editor
Answer: c)

Topic 2: Java Features & Basic Constructs (Variables, Data Types)


(Pages 2-3)

1. Which of the following is listed as a key feature of Java in the document?


a) Procedural Programming
b) Platform Dependence
c) Object Oriented
d) Single-threaded
Answer: c)
2. According to the document, variables are:
a) Fixed values that cannot be changed.
b) Keywords reserved by the Java language.
c) Containers for storing data values.
d) Operations performed on data.
Answer: c)
3. In the Java variable declaration int noofwatts = 100;, what does "noofwatts"
represent?
a) Data type
b) Literal
c) Identifier
d) Keyword
Answer: c)
4. Which of the following is a primitive data type in Java used for whole numbers?
a) String
b) float
c) int
d) Boolean
Answer: c)
5. Non-primitive data types in Java are also called:
a) Value types
b) Basic types
c) Reference types
d) Simple types
Answer: c)
6. What is a key difference between primitive and non-primitive data types mentioned in
the text?
a) Primitive types can be null, while non-primitive types cannot.
b) Non-primitive types can be used to call methods, whereas primitive types cannot
(generally).
c) Primitive types start with an uppercase letter, non-primitive types with a lowercase
letter.
d) Non-primitive types are predefined, while primitive types are created by the
programmer.
Answer: b)
7. Which of the following is an example of a non-primitive data type in Java?
a) char
b) double
c) String
d) boolean
Answer: c)
8. Which primitive data type is used for storing characters?
a) byte
b) char
c) string
d) boolean
Answer: b)
9. Primitive types typically start with a lowercase letter (e.g., int), while non-primitive
types (except for specific cases like String by convention) typically start with:
a) A lowercase letter
b) A number
c) An uppercase letter
d) A special symbol
Answer: c)
10. Which of the following statements is true about primitive types?
a) They are created by the programmer.
b) They can be null.
c) They always hold a value (of their type, or a default).
d) They are used to call methods directly.
Answer: c)

Topic 3: Literals (Pages 3-5)

1. What is a literal in Java?


a) A name given to a memory location.
b) A keyword with a special meaning.
c) A value assigned to a variable or constant.
d) An operation performed on data.
Answer: c)
2. A binary literal in Java must be prefixed with:
a) 0x or 0X
b) 0
c) 0b or 0B
d) No prefix is needed
Answer: c)
3. What is the decimal value of the octal literal 011?
a) 11
b) 3
c) 9
d) 8
Answer: c)
4. Which suffix is used to define an integer literal as a long type?
a) F or f
b) D or d
c) L or l
d) No suffix is needed, it's inferred.
Answer: c)
5. Floating-point literals are of type double by default. How do you specify a float
literal?
a) Append L or l
b) Append F or f
c) Append D or d
d) Prefix with 0f
Answer: b)
6. What are the only two possible values for a Boolean literal?
a) 0 and 1
b) "true" and "false" (as strings)
c) yes and no
d) true and false (as keywords)
Answer: d)
7. How is a character literal represented in Java?
a) Enclosed in double quotes (e.g., "A")
b) Enclosed in single quotes (e.g., 'A')
c) Without any quotes (e.g., A)
d) Using the char() constructor.
Answer: b)
8. Which literal is used to represent the absence of a value for an object reference?
a) 0
b) empty
c) void
d) null
Answer: d)
9. A hexadecimal literal 0x0001 represents which decimal value?
a) 16
b) 256
c) 1
d) 0
Answer: c)
10. String literals consist of zero or more characters enclosed within:
a) Single quotes
b) Backticks
c) Double quotes
d) Parentheses
Answer: c)

Topic 4: Operators Part 1 (Assignment, Arithmetic, Relational) (Pages


5-7)

1. What is the primary purpose of an assignment operator in Java?


a) To compare two values.
b) To perform arithmetic calculations.
c) To assign a value to a variable.
d) To create a new object.
Answer: c)
2. Which of the following is an example of an "Add and assign" operator?
a) =
b) +=
c) ==
d) +
Answer: b)
3. What does the % operator do in Java?
a) Calculates percentage
b) Performs division
c) Returns the modulo (remainder of a division)
d) Multiplies two numbers
Answer: c)
4. Which of these is NOT an arithmetic operator listed in the document?
a) * (Multiplication)
b) / (Division)
c) & (Bitwise AND)
d) + (Addition)
Answer: c)
5. Relational operators in Java primarily return what type of value?
a) int
b) String
c) double
d) boolean
Answer: d)
6. Which relational operator is used to check for "Not equal to"?
a) ==
b) !=
c) <>
d) !==
Answer: b)
7. If a = 10 and b = 20, what is the result of the expression a > b?
a) true
b) false
c) 10
d) 20
Answer: b)
8. The assignment operator (=) has which associativity?
a) Left-to-right
b) Right-to-left
c) No associativity
d) Depends on the data type
Answer: b)
9. What is the output of System.out.println("Greater Than Operator: a == b : \t\t" +(a >
b)); if a=10 and b=20 based on the example?
a) Greater Than Operator: a == b : true
b) Greater Than Operator: a == b : false
c) An error, because a==b is used in the string.
d) Greater Than Operator: a > b : false (Note: The text has a typo, a==b in string, but
a>b in logic)
Answer: b) (Based on the logic (a > b))
10. Which operator is used to check if one value is "Less than or equal to" another?
a) <
b) =>
c) <=
d) !=
Answer: c)

Topic 5: Operators Part 2 (Logical, Unary, Ternary) (Pages 8-10)

1. Which logical operator returns true only if both conditions are true?
a) || (Logical OR)
b) ! (Logical NOT)
c) && (Logical AND)
d) ^ (Logical XOR - not explicitly listed but good distractor)
Answer: c)
2. If condition1 is false and condition2 is true, what is the result of condition1 ||
condition2?
a) true
b) false
c) 0
d) 1
Answer: a)
3. What is the purpose of the Logical NOT (!) operator?
a) To combine two boolean expressions.
b) To reverse the boolean value of an expression.
c) To check for inequality.
d) To perform bitwise negation.
Answer: b)
4. Which of the following is a unary operator?
a) + (addition)
b) && (logical AND)
c) ++ (increment)
d) ?: (ternary)
Answer: c)
5. If int x = 2; int y = ++x;, what are the values of x and y after execution?
a) x = 2, y = 2
b) x = 2, y = 3
c) x = 3, y = 2
d) x = 3, y = 3
Answer: d)
6. If int x = 2; int y = x++;, what are the values of x and y after execution?
a) x = 2, y = 2
b) x = 3, y = 2
c) x = 2, y = 3
d) x = 3, y = 3
Answer: b)
7. The bitwise logical NOT operator is represented by:
a) !
b) ~
c) NOT
d) ^
Answer: b)
8. The ternary operator (?:) consists of how many operands?
a) One
b) Two
c) Three
d) Four
Answer: c)
9. In the ternary expression variable = (condition) ? expression1 : expression2;, when is
expression2 executed?
a) When the condition is true.
b) When the condition is false.
c) Always executed, but its value is chosen based on condition.
d) Never, it's for comments.
Answer: b)
10. If boolean flag = true;, what is the output of System.out.println(!flag);?
a) true
b) false
c) 1
d) 0
Answer: b)

Topic 6: Conditional Statements (If-else, Switch-case) (Pages 11-14)

1. Which type of statements are used to control the flow of execution of a program based
on certain conditions?
a) Looping statements
b) Assignment statements
c) Control flow statements
d) Declaration statements
Answer: c)
2. Which of the following is a conditional statement provided by Java as listed in the
document?
a) For loop
b) While loop
c) Switch-case
d) Try-catch
Answer: c)
3. In an if-else if-else structure, which block is executed if none of the if or else if
conditions are true?
a) The first if block.
b) All else if blocks.
c) The final else block.
d) No block is executed.
Answer: c)
4. Can if...else conditions be nested in Java?
a) No, Java does not allow nested conditionals.
b) Yes, if...else conditions can be nested.
c) Only if can be nested, not else.
d) Only up to two levels of nesting.
Answer: b)
5. The switch-case statement is described as a shorthand for:
a) A single if statement.
b) Multiple independent if statements.
c) A for loop.
d) Multiple if-else if statements (a chain of if statements).
Answer: d)
6. What is the purpose of the break statement within a switch-case block?
a) To skip the current case and move to the next one.
b) To exit the switch-case block entirely.
c) To indicate the default case.
d) To repeat the current case.
Answer: b)
7. In a switch statement, if no case matches the value of the expression and a default
case is present, which block of code is executed?
a) The first case.
b) The last case.
c) The default case.
d) An error occurs.
Answer: c)
8. Consider the example: int day=3; switch(day) { ... case 3:
System.out.println("Wednesday"); break; ... }. What is the output?
a) Monday
b) Tuesday
c) Wednesday
d) Invalid day
Answer: c)
9. If a break statement is omitted from a case in a switch statement, what happens?
a) A compile-time error occurs.
b) Execution stops at that case.
c) Execution "falls through" to the next case's statements until a break or the end of
the switch is reached.
d) Only the default case is executed.
Answer: c)
10. The expression in a switch statement can be of which types (traditionally, before
modern Java enhancements)?
a) Only boolean
b) byte, short, char, int, String, enum
c) Only float or double
d) Any object type
Answer: b) (The document doesn't specify this detail, but it's general Java knowledge
relevant to switch usage, and the example uses int)

Topic 7: Loops (For, While, Do-while, For-each) (Pages 14-17)

1. What is the primary purpose of loop statements in Java?


a) To make decisions based on conditions.
b) To execute a block of statements many times.
c) To declare variables.
d) To handle errors and exceptions.
Answer: b)
2. Which are the three common parts grouped together in a for loop statement?
a) Condition, Body, Termination
b) Initialization, Condition, Increment/Decrement
c) Start, Stop, Step
d) Declaration, Execution, Return
Answer: b)
3. In a while loop, when is the condition checked?
a) After each iteration.
b) Only once at the beginning.
c) Before each iteration.
d) It's optional to check the condition.
Answer: c)
4. What is a key characteristic of a do-while loop?
a) The condition is checked at the beginning of the loop.
b) The loop body will execute at least once.
c) It cannot have an increment/decrement statement inside.
d) It is only used for iterating over arrays.
Answer: b)
5. The "enhanced for loop" or "for-each loop" was introduced in which Java version
mentioned in the text?
a) Java 1.0
b) Java 2 (J2SE 1.2)
c) Java 5
d) Java 8
Answer: c)
6. What is mentioned as an advantage of the for-each loop?
a) It can traverse elements in reverse order.
b) It allows skipping elements based on an index.
c) It makes the code more readable.
d) It is faster than other loops.
Answer: c)
7. What is mentioned as a drawback of the for-each loop?
a) It is difficult to understand.
b) It cannot traverse elements in reverse order.
c) It can only be used with primitive data types.
d) It requires manual index management.
Answer: b)
8. Consider the loop: for(int i = 1; i <= 5; i++) System.out.println(i);. How many times
will System.out.println(i) be executed?
a) 4 times
b) 5 times
c) 6 times
d) 0 times
Answer: b)
9. Which loop type evaluates its condition at the end of the iteration?
a) for loop
b) while loop
c) do-while loop
d) for-each loop
Answer: c)
10. The syntax for (type variableName: arrayName) is characteristic of which loop?
a) Standard for loop
b) while loop
c) do-while loop
d) for-each loop
Answer: d)

Topic 8: Branching Statements (Break, Continue) (Pages 18-20)

1. Which statement is used to jump out of a loop or switch case?


a) continue
b) return
c) break
d) exit
Answer: c)
2. When a break statement is encountered inside a loop, what happens to the program
control?
a) It moves to the beginning of the current loop iteration.
b) It moves to the next iteration of the loop.
c) The loop is immediately terminated, and control moves to the statement after the
loop.
d) The program terminates.
Answer: c)
3. What is the primary purpose of the continue statement in Java?
a) To terminate the loop entirely.
b) To skip the current iteration and proceed with the next iteration of the loop.
c) To jump to a specific labeled statement.
d) To pause the execution of the loop.
Answer: b)
4. The continue statement can be used in which types of loops?
a) Only in for loops.
b) Only in while loops.
c) In for, while, and do-while loops.
d) Only in switch statements.
Answer: c)
5. Consider the code:
6. for (int i = 1; i <= 10; i++) {
7. if (i == 5) {
8. break;
9. }
10. System.out.println("i = " + i);
11. }
12. System.out.println("Loop exited.");

What will be the last value of i printed before "Loop exited."?


a) i = 10
b) i = 5
c) i = 4
d) i = 1
Answer: c) (The println for i is before the "Loop exited" but after the potential break,
so when i is 5, break happens, nothing prints. Last print is i=4)

13. Consider the code:


14. for(int i=1; i<=5 ; i++) {
15. if(i == 3) {
16. continue;
17. }
18. System.out.println("i = " + i);
19. }

IGNORE_WHEN_COPYING_START
content_copy download
Use code with caution. Java
IGNORE_WHEN_COPYING_END

Which value of i will NOT be printed?


a) 1
b) 2
c) 3
d) 5
Answer: c)

20. If a break statement is used outside of a loop or a switch statement, what is the result?
a) It is ignored.
b) It causes the current method to return.
c) It results in a compile-time error.
d) It terminates the entire program.
Answer: c)
21. Which statement is used to "exit from the loop or switch case"?
a) goto
b) continue
c) break
d) pass
Answer: c)
22. If you want to stop processing the current iteration of a loop and immediately start the
next one, you would use:
a) break;
b) return;
c) continue;
d) next;
Answer: c)
23. In the example for the break statement, System.out.println("Loop exited."); is printed:
a) After each iteration of the loop.
b) Only if the loop completes all its iterations without a break.
c) Immediately after the break statement is executed, inside the loop.
d) After the loop has terminated, either by completing all iterations or by a break.
Answer: d)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy