JAVA Practicals Final
JAVA Practicals Final
Practical 1
Aim: Write a Java program to print the string literal “Hello World!!!”
Program Code:
System.out.println("Hello world");
Output:
Practical 2
Aim : Write a Java program to print the poem
"");
Output:
Practical 3
Aim: Write a Java program to add two numbers using Command Line Argument
Program Code:
System.out.println("Sum of " + num1 + " and " + num2 + " is " + total);
Output:
Practical 4
Aim: Write a Java program to convert rupees into dollars using
(i) Command Line Argument
(ii) Scanner Class
Program Code:
Output:
import java.util.Scanner;
public class Practical4_2
{
public static void main(String[] args)
{
Scanner obj = new Scanner(System.in);
System.out.println("Enter the rupees:");
int r = obj.nextInt();
float d = (float) r / 60;
System.out.println(r + "Rupees = " + d + "Dollar");
}
}
Output:
Ans-
Ans-
-Multithreaded
With Java’s multithreaded feature it is possible to write programs that can perform many
tasks simultaneously. This design feature allows the developers to construct interactive
applications that can run smoothly.
Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.
-High Performance
-Distributed
-Dynamic
Ans- We can use parseXxx() methods to convert String to primitive. There are two types of
parseXxx() methods:
A. primitive parseXxx(String s): Every Wrapper class except the character class contains the
following parseXxx() method to find primitive for the given String object.
B. parseXxx(String s, int radix): Every Integral type Wrapper class (Byte, Short, Integer,
Long) contains the following parseXxx() method to convert specified radix String to
primitive.
Syntax:
Ans- The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be
used as an input.
So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Practical 1:
Aim: Write a Java program to compute the area of a circle using Scanner class
Method Description
nextLine() Reads a line of text (that is a string ending with the Enter
key pressed)
Program Code:
import java.util.Scanner;
class Practical1
double r= sc.nextDouble();
Output:
Practical 2:
Aim: Write a Java program that calculates the percentage marks of the student if marks of 6
subjects are given.
Program Code:
class Practical2
int N = 6, total_marks = 0;
float percentage;
total_marks += marks[i];
Output:
Practical 3:
Aim: Write a program to enter two numbers and perform mathematical operations on them.
Program Code:
import java.util.Scanner;
num1 = scan.nextInt();
num2 = scan.nextInt();
Output:
Practical 4:
Aim: Write a Java program that converts a Fahrenheit degree to Celsius using the formula:
Celsius = (5/9) (Fahrenheit - 32)
Program Code:
import java.util.Scanner;
Output:
Practical 5:
Aim: Write a program that computes loan payments. The loan can be a car loan, a student
loan, or a home mortgage loan. Allow the user to enter the interest, rate, number of years and
loan amount, and display the monthly payment as follows:
Program Code:
import java.util.Scanner;
import java.lang.Math;
Output:
Q.2) What are the four integer types supported by Java? Explain with some examples
Ans :.Java supports four integer types, which differ in size and range:
Byte : It’s the smallest integer type and occupies 8 bits.
Its range is from -128 to 127.
Ex : byte myByte = 100;
Short : It’s larger than a byte and occupies 16 bits.
Its range is from -32,768 to 32,767
Ex :Short myShort = 2000;
Int :This is the most commonly used integer type and occupies 32 bits.
Its range is from -2^31 to 2^31 – 1.
Ex : Int myInt = 50000;
Long :It’s the largest integer type and occupies 64 bits.
Its range is from -2^63 to 2^63 – 1.
Ex : Long myLong = 10000000000L; // Note the ‘L’ suffix to indicate a long literal
Q. 4). What are binary literals? Can we use an underscore with numeric literals?
Ans : Binary literals allows us to represent integer values in binary (base-2) notation. They
are introduced with the prefix “Ob” or “OB” followed by a sequence of binary digits (0 and
1). Binary literals are useful for better readability when dealing with binary data or specific
binary patterns.
Example : Int binaryValue = 0b101010; Yes, we can use underscores in numeric literals
(including binary literals) in Java starting from Java 7.
Underscores can be placed between digits to enhance the readability of large numbers. They
do not affect the value of the number, only how it’s presented in the code.
SET 3 – Arrays
Practical 1
Program Code:
class Practical1
{
public void Count( )
{
int arr[] = {1, 2, 2, 2, 2, 3, 4, 7 ,8 ,8 };
int n = arr.length;
obj.Count();
}
}
Output:
Practical2
Aim: To read an unspecified number of scores and determine how many scores are above or
equal to the average and how many scores are below the average.
Program Code:
import java.util.Scanner;
break;
average = average + scores[i];
numberofScores++;
}
average = average / numberofScores;
}
System.out.println("Average of scores:" + average);
System.out.println("Number of scores above or equal to average:" + AboveOREqual);
System.out.println("Number of scores below average:" + below);
}
Output:
Practical 3
Program code:
temp[j++] = arr[n-1];
return j;
}
Output:
Practical 4
Program Code:
import java.util.Scanner;
public class Practical4
{
tempar[j][1] = tempar[j+1][1];
tempar[j][0] = tempar[j+1][0];
tempar[j+1][1] = temp;
tempar[j+1][0] = temp2;
}
}
}
return tempar;
}
Output:
Practical 5
Program Code:
return max;
}
Output:
Ans : As per the convention of array declaration, it is mandatory that each time an array is
evaluated it shall have a size greater than 0. Declaring array size negative breaks this “shall”
condition. That’s why this action gives an error.
Ans : In Java, a jagged array is an array of arrays where each sub-array can have a different
length. Unlike a multi-dimensional array, where all sub-arrays have the same length, jagged
arrays allow for more flexibility in creating arrays with varying dimensions. Each sub-array
in a jagged array is an independent array object, and they can be of different lengths. This can
be useful when dealing with irregular data structures or when memory allocation needs vary
across different parts of your program.
Q3.What are the different ways of copying an array into another array?
Ans:
- You can copy one array from another in several ways − Copying element by
element − One way is to create an empty array with the length of the original array,
and copy each element (in a loop).
- Using the clone() method − The clone() method of the class java.lang.Object accepts
an object as a parameter, creates and returns a copy of it.
- Using the System.arraycopy() method − The copy() method of the System class
accepts two arrays (along with other details) and copies the contents of one array to
other.
Ans:
Primitive/ An array can store both objects and We cannot store primitive type
Generic type primitives type. in ArrayList. It automatically
converts primitive type to object.
Iterating We use for loop or for each loop to We use an iterator to iterate
Values iterate over an array. over ArrayList.
Practical 1
Aim - (The Account class) Design a class named Account that contains:
■ A private int data field named id for the account (default 0).
■ A private double data field named balance for the account (default 0).
■ A private double data field named annualInterestRate that stores the current
interest rate (default 0). Assume all accounts have the same interest rate.
■ A private Date data field named dateCreated that stores the date when the account was created.
■ The accessor and mutator methods for id, balance, and annualInterestRate.
interest rate.
■ A method named withdraw that withdraws a specified amount from the account.
Draw the UML diagram for the class. Implement the class. Write a test program that creates an Account object
with an account ID of 1122, a balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw method
to withdraw $2,500, use the deposit method to deposit $3,000, and print the balance, the monthly interest, and
the date when this account was created.
Program Code:
import java.util.Date;
public Account() {
id = 0;
balance = 0;
annualInterestRate = 0;
dateCreated = new Date();
}
Output:
Practical 2
1. Aim: (The Fan class) Design a class named Fan to represent a fan. The class contains:
■ Three constants named SLOW, MEDIUM, and FAST with values 1, 2, and 3 to denote the
fan speed.
■ A private int data field named speed that specifies the speed of the fan
(default SLOW).
■ A private boolean data field named on that specifies whether the fan is on (default false).
■ A private double data field named radius that specifies the radius of the fan (default 5).
■ A string data field named color that specifies the color of the fan (default blue).
■ The accessor and mutator methods for all four data fields.
■ A no-arg constructor that creates a default fan.
■ A method named toString() that returns a string description for the fan. If the fan is on, the
method returns the fan speed, color, and radius in one combined string. If the fan is not on,
the method returns fan color and radius along with the string “fan is off” in one combined
string.
Draw the UML diagram for the class. Implement the class. Write a test program that creates
two Fan objects. Assign maximum speed, radius 10, color yellow, and turn it on to the first
object. Assign medium speed, radius 5, color blue, and turn it off to the second object.
Display the objects by invoking their toString method.
public Fan() {
speed = SLOW;
on = false;
radius = 5.0;
color = "blue";
}
Output:
SET 5 – Strings
Practical 1
Aim: (Counting Each Letter in a String). Write a program that prompts the user
to enter a string and counts the number of occurrences of each letter in the string
regardless of case.
Program Code:
import java.util.Scanner;
count[str.charAt(i)]++;
char ch[] = new char[str.length()];
for (int i = 0; i < len; i++)
{
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++)
{
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
System.out.println("The occurrence of "+ str.charAt(i)+ " is: " + count[str.charAt(i)]);
}
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a string: ");
String str = sc.nextLine();
getOccuringChar(str);
}
}
Output:
Practical 2
Aim: (Anagrams). Write a method that checks whether two words are
anagrams. Two words are anagrams if they contain the same letters in any
order. For example, “silent” and “listen” are anagrams. The header of the
method is as follows:
public static Boolean isAnagram(String s1, String s2)
Write a test program that prompts the user to enter two strings and, if they are
anagrams, displays “anagram”, otherwise displays “not anagram”.
Program Code:
import java.util.Arrays;
import java.util.Scanner;
if (s1.length() != s2.length()) {
return false;
}
char[] s1Array = s1.toCharArray();
char[] s2Array = s2.toCharArray();
if (isAnagram(input1, input2)) {
System.out.println("Anagram");
} else {
System.out.println("Not anagram");
}
}
}
Output:
Practical 3
Aim: (Palindrome). Write a program that prompts the user to enter a string and
reports whether the string is a palindrome.
Program Code:
import java.util.Scanner;
if (isPalindrome(input)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
int left = 0;
int right = str.length() - 1;
Output:
Practical 4
Program Code:
import java.util.Scanner;
if (isSubstring(str1, str2)) {
System.out.println("The first string is a substring of the second string.");
} else {
System.out.println("The first string is not a substring of the second string.");
}
}
if (j == strLength1) {
return true;
}
}
return false;
}
}
Output:
Practical 5
Aim: (Sorting characters). Write a method that returns a sorted string using the
following header:
public static String sort(String s);
For example, sort(“acb”) returns abc
Write a test program that prompts the user to enter a string and displays the
sorted string.
Program Code:
import java.util.Scanner;
Output:
Practical 1
1. Aim: Describe abstract class called Shape which has three subclasses say
Triangle,Rectangle,Circle. Define one method area() in the abstract class
and override this area() in these three subclasses to calculate for specific
object i.e. area() of Triangle subclass should calculate area of triangle etc.
Same for Rectangle and Circle
Program Code:
double area() {
return 0.5 * base * height;
}
}
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
Output:
Practical 2
Program Code:
interface P {
int CONSTANT_P = 10;
void methodP();
}
interface P1 extends P {
int CONSTANT_P1 = 20;
}
interface P2 extends P {
int CONSTANT_P2 = 30;
}
Practical 3
Aim: The abstract Vegetable class has three subclasses named Potato, Brinjal
and Tomato. Write an application that demonstrates how to establish this class
Program Code:
potato.howToEat();
brinjal.howToEat();
tomato.howToEat();
}
}
Output:
Practical 4
Aim: The Transport interface declares a deliver() method. The abstract class
Animal is the superclass of the Tiger, Camel, Deer and Donkey classes. The
Transport interface is implemented by the Camel and Donkey classes. Write a
test program that initialize an array of four Animal objects. If the object
implements the Transport interface, the deliver() method is invoked.
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 54
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
Program Code:
interface Transport {
void deliver();
}
abstract class Animal {
}
Output:
Practical 1
Program Code:
Output:
Practical 2
Aim: Write an application that generates custom exception if any value from its
command line arguments is negative.
Program Code:
class NegativeNumberException extends Exception
{
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 58
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
public NegativeNumberException(String s)
{
super(s);
}
}
class expdemo3
{
static int check(int m)throws NegativeNumberException
{
if(m<0)throw new NegativeNumberException("Number<0");
return m;
}
public static void main(String args[])
{
try
{
int number=check(Integer.parseInt(args[0]));
System.out.println("You have Entered"+number);
}
catch(NegativeNumberException m)
{
System.out.println(m);
}
System.out.println("end");
}
}
Output:
Practical 3
Program Code:
Output:
Practical 4
Aim: Write a Java program to accept N integer numbers from the command
line. Raise and handle exceptions for the following cases:
Program Code:
Your Enrollment No: 23C22504
Name: Almash Yunus Lakdawala. Page 61
Object-Oriented Programming with Java (C2310C1)
SoCSET BTech Semester Ⅲ AI&DA/IT
import java.util.Scanner;
Output:
SET 8 - I/O
Practical 1
Program Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
Output:
Practical 2
Aim: Write a Java program to check whether the name from command line is a
file or not? If it is a file then print the size and if it is a directory then it should
display the name of all the files in it.
Program Code:
import java.io.File;
if (file.exists()) {
if (file.isFile()) {
System.out.println(fileName + " is a file.");
System.out.println("Size of " + fileName + " is " + file.length() + " bytes.");
} else if (file.isDirectory()) {
System.out.println(fileName + " is a directory.");
System.out.println("Files in " + fileName + ":");
Output:
Practical 3
Program Code:
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String sourceFile = "Test1.txt";
String destinationFile = "Test2.txt";
try (FileInputStream fileInputStream = new FileInputStream(sourceFile);
BufferedInputStream bufferedInputStream = new
BufferedInputStream(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);
BufferedOutputStream bufferedOutputStream = new
BufferedOutputStream(fileOutputStream)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, bytesRead);
SET 9 - MultiThreading
Practical 1
Aim: Write an application that creates and starts three threads. Each thread is
instantiated from the same class. It executes a loop with 10 iterations. Each
iteration displays string "HELLO", sleeps for 300 milliseconds. The application
waits for all the threads to complete & displays the message "Good Bye...".
Program Code:
class HelloThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("HELLO");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
thread1.start();
thread2.start();
thread3.start();
try {
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Good Bye...");
}
}
Output:
Practical 2
Program Code:
class PrimeChecker extends Thread {
private int number;
@Override
public void run() {
if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
// Starting threads
checkerThread.start();
printerThread.start();
}
}
Output: