Java Asgn 1
Java Asgn 1
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:
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;
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.
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;
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;
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) 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:
4. Nested if-statement
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++)
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:
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)
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.
if (i == 3)
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.
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)
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:
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;
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.
Example:
matrix[1][1] = 10;
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:
Ex:
String fullName = str1 + " " + str2; // Concatenating two strings
System.out.println(fullName); // Output: Hello World
3. Length:
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:
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:
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:
8. String Formatting:
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:
Every time an object is created using the new() keyword, at least one constructor is
called.
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;
// Getter methods
public String getMake() {
return make;
}
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 MyClass() {
this(0); // Invoking parameterized constructor with default value
}
public MyClass(int x) {
this.x = 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.