Assignment Set java
Assignment Set java
SEMESTER - 1
Question 2a) Write down the rules for naming variables in Java.
Begin with a Letter, Sign, or Underline: Variable names should start with either a letter (a-z or
A-Z), a dollar sign ($), or an underscore (_). They should not begin with a number. For example,
variables like variable1, _variable, and $variable are acceptable, whereas names like 1variable
are not.
Additional Characters: After the initial character, variable names can include letters, digits (0-9),
dollar signs, or underscores. An example is variable_name2 and variable$Name.
Case Matters: In Java, variables are case sensitive. This means variables, variable, and
VARIABLE are considered to be different. Using the same case consistently will help avoid any
confusion.
Stay Away from Reserved Keywords: You should avoid using variable names that are Java
keywords or reserved words such as class, public, or int. Attempting to use reserved words as
variable names will lead to errors.
Choose Meaningful Names: Although not mandatory, it's advisable to select names that clearly
indicate the purpose of the variable. For instance, total Amount is more descriptive than simply t.
Question 2b) Write down the rules for the main () method in Java.
Guidelines for the Main() Method in Java
The main() method plays a pivotal role in a Java application, acting as the entry point for the
program. To ensure it functions as intended, it must comply with the following rules:
Method Signature: The definition of the main() method requires the following signature:
public static void main(String[] args)
This specific signature is necessary for the Java Virtual Machine (JVM) to recognize and execute
the method.
Public Modifier: This method should be declared public so that it's accessible from the Java
Virtual Machine outside the class. This accessibility is essential for the JVM to execute the
method.
Static Keyword: It should be static to enable the JVM to call it without the need to create an
instance of the class. This indicates that the method belongs to the class rather than to an instance
of the class.
Void Return Type: The method must have a void return type, meaning it does not return any
value. This requirement is to ensure the method is executed properly by the JVM.
Parameter: It must accept a single parameter of type String[], which represents an array of
command-line arguments. This acceptance allows the method to receive and process any
arguments passed when the program is run.
Method Name: The name of the method must be precisely "main." Any deviation from this name
will result in the JVM failing to identify the method as the entry point for the application.
By adhering to these guidelines, you ensure the main() method functions correctly as the initial
entry point for Java applications, facilitating the execution of the program when it's initiated.
Question 3a) List different kinds of operator in Java with brief description of each.
Various Types of Operators in Java
Java provides a range of operators for executing various operations:
Arithmetic Operators:
These include:
- Addition (+): Add two or more values (e.g., a + b).
- Subtraction (-): Subtract one value from another (e.g., a - b).
- Multiplication (*): Perform multiplication on two values (e.g., a * b).
- Division (/): Divide one value by another (e.g., a / b).
- Modulus (%), which returns the remainder after division (e.g., a % b).
Relational Operators:
These operators evaluate the relationship between values:
- == (Equal to): Checks if two values are equal (e.g., a == b).
- != (Not equal to): Determines if two values are not equal (e.g., a != b).
- > (Greater than): Compares if the value of a is greater than that of b (e.g., a > b).
- < (Less than): Determines if the value of a is lesser than that of b (e.g., a < b).
- >= (Greater than or equal to): Checks if the value of a is greater than or equal to that of b (e.g.,
a >= b).
- <= (Less than or equal to): Determines if the value of a is lesser than or equal to that of b (e.g.,
a <= b).
Logical Operators:
These operators perform logical operations on boolean values:
- && (Logical AND): Returns true if both operands are true (e.g., a && b).
- || (Logical OR): Returns true if at least one of the operands is true (e.g., a || b).
- ! (Logical NOT): Inverts the boolean value (e.g., !a).
Bitwise Operators:
These operators manipulate bits:
- &, |, ^, ~ (Bitwise operations): Execute operations on bits (e.g., a & b, a | b).
- <<, >>, >>> (Shift operations): Shift bits to the left or right (e.g., a << 2, a >> 2).
Assignment Operators:
These operators modify or assign values to variables:
- = (Assignment): Assigns a value to a variable (e.g., a = 5).
- +=, -=, *=, /=, %=: Performs operations and assigns the result (e.g., a += 5).
Unary Operators:
These operators act on a single operand:
- +, - (Unary plus/minus): Indicates the positive or negative value (e.g., +a, -a).
- ++, -- (Increment/Decrement): Increases or decreases a value by 1 (e.g., a++, a--).
Ternary Operator:
This operator is a conditional assignment:
- ? : (Ternary): Specifies a condition? value1 ? value2 : value3 (e.g., a > b ? a : b).
Instance of Operator:
This operator verifies if an object is an instance of a class:
- Checks if an object is an instance of a class (e.g., obj instanceof ClassName).
Question 3b) Write a program to print numbers from 1 to 10 in Java using for loop.
Java Code for Generating Numbers 1 to 10 Using a For Loop
Java
Here's a straightforward Java program that generates numbers from 1 to 10:
Code
public class NumberGenerator {
public static void main(String[] args) {
// Display numbers 1 through 10
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
Explanation:
Class Definition: public class NumberGenerator defines the class.
Main Procedure: public static void main(String[] args) represents the main procedure.
For Loop: for (int i = 1; i <= 10; i++) loops from 1 to 10.
Print Statement: System.out.println(i); is used to display each number.
The for loop repeats for ten iterations, displaying numbers in order. This illustration showcases
the basic usage of a for loop in Java.
Assignment Set – 2
Question 1a) How do you implement Inheritance in Java? Demonstrate with one example.
Implementing Inheritance in Java
Inheritance in Java empowers a class to inherit properties and methods from another class,
facilitating code reusability and establishing a hierarchical structure among classes.
Key Points:
Superclass and Subclass: The class from which properties and methods are inherited is
considered the superclass, whereas the class gaining these benefits is the subclass.
Syntax: The declaration of inheritance uses the extends keyword.
Example:
java code
// Superclass
class Animal {
// Field of the superclass
String name;
// Subclass
class Dog extends Animal {
// Subclass-specific method
void bark() {
System.out.println(name + " is barking.");
}
}
// Testing inheritance
public class InheritanceDemo {
public static void main(String[] args) {
// Creating an instance of the subclass
Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.eat(); // Method inherited from Animal class
myDog.bark(); // Method specific to Dog class
}
}
Explanation:
Animal Class: Holds a method eat() and a field named name.
Dog Class: Extends Animal, acquiring its attributes and methods, and introducing a new method
bark().
InheritanceDemo: Showcases the creation of a Dog instance, employing inherited methods, and
subclass-specific methods.
Question 1b) Write down the rules for Overriding Methods in Java.
Guidelines for Implementing Method Overriding in Java
Java's mechanism of method overriding allows a subclass to provide a distinct implementation
for a method already defined within its parent class. Here are the essential guidelines:
Method Signature: The subclass's method must adhere to the same method name, return type,
and parameter set as defined in the parent class method.
Access Control: The subclass method is permitted to have a higher or lower access level than the
method in the parent class. For instance, if the parent class method is marked as protected, the
subclass method could be either protected or public.
Exception Handling: The subclass method may only raise exceptions that are more detailed or
specific than the exceptions raised by the parent class method.
Annotation: It is advisable to use the @Override annotation above the method in the subclass.
This annotation helps ensure the method is correctly overriding the method of the parent class,
and it aids in the detection of errors.
Method Execution: The subclass must offer its own implementation for the method, which may
utilize the superclass method with the super.methodName() function if required.
Example:
Java code
// Superclass
class Parent {
void show() {
System.out.println("Show from Parent.");
}
}
// Subclass
class Child extends Parent {
@Override
void show() {
System.out.println("Show from Child.");
}
}
Question 2) How do you implement exception-handling in Java using the keywords: try, catch,
finally, throw? Demonstrate with one example.
Exception Handling in Java plays a crucial role in managing errors that occur during runtime and
in ensuring that programs can respond to unexpected situations in an orderly fashion. Java offers
several essential keywords for this task: try, catch, finally, and throw. Here's a concise overview
of these keywords along with an example to show their application:
Keywords Overview
try: This block is utilized to encapsulate code that may cause an exception. It's the place to put
the code that might encounter issues.
catch: After the try block, the catch block is implemented to deal with exceptions raised by the
code in the try block. Multiple catch blocks can be utilized to handle various types of exceptions.
finally: If specified, this block is executed after the try and catch blocks, no matter whether an
exception occurred. It's beneficial for carrying out cleanup tasks, such as freeing resources or
closing files.
throw: This keyword is employed to explicitly raise an exception within a method or a block of
code. It's a way to signal that an error has been identified in a controlled manner.
Example
Let's look at the following Java program that showcases the use of these keywords:
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Attempting to run code that may cause an exception
int result = divide(10, 0); // This line will cause an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Handling the specific exception
System.out.println("Error: Division by zero is not permitted.");
} finally {
// This block is executed regardless of an exception being thrown
System.out.println("This block is always executed.");
}
}
Question 3) Write down any 5 reasons that justifies the need of collection classes in java.
The Java Collection Framework (JCF) plays a vital role in efficient data handling within Java
programming. Here are five primary reasons why working with collection classes is crucial:
1. Efficient Data Handling
Java collections provide structured approaches to manage data. They offer various structures like
Array List, LinkedList, HashSet, and HashMap, each suited for different data management
needs. Array List allows for dynamic resizing and swift access to elements, while LinkedList is
more efficient for frequent insertions and removals. HashSet guarantees unique element values,
and HashMap supports rapid retrieval of key-value pairs. These diverse options enable the
effective management of complex data.
2. Improved Code Reusability and Maintenance
Standard collection classes improve code reusability and maintenance. Utilizing in-built classes
such as HashMap and ArrayList prevents the need to develop custom data structures, thereby
saving development time. These classes are equipped with reliable, established methods for
standard operations, making the code easier to read and maintain. Uniform interfaces and
behaviors simplify code manipulation.
3. Enhanced Performance
The framework is designed for optimal performance. For example, ArrayList ensures constant-
time access through indices, and HashSet delivers average-time constant-time performance for
operations like insertions and lookups. These optimized structures guarantee efficient handling of
data operations, which is crucial for applications requiring high performance.
4. Versatility and Growth Potential
Java collections provide an array of data structures and algorithms, ensuring versatility for
various applications. Collections like PriorityQueue and TreeSet offer specialized functionalities
such as prioritizing orders and sorted storage. This versatility empowers developers to select the
most appropriate collection for their needs, while the framework can manage large datasets
efficiently, fostering scalable applications.
5. Type Safety Support with Generics
Generics improve collection classes by ensuring type safety. They permit collections to store
specific types of objects, reducing errors at runtime and eliminating the necessity for type
casting. For instance, a List<String> ensures that only String objects are added, enhancing code
security and clarity.
In conclusion, the Java Collection Framework offers key tools for efficient data management,
with a variety of structures, optimized performance, scalable capabilities, and enhanced type
safety through generics.