0% found this document useful (0 votes)
62 views13 pages

Java Programs for Beginners

The document contains a series of Java programming exercises that cover various concepts such as reading user input, command line arguments, recursion, matrix multiplication, sorting, palindrome checking, constructors, inheritance, interfaces, and mathematical operations. Each exercise includes a brief description followed by a complete Java program solution. The programs demonstrate fundamental programming techniques and object-oriented principles in Java.

Uploaded by

jainakshit526
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views13 pages

Java Programs for Beginners

The document contains a series of Java programming exercises that cover various concepts such as reading user input, command line arguments, recursion, matrix multiplication, sorting, palindrome checking, constructors, inheritance, interfaces, and mathematical operations. Each exercise includes a brief description followed by a complete Java program solution. The programs demonstrate fundamental programming techniques and object-oriented principles in Java.

Uploaded by

jainakshit526
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Practical Questions and Solutions

1. Write a program to read two numbers from user and print their product.

import [Link];

public class Product {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();
[Link]("Product: " + (a * b));
[Link]();
}
}

2. Write a program to print the square of a number passed through command line arguments.

public class SquareCLI {


public static void main(String[] args) {
int num = [Link](args[0]);
[Link]("Square: " + (num * num));
}
}

3. Write a program to send the name and surname of a student through command line
arguments and print a welcome message for the student.

public class WelcomeStudent {


public static void main(String[] args) {
String name = args[0];
String surname = args[1];
[Link]("Welcome " + name + " " + surname + "!");
}
}

4. Write a java program to find the largest number out of n natural numbers.

import [Link];
public class LargestNumber {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter how many numbers: ");
int n = [Link]();
int largest = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
[Link]("Enter number " + (i + 1) + ": ");
int num = [Link]();
if (num > largest) {
largest = num;
}
}
[Link]("Largest number is: " + largest);
[Link]();
}
}

5. Write a java program to find the Fibonacci series & Factorial of a number using
recursive and non -recursive functions.

public class FibFact {


// Recursive Fibonacci
static int fibRec(int n) {
if (n <= 1) return n;
return fibRec(n - 1) + fibRec(n - 2);
}
// Non-Recursive Fibonacci
static void fibNonRec(int n) {
int a = 0, b = 1;
[Link]("Fibonacci: " + a + " " + b + " ");
for (int i = 2; i < n; i++) {
int c = a + b;
[Link](c + " ");
a = b;
b = c;
}
[Link]();
}

// Recursive Factorial
static int factRec(int n) {
if (n == 0) return 1;
return n * factRec(n - 1);
}

// Non-Recursive Factorial
static int factNonRec(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}

public static void main(String[] args) {


int n = 5;
fibNonRec(n);
[Link]("Recursive Fibonacci of 5: " + fibRec(n));
[Link]("Recursive Factorial of 5: " + factRec(n));
[Link]("Non-Recursive Factorial of 5: " + factNonRec(n));
}
}

6. Write a java program to multiply two given matrices.

import [Link];
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int[][] a = new int[2][2];
int[][] b = new int[2][2];
int[][] c = new int[2][2];
[Link]("Enter matrix A:");
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
a[i][j] = [Link]();
[Link]("Enter matrix B:");
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
b[i][j] = [Link]();
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
c[i][j] += a[i][k] * b[k][j];
[Link]("Result Matrix:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
[Link](c[i][j] + " ");
[Link]();
}
[Link]();
}
}

7. Write a Java program for sorting a given list of names in ascending order.

import [Link].*;
public class SortNames {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of names: ");
int n = [Link]();
[Link]();
String[] names = new String[n];
for (int i = 0; i < n; i++) {
[Link]("Enter name " + (i + 1) + ": ");
names[i] = [Link]();
}
[Link](names);
[Link]("Sorted names:");
for (String name : names)
[Link](name);
[Link]();
}
}

8. Write a Java program that checks whether a given string is a palindrome or not.
Ex:MADAM is a palindrome.

import [Link];
public class PalindromeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();
String rev = new StringBuilder(str).reverse().toString();
if ([Link](rev))
[Link](str + " is a palindrome.");
else
[Link](str + " is not a palindrome.");
[Link]();
}
}

9. Write a java program to read n number of values in an array and display it in reverse order.

import [Link];
public class ReverseArray {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements: ");
int n = [Link]();
int[] arr = new int[n];
[Link]("Enter array elements:");
for (int i = 0; i < n; i++)
arr[i] = [Link]();
[Link]("Reversed array:");
for (int i = n - 1; i >= 0; i--)

[Link](arr[i] + " ");


[Link]();
}
}

10. Write a java program to illustrate the concept of Non-Parameterized Constructor


class NonParameterized {
NonParameterized() {
[Link]("This is a non-parameterized constructor.");
}
public static void main(String[] args) {
NonParameterized obj = new NonParameterized();
}
}

[Link] a java program to illustrate the concept of Parameterized Constructor


class Parameterized {
int a;

Parameterized(int value) {
a = value;
[Link]("Value is: " + a);
}

public static void main(String[] args) {


Parameterized obj = new Parameterized(10);
}
}

12. Write a java program to illustrate the concept of Method Overloading


class OverloadExample {
void display() {
[Link]("No arguments");
}

void display(String name) {


[Link]("Name: " + name);
}

void display(int number) {


[Link]("Number: " + number);
}

public static void main(String[] args) {


OverloadExample obj = new OverloadExample();
[Link]();
[Link]("Alice");
[Link](100);
}
}

13. Write a java program to illustrate the concept of Single Inheritance


class Parent {
void showParent() {
[Link]("This is the parent class.");
}
}
class Child extends Parent {
void showChild() {
[Link]("This is the child class.");
}

public static void main(String[] args) {


Child obj = new Child();
[Link]();
[Link]();
}
}

14. Write a java program to illustrate the concept of Multilevel Inheritance

class Grandparent {
void showGrandparent() {
[Link]("This is the grandparent class.");
}
}

class Parent extends Grandparent {


void showParent() {
[Link]("This is the parent class.");
}
}

class Child extends Parent {


void showChild() {
[Link]("This is the child class.");
}

public static void main(String[] args) {


Child obj = new Child();
[Link]();
[Link]();
[Link]();
}
}

15. Write a java program to illustrate the concept of Hierarchical Inheritance


class Base {
void showBase() {
[Link]("This is the base class.");
}
}

class Derived1 extends Base {


void showDerived1() {
[Link]("This is the first derived class.");
}
}
class Derived2 extends Base {
void showDerived2() {
[Link]("This is the second derived class.");
}

public static void main(String[] args) {


Derived1 d1 = new Derived1();
Derived2 d2 = new Derived2();

[Link]();
d1.showDerived1();

[Link]();
d2.showDerived2();
}
}

16. simple Java program demonstrating multiple inheritance using interfaces:


interface A {
void showA();
}

interface B {
void showB();
}

class C implements A, B {
public void showA() {
[Link]("This is method from interface A");
}

public void showB() {


[Link]("This is method from interface B");
}

public static void main(String[] args) {


C obj = new C();
[Link]();
[Link]();
}
}

17. Write a java program to illustrate the concept of Interface


interface Animal {
void sound();
}

class Dog implements Animal {


public void sound() {
[Link]("Dog barks.");
}
}

class Cat implements Animal {


public void sound() {
[Link]("Cat meows.");
}

public static void main(String[] args) {


Dog d = new Dog();
Cat c = new Cat();

[Link]();
[Link]();
}
}

18. Write a Java program to perform mathematical operations. Create a class called
AddSub with methods to add and subtract. Create another class called MulDiv
that extends from AddSub class to use the member data of the superclass.
MulDiv should have methods to multiply and divide A main function should
access the methods and perform the mathematical operations.

class AddSub {
int a = 10, b = 5;
void add() {
[Link]("Addition: " + (a + b));
}
void subtract() {
[Link]("Subtraction: " + (a - b));
}
}
class MulDiv extends AddSub {
void multiply() {
[Link]("Multiplication: " + (a * b));
}
void divide() {
if (b != 0)
[Link]("Division: " + (a / b));
else
[Link]("Cannot divide by zero.");
}
}
public class MathOperations {
public static void main(String[] args) {
MulDiv obj = new MulDiv();
[Link]();
[Link]();
[Link]();
[Link]();
}
}

19. Write a Java program to create a class called Shape with methods called
getPerimeter() and getArea(). Create a subclass called Circle that overrides
the getPerimeter() and getArea() methods to calculate the area and perimeterof a
circle.

class Shape {
double getPerimeter() {
return 0;
}

double getArea() {
return 0;
}
}

class Circle extends Shape {


double radius;

Circle(double radius) {
[Link] = radius;
}

@Override
double getPerimeter() {
return 2 * [Link] * radius;
}

@Override
double getArea() {
return [Link] * radius * radius;
}
}

public class CircleShapeTest {


public static void main(String[] args) {
Circle c = new Circle(5.0);
[Link]("Circle with radius %.2f%n", [Link]);
[Link]("Perimeter: %.2f%n", [Link]());
[Link]("Area: %.2f%n", [Link]());
}
}

20. Write a Java program using an interface called ‘Bank’ having function
‘rate_of_interest()’. Implement this interface to create two separate bank classes
‘SBI’ and ‘PNB’ to print different rates of interest. Include additionalmember
variables, constructors also in classes ‘SBI’ and ‘PNB’.
interface Bank {
double rate_of_interest();
}

class SBI implements Bank {


String branchName;
int branchCode;

SBI(String branchName, int branchCode) {


[Link] = branchName;
[Link] = branchCode;
}

public double rate_of_interest() {


return 6.5;
}

void displayDetails() {
[Link]("SBI Branch: " + branchName + ", Code: " + branchCode);
[Link]("SBI Interest Rate: " + rate_of_interest() + "%");
}
}

class PNB implements Bank {


String branchName;
int branchCode;

PNB(String branchName, int branchCode) {


[Link] = branchName;
[Link] = branchCode;
}

public double rate_of_interest() {


return 7.0;
}

void displayDetails() {
[Link]("PNB Branch: " + branchName + ", Code: " + branchCode);
[Link]("PNB Interest Rate: " + rate_of_interest() + "%");
}
}

public class BankTest {


public static void main(String[] args) {
SBI sbi = new SBI("Main Street", 101);
PNB pnb = new PNB("Central Avenue", 202);

[Link]();
[Link]();
[Link]();
}
}

Common questions

Powered by AI

The Java examples illustrate several OOP principles: abstraction, encapsulation, and polymorphism. Abstraction is shown through interfaces, like 'Bank' or 'Animal', which define methods without implementation details, focusing on what actions can be performed . Encapsulation is demonstrated in classes like 'Parameterized', where fields are hidden within objects and accessed via constructors . Polymorphism is evident in method overriding, such as 'Circle' subclassing 'Shape', and defining specific behavior for 'getArea' and 'getPerimeter', enabling a generic class type to execute task-specific methods at runtime . These principles help in designing robust, reusable, and modular programs.

Non-parameterized constructors default the state of an object and are useful for creating basic objects without specific initial conditions. The 'NonParameterized' example displays how an object can be instantiated without input data, initializing with default settings . Parameterized constructors, demonstrated in the 'Parameterized' class, provide a means to initialize objects with specific values upon creation, offering more control and customization . While parameterized constructors require initial values, which might complicate object creation if not managed properly, they provide flexibility and ensure that objects start in a valid state. Non-parameterized constructors can lead to poorly initialized objects if not used with caution.

Error checking and exception handling are crucial for robust Java applications, albeit not prominently featured in the examples given. Strategies to enhance robustness include implementing exception handling using try-catch blocks to manage runtime errors, such as input mismatches or arithmetic exceptions (e.g., division by zero). Validating inputs at the entry point, employing asserts and predicates, can prevent erroneous data propagation. Logging errors for diagnostics and using custom exceptions to signify application-specific issues can also enhance debugging and maintenance. These practices ensure graceful degradation of functionality and a better user experience .

Command line arguments offer a flexible way for users to provide input to a Java program without hardcoding values, which enhances reusability and testing. For instance, the 'SquareCLI' program uses command line arguments to calculate the square of a number, allowing different inputs without changing the code . Similarly, 'WelcomeStudent' uses arguments for a personalized greeting message . However, potential issues include handling user errors (such as missing or incorrectly typed arguments) and limited input data types. Programs must include validation to avoid security risks and ensure robustness .

Inheritance in Java allows a class to inherit fields and methods from another class, promoting reusability and hierarchical classifications. For example, single inheritance is depicted in 'Child' extending 'Parent' to gain access to its methods . Multilevel inheritance involves a class extending another class that is already a subclass, creating a chain. The 'Child' class in the 'Multilevel Inheritance' example extends 'Parent', which in turn extends 'Grandparent', allowing 'Child' to inherit from both . Hierarchical inheritance involves multiple classes extending a single class, as shown with 'Derived1' and 'Derived2' both extending 'Base', facilitating shared base functionality . These paradigms provide a structured approach to complex relationships between classes and enhance maintainability.

Java interfaces provide a way to define contracts for classes to implement, enabling multiple inheritance of behavior. This is particularly useful because Java does not support multiple inheritance of classes. In the 'Bank' example, both 'SBI' and 'PNB' classes implement the 'Bank' interface, each providing their own 'rate_of_interest' method, promoting the use of interface as a shared contract for behavior . Similarly, the 'Animal' interface defines a 'sound' method, which is implemented differently in the 'Dog' and 'Cat' classes, allowing these classes to achieve polymorphic behavior without sharing a common class hierarchy . Interfaces enhance modularity and decouple interfaces from implementations, facilitating flexible code design.

Method overloading allows multiple methods in the same class to have the same name but different parameters (type, number, or both). It provides flexibility and improves code readability by enabling methods to perform similar tasks with different input types. For example, the class 'OverloadExample' demonstrates this by having multiple 'display' methods that accept different parameters . Method overriding involves a subclass having a method with the same name, return type, and parameters as a method in its superclass, enabling polymorphic behavior. The overridden method in the subclass provides a specific implementation of a method that is already defined in its superclass, allowing for dynamic method invocation .

Using scanners to capture user input is direct and flexible, especially in console-based applications, such as accepting matrix entries for multiplication or processing arrays . However, scanners can lead to issues like input mismatch exceptions if user entries are not well-validated. For example, while reading integers for matrices and arrays, invalid input (such as non-integer values) can cause runtime errors. These challenges can be mitigated by implementing robust error handling and validating inputs before processing. Programs can use try-catch blocks to catch exceptions and prompt users for correct input, or use regular expressions to filter input before accepting it .

Recursive methods compute solutions by defining the problem in terms of itself, which can be elegant but may lead to excessive use of stack space and lower efficiency for larger inputs due to redundant calculations. In generating Fibonacci numbers, the recursive method 'fibRec' recalculates the Fibonacci sequence from the ground up each time, which can cause an exponential growth in computation steps . In contrast, the non-recursive version 'fibNonRec' iteratively computes each Fibonacci number by storing intermediate results, significantly improving efficiency . Similarly, a recursive factorial method like 'factRec' calls itself multiple times and may result in stack overflow if the number is large; whereas the non-recursive method 'factNonRec' calculates in a single loop, offering more straightforward and efficient computation .

The 'SortNames' program employs the Arrays.sort method to sort a list of names, leveraging the TimSort algorithm, which combines merge sort and insertion sort, providing efficient sorting for diverse data types. This approach is built-in, hence convenient and optimized for general use, sorting with a time complexity of O(n log n). While effective for typical cases, further performance improvements could be considered for specific scenarios by implementing custom sorting algorithms that better handle unique data structures or distribution patterns. Additionally, supporting custom comparator functions adds flexibility, permitting varied sorting criteria beyond natural order .

You might also like