You are on page 1of 44

1)Difference of Square of sum and sum of squares

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Power {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc = new Scanner(System.in);

int x = sc.nextInt();

int a=0;
int b=0;
int d=0;
while(x>0)
{
int c = x%10;

a=a+c;
x = x/10;
b=b+(c*c);
}
d=(a*a)-b;
System.out.println(d);

}
}

2) Create a class Car with below attributes

id - int
brand - string
type - string
price - double

Write getters, setters, and parameterized constructor as required

Create class Solution with main method.

Implement static method - searchCarType in Solution class

This method will take a String parameter along with the other parameter as array of
Car objects.

The method will return array of Cars where the String parameter appears in the type
attribute (with case insensitive search)

This method should be called from main method and display the id of returned objects
in ascending order.
Before calling this method (searchCarType) in the main method, use Scanner object to
read values for four Car objects referring the attributes in the above sequence.

Then read the value for search parameter

Next call the method searchCarType, write the logic to sort the id in ascending
order (in main method) and display the result.

INPUT:
1
Ferrari ZXi
Sports
2500000
2
Tata Xpnc
Luxury
1000000
3
BMW
Sports
1700000
4
Benz Dz
Luxury
2000000
Luxury

OUTPUT:
2
4

Public class Solution


{
Public static void main(String[] args)
{
//code to read values
//code to call required method
//code to display the result
}
Public static Car[] searchCarType(String search, Car[] cars)
}
//method logic
}
}
class Car
}
//code to build Book Class
}

SOLUTION
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String args[])
{
Car[] c=new Car[4];
Scanner sc=new Scanner(System.in);
for(int i=0;i<c.length;i++)
{
int id=sc.nextInt();sc.nextLine();
String brand=sc.nextLine();
String type=sc.nextLine();
double price=sc.nextDouble();
c[i]=new Car(id,brand,type,price);

}
String str=sc.next() ;
Car result[]=searchCarType(str,c);
for(int f=0;f<result.length;f++)
{
System.out.println(result[f].getId());
}
}

public static Car[] searchCarType(String type,Car[] c)


{
int count=0;
for(int t=0;t<c.length;t++)
{
if(c[t].getType().equalsIgnoreCase(type))
{
count++;
}
}
Car result[]=new Car[count];
int n=0;
for(int j=0;j<c.length;j++)
{
if(c[j].getType().equalsIgnoreCase(type))
{
result[n]=c[j];
n++;
}

}
for(int p=0;p<result.length;p++)
{
for(int j=p+1;j<result.length;j++) {
if(result[p].getId()>result[j].getId())
{
Car temp=result[p];
result[p]=result[j];
result[j]=temp;
}

}
}
return result;
}
}
class Car
{
private int id;
private String brand;
private String type;
private double price;

public Car(int id, String brand, String type, double price) {

this.id = id;
this.brand = brand;
this.type = type;
this.price = price;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getBrand() {


return brand;
}

public void setBrand(String brand) {


this.brand = brand;
}

public String getType() {


return type;
}

public void setType(String type) {


this.type = type;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}
}
3)
import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
Customer[] c=new Customer[4];
for(int i=0;i<c.length;i++)
{
int customerId=sc.nextInt();sc.nextLine();
String customerType=sc.nextLine();
String transactionType=sc.nextLine();
double paymentAmount=sc.nextDouble();
c[i]=new
Customer(customerId,customerType,transactionType,paymentAmount);
}
double adj=sc.nextDouble();
getCustomerBalance(c,adj);
for(int z=0;z<c.length;z++) {

System.out.println(c[z].getCustomerId()+c[z].getCustomerType()+c[z].getTransac
tionType()+c[z].getPaymentAmount());
}

}
public static void getCustomerBalance(Customer[] c, double adjustment )
{
for(int j=0;j<c.length;j++) {
if(c[j].getTransactionType().equals("discount"))
{
double k=c[j].getPaymentAmount()-(adjustment);
c[j].setPaymentAmount(k);
}
if(c[j].getTransactionType().equals("surcharge") &&
c[j].getCustomerType().equals("corporate"))
{
double m=c[j].getPaymentAmount()+(adjustment);
c[j].setPaymentAmount(m);
}

if(c[j].getTransactionType().equals("surcharge") &&
c[j].getCustomerType().equals("ordinary")) {
double n=c[j].getPaymentAmount()+(adjustment)+100;
c[j].setPaymentAmount(n);
}
}
for(int z=0;z<c.length;z++) {
System.out.println(c[z].getCustomerId()+c[z].getCustomerType()+c[z].getTransac
tionType()+c[z].getPaymentAmount());
}

}
class Customer{
private int customerId;
private String customerType;
private String transactionType;
private double paymentAmount;
public Customer(int customerId, String customerType, String transactionType,
double paymentAmount) {
super();
this.customerId = customerId;
this.customerType = customerType;
this.transactionType = transactionType;
this.paymentAmount = paymentAmount;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerType() {
return customerType;
}
public void setCustomerType(String customerType) {
this.customerType = customerType;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public double getPaymentAmount() {
return paymentAmount;
}
public void setPaymentAmount(double paymentAmount) {
this.paymentAmount = paymentAmount;
}

}
4)
import java.util.*;
import java.io.*;
import java.text.*;
import java.text.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {

Order[] o=new Order[3];


Scanner sc=new Scanner(System.in);
for(int i=0;i<o.length;i++)
{
int orderId=sc.nextInt();
int noOfItems=sc.nextInt();sc.nextLine();
String transactionType=sc.next();
int CustomerId=sc.nextInt();
double OrderAmount=sc.nextDouble();
o[i]=new Order(orderId,noOfItems,transactionType,CustomerId,OrderAmount);
}
Order high=getHighestOrder(o);
System.out.println(high.getOrderId()+":"+high.getNoOfItems()+":"+high.getTransactionT
ype()+":"+high.getCustomerId()+":"+high.getOrderAmount());

}
public static Order getHighestOrder(Order[] o) {

Order largestorder=o[0];
for(int j=0;j<o.length;j++) {
if(o[0].getOrderAmount()<o[j].getOrderAmount()) {
largestorder=o[j];

return largestorder;
}

}
class Order{
private int orderId;
private int noOfItems;
private String transactionType;
private int CustomerId;
private double OrderAmount;
public Order(int orderId, int noOfItems, String transactionType, int
customerId, double orderAmount) {
super();
this.orderId = orderId;
this.noOfItems = noOfItems;
this.transactionType = transactionType;
this.CustomerId = customerId;
this.OrderAmount = orderAmount;

}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public int getNoOfItems() {
return noOfItems;
}
public void setNoOfItems(int noOfItems) {
this.noOfItems = noOfItems;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public int getCustomerId() {
return CustomerId;
}
public void setCustomerId(int customerId) {
CustomerId = customerId;
}
public double getOrderAmount() {
return OrderAmount;
}

public void setOrderAmount(double orderAmount) {


OrderAmount = orderAmount;
}

}
5)
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Replace {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
String s=" ";
String p=str.substring(1,4);

for(int i=0;i<str.length();i++)
{
char c=str.toLowerCase().charAt(i);
if(c=='i')
{
s=str.replace('i','m');
}
}
System.out.println(s);
System.out.println(p);
}

}
6) "Create class Book with below attributes:

id - int
title - String
author - String
price - double

Write getters, setters and parameterized constructor as required.

Create class Solution with main method.

Implement static method - sortBooksByPrice in Solution class.


This method will take a parameter as array of Book objects.
It will return array of books which is sorted in ascending order of book price. Assume that no two books
will have same price.

This method should be called from main method and display values of returned objects as shared in the
sample.

Before calling this method, use Scanner object to read values for four Book objects referring attributes
in the above sequence.

Next call the method and display the result.

Consider below sample input and output:

Input:
1
hello
writer1
50
2
cup
writer2
55
3
Planet
writer3
45
4
India
writer4
40

Output (each line has values separated by single space):


4 India writer4 40.0
3 Planet writer3 45.0
1 hello writer1 50.0
2 cup writer2 55.0

Note on using Scanner object:


Sometimes scanner does not read the new line character while invoking methods like nextInt(),
nextDouble() etc.
Usually, this is not an issue, but this may be visible while calling nextLine() immediately after those
methods.

Consider below input values:


22
hello

Referring below code:

Scanner sc = new Scanner(System.in);


int x = sc.nextInt();
String str = sc.nextLine(); -> here we expect str to have value hello. Instead it may be """".

If above issue is observed, then it is suggested to add one more explicit call to nextLine() after reading
numeric value."

SOLUTION

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */

Book[] books = new Book[4];

Scanner sc = new Scanner(System.in);

for(int i = 0;i<books.length;i++)
{
int id = sc.nextInt();sc.nextLine();
String title = sc.nextLine();
String author = sc.nextLine();

double price = sc.nextDouble();

books[i]= new Book(id,title,author,price);


}

sortBooksByPrice(books);

for(Book b:books)
{
System.out.println(b.getId()+" "+b.getTitle()+ " " + b.getAuthor()+ " "+ b.getPrice());
}

public static void sortBooksByPrice(Book[] books)


{

for(int i = 0;i<books.length;i++)
{
for(int j = 0;j<i;j++)
{
if(books[i].getPrice() < books[j].getPrice())
{
Book tmp = books[i];
books[i] = books[j];
books[j] = tmp;
}
}
}

}
}

class Book
{

private int id;


private String title;
private String author;
private double price;
public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

public String getTitle() {


return title;
}

public void setTitle(String title) {


this.title = title;
}

public String getAuthor() {


return author;
}

public void setAuthor(String author) {


this.author = author;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}

public Book(int id, String title, String author, double price)


{
this.id = id;
this.title = title;
this.author = author;
this.price = price;
}
}
7)
"Write main method in Solution class.

Method will read input number (without decimals) and print the maximum digit in that number.

Consider below sample input and output:


input:

8656

output:

8
SOLUTION
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc = new Scanner(System.in);

int x = sc.nextInt();
int a = 0;

while(x>0)
{
int c = x%10;
if(a<c) a = c;

x = x/10;
}

System.out.println(a);
}
}
8)
"Define main method in Solution class.

The program will read a String value. It will calculate total number of vowels in that string and print the
answer.

Sample input:

internal
Output:

Sample input:

Apple

Output:

SOLUTION
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc = new Scanner(System.in);

String str = sc.nextLine();

int code = 0;

for(int i = 0;i<str.length();i++)
{
char c = str.toLowerCase().charAt(i);

if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u')
code++;
}

System.out.println(code);
}
}
9)
"Create class Document with below attributes

id - int
title - String
folderName - String
pages - int

Write getters, setters and parameterized constructor as required.

Create class Solution with main method.

Implement static method - docsWithOddPages in Solution class.

This method will take array of Document objects and return another array with Document objects
which has odd number of pages.

This method should be called from main method and display values of returned objects as shared in the
sample (in ascending order of id attribute).

Before calling this method, use Scanner object to read values for four Document objects referring
attributes in the above sequence.

Next call the method and display the result.

Consider below sample input and output:

Input:
1
resume
personal
50
2
question1
exams
55
3
question2
exams
45
4
India
misc
40

Output (each line has values separated by single space):


2 question1 exams 55
3 question2 exams 45

Note on using Scanner object:


Sometimes scanner does not read the new line character while invoking methods like nextInt(),
nextDouble() etc.
Usually, this is not an issue, but this may be visible while calling nextLine() immediately after those
methods.

Consider below input values:


22
hello

Referring below code:

Scanner sc = new Scanner(System.in);


int x = sc.nextInt();
String str = sc.nextLine(); -> here we expect str to have value hello. Instead it may be """".

If above issue is observed, then it is suggested to add one more explicit call to nextLine() after reading
numeric value."

SOLUTION
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


Scanner sc = new Scanner(System.in);
Document[] docs = new Document[4];

for(int i = 0;i<docs.length;i++)
{
int id = sc.nextInt();sc.nextLine();
String title = sc.nextLine();
String folderName = sc.nextLine();
int pages = sc.nextInt();

docs[i] = new Document(id,title,folderName,pages);

Document[] newDocs = docsWithOddPages(docs);

for(Document doc:newDocs)
{
System.out.println(doc.getId() + " " + doc.getTitle() + " " + doc.getFolderName() + " " +
doc.getPages());
}
}
public static Document[] docsWithOddPages(Document[] docs)
{
Document[] newDocs = null;

int n = 0;

for(Document doc:docs)
{
if(doc.getPages()%2 == 1) n++;
}

newDocs = new Document[n];

n = 0;

for(Document doc:docs)
{
if(doc.getPages()%2 == 1) newDocs[n++] = doc;
}

for(int i = 0;i<newDocs.length;i++)
{
for(int j = 0;j<i;j++)
{
if(newDocs[i].getId() < newDocs[j].getId())
{
Document tmp = newDocs[i];
newDocs[i] = newDocs[j];
newDocs[j] = tmp;
}
}
}

return newDocs;
}
}

class Document
{
private int id;
private String title;
private String folderName;
private int pages;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}

public String getTitle() {


return title;
}

public void setTitle(String title) {


this.title = title;
}

public String getFolderName() {


return folderName;
}

public void setFolderName(String folderName) {


this.folderName = folderName;
}

public int getPages() {


return pages;
}

public void setPages(int pages) {


this.pages = pages;
}

public Document(int id, String title, String folderName, int pages)


{
this.id = id;
this.title = title;
this.folderName = folderName;
this.pages = pages;
}
}
10)
"Define main method in Solution class.

The program will read a number (without decimal) and print the same in reverse order.

Sample input:
3454

Output

4543

SOLUTION

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc = new Scanner(System.in);

int x = sc.nextInt();
String a = "";

while(x>0)
{
int c = x%10;
a=a+c;

x = x/10;
}

System.out.println(a);
}
}
11)
"Write main method in Solution class.

The method will read a String value and print the maximum valued character (as per alphabet and ASCII
sequence).

Consider below sample input and output:

Input:

HellO
Output:

Important: It is 'l' and not 'O' since ASCII for 'l' is higher than 'O'.

SOLUTION
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc = new Scanner(System.in);

String str = sc.nextLine();

char c='x';

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

if(i == 0)
{
c = str.charAt(i);
}
else
{
if(c<str.charAt(i))
c = str.charAt(i);
}

System.out.println(c);
}
}
12)

"
Create class Document with below attributes

id - int
title - String
folderName - String
pages - int

Write getters, setters and parameterized constructor as required.

Create class Solution with main method.

Implement static method - combineDocs in Solution class.

This method will take array of Document objects and return another document object which will be
combinition of all objects in array.

The logic for combining each attribute will be as below:

id - this value will be 1 more than maximum value of id in object array.


title - this value will be concatanation of title values of all objects in the array (separated by #).
folderName - this value will be concatanation of folderName values of all objects in the array
(separated by @)
pages - this value will be total of page values in the object array.

This method should be called from main method and display values of returned object as shared in the
sample.

Before calling this method, use Scanner object to read values for four Document objects referring
attributes in the above sequence.

Next call the method and display the result.

Consider below sample input and output:

Input:
1
resume
personal
50
2
question1
exams
55
3
question2
exams
45
4
India
misc
40
Output:
5
resume#question1#question2#India
personal@exams@exams@misc
190

Note on using Scanner object:


Sometimes scanner does not read the new line character while invoking methods like nextInt(),
nextDouble() etc.
Usually, this is not an issue, but this may be visible while calling nextLine() immediately after those
methods.

Consider below input values:


22
hello

Referring below code:

Scanner sc = new Scanner(System.in);


int x = sc.nextInt();
String str = sc.nextLine(); -> here we expect str to have value hello. Instead it may be """".

If above issue is observed, then it is suggested to add one more explicit call to nextLine() after reading
numeric value."

SOLUTION

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */

Scanner sc = new Scanner(System.in);


Document[] docs = new Document[4];

for(int i = 0;i<docs.length;i++)
{
int id = sc.nextInt();sc.nextLine();
String title = sc.nextLine();
String folderName = sc.nextLine();
int pages = sc.nextInt();
docs[i] = new Document(id,title,folderName,pages);

Document doc = combineDocs(docs);

System.out.println(doc.getId());
System.out.println(doc.getTitle());
System.out.println(doc.getFolderName());
System.out.println(doc.getPages());
}

public static Document combineDocs(Document[] docs)


{
int id = 0;
String title = "";
String folderName = "";
int pages = 0;

for(int i = 0;i<docs.length;i++)
{
if(id < docs[i].getId()) id = docs[i].getId();

if(i == docs.length - 1)
{
title += docs[i].getTitle();
folderName += docs[i].getFolderName();
}
else
{
title += docs[i].getTitle()+"#";
folderName += docs[i].getFolderName()+"@";
}

pages += docs[i].getPages();
}

id++;

Document doc = new Document(id, title, folderName,pages);

return doc;
}
}

class Document
{
private int id;
private String title;
private String folderName;
private int pages;

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getTitle() {


return title;
}

public void setTitle(String title) {


this.title = title;
}

public String getFolderName() {


return folderName;
}

public void setFolderName(String folderName) {


this.folderName = folderName;
}

public int getPages() {


return pages;
}

public void setPages(int pages) {


this.pages = pages;
}

public Document(int id, String title, String folderName, int pages)


{
this.id = id;
this.title = title;
this.folderName = folderName;
this.pages = pages;
}
}
13)
"Define main method in Solution class to read a number (without digits). The program should display
the answer which is addition of those digits.
Sample input:

123

Output

SOLUTION

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc = new Scanner(System.in);

int x = sc.nextInt();
int a = 0;

while(x>0)
{
int c = x%10;
a=a+c;

x = x/10;
}

System.out.println(a);
}
}

14)

"Write main method in Solution class.

The method will read a String value and print the minimum valued character (as per alphabet and ASCII
sequence).

Consider below sample input and output:


Input:

HellO

Output:

Important: Answer is not 'e' since 'H' has lower ASCII value then 'e' "

SOLUTION

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {


public static void main(String args[] ) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
Scanner sc = new Scanner(System.in);

String str = sc.nextLine();

char c='x';

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

if(i == 0)
{
c = str.charAt(i);
}
else
{
if(c>str.charAt(i))
c = str.charAt(i);
}

System.out.println(c);
}
}
15)
IF THE GIVEN NUMBER IS POWER OF 2 OR NOT
EG 2^3=8
IF YES PRINT TRUE ELSE FALSE
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int count=0;
for(int i=0;i<15;i++)
{
double p=Math.pow(2, i);
if(p==a) {
count++;
}
}
if(count==1)
{
System.out.println("TRUE");

}
else
{
System.out.println("FALSE");
}
}

16)
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String args[])
{
Item[] it=new Item[4];
Scanner sc=new Scanner(System.in);
for(int i=0;i<it.length;i++)
{
int itemId=sc.nextInt();sc.nextLine();
String itemName=sc.nextLine();
String category=sc.nextLine();
double price=sc.nextDouble();
it[i]=new Item(itemId,itemName,category,price);

}
String str=sc.next() ;
Item[] result=searchNameByCategory(str,it);
for(int f=0;f<result.length;f++)
{
System.out.println(result[f].getItemId());
}
}

public static Item[] searchNameByCategory(String type,Item[] it)


{
int count=0;
for(int t=0;t<it.length;t++)
{
if(it[t].getCategory().equalsIgnoreCase(type))
{
count++;
}
}
Item result[]=new Item[count];
int n=0;
for(int j=0;j<it.length;j++)
{
if(it[j].getCategory().equalsIgnoreCase(type))
{
result[n]=it[j];
n++;
}

}
for(int p=0;p<result.length;p++)
{
for(int j=p+1;j<result.length;j++) {
if(result[p].getItemId()>result[j].getItemId())
{
Item temp=result[p];
result[p]=result[j];
result[j]=temp;
}

}
}
return result;
}
}
class Item
{
private int itemId;
private String itemName;
private String category;
private double price;
public Item(int itemId, String itemName, String category, double price) {
super();
this.itemId = itemId;
this.itemName = itemName;
this.category = category;
this.price = price;
}
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}

17)
public class ComplexNumber{
//for real and imaginary parts of complex numbers
double real, img;

//constructor to initialize the complex number


ComplexNumber(double r, double i){
this.real = r;
this.img = i;
}

public static ComplexNumber sum(ComplexNumber c1, ComplexNumber c2)


{
//creating a temporary complex number to hold the sum of two numbers
ComplexNumber temp = new ComplexNumber(0, 0);

temp.real = c1.real + c2.real;


temp.img = c1.img + c2.img;

//returning the output complex number


return temp;
}
public static void main(String args[]) {
ComplexNumber c1 = new ComplexNumber(5.5, 4);
ComplexNumber c2 = new ComplexNumber(1.2, 3.5);
ComplexNumber temp = sum(c1, c2);
System.out.printf("Sum is: "+ temp.real+" + "+ temp.img +"i");
}
}

18)SORTING ODD VALUES IN AN ARRAY


public class sort {

public static void sortOddValues(int array[])


{
int i,j,k,m;
int p=0;
int arr[]=new int[5];

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

if(array[i]>array[j])
{
int temp;
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
for(k=0;k<array.length;k++)
{
if((array[k]%2)!=0)
{
arr[p]=array[k];
p++;

}
for(m=0;m<arr.length;m++)
{
System.out.println(arr[m]);
}
}
public static void main(String[] args)
{

int array[]={111,77,88,44,32,11,13,25,44};

sortOddValues(array);
}
}

19)FINDING SEQUENTIAL DISTANCE BETWEEN TWO POINTS


class Point
{
private int x;
private int y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}

}
public class Solution {
public static void findSequentialDistance(Point p[])
{
double a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,s;

a=((p[1].getX())-(p[0].getX()));
b=((p[1].getX())-(p[0].getX()));
c=((p[1].getY())-(p[0].getY()));
d=((p[1].getY())-(p[0].getY()));
e=Math.sqrt((a*b)+(c*d));
f=((p[2].getX())-(p[1].getX()));
g=((p[2].getX())-(p[1].getX()));
h=((p[2].getY())-(p[1].getY()));
i=((p[2].getY())-(p[1].getY()));
j=Math.sqrt((f*g)+(h*i));

k=((p[3].getX())-(p[2].getX()));
l=((p[3].getX())-(p[2].getX()));
m=((p[3].getY())-(p[2].getY()));
n=((p[3].getY())-(p[2].getY()));
o=Math.sqrt((k*l)+(m*n));
s=e+j+o;

System.out.println(s);
}

public static void main(String[] args) {

Point p[]=new Point[4];


p[0]=new Point(-3,-4);
p[1]=new Point(0,0);
p[2]=new Point(4,3);
p[3]=new Point(16,-2);

findSequentialDistance(p);

20)

//SORT BOOKS BY PRICE


Import java.io.*;
Import java.util.*;
Import java.text.*;
Import java.math.*;
Import java.util.regex.*;

Public class Solution {


Public staticvoidmain(String args[]) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to
STDOUT */

Book[] books = new Book[4];

Scanner sc = new Scanner(System.in);

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


int id = sc.nextInt();sc.nextLine();
String title = sc.nextLine();
String author = sc.nextLine();

double price = sc.nextDouble();

books[i] = new Book(id, title, author, price);


}
sortBooksByPrice(books);

for (Book b : books) {


System.out.println(b.getId() + " " + b.getTitle() + " " +
b.getAuthor() + " " + b.getPrice());
}

Public static void sortBooksByPrice(Book[] books) {

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


for (int j = 0; j <i; j++) {
if (books[i].getPrice() < books[j].getPrice()) {
Book tmp = books[i];
books[i] = books[j];
books[j] = tmp;
}
}
}

}
}

class Book {

private int id;


private String title;
private String author;
private double price;

public int getId() {


return id;
}

Public void setId(int id) {


this.id = id;
}

public String getTitle() {


return title;
}
Public void setTitle(String title) {
this.title = title;
}

public String getAuthor() {


return author;
}

Public void setAuthor(String author) {


this.author = author;
}

Public double getPrice() {


return price;
}

Public void setPrice(double price) {


this.price = price;
}

Public Book(int id, String title, String author, double price) {


this.id = id;
this.title = title;
this.author = author;
this.price = price;
}
}
21)
//PRIME NUMBER CHECK

Import java.io.*;
Import java.util.*;
Import java.text.*;
Import java.math.*;
Import java.util.regex.*;

Public class Solution {


Public static void main(String args[]) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to
STDOUT */
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
intarr[] = newint[n];
int res[] = new int[n];
int j = 0;
for (int i = 0; i< n; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i< n; i++) {
int num = arr[i];
if (num == 0 || num == 1)
continue;
if (is_prime(num) == 1) {
int t = num;
int rev = 0;
while (t >0) {
int digit = t % 10;
rev = rev * 10 + digit;
t = t / 10;
}
if (is_prime(rev) == 1) {
res[j] = num;
j++;
}
}
}
Int acs[] = newint[j];
for (inti = 0; i< j; i++) {
acs[i] = res[i];

}
for (int i = 0; i< j - 1; i++) {
int min_idx = i;
for (int k = i + 1; k < j; k++)
if (acs[k] <acs[min_idx])
min_idx = k;

int temp = acs[min_idx];


acs[min_idx] = acs[i];
acs[i] = temp;
}
for (int i = 0; i< j; i++) {
System.out.println(acs[i]);
}
}
publicstaticintis_prime(int n) {
for (inti = 2; i< n; i++) {
if (n % i == 0)
return 0;

}
Return 1;
}
}

22)
//STUDENTS FROM SAME CITY AND SAME MARKS
Import java.io.*;
Import java.util.*;
Import java.text.*;
Import java.math.*;
Import java.util.regex.*;

Public class Solution {


Public static void main(String args[]) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to
STDOUT */
int i, j, min;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Student s[] = new Student[n];
for (i = 0; i< n; i++) {
int id = sc.nextInt();
sc.nextLine();
String name = sc.nextLine();
String city = sc.nextLine();
double marks = sc.nextDouble();
s[i] = new Student(id, name, city, marks);
// System.out.println(s[i].id + " " + s[i].name + " " + s[i].city +
" " +
// s[i].marks);
}
sc.nextLine();
String c = sc.nextLine();
double m = sc.nextDouble();
Student re[] = getStudentsWithCityAndMarks(s, c, m);
System.out.println(re.length);
Student t[] = new Student[re.length];
for (i = 0; i<re.length - 1; i++) {
min = i;
for (j = i + 1; j <re.length; j++) {
if (re[j].id < re[min].id)
min = j;
}
t[0] = re[min];
re[min] = re[i];
re[i] = t[0];

}
for (i = 0; i<re.length; i++) {
System.out.println(re[i].id + " " + re[i].name + " " + re[i].city +
" " + re[i].marks);
}

Public static Student[] getStudentsWithCityAndMarks(Student[]


students, String city, double marks) {
Student s[] = new Student[students.length];
int j = 0;
for (int i = 0; i<students.length; i++) {
if (students[i].city.equals(city)) {
if (students[i].marks == marks) {
s[j] = new Student(students[i].id,
students[i].name, students[i].city, students[i].marks);
j++;
}
}
}
Student res[] = new Student[j];
for (inti = 0; i< j; i++) {
res[i] = new Student(s[i].id, s[i].name, s[i].city,
s[i].marks);
}
return res;
}
}

class Student {
int id;
String name;
String city;
double marks;

Student(int id, String name, String city, double marks) {


this.id = id;
this.name = name;
this.city = city;
this.marks = marks;
}
}

23)
//RETURN VOWEL STRING
Import java.io.*;
Import java.util.*;
Import java.text.*;
Import java.math.*;
Import java.util.regex.*;

Public class Solution {


Public static voidmain(String args[]) throws Exception {
/* Enter your code here. Read input from STDIN. Print output to
STDOUT */
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
for (int j = 0; j <s.length(); j++) {
chari = s.charAt(j);
if (i == 'a' || i == 'e' || i == 'i' || i == 'o' || i == 'u' || i
== 'A' || i == 'E' || i == 'I' || i == 'O'
|| i == 'U') {
System.out.print(Character.toLowerCase(i));
}
}
}
}
24)
import java.util.Scanner;
public class AddTwoNumbers2 {

public static void main(String[] args) {

int num1, num2, sum;


Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();

System.out.println("Enter Second Number: ");


num2 = sc.nextInt();

sum = num1 + num2;


System.out.println("Sum of these numbers: "+sum);
}
}

25)
import java.util.Scanner;

class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");

//The input provided by user is stored in num


Scanner input = new Scanner(System.in);
num = input.nextInt();

/* If number is divisible by 2 then it's an even number


* else odd number*/
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
26)
import java.util.Scanner;

class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");

//The input provided by user is stored in num


Scanner input = new Scanner(System.in);
num = input.nextInt();

/* If number is divisible by 2 then it's an even number


* else odd number*/
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
27)
import java.util.Scanner;
public class Demo {

public static void main(String[] args) {

int year;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Year:");
year = scan.nextInt();
scan.close();
boolean isLeap = false;

if(year % 4 == 0)
{
if( year % 100 == 0)
{
if ( year % 400 == 0)
isLeap = true;
else
isLeap = false;
}
else
isLeap = true;
}
else {
isLeap = false;
}

if(isLeap==true)
System.out.println(year + " is a Leap Year.");
else
System.out.println(year + " is not a Leap Year.");
}
}
28)
import java.util.Scanner;
class PalindromeTest {
public static void main(String args[])
{
String reverseString="";
Scanner scanner = new Scanner(System.in);

System.out.println("Enter a string to check if it is a palindrome:");


String inputString = scanner.nextLine();

int length = inputString.length();

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


reverseString = reverseString + inputString.charAt(i);

if (inputString.equals(reverseString))
System.out.println("Input string is a palindrome.");
else
System.out.println("Input string is not a palindrome.");
}
}
29)
public class JavaExample {

public static void main(String[] args) {


String str = "BeginnersBook";
int vcount = 0, ccount = 0;

//converting all the chars to lowercase


str = str.toLowerCase();
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { vcount++;
} else if((ch >= 'a'&& ch <= 'z')) {
ccount++;
}
}
System.out.println("Number of Vowels: " + vcount);
System.out.println("Number of Consonants: " + ccount);
}
}

30)
public class Example
{
public void reverseWordInMyString(String str)
{
/* The split() method of String class splits
* a string in several strings based on the
* delimiter passed as an argument to it
*/
String[] words = str.split(" ");
String reversedString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
/* The charAt() function returns the character
* at the given position in a string
*/
reverseWord = reverseWord + word.charAt(j);
}
reversedString = reversedString + reverseWord + " ";
}
System.out.println(str);
System.out.println(reversedString);
}
public static void main(String[] args)
{
Example obj = new Example();
obj.reverseWordInMyString("Welcome to BeginnersBook");
obj.reverseWordInMyString("This is an easy Java Program");
}
}
32)
import java.util.Scanner;
public class Example
{
public static void main(String args[])
{
int counter, i=0, j=0, temp;
int number[] = new int[100];
Scanner scanner = new Scanner(System.in);
System.out.print("How many elements you want to enter: ");
counter = scanner.nextInt();

/* This loop stores all the elements that we enter in an


* the array number. First element is at number[0], second at
* number[1] and so on
*/
for(i=0; i<counter; i++)
{
System.out.print("Enter Array Element"+(i+1)+": ");
number[i] = scanner.nextInt();
}

/* Here we are writing the logic to swap first element with


* last element, second last element with second element and
* so on. On the first iteration of while loop i is the index
* of first element and j is the index of last. On the second
* iteration i is the index of second and j is the index of
* second last.
*/
j = i - 1;
i = 0;
scanner.close();
while(i<j)
{
temp = number[i];
number[i] = number[j];
number[j] = temp;
i++;
j--;
}

System.out.print("Reversed array: ");


for(i=0; i<counter; i++)
{
System.out.print(number[i]+ " ");
}
}
}

33)
import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int count, temp;

//User inputs the array size


Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements you want in the array: ");
count = scan.nextInt();

int num[] = new int[count];


System.out.println("Enter array elements:");
for (int i = 0; i < count; i++)
{
num[i] = scan.nextInt();
}
scan.close();
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (num[i] > num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
System.out.print("Array Elements in Ascending Order: ");
for (int i = 0; i < count - 1; i++)
{
System.out.print(num[i] + ", ");
}
System.out.print(num[count - 1]);
}
}
34)
public class JavaExample {

public static void main(String[] args) {

int num = 370, number, temp, total = 0;

number = num;
while (number != 0)
{
temp = number % 10;
total = total + temp*temp*temp;
number /= 10;
}

if(total == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
}
35)
import java.util.Scanner;
public class GCDExample3 {

public static void main(String[] args) {

int num1, num2;

//Reading the input numbers


Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");
num1 = (int)scanner.nextInt();

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


num2 = (int)scanner.nextInt();

//closing the scanner to avoid memory leaks


scanner.close();
while (num1 != num2) {
if(num1 > num2)
num1 = num1 - num2;
else
num2 = num2 - num1;
}

//displaying the result


System.out.printf("GCD of given numbers is: %d", num2);
}

}
36)FIBONACCI SERIES
import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {

int count, num1 = 0, num2 = 1;


System.out.println("How may numbers you want in the sequence:");
Scanner scanner = new Scanner(System.in);
count = scanner.nextInt();
scanner.close();
System.out.print("Fibonacci Series of "+count+" numbers:");

int i=1;
while(i<=count)
{
System.out.print(num1+" ");
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
i++;
}
}
}

You might also like