Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

1.

Define data types


Data types in programming define the type of data a variable can hold. Examples include:
• Primitive data types: int, float, char, boolean, etc.
• Non-primitive data types: Arrays, classes, interfaces, etc.

2. Write a program in java to print “Hello world”


public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

3. State Byte code in java.


• Java bytecode is an intermediate, platform-independent code generated by the Java compiler
from a .java source file.
• It is executed by the Java Virtual Machine (JVM), allowing the same Java program to run on any
platform with a compatible JVM.
• The JVM interprets or compiles this bytecode into machine code, ensuring security and
optimization during execution.

4. Write the concept of polymorphism.


Polymorphism is an Object-Oriented Programming (OOP) concept where a single action can behave
differently based on the object that is performing it. It can be achieved through:
• Method Overloading (Compile-time polymorphism): Same method name but different parameter
lists.
• Method Overriding (Run-time polymorphism): A subclass provides a specific implementation of a
method that is already defined in its superclass

5. Define objects and classes


• Class: A blueprint for creating objects. It defines a datatype by bundling data and methods that
work on the data.
• Object: An instance of a class. It is created from the class and has state and behavior defined by
the class

6. What is the output of the following code snippet?


int x = 5;
int y = x++;
System.out.println(x + " " + y);
Output: 6 5
Explanation:
x is initialized with the value 5
y = x++ assigns 5 to y and then increments x to 6.
The System.out.println(x + " " + y) prints x (which is now 6) and y (which is 5).
7. Define abstraction and encapsulation
• Abstraction: The concept of hiding the complex implementation details and showing only the
essential features of an object.
• Encapsulation: The bundling of data and methods that operate on the data into a single unit or
class, and restricting access to some of the object's components.

8. List the features of Object Oriented Programming.


• Encapsulation: Grouping data and methods, restricting access.
• Abstraction: Showing only essential details, hiding complexity.
• Inheritance: New class inherits properties from an existing class.
• Polymorphism: One function works on different types.
• Modularity: Dividing a program into independent parts.
• Reusability: Using code in multiple places or projects

9. What are public static void main(String args[]) and System.out.println()?


• public static void main(String args[]): This is the entry point for any Java application. It is a public
method that can be called without creating an instance of the class.
• System.out.println(): This method is used to print messages to the console. System is a class, out
is an instance of PrintStream, and println is a method of PrintStream

10. Write a simple java program using programming structure


public class SimpleProgram {
public static void main(String[] args) {
int number = 10;
if (number > 5) {
System.out.println("Number is greater than 5");
} else {
System.out.println("Number is 5 or less");
}
}
}

11. Define abstract class.


An abstract class in Java is a class that cannot be instantiated on its own and is meant to be subclassed. It
can contain both abstract methods and concrete methods. Abstract methods must be implemented by
any non-abstract subclass

12. Assess the error in the following array declaration and rectify them.
int a[]=new [10]int;
float []b=new int[10.5];
Correction 1: int a[] = new int[10];
Correction 2: float[] b = new float[10];

13. Write a program to find the Largest of three numbers using Ternary Operator
public class LargestOfThree {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
// Find the largest of three numbers using the ternary operator
int largest = (a > b) ? (a > c ? a : c) : (b > c ? b : c);

System.out.println("The largest number is: " + largest);


}
}
O/P: The largest number is: 30

14. Write a program to display total marks of 5 students with the following attributes: Regno(int),
Name(string), Marks in subjects(Integer Array), Total(int) using student class.
public class Student {
int regno;
String name;
int[] marks;
int total;

// Constructor
public Student(int regno, String name, int[] marks) {
this.regno = regno;
this.name = name;
this.marks = marks;
this.total = calculateTotal();
}

// Method to calculate total marks


private int calculateTotal() {
int sum = 0;
for (int mark : marks) {
sum += mark;
}
return sum;
}

// Method to display student details


public void display() {
System.out.println("Reg No: " + regno + ", Name: " + name + ", Total Marks: " + total);
}

public static void main(String[] args) {


// Create and initialize 5 students
Student[] students = {
new Student(101, "Alice", new int[]{85, 90, 78}),
new Student(102, "Bob", new int[]{75, 80, 88}),
new Student(103, "Charlie", new int[]{95, 92, 89}),
new Student(104, "David", new int[]{60, 70, 65}),
new Student(105, "Eve", new int[]{80, 85, 90})
};
// Display details of each student
for (Student student : students) {
student.display();
}
}
}
O/P
Reg No: 101, Name: Alice, Total Marks: 253
Reg No: 102, Name: Bob, Total Marks: 243
Reg No: 103, Name: Charlie, Total Marks: 276
Reg No: 104, Name: David, Total Marks: 195
Reg No: 105, Name: Eve, Total Marks: 255

15. What is a package? Give an example program to import and use packages.
In Java, a package is a namespace that arranges classes and interfaces into a hierarchical structure, aiding in
the organization of code. It helps avoid name conflicts by grouping related classes together, controls access by
restricting visibility, and enhances code reusability by allowing classes to be shared across different packages.
Create Package:
package MyPackage;
public class MyClass {
public void display() {
System.out.println("Hello from MyClass in MyPackage!");
}
}
Use the Package:
import MyPackage.MyClass;
public class TestPackage {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
O/P: Hello from MyClass in MyPackage!

16. Explain about Access Modifiers in Java.


In Java, access modifiers determine the visibility and accessibility of classes, methods, and variables. They
control which other parts of the program can access these elements. Java provides four primary access
modifiers:
1. Public
• Keyword: public
• Visibility: Accessible from any other class or package.
• Usage: Used when you want the class, method, or variable to be accessible from everywhere in the
program.
2. Private
• Keyword: private
• Visibility: Accessible only within the class where it is declared.
• Usage: Used to encapsulate data and prevent direct access from outside the class. It is often used
with getters and setters.
3. Protected
• Keyword: protected
• Visibility: Accessible within the same package and by subclasses (even if they are in different
packages).
• Usage: Used when you want to allow access to classes in the same package and also to subclasses,
even if they are in different packages.
4. Default (No Modifier)
• Keyword: None (default visibility)
• Visibility: Accessible only within the same package.
• Usage: Used when no access modifier is specified. It is package-private, meaning it is visible only to
other classes in the same package.

17. Create a Java class named Math Operations with overloaded methods to perform addition. Implement
three versions of the add() method:
One that adds two integers.
One that adds three integers.
public class MathOperations {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
MathOperations mathOps = new MathOperations();

int sum1 = mathOps.add(5, 10); // Adds two integers


int sum2 = mathOps.add(5, 10, 15); // Adds three integers
double sum3 = mathOps.add(5.5, 10.5); // Adds two double values
System.out.println("Sum of two integers: " + sum1);
System.out.println("Sum of three integers: " + sum2);
System.out.println("Sum of two double values: " + sum3);
}
}
O/P
Sum of two integers: 15
Sum of three integers: 30
Sum of two double values: 16.0
18. Write the difference between constructor and method?

19. Write a program to print the following output:


11111
2222
333
44
5
public class NumberPattern {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= (rows - i + 1); j++) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
20. Answer the following
i) Describe operators & its types in detail. (4)
Operators in Java are special symbols that perform operations on operands (variables, literals, or
expressions). They are used to perform arithmetic, comparison, logical, and other operations. Here are the
main types of operators in Java:
1. Arithmetic Operators
Purpose: Perform basic arithmetic operations.
Types:
o + (Addition): Adds two operands.
o - (Subtraction): Subtracts the second operand from the first.
o * (Multiplication): Multiplies two operands.
o / (Division): Divides the first operand by the second.
o % (Modulus): Returns the remainder of division
2. Relational Operators
Purpose: Compare two values and return a boolean result.
Types:
o == (Equal to): Checks if two values are equal.
o != (Not equal to): Checks if two values are not equal.
o > (Greater than): Checks if the first value is greater than the second.
o < (Less than): Checks if the first value is less than the second.
o >= (Greater than or equal to): Checks if the first value is greater than or equal to the second.
o <= (Less than or equal to): Checks if the first value is less than or equal to the second.
3. Logical Operators
Purpose: Perform logical operations and return a boolean result.
Types:
o && (Logical AND): Returns true if both operands are true.
o || (Logical OR): Returns true if at least one operand is true.
o ! (Logical NOT): Inverts the boolean value of the operand.
4. Assignment Operators
Purpose: Assign values to variables.
Types:
o = (Assignment): Assigns the value on the right to the variable on the left.
o += (Add and assign): Adds the right operand to the left operand and assigns the result to the left
operand.
o -= (Subtract and assign): Subtracts the right operand from the left operand and assigns the result to
the left operand.
o *= (Multiply and assign): Multiplies the left operand by the right operand and assigns the result to the
left operand.
o /= (Divide and assign): Divides the left operand by the right operand and assigns the result to the left
operand.
o %= (Modulus and assign): Takes the modulus of the left operand by the right operand and assigns the
result to the left operand.
5. Unary Operators
Purpose: Operate on a single operand.
Types:
o + (Unary plus): Indicates a positive value (usually optional).
o - (Unary minus): Negates the value.
o ++ (Increment): Increases the value by 1.
o -- (Decrement): Decreases the value by 1.
o ! (Logical NOT): Inverts the boolean value
6. Bitwise Operators
Purpose: Perform operations on the binary representations of integers.
Types:
o & (Bitwise AND): Performs a bitwise AND operation.
o | (Bitwise OR): Performs a bitwise OR operation.
o ^ (Bitwise XOR): Performs a bitwise XOR operation.
o ~ (Bitwise NOT): Inverts all bits.
o << (Left shift): Shifts bits to the left.
o >> (Right shift): Shifts bits to the right.
o >>> (Unsigned right shift): Shifts bits to the right, filling with zeroes.

ii) Write a java program using all the operators. (6)


public class OperatorsDemo {
public static void main(String[] args) {
// Arithmetic Operators
int a = 10, b = 5;
System.out.println("Arithmetic Operators:");
System.out.println("a + b = " + (a + b)); // Addition
System.out.println("a - b = " + (a - b)); // Subtraction
System.out.println("a * b = " + (a * b)); // Multiplication
System.out.println("a / b = " + (a / b)); // Division
System.out.println("a % b = " + (a % b)); // Modulus

// Relational Operators
System.out.println("\nRelational Operators:");
System.out.println("a == b: " + (a == b)); // Equal to
System.out.println("a != b: " + (a != b)); // Not equal to
System.out.println("a > b: " + (a > b)); // Greater than
System.out.println("a < b: " + (a < b)); // Less than

// Logical Operators
boolean x = true, y = false;
System.out.println("\nLogical Operators:");
System.out.println("x && y: " + (x && y)); // Logical AND
System.out.println("x || y: " + (x || y)); // Logical OR
System.out.println("!x: " + !x); // Logical NOT

// Unary Operators
int d = 5;
System.out.println("\nUnary Operators:");
System.out.println("++d: " + (++d)); // Pre-increment
System.out.println("d++: " + (d++)); // Post-increment
System.out.println("d after increment: " + d);
System.out.println("--d: " + (--d)); // Pre-decrement
System.out.println("d--: " + (d--)); // Post-decrement
System.out.println("d after decrement: " + d);

// Ternary Operator
int max = (a > b) ? a : b;
System.out.println("\nTernary Operator:");
System.out.println("Maximum of a and b: " + max);
}
}
21. Answer the following
i) Write a program with class name "first" as the parent class. Create class name "second" as one child class
and class name "third" as another child class. (6)
class First {
public void display() {
System.out.println("This is the First class.");
}
}
class Second extends First {
public void show() {
System.out.println("This is the Second class.");
}
}
class Third extends First {
public void print() {
System.out.println("This is the Third class.");
}
}

public class Main {


public static void main(String[] args) {
Second secondObj = new Second();
Third thirdObj = new Third();

secondObj.display();
secondObj.show();
thirdObj.display();
thirdObj.print();
}
}
O/P
This is the First class.
This is the Second class.
This is the First class.
This is the Third class.

ii) What is the type of inheritance involved in (i) and justify your answer. (4)
Type of Inheritance Involved: Hierarchical Inheritance
Justification:
In the provided code, the Second and Third classes both inherit from the same parent class, First. This means
that multiple subclasses (Second and Third) are derived from a single parent class (First). This type of
inheritance, where one parent class has multiple child classes inheriting from it, is known as Hierarchical
Inheritance.
Hierarchical Inheritance occurs when a single base class (First) is extended by multiple subclasses (Second
and Third). Each subclass inherits the properties and methods of the base class, as seen in the code where
both Second and Third can access the display() method from First while also having their own specific
methods (show() in Second and print() in Third).
22. Write a Java program that reads a list of integers from the user and sorts them using the
Bubble Sort algorithm.
import java.util.Scanner;

public class BubbleSortExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] array = new int[n];
System.out.println("Enter the integers:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
bubbleSort(array);
System.out.println("Sorted array:");
for (int i = 0; i < n; i++) {
System.out.print(array[i] + " ");
}
}

public static void bubbleSort(int[] array) {


int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
O/P
Enter the number of elements: 5
Enter the integers:
34 12 25 9 50
Sorted array:
9 12 25 34 50

23. Write a Java program using array to perform


Sum of all values in an array (5)
public class SumOfArray {
public static void main(String[] args) {
int[] numbers = {4, 8, 15, 16, 23, 42};
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println("Sum of all values in the array: " + sum);
}
}
O/P: Sum of all values in the array: 108

Find the greatest number in an array (5)


public class GreatestNumberInArray {
public static void main(String[] args) {
int[] numbers = {4, 8, 15, 16, 23, 42};
int max = numbers[0];
for (int number : numbers) {
if (number > max) {
max = number;
}
}
System.out.println("Greatest number in the array: " + max);
}
}
O/P: Greatest number in the array: 42

24. Write a simple Java program to implement basic Calculator operations.


import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter first number: ");


double num1 = scanner.nextDouble();

System.out.print("Enter second number: ");


double num2 = scanner.nextDouble();

System.out.print("Enter an operator (+, -, *, /): ");


char operator = scanner.next().charAt(0);

double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero.");
scanner.close();
return;
}
break;
default:
System.out.println("Error: Invalid operator.");
scanner.close();
return;
}
System.out.println("Result: " + result);
scanner.close();
}
}
O/P
Enter first number: 12
Enter second number: 8
Enter an operator (+, -, *, /): +
Result: 20.0

25. Define Inheritance? With diagrammatic illustration and java Programs illustrate the different types of
inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) where a new class, known as
the subclass or derived class, inherits properties and behaviors (methods) from an existing class, known as
the superclass or base class. This mechanism promotes code reusability and establishes a natural hierarchy
between classes.

Types of Inheritance

1. Single Inheritance:
A class inherits from one parent class.
class Parent {
void display() { System.out.println("Parent"); }
}
class Child extends Parent {
void show() { System.out.println("Child"); }
}
public class SingleLevelInheritanceDemo {
public static void main(String[] args) {
Child c = new Child();
c.display(); // Parent
c.show(); // Child
}
}
O/P
Parent
Child

2. Multilevel Inheritance:
A class inherits from another class, which itself is derived from another class

class Grandparent {
void show() { System.out.println("Grandparent"); }
}

class Parent extends Grandparent {


void display() { System.out.println("Parent"); }
}

class Child extends Parent {


void message() { System.out.println("Child"); }
}
public class MultiLevelInheritanceDemo {
public static void main(String[] args) {
Child c = new Child();
c.show(); // Grandparent
c.display(); // Parent
c.message(); // Child
}
}
O/P
Grandparent
Parent
Child

3. Hierarchical Inheritance:
Multiple classes inherit from a single parent class.

class Parent {
void show() { System.out.println("Parent"); }
}
class Child1 extends Parent {
void display1() { System.out.println("Child1"); }
}
class Child2 extends Parent {
void display2() { System.out.println("Child2"); }
}
public class HierarchicalInheritanceDemo {
public static void main(String[] args) {
Child1 c1 = new Child1();
Child2 c2 = new Child2();
c1.show(); // Parent
c1.display1(); // Child1
c2.show(); // Parent
c2.display2(); // Child2
}
}
O/P
Parent
Child1
Parent
Child2
4. Multiple Inheritance:
Java does not support multiple inheritance directly through classes but allows it through interfaces.

interface I1 { void method1(); }


interface I2 { void method2(); }

class Multi implements I1, I2 {


public void method1() { System.out.println("Method1"); }
public void method2() { System.out.println("Method2"); }
}

public class MultipleInheritanceDemo {


public static void main(String[] args) {
Multi m = new Multi();
m.method1(); // Method1
m.method2(); // Method2
}
}
O/P
Method1
Method2

5. Hybrid inheritance
Combination of multiple inheritance types (e.g., single, multilevel, and hierarchical) in one hierarchy, achieved
using a mix of classes and interfaces.

class Base {
void show() { System.out.println("Base"); }
}
class Intermediate extends Base {
void display() { System.out.println("Intermediate"); }
}
class Derived extends Intermediate {
void message() { System.out.println("Derived"); }
}

public class HybridInheritanceDemo {


public static void main(String[] args) {
Derived d = new Derived();
d.show(); // Base
d.display(); // Intermediate
d.message(); // Derived
}
}
O/P
Base
Intermediate
Derived

26. Create a package com.example.math containing two classes: Adder and Multiplier.
The Adder class should have a method add(int a, int b) and the Multiplier class should have a method
multiply(int a, int b).
In another package com.example.main, create a class Main that imports the Adder and Multiplier classes
and demonstrates their usage.
Ensure proper access protection and import statements. Also, explain the use of the CLASSPATH for
importing these packages.
Create Package com.example.math
Adder.java:
package com.example.math;
public class Adder {
public int add(int a, int b) {
return a + b;
}
}
Multiplier.java:
package com.example.math;
public class Multiplier {
public int multiply(int a, int b) {
return a * b;
}
}
2. Create Package com.example.main
Main.java:
package com.example.main;
import com.example.math.Adder;
import com.example.math.Multiplier;
public class Main {
public static void main(String[] args) {
Adder adder = new Adder();
Multiplier multiplier = new Multiplier();
System.out.println("Addition: " + adder.add(5, 3)); // Output: 8
System.out.println("Multiplication: " + multiplier.multiply(5, 3)); // Output: 15
}
}
The CLASSPATH is an environment variable in Java that tells the Java Virtual Machine (JVM) and Java compiler
where to find class files. To use packages, you need to set the CLASSPATH to include the directory where your
packages are located.
Output:
Addition: 8
Multiplication: 15

You might also like