JAVA ASSIGNMENT 1
1. implementation of counter(here counting the number of objects) using
static keyword
If you declare any variable as static, it is known as a static variable.
note:
The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
The static variable gets memory only once in the class area at the time of
class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
class VariableDemo
static int count=0;
public void increment()
count++;
public static void main(String args[])
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
now,without static keyword........
class CounterClass{
int count=0;//will get memory when instance is created
CounterClass(){
count++;
System.out.println(count);
public static void main(String args[]){
CounterClass c1=new CounterClass();
CounterClass c2=new CounterClass();
CounterClass c3=new CounterClass();
}
}
/* the difference is given below:
problem with instance variable:
instance variable gets the memory at the time of object creation,
each object will have the copy of the instance variable, if it is
incremented, it won't reflect to other objects. So each objects will
have the value 1 in the count variable.
*/
2. a. java program to display first 100 prime no.s
class PrimeNumberDemo
public static void main(String args[])
int n;
int status = 1;
int num = 3;
System.out.println("First 100 prime numbers are:");
System.out.println(2);
for ( int i = 2 ; i <=100 ; )
for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
if ( num%j == 0 )
status = 0;
break;
if ( status != 0 )
System.out.println(num);
i++;
status = 1;
num++;
b. prime no.s from 1 to 100
public class primeNumbersFoundber {
public static void main(String[] args) {
int i;
int num = 0;
int maxCheck = 100; // maxCheck limit till which you want to find prime
numbers
boolean isPrime = true;
//Empty String
String primeNumbersFound = "";
//Start loop 1 to maxCheck
for (i = 1; i <= maxCheck; i++) {
isPrime = CheckPrime(i);
if (isPrime) {
primeNumbersFound = primeNumbersFound + i + " ";
System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
// Print prime numbers from 1 to maxCheck
System.out.println(primeNumbersFound);
public static boolean CheckPrime(int numberToCheck) {
int remainder;
for (int i = 2; i <= numberToCheck / 2; i++) {
remainder = numberToCheck % i;
//if remainder is 0 than numberToCheckber is not prime and break
loop. Elese continue loop
if (remainder == 0) {
return false;
return true;
c. to break integer into digits
import java.util.Scanner;
public class JavaExample
{
public static void main(String args[])
int num, temp, digit, count = 0;
//getting the number from user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter any number:");
num = scanner.nextInt();
scanner.close();
//making a copy of the input number
temp = num;
//counting digits in the input number
while(num > 0)
num = num / 10;
count++;
while(temp > 0)
{
digit = temp % 10;
System.out.println("Digit at place "+count+" is: "+digit);
temp = temp / 10;
count--;
d. to check prime number
public class PrimeExample{
public static void main(String args[]){
int i,m=0,flag=0;
int n=3;//it is the number to be checked
m=n/2;
if(n==0||n==1){
System.out.println(n+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;
break;
}
if(flag==0) { System.out.println(n+" is prime number"); }
}//end of else
e. to check perfect square
import java.util.Scanner;
class JavaExample {
static boolean checkPerfectSquare(double x)
// finding the square root of given number
double sq = Math.sqrt(x);
/* Math.floor() returns closest integer value, for
* example Math.floor of 984.1 is 984, so if the value
* of sq is non integer than the below expression would
* be non-zero.
*/
return ((sq - Math.floor(sq)) == 0);
public static void main(String[] args)
System.out.print("Enter any number:");
Scanner scanner = new Scanner(System.in);
double num = scanner.nextDouble();
scanner.close();
if (checkPerfectSquare(num))
System.out.print(num+ " is a perfect square number");
else
System.out.print(num+ " is not a perfect square number");
f. to find square root of a number without sqrt()
import java.util.Scanner;
class JavaExample {
public static double squareRoot(int number) {
double temp;
double sr = number / 2;
do {
temp = sr;
sr = (temp + (number / temp)) / 2;
} while ((temp - sr) != 0);
return sr;
public static void main(String[] args)
System.out.print("Enter any number:");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
scanner.close();
System.out.println("Square root of "+ num+ " is: "+squareRoot(num));
}
g. to print armstrong numbers between a given range
import java.util.Scanner;
public class GenerateArmstrongNumber
public static void main(String args[])
int n, n1, n2, i, rem, temp, count=0;
Scanner scan = new Scanner(System.in);
/* enter the interval between which number is printed */
System.out.print("Enter the Interval :\n");
System.out.print("Enter Starting Number : ");
n1 = scan.nextInt();
System.out.print("Enter Ending Number : ");
n2 = scan.nextInt();
// read numbers one-by-one and generate armstrong.
for(i=n1+1; i<n2; i++)
temp = i;
n = 0;
while(temp != 0)
rem = temp%10;
n = n + rem*rem*rem;
temp = temp/10;
if(i == n)
// print all the armstrong number between given interval.
if(count == 0)
System.out.print("Armstrong Numbers Between the Given
Interval are : \n");
System.out.print(i + " ");
count++;
}
// print if no number found.
if(count == 0)
System.out.print("Armstrong Number not Found between the Given
Interval.");
h. java program to find sum of natural numbers
public class Natural
public static void main(String args[])
int x, i = 1 ;
int sum = 0;
System.out.println("Enter Number of items :");
Scanner s = new Scanner(System.in);
x = s.nextInt();
while(i <= x)
{
sum = sum +i;
i++;
System.out.println("Sum of "+x+" numbers is :"+sum);
i. to check whether a number is positive or negative or 0
import java.util.*;
class PosNegZero
public static void main(String []s)
int num;
//Scanner class to read value
Scanner sc=new Scanner(System.in);
System.out.print("Enter any integer number: ");
num=sc.nextInt();
//check condition for +ve, -ve and Zero
if(num>0)
System.out.println(num + " is POSITIVE NUMBER.");
else if(num<0)
System.out.println(num + " is NEGATIVE NUMBER.");
else
System.out.println("IT's ZERO.");
j. to generate random numbers
import java.util.*;
class RandomNumbers {
public static void main(String[] args) {
int c;
Random t = new Random();
// random integers in [0, 100]
for (c = 1; c <= 10; c++) {
System.out.println(t.nextInt(100));
}
}
k. to check armstrong number
class ArmstrongExample{
public static void main(String[] args) {
int c=0,a,temp;
int n=153;//It is the number to check armstrong
temp=n;
while(n>0)
a=n%10;
n=n/10;
c=c+(a*a*a);
if(temp==c)
System.out.println("armstrong number");
else
System.out.println("Not armstrong number");
l. to find GCD of two no.s
public class GCD {
public static void main(String[] args) {
int n1 = 81, n2 = 153, gcd = 1;
for(int i = 1; i <= n1 && i <= n2; ++i)
// Checks if i is factor of both integers
if(n1 % i==0 && n2 % i==0)
gcd = i;
System.out.printf("G.C.D of %d and %d is %d", n1, n2, gcd);
m. to find largest of three numbers
import java.util.Scanner;
class Largest
public static void main(String args[])
{
int x, y, z;
System.out.println("Enter three integers");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
if (x > y && x > z)
System.out.println("First number is largest.");
else if (y > x && y > z)
System.out.println("Second number is largest.");
else if (z > x && z > y)
System.out.println("Third number is largest.");
else
System.out.println("The numbers are not distinct.");
n. java program to swap two numbers using bitwise operator
import java.util.Scanner;
public class Swap_BitwiseXOR
{
public static void main(String args[])
int m, n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number:");
m = s.nextInt();
System.out.print("Enter the second number:");
n = s.nextInt();
m = m ^ n;
n = m ^ n;
m = m ^ n;
System.out.println("After Swapping");
System.out.println("First number:"+m);
System.out.println("Second number:"+n);
o. to find smallest of three numbers using ternary operator
import java.util.Scanner;
public class JavaExample
public static void main(String[] args)
{
int num1, num2, num3, result, temp;
/* Scanner is used for getting user input.
* The nextInt() method of scanner reads the
* integer entered by user.
*/
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First Number:");
num1 = scanner.nextInt();
System.out.println("Enter Second Number:");
num2 = scanner.nextInt();
System.out.println("Enter Third Number:");
num3 = scanner.nextInt();
scanner.close();
/* In first step we are comparing only num1 and
* num2 and storing the smallest number into the
* temp variable and then comparing the temp and
* num3 to get final result.
*/
temp = num1 < num2 ? num1:num2;
result = num3 < temp ? num3:temp;
System.out.println("Smallest Number is:"+result);
p. to find largest of three numbers using ternary operator
import java.util.Scanner;
public class JavaExample
public static void main(String[] args)
int num1, num2, num3, result, temp;
/* Scanner is used for getting user input.
* The nextInt() method of scanner reads the
* integer entered by user.
*/
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First Number:");
num1 = scanner.nextInt();
System.out.println("Enter Second Number:");
num2 = scanner.nextInt();
System.out.println("Enter Third Number:");
num3 = scanner.nextInt();
scanner.close();
/* In first step we are comparing only num1 and
* num2 and storing the largest number into the
* temp variable and then comparing the temp and
* num3 to get final result.
*/
temp = num1>num2 ? num1:num2;
result = num3>temp ? num3:temp;
System.out.println("Largest Number is:"+result);
3. write a program to find the second largest and smallest elements in an
array
import java.util.Scanner;
public class SecondLargest_Smallest
public static void main(String[] args)
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array(Minimum
2):");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
a[i] = s.nextInt();
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (a[i] > a[j])
temp = a[i];
a[i] = a[j];
a[j] = temp;
System.out.println("Second Largest:"+a[n-2]);
System.out.println("Smallest:"+a[0]);
4. Write a java program to add, subtract and multiply two numbers using
object and class considering the following 4 cases
* declaring the attributes and method as private
*declaring the attributes and method as default
*declaring the attributes and method as protected
*declaring the attributes and method as public
private
class ABC
private int num = 100;
private int mult(int a,int b){
return a*b;
private int add(int a,int b)
return a+b;
private int subtract(int a,int b)
{
if(a>b)
return a-b;
else
return b-a;
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.mult(10,20));
System.out.println(obj.add(10,20));
System.out.println(obj.subtract(10,20));
default
package abcpackage;
class ABC {
/* Since we didn't mention any access modifier here, it would
* be considered as default.
*/
int add(int a, int b){
return a+b;}
int mult(int a,int b){
return a*b;
int subtract(int a,int b){
if(a>b)
return a-b;
else
return b-a;
class ABC1
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.mult(10,20));
System.out.println(obj.add(10,20));
System.out.println(obj.subtract(10,20));
protected
package abcpackage;
public class ABC {
protected int add(int a, int b){
return a+b;
protected int mult(int a,int b){
return a*b;
protected int subtract(int a,int b){
if(a>b)
return a-b;
else
return b-a;
package xyzpackage;
import abcpackage.*;
class Test extends ABC{
public static void main(String args[]){
Test obj = new Test();
System.out.println(obj.add(11, 22));
System.out.println(obj.mult(11, 22));
System.out.println(obj.subtract(11, 22));
}
}
public
package abcpackage;
public class ABC {
public int add(int a, int b){
return a+b;
public int mult(int a,int b){
return a*b;
public int subtract(int a,int b){
if(a>b)
return a-b;
else
return b-a;
package xyzpackage;
import abcpackage.*;
class Test{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.add(100, 1));
System.out.println(obj.mult(100, 1));
System.out.println(obj.subtract(100, 1));
5. WAP in java to calculate the volume of a cube using the following 3
cases:
*overloading the method having different number of inputs
*having different type of inputs
*signature same but return type different
NOTE: HERE THE QUESTION IS MEANT TO USE THE VOLUME FUNCTION
IMPLEMENTING METHOD OVERLOADING SO WE NEED TO USE THE
VOLUME METHOD MORE THAN ONCE DEPICTING THE GIVEN CASES. SO I
HAVE CHOSEN CUBOID,CYLINDER AND RECTANGLE VOLUME FOR
IMPLEMENTATION.
THE LAST CASE IS SPECIAL. RETURN TYPE IS NOT INVOLVED IN METHOD
OVERLOADING.
class Overload
int volume (int x) // volume of cube
return (x*x*x);
}
double volume(double r, int h) // volume of cylinder
return (3.14519F*r*r*h) ;
long volume(long l, int b, int h) // volume of rectangle
return (l*b*h);
class OverloadDemo2
public static void main(String args[ ])
Overload v=new Overload();
System.out.println("Volume of a cube = "+v.volume(10));
System.out.println("Volume of a cylinder = "+v.volume(2.5,8));
System.out.println("Volume of a Rectangle = "+v.volume(100L,75,15));
}
}
NOTE: IF WE USE METHOD OVERLOADING BY ONLY CHANGING THE
RETURN TYPE AND NOT THE SIGNATURE WE WOULD GET UNDESIRED
SITUATION.
6. a. to determine the last position of a substring inside a string
public class SearchlastString {
public static void main(String[] args) {
String strOrig = "Hello world ,Hello Reader";
int lastIndex = strOrig.lastIndexOf("Hello");
if(lastIndex == - 1){
System.out.println("Hello not found");
} else {
System.out.println("Last occurrence of Hello is at index "+ lastIndex);
b. using StringBuffer() to insert the string "Java" in the middle of another
string at a particular position
public class example{
public static void main(String args[])
String str = "Java";
StringBuffer sb = new StringBuffer("Hello World");
sb.insert(6,str);
System.out.println(sb);
7. a.Write a Java program that would prompt the user to select a
particular bank from a list of options. Based on the specified bank
selected display the rate of interest using abstract class.
import java.util.Scanner;
abstract class Bank{
abstract void Allahabad();
abstract void SBI();
abstract void BankOfBaroda();
abstract void PNB();
class Select extends Bank{
void Allahabad(){System.out.println("THE RATE OF INTEREST IS:7.25%");}
void SBI(){System.out.println("THE RATE OF INTEREST IS:8.61%");}
void BankOfBaroda(){System.out.println("THE RATE OF INTEREST
IS:7.15%");}
void PNB(){System.out.println("THE RATE OF INTEREST IS:6.85%");}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("enter 1 for allahabad 2 for sbi 3 for bank of baroda 4 for
pnb");
int choice=sc.nextInt();
Bank obj = new Select();
if(choice==1)
obj.Allahabad();
else if(choice==2)
obj.SBI();
else if(choice==3)
obj.BankOfBaroda();
else if(choice==4)
obj.PNB();
else
System.out.println("you have entered wrong choice");
b. use constructor chaining (using this and super keywords) to create a
hierarchy of objects in java
package sreeparna
public class School {
// Declare the instance variable.
String stName;
int stRoll;
int stId;
School(String schoolName){
this(73); // calls one parameter constructor with int within same class.
System.out.println("Student's Detail: ");
School(int s){
System.out.println("ST. STEPHEN'S SCHOOL");
School(String stName, int stRoll, int stId){ (Line 6)
this("SSS");// calls one parameter constrcutor with String parameter
within same class.
this.stName=stName;
this.stRoll=stRoll;
this.stId=stId;
void display(){
System.out.println("Name: " +stName);
System.out.println("Roll no. : " +stRoll);
System.out.println("Id: " +stId);
}
package sreeparna;
public class Student extends School{ // extends is used for developing
inheritance between two classes.
Student(){
super("Sreeparna" , 73 , 2345);// It will call superclass constructor with
three parameters.
Student(String schoolName){
this();
public static void main(String[] args) {
// Create the object of the class School and passes String value within
double quotes from const.
Student st=new Student("SSS"); // calls one parameter const. of same
class.
st.display();