0% found this document useful (0 votes)
191 views11 pages

Java Programming Exercises for Beginners

The document contains 10 Java programming questions and their solutions. It includes programs to solve quadratic equations, multiply arrays, demonstrate bitwise operators, sort arrays, create student objects, demonstrate method and constructor overloading, create staff subclasses, demonstrate dynamic dispatch and exception handling.
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)
191 views11 pages

Java Programming Exercises for Beginners

The document contains 10 Java programming questions and their solutions. It includes programs to solve quadratic equations, multiply arrays, demonstrate bitwise operators, sort arrays, create student objects, demonstrate method and constructor overloading, create staff subclasses, demonstrate dynamic dispatch and exception handling.
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

Questions:

1 Write a JAVA program that prints all real solutions to the quadratic equation ax2+bx+c=0.
Read in a, b, c and use the quadratic formula.
2 Write a JAVA program for multiplication of two arrays.
3 Demonstrate the following operations and sign extension with Java programs
(i) << (ii) >> (iii) >>>
4 Write a JAVA program to sort list of elements in ascending and descending order
5 Create a JAVA class called Student with the following details as variables within it.
USN
NAME
BRANCH
PHONE
PERCENTAGE
Write a JAVA program to create n Student objects and print the USN, Name, Branch, Phone,
and percentage
of these objects with suitable headings.
6 Write a JAVA program demonstrating Method overloading and Constructor overloading.
7 Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this
class by writing three subclasses namely Teaching (domain, publications), Technical (skills),
and Contract (period). Write a JAVA program to read and display at least 3 staff objects of all
three categories.
8 Demonstrate dynamic dispatch using abstract class in JAVA.
9 Create two packages P1 and P2. In package P1, create class A, class B inherited from A,
class C . In package P2, create class D inherited from class A in package P1 and class E.
Demonstrate working of access modifiers (private, public, protected, default) in all these
classes using JAVA.
10 Write a JAVA program to read two integers a and b. Compute a/b and print, when b is not
zero. Raise an exception when b is equal to zero. Also demonstrate working of
ArrayIndexOutOfBoundException.

Solutions:
1)
package quadratic;

import [Link];

public class Quadratic


{
public static void main(String[] args)
{

double root1, root2,a,b,c,determinant,r;


Scanner input = new Scanner([Link]);

[Link]("Input a: ");
a = [Link]();
[Link]("Input b: ");
b = [Link]();
[Link]("Input c: ");
c = [Link]();

determinant = b * b - 4 * a * c;
r=[Link](determinant);

if (determinant > 0)
{
root1 = (-b+r)/(2*a);
root2 = (-b-r)/(2*a);
[Link]("root1 = %.2f and root2 = %.2f\n", root1, root2);
}

else if (determinant == 0)
{
root1 = root2 = (-b)/(2*a);
[Link]("Roots are equal\n");
[Link]("root1 = root2 = %.2f\n;", root1);
}
else
{
// roots are complex number and distinct
double real = -b / (2 * a);
double imaginary = [Link](-determinant) / (2 * a);
[Link]("Roots are imaginary\n");
[Link]("root1 = %.2f+%.2fi\n", real, imaginary);
[Link]("\nroot2 = %.2f-%.2fi\n", real, imaginary);
}
}
}

2)
package multiplyarray;

import [Link];
public class Multiplyarray {

public static void main(String[] args) {


int a1[] = {2,5,-2,10};
int a2[] = {3,-5,7,1};

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


a1[i] = a1[i] * a2[i];
}

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


{
[Link](a1[i] + " ");
}
}
}

3)
package shiftop;
public class Shiftop
{
public static void main(String args[]) {
byte x, y;
x = 10;
y = -10;
[Link]("Bitwise Left Shift: x<<2 = " + (x << 2));
[Link]("Bitwise Right Shift: x>>2 = " + (x >> 2));
[Link]("Bitwise Zero Fill Right Shift: x>>>2 = " + (x >>> 2));
[Link]("Bitwise Zero Fill Right Shift: y>>>2 = " + (y >>> 2));
}
}

4)
import [Link];

public class ArraySortingExample {


public static void main(String[] args) {
Scanner ed = new Scanner([Link]);
int[] a = new int[50];
int i, j, temp;
[Link]("Please Enter 5 elements in the Array");
for (i = 0; i < 5; i++) {
a[i] = [Link]();
}
for (i = 0; i < 5; i++) {
for (j = i + 1; j < 5; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
[Link]("Sorted Array in Increasing Order:-");
for (j = 0; j < 5; j++) {
[Link](a[j]);
}
for (i = 0; i < 5; i++) {
for (j = i + 1; j < 5; j++) {
if (a[i] < a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
[Link]("Sorted Array in Decreasing Order:-");
for (j = 0; j < 5; j++) {
[Link](a[j]);
}
}
}

5)
package studentinfo;
import [Link];
class Student {
private String usn;
private String name;
private String branch;
private String phone;
private String percentage;
public void read() {
Scanner sc = new Scanner([Link]);
usn = [Link]();
name = [Link]();
branch = [Link]();
phone = [Link]();
percentage = [Link]();
}

public void display() {


[Link](usn + "\t" + name + "\t" + branch + "\t" + phone + "\t" + percentage);
}
}
public class Studentinfo {
public static void main(String[] args) {
[Link]("Enter the total number of students");
Scanner sc = new Scanner([Link]);
int n = [Link]();

// Create n objects
Student[] st = new Student[n];
for (int i = 0; i < [Link]; i++) {
st[i] = new Student(); }
for (int i = 0; i < n; i++) { [Link]("Enter USN, Name, Branch, percentage of
marks and Phone no. for
student " + (i + 1));
st[i].read();
}
// Display the student information
[Link]("USN\tName\tBranch\tPercentage\tPhone");
for (int i = 0; i < n; i++) {
st[i].display();
}
}
}
6)
package mco;

class ABC {
int a, b;
ABC(int x, int y) {
a = x;
b = y;
[Link](" First version of constructor is called");
[Link]("values of a and b are\t" + a + " " + b);
}
ABC(int x) {
a = x;
b = 10;
[Link](" Second version of constructor is called");
[Link]("values of a and b are\t" + a + " " + b);
}
void meth() {
[Link](" First version of method is called");
}
void meth(int x) {
[Link](" Second version of method is called");
}
}

public class Mco {

public static void main(String[] args) {


ABC ob1 = new ABC(20, 20);
ABC ob2 = new ABC(20);
[Link]();
[Link](40);
}
}

7)
package staffmain;
import [Link];
class Staff {
private String staffId;
private String name;
private double phone;
private float salary;

public void accept() {


Scanner scanner = new Scanner([Link]);
[Link]("Enter Staff Id");
staffId = [Link]();
[Link]("Enter Name");
name = [Link]();
[Link]("Enter Phone");
phone = [Link]();
[Link]("Enter Salary");
salary = [Link]();
}
public void display() {
[Link]("Staff Id: " + staffId);
[Link]("Name: " + name);
[Link]("Phone: " + phone);
[Link]("Salary: " + salary);
}
}
class Teaching extends Staff {
private String domain;
private String[] publications;
public void accept() {
[Link]();
Scanner scanner = new Scanner([Link]);
[Link]("Enter Domain");
domain = [Link]();
[Link]("Enter Number of Publications");
int n = [Link]();
publications = new String[n];
[Link]("Enter Publications");
for (int i = 0; i < n; i++) {
publications[i] = [Link]();
}
}

public void display() {


[Link]();
[Link]("Domain: " + domain);
[Link]("Publications:");
for (int i = 0; i < [Link]; i++)
{
[Link](publications[i]);
}
}
}
class Technical extends Staff {
private String[] skills;

public void accept() {


[Link]();
Scanner scanner = new Scanner([Link]);
[Link]("Enter Number of Skills");
int n = [Link]();
skills = new String[n];
[Link]("Enter Skills");
for (int i = 0; i < n; i++) {
skills[i] = [Link]();
}
}

public void display() {


[Link]();
[Link]("Skills:");
for (int i = 0; i < [Link]; i++) {
[Link](skills[i]);
}
}
}

class Contract extends Staff {


private int period;
public void accept() {
[Link]();
Scanner scanner = new Scanner([Link]);
[Link]("Enter Period");
period = [Link]();
}

public void display() {


[Link]();
[Link]("Period: " + period);
}
}

public class Staffmain {

public static void main(String[] args) {


Teaching teaching = new Teaching();
Technical technical = new Technical();
Contract contract = new Contract();
[Link]("Enter Details for Teaching Staff Member");
[Link]();
[Link]("Enter Details for Technical Staff Member");
[Link]();
[Link]("Enter Details for Contract Staff Member");
[Link]();
[Link]("Details for Teaching Staff Member are");
[Link]();
[Link]("Details for Technical Staff Member are");
[Link]();
[Link]("Details for Contract Staff Member are");
[Link]();
}
}

8)
package dynamicdsp;

abstract class Figure {


double d1;
double d2;
Figure(double a, double b) {
d1 = a;
d2 = b;
}

abstract double area();


}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}

double area() {
[Link]("Inside Area for Rectangle.");
return d1 * d2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}

double area() {
[Link]("Inside Area for Triangle.");
return 0.5 * d1 * d2;
}
}
public class Dynamicdsp {

public static void main(String[] args) {


Rectangle r = new Rectangle(5, 10);
Triangle t = new Triangle(5, 10);
Figure f; //reference only(no object is created)

f = r;
[Link]("Area is " + [Link]());

f = t;
[Link]("Area is " + [Link]());
}
}

9)
package P1;

public class A {
protected int a;
void displayA(){
[Link]("class A");
}
}
public class B extends A{
public void displayB(){
a=10;
[Link]("Class B:"+" The value of a is "+a);
}
}

public class C {
void displayC(){
[Link]("Class C");
}
}

package P2;
import P1.*;

public class D extends A {


public void displayD(){
a=100;
[Link]("Class D: "+"The value of a is "+a);
}
}

public class E {
private void displayE(){
[Link]("Class E");
}
}

package packagesdemo;

import P1.*;
import P2.*;
public class Packagesdemo {

public static void main(String[] args) {


B b=new B();
C c=new C();
D d=new D();
E e=new E();

[Link](); //public method, protected data member


//error [Link](); //default method
[Link](); //public method,protected data member
//error [Link](); //private method

}
}
10)

(WRITE THESE IN LOER CASE LETTERS)

package excdemo;

import [Link];
public class excdemo {
PUBLIC STATIC VOID MAIN(STRING ARGS[]) {
INT A, B, RESULT;
SCANNER S = NEW SCANNER([Link]);
[Link]("ENTER THE VALUE OF A AND B");
A = [Link]();
B = [Link]();
TRY {
RESULT = A / B;
INT C[] = {1};
C[40] = 99;
} CATCH (ARITHMETICEXCEPTION E) {
[Link]("DIVIDE BY 0: " + E);
} CATCH (ARRAYINDEXOUTOFBOUNDSEXCEPTION E) {
[Link]("ARRAY INDEX OUT OF BOUND: " + E);
}
[Link]("AFTER TRY/CATCH BLOCKS.");
}

Common questions

Powered by AI

The program demonstrates three types of bitwise shift operations: left shift (<<), right shift (>>), and zero-fill right shift (>>>). These operations manipulate the bits of a binary number, shifting them left or right. Left shift (<<) multiplies the number by 2 for each shift, right shift (>>) preserves the sign bit filling with the sign bit, and zero-fill right shift (>>>) fills with zero regardless of the sign bit .

The Java program uses try-catch blocks to manage exceptions, ensuring the program continues running even if an error occurs. For arithmetic exceptions, such as dividing by zero, an ArithmeticException is caught. ArrayIndexOutOfBoundsException is caught for attempts to access invalid array indices. Each catch block handles the specific exception type, allowing separate responses for different errors .

The Java program illustrates inheritance by extending classes (e.g., class 'B' inherits 'A', and 'D' inherits from 'A' in different packages). Access modifiers (public, private, protected, default) control visibility. Public methods are accessible throughout, protected ones within the same package or subclasses, and private methods only within their own class. The program shows errors when trying to access private methods outside their class .

The program prompts user input for array elements, storing them in an integer array. Sorting is executed in two steps, first arranging elements in ascending order by comparing and swapping, followed by a similar process for descending order. Nested loops iteratively position elements based on comparative conditions, resulting in sorted outputs .

Method overloading involves defining multiple methods with the same name but different parameter lists, whereas constructor overloading involves defining multiple constructors in a class with different parameter configurations. The provided program demonstrates method overloading with 'meth()' and 'meth(int x)', and constructor overloading with 'ABC(int x, int y)' and 'ABC(int x)' versions .

Dynamic method dispatch in Java allows a superclass reference variable to refer to a subclass object, enabling Java to invoke subclass methods at runtime. In the program, the superclass reference 'f' is used to call 'area()' for both 'Rectangle' and 'Triangle' objects, allowing the invocation of the appropriate subclass method .

The Java program calculates the determinant (b^2 - 4ac) to determine the nature of roots. If the determinant is positive, it computes two real solutions using the formula (-b±√determinant)/(2a). If zero, it indicates two equal real roots, calculated as -b/(2a). If negative, it calculates complex roots using real = -b/(2a) and imaginary = √(-determinant)/(2a).

In package P1, class B extends class A, inheriting its protected members, which can be accessed within subclass B. Class C, with default access, limits use within its package. In package P2, class D inherits A, accessed due to protected visibility and proper package importation. Class E, with private methods, restricts external access, demonstrating varied access control mechanics .

Designing a Staff superclass in Java facilitates code reuse and scalability, allowing shared attributes like StaffId, Name, and Salary to be defined once. Subclasses (Teaching, Technical, Contract) extend the superclass to add specific features (e.g., publications, skills, period), enhancing specialization while preserving base class functionality. This promotes modularity and organized management of different staff categories .

The program uses a Student class encapsulating data fields such as USN, Name, and Percentage. It provides methods for reading via keyboard input and displaying the data. A 'Studentinfo' class manages multiple Student objects by creating an array of Student, invoking methods to populate and showcase student data, practicing encapsulation and class object management .

You might also like