Friday, 5 February 2021

Railway Reservation java ---simple Format

QUESTION: Develop a Railway Reservation Application 

contains

1.AC coach

2.Non AC coach

3. Seater

each should contain 60 seats and 10 waiting list max allowed rest request should be cancelled. If a confirmed ticket is cancelled then waiting list should moved to confirm ticket.

you should have

1.Ticket Booking

2.Ticket Cancellation

3.Status Checking

ANSWER:

//here i had 4 class 1-main class 2-manager class in which all the operations takes place 3&4-passenger and booking declaration class 

//MAIN CLASS BookingSystem.java

package RailwayReservation;


import java.util.ArrayList;

import java.util.HashMap;

import java.util.Map.Entry;

import java.util.Scanner;


class BookingSystem {


public static BookingManager bookingManager=new BookingManager();

static Scanner scanner=new Scanner(System.in);

public static void main(String[] args) {

int choice;

do

{

System.out.println("Enter you choice \n1.Ticket Booking \n2. Ticket Cancellation\n3. Status checking \n4.exit");

choice=scanner.nextInt();

while(choice<=4)

{

switch(choice) {

case 1: getBookingDetails();

break;

case 2: cancelBooking();

break;

case 3: showStatus();

break;

case 4: System.out.println("Thank u!! Visit again");

break;

}

break;

}

}while(choice<=4);

}

private static void getBookingDetails() {

int count,select=1;

int coach,noOfTickets,age;

char from,to,gender;

String name,preferedBerth;

System.out.println("enter the 1.AC, 2.Non-Ac, 3.Seater");

do

{

coach=scanner.nextInt();

}while(coach>3);

count=bookingManager.checkAvailability(coach);

if(count<=70)

{

if(count<=60) {

System.out.println("from");

from=scanner.next().charAt(0);

System.out.println("To");

to=scanner.next().charAt(0);

System.out.println("enter how many tickets required ");

noOfTickets=scanner.nextInt();

scanner.nextLine();

if(count+noOfTickets>4)

{

System.out.println("Cannot book"+(count+noOfTickets-70)+"/n want to continue enter 1 ");

select=scanner.nextInt();

noOfTickets=count+noOfTickets-70;

}

if(select==1)

{

HashMap<Integer,Booking> bookedTickets=new HashMap<Integer,Booking>();

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

//scanner.nextLine();

System.out.println("enter name");

name=scanner.nextLine();

System.out.println("enter age");

age=scanner.nextInt();

System.out.println("enter gender");

gender=scanner.next().charAt(0);

scanner.nextLine();

System.out.println("enter  preferedBerth");

preferedBerth=scanner.nextLine();

ArrayList<Booking> temp=bookingManager.bookTicket(from,to,coach,noOfTickets,name,age,gender,preferedBerth);


bookedTickets.put(i+1, temp.get(0));

}

for(Entry<Integer, Booking> temp:bookedTickets.entrySet()) {

System.out.println("Customer Id : "+temp.getValue().getCustId());

System.out.println("Status "+temp.getValue().getStatus());

}

}

}

}

}

private static void showStatus() {

int custId;

String status;

System.out.println("enter customer id");

custId=scanner.nextInt();

status=bookingManager.checkStatus(custId);

System.out.println("your ticket is"+status);

}

private static void cancelBooking() {

int custId,select;

boolean check=true;

int amount=0;

System.out.println("enter customer id");

custId=scanner.nextInt();

check=showDetails(custId);

if(check) {

System.out.println("Kindly confirm to proceed cancel by enter 1");

select=scanner.nextInt();

if(select==1)

{

bookingManager.cancelTicket(custId);

System.out.println("your ticket canncelled and 5%  "+(amount*5/100)+"  of the ticket price "+amount+"    non refunded");


}

else

{

System.out.println("Thank you! your ticket is not cancelled");

}

}

}

private static boolean showDetails(int custId) {

boolean s=true;

Passenger passenger=bookingManager.getCustomerDetails(custId);

if(passenger!=null)

{

System.out.println("Name  "+passenger.getName());

System.out.println("From  "+passenger.getFrom());

System.out.println("To   "+passenger.getTo());

System.out.println("Coach   "+passenger.getCoachReq());

if(passenger.getStatus().equals("Cancelled"))

{

System.out.println("your ticket is already cancelled");

s=false;

}

else

{

System.out.println("status     "+passenger.getStatus());

System.out.println("Kindly note that once you cancel 5% of your ticket charges are not returnable");

}

}

return s;

}

void showTotalBookedTickets()

{

HashMap<Integer,Passenger> passList=bookingManager.getPassengerDetails();

}


}

//Booking class Booking.java

package RailwayReservation;
class Booking {
private int bookingId;
private int custId;
private String berth;
private int charges;
private int coachType;
public int getCharges() {
return charges;
}
public void setCharges(int charges) {
this.charges = charges;
}
public Booking(int bookingId, int custId, int coachType,String berth, String status,int charges) {
super();
this.bookingId = bookingId;
this.custId = custId;
this.berth = berth;
this.status = status;
this.charges=charges;
this.coachType=coachType;
}
private String status;
public int getBookingId() {
return bookingId;
}
public int getCoachType() {
return coachType;
}
public void setCoachType(int coachType) {
this.coachType = coachType;
}
public void setBookingId(int bookingId) {
this.bookingId = bookingId;
}
public int getCustId() {
return custId;
}
public void setCustId(int custId) {
this.custId = custId;
}
public String getBerth() {
return berth;
}
public void setBerth(String berth) {
this.berth = berth;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}

}

//Passenger class

package RailwayReservation;

class Passenger {
int custId;
String name;
int age;
char gender;
String preferedBerth;
int  noOfTicketsReq;
int coachReq;
String status;
int ticketId;
char from;
char to;
public Passenger(int custId, String name,int age, char gender, String preferedBerth, int noOfTicketsReq, int coachReq,
String status, int ticketId, char from, char to) {
super();
this.custId = custId;
this.age = age;
this.gender = gender;
this.preferedBerth = preferedBerth;
this.noOfTicketsReq = noOfTicketsReq;
this.coachReq = coachReq;
this.status = status;
this.ticketId = ticketId;
this.from = from;
this.to = to;
this.name=name;
}

public char getFrom() {
return from;
}

public void setFrom(char from) {
this.from = from;
}

public char getTo() {
return to;
}

public void setTo(char to) {
this.to = to;
}

public int getCustId() {
return custId;
}
public void setCustId(int custId) {
this.custId = custId;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getPreferedBerth() {
return preferedBerth;
}
public void setPreferedBerth(String preferedBerth) {
this.preferedBerth = preferedBerth;
}
public int getNoOfTicketsReq() {
return noOfTicketsReq;
}
public void setNoOfTicketsReq(int noOfTicketsReq) {
this.noOfTicketsReq = noOfTicketsReq;
}
public int getCoachReq() {
return coachReq;
}
public void setCoachReq(int coachReq) {
this.coachReq = coachReq;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getTicketId() {
return ticketId;
}
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void setTicketId(int ticketId) {
this.ticketId = ticketId;
}

}

//Booking manager class


package RailwayReservation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

class BookingManager {

static int passId=1,bookIdBAC=1,bookIdBNAC=1,bookIdBS=1,bookIdWAC=1,bookIdWNAC=1,bookIdWS=1;
HashMap<Integer,Booking> bookedTicketsAC=new HashMap<Integer,Booking>();
HashMap<Integer,Booking> waitingTicketsAC=new HashMap<Integer,Booking>();
HashMap<Integer,Booking> bookedTicketsNonAC=new HashMap<Integer,Booking>();
HashMap<Integer,Booking> waitingTicketsNonAC=new HashMap<Integer,Booking>();
HashMap<Integer,Booking> bookedTicketsSeater=new HashMap<Integer,Booking>();
HashMap<Integer,Booking> waitingTicketsSeater=new HashMap<Integer,Booking>();
HashMap<Integer,Passenger> passengerDetails=new HashMap<Integer,Passenger>();

public HashMap<Integer, Passenger> getPassengerDetails() {
return passengerDetails;
}

public void setPassengerDetails(HashMap<Integer, Passenger> passengerDetails) {
this.passengerDetails = passengerDetails;
}

public HashMap<Integer, Booking> getBookedTicketsAC() {
return bookedTicketsAC;
}
public void setBookedTicketsAC(HashMap<Integer, Booking> bookedTickets) {
this.bookedTicketsAC = bookedTickets;
}

public int checkAvailability(int coachType) {
int val=0;
switch(coachType)
{
case 1: val=bookedTicketsAC.size()+waitingTicketsAC.size();
break;
case 2: val=bookedTicketsNonAC.size()+waitingTicketsNonAC.size();
break;
case 3: val=bookedTicketsSeater.size()+waitingTicketsSeater.size();
break;
}
return val;
}
public ArrayList<Booking> bookTicket(char from,char to,int coach, int noOfTickets, String name, int age, char gender, String preferedBerth) {
ArrayList<Booking> result=new ArrayList<Booking>();
char berth='l';
switch(coach)
{
case 1: 
if(bookedTicketsAC.size()<2)
{
if(age>=60)
{
berth='l';
}
Booking book=new Booking(bookIdBAC,passId,coach,"L","Confirmed",1000);
Passenger pass=new Passenger(passId,name,age,gender,preferedBerth,noOfTickets,coach,"confirmed",bookIdBAC,from,to);
result.add(book);
bookedTicketsAC.put(bookIdBAC, book);
passengerDetails.put(passId, pass);
bookIdBAC++;
//passId--;
}
else
{
Booking book=new Booking(bookIdWAC,passId,coach,"L","Waiting",1000);
result.add(book);
waitingTicketsAC.put(bookIdWAC, book);
Passenger pass=new Passenger(passId,name,age,gender,preferedBerth,noOfTickets,coach,"Waiting",bookIdWAC,from,to);
passengerDetails.put(passId, pass);
bookIdWAC++;

}
passId++;
break;
case 2:
if(bookedTicketsNonAC.size()<=2)
{
Booking book=new Booking(bookIdBNAC,passId,coach,"L","Confirmed",500);
Passenger pass=new Passenger(passId,name,age,gender,preferedBerth,noOfTickets,coach,"Confirmed",bookIdBNAC,from,to);
result.add(book);
bookedTicketsNonAC.put(bookIdBNAC, book);
passengerDetails.put(passId, pass);
bookIdBNAC++;
}
else
{
Booking book=new Booking(bookIdWNAC,passId,coach,"L","Waiting",500);
result.add(book);
waitingTicketsNonAC.put(bookIdWNAC++, book);
Passenger pass=new Passenger(passId,name,age,gender,preferedBerth,noOfTickets,coach,"Waiting",bookIdWNAC,from,to);
passengerDetails.put(passId, pass);
bookIdWNAC++;
}
passId++;
break;
case 3:
if(bookedTicketsSeater.size()<=60)
{
Booking book=new Booking(bookIdBS,passId,coach,"L","Confirmed",200);
Passenger pass=new Passenger(passId,name,age,gender,preferedBerth,noOfTickets,coach,"confirmed",bookIdBS,from,to);
result.add(book);
bookedTicketsNonAC.put(bookIdBS, book);
passengerDetails.put(passId, pass);
bookIdBS++;
}
else
{
Booking book=new Booking(bookIdWS,passId,coach,"L","Waiting",200);
result.add(book);
waitingTicketsNonAC.put(bookIdWS, book);
Passenger pass=new Passenger(passId,name,age,gender,preferedBerth,noOfTickets,coach,"Waiting",bookIdWS,from,to);
passengerDetails.put(passId, pass);
//passId++;
bookIdWS++;
}
passId++;
break;
}
return result;
// TODO Auto-generated method stub
}

public String checkStatus(int custId) {
String status="invalid id";
Passenger pass=passengerDetails.get(custId);
if(pass!=null)
{
status=pass.getStatus();
}
return status;
}

public Passenger getCustomerDetails(int custId) {
Passenger pass=passengerDetails.get(custId);
System.out.println(pass.getName());
return pass;
}

public int cancelTicket(int custId) {
Passenger pass=passengerDetails.get(custId);
int ticketId=pass.getTicketId();
String status=pass.getStatus();
int coach=pass.getCoachReq();
int amount=0;
if(status.equals("Waiting"))
{
switch(coach)
{
case 1: waitingTicketsAC.remove(ticketId);
amount=1000;
break;
case 2: waitingTicketsNonAC.remove(ticketId);
amount=500;
break;
case 3: waitingTicketsSeater.remove(ticketId);
amount=200;
break;
}
}
else
{
Booking book=null;
int key=0;
switch(coach)
{
case 1: bookedTicketsAC.remove(ticketId);
for(Entry<Integer, Booking> temp:waitingTicketsAC.entrySet())
{
book=temp.getValue();
book.setStatus("Confirmed");
int k=book.getCustId();
Passenger p=passengerDetails.get(k);
p.setStatus("confirmed");
key=temp.getKey();
break;
}
bookedTicketsAC.put(bookIdBAC,book);
bookIdBAC++;
waitingTicketsAC.remove(key);
amount=1000;
break;
case 2: bookedTicketsNonAC.remove(ticketId);
for(Entry<Integer, Booking> temp:waitingTicketsNonAC.entrySet())
{
book=temp.getValue();
book.setStatus("Confirmed");
int k=book.getCustId();
Passenger p=passengerDetails.get(k);
p.setStatus("confirmed");
key=temp.getKey();
break;
}
bookedTicketsAC.put(bookIdBNAC,book);
bookIdBNAC++;
waitingTicketsNonAC.remove(key);
amount=500;
break;
case 3:bookedTicketsSeater.remove(ticketId);
for(Entry<Integer, Booking> temp:waitingTicketsSeater.entrySet())
{
book=temp.getValue();
book.setStatus("Confirmed");
int k=book.getCustId();
Passenger p=passengerDetails.get(k);
p.setStatus("confirmed");
key=temp.getKey();
break;
}
bookedTicketsSeater.put(bookIdBS,book);
bookIdBS++;
amount=200;
waitingTicketsNonAC.remove(key);
break;
}
}
pass.setStatus("Cancelled");
return amount;
}


}

Note: for me they didn't asked about the seat arrangement so i didnt concentrate on it


Solve the string expression

QUESTION: 

Alphabets are inside () and the number -9<=0>=9 which is under{} solve the string according to the sample input output  

Input (z){-2}oho

Output ZZoho

Input ((X){2}(y){3}(z)){2}

Output xxyyyzxxyyyz

Input ((x){2}){0}

output -(nothing should print)


ANSWER

package Practice;


import java.util.*;


class Expressions {


public static void main(String[] args) {

// TODO Auto-generated method stub

String input,output="",temp="",check="";

Scanner scanner=new Scanner(System.in);

input=scanner.nextLine();

Stack <String> stack=new Stack<String>();

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

{

if(input.charAt(i)=='(') {

stack.push("(");

}

else if(input.charAt(i)>='a'&&input.charAt(i)<='z')

{

check+=input.charAt(i);


if(!stack.empty()&&!stack.peek().equals("("))

{

check=stack.pop()+check;

}


stack.push(check);

check="";

}

else if(input.charAt(i)==')')

{

temp=stack.pop();

while(!stack.peek().equals("("))

{

temp=stack.pop()+temp;

}

stack.pop();

stack.push(temp);

}

else if(input.charAt(i)=='{') {

i++;

temp=stack.pop();

if(input.charAt(i)=='-')

{

temp=temp.toUpperCase();

i++;

}

String temp1=temp;

if((input.charAt(i)-48)==0)

temp="";

for(int j=1;j<input.charAt(i)-48;j++)

{

temp+=temp1;

}

i++;

if(input.charAt(i)=='}') {

stack.push(temp);

}

else

{

stack.push("invalid expression");

break;

}

}

}

temp="";

for(int j=0;j<stack.size();j++)

{

temp+=stack.get(j);

}

System.out.println(temp);

}


}


Monday, 11 January 2021

You are given an array of integers with size n .you have to form an array such that all zeros present in array will locate to the last.(move zeros to end of array)

 Input format:

 First line contain size of array 

Second line contain array of elements with separate by space 

Output format: 

print array of integers such that zeros are at last 

sample input: 10 8 0 4 0 2 0 1 3 55 1005

 Sample output: 8 4 2 1 3 55 1005 0 0 0

Program

import java.util.*;

class ZeroMove {


public static void main(String[] args) {

int size,number=0,count=0;

Scanner scanner=new Scanner(System.in);

size=scanner.nextInt();

int array[]=new int[size];

for(int i=0;i<size;i++)

{

array[i]=scanner.nextInt();

}

for(int i=0;i<size;i++)

{

if(array[i]==0)

{

number++;

}

else

{

System.out.println(array[i]+"=="+i+"=="+number);

array[i-number]=array[i];

if(number!=0)

{

array[i]=0;

i-=number;

}

number=0;

}

}

for(int i=0;i<size;i++)

{

System.out.println(array[i]);

}

}


}


Monday, 14 December 2020

Zoho interview Question-Path

Question

Find the Path Given an (m x n) matrix, write a program to traverse the cell and print the values present in the given path. Inclued necessary validation and proper error messages in case of given path is out of bounds. 5 x 5 matrix : {1 2 3 4 5 } (row 1) {6 7 8 9 0 } (row 2) {1 2 3 4 5 } (row 3) {6 7 8 9 0 } (row 4) {1 2 3 4 5 } (row 5) Path Notation : ‘’>” is going right, “v” going down, “<” is going left, “^” is going up


Answer

 import java.util.Scanner;


class FindPath {


public static void main(String[] args) {

int row,col,startRow,startCol,length=0;

String path,output="";

Scanner scanner=new Scanner(System.in);

row=scanner.nextInt();

col=scanner.nextInt();

int matrix[][]=new int[row][col];

for(int i=0;i<row;i++)

{

for(int j=0;j<col;j++)

{

matrix[i][j]=scanner.nextInt();

}

}

startRow=scanner.nextInt();

startCol=scanner.nextInt();

scanner.nextLine();

path=scanner.nextLine();

if(row>startRow-1&&col>startCol-1)

{

startRow--;

startCol--;

output+=matrix[startRow][startCol]+"  ";

for(length=0;length<path.length();length++)

{

if(path.charAt(length)=='>'&&startCol+1<col)

{

output+=matrix[startRow][startCol+1]+"  ";

startCol++;

}

else if(path.charAt(length)=='<'&&startCol-1>=0)

{

output+=matrix[startRow][startCol-1]+"  ";

startCol--;

}

else if(path.charAt(length)=='^'&&startRow-1>=0)

{

output+=matrix[startRow-1][startCol]+"  ";

startRow--;

}

else if((path.charAt(length)=='v'||path.charAt(length)=='V')&&startRow+1<row)

{

output+=matrix[startRow+1][startCol]+"  ";

startRow++;

}

else

{

System.out.println("Invalid path");

output="";

break;

}

}

}

else

{

System.out.println("Invalid path");

}

System.out.println(output);


}


}

Example

inputs

5 5

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

 v>>v<<^>>vv

output


8 3 4 5 0 9 8 3 4 5 0 5 

Zoho Programming question -Locker Problem

 Question

Locker Problem There is a school with 100 students, and correspondingly 100 lockers, all of which start off closed. The first student opens every locker. The second student closes every other locker, starting with the second (2, 4, 6 etc). The third student changes the state of every third locker starting with the third (3,6,9 etc). The fourth would change the status of lockers numbered 4,8,12 etc.,. That is, if the locker is open, it is closed, and if it is closed, it is opened. This continues until all 100 students have passed along the lockers. After the 100th student is done, which lockers are open and which are closed? [Note: program should work for any number of students/lockers]

Logic:

1 4 9 16...

every perfect square will b in open. 


Solution:

import java.util.Scanner;


class Locker {


public static void main(String[] args) {

Scanner scanner=new Scanner(System.in);

int lockerCount,index=2,square=1,open=0;

lockerCount=scanner.nextInt();

while(square<=lockerCount)

{

open++;

square=index*index;

index++;

}

System.out.println("open count"+open+"        close count"+(lockerCount-open));

}


}

Example


100 

open = 10 close = 90 

6456 
open = 80 close = 6376 

Tuesday, 1 December 2020

Zoho 1st round Questions

helloo guys after lockdown this interview process happens through online. i took snap shot of technical questions and i wish to share to all of u... 

1.int main(int argc, char *argv[])

{

  union check

  {

      int i;

      int j;

  };

  union check uij;

  uij.i=10;

  uij.j=20;

  if(uij.i>0){

      printf("%d %d",uij.i,uij.j);

  }else{

      printf("Zoho Interview");

  }

    return 0;

}


Output : 20 20


Since union share the same memory location for both i & j last stored value will be  displayed.

2)int main(int argc, char *argv[])

{

 int i=0;

 if(+(+i--)!=0){ //-1

     i-=i++;  //-1-0

 }else{

     i-=i--;

 }

 printf("%d",i);

    return 0;

}


ans  -1


3)


#include <stdio.h>


int main(int argc, char *argv[]){

int tally;

char p[]="zoho";

char t;

int i,j;

for(i=0,j=strlen(p);i<j;i++){

    t=p[i];

    p[i]=p[j-i];

    p[j-i]=t;

    printf("%c %c \n",t,p[i]);

}

    return 0;

}


ans : 

z

o o 

h h 

o o

4)

int main(int argc, char *argv[]){

int c[]={2.8,3.4,4,6.7,5};

int j, *p=c, *q=c;

for(j=0;j<5;j++){

    printf("%d",*c);//here it called the c[0] 5 times c didnnt get incremented

    ++q;

}

for(j=0;j<5;j++){

    printf("%d",*p); // here p gets incremented

    ++p;

}

    return 0;

}


ans : 2222223465

5)final class GetValues{

    private final double im;

    public GetValues(double im){

        this.im=im;

    

    }

    public String toString(){ // over ridding

        return "(Value is:"+im+")";

    }

}

public class Main

{

public static void main(String[] args) {

    GetValues c=new GetValues(10);

System.out.println(c);// when we call object it will call toString() method

}

}


ans : value is:10.0

6)

public class Main

{

    public static void swap(Integer i,Integer j){

        Integer temp=new Integer(i);

        i=j;

        j=temp;

        System.out.println("Swapped:"+"i="+i+",j="+j);

    }

public static void main(String[] args) {

    Integer i=new Integer(10);

    Integer j=new Integer(20);

    swap(i,j);

System.out.println("final:"+"i="+i++ +",j="+j++);

}

}


Ans : swapped:i=20,j=10

final:i=10,j=20


7)

public class Main

{

public static void main(String[] args) {

    final String testString="Zoho";

    testString.chars().forEach(ch->System.out.print(ch)); //stream gives integer as output

}

   

}


ans : 90111104111

8)

public class Main

{

public static void main(String[] args) {

  int x=0;

  while(1) // is not allowed should contains boolean alone

  {

      x+=1;

      if(x==3){continue;}

      if(x==5)break;

      System.out.println("x:"+(x));

  }

}

   

}


ans : compilation error

9)public class Main

{

public static void main(String[] args) {

  int currentStatus=0;

  stateOne:

  {

  if(8!=15>>1){

      currentStatus=1;

      stateTwo:

      {

          if (5==10>>1){

              currentStatus=2;

              break stateOne;  // break the entire block

          }

          break stateTwo;

      }

      currentStatus=-1;

  }

  }

  System.out.println(currentStatus);

}

}


ans : 2

10)

import java.util.TreeSet;

public class Main

{

public static void main(String[] args) {

TreeSet alphabetStrings=new TreeSet<>(String::compareTo);


alphabetStrings.add("Zebra");

alphabetStrings.add("Apples");

alphabetStrings.add("Ball");

alphabetStrings.add("zebra");

alphabetStrings.add("apple");

alphabetStrings.add("ball");

  System.out.println("AlphabetString Set contains:"+alphabetStrings);

}

}


ans : AlphabetString Set contains:[Apples, Ball, Zebra, apple, ball, zebra]

11)import java.util.*;
public class Main
{
public static void main (String[] args)
{
    int arr1[]={1,2,3};
    int arr2[]=arr1;
    if (Arrays.equals(arr1,arr1.clone()))
    System.out.println("Same");
    else
    System.out.println("Not Same");
    if(Arrays.equals(arr1,arr2))
     System.out.println("Same");
    else
    System.out.println("Not Same");
}
 
}

ans : Same
Same
12)
public class Main
{
public static void main (String[] args)
{
   String str="zoho";
   str.toUpperCase();
   str+="onzoho";
   String string = str.substring(2);
   string = string + str.substring(10);
   System.out.println(string);
}
 
}
ans : hoonzoho

13)
import java.util.stream.*;
public class Main
{
public static void main (String[] args)
{
  Stream.of("Apples","Zebra","apples","zebra")
  .sorted()
  .map(s->{
      return s.toUpperCase();
  })
  .anyMatch(s->{
      System.out.println("String Match Condition:"+s);
      return s.startsWith("Z");
     
  });
}
 
}

ans : String Match Condition:APPLES                                                                                                                                                      
String Match Condition:ZEBRA

14)
class Base extends Exception {}
class Derived extends Base {}
public class Main
{
public static void main (String[] args)
{
  try{
      throw new Derived();
  }
  catch(Base b){    //parent class catch hence child case exception does not required
      System.out.println("Caught base class exception");
  }
  catch(Derived d){
      System.out.println("Caught derived class exception");
  }
}
 
}

Compiler error
15)
class Derived
{
    public void methodInvoke() //privileges public to protected not allowed
    {
        System.out.println("Derived Class");
    }
}
public class Main extends Derived
{
    protected void methodInvoke()
    {
        System.out.println("Test Class");
    }
public static void main (String[] args)
{
  Derived obj=new Main();
  obj.methodInvoke();
}
 
}
compiler error

16)
interface InterF {
    default void implMethod()
    {
        System.out.println("Base Method");
    }
}
class Test implements UbterF {
    public void implMethod() {
        System.out.println("Override Method");
    }
}
public class TestClass
{
    public static void main(String[] args)
    {
        InterF interF=new Test();
        interF.implMethod();
    }
}

ans : Override Method
17)
public class Main
{
    interface InterF{
        int getRes(int a,int b);
    }
    public static int printRes(int a,int b,InterF interF){
        return interF.getRes(b,a);
    }
    public static void main(String[] args)
    {
        InterF interF=(a,b)->a%b;
        System.out.println(printRes(20,30, interF));
    }
}
ANS 10

18)

import java.util.TreeSet;
import java.util.stream.Stream;

public class Main
    {
        public static void main(String args[])
        {
            Stream.of(1,-2,3)
            .sorted((s1,s2)->{
                System.out.printf("Sort Compare:%s;%s\n",s1,s2);
                return s1.compareTo(s2);
            
            })
            .filter(s->{
                return s>0;
                })
                .map(s->{
                    return s.doubleValue();
                })
                .forEach(s->System.out.println("Printed Val:"+s));
    }
}

ans : 

Sort Compare:-2;1                                                                                                                                                                  
Sort Compare:3;-2                                                                                                                                                                  
Sort Compare:3;1                                                                                                                                                                   
Printed Val:1.0                                                                                                                                                                    
Printed Val:3.0

19)

class Base{
    Base(){
        System.out.println("Base");
    }
    public void Print() {
        System.out.println("BasePrint");
    }
}
class Derived extends Base {
    public void Print() {
        System.out.println("DerivedPrint");
    }
}
class Main {
    public static void DoPrint(Base o) {
        o.Print();
    }
    public static void main(String[] args) {
        Base y=new Derived();
        Derived z=new Derived();
        DoPrint(y);
        DoPrint(z);
    }
}

ans : 

Base                                                                                                                                                                               
Base                                                                                                                                                                               
DerivedPrint                                                                                                                                                                       
DerivedPrint
220)
import java.util.*;
class Variable implements Comparable<Variable>{
    int id;
    int quantity;
    public Variable(int id,int quantity){
        this.id=id;this.quantity=quantity;
    }
    public int compareTo(Variable b){
        if(id>b.id){
            return -1;
        }else if(id<b.id){
            return 1;
        }else{
            return 0;
        
        }
    }
}
public class Main {
    public static void main(String[] args) {
Queue<Variable> queue=new PriorityQueue();
        Variable v1=new Variable(1,100);
        Variable v2=new Variable(2,1000);
        Variable v3=new Variable(3,500);
        Variable v4=new Variable(4,10);
        queue.add(v1);
        queue.add(v2);
        queue.add(v3);
        queue.add(v4);
        queue.remove();
        System.out.println(queue.peek().id+":"+queue.peek().quantity);
    }
}

ans : 3:500
21)

class PrivClass
{
    private PrivClass()
    {
        System.out.println("PrivClass called");
    }
    protected static PrivClass create()
    {
        PrivClass obj = new PrivClass();
        return obj;
    }
    public void myMethod()
    {
        System.out.println("PrivClass Method called");
    }
}
public class Main
{
    public static void main(String[] args)
    {
        try{
            PrivClass obj=PrivClass.create();
            obj.myMethod();
        }catch (Exception e){
        System.out.println("PrivClass Creation Error");
    }
}
}

ans : 

PrivClass called                                                                                                                                                                   
PrivClass Method called 
22)

import java.io.*;
public class Main {
    {
        public static void main(String[] args)
        {
            try
            {
                MyVariable object1=new MyVariable(Integer.MAX_VALUE+1);
                FileOutputStream fos=new FileOutputStream("serial");
                ObjectOutputStream oos=new ObjectOutputStream(fos);
                oos.writeObject(object1);
                oos.flush();
                oos.close();
            }
            catch(Exception e)
            {
                System.exit(0);
            }
            try
            {
                MyVariable object2;
                FileInputStream fis=new FileInputStream("serial");
                ObjectInputStream ois=new ObjectInputStream(fis);
                object2=(MyVariable)ois.readObject();
                ois.close();
                System.out.println(object2);
            }
            catch (Exception e)
            {
                System.exit(0);
            }
        }
    }
    class MyVariable implements Serializable
    {
        int i;
        MyVariable (int i)
        {
            this.i=i;
        }
        public String toString() {
            return ""+(i/1000)+"";
        }
    }
}

ans : -2147483
23)

class Test
{
    int a;
    
    Test cloning()
    {
        try
        {
            return (Test) super.clone();
        }
        catch(CloneNotSupportedException e)
        {
            System.out.println("CloneNotSupportedException is caught");
            return this;
        }
    }
    public String toString() {
        return a+"";
    }
}
class Main
{
    public static void main(String args[])
    {
        Test obj1=new Test();
        Test obj2;
        obj1.a=10;
        obj2=obj1.cloning();
        obj2.a=20;
        System.out.println("obj1.a="+obj1.a+","+"obj2.a="+obj2.a);
    }
}

ans : 


CloneNotSupportedException is caught                                                                                                                                               
obj1.a=20,obj2.a=20

Friday, 17 May 2019

Write a program to sort the elements in odd positions in descending order and elements in

ascending order


Eg 1: Input: 13,2 4,15,12,10,5

        Output: 13,2,12,10,5,15,4

Eg 2: Input: 1,2,3,4,5,6,7,8,9

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


CODE

#include<conio.h>
#include<string.h>
void main()
{
int i,n,t,a[100];

scanf("%d",&n);

for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}


for(i=0;i<n;i+=2)
{
if(i%2==0)
{
if((a[i]<a[i+2])&&((i+2)<n))
{
t=a[i];
a[i]=a[i+2];

a[i+2]=t;
}
}
else
{
if((a[i]>a[i+2])&&((i+2)<n))
{
t=a[i];
a[i]=a[i+2];
a[i+2]=t;
}
}
}
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}


}



 Find if a String2 is substring of String1. If it is, return the index of the first occurrence. else return -1.
Eg 1:Input:
        String 1: test123string
         String 2: 123
        Output: 4
Eg 2: Input:
        String 1: testing12
        String 2: 1234 
        Output: -1

#include<conio.h>
#include<string.h>
void main()
{
int i,j=0,r=0,m,n;
char a[100],b[100];
scanf("%d,%d",&n,&m);

gets(a);
gets(b);

n=strlen(a);
m=strlen(b);


for(i=0;i<n;i++)
{
if(a[i]==b[j])
{
r=i;
i++;
for(j=1;j<m;j++)
{
if(a[i]==b[j])
{
i++;
}
else
{
r=-1;
j=m;
}
}
}
else
{
if(r==0)
{
r=-1;
}
}

j=0;

}
printf("%d",r);


}