Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Java Assignment-3 (Programmes)

Uploaded by

aaaryasingh1602
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java Assignment-3 (Programmes)

Uploaded by

aaaryasingh1602
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1.

Write a Java program to create a class called "Rectangle" with width


and height attributes. Calculate the area and perimeter of the
rectangle.

Java Code:

//Rectangle.java
public class Rectangle {
private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
}

2. Java Program to Print Pyramid Number Pattern

Here we are getting a step ahead in printing patterns as in generic we usually play with columnar
printing in the specific row keep around where elements in a row are either added up throughout
or getting reduced but as we move forward we do start playing with rows which hold for outer
loop in our program.

Illustrations:

A pyramid number pattern of row size r = 5 would look like:


1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
A pyramid number pattern of row size r = 4 would look like:
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4

Approach:

1. For loop will be used to print each row in the pyramid.


2. Inside the for loop we will use two loops :
3. One loop is used to print the spaces
4. The second loop will be used to print the numbers.

Implementation:

// Java Program to Print the Pyramid pattern

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
int num = 5;
int x = 0;

// Outer loop for rows


for (int i = 1; i <= num; i++) {
x = i - 1;

// inner loop for "i"th row printing


for (int j = i; j <= num - 1; j++) {

// First Number Space


System.out.print(" ");

// Space between Numbers


System.out.print(" ");
}

// Pyramid printing
for (int j = 0; j <= x; j++)
System.out.print((i + j) < 10
? (i + j) + " "
: (i + j) + " ");

for (int j = 1; j <= x; j++)


System.out.print((i + x - j) < 10
? (i + x - j) + " "
: (i + x - j) + " ");
// By now we reach end for one row, so
// new line to switch to next
System.out.println();
}
}
}

Output
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5

3. Java Program to Check Armstrong Number between Two Integers

A positive integer with digits p, q, r, s…, is known as an Armstrong number of order n if the
following condition is fulfilled.

pqrs... = pn + qn + rn + sn +....

Example:

370 = 3*3*3 + 7*7*7 + 0


= 27 + 343 + 0
= 370

Therefore, 370 is an Armstrong number.

Examples:

Input : 100 200


Output :153
Explanation : 100 and 200 are given
two integers.
153 = 1*1*1 + 5*5*5 + 3*3*3
= 1 + 125 + 27
= 153
Therefore, only 153 is an Armstrong number between 100 and 200.

Approach:

Firstly, we will traverse through all the numbers in the given range. Then, for every number, we
have to count the number of digits in it. If the number of digits in the current number is n then,
find the sum of (n-th) power of all the digits in the number stated. And if the sum is equal to the
current number i, then print the number.

Example:
// JAVA program to find Armstrong
// numbers between two integers
import java.io.*;
import java.math.*;

class gfg {

// Function to print Armstrong


// Numbers between two integers
static void ArmstrongNum(int l, int h)
{
for (int j = l + 1; j < h; ++j) {

// Calculating number of digits


int y = j;
int N = 0;
while (y != 0) {
y /= 10;
++N;
}

// Calculating the sum of nth


// power of all the digits
int sum_power = 0;
y = j;
while (y != 0) {
int d = y % 10;
sum_power += Math.pow(d, N);
y /= 10;
}

// Checking if the current number


// i is equal to the sum of nth
// power of all the digits
if (sum_power == j)
System.out.print(j + " ");
}
}

// The Driver code


public static void main(String args[])
{
int n1 = 50;
int n2 = 500;
ArmstrongNum(n1, n2);
System.out.println();
}
}
Output
153 370 371 407

Similarly, we can find Armstrong numbers within any given range.


4. Java Program to Calculate Simple Interest

Simple interest is a quick method of calculating the interest charge on a loan. Simple interest is
determined by multiplying the daily interest rate by the principal by the number of days that
elapse between payments.

Simple interest formula is given by:

Simple Interest = (P x T x R)/100

Where,

• P is the principal amount


• T is the time and
• R is the rate

Examples: –

Example 1:

Input : P = 10000
R = 5
T = 5
Output : 2500

Explanation - We need to find simple interest on


Rs. 10, 000 at the rate of 5% for 5
units of time.

Example 2:

Input : P = 3000
R = 7
T = 1
Output : 210

Example 1:

// Java program to compute


// simple interest for given principal
// amount, time and rate of interest.
import java.io.*;

class GFG {
public static void main(String args[])
{
// We can change values here for
// different inputs
float P = 1, R = 1, T = 1;

/* Calculate simple interest */


float SI = (P * T * R) / 100;
System.out.println("Simple interest = " + SI);
}
}

// This code is contributed by Anant Agarwal.

Output
Simple interest = 0.01

Example 2:

// Java program to compute


// simple interest for given principal
// amount, time and rate of interest.
import java.io.*;
class GFG {
public static void main(String args[])
{
// We can change values here for
// different inputs
float P = 10000, R = 5, T = 5;

// Calculate simple interest


float SI = (P * T * R) / 100;
System.out.println("Simple interest = " + SI);
}
}
Output
Simple interest = 2500.0

5. Write a Java Program on Encapsulation

Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together code and the data it manipulates. Another way to think about encapsulation is, that
it is a protective shield that prevents the data from being accessed by the code outside this
shield.

• Technically in encapsulation, the variables or data of a class is hidden from any other class and
can be accessed only through any member function of its own class in which it is declared.
• As in encapsulation, the data in a class is hidden from other classes using the data hiding
concept which is achieved by making the members or methods of a class private, and the class is
exposed to the end-user or the world without providing any details behind implementation
using the abstraction concept, so it is also known as a combination of data-hiding and
abstraction.
• Encapsulation can be achieved by Declaring all the variables in the class as private and writing
public methods in the class to set and get the values of variables.

• It is more defined with the setter and getter method.


Advantages of Encapsulation
• Data Hiding: it is a way of restricting the access of our data members by hiding the
implementation details. Encapsulation also provides a way for data hiding. The user will have no
idea about the inner implementation of the class. It will not be visible to the user how the class
is storing values in the variables. The user will only know that we are passing the values to a
setter method and variables are getting initialized with that value.
• Increased Flexibility: We can make the variables of the class read-only or write-only depending
on our requirements. If we wish to make the variables read-only then we have to omit the setter
methods like setName(), setAge(), etc. from the above program or if we wish to make the
variables write-only then we have to omit the get methods like getName(), getAge(), etc. from
the above program
• Reusability: Encapsulation also improves the re-usability and is easy to change with new
requirements.
• Testing code is easy: Encapsulated code is easy to test for unit testing.
• Freedom to programmer in implementing the details of the system: This is one of the major
advantage of encapsulation that it gives the programmer freedom in implementing the details of
a system. The only constraint on the programmer is to maintain the abstract interface that
outsiders see.
Disadvantages of Encapsulation in Java
• Can lead to increased complexity, especially if not used properly.
• Can make it more difficult to understand how the system works.
• May limit the flexibility of the implementation.

Java Encapsulation Example 1:


Below is the implementation of the above topic:
// Java Program to demonstrate
// Java Encapsulation
// fields to calculate area
class Area {
int length;
int breadth;
// constructor to initialize values
Area(int length, int breadth)
{
this.length = length;
this.breadth = breadth;
}
// method to calculate area
public void getArea()
{
int area = length * breadth;
System.out.println("Area: " + area);
}
}
class Main {
public static void main(String[] args)
{
Area rectangle = new Area(2, 16);
rectangle.getArea();
}
}

Output
Area: 32

Java Encapsulation Example 2:

// Java Encapsulation
// Person Class
class Person {
// Encapsulating the name and age
// only approachable and used using
// methods defined
private String name;
private int age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}

// Driver Class
public class Main {
// main function
public static void main(String[] args)
{
// person object created
Person person = new Person();
person.setName("John");
person.setAge(30);

// Using methods to get the values from the


// variables
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
Output
Name: John
Age: 30
6. Method Overloading in Java

In Java, Method Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters or type of input
parameters, or a mixture of both.

Method overloading in Java is also known as Compile-time Polymorphism, Static


Polymorphism, or Early binding. In Method overloading compared to the parent argument, the
child argument will get the highest priority.

Example of Method Overloading


// Java program to demonstrate working of method
// overloading in Java

public class Sum {


// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output
30
60
31.0
Different Ways of Method Overloading in Java

• Changing the Number of Parameters.


• Changing Data Types of the Arguments.
• Changing the Order of the Parameters of Methods

1. Changing the Number of Parameters

Method overloading can be achieved by changing the number of parameters while passing to
different methods.

Below is the implementation of the above method:

// Java Program to Illustrate Method Overloading


// By Changing the Number of Parameters

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Product {
// Method 1
// Multiplying two integer values
public int multiply(int a, int b)
{
int prod = a * b;
return prod;
}

// Method 2
// Multiplying three integer values
public int multiply(int a, int b, int c)
{
int prod = a * b * c;
return prod;
}
}

// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of above class inside main()
// method
Product ob = new Product();
// Calling method to Multiply 2 numbers
int prod1 = ob.multiply(1, 2);

// Printing Product of 2 numbers


System.out.println(
"Product of the two integer value :" + prod1);

// Calling method to multiply 3 numbers


int prod2 = ob.multiply(1, 2, 3);

// Printing product of 3 numbers


System.out.println(
"Product of the three integer value :" + prod2);
}
}
Output
Product of the two integer value :2
Product of the three integer value :6

2. Changing Data Types of the Arguments


In many cases, methods can be considered Overloaded if they have the same name but have
different parameter types, methods are considered to be overloaded.

Below is the implementation of the above method:


// Java Program to Illustrate Method Overloading
// By Changing Data Types of the Parameters

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Product {
// Multiplying three integer values
public int Prod(int a, int b, int c)
{
int prod1 = a * b * c;
return prod1;
}

// Multiplying three double values.


public double Prod(double a, double b, double c)
{
double prod2 = a * b * c;
return prod2;
}
}
class GFG {
public static void main(String[] args)
{
Product obj = new Product();

int prod1 = obj.Prod(1, 2, 3);


System.out.println(
"Product of the three integer value :" + prod1);

double prod2 = obj.Prod(1.0, 2.0, 3.0);


System.out.println(
"Product of the three double value :" + prod2);
}
}
Output
Product of the three integer value :6
Product of the three double value :6.0

3. Changing the Order of the Parameters of Methods

Method overloading can also be implemented by rearranging the parameters of two or more
overloaded methods. For example, if the parameters of method 1 are (String name, int roll_no) and
the other method is (int roll_no, String name) but both have the same name, then these 2 methods
are considered to be overloaded with different sequences of parameters.

Below is the implementation of the above method:

// Java Program to Illustrate Method Overloading


// By changing the Order of the Parameters

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Student {
// Method 1
public void StudentId(String name, int roll_no)
{
System.out.println("Name :" + name + " "
+ "Roll-No :" + roll_no);
}

// Method 2
public void StudentId(int roll_no, String name)
{
// Again printing name and id of person
System.out.println("Roll-No :" + roll_no + " "
+ "Name :" + name);
}
}

// Class 2
// Main class
class GFG {
// Main function
public static void main(String[] args)
{
// Creating object of above class
Student obj = new Student();

// Passing name and id


// Note: Reversing order
obj.StudentId("Spyd3r", 1);
obj.StudentId(2, "Kamlesh");
}
}
Output
Name :Spyd3r Roll-No :1
Roll-No :2 Name :Kamlesh
What if the exact prototype does not match with arguments?

Priority-wise, the compiler takes these steps:

• Type Conversion but to a higher type(in terms of range) in the same family.
• Type conversion to the next higher family(suppose if there is no long data type available for an
int data type, then it will search for the float data type).
Let’s take an example to clarify the concept:

// Demo Class

class Demo {

public void show(int x)

System.out.println("In int" + x);

public void show(String s)

System.out.println("In String" + s);

public void show(byte b)

System.out.println("In byte" + b);

class UseDemo {

public static void main(String[] args)

byte a = 25;

Demo obj = new Demo();

// it will go to

// byte argument

obj.show(a);

// String

obj.show("hello");

// Int
obj.show(250);

// Since char is

// not available, so the datatype

// higher than char in terms of

// range is int.

obj.show('A');

// String

obj.show("A");

// since float datatype

// is not available and so it's higher

// datatype, so at this step their

// will be an error.

obj.show(7.5);

Output

./UseDemo.java:46: error: no suitable method found for show(double)


obj.show(7.5);
^
method Demo.show(int) is not applicable
(argument mismatch; possible lossy conversion from double to int)
method Demo.show(String) is not applicable
(argument mismatch; double cannot be converted to String)
method Demo.show(byte) is not applicable
(argument mismatch; possible lossy conversion from double to byte)
1 error
Advantages of Method Overloading

• Method overloading improves the Readability and reusability of the program.


• Method overloading reduces the complexity of the program.
• Using method overloading, programmers can perform a task efficiently and effectively.
• Using method overloading, it is possible to access methods performing related functions with
slightly different arguments and types.
• Objects of a class can also be initialized in different ways using the constructors.

You might also like