You are on page 1of 57

Milestone – 1

NAME :- SHIVAM SHARMA

ROLL NO-96

IT- (B)

JAVA FUNDAMENTALS
Language Basics Assignment
1. Write a Program that accepts two Strings as command line
arguments and generate the output in a specific way as given
below.

Example:

If the two command line arguments are Wipro and Bangalore


then the output generated should be Wipro Technologies
Bangalore.

If the command line arguments are ABC and Mumbai then the
output generated should be ABC Technologies Mumbai

SOLUTION
package Milestone1.javafundamentals.Basics;
import java.util.*;
public class Assignment1 {

public static void main(String[] args) {


Scanner scn = new Scanner(System.in);
String x = scn.next();
String y = scn.next();
System.out.println(x + " Technologies " + y);
}

}
2.Write a Program to accept two integers through the
command line argument and print the sum of the two numbers

SOLUTION

import java.util.Scanner;
public class Assignment2 {

public static void main(String[] args) {


Scanner scn = new Scanner(System.in);
int a = scn.nextInt();
int b = scn.nextInt();
int c = a + b;

System.out.printf("The sum of %d and %d is %d", a, b, c);

}
FLOW CONTROL ASSIGNMENT
1.Write a program to check if a given number is Positive,
Negative, or Zero.

SOLUTION
import java.util.Scanner;

public class Assignment1 {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

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


int x = sc.nextInt();

if (x < 0) System.out.println("Negative");
else if (x == 0) System.out.println("Zero");
else System.out.println("Positive");

main(args);
sc.close();
}

}
2.Write a program to check if a given number is odd or even.

SOLUTION
import java.util.Scanner;

public class Assignment2 {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

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


int x = sc.nextInt();

if (x % 2 == 0) System.out.println("Even");
else System.out.println("Odd");

main(args);
sc.close();
}

}
3.Initialize two character variables in a program and display the
characters in alphabetical order. Eg1) if first character is s and
second is e O/P: e,s Eg2) if first character is a and second is e
O/P: a,e.

SOLUTION
public class Assignment4 {

public static void main(String[] args) {


char x = 'e';
char y = 'a';

if (x < y) {
System.out.println(x + ", " + y);
} else {
System.out.println(y + ", " + x);
}

}
4.Write a program to accept gender ("Male" or "Female") and
age (1-120) from command line arguments and print the
percentage of interest based on the given conditions. Interest
== 8.2% Gender ==> Female Age ==>1 to 58 Interest == 7.6%
Gender ==> Female Age ==>59 -120 Interest == 9.2% Gender
==> Male Age ==>1-60 Interest == 8.3% Gender ==> Male
Age ==>61-120.

SOLUTION
import java.util.*;
public class Assignment6 {

public static void main(String[] args) {


Scanner scn = new Scanner(System.in);
String gender = scn.next();
int age = scn.nextInt();

if (!gender.equals("Male") && !gender.equals("Female"))


System.out.println("Invalid gender");

if (age < 1 || age >= 120)


System.out.println("Invalid age");

if (gender.equals("Female") && (age >= 1 && age <= 58)) {


System.out.println("Interest == 8.2%");
} else if (gender.equals("Female") && (age >= 59 && age
<= 120)) {
System.out.println("Interest == 7.6%");
} else if (gender.equals("Male") && (age >= 1 && age <=
60)) {
System.out.println("Interest == 9.2%");
} else if (gender.equals("Male") && (age >= 61 && age <=
120)) {
System.out.println("Interest == 8.3%");
}

5.Write a program to convert from upper case to lower case


and vice versa of an alphabet and print the old character and
new character as shown in example (Ex: a->A, M->m).

SOLUTION
public class Assignment7 {

public static void main(String[] args) {


char ch = 'a';

if (Character.isLowerCase(ch))
System.out.println(ch + "->" +
Character.toUpperCase(ch));
else
System.out.println(ch + "->" +
Character.toLowerCase(ch));

6. Write a program to print month in words, based on input


month in numbers

SOLUTION
import java.util.*;
import java.time.Month;
public class Assignment9 {

public static void main(String[] args) {


Scanner scn = new Scanner(System.in);
if (args.length == 0) {
System.out.println("Please enter the month in
numbers");
}

int month =scn.nextInt();

if (month < 1 || month > 12) {


System.out.println("Invalid month");
System.exit(0);
}

String monthStr = Month.of(month).name();


monthStr = monthStr.substring(0,1).toUpperCase() +
monthStr.substring(1).toLowerCase();

System.out.println(monthStr);

7. Write a program to check if a given number is prime or not.

SOLUTION
public class Assignment12 {

public static void main(String[] args) {


int no = -4;

if (no < 0) no *= -1;

Boolean isPrime = true;

for (int i = 2; i < no/2+1; i++) {


if (no % i == 0) {
isPrime = false;
break;
}
}

if (no == 0 || no == 1) isPrime = false;

if (isPrime) System.out.println("prime");
else System.out.println("not prime");
}

8. Write a program to print prime numbers between 10 and 99.

SOLUTION
public class Assignment13 {

public static void main(String[] args) {


for (int i = 10; i <= 99; i++) {
if (isPrime(i)) System.out.println(i);
}

public static boolean isPrime(int no) {


if (no < 0) no *= -1;

Boolean isPrime = true;


for (int i = 2; i < no/2+1; i++) {
if (no % i == 0) {
isPrime = false;
break;
}
}

if (no == 0 || no == 1) isPrime = false;

return isPrime;
}

9.Write a program to reverse a given number and print.

SOLUTION
package Milestone1.javafundamentals.Flowcontrol;
import java.util.*;
public class Assignment17 {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

int ip = sc.nextInt();
int op = 0;
int i = (int) Math.pow(10, String.valueOf(ip).length() -
1);
while (ip != 0) {
int digit = ip % 10;
op += digit * i;
i /= 10;
ip /= 10;
}

System.out.println(op);

sc.close();
}

10. Write a Java program to find if the given number is


palindrome or not.

SOLUTION
package Milestone1.javafundamentals.Flowcontrol;
import java.util.*;
public class Assignment18 {

public static void main(String[] args) {


Scanner scn = new Scanner(System.in);
int number = scn.nextInt();

if (getPalindromeNumber(number) == 2)
System.out.println(number + " is a palindrome");
else
System.out.println(number + "is not a palindrome");
}

public static int getPalindromeNumber (int input1) {


String numberStr = String.valueOf(input1);
int digitCount = numberStr.length();
boolean isPalindrome = true;

int range = digitCount / 2;


if (digitCount % 2 == 0) range--;

for (int i = 0; i <= range; i++) {


if (numberStr.charAt(i) !=
numberStr.charAt(digitCount - i - 1)) isPalindrome = false;
}

if (isPalindrome == true) return 2;


else return 1;
}

Arrays Assignment
1.Write a program to initialize an integer array and print the
sum and average of the array.
SOLUTION
package Milestone1.javafundamentals.Arrays;
public class Assignment1 {
public static void main(String[] args) {
int[] array = {5, 4, 3, 9, 1, 7, 9};

double sum = 0;
double avg;

for (int i = 0; i < array.length; i++) {


sum += array[i];
}

avg = sum / array.length;

System.out.println("Average: " + avg);


}
}

2.Write a program to initialize an integer array and find the


maximum and minimum value of an array.

SOLUTION
package Milestone1.javafundamentals.Arrays;
public class Assignment2 {

public static void main(String[] args) {


int[] array = {5, 4, 3, 9, 1, 7, 9};

int min = array[0];


int max = array[0];

for (int i = 0; i < array.length; i++) {


if (array[i] < min) min = array[i];
if (array[i] > max) max = array[i];
}

System.out.println("Min: " + min);


System.out.println("Max: " + max);
}

3. Write a program to initialize an integer array with values and


check if a given number is present in the array or not. If the
number is not found, it will print -1 else it will print the index
value of the given number in the array Ex1) Array elements are
{1,4,34,56,7} and the search element is 90 O/P: -1 Ex2)Array
elements are {1,4,34,56,7} and the search element is 56 O/P: 4.

SOLUTION
package Milestone1.javafundamentals.Arrays;
public class Assignment3 {
public static void main(String[] args) {
int[] haystack = {5, 4, 3, 9, 1, 7, 9};
int needle = 9;
int index = -1;

for (int i = 0; i < haystack.length; i++) {


if (haystack[i] == needle) {
index = i + 1;
break;
}
}

System.out.println(index);
}

4.Initialize an integer array with ascii values and print the


corresponding character values in a single row.

SOLUTION
package Milestone1.javafundamentals.Arrays;
public class Assignment4 {

public static void main(String[] args) {


int[] array = {48, 55, 68, 88, 101, 122};
for (int i = 0; i < array.length; i++) {
System.out.printf("%c ", array[i]);
}

5. Write a program to find the largest 2 numbers and the


smallest 2 numbers in the given array.

SOLUTION
package Milestone1.javafundamentals.Arrays;
import java.util.Arrays;

public class Assignment5 {

public static void main(String[] args) {


int[] array = {48, 55, 68, 88, 101, 122};
Arrays.sort(array);

System.out.println("Smallest two in the array: " +


array[0] + " and " + array[1]);
System.out.println("Largest two in the array: " +
array[array.length-1] + " and " + array[array.length-2]);
}

}
6.Write a program to initialize an array and print them in a
sorted fashion.

SOLUTION
package Milestone1.javafundamentals.Arrays;
import java.util.Arrays;

public class Assignment6 {

public static void main(String[] args) {


int[] array = {48, 105, 8, 88, 101, 122};

Arrays.sort(array);

System.out.println(Arrays.toString(array));

}
7. Write a program to remove the duplicate elements in an
array and print .

SOLUTION
package Milestone1.javafundamentals.Arrays;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Assignment7 {

public static void main(String[] args) {


int[] array = {12, 34, 12, 45, 67, 89};
List<Integer> distinctArray = new ArrayList<>();

for (int item : array) {


if (!distinctArray.contains(item))
distinctArray.add(item);
}

System.out.println(Arrays.toString(distinctArray.toArray()));

}
OOPS/INHERITANCE
Object And Classes Assignment
1.Create a class Box that uses a parameterized method to
initialize the dimensions of a box.(dimensions are width, height,
depth of double type). The class should have a method that can
return volume. Obtain an object and print the corresponding
volume in main() function.

SOLUTION
package Milestone1.Oops.ObjectClasses;
class Box {
private double width;
private double height;
private double depth;

public Box(double width, double height, double depth) {


this.width = width;
this.height = height;
this.depth = depth;
}
public double getVolume() {
return width * height * depth;
}
}

public class Assignment1 {

public static void main(String[] args) {


Box box = new Box(16, 9, 4);
System.out.println(box.getVolume());
}

2.Create a new class called “Calculator” which contains the


following:

1. A static method called powerInt(int num1,int num2) that


accepts two integers and returns num1 to the power of
num2 (num1 power num2).

2. A static method called powerDouble(double num1,int


num2) that accepts one double and one integer and
returns num1 to the power of num2 (num1 power num2).
3. Call your method from another class without instantiating
the class (i.e. call it like Calculator.powerInt(12,10) since
your methods are defined to be static) Hint: Use
Math.pow(double,double) to calculate the power.

SOLUTION
package Milestone1.Oops.ObjectClasses;
class Calculator {
public static int powerInt(int num1, int num2) {
return (int) Math.pow(num1, num2);
}

public static double powerDouble(double num1, int num2) {


return Math.pow(num1, num2);
}
}

public class Assignment2 {

public static void main(String[] args) {


System.out.println(Calculator.powerInt(12, 2));
System.out.println(Calculator.powerDouble(1.5, 2));
}

}
ENCAPSULATION/ABSTRACTION ASSIGNMENT
1.Create a class called Author is designed as follows:

It contains: • Three private instance variables: name (String),


email (String), and gender (char of either ‘m’ or ‘f’). • One
constructor to initialize the name, email and gender with the
given values.

And, a class called Book is designed as follows: It contains: •


Four private instance variables: name (String), author (of the
class Author you have just created), price (double), and
qtyInStock (int). Assuming that each book is written by one
author. • One constructor which constructs an instance with the
values given. • Getters and setters: getName(), getAuthor(),
getPrice(), setPrice(), getQtyInStock(), setQtyInStock(). Again
there is no setter for name and author. Write the class Book
(which uses the Author class written earlier). Try:

1. Printing the book name, price and qtyInStock from a Book


instance. (Hint: aBook.getName())

2. After obtaining the “Author” object, print the Author


(name, email & gender) of the book.

SOLUTION
package Milestone1.Oops.Encapsulation;
class Author {
private String name;
private String email;
private char gender;

public Author(String name, String email, char gender) {


super();
this.name = name;
this.email = email;
this.gender = gender;
}
public String getName() {
return name;
}

public String getEmail() {


return email;
}

public char getGender() {


return gender;
}
public String toString() {
return "Author [name=" + name + ", email=" + email + ",
gender=" + gender + "]";
}

class Book {
private String name;
private Author author;
private double price;
private int qtyInStock;

public Book(String name, Author author, double price, int


qtyInStock) {
super();
this.name = name;
this.author = author;
this.price = price;
this.qtyInStock = qtyInStock;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}

public int getQtyInStock() {


return qtyInStock;
}

public void setQtyInStock(int qtyInStock) {


this.qtyInStock = qtyInStock;
}
public String getName() {
return name;
}

public Author getAuthor() {


return author;
}

public String toString() {


return "Book [name=" + name + ", author=" + author + ",
price=" + price + ", qtyInStock=" + qtyInStock + "]";
}

public class Assignment1 {

public static void main(String[] args) {


Author author = new Author("Arpan Das",
"arp14@yahoo.com", 'M');
Book book = new Book("Java Fundamentals", author, 199.0,
500);

System.out.println(book);
}

}
INHERITANCE ASSIGNMENT
1.Create a class named ‘Animal’ which includes methods like
eat() and sleep(). Create a child class of Animal named ‘Bird’ and
override the parent class methods. Add a new method named
fly(). Create an instance of Animal class and invoke the eat and
sleep methods using this object.Create an instance of Bird class
and invoke the eat, sleep and fly methods using this object.

SOLUTION
package Milestone1.Oops.Inheritance;
class Animal {

public void eat () {


System.out.println("Animal eat");
}

public void sleep () {


System.out.println("Animal sleep");
}
}

class Bird extends Animal {

public void eat () {


System.out.println("Bird eat");
}
public void sleep () {
System.out.println("Bird sleep");
}

public void fly () {


System.out.println("Bird fly");
}
}

public class Assignment1 {

public static void main(String[] args) {


Animal animal = new Animal();
animal.eat();
animal.sleep();

Bird bird = new Bird();


bird.eat();
bird.sleep();
bird.fly();
}

2.Create a class called Person with a member variable name.


Save it in a file called Person.java Create a class called Employee
who will inherit the Person class.The other data members of the
employee class are annual salary (double), the year the
employee started to work, and the national insurance number
which is a String.Save this in a file called Employee.java Your
class should have a reasonable number of constructors and
accessor methods. Write another class called TestEmployee,
containing a main method to fully test your class definition.

SOLUTION

Person Class
package Milestone1.Oops.Inheritance;
public class Person {
protected String name;
public Person(String name) {
this.name = name;
}

public String getName() {


return name;
}

@Override
public String toString() {
return "Person [name=" + name + "]";
}

Employee Class
package Milestone1.Oops.Inheritance;
public class Employee extends Person {
private double annualSalary;
private int yearOfJoining;
private String nationalInsuranceNo;

public Employee(String name, double annualSalary, int


yearOfJoining, String nationalInsuranceNo) {
super(name);
this.annualSalary = annualSalary;
this.yearOfJoining = yearOfJoining;
this.nationalInsuranceNo = nationalInsuranceNo;
}

public double getAnnualSalary() {


return annualSalary;
}

public int getYearOfJoining() {


return yearOfJoining;
}

public String getNationalInsuranceNo() {


return nationalInsuranceNo;
}

public String getName() {


return name;
}
public String toString() {
return "Employee [annualSalary=" + annualSalary + ",
yearOfJoining=" + yearOfJoining + ", nationalInsuranceNo="
+ nationalInsuranceNo + ", name=" + name +
"]";
}

Main Class
package Milestone1.Oops.Inheritance;

public class Assignment2 {

public static void main(String[] args) {


Employee employee = new Employee("John Doe", 5000000,
2019, "321a2sd1321ad");
System.out.println(employee);
}

}
STRING & STRING BUFFER ASSIGNMENT
1.Write a Program that will check whether a given String is
Palindrome or not.

SOLUTION
package Milestone1.Oops.String;
public class Assignment1 {
public static boolean isPalindrome (String input1) {
int digitCount = input1.length();
boolean isPalindrome = true;

int range = digitCount / 2;


if (digitCount % 2 == 0) range--;

for (int i = 0; i <= range; i++) {


if (input1.charAt(i) != input1.charAt(digitCount - i
- 1)) isPalindrome = false;
}

return isPalindrome;
}

public static void main(String[] args) {


System.out.println(isPalindrome("MADAM"));
System.out.println(isPalindrome("MOM"));
System.out.println(isPalindrome("MOTHER"));

2.Given two strings, append them together (known as


"concatenation") and return the result. However, if the
concatenation creates a double-char, then omit one of the
chars. If the inputs are “Mark” and “Kate” then the ouput should
be “markate”. (The output should be in lowercase).

SOLUTION
package Milestone1.Oops.String;
public class Assignment2 {

public static void main(String[] args) {

String str1 = "Mark";


String str2 = "Kate";

str1 = str1.toLowerCase();
str2 = str2.toLowerCase();

StringBuffer sb = new StringBuffer();


sb.append(str1);

if (str1.charAt(str1.length() - 1) == str2.charAt(0)) {
sb.append(str2.substring(1, str2.length()));
} else {
sb.append(str2);
}

System.out.println(sb);

sb.append(str1);

}
3.Given a string, return a new string made of n copies of the
first 2 chars of the original string where n is the length of the
string. The string may be any length. If there are fewer than 2
chars, use whatever is there. If input is "Wipro" then output
should be "WiWiWiWiWi".

SOLUTION
package Milestone1.Oops.String;
public class Assignment3 {

public static void main(String[] args) {


String str = "Wipro";
int n = str.length();

String repeater = "";

if (n < 2) repeater = str;


else repeater = str.substring(0, 2);

String output = "";

for (int i = 0; i < n; i++) {


output += repeater;
}

System.out.println(output);
}
}

4.Given a string of even length, return the first half. So the


string "CatDog" yields "Cat". If the string length is odd number
then return null.

SOLUTION
package Milestone1.Oops.String;
public class Assignment4 {

public static void main(String[] args) {


String str = "CatDogs";

String output;

if (str.length() % 2 == 0) {
output = str.substring(0, str.length() / 2);
} else {
output = null;
}

System.out.println(output);
}

}
5.Given a string, return a version without the first and last char,
so "Wipro" yields "ipr". The string length will be at least 2.

SOLUTION
package Milestone1.Oops.String;
public class Assignment5 {

public static void main(String[] args) {


String str = "Wipro";

str = str.substring(1, str.length() - 1);

System.out.println(str);
}

}
6.Given 2 strings, a and b, return a string of the form
short+long+short, with the shorter string on the outside and
the longer string on the inside. The strings will not be the same
length, but they may be empty (length 0). If input is "hi" and
"hello", then output will be "hihellohi".

SOLUTION
package Milestone1.Oops.String;
public class Assignment6 {

public static void main(String[] args) {


String a = "hi";
String b = "hello";
String output;

if (a.length() < b.length())


output = a + b + a;
else
output = b + a + b;

System.out.println(output);
}

}
7.Given a string, if the first or last chars are 'x', return the string
without those 'x' chars, and otherwise return the string
unchanged. If the input is "xHix", then output is "Hi".

SOLUTION
package Milestone1.Oops.String;
public class Assignment7 {

public static void main(String[] args) {


String str = "xHix";

if (str.charAt(0) == 'x')
str = str.substring(1, str.length());

if (str.charAt(str.length() - 1) == 'x')
str = str.substring(0, str.length() - 1);

System.out.println(str);

}
ABSTRACTION/PACKAGES/EXCEPTION HANDLING
ABSTRACT CLASSES ASSIGNMENT
1.Create an abstract class Compartment to represent a rail
coach. Provide an abstract function notice in this class. Derive
FirstClass, Ladies, General, Luggage classes from the
compartment class. Override the notice function in each of
them to print notice suitable to the type of the compartment.
Create a class TestCompartment . Write main function to do the
following: Declare an array of Compartment of size 10. Create a
compartment of a type as decided by a randomly generated
integer in the range 1 to 4. Check the polymorphic behavior of
the notice method.

SOLUTION

Compartment Class
package Milestone1.ExceptionHandling.AbstractClass;

public abstract class Compartment {


public abstract void notice();
}

FirstClass
package Milestone1.ExceptionHandling.AbstractClass;

public class FirstClass extends Compartment {

public void notice() {


System.out.println("Notice: You're in FirstClass");
}

General Class
package Milestone1.ExceptionHandling.AbstractClass;

public class General extends Compartment {

public void notice() {


System.out.println("Notice: You're in General");
}

Ladies Class
package Milestone1.ExceptionHandling.AbstractClass;

public class Ladies extends Compartment {

public void notice() {


System.out.println("Notice: You're in Ladies");
}

Luggage Class
package Milestone1.ExceptionHandling.AbstractClass;

public class Luggage extends Compartment {

public void notice() {


System.out.println("Notice: You're in Luggage");
}

TestCompartment Class
package Milestone1.ExceptionHandling.AbstractClass;

import java.util.Random;

public class TestCompartment {

public static void main(String[] args) {


Compartment[] compartments = new Compartment[10];

Random rand = new Random();

for (int i = 0; i < 10; i++) {


int randomNum = rand.nextInt((4 - 1) + 1) + 1;

if (randomNum == 1)
compartments[i] = new FirstClass();
else if (randomNum == 2)
compartments[i] = new Ladies();
else if (randomNum == 3)
compartments[i] = new General();
else if (randomNum == 4)
compartments[i] = new Luggage();

compartments[i].notice();
}
}

}
EXCEPTION HANDLING ASSIGNMENT
1.Write a program that takes as input the size of the array and
the elements in the array. The program then asks the user to
enter a particular index and prints the element at that index.
This program may generate Array Index Out Of Bounds
Exception. Use exception handling mechanisms to handle this
exception. In the catch block, print the class name of the
exception thrown.

SOLUTION
package Milestone1.ExceptionHandling.Exception;
import java.util.Scanner;

public class Assignment1 {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of elements in the


array: ");
int n = sc.nextInt();

int[] arr = new int[n];

System.out.println("Enter the elements in the array: ");


for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();

System.out.println("Enter the index of the array element


you want to access");
int index = sc.nextInt();
try {
System.out.println("The array element at index " +
index + " = " + arr[index]);
System.out.println("The array element successfully
accessed");
} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("java.lang.ArrayIndexOutOfBoundsException");
}

sc.close();
}

}
2.Write a class MathOperation which accepts integers from
command line. Create an array using these parameters. Loop
through the array and obtain the sum and average of all the
elements. Display the result. Check for various exceptions that
may arise like ArithmeticException, NumberFormatException,
and so on.

SOLUTION
package Milestone1.ExceptionHandling.Exception;
import java.util.InputMismatchException;
import java.util.*;

public class Assignment2 {

public static void main(String[] args) {


Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];

int sum = 0;
double avg = 0;

try {
for (int i = 0; i < n; i++)
arr[i] = scn.nextInt();
for (int i = 0; i < n; i++)
sum += arr[i];

avg = sum / n;
} catch (NumberFormatException e) {
System.out.println("NumberFormatException");
} catch (ArithmeticException e) {
System.out.println("ArithmeticException");
} catch (InputMismatchException e) {
System.out.println("InputMismatchException");
}

System.out.println("sum: " + sum);


System.out.println("avg: " + avg);

3.Write a Program to take care of Number Format Exception if


user enters values other than integer for calculating average
marks of 2 students. The name of the students and marks in 3
subjects are taken from the user while executing the program.
In the same Program write your own Exception classes to take
care of Negative values and values out of range (i.e. other than
in the range of 0-100)

SOLUTION

ValuesOutOfRangeException Class

public class ValuesOutOfRangeException extends Exception {


public ValuesOutOfRangeException() {
super();
System.out.println("ValuesOutOfRangeException occured");
}
}

NegativeValuesException Class

public class NegativeValuesException extends Exception {


public NegativeValuesException() {
super();
System.out.println("NegativeValuesException occured");
}
}

Main Class
import java.util.Scanner;

public class Assignment3 {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

for (int i = 0; i < 2; i++) {


String name = "";
int subA = 0;
int subB = 0;
int subC = 0;

try {
name = sc.nextLine();

if (sc.hasNextInt())
subA = sc.nextInt();
else
throw new NumberFormatException();

if (sc.hasNextInt())
subB = sc.nextInt();
else
throw new NumberFormatException();

if (sc.hasNextInt())
subC = sc.nextInt();
else
throw new NumberFormatException();

if (subA < 0) throw new


NegativeValuesException();
if (subA > 100) throw new
ValuesOutOfRangeException();

if (subB < 0) throw new


NegativeValuesException();
if (subB > 100) throw new
ValuesOutOfRangeException();

if (subC < 0) throw new


NegativeValuesException();
if (subC > 100) throw new
ValuesOutOfRangeException();

} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (NegativeValuesException e) {
System.out.println(e.getMessage());
} catch (ValuesOutOfRangeException e) {
System.out.println(e.getMessage());
}

System.out.println("Name: " + name);


System.out.println("Marks of subject A: " + subA);
System.out.println("Marks of subject B: " + subB);
System.out.println("Marks of subject C: " + subC);
}

sc.close();

}
4.Write a program to accept name and age of a person from
the command prompt(passed as arguments when you execute
the class) and ensure that the age entered is >=18 and < 60.
Display proper error messages. The program must exit
gracefully after displaying the error message in case the
arguments passed are not proper. (Hint : Create a user defined
exception class for handling errors).

SOLUTION

InvalidAgeException Class
package Milestone1.ExceptionHandling.Exception;
public class InvalidAgeException extends Exception {
public InvalidAgeException() {
super();
System.out.println("Invalid age");
}
}

Main Class
package Milestone1.ExceptionHandling.Exception;
import java.util.Scanner;
public class Assignment4 {

public static void main(String[] args) throws


InvalidAgeException {
Scanner scn = new Scanner(System.in);
String name = scn.next();

int age = scn.nextInt();

if (age < 18 || age >= 60)


throw new InvalidAgeException();

System.out.println("Name: " + name + " Age: " + age);


}

}
WRAPPER CLASSES ASSIGNMENT
1.Write a java program which generates the minimum and
maximum value for each of the Numeric Wrapper classes (Byte,
Short, Integer, Long, Float, Double).

SOLUTION
package Milestone1.WrapperClasses;
public class Assignment1 {

public static void main(String[] args) {


System.out.println("Integer range:");
System.out.println("min: " + Integer.MIN_VALUE);
System.out.println("max: " + Integer.MAX_VALUE);

System.out.println("Double range:");
System.out.println("min: " + Double.MIN_VALUE);
System.out.println("max: " + Double.MAX_VALUE);

System.out.println("Long range:");
System.out.println("min: " + Long.MIN_VALUE);
System.out.println("max: " + Long.MAX_VALUE);

System.out.println("Short range:");
System.out.println("min: " + Short.MIN_VALUE);
System.out.println("max: " + Short.MAX_VALUE);

System.out.println("Byte range:");
System.out.println("min: " + Byte.MIN_VALUE);
System.out.println("max: " + Byte.MAX_VALUE);

System.out.println("Float range:");
System.out.println("min: " + Float.MIN_VALUE);
System.out.println("max: " + Float.MAX_VALUE);
}

2.Accept a integer number as Command line argument from


the program and when the program is executed print the
binary, octal and hexadecimal equivalent of the given number.

SOLUTION
package Milestone1.WrapperClasses;
import java.util.Scanner;
public class Assignment2 {

public static void main(String[] args) {


Scanner scn = new Scanner(System.in);
int num = scn.nextInt();
System.out.println("Given Number: " + num);
System.out.println("Binary equivalent: " +
Integer.toBinaryString(num));
System.out.println("Octal equivalent: " +
Integer.toOctalString(num));
System.out.println("Hexadecimal equivalent: " +
Integer.toHexString(num));

3.Define a java class that accepts an integer(between 1 and 255)


from the user and displays the String representation of the
argument passed as an unsigned integer in base 2. The output
displayed should contain 8 digits and should be padded with
leading 0s(zeros), in case the returned String contains less than
8 characters.

SOLUTION
package Milestone1.WrapperClasses;
import java.util.Scanner;

public class Assignment3 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

int input = sc.nextInt();

String output = String.format("%8s",


Integer.toBinaryString(input)).replace(' ', '0');
System.out.println(output);

sc.close();

4.Create an employee object and initialize its properties. Create


a clone of this object and store it in a different object. Now
change the properties of the first employee object. Print both
the objects and observe the change.

SOLUTION
package Milestone1.WrapperClasses;
class Employee implements Cloneable {
private String name;
public Employee(String name) {
this.name = name;
}

// public Employee(Employee emp) {


// this.name = emp.name;
// }

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
public Employee clone() {
try {
return (Employee) super.clone();
} catch (CloneNotSupportedException e) {
System.out.println("Cloning Not Allowed");
return this;
}
}
}

public class Assignment4 {

public static void main(String[] args) {


Employee emp = new Employee("Bob Biswas");
Employee empClone = emp.clone();

empClone.setName("John Doe");

System.out.println(empClone.getName());
System.out.println(emp.getName());
}

You might also like