Java 2
Java 2
import java.util.*;
class Pattern2{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int count=0;
System.out.println("enter any string pattern containing 0's and 1's");
String s=sc.next();
for(int i=0;i<s.length()-1;)
{
if(s.charAt(i)=='0')
{
int j=i+1;
while(j<s.length()&&s.charAt(j)!='0')
{
j++;
}
if(j<s.length()&&j!=i+1)
{
count++;
}
i=j;
}
else
{
i++;
}
}
System.out.println("occurence of pattern in string"+count);
}
}
Output: 3
//Q24.Write a java program to delete vowels using StringBuffer class.
import java.util.Scanner;
public class DelVowel {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter any string");
StringBuffer sb=new StringBuffer(sc.nextLine());
delVowel(sb);
}
public static void delVowel(StringBuffer sb){
for(int i=0;i<sb.length();i++)
{
char ch=sb.charAt(i);
if(isVowel(ch)){
sb.deleteCharAt(i);
i--;
}
}
System.out.println(sb);
System.out.println(sb.toString());//to show content as string.
}
public static boolean isVowel(char ch){
return "aeiouAEIOU".indexOf(ch)!=-1;
}
}
Output: grphcrhllNVRSTY
/*Q25.Class definition, creating objects and constructors:
Write a java program to create a class named 'Bank ' with the following data members:
• Name of depositor
• Address of depositor
• Account Number
• Balance in account
Class 'Bank' has a method for each of the following:
1. Generate a unique account number for each depositor.
2. For first depositor, account number will be 1001, for second depositor it will be 1002 and so
on
3. Display information and balance of depositor
4. Deposit more amount in balance of any depositor
5. Withdraw some amount from balance deposited.
6. Change address of depositor
2.After creating the class, do the following operations.
1. Enter the information (name, address, account number, balance) of the depositors. Number
of depositors is to be entered by the user.
2. Print the information of any depositor.
3. Add some amount to the account of any depositor and then display final information of that
depositor.
4. Remove some amount from the account of any depositor and then display final information
of that depositor.
5. Change the address of any depositor and then display the final information of that depositor.
6. Randomly repeat these processes for some other bank accounts.
*/
class Bank{
private String name,add;
private static int acc;
private float bal;
static{
acc=1001;
}
Bank(String s ,String ad,float b){
name=s;add=ad;bal=b;
}
public static void unique(){
acc++;
}
public void display(){
System.out.println(name+" "+add+" "+acc+" "+bal);
}
public void deposit(float d){
bal=bal+d;
System.out.println("Deposited successfully");
display();
}
public void withdraw(float w){
if(bal==0){
System.out.println("zero amount");
}
else if(w>bal){
System.out.println("not enough amount");
}
else{
bal=bal-w;
System.out.println("withdrew successfully ");
}
display();
}
public void changeAddress(String s){
add=s;
System.out.println("address changed successfully");
display();
}
}
public class BankDemo
{
public static void main(String[] args) {
Bank b=new Bank("Neha","Nagloi Chowk,Delhi",2000.50f);
b.display();
b.deposit(300.90f);
b.withdraw(400.00f);
b.changeAddress("Rohini,Delhi");
Bank.unique();
Bank b1=new Bank("Manish","Lodhi Colony,Dehli",4000.50f);
b1.display();
b1.deposit(200.90f);
b1.withdraw(700.00f);
b1.changeAddress("Patel Chowk,Dehli");
}
}
Output: Neha Nagloi Chowk, Delhi 1001 2000.5
Manish Lodhi Colony, Delhi 1002 4000.5
/*Q26.Define a class Word Example having the followingdescription:
Data members/instance variables:
private String strdata: to store a sentence.
Parameterized Constructor WordExample(String) : Accept a
sentence which may be terminated by either’.’, ‘? ’or’!’ only. The wordsmay be separated by
more than one blank space and are in UPPER CASE.
Member Methods:
void countWord(): Find the number of wordsbeginning and
ending with a vowel.
void placeWord(): Place the words which begin andend with a vowel at the
beginning, followed by the remaining words as they occur in the sentence
*/
import java.util.*;
public class StringExample{
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
String s;
while(true){
System.out.println("enter any string");
s=scn.nextLine();
String upper=s.toUpperCase();
if(!s.equals(upper)){
System.out.println("enter uppercase");
continue;
}
if(s.charAt(s.length()-1)=='.'||s.charAt(s.length()-1)=='?'||s.charAt(s.length()-1)=='!'){
break;
}
else
{
System.out.println("end with '?','.','!' ");
}
}
WordExample w=new WordExample(s);
w.countWord();
w.placeWord();
}
}
class WordExample{
private String strdata;
WordExample(String s){
strdata=s;
}
void countWord(){
int count=0;
String []newstr=SplitString(strdata);
for(int i=0;i<newstr.length;i++){
if(isVowel(newstr[i].charAt(0))&&isVowel(newstr[i].charAt(newstr[i].length()-1))){
count++;
}
}
System.out.println("count="+count);
}
void placeWord(){
String []newstr=SplitString(strdata);
String res="";
String vow="",nonvow="";
for(int i=0;i<newstr.length;i++){
if(isVowel(newstr[i].charAt(0))&&isVowel(newstr[i].charAt(newstr[i].length()-1))){
vow=vow+" "+newstr[i];
}
else{
nonvow=nonvow+" "+newstr[i];
}
}
res=vow+nonvow;
System.out.println(res.trim());
}
boolean isVowel(char ch){
return "AEIOU".indexOf(ch)!=-1;
}
String[] SplitString(String strdata){
String newstr[]=strdata.substring(0,strdata.length()-1).split("\\s+");
return newstr;
}
}
Output: 1
ERA GRA PHIC HILL UNIVERSITY
/*Q27.Method overloading (Compile time Polymorphism):
Write a Java program to create a class called ArrayDemo and overload arrayFunc() function.
void arrayFunc(int [], int) To find all pairs of elements in an Array whose sum is equal to a
given number :
Array numbers= [4, 6, 5, -10, 8, 5, 20], target=10
Output :
Pairs of elements whose sum is 10 are :4 + 6 = 10
5 + 5 = 10
-10 + 20 = 10
void arrayFunc(int A[], int p, int B[], int q) Given two sorted arrays A and B of size p and q,
Overload method arrayFunc() to merge elements of A with B by maintaining the sorted order
i.e. fill A with first p smallest elements and fill B with remaining elements.
Example:
Input :
2
int[] A = { 1, 5, 6, 7, 8, 10 }
int[] B = { 2, 4, 9 }
Output:
Sorted Arrays:
A: [1, 2, 4, 5, 6, 7]
B: [8, 9, 10]
(Use Compile time Polymorphism MethodOverloading)
*/
import java.util.*;
class arraydemo{
public void arrayfun(int []ar,int key){
for(int i=0;i<ar.length-1;i++){
for(int j=i+1;j<ar.length;j++){
if(ar[i]+ar[j]==key){
System.out.println(ar[i]+","+ar[j]);
}
}}}
public void arrayfun(int ara[],int p,int arb[],int q){
int n=ara.length;
int m=arb.length;
int r=n+m;
int newar[]=new int[r];
int i=0,j=0,k=0;
while(i<n&&j<m){
if(ara[i]<=arb[j]){
newar[k++]=ara[i++];
}
else{
newar[k++]=arb[j++];
}
}
while(i<n){
newar[k++]=ara[i++];
}
while(j<m){
newar[k++]=arb[j++];
}
for( i=0;i<p;i++){
ara[i]=newar[i];
System.out.print(ara[i]+" ");
}
System.out.println();
for(j=0;j<q;j++){
arb[j]=newar[i++];
System.out.print(arb[j]+" ");
}}}
public class Overload{
public static void main(String []arg){
Scanner sc=new Scanner(System.in);
int arr[]=new int[7];
int arr1[]=new int[6];
int arr2[]=new int[3];
System.out.println("INPUT1");
for(int i=0;i<7;i++){
arr[i]=sc.nextInt();
}
int key=sc.nextInt();
System.out.println("INPUT2");
for(int i=0;i<6;i++){
arr1[i]=sc.nextInt();
}
for(int i=0;i<3;i++){
arr2[i]=sc.nextInt();
}
int p=arr1.length;
int q=arr2.length;
arraydemo a=new arraydemo();
System.out.println("DISPLAY1");
a.arrayfun(arr,key);
System.out.println("DISPLAY2");
a.arrayfun(arr1,p,arr2,q); }
}
Output: 4,6
5,5
-10,20
1234567
8 9 10
/*Q28.Method overriding (Runtime Polymorphism), Abstract class and Abstract method,
Inheritance, interfaces:
Write a java program to calculate the area of a rectangle, a square and a circle.Create an abstract
class 'Shape' with three abstract methods namely rectangleArea() taking two parameters,
squareArea() and circleArea() takingone parameter each.Now create another class ‘Area’
containing all the three methods rectangleArea(), squareArea() and circleArea() for printing
the area of rectangle, square and circle respectively. Create an object of class Area and call all
the three methods.
(Use Runtime Polymorphism)
*/
import java.util.*;
abstract class Shape
{
abstract public void rectanglearea(int l,int b);
abstract public void squarearea(int a);
abstract public void circlearea(float r);
}
class Area extends Shape{
public void rectanglearea(int l,int b){
System.out.println("area of rectangle"+l*b);
}
public void squarearea(int a){
System.out.println("area of square"+a*a);
}
public void circlearea(float r){
System.out.println("area of circle"+Math.PI*r*r);
}
}
public class AbstractDemo{
public static void main(String []arg){
Scanner sc =new Scanner(System.in);
System.out.println("enter the length and width of rectangle");
int length=sc.nextInt();
int breadth=sc.nextInt();
System.out.println("enter the side of square ");
int s=sc.nextInt();
System.out.println("enter the radius of circle");
float r=sc.nextFloat();
Output:4368,2025,3782.76
/*Q29.Write a java program to implement abstract class and abstract method with
following details:
Create a abstract Base Class TemperatureData members:
double temp;
Method members:
void setTempData(double) abstact void changeTemp()
Sub Class Fahrenheit (subclass of Temperature) Data members:
double ctemp;
method member:
Override abstract method changeTemp() to convert Fahrenheit temperature into degree Celsius
by using formula C=5/9*(F-32) and display converted temperature
Sub Class Celsius (subclass of Temperature)
Data member:
double ftemp;
Method member:
Override abstract method changeTemp() to convert degree Celsius into Fahrenheit temperature
by using formula F=9/5*c+32 and display converted temperature
*/
import java.util.*;
abstract class TemperatureData{
double temp;
public void setTempData(double t){
temp=t;
}
abstract public void changeTemp();
}
class Fahrenheit extends TemperatureData{
double ctemp;
public void changeTemp(){
ctemp=(5/9.0)*(temp-32);
}
public void display(){
System.out.println("fahrenheit----->celsius"+ctemp);
}
}
class Celsius extends TemperatureData{
double ftemp;
public void changeTemp(){
ftemp=9/5.0*temp+32;
}
public void display(){
System.out.println("celsius------>fahrenheit"+ftemp);
}
}
public class TemperatureConversion{
public static void main(String []arg){
Scanner sc=new Scanner(System.in);
Fahrenheit f=new Fahrenheit();
System.out.println("enter the temperature in fahrenheit");
double fah=sc.nextDouble();
f.setTempData(fah);
Celsius c=new Celsius();
System.out.println("enter the temperature in celsius");
double cel=sc.nextDouble();
c.setTempData(cel);
System.out.println("conversion");
f.changeTemp();
c.changeTemp();
f.display();
c.display();
}
}
Output:13.72
193.46
/*Q30.Write a java program to create an interface that consists of a method to display volume()
as an abstract method and redefine this method in the derived 2 classes to suit their
requirements. Create classes called Cone, Hemisphere and Cylinder that implements the
interface. Using these three classes, design a program that will accept dimensions of a cone,
cylinder and hemisphere interactively and display the volumes.
Volume of cone = (1/3)πr2h Volume of hemisphere = (2/3)πr3Volume of cylinder = πr2h
*/
import java.util.*;
interface MyVolume{
public void volume();
}
class Cone implements MyVolume{
double r,h;
public void setDim(double r,double h){
this.r=r;
this.h=h;
}
public void volume(){
System.out.println("Volume of Cone"+" "+ 1/3.0*Math.PI*r*r*h);
}
}
class Hemisphere implements MyVolume{
double r;
public void setDim(double r){
this.r=r;
}
public void volume(){
System.out.println("Volume of Hemisphere"+" "+ 2/3.0*Math.PI*r*r*r);
}
}
class Cylinder implements MyVolume{
double r,h;
public void setDim(double r,double h){
this.r=r;
this.h=h;
}
public void volume(){
System.out.println("Volume of Cylinder"+" "+ Math.PI*r*r*h);
}
}
public class InterfaceDemo{
public static void main(String []arg){
Scanner sc=new Scanner(System.in);
Cone c=new Cone();
Cylinder cl=new Cylinder();
Hemisphere h=new Hemisphere();
System.out.println("enter the radius and height of cone");
double rcone=sc.nextDouble();
double hcone=sc.nextDouble();
c.setDim(rcone,hcone);
System.out.println("enter the radius of hemisphere");
double rhemis=sc.nextDouble();
h.setDim(rhemis);
System.out.println("enter the radius and height of cylinder");
double rcy=sc.nextDouble();
double hcy=sc.nextDouble();
cl.setDim(rcy,hcy);
c.volume();
cl.volume();
h.volume();
}
}
Output:145892.54,439609.34,87507.85
/*Q31.Write a java program to accept and print the employee details during runtime.The details
will include employee id, name, dept_ Id. The program should raise an exception if user inputs
incomplete or incorrect data. The entered value should meet the following conditions:
a. First Letter of employee name should be in capital letter.
b. Employee id should be between 2001 and 5001
c. Department id should be an integer between 1 and 5.
If the above conditions are not met, then the application should raise specific exception else
should complete normal execution.*/
import java.util.Scanner;
try {
// Accept Employee ID
System.out.print("Enter Employee ID: ");
int employeeId = scanner.nextInt();
if (employeeId < 2001 || employeeId > 5001) {
throw new InvalidEmployeeIdException("Employee ID must be between 2001 and
5001.");
}
// Accept Department ID
System.out.print("Enter Department ID: ");
int deptId = scanner.nextInt();
if (deptId < 1 || deptId > 5) {
throw new InvalidDepartmentIdException("Department ID must be between 1 and
5.");
}
import java.util.Scanner;
class MyCalculator {
// Method to calculate n raised to the power of p
public long power(int n, int p) throws Exception {
if (n < 0 || p < 0) {
throw new Exception("n and p should be non-negative");
} else if (n == 0 && p == 0) {
throw new Exception("n and p should not be zero");
} else {
return (long) Math.pow(n, p);
}
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Output:
/*Q35.Write a java program for to solve producer consumer problem in which a
producer produces a value and consumer consume the value before producer
generate the next value.*/
class SharedBuffer {
private int value;
private boolean hasValue = false;
producerThread.start();
consumerThread.start();
}
} } catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
producerThread.start();
consumerThread.start();
}
}
Output:
/*Q36.Collection and Generic Framework:
Write a method removeEvenLength that takes an ArrayList of Strings as a parameter and that
removes all the strings of even length from the list.
(Use ArrayList)*/
import java.util.ArrayList;
import java.util.Iterator;
while (iterator.hasNext()) {
String str = iterator.next();
// Check if the length of the string is even
if (str.length() % 2 == 0) {
// Remove the string if its length is even
iterator.remove();
}
}
}
Output: [Hello,world,programming,fun]
/*Q37.Write a method swapPairs that switches the order of values in an ArrayList of Strings
in a pairwise fashion. Your method should switch the order of the first two values, then switch
the order of the next two, switch the order of the next two, and so on.
For example, if the list initially stores these values: {"four", "score", "and","seven", "years",
"ago"} your method should switch the first pair, "four", "score", the second pair, "and",
"seven", and the third pair, "years", "ago", to yield this list:{"score", "four", "seven", "and",
"ago", "years"}.If there are an odd number of values in the list, the final element is not moved.
For example, if the original list had been: {"to", "be", "or", "not", "to", "be",
"hamlet"} It would again switch pairs of values, but the final value, "hamlet"
would not be moved, yielding this list: {"be", "to", "not", "or", "be", "to",
"hamlet"}
*/
import java.util.ArrayList;
Output: [score,four,seven,and,ago,years]
[be,to,not,or,be,to,hamlet]
/*Q38.Write a method called alternate that accepts two Lists of integers as its
parameters and returns a new List containing alternating elements from the twolists, in the
following order:
• First element from first list
• First element from second list
• Second element from first list
• Second element from second list
• Third element from first list
• Third element from second list
If the lists do not contain the same number of elements, the remaining elements from the longer
list should be placed consecutively at the end. For example, for a first list of (1, 2, 3, 4, 5) and
a second list of (6, 7, 8, 9, 10, 11, 12), a call of alternate (list1,list2) should return a list
containing (1, 6, 2, 7, 3, 8, 4,9, 5, 10, 11, 12). Do not modify the parameter lists passed in.*/
import java.util.ArrayList;
import java.util.List;
return result;
}
Output: [1,6,2,7,3,8,4,9,5,10,11,12]
/*Q39.AWT & Swing, Event Handling:
Write a GUI program to develop an application that receives a string in one text field, and count
number of vowels in a string and returns it in another text field, when the button named
“CountVowel” is clicked.
When the button named “Reset” is clicked it will reset the value of
textfield one and Textfield two.
When the button named “Exit” is clicked it will closed the application*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
resetButton.addActionListener(new ActionListener() {
exitButton.addActionListener(new ActionListener() {
Output:
/*Q40.Java Database Connectivity (JDBC):
Create a database of employee with the following fields.
• Name
• Code
• Designation
• Salary
a) Write a java program to create GUI java application to take employee data from the
TextFields and store it in database using JDBC connectivity.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public EmployeeDatabaseApp() {
setTitle("Employee Data Entry");
setSize(400, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Initialize components
nameLabel = new JLabel("Name:");
codeLabel = new JLabel("Code:");
designationLabel = new JLabel("Designation:");
salaryLabel = new JLabel("Salary:");
// Set layout
setLayout(new GridLayout(6, 2));
setVisible(true);
}
try {
// Register MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Open a connection
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedb",
"root","your_sql_password");
// Close resources
statement.close();
connection.close();
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
Output:
/*Q40.b) Write a JDBC Program to retrieve all the records from the employee database.*/
import java.sql.*;
try {
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedb", "root",
"your_sql_password");
System.out.println("connected");
while (resultSet.next()) {
System.out.println("Name: " + name + ", Code: " + code + ", Designation: " + designation + ",
Salary: " + salary);
connection.close();
} catch (SQLException e) {
e.printStackTrace();