0% found this document useful (0 votes)
9 views43 pages

Java Data Types and Control Structures

The document provides an overview of core Java concepts, including data types, control structures, methods, and string handling. It explains primitive and non-primitive data types, type conversion, the use of the final keyword, and differences between break and continue statements. Additionally, it covers method overloading, pass by value vs. reference, recursion, and the differences between String, StringBuilder, and StringBuffer.

Uploaded by

Prem Shinde
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)
9 views43 pages

Java Data Types and Control Structures

The document provides an overview of core Java concepts, including data types, control structures, methods, and string handling. It explains primitive and non-primitive data types, type conversion, the use of the final keyword, and differences between break and continue statements. Additionally, it covers method overloading, pass by value vs. reference, recursion, and the differences between String, StringBuilder, and StringBuffer.

Uploaded by

Prem Shinde
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

📁

1. Core Java Basics

1. Data Types and Variables

1. What are the different data types in Java? Provide examples of


each.
Answer:
Java has two types of data types: primitive and non-primitive.

Primitive types: These are predefined by Java and include:

int (integer numbers): Example: int age = 25;

double (decimal numbers): Example: double salary = 5000.50;

char (single character): Example: char grade = 'A';

boolean (true or false): Example: boolean isActive = true;

Others are float , long , short , and byte .

Non-primitive types: These include objects and arrays. Examples:

String: String name = "Prem";

Arrays: int[] numbers = {1, 2, 3};

Primitive types store values directly, while non-primitive types store references to
objects.

2. What is the difference between int and Integer ?


Answer:

1. Core Java Basics 1


int is a primitive data type, while Integer is a wrapper class in Java.

int stores the actual numeric value. Example: int x = 10;

is an object that wraps the primitive value and provides additional


Integer

methods. Example: Integer y = 20;

Key Differences:

int is more memory-efficient and faster because it's directly stored in memory.

allows null values and can be used in collections like ArrayList where
Integer

objects are required. Example: ArrayList<Integer> list = new ArrayList<>();

3. How does Java handle type conversion?


Answer:
Java handles type conversion in two ways:

1. Implicit Casting (Widening): Automatically converts a smaller type to a larger


type.
Example:

int a = 10;
double b = a; // int to double (widening)
[Link](b); // Output: 10.0

This is safe because there's no loss of information.

2. Explicit Casting (Narrowing): Manually converts a larger type to a smaller


type.

Example:

double x = 10.5;
int y = (int) x; // double to int (narrowing)
[Link](y); // Output: 10

Here, you might lose data (e.g., the decimal part).

1. Core Java Basics 2


Implicit casting happens automatically, but explicit casting requires the
programmer to handle potential data loss.

4. What is the default value of a local variable and an instance


variable?
Answer:

Local variables: These do not have a default value. They must be initialized
before use. If you try to access a local variable without initializing it, the
compiler will throw an error.
Example:

void display() {
int num; // Not initialized
// [Link](num); // This will give a compile-time error
}

Instance variables: These do have default values depending on the data


type:

Numeric types ( int , double , etc.): 0

boolean : false

char : '\\u0000' (null character)

Non-primitive types ( String , arrays): null

Example:

class Example {
int number; // Default value is 0
String name; // Default value is null
}

5. What is the final keyword in Java, and how is it used with


variables?

1. Core Java Basics 3


Answer:
The final keyword is used to declare constants or make variables immutable.

Once a final variable is assigned a value, it cannot be changed.


Example:

final int MAX_VALUE = 100;


// MAX_VALUE = 200; // This will give a compile-time error

Use Cases:

1. For constants: final double PI = 3.14;

2. To prevent reassignment in a method:

void display(final int num) {


// num = num + 1; // This will give a compile-time error
}

Declaring a variable as final ensures that its value remains consistent

2. Control Structures
What is the difference between break and continue ? Provide examples.

How does the switch statement work in Java? Can it handle strings?

Write a program to print numbers from 1 to 100, skipping multiples of 5.

Explain the difference between a while loop and a do-while loop with
examples.

How do nested loops work? Can they be optimized?

1. What is the difference between break and continue ? Provide


examples.
Answer:

1. Core Java Basics 4


The break statement is used to exit a loop or a switch case prematurely.

The continue statement skips the remaining code in the current iteration and
moves to the next iteration of the loop.

Example:

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


if (i == 5) {
break; // Exits the loop when i equals 5
}
[Link](i);
}
// Output: 1 2 3 4

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


if (i % 2 == 0) {
continue; // Skips even numbers
}
[Link](i);
}
// Output: 1 3 5 7 9

2. How does the switch statement work in Java? Can it handle


strings?
Answer:

The switch statement evaluates an expression and matches it against multiple case

values. If a match is found, the code inside that case block is executed. Java
supports strings in the switch statement (from Java 7 onward).

Syntax:

switch (expression) {
case value1:
// Code block
break;

1. Core Java Basics 5


case value2:
// Code block
break;
default:
// Code block if no case matches
}

Example with Strings:

String day = "Monday";


switch (day) {
case "Monday":
[Link]("Start of the workweek");
break;
case "Friday":
[Link]("End of the workweek");
break;
default:
[Link]("Midweek day");
}
// Output: Start of the workweek

3. Write a program to print numbers from 1 to 100, skipping


multiples of 5.
Answer:

public class SkipMultiplesOfFive {


public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 5 == 0) {
continue; // Skip multiples of 5
}
[Link](i + " ");
}

1. Core Java Basics 6


}
}

Output:
1 2 3 4 6 7 8 9 11 ...

4. Explain the difference between a while loop and a do-while


loop with examples.
Answer:

A while loop evaluates the condition before executing the loop body. If the
condition is false initially, the loop body won’t execute.

A do-while loop evaluates the condition after executing the loop body. The loop
body will execute at least once, even if the condition is false.

Example:

// while loop
int x = 5;
while (x < 5) { // Condition checked first
[Link]("This won't print");
}

// do-while loop
int y = 5;
do {
[Link]("This will print once");
} while (y < 5);

5. How do nested loops work? Can they be optimized?


Answer:
Nested loops are loops inside other loops. The inner loop runs completely for
each iteration of the outer loop.

Example:

1. Core Java Basics 7


for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
[Link]("i: " + i + ", j: " + j);
}
}
// Output:
// i: 1, j: 1
// i: 1, j: 2
// i: 1, j: 3
// i: 2, j: 1
// ...

Optimization Tips:

Avoid unnecessary iterations by modifying loop conditions or using break .

Use appropriate data structures or algorithms to reduce time complexity.

Example of optimization:

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


for (int j = i; j <= 3; j++) { // Start from 'i' instead of 1
[Link]("i: " + i + ", j: " + j);
}
}

This reduces redundant iterations.

Let me know if you'd like detailed explanations or additional examples!

3. Methods
What is method overloading? Provide a program to illustrate.

What is the difference between pass by value and pass by reference in Java?

What are varargs ( ... )? Write a method to demonstrate their use.

Can a method have a return type of void and still return a value?

1. Core Java Basics 8


Explain the concept of recursion with an example.

1. What is method overloading? Provide a program to illustrate.


Answer:
Method overloading is a feature in Java where multiple methods in the same class
have the same name but different parameter lists (number, type, or order of
parameters). It allows methods to perform similar operations but with different
inputs.
Example:

class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two doubles


double add(double a, double b) {
return a + b;
}
}

public class MethodOverloadingExample {


public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](10, 20)); // Output: 30
[Link]([Link](10, 20, 30)); // Output: 60
[Link]([Link](10.5, 20.3)); // Output: 30.8

1. Core Java Basics 9


}
}

2. What is the difference between pass by value and pass by


reference in Java?
Answer:

Java uses pass by value for both primitives and objects. This means a copy of
the value is passed to the method.

For primitives, the actual value is copied.

For objects, the reference (memory address) is copied, so changes made to


the object inside the method reflect outside, but you cannot reassign the
reference itself.

Example:

class Test {
void modifyPrimitive(int num) {
num = 20; // Change won't affect the original value
}

void modifyObject(StringBuilder sb) {


[Link](" World!"); // Change will reflect outside
}
}

public class PassByValueExample {


public static void main(String[] args) {
Test test = new Test();

int num = 10;


[Link](num);
[Link]("Primitive value: " + num); // Output: 10

StringBuilder sb = new StringBuilder("Hello");

1. Core Java Basics 10


[Link](sb);
[Link]("Object value: " + sb); // Output: Hello World!
}
}

3. What are varargs ( ... )? Write a method to demonstrate their


use.
Answer:
Varargs (variable-length arguments) allow you to pass a variable number of
arguments to a method. It is declared using ... in the method parameter.

Example:

class VarargsExample {
void displayNumbers(int... numbers) {
[Link]("Number of arguments: " + [Link]);
for (int num : numbers) {
[Link](num + " ");
}
[Link]();
}
}

public class VarargsDemo {


public static void main(String[] args) {
VarargsExample example = new VarargsExample();
[Link](1, 2, 3); // Output: 1 2 3
[Link](10, 20, 30, 40); // Output: 10 20 30 40
[Link](); // Output: (no arguments)
}
}

Key Points:

Varargs must be the last parameter in a method.

1. Core Java Basics 11


Only one vararg parameter is allowed in a method.

4. Can a method have a return type of void and still return a


value?
Answer:

No, a method with a void return type cannot return a value. However, it can use
the return statement to exit the method early without returning a value.
Example:

void checkNumber(int num) {


if (num < 0) {
[Link]("Negative number");
return; // Exits the method early
}
[Link]("Positive number");
}

If you try to return a value in a void method, the compiler will throw an error.

5. Explain the concept of recursion with an example.


Answer:

Recursion is a programming technique where a method calls itself to solve smaller


sub-problems of the original problem. Every recursive method needs a base
condition to terminate the recursion.

Example:

class RecursionExample {
// Method to calculate factorial recursively
int factorial(int n) {
if (n == 0 || n == 1) { // Base condition
return 1;
}
return n * factorial(n - 1); // Recursive call

1. Core Java Basics 12


}
}

public class RecursionDemo {


public static void main(String[] args) {
RecursionExample example = new RecursionExample();
[Link]("Factorial of 5: " + [Link](5)); // Output: 120
}
}

How It Works:

The method keeps calling itself with a smaller value of n until it reaches the
base condition ( n == 0 or n == 1 ).

Once the base condition is met, the recursion unwinds, and the results are
calculated step-by-step.

Key Points:

Ensure there’s a base condition; otherwise, it will lead to a StackOverflowError .

Recursion can be memory-intensive; use iteration if possible for efficiency.

4. String Handling
What is the difference between String , StringBuilder , and StringBuffer ?

How does the equals() method differ from == for strings?

What is the difference between substring() and split() in the String class?

Write a program to count the occurrences of a character in a string.

Explain the concept of string immutability. How does it improve memory


efficiency?

Here are the answers to your String Handling questions:

1. Core Java Basics 13


1. What is the difference between String , StringBuilder , and
StringBuffer ?
Answer:

: Immutable. Once created, its value cannot be changed. Any


String

modification creates a new object.

StringBuilder : Mutable and not synchronized, meaning it is faster but not thread-
safe.

StringBuffer : Mutable and synchronized, making it thread-safe but slower than


StringBuilder .

Key Differences:

Feature String StringBuilder StringBuffer

Mutability Immutable Mutable Mutable

Thread-Safety Not thread-safe Not thread-safe Thread-safe

Slower for Faster for Slower than


Performance
modifications modifications StringBuilder

Example:

public class StringExamples {


public static void main(String[] args) {
// String
String s = "Hello";
s = s + " World"; // Creates a new object
[Link](s);

// StringBuilder
StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // Modifies the same object
[Link](sb);

// StringBuffer
StringBuffer sbf = new StringBuffer("Hello");
[Link](" World"); // Modifies the same object

1. Core Java Basics 14


[Link](sbf);
}
}

2. How does the equals() method differ from == for strings?


Answer:

compares references (memory locations), checking if two string objects


==

point to the same memory.

equals() compares the actual content (values) of the strings.

Example:

public class StringComparison {


public static void main(String[] args) {
String str1 = new String("Hello");
String str2 = new String("Hello");
String str3 = "Hello";

// Reference comparison
[Link](str1 == str2); // false, different objects
[Link](str3 == "Hello"); // true, same object in string pool

// Content comparison
[Link]([Link](str2)); // true, same content
}
}

3. What is the difference between substring() and split() in the


String class?
Answer:

substring(int start, int end) : Extracts a portion of the string from the start index to
(end-1).

1. Core Java Basics 15


split(String regex) : Splits the string into an array of substrings based on the regex
pattern.

Example:

public class StringMethods {


public static void main(String[] args) {
String str = "Java Programming";

// Substring
String sub = [Link](5, 16);
[Link]("Substring: " + sub); // Output: Programming

// Split
String[] parts = [Link](" ");
for (String part : parts) {
[Link](part); // Output: Java \\n Programming
}
}
}

4. Write a program to count the occurrences of a character in a


string.
Answer:

public class CharCount {


public static void main(String[] args) {
String str = "programming";
char target = 'm';
int count = 0;

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


if ([Link](i) == target) {
count++;
}

1. Core Java Basics 16


}

[Link]("Occurrences of '" + target + "': " + count); // Output:


2
}
}

5. Explain the concept of string immutability. How does it


improve memory efficiency?
Answer:
String Immutability:

A String object cannot be modified after creation. Any change creates a new
object.

For example:

String str = "Hello";


str = str + " World"; // A new object is created, "Hello" remains unchange
d.

Benefits of Immutability:

1. Memory Efficiency:

Strings are stored in the String Pool. If two strings have the same value,
they point to the same memory location. This avoids duplicating memory.

Example:

String str1 = "Java";


String str2 = "Java"; // Points to the same memory location

2. Thread-Safety:

Immutable strings are inherently thread-safe, as their values cannot be


changed.

1. Core Java Basics 17


3. Caching and Optimization:

Hash codes of strings are cached for faster retrieval in hash-based


collections like HashMap .

Let me know if you'd like further clarification or additional examples!

5. Arrays
What are the different ways to declare and initialize an array in Java?

Write a program to find the largest and smallest elements in an array.

How do multidimensional arrays work in Java?

What is the difference between a jagged array and a rectangular array ?

Write a program to reverse an array without using additional memory.

1. What are the different ways to declare and initialize an array in


Java?
Answer:

Arrays in Java can be declared and initialized in several ways:

1. Declaration Only:

int[] arr; // Preferred syntax


int arr[]; // Also valid

2. Declaration and Memory Allocation:

arr = new int[5]; // Array of size 5, initialized with default values (0 for int)

3. Declaration and Initialization:

int[] arr = {10, 20, 30, 40, 50}; // Initialize with values
int[] arr2 = new int[]{10, 20, 30, 40, 50}; // Explicit initialization

4. For Multi-dimensional Arrays:

1. Core Java Basics 18


int[][] matrix = new int[3][3]; // 3x3 rectangular array
int[][] jagged = new int[3][]; // Jagged array, rows can have varying length
s

2. Write a program to find the largest and smallest elements in an


array.
Program:

public class ArrayMinMax {


public static void main(String[] args) {
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6};
int max = arr[0];
int min = arr[0];

for (int num : arr) {


if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}

[Link]("Largest Element: " + max); // Output: 9


[Link]("Smallest Element: " + min); // Output: 1
}
}

3. How do multidimensional arrays work in Java?


Answer:
Multidimensional arrays in Java are arrays of arrays. The most common type is a
rectangular array, where each row has the same number of columns. Java also

1. Core Java Basics 19


supports jagged arrays, where rows can have different lengths.
Example of a Rectangular Array:

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
[Link](matrix[1][2]); // Output: 6

Example of a Jagged Array:

int[][] jagged = new int[3][];


jagged[0] = new int[]{1, 2};
jagged[1] = new int[]{3, 4, 5};
jagged[2] = new int[]{6};

[Link](jagged[1][2]); // Output: 5

4. What is the difference between a jagged array and a rectangular


array ?

Feature Rectangular Array Jagged Array

Structure All rows have the same length. Rows can have different lengths.

Memory Usage Requires contiguous memory. Uses less memory for sparse data.

Declaration int[][] arr = new int[3][3]; int[][] arr = new int[3][];

Example {{1, 2}, {3, 4}} {{1, 2}, {3, 4, 5}}

5. Write a program to reverse an array without using additional


memory.
Program:

1. Core Java Basics 20


public class ReverseArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};

// Reversing the array in-place


int start = 0, end = [Link] - 1;
while (start < end) {
// Swap elements
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;

start++;
end--;
}

// Printing the reversed array


for (int num : arr) {
[Link](num + " "); // Output: 5 4 3 2 1
}
}
}

Would you like further details or examples?

6. Input and Output


How do you take input from a user in Java using Scanner ?

Write a program to read and print a matrix.

Explain the role of [Link] , [Link] , and [Link] .

What is the difference between print() and println() methods?

1. How do you take input from a user in Java using Scanner ?

1. Core Java Basics 21


Answer:
The Scanner class in Java is used to take user input from the console.
Steps to Use Scanner :

1. Import the [Link] package.

2. Create an instance of Scanner .

3. Use appropriate methods (e.g., nextInt() , nextLine() ) to read input.

Example:

import [Link];

public class UserInputExample {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Reading input
[Link]("Enter your name: ");
String name = [Link]();

[Link]("Enter your age: ");


int age = [Link]();

[Link]("Hello " + name + ", you are " + age + " years old.");

[Link](); // Always close the scanner to release resources


}
}

2. Write a program to read and print a matrix.


Program:

import [Link];

1. Core Java Basics 22


public class MatrixInputOutput {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter the number of rows: ");


int rows = [Link]();
[Link]("Enter the number of columns: ");
int cols = [Link]();

int[][] matrix = new int[rows][cols];

// Reading the matrix


[Link]("Enter the elements of the matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = [Link]();
}
}

// Printing the matrix


[Link]("The matrix is:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}

[Link]();
}
}

3. Explain the role of [Link] , [Link] , and [Link] .


Answer:

1. Core Java Basics 23


[Link] :

Represents the standard input stream, typically the keyboard.

Used to read input using tools like Scanner or BufferedReader .

[Link] :

Represents the standard output stream.

Used to print data to the console using print() , println() , or printf() .

[Link] :

Represents the standard error stream.

Used to display error messages separately from standard output, often in


red in IDEs.

Example:

public class SystemStreamsExample {


public static void main(String[] args) {
[Link]("This is standard output.");
[Link]("This is an error message.");
}
}

4. What is the difference between print() and println() methods?


Answer:

Feature print() println()

Outputs text without a


Behavior Outputs text followed by a newline.
newline.

Used to move to the next line after


Use Case Used for inline outputs.
output.

Example:

1. Core Java Basics 24


public class PrintVsPrintln {
public static void main(String[] args) {
[Link]("Hello"); // No newline
[Link](" World");
[Link]("!"); // Adds a newline
[Link]("This is on a new line.");
}
}

Output:

Hello World!
This is on a new line.

Let me know if you'd like further examples or clarification!

7. Operators
What is the difference between && and & , || and | in Java?

Explain operator precedence with an example.

What is the instanceof operator? Provide a use case.

How do unary operators like ++ and - work in pre-increment and post-


increment?

What are bitwise operators in Java? Explain with examples.

1. What is the difference between && and & , || and | in Java?


Answer:

These operators are used for logical and bitwise operations.

Operator Type Behavior

Short-circuiting: Evaluates the second condition only if


&& Logical AND
the first is true.

1. Core Java Basics 25


Performs a bitwise AND operation on binary
& Bitwise AND
representations.

` `

` ` Bitwise OR

Examples:

public class LogicalBitwiseExample {


public static void main(String[] args) {
int a = 5, b = 10;

// Logical AND
if (a > 3 && b > 8) {
[Link]("Logical AND is true."); // Output
}

// Bitwise AND
[Link]("Bitwise AND: " + (a & b)); // Output: 0 (binary: 0101 &
1010)

// Logical OR
if (a > 10 || b > 8) {
[Link]("Logical OR is true."); // Output
}

// Bitwise OR
[Link]("Bitwise OR: " + (a | b)); // Output: 15 (binary: 0101 | 10
10)
}
}

2. Explain operator precedence with an example.


Answer:
Operator precedence determines the order in which operations are performed.

1. Core Java Basics 26


Precedence Level Operators

Highest () , . , []

Unary ( + , - , ++ , -- , ! )

Multiplicative ( * , / , % )

Additive ( + , - )

Relational ( < , > , <= , >= )

Logical ( && , `

Lowest Assignment ( = , += , -= , etc.)

Example:

public class OperatorPrecedence {


public static void main(String[] args) {
int result = 10 + 2 * 5 / 2 - 3;
// Step-by-step:
// 1. Multiplication and division: 2 * 5 = 10, 10 / 2 = 5
// 2. Addition and subtraction: 10 + 5 = 15, 15 - 3 = 12
[Link]("Result: " + result); // Output: 12
}
}

3. What is the instanceof operator? Provide a use case.


Answer:
The instanceof operator is used to check whether an object is an instance of a
specific class or implements an interface.

Syntax:

object instanceof ClassName

Use Case:

class Parent {}
class Child extends Parent {}

1. Core Java Basics 27


public class InstanceofExample {
public static void main(String[] args) {
Parent obj = new Child();

[Link](obj instanceof Parent); // Output: true


[Link](obj instanceof Child); // Output: true
}
}

This is often used in polymorphism to determine the object's runtime type.

4. How do unary operators like ++ and - work in pre-increment


and post-increment?
Answer:

Operation Behavior

Pre-increment ++a : Increments the value, then uses it in the expression.

Post-increment a++ : Uses the current value in the expression, then increments it.

Example:

public class UnaryOperators {


public static void main(String[] args) {
int a = 5, b;

// Pre-increment
b = ++a; // a = 6, b = 6
[Link]("Pre-increment: a = " + a + ", b = " + b);

// Post-increment
b = a++; // b = 6, a = 7
[Link]("Post-increment: a = " + a + ", b = " + b);
}
}

1. Core Java Basics 28


5. What are bitwise operators in Java? Explain with examples.
Answer:
Bitwise operators perform operations on the binary representation of numbers.

Operator Description Example (5 = 0101, 3 = 0011)


& Bitwise AND 5 & 3 = 1 (0001)

` ` Bitwise OR
^ Bitwise XOR 5 ^ 3 = 6 (0110)

~ Bitwise Complement ~5 = -6 (inverts all bits)

<< Left Shift 5 << 1 = 10 (1010)

>> Right Shift 5 >> 1 = 2 (0010)

Example:

public class BitwiseExample {


public static void main(String[] args) {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary

[Link]("Bitwise AND: " + (a & b)); // Output: 1


[Link]("Bitwise OR: " + (a | b)); // Output: 7
[Link]("Bitwise XOR: " + (a ^ b)); // Output: 6
[Link]("Bitwise Complement: " + (~a)); // Output: -6
[Link]("Left Shift: " + (a << 1)); // Output: 10
[Link]("Right Shift: " + (a >> 1)); // Output: 2
}
}

Let me know if you’d like any further explanations or additional examples!

8. Type Conversion
What is implicit type conversion? Provide an example.

1. Core Java Basics 29


What is explicit type casting? When is it required?

Write a program to convert a double to int and explain the data loss.

What is autoboxing and unboxing in Java?

Can we convert a String to a number in Java? If so, how?

1. What is implicit type conversion? Provide an example.


Answer:
Implicit type conversion, also known as automatic type casting, occurs when the
Java compiler automatically converts a smaller data type to a larger one. This
happens when there is no risk of data loss, and the conversion is safe.
Example:

public class ImplicitConversion {


public static void main(String[] args) {
int num = 100; // 4 bytes
double result = num; // int is automatically converted to double (8 bytes)

[Link]("Implicit Conversion: " + result); // Output: 100.0


}
}

Here, the int value num is implicitly converted to a double during the assignment
because a double can hold larger values than an int without data loss.

2. What is explicit type casting? When is it required?


Answer:
Explicit type casting (or manual type casting) occurs when the programmer
explicitly tells the compiler to convert one type to another. This is done when
converting a larger data type to a smaller one, which could lead to data loss or
overflow, hence Java requires the programmer to perform this conversion using a
cast operator (type) .
Example:

1. Core Java Basics 30


public class ExplicitConversion {
public static void main(String[] args) {
double num = 9.99; // 8 bytes
int result = (int) num; // Explicit casting from double to int (data loss)

[Link]("Explicit Conversion: " + result); // Output: 9


}
}

In this case, the double value is explicitly cast to int , and the decimal part is
discarded during the conversion, leading to data loss.

3. Write a program to convert a double to int and explain the


data loss.
Program:

public class DoubleToIntConversion {


public static void main(String[] args) {
double num = 99.99; // 8 bytes
int convertedNum = (int) num; // Explicit casting from double to int

[Link]("Original double: " + num); // Output: 99.99


[Link]("Converted int: " + convertedNum); // Output: 99
}
}

Explanation:
Here, the double value 99.99 is cast to int , and during this conversion, the
fractional part .99 is discarded. This causes data loss, and the result is 99 instead
of 99.99 .

4. What is autoboxing and unboxing in Java?


Answer:

1. Core Java Basics 31


Autoboxing: It is the automatic conversion of primitive types to their
corresponding wrapper classes. For example, converting int to Integer , char to
Character , etc.

Unboxing: It is the reverse process where the wrapper class object is


converted to its corresponding primitive type.

Examples:

public class AutoboxingUnboxing {


public static void main(String[] args) {
// Autoboxing: converting primitive to wrapper class
int a = 10;
Integer obj = a; // [Link](a)

// Unboxing: converting wrapper class to primitive


Integer b = 20;
int c = b; // [Link]()

[Link]("Autoboxed Integer: " + obj); // Output: 10


[Link]("Unboxed int: " + c); // Output: 20
}
}

Autoboxing happens when you assign a primitive to a wrapper class, and


unboxing happens when you assign a wrapper class to a primitive.

5. Can we convert a String to a number in Java? If so, how?


Answer:

Yes, we can convert a String to a number in Java using parse methods of wrapper
classes like [Link]() , [Link]() , or [Link]() . These methods
throw NumberFormatException if the String cannot be converted to the desired numeric
type.
Example:

1. Core Java Basics 32


public class StringToNumber {
public static void main(String[] args) {
String str = "12345";
int num = [Link](str); // Convert String to int
double decimal = [Link]("12.34"); // Convert String to doub
le

[Link]("String to int: " + num); // Output: 12345


[Link]("String to double: " + decimal); // Output: 12.34
}
}

In this example:

[Link](str) converts the String to an int .

[Link]() converts the String to a double .

If the String does not represent a valid number, an exception will be thrown:

String invalid = "abc";


int invalidNum = [Link](invalid); // Throws NumberFormatException

Let me know if you need further details or examples!

9. Java Keywords
What is the difference between static and final keywords?

Explain the this keyword with an example.

What is the purpose of the void keyword in Java?

What is the default keyword used for in a switch case and interfaces?

1. What is the difference between static and final keywords?


Answer:

1. Core Java Basics 33


static keyword:

The static keyword is used to declare class-level variables and methods.


This means they belong to the class rather than to instances (objects) of
the class. A static member is shared by all instances of the class, and it
can be accessed without creating an object of the class.

Usage: It is used for constants, utility methods, and for sharing data
among all instances of a class.

final keyword:

The final keyword is used to declare constants, prevent method overriding,


or prevent inheritance. When applied to a variable, it makes that variable a
constant. When applied to a method, it prevents the method from being
overridden in subclasses. When applied to a class, it prevents the class
from being subclassed.

Example:

public class StaticFinalExample {


static int count = 0; // static variable shared by all instances

final int id; // final variable (constant)

StaticFinalExample(int id) {
[Link] = id; // final variable initialized in the constructor
}

static void incrementCount() {


count++; // static method can access static variables
}

public static void main(String[] args) {


StaticFinalExample obj1 = new StaticFinalExample(1);
StaticFinalExample obj2 = new StaticFinalExample(2);

[Link]("ID for obj1: " + [Link]); // Output: 1


[Link]("ID for obj2: " + [Link]); // Output: 2

1. Core Java Basics 34


incrementCount(); // Static method call
[Link]("Count: " + count); // Output: 1
}
}

In the above example:

count is a static variable, shared across all objects.

id is a final variable, making it immutable once assigned.

2. Explain the this keyword with an example.


Answer:
The this keyword refers to the current instance of the class. It is used to refer to
the current object, especially when there is a conflict between instance variables
and local variables. It can also be used to invoke instance methods, constructors,
and to pass the current object as a parameter to other methods.
Example:

public class ThisKeywordExample {


int x; // instance variable

ThisKeywordExample(int x) {
this.x = x; // `this.x` refers to the instance variable, `x` refers to the param
eter
}

void display() {
[Link]("Value of x: " + this.x); // `this` refers to the instance v
ariable
}

public static void main(String[] args) {


ThisKeywordExample obj = new ThisKeywordExample(5);
[Link](); // Output: Value of x: 5

1. Core Java Basics 35


}
}

In this example:

refers to the instance variable


this.x x , whereas x refers to the parameter of
the constructor.

3. What is the purpose of the void keyword in Java?


Answer:
The void keyword is used to indicate that a method does not return any value. It
specifies that the method is only used for performing an operation or side-effect
but does not provide a result back to the caller.
Example:

public class VoidKeywordExample {


void displayMessage() {
[Link]("Hello, World!"); // This method does not return any va
lue
}

public static void main(String[] args) {


VoidKeywordExample obj = new VoidKeywordExample();
[Link](); // Output: Hello, World!
}
}

In this example:

The displayMessage() method is declared with the void keyword, indicating that it
does not return anything.

4. What is the default keyword used for in a switch case and


interfaces?
Answer:

1. Core Java Basics 36


In switch case:

The default keyword is used as a fallback option when no case matches the
given expression. It is optional and can be used at the end of the switch

statement.

Example:

public class DefaultSwitchExample {


public static void main(String[] args) {
int day = 3;

switch(day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
default:
[Link]("Invalid day"); // Will be executed if no case matc
hes
}
}
}

In this example:

If day is not 1 or 2, the default case will be executed, printing "Invalid day" .

In interfaces (Java 8 and onwards):

The default keyword is used to define methods with default


implementations in interfaces. This allows adding new methods to
interfaces without breaking existing implementations.

Example:

1. Core Java Basics 37


interface MyInterface {
default void greet() {
[Link]("Hello from the default method in the interface!");
}
}

public class DefaultInterfaceExample implements MyInterface {


public static void main(String[] args) {
MyInterface obj = new DefaultInterfaceExample();
[Link](); // Output: Hello from the default method in the interface!
}
}

In this example:

The greet() method is a default method in the interface, and it provides a default
implementation which can be used directly or overridden by the implementing
class.

Let me know if you need further clarification or examples!

10. Miscellaneous
What is the main() method? Why is it declared as public static void main(String[] args) ?

What is the significance of [Link]() in Java?

Explain how Java handles memory allocation for objects and primitives.

What are comments in Java? What is the purpose of JavaDoc?

Can Java variables store Unicode characters? Demonstrate with an


example.

1. What is the main() method? Why is it declared as public static


void main(String[] args) ?
Answer:

1. Core Java Basics 38


The main() method in Java is the entry point of any Java program. When you run a
Java program, the Java Virtual Machine (JVM) starts execution from the main()

method. It is the first method that is called when the program starts.
Why it is declared as public static void main(String[] args) ?

: The main() method must be public because it is called by the JVM, which
public

is external to the class. If it's not public, the JVM won't be able to access it.

: The main() method is static so that it can be invoked without creating an


static

instance of the class. This allows the JVM to call the main() method without
needing to create an object of the class first.

void : The main() method does not return any value, so it is declared as void .

String[] args : This is an array of String objects that can hold command-line
arguments passed to the program when it is run.

Example:

public class MainMethodExample {


public static void main(String[] args) {
[Link]("Hello, World!"); // This is the first method executed w
hen the program starts.
}
}

In this example:

The main() method prints "Hello, World!" when the program is run.

2. What is the significance of [Link]() in Java?


Answer:

[Link]() is used to print text or data to the console or terminal.

System : It refers to the standard system class, which is a part of the [Link]

package and provides access to system resources.

out : It is a static member of the System class, which represents the standard
output stream (typically the console).

1. Core Java Basics 39


: It is a method of the PrintStream class (which [Link] is an instance of)
println()

that prints the argument followed by a newline. The difference between println()
and print() is that println() adds a new line after printing the text.

Example:

public class PrintExample {


public static void main(String[] args) {
[Link]("This is printed on a new line.");
[Link]("This is printed on the same line.");
[Link](" And this is printed on a new line again.");
}
}

In this example:

[Link]() prints the first and last lines, each followed by a new line, while
[Link]() prints the text on the same line.

3. Explain how Java handles memory allocation for objects and


primitives.
Answer:

Memory allocation for primitives:

Java allocates memory for primitive data types directly in the stack.
Primitives are simple data types such as int , float , char , boolean , etc. The
value is directly stored in memory and does not require additional memory
overhead for object management.

Example:

int x = 10; // Allocated in stack memory

Memory allocation for objects:

Objects in Java are stored in the heap memory, while references to these
objects are stored in the stack memory. When you create an object using

1. Core Java Basics 40


new , memory for the object is allocated in the heap, and a reference to it is
stored in the stack.

Example:

String str = new String("Hello"); // Memory for the object "Hello" is allocat
ed in heap

The JVM automatically manages memory allocation and garbage collection,


freeing up memory occupied by objects that are no longer in use.

4. What are comments in Java? What is the purpose of JavaDoc?


Answer:

Comments in Java:

Comments are used to annotate code and make it more understandable


for other developers (or for yourself). They are ignored by the Java
compiler.

There are three types of comments:

Single-line comment: // This is a comment

Multi-line comment: /* This is a multi-line comment */

Documentation comment: /** This is a JavaDoc comment */

JavaDoc:

JavaDoc is a tool used to generate HTML documentation from special


comments in the source code. It uses /** and / to mark comments that
describe classes, methods, and fields.

The purpose of JavaDoc is to provide a standardized format for


documenting the functionality of Java classes and methods, which can
then be used to automatically generate user-friendly HTML
documentation.

Example of JavaDoc comment:

1. Core Java Basics 41


/**
* This class represents a simple example for JavaDoc.
* It demonstrates how to use JavaDoc comments.
*/
public class JavaDocExample {
/**
* This method adds two numbers and returns the result.
* @param a The first number
* @param b The second number
* @return The sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
}

To generate the JavaDoc documentation, you would run the following command in
the terminal:

javadoc [Link]

5. Can Java variables store Unicode characters? Demonstrate


with an example.
Answer:
Yes, Java variables can store Unicode characters. Java supports Unicode, which
means it can handle characters from virtually all languages, including special
symbols and emojis.
You can directly assign Unicode characters to char or String variables.

Example:

public class UnicodeExample {


public static void main(String[] args) {
char unicodeChar = '\\u0048'; // Unicode for 'H'

1. Core Java Basics 42


String unicodeString = "Hello, \\u263A!"; // Unicode for a smiley face ☺

[Link]("Unicode Character: " + unicodeChar); // Output: H


[Link]("Unicode String: " + unicodeString); // Output: Hello,
☺!
}
}

In this example:

\\u0048 is the Unicode for the character H .

\\u263A is the Unicode for the smiley face ☺.

This demonstrates that Java can store and work with Unicode characters, allowing
for internationalization and special characters in applications.

1. Core Java Basics 43

You might also like