0% found this document useful (0 votes)
111 views

Msbte JPR All Program Chapter-2

The document contains 16 questions related to Java programming. Each question provides a code snippet to demonstrate a concept such as: - Constructing objects using constructors - Calculating area of a rectangle - Finding factorial of a number - Counting characters in a string - Reversing a string - Concatenating strings - Sorting strings - Using StringBuffer methods like replace, delete, length - Creating and manipulating vectors

Uploaded by

zayankhan368369
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)
111 views

Msbte JPR All Program Chapter-2

The document contains 16 questions related to Java programming. Each question provides a code snippet to demonstrate a concept such as: - Constructing objects using constructors - Calculating area of a rectangle - Finding factorial of a number - Counting characters in a string - Reversing a string - Concatenating strings - Sorting strings - Using StringBuffer methods like replace, delete, length - Creating and manipulating vectors

Uploaded by

zayankhan368369
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
You are on page 1/ 28

Q.

1] Calculate area of rectangle by using constructor method to initialize an


object at the time of its creation.

class Rectangle

int length, width;

// Define constructor Rectangle (int a, int b)

length = a;

width = b;

int RectArea ()

{
return(length * width);
}

// class with main ()

class Rectangle Area

public static void main(String args[])

// calling constructor Rectangle R1 = new Rectangle (15, 11);


int areal = R1.RectArea ();

System.out.println("Areal = " + areal);

}
{
Q.2] Following programe demonstrates the parameterized constructor.

public class Cubel

int length; int breadth; int height; public int getVolume()

{ return (length * breadth * height );


}
Cubel()
{
length = 10;
breadth = 10;
height = 10;

}
Cubel (int l, int b, int h)

length = 1;
breadth = b;
height = h;

public static void main(String[] args)

{
Cubel cubeObj1, cubeObj2;
cubeObj1 = new Cubel();
cubeObj2 = new Cubel(10, 20, 30);
System.out.println("Volume of Cubel is:" +cubeObjl.getVolume());
System.out.println("Volume of Cube2 is:" +cubeObj2.getVolume());
}
}
Q.3] Write a program to Find Factorial of Given number using command line
arguments

/*Write a program to Find Factorial of Given no. */

class Factorial

public static void main(String args[])

int num = Integer.parseInt(args[0]);//take

argument as command line

int result = 1;

while(num>0)

result = result * num;

num--;

System.out.println("Factorial of Given no. is :" +result);

}
Q.4] Write a program to count number of numeric character in a string.

import java.io.*;

class Program2

public static void main(String args[])


has

{
Try
{
BufferedReader din=new BufferedReader (new
InputStreamReader(System.in));
System.out.print(" Enter the String with Numeric Number :- ");
String s-din.readLine();

int counter-0;
int l=s.length();
char ch;

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

ch-s.charAt(i); if(ch>='0'&&ch<='9')

counter++;
}
}
System.out.print(" The number of digits in String is :- "+counter);
}
catch(Exception e)
{
}
}
}
Q.5] Write a program to count number of vowels character in a string.

import java.io.*;
class Program2
{
public static void main(String args[])
{
Try
{

BufferedReader din=new BufferedReader (new


InputStreamReader(System.in)); System.out.print("Enter the String :- "); String
s=din.readLine();

int vcnt=0;
int l=s.length();
char ch;

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

ch=s.charAt(i);

if (ch'a' || ch='A' ||
ch'e' || ch='E' ||
ch'i' || ch=T ||
ch= 'o' || ch='0' ||
ch= 'u' || ch=U')
vcnt++;
{
}
}
System.out.print(" The number of vowels in String is :- "+vcnt);
}
catch(Exception e) {}
}
}
Q.6] Write a program to count number of occurrences of character 'a' in given
string.

import java.io.*;
class Program2
{
public static void main(String args[])
{
String s;
s="Java";

int i,l,f=0,ctr=0;

I=s.length();
for(i=0;i<l;i++)

{
if(s.charAt(i)='a')

{
f-1;
ctr++;
}
}

if(f=1)

System.out.println(" The number of A is :- "+ctr);

}
else
{
System.out.println(" No A Found ");

}
Q.7] Write a program to string in reverse order (Java - Output avaJ).

import java.io.*;

class Program4

public static void main(String args[])

String s;

s="COMPUTER";

int i,l;

I=s.length();

System.out.println(" The String IS

COMPUTER");

System.out.print(" The Reverse String is :-");

for(i=1-1;i>=0;i-)

System.out.print(s.charAt(i));

}
Q.8] Write a program to accept first name, middle name and sumame in three
different strings and then concatenate the three strings to make full name.

import java.io.*;

class Programs

public static void main(String args[])

String s,s1,s2,s3;

sl=args[0];

s2-args[1];

s3=args[2]:

s-s1.concat(s2);

s-s.concat(s3);

System.out.println("First Name :-"+s1);

System.out.println("Middle Name :-"+s2);

System.out.println("Surname :-"+s3);

System.out.println("Full Name :-"+s!);

}
}
Q.9] Write a program in Java to read 10 strings from console and then print the
sorted strings on console(Use String Class).

import java.io.*;
import java.lang.*;
public class sort
{
public static void main(String args[])
{
String str[] = new String[10]:
//create array of object of class string
int i,j;
try
{
InputStream Reader in= new InputStreamReader(System.in);
BufferedReader br = new
BufferedReader(in);
System.out.println("Enter the strings to be sort::");
for(i=0;i<10;i++)
str[i] = br.readline();
}
System.out.println("Sorted strings are::."); for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
if(str[j].compareTo(str[i] < (0)
{
String temp = str[i];
Str[i] = str[j];
Str[j] = temp;
}
}
System.out.println(str[i]);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Q.10]Write a program to Java StringBuffer Replace method.

/* Java StringBuffer Replace Example This example shows how contents of java
StringBuffer can be replaced using replace method of Java StringBuffer class. */

public class StringBufferReplace

public static void main(String[] args)

//Create the StringBuffer object


StringBuffer sb = new StringBuffer("Hello World");
System.out.println("Original Text: " + sb);
/*

To replace the contents of Java StringBuffer use StringBuffer replace(int start,


int end, String str) method. It replaces the content from StringBuffer string
from start index to end - I index by the content of the String str.

*/

sb.replace(0,5,"Hi");

System.out.println("Replaced Text: " + sb);

}
Q.11] Write a program to delete remove character or clear using StringBuffer
class.

public class StringBufferDelete {

public static void main(String[] args)


/*
Java StringBuffer class following methods to delete / remove characters or
claring the contents of a StringBuffer object. StringBuffer delete(int start, int
end) remove the characters from start index to an end-1 index provided.
This method can throw a StringIndexOutOfBoundException if the start index is
invalid.

*/

StringBuffer sb1 = new StringBuffer("Hello World"); sb1.delete(0,6);


System.out.println(sb1);

/*

To clear contents of a StringBuffer use delete(int start, int end) method in the
below given way

*/

StringBuffer sb2 = new StringBuffer("Some Content"); System.out.println(sb2);


sb2.delete(0, sb2.length()); System.out.println(sb2);

/*
StringBuffer deleteCharAt(int index) deletes the character at specified index.
This method throws StringIndexOutOfBound
Exception if index is negative or greater than or equal to the length.
*/

StringBuffer sb3 = new StringBuffer("HelloWorld");


sb3.deleteCharAt(0);
System.out.println(sb3);
}
}
Q.12] Write a program to demonstrate StringBuffer Replace method.

public class StringBufferExample {

public static void main(String[] args)


{

/*
1. StringBuffer StringBuffer() Construct empty StringBuffer with initial capacity
of 16
*/

StringBuffer sbObj 1 = new StringBuffer();

/*
2. StringBuffer StringBuffer(int length) Constructs empty StringBuffer with
initial capacity of length
*/

StringBuffer sbObj2 = new StringBuffer(10);

/*
3. StringBuffer StringBuffer(String str) constructs StringBuffer with the contents
same as argument String
*/

StringBuffer sbObj3 = new StringBuffer("Hello World");


System.out.println(sbObj3);
}

}
Q.13] Write a program to demonstrate Java StringBuffer length.

public class StringBufferLengthEx

public static void main(String[] args)

/*
int length() method of Java StringBuffer class returns the length of a
StringBuffer object.
*/

StringBuffer sb = new StringBuffer("Hello World");


int len = sb.length();

System.out.println("Length of a StringBuffer object is:” + len);

}
Q.14] Demonstrate the use of Vector - creation of Vector, insertion of object
into Vector and how to store Vector elements in an enumerated data type.

import java.util.*;
class Languagevector
{
{
public static void main(String args[])
Vector list-new Vector();
int length args.length;
seven
elemem
position
import
import
class V
P
{
for(int i=0;i<length;i++)
{
list.addElement(args[i]);
}
list.insertElementAt("COBOL",2);

int size-list.size();

String listarray[] = new String[size];


list.copyInto(listarray);
System.out.println(" List of Languages");
System.out.println(listarray[i]);
for(int i=0;i<size;i++)
{
}
}
}
Q.15] Write a program to create a vector with seven elements as (10, 30, 50,
20, 40, 10, 20). Remove element 3rd and 4th position. Insert new element at 3
position. Display the original and current size of the vector.

import java.util. Vector,

import java.util.Enumeration;

class Vectordemo
{
public static void main(String args[])
{
Vector v-new Vector();
v.addElement(new Integer(10));
v.addElement(new Integer(30));
v.addElement(new Integer(50));
v.addElement(new Integer(20));
v.addElement(new Integer(40));
v.addElement(new Integer(10));
v.addElement(new Integer(20));
System.out.println(" Initial vector size :- " +v.size());
v.removeElementAt(3);
v.removeElementAt(4);

System.out.println(" Final vector size :-"

+v.size());

}
}
Q.16] Write a program to accept as many integers as user wants in a vector.
Delete specific element and display remaining list.

import java.util. Vector;


import java.util. Enumeration;
import java.io.*;
class Vectordemo
{
public static void main(String args[]) throws IOException
{
Vector v-new Vector();
BufferedReader br = new BufferedReader(newInputStreamReader(System.in));
System.out.println("Enter no of integer elements want to enter: ");
int n = Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{
System.out.println("Enter Integer : ");
int no = Integer.parseInt(br.readLine());
v.addElement(new Integer(no));
}
System.out.println(" "+v.size()); Initial vector size :-
System.out.println("Vector contents before remove element...");

//display elements of Vector

for(int index=0; index <v.size(); index++)


System.out.println(v.get(index));
System.out.println("Enter index of element to be deleted: ");
int index1 = Integer.parseInt(br.readLine()); v.removeElementAt(index1);
System.out.println(" Final vector size :- "+v.size());
System.out.println("Vector contents after remove element...");
for(int index=0; index < v.size(); index++)
}
}
System.out.println(v.get(index));
Q.17] Write a program to insert element at specified index.

import java.util.Vector, public class AddEle Vector


public static void main(String[] args)

//create an Vector object

Vector v = new Vector();

//Add elements to Vector

v.add("10");
v.add("20");
v.add("30");
v.add(1,"First INSERTED ELEMENT");
v.add(2,"Fisrt INSERTED ELEMENT");

/* add method DOES NOT overwrites the element previously at the specified
index in the Vector. It shifts the elements to right side and increasing the
Vector size by 1. */

System.out.println("Vector contains...");

//display elements of Vector

for(int index=0; index <v.size(); index++) System.out.println(v.get(index));


}
}
Q.18] Write a program to convert Binary to decimal using Integer Wrapper
class.

public class Convert BinaryToDecimalNumber {

public static void main(String[] args)

//declare string containing binary number String strBinary Number = "111000";

int decimalNumber = Integer.parseInt

(strBinary Number,2);

System.out.println("Binary number converted to decimal number");

System.out.println("Decimal number is: " + decimalNumber);


}

}
Q.19] Write a program to accept number from user and convert it into binary
by using wrapper class method.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.*;
import java.io.IOException;
public class ConvertIntToBinary }
public static void main(String[] args) throws Exception

{
BufferedReader br-new BufferedReader (new InputStreamReader(System.in));

String str;
int i;
try

str-br.readLine();
i-Integer.parseInt(str);
String strBinary Number =Integer.toBinaryString(i);
System.out.println(i+strBinary Number);

}
catch(IOException ie)
{

}
}
}
Q.20] Write a program to convert Integer To Hexadecimal Number using
Integer Wrapper class.

public class ConvertintToHex

public static void main(String[] args)

int i = 32;
String strHexNumber = Integer.toHexString(i);
System.out.println ("Convert decimal number To hexadecimal number
example");
System.out.println("Hexadecimal value of " +i+" is "+ strHexNumber);

}
}

Q.21] Write a program to convert Integer To Java String Object using Integer
Wrapper class.

public class Integer ToString


{
public static void main(String[] args)
{
Integer intObj = new Integer(10);
/*use toString method of Integer class to convert Integer into String.*\

String str = intObj.toString();


System.out.println("Integer converted to String as." + str);

}
}
Q.22] Write a program to convert Java Int To Integer Object using Integer
Wrapper class.
public class IntToInteger
{
public static void main(String[] args)
{
int i = 10;
/*Use Integer constructor to convert int primitive type to Integer object.*\

Integer intObj = new Integer(i);


System.out.println(intObj);
}

Q.23] Write a program to convert Java String To Integer Object using Integer
Wrapper class.
public class StringToInteger
{
public static void main(String[] args)
{
/*We can convert String to Integer using following ways.
1. Construct Integer using constructor.*/

Integer intObj 1 = new Integer("100"); System.out.println("String to integer


conversion: "+intObj1);

/*2. Use valueOf method of Integer class. This method is static.*/

String str = "100";


Integer intObj2 = Integer.valueOf(str);
System.out.println("String to integer conversion: "+intObj2);

/*both method can throw a NumberFormatException if string can not be


parsed. */
}
}
Q.24] Write a program to convert Java Integer Object To Numeric Primitive
Types using Integer Wrapper class.
public class Integer ToNumeric PrimitiveTypes

public static void main(String[] args) (

Integer intObj = new Integer("10");

/use byte Value method of Integer class to convert it into byte type,/ byte b =
intObj.byteValue(); System.out.println("Convert Integer (10) to byte: "+b);

/*use shortValue method of Integer class to

convert it into short type*/ short s = intObj.shortValue();


System.out.println("Convert Integer(10) to short: "+s);

/*use intValue method of Integer class to

convert it into int type.*/

int i = intObj.intValue(); System.out.println("Convert Integer (10) to int : "+i);

/*use floatValue method of Integer class to


convert it into float type*/
float fintObj.floatValue();
System.out.println("Convert Integer (10) to float : "+f);

/*use doubleValue method of Integer class to convert it into double type.*/

double d = intObj.doubleValue();
System.out.println("Convert Integer (10) to double: "+d);

}
Q.25] Write a program to convert Octal Number To Decimal Number using
Integer Wrapper class.

public class OctalToDecimalNumber


{
public static void main(String[] args)
{
//declare string containing octal number
String strOctalNumber = "32";
/*
To convert octal number to decimal number use, int parselnt method of
Integer wrapper class. Pass 8 as redix second argument.
*/

int decimalNumber = Integer.parseInt (strOctalNumber,8);


System.out.println("Octal number converted to decimal number");

System.out.println("Decimal number is: " + decimalNumber);

}
Q.26] Write a program to convert String To Java Int using Integer Wrapper
class.

import java.lang.*;

public class String Tolnt

public static void main(String[] args)

//declare String object

String str = new String("100");

/* use parseInt method of Integer class to convert String into int primitive data
type. This is a static method. Please note that this method can throw a
NumberFormatException if the string is not parsable to int.*/

int i = Integer.parseInt(str);
System.out.println("Conversion of String to Int : "+i);

}
}
Q.27] This program accepts principal, rate of interest and number of years
from user and calculate simple interest.

import java.lang.*; //import language package


import java.io.*; // import DataInputStream class to accept data

class wrapperdemo
}
float princpl:
float rate;
int no;
float interest;
wrapperdemo() //constructor to accept data
{
BufferReader in = new BufferReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter principal amount::");
princpl Float.parseFloat(in.readLine());
System.out.println("Enter rate of interest::");
interest = Float.parseFloat(in.readLine());
System.out.println("Enter no of years:.");
no = integer.parseInt(in.readLine());
}
catch(Exception e)
{
}
}
void display_interest()
{
interest = (princpl * rate * no)/100;
String s = Float.toString(interest);
System.out.println("The Simple Interest is::" +s);
}
public static void main(String args[])
{
wrapperdemo a = new wrapperdemo(); //instantiate wrapperdemo class or
create object a.display_interest();
}
}
Q.28] Accept three numbers from user and display greatest number by using
wrapper class methods.

import java.io.*;
class Programl

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

BufferedReader din=new BufferedReader (new


InputStreamReader(System.in));
System.out.print(" Enter the first number :-");
int i=Integer.parseInt(din.readLine());
System.out.print(" Enter the second number :- ");
int j=Integer.parseInt(din.readLine());
System.out.print(" Enter the third number :- ");
int k=Integer.parseInt(din.readLine()); if(i>j&&i>k)
{
System.out.print(" The Greatest number is: "+i);
}
else
{
if(j>i&&j>k)
{
System.out.println(" The Greatest number is: "+j);
else
{ if(k>i&&k>j)
{ System.out.println(" The Greatest number is :- "+k);
}
}
}
}
catch(Exception e)
{
}
}
}
Q.29] Accept string from user and count number digits by using wrapper class
methods.

import java.io.*;
class Program2

{
public static void main(String args[])
{
try
{
BufferedReader din=new BufferedReader (newInputStreamReader(System.in));
System.out.print(" Enter the String with Numeric Number :- ");
String s=din.readLine();
int counter-0;
int l=s.length();
char ch;
for(int i=0;i<l;i++)
{
ch-s.charAt(i);
if(ch>='0'&&ch<='9')
{
}
counter++;
}
System.out.print(" The number of digits in String is :- "+counter);

}
catch(Exception e)

{
}
}
}
Q.30] Accept numbers from user and convert it into binary by using wrapper
class methods.

import java.io.*;
class Program3
{
public static void main(String args[])

{
try
{

BufferedReader din-new BufferedReader (new InputStreamReader(System.in));


System.out.print(" Enter the number :- ");

int i=Integer.parseInt(din.readLine());
int j=0;
System.out.print(" Its Binary Conversion:-");
while(i>1)
{
j=i%2;
i=i/2;

System.out.print(j);
}
System.out.println(i);

}
catch(Exception e)
{
}
}
}

You might also like