0% found this document useful (0 votes)
7 views18 pages

Java Module1 - QB

The document outlines important Java concepts, including Java buzzwords, object-oriented principles, lexical issues, data types, variable scopes, type conversion, and operators. It also provides examples of Java programs for temperature conversion, array declaration, and finding the greatest of three numbers using a ternary operator. Additionally, it discusses control statements in Java, including selection, iteration, and jump statements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views18 pages

Java Module1 - QB

The document outlines important Java concepts, including Java buzzwords, object-oriented principles, lexical issues, data types, variable scopes, type conversion, and operators. It also provides examples of Java programs for temperature conversion, array declaration, and finding the greatest of three numbers using a ternary operator. Additionally, it discusses control statements in Java, including selection, iteration, and jump statements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Module-1 important questions with answers

1. Explain Java Buzzwords <OR> Explain features of Java that makes it different
from other languages <OR> Write a key advantage of Java.
The 11 Buzzwords are as mentioned below
Simple:
Java is easy to learn and use. It removes complex features like pointers, header files,
operator overloading, structures, and unions found in C/C++.
Secure:
Java provides a secure environment with built-in security features that help create virus-
free and tamper-free applications.
Portable:
Java programs are platform-independent. Code written once can run on any machine
— “Write Once, Run Anywhere.”
Object-Oriented:
Java follows object-oriented principles, focusing on objects and interfaces. Everything
is an object except primitive data types for better performance.
Robust:
Java has strong memory management, automatic garbage collection, and exception
handling, reducing runtime errors and memory corruption.
Multithreaded:
Java allows multiple threads to run simultaneously, enabling efficient multitasking
within a program.
Architectural Neutral:
Java generates architecture-independent bytecode that can run on any processor with a
Java Runtime Environment.
Interpreted & High Performance:
Java bytecode is interpreted and optimized using Just-In-Time (JIT) compilation for
better performance.
Distributed:
Java supports network-based applications using standard protocols like HTTP, FTP,
and features such as RMI.
Dynamic:
Java is more dynamic than C/C++ and is designed to adapt to changing environments.
It supports runtime type information, making programs flexible and extensible.

2. Explain object -oriented principles.


The three main principles of OOP are:
• Encapsulation: is a mechanism that binds together code and the data it manipulates.
It ensures that the data is safe and is not freely available for outside interference and
misuse.
• Inheritance: is the process by which one class acquires the properties of another class.
This is important because it supports the concept of hierarchical classification. By the
use of inheritance, a class has to define only those qualities that make it unique. The
general qualities can be inherited from the parent class.
• Polymorphism: in general refers to “one interface multiple methods” philosophy. It
means that it is possible to generate a generic interface for a group of related activities.

3. Explain different lexical issues in JAVA.

Java Programs are collections of whitespaces, identifiers, literals, comments,


operators, separators and keywords.

1. Whitespaces –
Java is a free-form language. This means that you do not need to follow any special
indentation rules. In Java, whitespaces include space, tab or newline.

2. Identifiers –
Identifiers are used to name classes, variables and methods. An identifier may be any
descriptive sequence of uppercase and lower case letters, numbers. Java is a case-
sensitive, so VALUE is different from value.

3. Literals –
A constant value in Java is created by using a literal representation for it. For
example, 100 is an integer literal, 98.6 is a floating-point literal, ‘N’ is a character
literal, and “Hello World” is a string literal.

4. Comments –
Java supports three types of comments:
• Single Line Comment – e.g., // this is a single line comment
• Multiline Comment – e.g., /* this is a Multiline comment */
• Documentation Comment – this type of comment is used to produce an HTML file
that documents your program. The documentation comment begins with /** and ends
with */.

5. Separators –
In Java, the most commonly used separator is semicolon ; – used to terminate
statements. The various separators are listed below,

Sl.
Symbol Name Purpose
No.
Used to contain parameter
list in method invocation,
for defining precedence in
1 () Parentheses expressions, to contain
expressions in control
statements, and for
surrounding cast types.
Used to define block of
code, for classes, methods
2 {} Braces and local scope, and
values of automatically
initialized arrays.
Sl.
Symbol Name Purpose
No.
Used to declare array
3 [] Brackets types and dereferencing
array value.
4 ; Semicolon Terminates statements.
Separates consecutive
5 , Comma identifiers in a variable
declaration.
Used to separate package
names, and to separate
6 . Period
variables and methods
from reference variables.

6. Java Keywords:
Java has 50 predefined keywords that cannot be used as identifiers (names of
variables, classes, or methods). Additionally, true, false, and null are data literals
and also cannot be used as identifiers.
4. Discuss the different data types supported by java along with the default values
and literals

Java defines eight primitive types of data: byte, short, int, long, float, double, char
and boolean. As shown in above figure
Integer Types: are signed, positive and negative values. Java does not support unsigned
values. Integer types hold the whole numbers, they cannot hold real numbers. There are
4 datatypes related to Integer group such as- byte, short, int, long. The size (width) of
Integer group is as shown below,

Floating-Point Numbers (Real Types): can hold real numbers, there are 2 datatypes
related to floating-point numbers, such as, float and double. ‘float’ stores real numbers
using single precision, whereas, ‘double’ stores real numbers using double precision.
The size of these datatypes are shown below,

Character Types: in Java is used to store characters. It occupies 2 bytes in the memory
unit and uses Unicode (ASCII + Other character set) to represent characters. The default
value for char is ‘space’.
Boolean: is used to deal with the logical values. It occupies 1 byte in the memory with
default value as ‘false’. It can have one of the two values namely ‘true’ or ‘false’. This
is the type returned by all relational operators.

5. Explain various scopes of variables in Java.


• Java allows variables to be declared inside blocks {}.

• A block defines a scope, and variables declared within it are accessible only
inside that block.

• This helps protect variables from unauthorized access or modification.

class Scope
{
public static void main(String args[])
{
int x; // known to all code within main x = 10; if(x == 10) // start new scope
{
int y = 20; // known only to this block
// x and y both known here.
[Link]("x and y: " + x + " " + y); x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here. [Link]("x is " + x);
}
}

6. What do you mean by type conversion and type casting? Give examples.
The process of converting one datatype value to another datatype value is termed as
Type Casting. There are two types of type casting:
1. Implicit Casting (Widening Conversion) – Converting smaller datatype value to
bigger datatype value.
This type of conversion happens in following two conditions,
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. This happens
automatically. There is no loss of data in implicit conversion.
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
[Link]("Int value "+i);
[Link]("Long value "+l);
}
}

2. Explicit Casting (Narrowing Conversion) – Converting bigger datatype value to


smaller datatype value.
This type of conversion happens in following two conditions,
• The two types are incompatible.
• The destination type is smaller than the source type.

public class Test


{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
[Link]("Double value "+d);
[Link]("Long value "+l);
}
}
Automatic type promotion in expressions:
• Type conversions also occurs in expressions.
• Java automatically promotes each byte, short, or char operand to int when
evaluating an expression.
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
• byte b = 50;
• b = (byte)(b * 2); which yields the correct value of 100.

7. Develop a Java program to convert Celsius temperature to Fahrenheit.


public class CelsiusToFahrenheit {
public static void main(String[] args) {
double celsius = 25; // Hardcoded temperature
double fahrenheit = (celsius * 9/5) + 32;

[Link]("Temperature in Celsius: " + celsius);


[Link]("Temperature in Fahrenheit: " + fahrenheit);
}
}
8. How to declare and initialize l-D and 2-D arrays in java. Give examples
An array is a collection of elements of the same data type stored in contiguous
memory locations.
1-D(one dimensional array):
Declaring an array: int arr[];
Initializing an array: arr = new int[5];
Combining both: int[] arr = new int[5];
ex:
public class OneDArrayExample {
public static void main(String[] args) {
int[] arr = {10, 20, 30};

for(int i = 0; i < [Link]; i++) {


[Link](arr[i]);
}
}
}

2-D(Two dimensional array):


Declaring: int[][] matrix;
Initializing: matrix = new int[2][3]; // 2 rows, 3 columns
Combining both: int[][] matrix = new int[2][3];
Ex:

9. List and explain operators in Java.


i. Arithmetic Operators:

• Arithmetic operators are used in mathematical expressions.


• Combining operators with operands forms an arithmetic expression, which
produces an integer or floating-point result.
• Most arithmetic operators are binary, except + and -, which can be both
unary and binary. Unary - negates a value.

class BasicMath {
public static void main(String args[]) {
[Link]("Arithmetic Operators Demo");
int a = 10;
int b = 20;
int c = a + b;
int d = a - b;
int e = a * b;
int f = b / a;
int g = b % a;
[Link]("Value of Addition = " + c);
[Link]("Value of Subtraction = " + d);
[Link]("Value of Multiplication = " + e);
[Link]("Value of Division = " + f);
[Link]("Value of Modulus = " + g);
String s1 = "10";
String s2 = "20";
String s3 = s1 + s2; // + performs concatenation
[Link]("Value of s3 is " + s3);
}}

ii. Bitwise operators:


• Bitwise operators work on the individual bits of operands.
• Java supports several bitwise operators for performing bit-level operations.

class BitwiseDemo {
public static void main(String[] args)
{
[Link]("Bitwise Operators Demo");
byte a = 5;
int b = a >> 1; // Right shifting a value by 1 is same as dividing the value by 2
int c = a << 1; // Left shifting a value by 1 is same as multiplying the value by 2
[Link]("Value of a is " + a);
[Link]("Value of b is " + b);
[Link]("Value of c is " + c);
}
}
iii. Relational operators:
• Relational operators compare two operands to determine their relationship.
• They are binary operators and return a Boolean value (true or false).
• They are commonly used in loop and if statements for decision making.

class Demo{
public static void main(String [ ] args){
[Link]("Relational Operators Demo");
int a = 4;
int b = 1;
boolean c = a < b;
boolean d = a > b;
boolean e = (a == b);
boolean f = (a != b);
[Link]("Value of c = " + c);
[Link]("Value of d = " + d);
[Link]("Value of e = " + e);
[Link]("Value of f = " + f);
}
}

iv. Logical operators(Short Circuit Operators):


• Logical operators are used to find logical relation among the Boolean
values.
• It operates on Boolean operands and the result of the operation is Boolean
value.
• Logical operators can also be used between relational operators.
• E.g., if(a>b && b<c)
• The list of logical operators are

v. The Assignment Operator:


• Assignment operator is used to assign value from right side operand to left side
operand.
• All assignment operators are binary operators.
• When assigning operators, both the operands must be of same type.
• If there is an assignment of one datatype value to another, then typecasting has to
happen (implicit/explicit).
• The general form of the assignment operator is ,
var=expression

E.g: int a=2*9;

• The chain of assignments can also be done.

a=b=c=9;

vi. The ? Operator(Ternary operator):


• Java supports a special operator called ternary operator (?), which can be used
instead of if-then-else.
• The general form of ? Operator is,
• Var = (condition) ? Expression1 : expression2
• If the condition is true, then expression1 is evaluated, otherwise expression2 is
evaluated.
class TernaryDemo{
public static void main(String [ ] args){
[Link]("Ternary Operator Demo");
int a, b;
a = 28;
b = (a != 0) ? -a : a;
[Link]("Value of b = " + b);
}
}
vii. Strings:
• The String type is used to declare string variables.
• A quoted string can be assigned to a String variable, and one string variable
can be assigned to another.

Ex: String str = "this is a test";

[Link](str);

10. With a java program, illustrate the use of ternary operator to find the greatest of
three numbers.
class GreatestOfThree {
public static void main(String[] args) {
int a = 25;
int b = 40;
int c = 30;
// Using nested ternary operator
int greatest = (a > b)
? (a > c ? a : c)
: (b > c ? b : c);
[Link]("Numbers: " + a + ", " + b + ", " + c);
[Link]("Greatest number is: " + greatest);
}}
11. Develop a Java program to add two matrices using command line argument.
Study lab program
12. List and explain control statements in Java with programming example.
Java supports three types of control statements:
• Selection statement
• Iteration statement
• Jump statement

1. Selection statement:
• Java has two selection statements: if and switch.
• They control program flow based on conditions.
Types of if statements:
i. Simple if
ii. if-else
iii. if-else-if ladder
iv. Nested if-else
i. Simple if:
The general form of if statement is:

if (condition)
{
Statement1;
}
else
{
Statement2;
}
ii. if-else:

• A nested if is an if statement inside another if or else.


• In nested if, the else always matches the nearest if within the same
block.

General form:

if (condition1)
{
if (condition2)
Statement1;
else
Statement2;
}
else
Statement3;

iii. if-else-if ladder:


The if–else–if ladder is used when you need to check multiple conditions one after
another.
The program executes the block of the first true condition and skips the remaining
conditions.
if (condition1) {
// statement block 1
}
else if (condition2) {
// statement block 2
}
else if (condition3) {
// statement block 3
}
else {
// default block
}
Example:
public class ElseIfLadderExample {
public static void main(String[] args) {

int a = 10;
int b = 25;
int c = 15;

if (a > b && a > c) {


[Link]("A is greatest");
}
else if (b > a && b > c) {
[Link]("B is greatest");
}
else {
[Link]("C is greatest");
}
}
}
iv. Nested if-else:
It is a sequence of nested if statements used to check multiple conditions.
if (condition1)
statement1;
else if (condition2)
statement2;
...
else
statement;
v. Switch statement:
• It is a multiway branch statement.
• It allows execution of different parts of code based on the value of an
expression.
• It is an alternative to long if–else–if ladder statements.

switch (expression) {
case value1:
// statements
break;

case value2:
// statements
break;

case value3:
// statements
break;

default:
// default statements
}

2. Iteration statements:
Java supports 4 types of iterative statements,
• While loop
• Do-while loop
• For loop
• Enhanced for loop(for each loop)
i. While loop:
• It is a fundamental loop statement.
• It repeats a statement or block of statements as long as the condition is
true.
• The condition is checked before executing the loop body.
while (condition) {

// body of loop

}
Example:
public class WhileExample {
public static void main(String[] args) {

int i = 1;

while (i <= 5) {
[Link](i);
i++;
}
}
}
ii. do-while Loop:

• The do-while loop always executes its body at least once.


• This is because the condition is checked after the loop body.

do {

// body of loop

} while (condition);

Example:

public class DoWhileExample {


public static void main(String[] args) {

int i = 1;

do {
[Link](i);
i++;
} while (i <= 5);
}
}
iii. For loop:

• The for loop is a looping statement used to repeat a block of code a fixed
number of times.
• It is commonly used when the number of iterations is known.
• It checks the condition before executing the loop body.

for (initialization; condition; update) {


// body of loop
}
Example:

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

[Link](i);

iv. For-each loop:


• The for-each loop is used to traverse (access) elements of an array or collection.
• It is simpler than the normal for loop.
• It is mainly used when we only need to read elements (not modify index).

for (datatype variable : array_name) {

// body of loop

}
Example:
int[] arr = {10, 20, 30};
for (int num : arr) {
[Link](num);
}

3. Jump statement:

Java supports three jump statements namely,


i. Break
ii. Continue
iii. Return

i. Break:
The break statement has three uses:
• It terminates a statement sequence in a switch statement.
• It is used to exit a loop (for, while, do-while).
• It can be used as a labeled break (similar to goto) to exit from a specific block.
public class BreakExample {
public static void main(String[] args) {

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


if (i == 3) {
break;
}
[Link](i);
}
}
}

ii. Continue statement:


• The continue statement skips the remaining code inside the loop for the current
iteration.
• It then moves to the next iteration of the loop.

public class ContinueDemo {


public static void main(String[] args) {

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

if (i == 3)
continue;

[Link](i);
}
}
}

iii. Return statement:


• The return statement is used to exit from a method.
• It transfers program control back to the calling method.
• It can also return a value.
public class ReturnExample {

static void show() {


[Link]("Hello");
return;
}

public static void main(String[] args) {


show();
[Link]("End");
}
}

13. Develop a java program to demonstrate the working of for each version of for
loop. Initialize the 2D array with values and print them using for each.
public class ForEachDemo {
public static void main(String[] args) {

int[][] arr = {
{1, 2},
{3, 4}
};

for (int[] row : arr) {


for (int num : row) {
[Link](num + " ");
}
[Link]();
}
}
}

14. Write a Java program with a method to check whether a given number is prime
or not.
public class PrimeNumber {

// Method to check prime


static boolean isPrime(int num) {

if (num <= 1) {
return false;
}

for (int i = 2; i <= num / 2; i++) {


if (num % i == 0) {
return false;
}
}

return true;
}

public static void main(String[] args) {

int number = 7; // Change this value to test

if (isPrime(number)) {
[Link](number + " is a Prime number");
} else {
[Link](number + " is not a Prime number");
}
}
}
15. Write a Java program to perform linear search on an array elements accepted
from keyboard and key element also accepted from key board.
import [Link];

public class LinearSearch {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter number of elements: ");


int n = [Link]();
int[] arr = new int[n];

// Accept array elements


[Link]("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

// Accept key element


[Link]("Enter element to search: ");
int key = [Link]();

boolean found = false;

// Linear Search
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
[Link]("Element found at position " + (i + 1));
found = true;
break;
}
}

if (!found) {
[Link]("Element not found");
}

[Link]();
}
}
16. Write a Java program to sort the elements using for loop.
public class SortArray {
public static void main(String[] args) {

int[] arr = {5, 2, 8, 1, 3};

int temp;

// Sorting using for loop


for (int i = 0; i < [Link]; i++) {
for (int j = i + 1; j < [Link]; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

// Printing sorted array


[Link]("Sorted Array:");
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
}
}
}

You might also like