NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

LAB:1
1] Write a program to display “Welcome To Java World”.
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
}
}
2]Write a program to find whether the number is prime or not.
import java.util.Scanner;

class prime {
public static void main(String[] args) {
boolean flag = true;
System.out.println("Enter a number : ");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0)
flag = false;
break;
}
if (flag == true)
System.out.println("The number is prime");
else
System.out.println("The number is not prime");
}
}

3. Write a program to find a greater number among given three numbers using
a) ternary operator

A) CODE -
import java.util.Scanner;

class greatest {
public static void main(String a[]) {
System.out.println("Enter three numbers : ");
Scanner input = new Scanner(System.in);
int n1 = input.nextInt();
int n2 = input.nextInt();
int n3 = input.nextInt();
int largest = n3 > (n1 > n2 ? n1 : n2) ? n3 : ((n1 > n2) ? n1 : n2);
System.out.println("Largest Number : " + largest);
}
}
b) nested if

import java.util.Scanner;

class greatest {
public static void main(String a[]) {
System.out.println("Enter three numbers: ");
Scanner input = new Scanner(System.in);
int n1 = input.nextInt();
int n2 = input.nextInt();
int n3 = input.nextInt();
if (n1 > n2 && n1 > n3)
System.out.println(n1 + " is greatest");

else if (n2 > n3)
System.out.println(n2 + " is greatest");

else
System.out.println(n3 + " is greatest");
}
}
4. Write a program to print the Fibonacci series.
import java.util.Scanner;

public class fibonacci {
public static void main(String[] args) {
int a = 0, b = 1, c;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of terms in series: ");
int n = input.nextInt();
System.out.print(a + " " + b);
for (int i = 2; i < n; i++) {
c = a + b;
System.out.print(" " + c);
a = b;
b = c;
}
}
}
LAB - 2:

Write a program to find the average of n numbers stored in an Array.
import java.util.*;

public class average {
public static void main(String[] args) {
int sum = 0;
int[] input = new int[50];
System.out.println("How many numbers do you want to enter?");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println("Enter the numbers:");
for (int i = 0; i < n; i++) {
input[i] = in.nextInt();
sum += input[i];
}
System.out.println("Average = " + ((double) sum / n)); // Type conversion (int to double)
}
}
LAB - 3:

1. WAP to replace substring with another substring in the given string.
public class substring {
public static void main(String[] args) {
String str = "This is a string";
System.out.println("Original string : " + str);

String replace = str.replace("This", "That");
System.out.println("Replaced string : " + replace);
}
}
2. WAP that to sort given strings into alphabetical order.
import java.util.Scanner;

public class Main
{
public static void main(String[] args)
{
int n;
String tmp;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of names you want to enter : ");
n = scanner.nextInt();

String names[] = new String[n];
Scanner scanner1 = new Scanner(System.in);
System.out.println("Enter the list of names:");

for(int i=0; i < n; i++)
{
names[i] = scanner1.nextLine();
}
for (int i=0; i < n; i++)
{
for (int j=i+1; j < n; j++)
{
if (names[i].compareTo(names[j]) > 0)
{
tmp = names[i];
names[i] = names[j];
names[j] = tmp;
}
}
}
System.out.print("List of names in sorted order is : ");
for (int i=0; i < n-1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
}

3. Create a String Buffer with some default string. Append any string to ith position of the original string and display the modified string. Also display the reverse of modified string.

public class stringbuffer {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java ");
System.out.println("Original String : " + sb);
sb.append("Programming");
System.out.println("Modified String : " + sb);
sb.reverse();
System.out.println("Reverse String : " + sb);
}
}
LAB - 4:
1. a) WAP that declares a class named Person. It should have instance variables to record name, age and salary. Use a new operator to create a Person object. Set and display its instance variables.
b) Add a constructor to the Person class developed above.

import java.util.*;

public class Person {
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int no = sc.nextInt();
float salary = sc.nextFloat();

public Person() {
System.out.println("name:" + name);
System.out.println("Age: " + no);
System.out.println("Salary: " + salary);
}

public static void main(String[] args) {
Person p = new Person();
}
}
2. The employee list for a company contains employee code, name, designation and basic pay. The employee is given HRA of 10% of the basic pay and DA of 45% of the basic pay. The total pay of the employee is calculated as Basic pay+HRA+ DA. Write a class to define the details of the employee. Write a constructor to assign the required initial values. Add a method to calculate HRA, DA and Total pay and print them out. Write another class with a main method. Create objects for three different employees and calculate the HRA, DA and total pa

public class employee {
int emp_code;
String name, desg;
double basic_pay, total, hra, da;

employee(int a, String b, String c, double d) {
emp_code = a;
name = b;
desg = c;
basic_pay = d;
}

public void display() {
hra = 0.1 * basic_pay;
da = 0.45 * basic_pay;
total = basic_pay + hra + da;
System.out.println("nEmployee code : " + emp_code);
System.out.println("Name : " + name);
System.out.println("Designation : " + desg);
System.out.println("Total salary : " + total);
}

public static void main(String[] args) {
employee emp1 = new employee(101, "Amar", "CEO", 700000);
employee emp2 = new employee(102, "Akbar", "Director", 500000);
employee emp3 = new employee(103, "Anthony", "President", 300000);
emp1.display();
emp2.display();
emp3.display();
}
}
LAB - 5:

1. Write a program which defines base class Employee having three data members, namely name[30], emp_numb and gender and two methods namely input_data() and show_data(). Derive a class SalariedEmployee from Employee and add a new data member, namely salary. It also adds two member methods, namely allowance (if gender is female HRA=0.1 *salary else 0.09* salary. DA= 0.05*salary) and increment (salary= salary+0.1*salary). Display the gross salary in the main class. (Tip: Use super to call base class’s constructor0).

class Employee {
int emp_numb;
String name;
String gender;

Employee(int e, String n, String g) {
input_data(e, n, g);
}

void input_data(int e1, String n1, String g1) {
emp_numb = e1;
name = n1.toUpperCase();
gender = g1.toUpperCase();
show_data();
}

void show_data() {
System.out.println("Emp_num: " + emp_numb + "tName: " + name + "tGender:" + gender);
}
}

class SalariedEmployee extends Employee {
double salary, HRA, DA;
SalariedEmployee(int e3, String n3, String g3, double s) {
super(e3, n3, g3);
salary = s;
}
double allowance() {
DA = (0.05) * salary;
if (gender.equals("FEMALE")) {
HRA = (0.1) * salary;
} else {
HRA = (0.09) * salary;
}
return (HRA + DA);
}

double increment() {
salary = salary + (0.1 * salary);
return salary;
}
}

class Test {
public static void main(String args[]) {
SalariedEmployee emp1 = new SalariedEmployee(1, "Gabbar", "Male", 69000);
System.out.println("nGross Salary for " + emp1.name + ":" + (emp1.salary + emp1.allowance() + emp1.increment()));
}
}
2. WAP that illustrates method overriding. Class A3 is extended by Class B3. Each of these classes defines a hello(string s) method that outputs the string “A3: Hello From” or “B3: Hello From” respectively. Use the concept Dynamic Method Dispatch and keyword super.
import java.util.*;

class A3 {
String S;

A3(String s) {
hello(s);
}

public void hello(String s) {
S = s;
System.out.println("A3 : Hello From " + S);
}
}

class B3 extends A3 {
B3(String s) {
super(s);
}

public void hello(String s) {
S = s;
System.out.println("B3 : Hello From " + S);
}
}

class Test {
public static void main(String args[]) {
A3 a = new A3("GG");
A3 b = new B3("GG");
}
}

LAB - 6:
1. Write an abstract class shape, which defines an abstract method area. Derive class circle from shape. It has data member radius and implementation for area function. Derive class Triangle from shape. It has data members height, base and implementation for area function. Derive class Square from shape. It has data member side and implementation for area function. In the main class, use dynamic method dispatch in order to call the correct version of the method.

import java.util.*;

abstract class Shape {
abstract void area();
}

class Circle extends Shape {
double radius;

void area() {
System.out.println("nArea of Circle: " + (3.14 * radius * radius));
}
}

class Triangle extends Shape {
double height, base;

void area() {
System.out.println("Area of Triangle: " + ((height * base) / 2));
}
}

class Square extends Shape {
double side;

void area() {
System.out.println("Area of Square: " + (side * 2));
}
}

class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Circle C1 = new Circle();
System.out.println("Enter the Radius");
C1.radius = sc.nextDouble();
Triangle T1 = new Triangle();
System.out.println("Enter height & base:");
T1.height = sc.nextDouble();
T1.base = sc.nextDouble();
Square S1 = new Square();
System.out.println("Enter the value of side:");
S1.side = sc.nextDouble();
Shape S;
S = C1;
S.area();
S = T1;
S.area();
S = S1;
S.area();
}
}
2. Create an interface Shape2D which declares a getArea() method.. The abstract class Shape declares abstract display () method .Circle class is extended from shape class and implemented from shape 2D interface. Write appropriate method required in class circle and Create instance of circle object and display area of circle
import java.util.*;

interface Shape2D {

void getArea();
}

abstract class Shape {
abstract void display();
}

class Point3D {
double x, y, z;

Point3D(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
}

class Circle extends Shape implements Shape2D {
Point3D CenterPoint, OtherPoint;
double area;

Circle(Point3D P1, Point3D P2) {
CenterPoint = P1;
OtherPoint = P2;
}

public void getArea() {
double d1 = CenterPoint.x - OtherPoint.x;
double d2 = CenterPoint.y - OtherPoint.y;
double d = (d1 * d1) + (d2 * d2);
double radius = Math.sqrt(d);
area = Math.PI * radius * radius;
}

public void display() {
System.out.println("nGiven points-> Center Point: (" + CenterPoint.x + "," + CenterPoint.y + ", "
+ CenterPoint.z + ") , Other Point: (" + OtherPoint.x + "," + OtherPoint.y + ", " + OtherPoint.z
+ ")nArea for a circle having given points: " + area + "n");
}
}

class Main {
public static void main(String args[]) {
Point3D point1 = new Point3D(7, 4, 6);
Point3D point2 = new Point3D(5, 2, 8);
Circle obj = new Circle(point1, point2);
obj.getArea();
obj.display();
}
}
LAB - 7:
1. Create a package “employee” and define a Class Employee having three data members, name, emp_num, and gender and two methods- input_data and show_data. Inherit class SalariedEmployee from this class and keep it in package “employee”. Add new variable salary and methods allowance (if female hra=0.1* salary else 0.09* salary. DA= 0.05*salary) and increment (salary= salary+0.01 * salary). Calculate gross salary in the main class defined in the same package.
package employee;

class Employee {
public int emp_numb;
public String name;
public String gender;

public Employee(int e, String n, String g) {
input_data(e, n, g);
}

public void input_data(int e1, String n1, String g1) {
emp_numb = e1;
name = n1.toUpperCase();
gender = g1.toUpperCase();
show_data();
}

public void show_data()
{
System.out.println("---------------------------------------------------");
System.out.println("Emp_num: "+emp_numb+"tName: "+name+"tGender:
"+gender);
}
}

public class Test extends Employee {
public double salary, HRA, DA;

public Test(int e3, String n3, String g3, double s) {
super(e3, n3, g3);
salary = s;
}

public double allowance()
{
DA = (0.05)*salary;
if(gender.equals("FEMALE"))
{
HRA = (0.1)*salary;
}
else
{
HRA = (0.09)*salary;
}
return (HRA+DA);
}

public double increment() {
salary = salary + (0.1 * salary);
return salary;
}
}

import employee.Test;

class Test1 {
public static void main(String args[])
{
Test emp1 = new Test(1,"Gangey","male",30000);
System.out.println("nGross Salary for "+emp1.name+ ":
"+(emp1.salary+emp1.allowance()+emp1.increment()));
Test emp2 = new Test(2,"Natasha","female",30000);
System.out.println("nGross Salary for "+emp1.name+ ":
"+(emp1.salary+emp1.allowance()+emp1.increment()));
}
}
LAB - 8:
1. WAP using try catch block. User should enter two command line arguments. If only one argument is entered then an exception should be caught. In case of two command line arguments, if fist is divided by second and if second command line argument is 0 then catch the appropriate exception.
class NewException extends Exception {
String m;

NewException(String message) {
m = message;
}

void printmsg() {
System.out.println(m);
}
}

class Main {
public static void main(String args[]) {
int num[] = new int[args.length];
try {
if (args.length < 2) {
throw new NewException("Require at least 2 command line arguments.");
}
for (int i = 0; i < args.length; i++) {
num[i] = Integer.parseInt(args[i]);
}
int a = (int) num[0];
int b = (int) num[1];
double div = a / b;
System.out.println("nDivision successful. No exceptions found.n" + a + "/" + b + " = " + div);
} catch (NewException e) {
System.out.println("nException Caught: ");
e.printmsg();
} catch (NumberFormatException e2) {
System.out.println("nException Caught: ");
System.out.println("Require Integer arguments.");
} catch (ArithmeticException e3) {
System.out.println("nException Caught: ");
System.out.println("Division by Zero.");
}
}
}
2. Define an exception called “NoMatchException” that is thrown when a string is not equal to “India”. Write a program that uses this exception.
class NoMatchException extends Exception {
String m;

NoMatchException(String message) {
m = message;
}

void printmsg() {
System.out.println(m);
}
}

class Main {
public static void main(String args[]) {
if (args.length != 1) {
System.out.println("nEnter only one String argument");
} else {
try {
if (args[0].compareTo("Gappi") == 0) {
System.out.println("nString is equal to 'Gappi'.");
} else {
throw new NoMatchException("Arguments is not equal to 'Gappi'.");
}
} catch (NoMatchException e) {
System.out.println("nOh no...WASTED ");
e.printmsg();
}
}
}
}

LAB - 9:
1. The program creates and run the following three threads. The first thread prints the letter ‘a’ 100 times.
The second thread prints the letter ‘b’ 100 times.
The third thread prints the integer 1 to 100.
class A extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.print("at");
}
}
}

class B extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.print("bt");
}
}
}

class C extends Thread {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.print((i + 1) + "t");
}
}
}
class Main {
public static void main(String args[]) {
new A().start();
new B().start();
new C().start();
}
}
2. Write the thread program -using Runnable interface.
class MyThread implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("NewThread: " + (i + 1));
}
System.out.println("End of NewThread");
}
}
class Main {
public static void main(String args[]) {
MyThread runn = new MyThread();
Thread NewThread = new Thread(runn);
NewThread.start();
System.out.println("nEnd of main Thread");
}
}
LAB - 10:
1. Write a program that takes two files names (source and destination) as command line argument .Copy source file’s content to destination file. Use character stream class. Also do the same using byte stream and buffer stream.
import java.io.*;

class Main {
public static void main(String[] args) {
String f_name1 = args[0];
String f_name2 = args[1];
FileReader Infile = null;
FileWriter Outfile = null;
int ReadC;
try {
Infile = new FileReader(f_name1);
Outfile = new FileWriter(f_name2);
while ((ReadC = Infile.read()) != -1) {
System.out.print((char) ReadC);
Outfile.write(ReadC);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found!");
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
Infile.close();
Outfile.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
2. Write a program which generates random integers and stores them in a file named “rand.dat”. The program then reads the integers from the file and displays on the screen.
import java.io.*;
import java.util.*;

class Test {
public static void main(String args[]) {
FileWriter FW = null;
BufferedWriter bfwr = null;
File inFile = new File("rand.dat");
try {
int rand_int;
FW = new FileWriter(inFile);
bfwr = new BufferedWriter(FW);
Random generate_rand = new Random();
System.out.println("nGenerating & Storing Random integers from 0 to 99..n");
for (int i = 0; i < 10; i++) {
rand_int = generate_rand.nextInt(100);
System.out.print(rand_int + "t");
bfwr.write(rand_int + "rn");
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
bfwr.close();
} catch (IOException e) {
}
}
try {
System.out.println("nRetrieving Random integers stored in file 'rand.dat'..");
Scanner scanner = new Scanner(inFile);
while (scanner.hasNextInt()) {
System.out.println(scanner.nextInt() + "t");
}
} catch (NullPointerException e) {
System.out.println(e.getMessage());
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
LAB - 11:

1. Write the program that demonstrate the use of Stack, Vector and ArrayList classes.
// 1. Stack:
import java.util.Stack;

public class Test {
public static void main(String[] args) {
Stack s = new Stack();
s.push("its");
s.push("gap");
s.push("pi");
s.push("he");
s.push("re");
s.push(null);
s.push(true);
System.out.println(s);
s.pop();
System.out.println(s);
s.pop();
System.out.println(s);
s.pop();
System.out.println(s);
s.pop();
}
}
// 2. ArrayList:
import java.util.ArrayList;

public class Test {
public static void main(String[] args) {
ArrayList<Comparable> arr = new ArrayList();
arr.add(1);
arr.add('a');
arr.add(10.2);
arr.add("clavie");
arr.add('c');
arr.add(true);
System.out.println(arr);
System.out.println(arr.size());
arr.remove(1);
arr.remove("clavie");
arr.add(0, "40");
System.out.println(arr);
System.out.println(arr.size());
}
}
// 3. Vector:
import java.util.Vector;
import java.util.Enumeration;

public class Test {
public static void main(String args[]) {
Enumeration days;
Vector Names = new Vector();
Names.add("ZLATANMAY");
Names.add("Jainam18");
Names.add("kush_02");
Names.add("Anshulp1806");
Names.add("Devu_1108");
Names.add("deadpooloi");
Names.add("itsdj");
Names.add("itsgappihere");
days = Names.elements();
while (days.hasMoreElements()) {
System.out.println(days.nextElement());
}
}
}
LAB - 12:

1. Write a Network program where the client sends the data as radius of circle to server and server receives that data and sends the resultant area of circle to requested client.
//MyServer.java
import java.io.*;
import java.net.*;

public class MyServer {
public static void main(String[] args){try{
ServerSocket ss=new ServerSocket(1111);

Socket s=ss.accept();

DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();

System.out.println("message= "+str);
ss.close();

}catch(Exception e)
{System.out.println(e);}
}//psvm
}//class
//MyClient.java
import java.net.*;
import java.io.*;

public class MyClient {
public static void main(String[] args){
try {
Socket s=new Socket("localhost",1111);

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

dout.writeUTF("Hello Server");
}//try
catch(Exception e)
{System.out.println(e);}
} //psvm
}//class

LAB - 13:
1. Write a program to count occurrence of character in a string.
class Test
{
// Method that return count of the given
// character in the string
public static int count(String s, char c)
{
int res = 0;

for (int i=0; i<s.length(); i++)
{
// checking character in string
if (s.charAt(i) == c)
res++;
}
return res;
}

// Driver method
public static void main(String args[])
{
String str= "NotFairAtAll";
char c = 'A';
System.out.println(c + " appears in string "+count(str, c)+" times");
}
}







     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.