Department of Computer Science and Engineering: Lab Manual

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

Department of Computer Science and

Engineering

B.Tech (CSE,NS,DA) / M.Tech (SWE)

CS1004 – Problem Solving Using Java

Lab Manual
2018-19
LIST OF EXPERIMENTS

1. Problems with Flow chart

2. Input and Output Statements

3. Operators and Expressions

4. Conditional Statements

5. Looping Constructs

6. Functions

7. Arrays

8. Strings

9. Files

10.Classes
GRADING POLICY

Experiment No. Marks Weightage


1 100
2 100
3 100
4 100
5 100
Average mark
6 100 converted
20 Marks
7 100
8 100
9 100
10 100
Average 100
1

Ex No. 1 PROBLEMS WITH FLOW CHART

Flow chart basic components

Problem 1:

Draw a flow chart to find the number of digits in a given number.

Input Format:
Input consists of an integer.

Output Format:
Output consists of a single line. Refer sample output for details.

Sample Input 1:
42

Sample Output 1:
The number of digits in 42 is 2
2

Problem 2:

Draw a flow chart to convert decimal into binary.

Input Format:
Input consists of an integer which corresponds to n.

Output Format:
Refer Sample Input and Output for exact formatting specifications.

Sample Input 1 :
65
Sample output 1 :
1000001

Sample Input 2 :
82
Sample output 2 :
1010010
3
4

Ex No. 2 INPUT AND OUTPUT STATEMENTS

In Java, 3 streams are created for us automatically. All these streams are attached with
the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Scanner Class:

Scanner is a class in java.util package used for obtaining the input of the primitive types like int,
double etc. and strings. It is the easiest way to read input in a Java program, though not very
efficient if you want an input method for scenarios where time is a constraint like in competitive
programming.

• To create an object of Scanner class, we usually pass the predefined object System.in,
which represents the standard input stream. We may pass an object of class File if we
want to read input from a file.
• To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For
example, to read a value of type short, we can use nextShort()
• To read strings, we use nextLine().
• To read a single character, we use next().charAt(0). next() function returns the next
token/word in the input as a string and charAt(0) funtion returns the first character in that
string.

Problem 1: Event Details

Be it a last minute get together, a birthday party or corporate events, the "Pine Tree" Event
Management Company helps you plan and execute it better and faster. Nikhil, the founder of the
company wanted the Amphi Event Management System to get and display the event details from
his Customers for every new order of the Company.

Write a program that will get the input of the event details like name of the event, type of the
event, number of people expected, a string value (Y/N) telling whether the event is going to be a
paid entry and the projected expenses (in lakhs) for the event. The program should then display
the input values as a formatted output.

Input Format:
First input is a string that corresponds to the name of the event. Assume the maximum length of
the string as 50.
Second input is a string that corresponds to the type of the event. Assume the maximum length
of the string as 50.
5

Third input is an integer that corresponds to the number of people expected for the event.
Fourth input is a character that corresponds to Y/N telling whether the event is going to be a paid
entry or not.
Fifth input is a double value that corresponds to the projected expenses (in lakhs) for the event.

Output Format:
Output should display the event details as given in the sample output.
All double values need to be displayed correct to 1 decimal place
Refer sample input and output for formatting specifications.
[All text in bold corresponds to input and rest corresponds to output.]

Sample Input and Output:


Enter the name of the event
Food Fest 2017
Enter the type of the event
Public
Enter the number of people expected
5000
Is it a paid entry? (Type Y or N)
N
Enter the projected expenses (in lakhs) for this event
5.7
Event Name : Food Fest 2017
Event Type : Public
Expected Count : 5000
Paid Entry : N
Projected Expense : 5.7L
Test Cases:

SNo Name Input Output Visibility


1 T1 Food Fest 2017 Enter the name of the event Public
Public Enter the type of the event
5000 Enter the number of people expected
N Is it a paid entry? (Type Y or N)
5.7 Enter the projected expenses (in lakhs) for this event
Event Name : Food Fest 2017
Event Type : Public
Expected Count : 5000
Paid Entry : N
Projected Expense : 5.7L
2 T2 Big Boss 2017 Enter the name of the event Private
Private Enter the type of the event
25 Enter the number of people expected
N Is it a paid entry? (Type Y or N)
500.00 Enter the projected expenses (in lakhs) for this event
Event Name : Big Boss 2017
Event Type : Private
Expected Count : 25
Paid Entry : N
Projected Expense : 500.0L
6

3 T3 Seminars 2017 Enter the name of the event Private


Public Enter the type of the event
5000 Enter the number of people expected
Y Is it a paid entry? (Type Y or N)
1.505 Enter the projected expenses (in lakhs) for this event
Event Name : Seminars 2017
Event Type : Public
Expected Count : 5000
Paid Entry : Y
Projected Expense : 1.5L

Program :

import java.util.*;
class Main {
public static void main(String args[]) {
System.out.println("Enter the name of the event");
Scanner s= new Scanner(System.in);
String st=s.nextLine();
System.out.println("Enter the type of the event");
String str=s.nextLine();
System.out.println("Enter the number of people expected");
int n=s.nextInt();
System.out.println("Is it a paid entry? (Type Y or N)");
char c=s.next().charAt(0);
System.out.println("Enter the projected expenses (in lakhs) for this event");
float f=s.nextFloat();
System.out.println("Event Name : " +st+ "\nEvent Type : " +str+ "\nExpected Count
: " +n+ "\nPaid Entry : "+c);
System.out.printf("Projected Expense : %.1fL",f);

}
}

Problem 2: Wrapper Class – Integer I

This program is to illustrate Integer Wrapper class.

Write a program that accepts a “Integer” class type value as input and invokes some of the
methods defined in the Integer Wrapper class.

Refer sample input and output. All functions should be performed using the methods defined in
the Integer class.
7

Input and Output Format:

Refer sample input and output for formatting specifications.


All text in bold corresponds to input and the rest corresponds to output.

Sample Input and Output :

Enter an integer
540
The binary equivalent of 540 is 1000011100
The hexadecimal equivalent of 540 is 21c
The octal equivalent of 540 is 1034
Byte value of 540 is 28
Short value of 540 is 540
Long value of 540 is 540
Float value of 540 is 540.0
Double value of 540 is 540.0

Test Cases:

SNo Name Input Output Visibility


1 T3 40000 Enter an integer Private
The binary equivalent of 40000 is 1001110001000000
The hexadecimal equivalent of 40000 is 9c40
The octal equivalent of 40000 is 116100
Byte value of 40000 is 64
Short value of 40000 is -25536
Long value of 40000 is 40000
Float value of 40000 is 40000.0
Double value of 40000 is 40000.0

2 T2 1101 Enter an integer Private


The binary equivalent of 1101 is 10001001101
The hexadecimal equivalent of 1101 is 44d
The octal equivalent of 1101 is 2115
Byte value of 1101 is 77
Short value of 1101 is 1101
Long value of 1101 is 1101
Float value of 1101 is 1101.0
Double value of 1101 is 1101.0
8

3 T1 540 Enter an integer Public


The binary equivalent of 540 is 1000011100
The hexadecimal equivalent of 540 is 21c
The octal equivalent of 540 is 1034
Byte value of 540 is 28
Short value of 540 is 540
Long value of 540 is 540
Float value of 540 is 540.0
Double value of 540 is 540.0

Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter an integer");
int n= sc.nextInt();
long b;
int n1=n,n2=n,n3=n;
int r;
long i=1,sum=0;
while(n1>0)
{
r=n1%2;
sum=sum+(r*i);
i=i*10;
n1=n1/2;
}
System.out.println("The binary equivalent of " +n+ " is "+sum);
char ch[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
int rem;
String hd="";
while (n2>0)
{rem=n2%16;
hd=ch[rem]+hd;
n2=n2/16;
}
System.out.println("The hexadecimal equivalent of "+n+" is "+hd);
long o;
int r1;
long i1=1,sum1=0;
while (n3>0)
{
r1=n3%8;
sum1=sum1+(r1*i1);
i1=i1*10;
n3=n3/8;
}
9

System.out.println("The octal equivalent of "+n+" is "+sum1);


byte by=(byte)n;
System.out.println("Byte value of " +n+" is "+by);
short s=(short)n;
System.out.println("Short value of " +n+" is "+s);
long l=(long)n;
System.out.println("Long value of " +n+" is "+l);
float f=(float)n;
System.out.println("Float value of " +n+" is "+f);
double d= (double)n;
System.out.println("Double value of " +n+" is "+d);
}
}
10

Ex No. 3 OPERATORS AND EXPRESSIONS

Operators in java

Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in java which are given below:

• Unary Operator,
• Arithmetic Operator,
• Shift Operator,
• Relational Operator,
• Bitwise Operator,
• Logical Operator,
• Ternary Operator and
• Assignment Operator.

Operator Type Category Precedence


Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
11

Problem 1: Pranav and Change


Pranav, an enthusiastic kid visited the "Fun Fair 2017" along with his family. His father wanted
him to purchase entry tickets from the counter for his family members. Being a little kid, he is just
learning to understand about units of money. Pranav has paid some amount of money for the
tickets but he wants your help to give him back the change of Rs. N using minimum number of
rupee notes.

Consider a currency system in which there are notes of seven denominations, namely, Rs. 1, Rs.
2, Rs. 5, Rs. 10, Rs. 50, Rs. 100. If the change given to Pranav Rs. N is input, write a program to
computer smallest number of notes that will combine to give Rs. N.

Note:
Refer to problem specifications.

Input Format:
First line of the input is an integer N, the change to be given to Pranav.

Output Format:
Output should display the the smallest number of notes that will combine to give N.
Refer sample input and output for formatting specifications.

Sample Input 1:
1200

Sample Output1:
12

Sample Input 2:
242

Sample Output2:
7

Test Cases:

SNo Name Input Output Visibility


1 T8 5 1 Private
2 T7 2 1 Private
3 T2 242 7 Public
4 T5 15 2 Private
5 T11 660 8 Private
6 T10 657 9 Private
7 T9 10 1 Private
8 T1 1200 12 Public
12

9 T4 250 3 Private
10 T3 500 5 Private
11 T6 100 1 Private

Program:

import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int rupees[]={100,50,10,5,2,1};
int amount=sc.nextInt();
int count=0;
for (int i=0;i<rupees.length;i++)
{
int c=amount/rupees[i];
amount=amount-c*rupees[i];
count=count+c;
}
System.out.println(count);

}
}

Problem 2: WonderWorks Magic Show

The Magic Castle, the home of the Academy of Magical Arts at California has organized the
great ‘WonderWorks Magic Show’. 3 renowned magicians were invited to mystify and thrill the
crowd with their world’s spectacular magic tricks. At the end of each of the 3 magicians’ shows,
the audience were requested to give their feedback in a scale of 1 to 10. Number of people who
watched each show and the average feedback rating of each show is known. Write a program to
find the average feedback rating of the WonderWorks Magic show.

Input Format:
First line of the input is an integer value that corresponds to the number of people who watched
show 1.
Second line of the input is a float value that corresponds to the average rating of show 1.
Third line of the input is an integer value that corresponds to the number of people who watched
show 2.
Fourth line of the input is a float value that corresponds to the average rating of show 2.
Fifth line of the input is an integer value that corresponds to the number of people who watched
show 3.
Sixth line of the input is a float value that corresponds to the average rating of show 3.

Output Format:
Output should display the overall average rating for the show. Display the rating correct to 2
decimal places.
13

Refer sample input and output for formatting specifications.


[All text in bold corresponds to input and rest corresponds to output.]

Sample Input and Output:


Enter the number of people who watched show 1
400
Enter the average rating for show 1
9.8
Enter the number of people who watched show 2
500
Enter the average rating for show 2
9.6
Enter the number of people who watched show 3
100
Enter the average rating for show 3
5
The overall average rating for the show is 9.22

Test Cases:
SNo Name Input Output Visibility
1 T4 50 Enter the number of people who watched show 1 Private
2 Enter the average rating for show 1
34 Enter the number of people who watched show 2
2.7 Enter the average rating for show 2
15 Enter the number of people who watched show 3
1 Enter the average rating for show 3
The overall average rating for the show is 2.09
2 T3 1000 Enter the number of people who watched show 1 Private
90.8 Enter the average rating for show 1
500 Enter the number of people who watched show 2
78.0 Enter the average rating for show 2
2000 Enter the number of people who watched show 3
67.9 Enter the average rating for show 3
The overall average rating for the show is 75.89
3 T2 200 Enter the number of people who watched show 1 Private
5.8 Enter the average rating for show 1
100 Enter the number of people who watched show 2
4 Enter the average rating for show 2
300 Enter the number of people who watched show 3
9.1 Enter the average rating for show 3
The overall average rating for the show is 7.15
4 T1 400 Enter the number of people who watched show 1 Public
9.8 Enter the average rating for show 1
500 Enter the number of people who watched show 2
9.6 Enter the average rating for show 2
100 Enter the number of people who watched show 3
5 Enter the average rating for show 3
The overall average rating for the show is 9.22
14

Program :
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of people who watched show 1");
int a=sc.nextInt();
System.out.println("Enter the average rating for show 1");
double a1=sc.nextDouble();
System.out.println("Enter the number of people who watched show 2");
int b=sc.nextInt();
System.out.println("Enter the average rating for show 2");
double b1=sc.nextDouble();
System.out.println("Enter the number of people who watched show 3");
int c=sc.nextInt();
System.out.println("Enter the average rating for show 3");
double c1=sc.nextDouble();
double r=((a*a1)+(b*b1)+(c*c1))/(a+b+c);
System.out.printf("The overall average rating for the show is %.2f",r);
}}

Problem 3: PLACING THE FLAG POST

The shape of the college ground is Square. For the Independence day Flag Hoisting Function, it
has been decided to place the flag post at the exact center of the ground. Can you please help
them in placing the flag post at the exact center?

Given the coordinates of the left bottom vertex of the square ground and the length of the side,
you need to write a program to determine the coordinates of the centre of the ground.

[Assumption --- Length of the side is always even]

Input Format:
Input consists of 3 integers. The first integer corresponds to the x-coordinate of the left bottom
vertex. The second integer corresponds to the y-coordinate of the left bottom vertex. The third
integer corresponds to the length of the square.

Output Format:
Refer Sample Input and Output for exact formatting specifications.

Sample Input and Output:


[All text in bold corresponds to input and the rest corresponds to output]
Enter the x-coordinate of the left bottom vertex
4
Enter the y-coordinate of the left bottom vertex
O
Enter the length of a side
8
The centre of the ground is at (8,4)
15

Test cases:

SNo Name Input Output Visibility


1 T1 4 Enter the x-coordinate of the left bottom vertex Public
Enter the y-coordinate of the left bottom vertex
8 Enter the length of a side
The centre of the ground is at (8,4)

2 T2 10 Enter the x-coordinate of the left bottom vertex Private


30 Enter the y-coordinate of the left bottom vertex
16 Enter the length of a side
The centre of the ground is at (18,38)

Program:

import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the x-coordinate of the left bottom vertex");
int a=sc.nextInt();
System.out.println("Enter the y-coordinate of the left bottom vertex");
int b=sc.nextInt();
System.out.println("Enter the length of a side");
int c=sc.nextInt();
int x=(a+(a+c))/2;
int y=(b+(b+c))/2;
System.out.println("The centre of the ground is at (" +x+","+y+")");

}
}
16

Ex No. 4 CONDITIONAL STATEMENTS

Java if and if-else syntax:


...
if ( condition ) // The condition is a boolean expression
statement; // Executes if condition is true
// No enclosing block is required when only one statement
[ else {
statement; // Executes if condition is false
statement; // Enclosing block is necessary when more than one statement
}
]
...

The conditional (ternary) operator :

This operator is frequently used as a shortcut for the if-else statement.


Code example:

// First the syntax


// (expression1) ? (expression2) : (expression3)
...
int z = (x < y) ? x : y;
// When x > y then z=x else z=y
...

Java switch statements.

• The switch statement can have a number of possible execution paths.


• A switch works with the byte, char, short, and int primitive data types.
• It works with enum type (java.lang.Enum).
• It also works with java.lang.String class and a few special classes that wrap certain
primitive types: java.lang.Character, java.lang.Byte, java.lang.Short, and java.lang.Integer.
• Must use break to terminate each branch.
• Each case will be tested and if none results in a true condition an optional default path
with statements will be executed.

Switch syntax:
...
for ( initialization; condition; incrementor )
statement;
switch ( int expression )
{
case int constantExpression :
statement; break;
17

[ case int constantExpression


statement; break; ]
...
[ default :
statement; ]
}
...

Java break/continue statements.

A break causes Java to stop the current block statement and resume execution after it:
...
while( true ) {
if ( condition( ) )
break;
}
// after while
...

A continue statement causes loops to move on to their next iteration by returning to the point
where they check their condition:

...
for( int i=0; i < 100; i++ ) {
if ( i == 33 )
continue;
System.out.println( i );
}

...

Problem 1: Calendar Quiz

Super Quiz Bee is a famous quiz Competition that tests students on a wide variety of academic
subjects. This week’s participants were kids of age 12 to 15 and the quiz questions were based on
Gregorian calendar.

In the first round of the competition, the Host of the event told the participants that it was Monday on
the date 01/01/2001. Later he questioned each one of the participant what would be the day on the
1st January, giving them a particular year. Write a program to help the Host validate the answers
given by the participants.

Input Format:
The first line contains an integer that corresponds to a year.
18

Output Format:
Output the day on the 1st January of that given year.
Refer sample input and output for formatting specifications.

Sample Input 1:
1994

Sample Output 1:
Saturday

Sample Input 2:
2014

Sample Output 2:
Wednesday

Test Cases:

SNo Name Input Output Visibility


1 T2 2014 Wednesday Public
2 T6 2010 Friday Private
3 T3 1991 Tuesday Private
4 T1 1994 Saturday Public
5 T7 2000 Saturday Private
6 T5 2017 Sunday Private
7 T4 2004 Thursday Private
8 T8 1990 Monday Private

Program :
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int y=sc.nextInt();
int i,s4,d=0;
if(y>0)
{
if (y<2001)
{
for(i=2000;i>=y;i--)
{
if((i%400==0)||(i%4==0)&&(i%100!=0))
d=d+2;
else
d=d+1;
}
s4=d%7;
19

if (s4==6)
System.out.println("Tuesday");
else if(s4==5)
System.out.println("Wednesday");
else if(s4==4)
System.out.println("Thursday");
else if(s4==3)
System.out.println("Friday");
else if(s4==2)
System.out.println("Saturday");
else if(s4==1)
System.out.println("Sunday");
else
System.out.println("Monday");
}
else if (y>2001)
{
for(i=2002;i<=y;i++)
{
if((i%400==0)||(i%4==0)&&(i%100!=0))
d=d+2;
else
d=d+1;
}
if((y%400==0)||(y%4==0)&&(y%100!=0))
d--;
s4=d%7;
if (s4==1)
System.out.println("Tuesday");
else if(s4==2)
System.out.println("Wednesday");
else if(s4==3)
System.out.println("Thursday");
else if(s4==4)
System.out.println("Friday");
else if(s4==5)
System.out.println("Saturday");
else if(s4==6)
System.out.println("Sunday");
else
System.out.println("Monday");
}
else
System.out.println("Monday");
}

}
}
20

Problem 2: Grades of Rides


“AquaticaCarnival” is the most successful event dedicated to children and families. The Event
has more than 20 rides for children and adults and the organizers always ensure not to
compromise on the safety of the visitors.
To ensure the safety of the rides, the organizers have graded the rides in the fair according to the
following conditions:
Hurl Factor must be greater than 50.
Spin Factor must be greater than 60.
Speed factor must be greater than 100.

The grades are as follows:


Grade is 10 if all three conditions are met.
Grade is 9 if conditions (i) and (ii) are met.
Grade is 8 if conditions (ii) and (iii) are met.
Grade is 7 if conditions (i) and (iii) are met.
Garde is 6 if only one condition is met.
Grade is 5 if none of three conditions are met.
Write a program display the grade of the rides, given the values of hurl factor, spin factor and
speed factor of the ride under consideration.

Input Format:
First line of the input consists of 3 integers that gives the Hurl Factor, Spin Factor and Speed
Factor of the ride, each separated by a space.

Output Format:
Output should display the grade of the ride depending on Conditions.
Refer sample input and output for formatting specifications.

Sample Input 1:
51 89 150

Sample Output 1:
10

Sample Input 2:
45 69 102

Sample Output 2:
8

Test Cases:

SNo Name Input Output Visibility


1 T11 51 61 101 10 Private
2 T7 50 60 100 5 Private
3 T3 60 80 90 9 Private
21

4 T12 56 60 108 7 Private


5 T4 60 40 200 7 Private
6 T9 60 60 100 6 Private
7 T10 45 65 100 6 Private
8 T2 45 69 102 8 Public
9 T1 51 89 150 10 Public
10 T6 10 20 30 5 Private
11 T5 10 40 101 6 Private
12 T8 50 60 105 6 Private

Program:

import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n1=sc.nextInt();
int n2=sc.nextInt();
int n3=sc.nextInt();
if (n1>50 && n2>60 && n3>100)
System.out.println("10");
else if(n1>50 && n2>60)
System.out.println("9");
else if(n2>60 && n3>100)
System.out.println("8");
else if(n1>50 && n3>100)
System.out.println("7");
else if(n1>50 || n2>60 ||n3>100)
System.out.println("6");
else
System.out.println("5");

}
}

Problem 3: Help Lost Child


Harry, a little boy was accompanied by his Dad to visit the "Aquatica Carnival". The event saw a
large crowd and the Security Chiefs found it hard to control them. Very regretfully, Harry got lost
and was seen extremely worried. He wanted to reach back home as soon as possible. He was
standing currently at coordinates (x1, y1) in 2-D plane. His home is at coordinates (x2, y2).

Please help him by giving a command by telling the direction in which he should go, so as to
reach his home. If you give him a direction, he will keep moving in that direction till he reaches
home. There are four possible directions you can give as command - "left", "right", "up", "down".
22

It might be possible that you can't instruct Harry in such a way that he reaches his home. In that
case, display the output as "sad".

Input Format:
First line of the input contains four space separated integers x1, y1, x2, y2.

Output Format:
Output a single line containing "left" or "right" or "up" or "down" or "sad" (without quotes).
Refer sample input and output for formatting specifications.

Sample Input 1:
0010

Sample Output 1:
right

Sample Input 2:
0011

Sample Output 2:
sad

Test cases:

SNo Name Input Output Visibility


1 T6 100 100 100 200 up Private
2 T9 0 10 1 10 right Private
3 T8 100 200 100 100 down Private
4 T4 5 4 5 10 up Private
5 T7 10 20 30 40 sad Private
6 T5 10 5 4 5 left Private
7 T2 0001 up Private
8 T1 0010 right Public
9 T3 0011 sad Public

Program :

import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int x1=sc.nextInt();
int y1=sc.nextInt();
int x2=sc.nextInt();
int y2=sc.nextInt();
23

if (x1==x2 || y1==y2)
{ if (x1>x2)
System.out.println ("left");
else if (x2>x1)
System.out.println("right");
else if (y1>y2)
System.out.println("down");
else if (y2>y1)
System.out.println("up");
}
else
System.out.println("sad");

}
}
24

Ex No. 5 LOOPING CONSTRUCTS

Java while and do-while loop:

while will perform a logical test, and if this results in a true condition execute subsequent
statements bounded by {} brackets.
do while will first execute statements bounded by {} brackets and than perform a logical test. If
the logical test results in a true condition execute the statements bounded by {} brackets again.

Java while and do-while loop syntax::

// The while syntax


while ( condition ){
statement; // Statements executes as long as condition is true
statement;
}
// This is the do-while syntax
do {
statement; // do-while loop always executes
statement; // its statement body at least once.
statement; // Statements executes as long as condition is true
}
while ( condition );

Java for loop.

• A for loop is divided into three parts, an initialization part, a conditional part and an
increment part
• You should sett all initial values in the initialization part of the loop.
• A true from the condition part will execute subsequent statements bounded by {} brackets.
A false from the condition part will end the loop.
• For each loop the increment part will be executed.

Java for loop syntax:


...
for ( initialization; condition; incrementor )
statement;
// Initialization are limited to the scope of the for statement
// The condition is a boolean expression (if true the body is executed)
// Following each execution of the body, the incrementor expressions are evaluated.
...
25

Problem 1: Peter and Casino

Hotel Royal Gardenia has arranged for an elite business party for the lead industrialists and
celebrities of the City. Followed by a dinner buffet, the Event coordinators planned for some
casino game events for the high-toned crowd. Peter was a visitor at the party and he takes some
number of rubles to the casino with the intention of becoming rich. He plays three machines in
turn. Unknown to him, the machines are entirely predictable. Each play costs one ruble. The first
machine pays 20 rubles every 25th time it is played; the second machine pays 80 rubles every
120th time it is played; the third pays 8 rubles every 12th time it is played.
Given the number of rubles with Peter initially (there will be at least one and fewer than 1000),
and the number of times each machine has been played since it last paid, write a program that
calculates the number of times Peter plays until he goes broke.

Input Format:
First line of the input is an integer that corresponds to the number of rubles with Peter initially.
Next 3 lines of the input is an integer that corresponds to the number of times each machine has
been played since it last paid.

Output Format:
Output a single line that gives the number of times Peter plays until he goes broke.
Refer sample input and output for formatting specifications.

Sample Input 1:
48
3
12
4

Sample Output 1:
Peter plays 56 times before going broke

Sample Input 2:
35
10
30
9

Sample Output 2:
Peter plays 71 times before going broke
26

Test Cases:

SNo Name Input Output Visibility


1 T6 100 Peter plays 360 times before going broke Private
18
75
5
2 T2 35 Peter plays 71 times before going broke Public
10
30
9
3 T3 24 Peter plays 60 times before going broke Private
20
15
10
4 T4 25 Peter plays 61 times before going broke Private
22
20
10
5 T1 48 Peter plays 56 times before going broke Public
3
12
4
6 T5 10 Peter plays 18 times before going broke Private
8
20
11

Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a1=sc.nextInt();
int a2=sc.nextInt();
int a3=sc.nextInt();
int b1=25,b2=120,b3=12,c1=20,c2=80,c3=8,i,c=0;
while (n>0)
{for(i=1;i<=3;i++)
{
switch(i)

{
case 1:
if(n>0)
{
++c;
27

n--;
if (++a1%b1==0)
n+=c1;}
break;

case 2:
if(n>0)
{
++c;
n--;
if (++a2%b2==0)
n+=c2;}
break;

case 3:
if(n>0)
{
++c;
n--;
if (++a3%b3==0)
n+=c3;}
break;
}

}
System.out.println("Peter plays "+c+" times before going broke");
}
}

Problem 2: Charity Dinner

WeCanNGO Trust is organizing a charity dinner at St. John’s College. Since older students are
both wiser and richer, the members of the trust decide that the price of each ticket will be based
on how many years the students have been in the school. A first year student will buy a PINK
ticket, a second year student will buy a GREEN ticket, a third year student will buy a RED ticket,
and a fourth year student will buy an ORANGE ticket.

Assume that all tickets are sold. Each colour of ticket is uniquely priced. Write a program to
output all combinations of tickets that produce exactly the desired amount to be raised. The
combinations may appear in any order. Also display the total number of combinations found and
the smallest number of tickets to be printed to raise the desired amount so that printing cost is
minimized.
28

Input Format:
First 4 lines of the input correspond to the cost of a PINK, GREEN, RED, ORANGE ticket (in the
exact order).
Last line of the input corresponds to the exact amount of money to be raised by selling tickets.

Output Format:
Output all combinations of tickets that produce exactly the desired amount to be raised. The
combinations may appear in any order. Output the total number of combinations found. Output
the smallest number of tickets to print to raise the desired amount so that printing cost is
minimized.
Refer sample input and output for formatting specifications.

Sample Input 1:
1
2
3
4
3

Sample Output 1:
# of PINK is 0 # of GREEN is 0 # of RED is 1 # of ORANGE is 0
# of PINK is 1 # of GREEN is 1 # of RED is 0 # of ORANGE is 0
# of PINK is 3 # of GREEN is 0 # of RED is 0 # of ORANGE is 0
Total combinations is 3
Minimum number of tickets to print is 1

Sample Input 2:
1
2
4
3
4

Sample Output 2:
# of PINK is 0 # of GREEN is 0 # of RED is 1 # of ORANGE is 0
# of PINK is 0 # of GREEN is 2 # of RED is 0 # of ORANGE is 0
# of PINK is 1 # of GREEN is 0 # of RED is 0 # of ORANGE is 1
# of PINK is 2 # of GREEN is 1 # of RED is 0 # of ORANGE is 0
# of PINK is 4 # of GREEN is 0 # of RED is 0 # of ORANGE is 0
Total combinations is 5
Minimum number of tickets to print is 1
29

Test cases:

SNo Name Input Output Visibility


1 T3 5 # of PINK is 0 # of GREEN is 0 # of RED is 0 # of ORANGE is 2 Private
4 Total combinations is 1
7 Minimum number of tickets to print is 2
3
6
2 T2 1 # of PINK is 0 # of GREEN is 0 # of RED is 1 # of ORANGE is 0 Public
2 # of PINK is 0 # of GREEN is 2 # of RED is 0 # of ORANGE is 0
4 # of PINK is 1 # of GREEN is 0 # of RED is 0 # of ORANGE is 1
3 # of PINK is 2 # of GREEN is 1 # of RED is 0 # of ORANGE is 0
4 # of PINK is 4 # of GREEN is 0 # of RED is 0 # of ORANGE is 0
Total combinations is 5
Minimum number of tickets to print is 1
3 T1 1 # of PINK is 0 # of GREEN is 0 # of RED is 1 # of ORANGE is 0 Public
2 # of PINK is 1 # of GREEN is 1 # of RED is 0 # of ORANGE is 0
3 # of PINK is 3 # of GREEN is 0 # of RED is 0 # of ORANGE is 0
4 Total combinations is 3
3 Minimum number of tickets to print is 1
4 T4 2 # of PINK is 0 # of GREEN is 0 # of RED is 0 # of ORANGE is 1 Private
4 # of PINK is 0 # of GREEN is 0 # of RED is 3 # of ORANGE is 0
1 # of PINK is 1 # of GREEN is 0 # of RED is 1 # of ORANGE is 0
3 Total combinations is 3
3 Minimum number of tickets to print is 1
5 T5 2 # of PINK is 0 # of GREEN is 0 # of RED is 0 # of ORANGE is 1 Private
2 # of PINK is 0 # of GREEN is 0 # of RED is 1 # of ORANGE is 0
2 # of PINK is 0 # of GREEN is 1 # of RED is 0 # of ORANGE is 0
2 # of PINK is 1 # of GREEN is 0 # of RED is 0 # of ORANGE is 0
2 Total combinations is 4
Minimum number of tickets to print is 1

Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int p=sc.nextInt();
int g=sc.nextInt();
int r=sc.nextInt();
int o=sc.nextInt();
int t=sc.nextInt();
int a,b,c,d,i,j,k,l,x,m,count=0;
a=t/p;
b=t/g;
c=t/r;
d=t/o; //max times a loop can run
m=a+b+c+d; //random value dp wanted
for(i=0;i<=a;i++)
{
30

for(j=0;j<=b;j++)
{
for(k=0;k<=c;k++)
{
for(l=0;l<=d;l++)
{ if((i*p)+(j*g)+(k*r)+(l*o)==t)
{count++;
x=i+j+k+l;
if(x<m)
m=x;
System.out.println("# of PINK is "+i+" # of GREEN is "+j+" # of RED is "+k+"
# of ORANGE is "+l);
}

}
}
}}
System.out.println("Total combinations is "+count);
System.out.println("Minimum number of tickets to print is "+m);

}
}

Problem 3: Pattern Printing


The Pan Am 73 aircraft was hijacked by a group of Palestinian terrorists in the Karachi
International Airport. Neerja Banhot the flight purser had to stand up, wither her fear and act
intellectually to save the passengers on board. Neerja used a few patterns that was
understandable only by the cabin crew for passing information.
Given c the character upto which the pattern needs to proceed, print the pattern.

Input Format:
The first line of input consists of a character c corresponding to the character upto which the
pattern needs to proceed.

Output Format:
The output consists of n lines. The ith line consists of i uppercase character(s) separated by a
space.
Print “Invalid Input” if n is not an uppercase alphabet.
Refer sample input and output for further specifications.
Sample Input 1:
E
Sample Output 1:
ABCDE
ABCD
ABC
AB
A
31

Sample Input 2:
G
Sample Output 2:
ABCDEFG
ABCDEF
ABCDE
ABCD
ABC
AB
A

Sample Input 3:
a
Sample Output 3:
Invalid Input

Test Cases:

S.No Name Input Output Visibility


1 st3 a Invalid Input Public
2 st1 E ABCDE Public
ABCD
ABC
AB
A
3 t6 H ABCDEFGH Private
ABCDEFG
ABCDEF
ABCDE
ABCD
ABC
AB
A
4 st2 G ABCDEFG Public
ABCDEF
ABCDE
ABCD
ABC
AB
A
5 t7 B AB Private
A
6 t4 Z ABCDEFGHIJKLMNOPQRSTUVWXYZ Private
ABCDEFGHIJKLMNOPQRSTUVWXY
ABCDEFGHIJKLMNOPQRSTUVWX
ABCDEFGHIJKLMNOPQRSTUVW
ABCDEFGHIJKLMNOPQRSTUV
ABCDEFGHIJKLMNOPQRSTU
ABCDEFGHIJKLMNOPQRST
32

ABCDEFGHIJKLMNOPQRS
ABCDEFGHIJKLMNOPQR
ABCDEFGHIJKLMNOPQ
ABCDEFGHIJKLMNOP
ABCDEFGHIJKLMNO
ABCDEFGHIJKLMN
ABCDEFGHIJKLM
ABCDEFGHIJKL
ABCDEFGHIJK
ABCDEFGHIJ
ABCDEFGHI
ABCDEFGH
ABCDEFG
ABCDEF
ABCDE
ABCD
ABC
AB
A
7 t5 6 Invalid Input Private

Program:
import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
char c=sc.next().charAt(0);
int x=(int)c;
int y=65;
char i,j,ch;
if (x>=65 && x<=90)
{
for(i='A';i<=c;i++)
{
for(j=c;j>=i;j--)
{ch=(char)y;
System.out.print(ch+" ");
y++;}

System.out.println();
y=65;
}}
else
System.out.println("Invalid Input");

}
}
33

Ex No. 6 FUNCTIONS

Creating Method

Considering the following example to explain the syntax of a method −

Syntax

public static int methodName(int a, int b) {


// body
}

Here,

• public static − modifier


• int − return type
• methodName − name of the method
• a, b − formal parameters
• int a, int b − list of parameters

Method definition consists of a method header and a method body. The same is shown in
the following syntax −

Syntax

modifier returnType nameOfMethod (Parameter List) {


// method body
}

The syntax shown above includes −

• modifier − It defines the access type of the method and it is optional to use.
• returnType − Method may return a value.
• nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
• Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
• method body − The method body defines what the method does with the
statements.
34

Method Calling

For using a method, it should be called. There are two ways in which a method is called i.e.,
method returns a value or returning nothing (no return value).

The process of method calling is simple. When a program invokes a method, the program
control gets transferred to the called method. This called method then returns control to the
caller in two conditions, when −

• the return statement is executed.


• it reaches the method ending closing brace.

The methods returning void is considered as call to a statement. Lets consider an example

System.out.println("This is tutorialspoint.com!");

The method returning value can be understood by the following example −

int result = sum(6, 9);

Problem1: Expression Evaluation

In the Mini project 7th module is to evaluate the expression y = x + x^2+........+x^n. Rita
allotted this function to Malini. Collect and display the values returned by the called function.
Test your program and report the results obtained.
Help Malini to write a program to evaluate the expression?

Get the value of x and n from the user as input

Function Specification:
int calculate(int,int);
where the first argument corresponds to the value of x and second corresponds to n.

Input Format:
The first line of the input contains an integer x.
The second line of the input contains an integer n (n>=0).

Output Format:
Output displays an integer.
Refer sample input and output for formatting details.

[ All text in bold corresponds to Input and the rest output ]


Sample Input and Output:
Enter the value of x
35

2
Enter the value of n
3
The result is
14

Function Definitions:

int calculate (int,int)

Test Cases:

SNo Name Input Output Visibility


1 T6 0 Enter the value of x Private
10 Enter the value of n
The result is
0
2 T7 1 Enter the value of x Private
12 Enter the value of n
The result is
12
3 T4 5 Enter the value of x Private
5 Enter the value of n
The result is
3905
4 T3 5 Enter the value of x Private
1 Enter the value of n
The result is
5
5 T1 2 Enter the value of x Public
3 Enter the value of n
The result is
14
6 T2 5 Enter the value of x Private
7 Enter the value of n
The result is
97655
7 T5 10 Enter the value of x Private
Enter the value of n
The result is
1
36

Program:

import java.util.*;
import java.lang.*;
class Main {
int calculate(int x,int n)
{
int i=0,sum=0;
if(n==0)
{
return 1;
}
else
{
for(i=1;i<=n;i++)
{
sum=sum+(int)Math.pow(x,i);
}
return sum;
}
}

public static void main(String args[]) {

Main m=new Main();


Scanner sc=new Scanner(System.in);
System.out.println("Enter the value of x");
int x=sc.nextInt();
System.out.println("Enter the value of n");
int n=sc.nextInt();
int sum=m.calculate(x,n);
System.out.println("The result is");
System.out.println(sum);

}
}
37

Recursion in Java

Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method.

It makes the code compact but complex to understand.

Syntax:

1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }

Problem 2: Reverse the digits

Asha’s birthday is shortly coming and her parents have planned to arrange for a house
party. Deepa was Asha’s best friend and was expecting her birthday since a month. This is
because Deepa’s Dad has promised her that he and Deepa together would design a
Reverse Talking kitty toy all by themselves and gift it to Asha. Deepa believed that Asha
might be overjoyed with this gift from her dear friend.

Deepa’s Dad put the best of his efforts to design the toy. As a first module in the design he
intended to write a program that would reverse a numeric input given to it. He needs your
help to write a recursive function for reversing the digits of the given number N. Please
assist him in the task.
Function Specifications:
Use the function name, return type and the argument type as:
int reverse(int)
This recursive function should return the reverse of a N digit number.

Input Format:
The first line of the input is an integer N.

Output Format:
Print the reverse of a N digit number.
Refer sample input and output for formatting specifications.

Sample Input 1:
1234

Sample Output 1:
4321

Sample Input 2:
32333333
38

Sample Output 2:
33333323

Test Cases:

SNo Name Input Output Visibility

1 T3 200 2 Private
2 T2 32333333 33333323 Public
3 T1 1234 4321 Public

4 T4 1245363 3635421 Private

5 T5 11111 11111 Private

Program:

import java.util.*;
import java.lang.*;
class Main {

int reverse(int num)


{
int digit = (int) Math.log10(num);
if(num == 0)
return 0;

return ((num%10 * (int)Math.pow(10, digit)) + reverse(num/10));


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

Scanner sc=new Scanner(System.in);


Main m=new Main();
int num=sc.nextInt();
int rev=m.reverse(num);
System.out.println(rev);

}
}
39

Ex No. 7 ARRAYS

Java Array

Normally, an array is a collection of similar type of elements that have a contiguous memory
location.

Java array is an object which contains elements of a similar data type. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.

Array in java is index-based, the first element of the array is stored at the 0 index.

Types of Array in java

There are two types of array.

• Single Dimensional Array


• Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization


40

Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column

Problem 1: Best Couple Event

"Shades" Television Channel organizes a fun-filled event named "Best Couple 2017", where
in married couples would be invited and given many tasks and activities. Based on some
criteria decided by the jury, a best couple will be chosen.
N couples registered for the event and each couple was given a unique registration number.
One specific couple's registration Id got missed. The event coordinators wanted your help in
finding the missing Id.
Write a program which takes an array of registration numbers as input and outputs the
missing registration Id.

Input Format:
First line of the input contains the number of couples N who registered for the event.
Assume that the maximum value for N as 50.
Second line of input contains N registration Id of each of the couple, separated by a space.

Output Format:
Output in a single line the missing registration Id.
Refer sample input and output for formatting specifications.

Sample Input 1:
3
121

Sample Output 1:
2

Sample Input 2:
5
11223

Sample Output 2:
3
41

Test Cases:

SNo Name Input Output Visibility


1 T4 9 3 Private
333333333
2 T1 3 2 Public
121
3 T6 1 1 Private
1
4 T3 9 1 Private
123213414
5 T2 5 3 Public
11223
6 T5 15 2 Private
136221634557472

Program:

import java.util.*;
class Main {
public static void main(String args[]) {
int[] a=new int[50];
int i,j,temp=0,flag=0;
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}

for(i=0; i < n; i++){


for(j=1; j < (n-i); j++){
if(a[j-1] > a[j]){
//swap elements
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}

/* for(i=0;i<n;i++)
{
System.out.print(a[i]+" ");
42

}*/

for(i=0;i<n;i=i+2)
{
if(a[i]!=a[i+1])
{

flag =1;
}
if(flag==1)
{
System.out.println(a[i]);
break;
}

}
}
}

Problem 2: Nationality
The Pan Am 73 flight from Bombay to New York en route Karachi and Frankfurt was
hijacked by a few Palestinian terrorists at the Karachi International Airport. The senior flight
purser Neerja Banhot had to wither her fear and rescue the passengers on board.

The hijackers targetted passengers of a specific nationality and threatened to kill them.
Neerja did not want this to happen and plotted a plan to evacuate the passengers.

Before proceeding, she wanted to know the count of passengers from the specific country x,
who are threatened by the hijackers. Given r the number of rows, c the number of columns,
and the description of the nationality of each passenger in the grid r*c, can you find the
number of passengers from a particular country c ?

Input Format :
The first line of input consists of an integer r, corresponding to the number of rows of seats
in the aircraft.
The second line of input consists of an integer c, corresponding to the number of seats in a
row.
The following r lines each with c columns of inputs, consist of uppercase alphabets that
corresponds to the nationalities of passengers.
The next line of input is a character that corresponds to a specific country.

Output Format :
The output consists of an integer corresponding to the number of passengers from country
x.
Refer sample input and output for further specifications.
43

Sample Input 1:
6
5
ICBIC
IABIS
IVBIG
GHIHI
OMOMO
OIUIU
B
Sample Output 1:
3

Test Case:

SNo Name Input Output Visibility


1 t3 3 12 Private
4
AAAA
AAAA
AAAA
A
2 st2 1 1 Private
1
J
J
3 st1 6 3 Public
5
ICBIC
IABIS
IVBIG
GHIHI
OMOMO
OIUIU
B
4 t4 4 0 Private
6
QWERTY
ASDFGH
ZXCVBN
YUIOPH
M

Program:

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

Scanner sc=new Scanner(System.in);


44

char[][] a=new char[100][100];

int i,j,r,c,count=0;
r=sc.nextInt();
c=sc.nextInt();

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
a[i][j]=sc.next().charAt(0);
}
}

char ch=sc.next().charAt(0);

for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
if(a[i][j]==ch)
{
count++;
}
}
}
System.out.println(count);

}
}
45

Ex No. 8 STRINGS

What is String in java

Generally, String is a sequence of characters. But in Java, string is an object that represents
a sequence of characters. The java.lang.String class is used to create a string object.

How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword

Java String class methods

The java.lang.String class provides many useful methods to perform operations on


sequence of char values.

No. Method Description


1 char charAt(int index) returns char value for the particular
index
2 int length() returns string length
3 static String format(String format, returns a formatted string.
Object... args)
4 static String format(Locale l, String returns formatted string with given
format, Object... args) locale.
5 String substring(int beginIndex) returns substring for given begin index.
6 String substring(int beginIndex, int returns substring for given begin index
endIndex) and end index.
7 boolean contains(CharSequence s) returns true or false after matching the
sequence of char value.
8 static String join(CharSequence returns a joined string.
delimiter, CharSequence... elements)
9 static String join(CharSequence returns a joined string.
delimiter, Iterable<? extends
CharSequence> elements)
10 boolean equals(Object another) checks the equality of string with the
given object.
11 boolean isEmpty() checks if string is empty.
12 String concat(String str) concatenates the specified string.
13 String replace(char old, char new) replaces all occurrences of the specified
char value.
14 String replace(CharSequence old, replaces all occurrences of the specified
CharSequence new) CharSequence.
15 static String equalsIgnoreCase(String compares another string. It doesn't
46

another) check case.


16 String[] split(String regex) returns a split string matching regex.
17 String[] split(String regex, int limit) returns a split string matching regex and
limit.
18 String intern() returns an interned string.
19 int indexOf(int ch) returns the specified char value index.
20 int indexOf(int ch, int fromIndex) returns the specified char value index
starting with given index.
21 int indexOf(String substring) returns the specified substring index.
22 int indexOf(String substring, int returns the specified substring index
fromIndex) starting with given index.
23 String toLowerCase() returns a string in lowercase.
24 String toLowerCase(Locale l) returns a string in lowercase using
specified locale.
25 String toUpperCase() returns a string in uppercase.
26 String toUpperCase(Locale l) returns a string in uppercase using
specified locale.
27 String trim() removes beginning and ending spaces
of this string.
28 static String valueOf(int value) converts given type into string. It is an
overloaded method.

Problem 1: Lower Case

Write a program to convert the string to lower case.

Input and Output Format:

Input consists of a string. Assume that the input string consists of only letters and the
maximum length of the string is 20.

Refer sample input and output for formatting specifications.

All text in bold corresponds to input and the rest corresponds to output.

Sample Input and Output:

Enter the input string

AmphiSoft

The output string is amphisoft


47

Test Cases:

SNo Name Input Output Visibility


1 T1 AmphiSOft Enter the input string Public
The output string is amphisoft
2 T3 TamilNadu Enter the input string Private
The output string is tamilnadu
3 T4 INDIA Enter the input string Private
The output string is india
4 T2 EngineeriNG Enter the input string Private
The output string is engineering
5 T5 QWERTYASDFGZXCVBNO Enter the input string Private
The output string is qwertyasdfgzxcvbno

Program:

import java.util.*;
class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the input string");
String str=sc.next();
String str2=str.toLowerCase();
System.out.printf("The output string is %s",str2);

}
}

Problem 2: Delete Vowels

Write a program to delete all vowels present in a string.

Input and Output Format:

Input consists of a string. Assume that all characters in the string are lowercase letters and
the maximum length of the string is 200.

Refer sample input and output for formatting specifications.

All text in bold corresponds to input and the rest corresponds to output.
Sample Input and Output:
Enter the input string
amphisoft
The output string is mphsft
48

Test Cases:

SNo Name Input Output Visibility


1 T5 technologies Enter the input string Private
The output string is tchnlgs
2 T4 behaviour Enter the input string Private
The output string is bhvr
3 T2 education Enter the input string Private
The output string is dctn
4 T1 amphisoft Enter the input string Public
The output string is mphsft
5 T6 aeioudhg Enter the input string Private
The output string is dhg

Program:
import java.util.*;

class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the input string");
String str=sc.nextLine();
String str1=str.replaceAll("[aeiouAEIOU]", "");
System.out.printf("The output string is %s",str1);

}
}
49

Ex No. 9 FILES

OutputStream vs InputStream

The explanation of OutputStream and InputStream classes are given below:

OutputStream

Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.

InputStream

Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.

Let's understand the working of Java OutputStream and InputStream by the figure given
below.

OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes representing an


output stream of bytes. An output stream accepts output bytes and sends them to some
sink.

Useful methods of OutputStream

Method Description
1) public void write(int)throws is used to write a byte to the current output
IOException stream.
2) public void write(byte[])throws is used to write an array of byte to the
IOException current output stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.
50

OutputStream Hierarchy

InputStream class

InputStream class is an abstract class. It is the superclass of all classes representing an


input stream of bytes.

Useful methods of InputStream

Method Description
1) public abstract int reads the next byte of data from the input stream. It
read()throws IOException returns -1 at the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can
IOException be read from the current input stream.
3) public void close()throws is used to close the current input stream.
IOException

InputStream Hierarchy
51

Problem1 : Byte Streams


Java byte streams are used to perform input and output of 8-bit bytes. Though there are
many classes related to byte streams but the most frequently used classes are,
FileInputStream and FileOutputStream. Following is an example which makes use of these
two classes to copy an input file into an output file.

Program 1:
import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Problem 2: Character Streams

Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java
Character streams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes are,
FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.

We can re-write the above example, which makes the use of these two classes to copy an
input file (having unicode characters) into an output file
52

Program 2:

import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Standard Streams

All the programming languages provide support for standard I/O where the user's program
can take input from a keyboard and then produce an output on the computer screen. If you
are aware of C or C++ programming languages, then you must be aware of three standard
devices STDIN, STDOUT and STDERR. Similarly, Java provides the following three
standard streams −

• Standard Input − This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
• Standard Output − This is used to output the data produced by the user's program
and usually a computer screen is used for standard output stream and represented
as System.out.
• Standard Error − This is used to output the error data produced by the user's
program and usually a computer screen is used for standard error stream and
represented as System.err.
53

FileInputStream

Sr.No. Method & Description


1 public void close() throws IOException{}

This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures that the close method of
this file output stream is called when there are no more references to this stream.
Throws an IOException.
3 public int read(int r)throws IOException{}

This method reads the specified byte of data from the InputStream. Returns an int.
Returns the next byte of data and -1 will be returned if it's the end of the file.
4 public int read(byte[] r) throws IOException{}

This method reads r.length bytes from the input stream into an array. Returns the
total number of bytes read. If it is the end of the file, -1 will be returned.
5 public int available() throws IOException{}

Gives the number of bytes that can be read from this file input stream. Returns an
int.

FileOutputStream

Sr.No. Method & Description


1 public void close() throws IOException{}

This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures that the close method of
this file output stream is called when there are no more references to this stream.
Throws an IOException.
3 public void write(int w)throws IOException{}

This methods writes the specified byte to the output stream.


4 public void write(byte[] w)

Writes w.length bytes from the mentioned byte array to the OutputStream.
54

Program 3:

import java.io.*;
public class fileStreamTest {

public static void main(String args[]) {

try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();

InputStream is = new FileInputStream("test.txt");


int size = is.available();

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


System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
}
}
55

Ex No. 10 CLASSES

Classes in Java

A class is a blueprint from which individual objects are created.

Following is a sample of a class.

Example

public class Dog {


String breed;
int age;
String color;

void barking() {
}

void hungry() {
}

void sleeping() {
}
}

A class can contain any of the following variable types.

• Local variables − Variables defined inside methods, constructors or blocks are


called local variables. The variable will be declared and initialized within the method
and the variable will be destroyed when the method has completed.
• Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
• Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.

A class can have any number of methods to access the value of various kinds of methods.
In the above example, barking(), hungry() and sleeping() are methods.

Creating an Object
56

As mentioned previously, a class provides the blueprints for objects. So basically, an object
is created from a class. In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −

• Declaration − A variable declaration with a variable name with an object type.


• Instantiation − The 'new' keyword is used to create the object.
• Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.

Following is an example of creating an object −

Program 1:

public class Puppy {


public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}

public static void main(String []args) {


// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}

If we compile and run the above program, then it will produce the following result −

Output

Passed Name is :tommy

Accessing Instance Variables and Methods

Instance variables and methods are accessed via created objects. To access an instance
variable, following is the fully qualified path −

/* First create an object */


ObjectReference = new Constructor();

/* Now call a variable as follows */


ObjectReference.variableName;

/* Now you can call a class method as follows */


ObjectReference.MethodName();

Example
57

This example explains how to access instance variables and methods of a class.

Program 2:

public class Puppy {


int puppyAge;

public Puppy(String name) {


// This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}

public void setAge( int age ) {


puppyAge = age;
}

public int getAge( ) {


System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}

public static void main(String []args) {


/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */


myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */


myPuppy.getAge( );

/* You can access instance variable as follows as well */


System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}

If we compile and run the above program, then it will produce the following result −

Output

Name chosen is :tommy


Puppy's age is :2
Variable Value :2

A Simple Case Study

For our case study, we will be creating two classes. They are Employee and EmployeeTest.
58

First open notepad and add the following code. Remember this is the Employee class and
the class is a public class. Now, save this source file with the name Employee.java.

The Employee class has four instance variables - name, age, designation and salary. The
class has one explicitly defined constructor, which takes a parameter.

Example

import java.io.*;
public class Employee {

String name;
int age;
String designation;
double salary;

// This is the constructor of the class Employee


public Employee(String name) {
this.name = name;
}

// Assign the age of the Employee to the variable age.


public void empAge(int empAge) {
age = empAge;
}

/* Assign the designation to the variable designation.*/


public void empDesignation(String empDesig) {
designation = empDesig;
}

/* Assign the salary to the variable salary.*/


public void empSalary(double empSalary) {
salary = empSalary;
}

/* Print the Employee details */


public void printEmployee() {
System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}
}

You might also like