0% found this document useful (0 votes)
14 views

Java Preparation Unit - 1

Uploaded by

Vighnesh Pote
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java Preparation Unit - 1

Uploaded by

Vighnesh Pote
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Java Preparation

Unit-1
Basic Syntactical Constructs in Java
2 Marks
1. Enlist any two logical operators and two bitwise operators.
OR
Enlist the logical operators in Java.
OR
Enlist the Relational /comparison operators in Java.
Ans) Logical Operators:
1. AND Operator (&&): Returns true if both operands are true.
2. OR Operator (||): Returns true if at least one of the operands is true.
3. NOT Operator (!): Returns true if the operand is false and vice versa.

Bitwise Operators:
1. Bitwise OR (|): Sets each bit to 1 if either of the corresponding bits of the two
operands is 1.
2. Bitwise AND (&): Sets each bit to 1 if both corresponding bits of the two
operands are 1.
3. Bitwise XOR (^): Sets each bit to 1 if only one of the corresponding bits of the
two operands is 1.
4. Bitwise Complement (~): Flips the bits of its operand.
5. Bitwise Left Shift (<<): Shifts the bits of the first operand to the left by the
number of positions specified by the second operand.
6. Bitwise Right Shift (>>): Shifts the bits of the first operand to the right by the
number of positions specified by the second operand.

Comparison Operators:

2. Write down the syntax of array declaration, initialization.


Ans) Array Declaration Syntax:
datatype[] arrayName;
Here, datatype is the type of element that will be stored in the array, [] denotes an array,
and arrayName is the name of the array.

Array Initialization Syntax:


datatype[] arrayName = new datatype[size];
Here, datatype[] indicates the data type of the array elements and new datatype[size]
allocates memory for the array with the specified size.
3. Give the syntax and example for the following functions
i) min ( )
ii) sqrt ( )
Ans) i) min() Function:
• Explanation: The min() function returns the smaller of two specified numeric
values.
• Syntax: (Any one of the following )
static int min(int x, int y)
static long min(long x, long y)
static float min(float x, float y)
static double min(double x, double y)
• Example:
int minValue = Math.min(64, 45); // Returns the minimum of 64 and 45:

ii) sqrt() Function:


• Explanation: The sqrt() function returns the square root of a specified numeric
value.
• Syntax:
static double sqrt(double arg)
• Example:
double squareRoot = Math.sqrt(64); // Returns the square root of 64

4. Enlist any two access specifier with syntax.


Ans) There are 5 types of java access specifier:
• public
• private
• default (Friendly)
• protected
• private protected

5. Describe type casting in java with example.


Ans) Type Casting:
• The process of converting one data type to another is called casting or type casting.
• If the 2 types are compatible, then Java will perform the conversion automatically.
• It is possible to assign an int value to long variable.
• However, if two types of variables are not compatible, the type conversions are not
implicitly allowed, hence the need for typecasting.

There are two types of conversion:


▪ Implicit Type Casting
▪ Explicit Type Casting

Example:
public class TypeCastingExample
{
public static void main(String[] args)
{
int intValue = 10;
double doubleValue = intValue;
System.out.println("Implicit Type Casting: " + doubleValue);

double anotherDoubleValue = 15.75;


int anotherIntValue = (int) anotherDoubleValue;
System.out.println("Explicit Type Casting: " + anotherIntValue);
}
}

6. Write all primitive data type available in Java with their storage Sizes in byte.
Ans)

7. List any eight features of Java.


Ans) Features of Java:
1. Data Abstraction and Encapsulation
2. Inheritance
3. Polymorphism
4. Platform independence
5. Portability
6. Robust
7. Supports multithreading
8. Supports distributed applications
9. Secure
10. Architectural neutral
11. Dynamic

8. Define array and list its types.


Ans) Array:
• An array is a fixed-size sequential collection of elements of the same data type.
• They have a fixed size, which is specified at the time of array creation.
• Elements in an array are indexed starting from 0.
• All elements in an array must be of same data type.

Types of array are:


▪ Single-Dimensional Array(One-Dimentional)
▪ Multi-Dimensional Array
o Two-Dimentional
o Three-Dimentional
4 Marks
1. Explain implicit and explicit type conversion with example in detail.
OR
Describe type casting in java with example
Ans) Type Casting:
• The process of converting one data type to another is called casting or type casting.
• If the 2 types are compatible, then Java will perform the conversion automatically.
• It is possible to assign an int value to long variable.
• However, if two types of variables are not compatible, the type conversions are not
implicitly allowed, hence the need for typecasting.

There are two types of conversion:


▪ Implicit Type Casting
▪ Explicit Type Casting

1) Implicit Type Casting:


• Implicit typecasting is converting smaller data type to larger data type.
• It is also called widening.
• Java automatically performs implicit typecasting.
• Implicit typecasting does not result in data loss.
• For Example: Converting ‘int’ datatype into ‘double’.

2) Explicit Type Casting:


• Explicit typecasting is converting larger data type into smaller data type.
• It is also called narrowing.
• Explicit typecasting is not performed implicitly. We need to explicitly specify
the target data type to perform the conversion.
• Explicit typecasting may result in data loss or truncation of the value.
• For Example: Converting ‘double’ datatype into ‘int’

Example:
public class TypeCastingExample
{
public static void main(String[] args)
{
int intValue = 10;
double doubleValue = intValue;
System.out.println("Implicit Type Casting: " + doubleValue);

double anotherDoubleValue = 15.75;


int anotherIntValue = (int) anotherDoubleValue;
System.out.println("Explicit Type Casting: " + anotherIntValue);
}
}

2. Explain any four features of Java.


OR
Explain the concept of platform independence and portability with respect to Java
language.
Ans) Features Of Java:
1. Data Abstraction and Encapsulation:
• Abstraction: Java allows you to represent essential features without including
the background details. For example, a class representing a car may abstract
away the details of its internal combustion engine.
• Encapsulation: Java supports encapsulation, which means bundling the data
(attributes) and methods (behaviors) that operate on the data into a single unit
(class). Access to the data is controlled by access specifiers like private,
protected, and public.

2. Inheritance:
• Inheritance allows one class (subclass or derived class) to inherit the properties
and behaviors (methods) of another class (superclass or base class).
• It promotes code reusability and allows the creation of a hierarchy of classes.

3. Polymorphism:
• Polymorphism means the ability to take many forms. In Java, polymorphism
allows objects to be treated as instances of their superclass, enabling different
behaviors to be invoked through a single interface.
• It includes method overriding and method overloading.

4. Platform Independence:
• Java programs are compiled into platform-independent bytecode, which can be
executed on any platform with a Java Virtual Machine (JVM).
• This is achieved through the "Write once, run anywhere" (WORA) principle.

5. Portability:
• Portability refers to the ability of Java programs to run on any platform with a
compatible JVM without modification.
• Java achieves portability by providing a standard set of libraries and APIs.

6. Robust:
• Java is robust due to its strong memory management, automatic garbage
collection, exception handling mechanism, and strict compile-time and runtime
checking.
• It prevents memory leaks, buffer overflows, and other common programming
errors.

7. Supports Multithreading:
• Java supports multithreading, allowing concurrent execution of multiple threads
within a single program.
• Multithreading enhances responsiveness and improves performance in
applications that need to perform multiple tasks simultaneously.

8. Supports Distributed Applications:


• Java provides libraries and APIs for network communication, allowing the
development of distributed applications that can run on different machines
connected via a network.
• Java's networking capabilities simplify the development of client-server
applications and web services.

9. Secure:
• Java's security features include bytecode verification, classloader architecture,
access control mechanisms, and the Java Security Manager.
• These features prevent unauthorized access to resources and protect against
malicious code.

10. Architectural Neutral:


• Java is designed to be architectural neutral, meaning it can be implemented on
any hardware or software platform.
• It is not tied to any specific architecture, allowing Java programs to run on
various platforms seamlessly.

11. Dynamic:
• Java is dynamically extensible, meaning classes can be loaded on-demand at
runtime.
• This enables dynamic linking of libraries and the creation of flexible, adaptable
applications.

3. Explain any four visibility controls in Java.


Ans) Visibility controls in Java, also known as access specifiers, define the level of accessibility
or visibility of classes, variables, methods, and constructors within a Java program.

There are five types of access specifiers in Java:


1. public:
• The public access specifier allows the element to be accessed from
anywhere, both within the same package and from other packages.
• Public members are visible to all classes, regardless of their location.

2. private:
• The private access specifier restricts access to the element only within the
same class where it is declared.
• Private members are not visible to any other class, even within the same
package.

3. default (Friendly):
• The default access specifier, also known as the package-private specifier,
allows access to the element within the same package but not from outside
the package.
• If no access specifier is specified, Java considers it as default access.
• Default members are visible only within the same package and not to
classes outside the package.
4. protected:
• The protected access specifier allows access to the element within the
same package and by subclasses (inheritance), regardless of their location.
• Protected members are visible to subclasses and classes within the same
package.

5. private protected (Introduced in Java 9):


• The private protected access specifier combines the behavior of private
and protected.
• It allows access within the same package and by subclasses, but not from
classes outside the package that are not subclasses.

4. Explain switch case and conditional operator in java with suitable example.
Ans) Switch-case Statement:
• The switch-case statement is used to select one of many code blocks to be
executed based on the value of a variable or expression.
• It provides a cleaner and more readable way to write multiple if-else statements
when comparing the value of a single variable against multiple possible values.
• The switch-case statement consists of multiple case blocks and an optional default
block.
• When a switch-case statement is executed, the value of the expression inside the
switch is compared with the values of each case block.
• If a match is found, the corresponding case block is executed. If no match is found,
the optional default block is executed (if present).
Syntax:
switch (expression) {
case value1:
// Code block to execute if expression matches value1
break;
case value2:
// Code block to execute if expression matches value2
break;
// Additional case blocks for other values
default:
// Code block to execute if no case matches expression
break;
}
Example:
public class SwitchCaseExample {
public static void main(String[] args) {
int dayOfWeek = 3;

switch (dayOfWeek) {
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;
default:
System.out.println("Invalid day");
break;
}
}
}
Conditional (Ternary) Operator:
• The conditional operator, also known as the ternary operator, is a shorthand way
of writing an if-else statement.
• It takes three operands: a boolean expression followed by a question mark (?), a
value if the expression is true, and a value if the expression is false.
• It is used to make decisions within a single expression rather than using multiple
lines of code.
• The conditional operator is useful when you want to assign a value to a variable
based on a condition in a concise manner.
Syntax:
variable = (condition) ? expression1 : expression2;
Example:
public class ConditionalOperatorExample
{
public static void main(String[] args) {
int x = 5;
int y = (x < 10) ? 10 : 20;

System.out.println("Value of y: " + y); // Output: Value of y: 10


}
}

5. Explain the concept of platform independence and portability with respect to Java
language.
Ans) Platform Independence in Java:
1. Java achieves platform independence by compiling the source code into bytecode,
rather than directly into machine code.
2. Bytecode is a platform-independent intermediate code.
3. The Java Virtual Machine (JVM) interprets the bytecode at runtime and translates
it into machine code suitable for the host platform.
4. This bytecode interpretation allows Java programs to run on any platform with a
compatible JVM, without the need for recompilation.
5. As a result, Java follows the "Write once, run anywhere" (WORA) principle,
enabling developers to write code on one platform and execute it on multiple
platforms without modification.
Portability in Java:
1. Portability in Java refers to the ability of Java programs to be easily transferred
from one computer system to another, without requiring modifications to the
code.
2. Java achieves portability by providing a standard set of libraries and APIs that
abstract away the underlying hardware and operating system details.
3. Java's platform-independent bytecode and the JVM enable Java programs to run
on different hardware architectures and operating systems seamlessly.
4. Developers can write Java applications once and deploy them across various
platforms, reducing the effort and cost associated with maintaining multiple code
bases for different platforms.

6. Explain any two logical operator in java with example.


Ans) Logical Operators in Java:
Logical operators in Java are used to perform logical operations on boolean expressions.
These operators are used to combine multiple conditions and produce a single boolean
result. There are three logical operators in Java:
1. AND Operator (&&):
• The AND operator returns true if both operands are true, otherwise, it
returns false.
• Syntax: expression1 && expression2
• Example: if (x > 0 && x < 10) { // true if x is greater than 0 and less
than 10 }
2. OR Operator (||):
• The OR operator returns true if at least one of the operands is true,
otherwise, it returns false.
• Syntax: expression1 || expression2
• Example: if (x == 0 || y == 0) { // true if either x or y is equal to 0 }
3. NOT Operator (!):
• The NOT operator is a unary operator that negates the value of its operand.
If the operand is true, it returns false, and vice versa.
• Syntax: !expression
• Example: if (!isDone) { // true if isDone is false }

Common Example:
public class LogicalOperatorsExample {
public static void main(String[] args) {
int x = 5;
int y = 10;
boolean isEven = (x % 2 == 0);
boolean isPositive = (y > 0);

// Using && (AND) operator


if (isEven && isPositive) {
System.out.println("Both x is even and y is positive");
} else {
System.out.println("Either x is not even or y is not positive");
}

// Using || (OR) operator


if (isEven || isPositive) {
System.out.println("Either x is even or y is positive (or both)");
} else {
System.out.println("Neither x is even nor y is positive");
}

// Using ! (NOT) operator


if (!isEven) {
System.out.println("x is not even");
} else {
System.out.println("x is even");
}
}
}

You might also like