You are on page 1of 20

Q1.

Ans:

1. Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.

2. Object- Oriented
Everything in Java is an object. Object-oriented means we organize our software as a
combination of different types of objects that incorporate both data and behavior.
3. Platform Independent
Java is platform independent because it is different from other languages like C, C+
+, etc. which are compiled into platform specific machines while Java is a write once,
run anywhere language.

4. Robust
The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection
o There are exception handling and the type checking mechanism in Java

5. Architecture-neutral
Java is architecture neutral because there are no implementation dependent features,
for example, the size of primitive types is fixed.

6. Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.

7. High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code.

8. Distributed
Java is distributed because it facilitates users to create distributed applications in
Java. RMI and EJB are used for creating distributed applications.

9. Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads.

10. Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means
classes are loaded on demand.

Q2.
Ans:

Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
1. Boolean Data Type
Boolean data type represents only one bit of information either true or false which
is intended to represent the two truth values of logic and Boolean algebra
2. Byte Data Type
The byte data type is an 8-bit signed two’s complement integer. The byte data type is
useful for saving memory in large arrays.
3. Short Data Type
The short data type is a 16-bit signed two’s complement integer. Similar to byte, use
a short to save memory in large arrays, in situations where the memory savings
actually matters.
4. Integer Data Type
It is a 32-bit signed two’s complement integer.
5. Long Data Type
The range of a long is quite large. The long data type is a 64-bit two’s complement
integer and is useful for those occasions where an int type is not large enough to
hold the desired value.
6. Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float
(instead of double) if you need to save memory in large arrays of floating-point
numbers
7. Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating-point. For
decimal values, this data type is generally the default choice
8. Char Data Type
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16
bits).

Example:

class DataType
{
public static void main(String args[])
{
char a = 'G';
int i = 89;
byte b = 4;
short s = 56;
double d = 4.355453532;
float f = 4.7333434f;
long l = 12121;

System.out.println("char: " + a);


System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("long: " + l);
}
}
Output:

char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121

Variable:

A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java:
local, instance and static.

1) Local Variable

A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class is
loaded in the memory.

Example :
public class Variable
{
public static void main(String[] args)
{
int num1 = 5;
int num2 = 7;
int sum;
sum = num1 + num2;

System.out.println("Sum: " + sum);

num1 = 10;
sum = num1 + num2;
System.out.println("New Sum: " + sum);
}
}

Output:
Sum: 12
New Sum: 17

Constants:
A constant is an entity in programming that is immutable. In other words, the value
that cannot be changed
Constant is a value that cannot be changed after assigning it. Java does not directly
support the constants. There is an alternative way to define the constants in Java by
using the non-access modifiers static and final.
When we use static and final modifiers together, the variable remains static and can
be initialized once. Therefore, to declare a variable as constant, we use both static and
final modifiers. It shares a common memory location for all objects of its containing
class.

Example:
public class Constants
{
public static final double PI = 3.14159;
public static final int MAX_VALUE = 100;

public static void main(String[] args)


{
System.out.println("Value of PI: " + PI);
System.out.println("Max Value: " + MAX_VALUE);
}
}

Output:
Value of PI: 3.14159
Max Value: 100

Q4.
Ans:

Java provides statements that can be used to control the flow of Java code. Such
statements are called control flow statements. It is one of the fundamental features
of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program
is diverted depending upon the specific condition. The condition of the If statement
gives a Boolean value, either true or false.

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block. The else block is executed if the condition of the if-block is
evaluated as false.

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if


statements. In other words, we can say that it is the chain of if-else statements that
create a decision tree where the program may enter in the block of code where the
condition is true.

4. Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside


another if or else-if statement.
Example:
public class ConditionalExample
{
public static void main(String[] args)
{
int num = 10;
if (num > 0)
{
System.out.println("The number is positive.");
}
if (num % 2 == 0)
{
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
if (num > 0)
{
if (num % 2 == 0)
{
System.out.println("The number is positive and even.");
} else
{
System.out.println("The number is positive and odd.");
}
}
else
{
System.out.println("The number is non-positive.");
}
}
}

Output:
The number is positive.
The number is even.
The number is positive and even.

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while
some condition evaluates to true. However, loop statements are used to execute the
set of instructions in a repeated order.

for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable,
check the condition, and increment/decrement in a single line of code. We use the
for loop only when we exactly know the number of times, we want to execute the
block of code.

Ex:
for (int i = 0; i < 5; i++)

System.out.println("Iteration " + i);

for-each loop
Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable

Ex:

public class ForEachExample

public static void main(String[] args)

String[] colors = {"Red", "Green", "Blue", "Yellow"};

for (String color : colors)

System.out.println(color);

while loop
The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to
use a while loop. Unlike for loop, the initialization and increment/decrement doesn't
take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the
start of the loop

Ex:

int i = 0;

while (i < 5)

System.out.println("Iteration " + i);

i++;

do-while loop
The do-while loop checks the condition at the end of the loop after executing the
loop statements. When the number of iteration is not known and we have to execute
the loop at least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in
advance.

Ex:
int i = 0;
do
{
System.out.println("Iteration " + i);
i++;
} while (i < 5);

Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the
other part of the program. There are two types of jump statements in Java, i.e., break
and continue.

break statement
As the name suggests, the break statement is used to break the current flow of the
program and transfer the control to the next statement outside a loop or switch
statement. However, it breaks only the inner loop in the case of the nested loop.

public class BreakExample

public static void main(String[] args)

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

System.out.println("Iteration: " + i);

if (i == 3)

System.out.println("Breaking the loop...");

break;

continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it
skips the specific part of the loop and jumps to the next iteration of the loop
immediately.

public class ContinueExample


{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
System.out.println("Skipping iteration " + i);
continue;
}
System.out.println("Iteration: " + i);
}
}
}

Q5.
Ans:
The Java program compilation process involves several steps, starting from writing
the source code to generating the bytecode executable by the Java Virtual Machine
(JVM)

1. Writing the Source Code:


 The Java program starts with writing the source code in a text editor or
an Integrated Development Environment (IDE).
 Source code files typically have a .java extension.
2. Compiling the Source Code:
 Once the source code is written, it needs to be compiled into bytecode.
 Java provides a compiler called javac to compile Java source code files.
 The compilation process checks the syntax and semantics of the code
and generates bytecode if the code is error-free.
 Syntax errors, such as missing semicolons or incorrect identifiers, are
detected during this phase.
 If there are compilation errors, the compiler generates error messages
indicating the location and nature of the errors.
3. Generating Bytecode:
 Bytecode is a platform-independent intermediate representation of the
Java source code.
 The Java compiler ( javac) translates the source code into bytecode
instructions.
 Bytecode instructions are stored in .class files, which contain the
compiled code in a format understandable by the JVM.
4. Bytecode Verification:
 Before executing the bytecode, the JVM performs bytecode verification
to ensure that it adheres to Java language rules and does not violate
security constraints.
 Bytecode verification checks for illegal bytecode instructions, invalid
type casts, and other potential security vulnerabilities.
 If the bytecode passes verification, it is considered safe for execution;
otherwise, an error is thrown.
5. Loading and Execution:
 Once bytecode is verified, the JVM loads the .class files into memory.
 The class loader loads the required classes and resolves dependencies.
 The JVM then executes the bytecode instructions using its interpreter
or just-in-time (JIT) compiler.
 During execution, the JVM manages memory, threads, and other
runtime resources.
6. Just-In-Time (JIT) Compilation (Optional):
 Some JVM implementations use a JIT compiler to improve
performance.
 The JIT compiler translates bytecode into native machine code on-the-
fly during runtime.
 This native code is cached and reused for subsequent invocations of
the same code, leading to faster execution.
7. Garbage Collection:
 The JVM includes a garbage collector that automatically manages
memory by reclaiming memory occupied by objects that are no longer
in use.
 Garbage collection runs in the background, reclaiming memory from
unreachable objects and compacting memory to reduce fragmentation.
8. Execution Result:
 Finally, the Java program executes based on the bytecode instructions
provided.
 Output is displayed in the console or written to files, depending on the
program's functionality.

This compilation process ensures that Java programs are portable and can run on
any platform that has a compatible JVM implementation. Additionally, Java's strict
compilation and runtime environment help in providing robust and secure
applications.

Q6.
Ans:
Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store only a fixed set of elements
in a Java array.

Single-Dimensional Array:

A single-dimensional array stores elements in a linear sequence, accessed by a single


index.

Single-dimensional arrays are commonly used to store lists of items of the same
type, such as a list of integers, strings, or objects.

Example:
public class SingleDim
{
public static void main(String[] args)
{
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("First element: " + numbers[0]);
System.out.println("Second element: " + numbers[1]);

numbers[2] = 10;

for (int i = 0; i < numbers.length; i++)


{
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}

Multidimensional Array:
A multidimensional array stores elements in multiple dimensions, such as rows and
columns for a 2D array, or layers, rows, and columns for a 3D array.

Multidimensional arrays are used to represent data structures with multiple


dimensions, such as matrices, tables, or grids.

Example:

public class MultiDim


{
public static void main(String[] args)
{
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

System.out.println("Element at row 1, column 2: " + matrix[0][1]);


System.out.println("Element at row 2, column 3: " + matrix[1][2]);

matrix[1][1] = 10;

for (int i = 0; i < matrix.length; i++)


{
for (int j = 0; j < matrix[i].length; j++)
{
System.out.println("Element at row " + i + ", column " + j + ": " + matrix[i][j]);
}
}
}
}

Q7.
Ans:
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string. Strings are immutable in Java,
meaning once created, their values cannot be changed

1. Creating Strings:

 Strings in Java can be created using string literals or by using the new keyword
with the String constructor.

Ex:
String str1 = "Hello"; // Using string literal
String str2 = new String("World"); // Using constructor

2. Concatenation:

 Concatenation is the process of combining two strings into one.

Ex:
String fullName = str1 + " " + str2; // Concatenating two strings
System.out.println(fullName); // Output: Hello World

3. Length:

 The length() method returns the length of the string.

Ex:
int length = fullName.length(); // Getting the length of the string
System.out.println("Length of the string: " + length); // Output: Length of the string: 11

4. Substring:

 The substring() method extracts a portion of the string.

Ex:
String subStr = fullName.substring(6); // Extracting substring from index 6 to end
System.out.println("Substring: " + subStr); // Output: Substring: World

5. Index Of:

 The indexOf() method returns the index of the first occurrence of a specified
substring within the string.

Ex:
int index = fullName.indexOf("World"); // Finding the index of "World" in the string
System.out.println("Index of 'World': " + index); // Output: Index of 'World': 6

6. Conversion:

 Strings can be converted to uppercase or lowercase using toUpperCase() and


toLowerCase() methods.

Ex:
String upperCaseStr = fullName.toUpperCase(); // Converting string to uppercase
String lowerCaseStr = fullName.toLowerCase(); // Converting string to lowercase
System.out.println("Uppercase: " + upperCaseStr); // Output: Uppercase: HELLO WORLD
System.out.println("Lowercase: " + lowerCaseStr); // Output: Lowercase: hello world

7. Equality Comparison:

 Strings can be compared for equality using the equals() method or the equality
operator ( ==).

Ex:

boolean isEqual = str1.equals("Hello"); // Using equals() method for comparison


System.out.println("Is str1 equal to 'Hello'?: " + isEqual); // Output: Is str1 equal to 'Hello'?:
true

8. String Formatting:

 String formatting can be done using the printf() method or String.format()


method.

Ex:
int age = 30;
String formattedStr = String.format("My name is %s and I am %d years old.", fullName, age);
System.out.println(formattedStr); // Output: My name is Hello World and I am 30 years old.

Q8.
Ans:

In Java, a constructor is a block of codes similar to the method. It is called when an


instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is
called.

It calls a default constructor if there is no constructor available in the class. In such


case, Java compiler provides a default constructor by default.

There are two types of constructors in Java:


1. Default constructor (no-arg constructor)
2. Parameterized constructor

Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.

Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.

Ex:
public class Car {
private String make;
private String model;
private int year;

// Constructor with parameters


public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}

// Getter methods
public String getMake() {
return make;
}

public String getModel() {


return model;
}

public int getYear() {


return year;
}

public static void main(String[] args) {


// Creating an instance of the Car class using the constructor
Car myCar = new Car("Toyota", "Camry", 2022);

// Accessing object properties using getter methods


System.out.println("Make: " + myCar.getMake());
System.out.println("Model: " + myCar.getModel());
System.out.println("Year: " + myCar.getYear());
}
}

Q9.
Ans:
In Java, ‘this’ is a reference variable that refers to the current object, or can be said “this” in
Java is a keyword that refers to the current object instance. It can be used to call current
class methods and fields, to pass an instance of the current class as a parameter, and to
differentiate between the local and instance variables. Using “this” reference can improve
code readability and reduce naming conflicts.

Following are the ways to use the ‘this’ keyword in Java mentioned below:
1. Using the ‘this’ keyword to refer to current class instance variables.
Ex:
public class MyClass {
private int x;

public void setX(int x) {


this.x = x; // 'this' is used to refer to the instance variable x
}
}

2. Using this() to invoke the current class constructor


Ex:
public class MyClass {
private int x;

public MyClass() {
this(0); // Invoking parameterized constructor with default value
}

public MyClass(int x) {
this.x = x;
}
}

3. Using ‘this’ keyword to return the current class instance


Ex:
public class MyClass {
private int x;

public MyClass setX(int x) {


this.x = x;
return this; // Returning the current class instance
}
}
4. Using ‘this’ keyword as the method parameter
Ex:
public class MyClass {
private int x;

public void doSomething(MyClass obj) {


// Method implementation
}

public void anotherMethod() {


doSomething(this); // Passing 'this' as an argument
}
}

5. Using ‘this’ keyword to invoke the current class method


Ex:
public class MyClass {
private int x;

public void method1() {


// Method implementation
}

public void method2() {


this.method1(); // Invoking method1 using 'this'
}
}

6. Using ‘this’ keyword as an argument in the constructor call


Ex:
public class MyClass {
private int x;

public MyClass() {
this(0); // Invoking parameterized constructor with default value
}

public MyClass(int x) {
this.x = x;
}
}

Q10.
Ans:
Garbage collection in Java is the process by which Java programs perform automatic
memory management. Java programs compile to bytecode that can be run on a Java
Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are
created on the heap, which is a portion of memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage collector finds these
unused objects and deletes them to free up memory.
Why garbage collection is necessary in Java:
1. Automatic Memory Management: In Java, developers do not manually allocate and
deallocate memory for objects. Instead, the Java Virtual Machine (JVM) automatically
manages memory, including allocating memory for new objects and reclaiming memory from
objects that are no longer reachable.
2. Preventing Memory Leaks: Without garbage collection, if developers forget to deallocate
memory or lose reference to objects, it could lead to memory leaks, where memory is
consumed by unreachable objects, eventually leading to OutOfMemoryError.
3. Simplifying Memory Management: Garbage collection simplifies memory management for
developers by removing the burden of manual memory management. Developers can focus
on writing application logic rather than worrying about memory allocation and deallocation.

How Garbage Collection takes place in Java:


1. Mark and Sweep: Garbage collection involves two main steps: marking objects that are still
in use, and then sweeping away (deleting) the rest.
2. Generational Approach: It divides memory into different areas and applies different cleanup
strategies to each area based on how long objects have been there.
3. Minor and Major Cleanup: It performs regular, quick cleanups for newer objects, and less
frequent, deeper cleanups for older ones.
4. Background Threads: Garbage collection runs in the background, so it doesn't disrupt the
main program's execution.
5. Tuning: There are tools and options available to tweak how garbage collection behaves to
better suit your application's needs and performance requirements.

You might also like