JAVA Lab
JAVA Lab
PRACTICAL 1
1. Write a JAVA Program to make a calculator using switch case. You can have 5
operations +,-,/,*,%.
Source Code:
import java.util.Scanner;
class q1 {
public static void main(String[] args) {
char operator;
Double n1, n2, result;
Scanner input = new Scanner(System.in);
System.out.println("Choose an operator: +, -, *, or /");
operator = input.next().charAt(0);
System.out.println("Enter first number");
n1 = input.nextDouble();
System.out.println("Enter second number");
n2 = input.nextDouble();
switch (operator) {
case '+':
result = n1 + n2;
System.out.println(n1 + " + " + n2 + " = " + result);
break;
case '-':
result = n1 - n2;
System.out.println(n1 + " - " + n2 + " = " + result);
break;
case '*':
result = n1 * n2;
System.out.println(n1 + " * " + n2 + " = " + result);
break;
case '/':
result = n1 / n2;
System.out.println(n1 + " / " + n2 + " = " + result);
break;
default:
System.out.println("Invalid operator!");
break;
}
input.close();
}
}
OUTPUT:
Screenshot
Source Code:
import java.util.Scanner;
public class Floyd {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of row to print");
int rows = sc.nextInt();
int floydNumber=1;
for(int i=1;i<=rows;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(floydNumber+" ");
floydNumber = floydNumber + 1;
}
System.out.println();
}
}
}
OUTPUT:
Screenshot
PRACTICAL 2
3. Given a list of marks ranging from 0 to 100. Write a JAVA Program to compute and
print the number of students who have obtained marks
a. in the range of 81-100
b. in the range of 61-80
c. in the range of 41-60
d. in the range of 0-40.
The program should use a minimum number of if statements.
Source Code:
import java.util.*;
public class q3
{
public static ArrayList<Integer> marksList = new ArrayList<Integer>();
public static void main(String[] args)
{
marks();
int first=0;
int second=0;
int third=0;
int fourth=0;
for(int mark : marksList)
{
if(mark>=81 && mark<=100)
{
first++;
}
else if(mark>=61 && mark<=80)
{
second++;
}
else if(mark>=41 && mark<=60)
{
third++;
}
else if(mark <=40)
{
fourth++;
}
}
System.out.println("No of student in the range 81 to 100:"+first);
System.out.println("No of student in the range 61 to 80:"+second);
System.out.println("No of student in the range 41 to 60:"+third);
System.out.println("No of student in the range 0 to 40:"+fourth);
Shashank Garg/BTECH CSE/20011190/SEM-IV/SECTION-K
Java Programming Lab
OUTPUT:
Screenshot
Source Code:
import java.util.*;
public class StringFunction {
public static void main(String[] args)
{
String first="",second="";
Scanner c=new Scanner(System.in);
System.out.println("String Functions");
System.out.println();
System.out.print("Enter the first Sting: ");
first=c.nextLine();
System.out.print("Enter the second Sting: ");
second=c.nextLine();
System.out.println("The strings are: "+first+" , "+second);
System.out.println("The length of the first string is :"+first.length());
System.out.println("The length of the second string is :"+second.length());
System.out.println("The concatenation of first and second string is :"+first.concat("
"+second));
System.out.println("The first character of " +first+" is: "+first.charAt(0));
System.out.println("The uppercase of " +first+" is: "+first.toUpperCase());
System.out.println("The lowercase of " +first+" is: "+first.toLowerCase());
System.out.print("Enter the occurance of a character in "+first+" : ");
String str=c.next();
char b=str.charAt(0);
System.out.println("The "+c+" occurs at position " + first.indexOf(b)+ " in " + first);
System.out.println("The substring of "+first+" starting from index 3 and ending at 6 is: " +
first.substring(3,7));
System.out.println("Replacing 'a' with 'o' in "+first+" is: "+first.replace('a','o'));
boolean check=first.equals(second);
if(!check)
System.out.println(first + " and " + second + " are not same.");
else
System.out.println(first + " and " + second + " are same.");
}
}
OUTPUT:
Screenshot
PRACTICAL 3
5. Write a JAVA Program to compute power of 2 using for loop.
Source Code:
import java.util.Scanner;
public class Power {
OUTPUT:
Screenshot
Source Code:
import java.util.Scanner;
class staffCodeName{
private
String name;
public
Scanner sc = new Scanner(System.in);
void setname()
{
System.out.println("enter the name of user");
name = sc.nextLine();
}
void getname()
{
System.out.println("the name of staff memeber is : "+name);
}
}
void getspeed()
{
System.out.println("the speed of typist is : "+speed);
}
}
}
}
OUTPUT:
Screenshot
PRACTICAL 4
7. Design a class to represent a bank account. Include the following members-
Data Members-
*Name of the Depositor
*Type of account
*Account Number
*Balance amount in the account
Methods-
*To assign initial values.
*To deposit an amount
*To withdraw an amount after checking balance.
*To display the name and balance.
Source code:
import java.io.*;
import java.util.*;
import java.util.Scanner;
import java.util.Random;
class Bank
{
public String nameOfDepositor;
public int accNumber;
public String accType;
public double balanceAmount;
this.balanceAmount=balanceAmount;
if(accNumber==0)
System.out.println("!You don't have bank account\nNote:please assign values to create an
account");
else
{
System.out.println("Name of the Depositor: "+nameOfDepositor);
System.out.println("Balance amount in the account: "+balanceAmount);
}
}
public void getInput()
{
class Main
{
public static void main(String[] s) throws IOException
{
Bank newAccount=new Bank();
while(continueState==0)
Shashank Garg/BTECH CSE/20011190/SEM-IV/SECTION-K
Java Programming Lab
{
newAccount.getInput();
int currentProcess=scan.nextInt();
if(currentProcess==1)
{
System.out.print("Enter your name: ");
String nameOfDepositor=scan.next();
System.out.print("Enter your account type: ");
String accType=scan.next();
System.out.print("Enter your opening balance: ");
double balanceAmount=scan.nextDouble();
newAccount.assignValues(nameOfDepositor, accType, balanceAmount);
}
else if(currentProcess==2)
{
System.out.print("Enter amount to deposit: ");
newAccount.depositAmount(scan.nextDouble());
}
else if(currentProcess==3)
{
System.out.print("Enter amount to withdraw: ");
newAccount.withdrawAmount(scan.nextDouble());
}
else if(currentProcess==4)
{
newAccount.displayDetails();
}
else if(currentProcess==5)
{
continueState=1;
System.out.println("THANK YOU");
}
OUTPUT:
Screenshot
Source Code:
OUTPUT:
Screenshot
PRACTICAL 5
9. Create a class “Student” having following instance variables and methods.
Instance variables: ID, Name, Branch, city and university
While creating constructors with one, two, three, four and five arguments reuse the
constructors by construction chaining.
Source Code:
import java.util.Scanner;
class Student
{
private int id;
private String name,branch,city,university;
return this.university;
}
}
public class Student_Overloading
{
public static void main(String[] args)
{
Scanner sc1=new Scanner(System.in);
Scanner sc2=new Scanner(System.in);
Scanner sc3=new Scanner(System.in);
Scanner sc4=new Scanner(System.in);
Scanner sc5=new Scanner(System.in);
Scanner sc6=new Scanner(System.in);
if(answer.equalsIgnoreCase("Y"))
{
Student s=new Student(id, name, city, branch);
System.out.println(" Id :"+s.getid());
System.out.println(" Student Name :"+s.getname());
System.out.println(" Student City :"+s.getcity());
System.out.println(" Student Branch :"+s.getbranch());
break;
}
else if(answer.equalsIgnoreCase("N"))
{
System.out.println("Enter the College Name :");
String c_name=sc6.nextLine();
Student s=new Student(id, name, city, branch, c_name);
System.out.println(" Student Id :"+s.getid());
System.out.println(" Student Name :"+s.getname());
System.out.println(" Student City :"+s.getcity());
System.out.println(" Student Branch :"+s.getbranch());
System.out.println(" Student University :"+s.getunivesity());
break;
}
Shashank Garg/BTECH CSE/20011190/SEM-IV/SECTION-K
Java Programming Lab
else
{
System.out.println("<<<<<.WRONG INPUT.>>>>>");
}
}
}
}
OUTPUT:
Screenshot
10.Create a class “Shape” having area() method to calculate area. Overload the area()
method for shapes like triangle, rectangle and circle.
Source Code:
import java.io.*;
class Calculate {
static final double PI = Math.PI;
void Area(float a)
{
float A = a * a;
System.out.println("Area of the Square: " + A);
}
void Area(double a)
{
double A = PI * a * a;
System.out.println("Area of the Circle: " + A);
}
void Area(int a, int b)
{
int A = a * b;
System.out.println("Area of the Rectangle: " + A);
}
}
class Shape {
OUTPUT:
Screenshot
PRACTICAL 6
11. Create two dimensional integer array and insert, search and traverse this array.
Note: Use Scanner class to insert data.
Source Code:
import java.util.Scanner;
public class Carr {
}
System.out.println();
}
System.out.println("Enter a integer value to search.");
k=sc.nextInt();
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
if(k==arr[i][j])
{
System.out.println("The element is found at index:"+i +j);
return;
}
}
}
System.out.println("Element not found.");
}
}
OUTPUT:
Screenshot
12.A cloth showroom has announced the following seasonal discounts on purchase of
items:
Discount
Purchase Mill Handloom
Amount Cloth Items
1-100 --- 5%
101-200 5% 7.50%
210-300 7.50% 10%
Above 300 10% 15%
Write a program using switch and if statements to compute the net amount to
be paid by a customer.
Source Code:
import java.util.*;
char c=scan.nextLine().toUpperCase().toCharArray()[0];
double cost=scan.nextDouble();
double dis=discount(c,cost);
double netAmt=cost-dis;
double dis = 0;
double rate = 0;
switch (typ)
case 'M':
rate = 5;
rate = 7.5;
rate = 10;
break;
case 'H':
rate = 5;
rate = 7.5;
rate = 10;
rate = 15;
break;
return dis;
OUTPUT:
Screenshot
PRACTICAL 7
13.Create a Java program to perform survey on four different model of Maruti (Maruti
-K10, Zen-Astelo, Wagnor, Maruti- SX4) owned by person living in four metro
cities(Delhi, Mumbai, Chennai & Kolkatta). Display tabulated report like format
given below:
14.Write a Java program to find the duplicate characters in the given paragraph
using either String or StringBuffer class methods.
Sample Output:
Source Code:
import java.util.*;
public class Duplicate
{
public static String unique(String s)
{
String str = new String();
int len = s.length();
for (int i = 0; i < len; i++)
{
char c = s.charAt(i);
if (str.indexOf(c) < 0)
{
str += c;
}
}
System.out.println("String after Removing Duplicate :");
return str;
}
public static void main(String[] args)
{
String s =" ";
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String :");
s=sc.nextLine();
System.out.println(unique(s));
}
}
OUTPUT:
Screenshot
PRACTICAL 8
15. Write a Java program implementing students of marks using Inheritance.
16.Write a Java program to count the occurrences of a given string in another given
string.
Sample Output:
aa' has occured 3 times in 'abcd abc aabc baa abcaa'
Source Code:
import java.util.Arrays;
import java.util.Scanner;
public class string {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String :");
String m_string =sc.nextLine();
System.out.println("Enter the sub String to Search :");
String s_string = sc.nextLine();
int countV1 = count_sub_str_in_main_str(m_string, s_string);
System.out.println(s_string + "' has occured " + countV1 + " times in '" + m_string + "'");
}
public static int count_sub_str_in_main_str(String m_string, String s_string) {
if (m_string == null || s_string == null) {
throw new IllegalArgumentException("The given strings cannot be null");
}
if (m_string.isEmpty() || s_string.isEmpty()) {
return 0;
}
int position = 0;
int ctr = 0;
int n = s_string.length();
while ((position = m_string.indexOf(s_string, position)) != -1) {
position = position + n;
ctr++;
}
return ctr;
}
}
OUTPUT:
Screenshot
17. Define an exception called “NoMatchException” that is thrown when a string is not
equal to “India”. Write a program in Java that uses this exception.
Source Code:
import java.util.Scanner;
class NoMatchException extends Exception{
String s1;
NoMatchException(String s2)
{
this.s1=s2;
}
try {
if(!"india".equalsIgnoreCase(s3))
throw new NoMatchException("NoMatchException caught!!!");
else {
System.out.println("String matched!!!");
}
}
catch(NoMatchException e) {
System.out.println(e);
}
}
}
OUTPUT:
Screenshot
Source Code:
class stringbuffer{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
//APPEND
sb.append(" Java");
System.out.println(sb);
//INSERT AT INDEX 1
sb.insert(1," Java");
System.out.println(sb);
//REPLACE AT INDEX
sb.replace(1,3," Java");
System.out.println(sb);
//DELETE CHAR BETWEEN INDEX
sb.delete(1,3);
System.out.println(sb);
//REVERSE OF STRING
sb.reverse();
System.out.println(sb);
}
}
OUTPUT:
Screenshot
19. Create a jagged array having three rows. Where 1st row contains 3 columns, 2nd row contains 4
columns and 3rd row contains 2 columns. Insert and traverse it.
Source Code:
OUTPUT:
Screenshot