Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
43 views28 pages

Tanay

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 28

Practical-1

Aim : Write a program to display Hello World message in console window


Code :
public class Demo {
public static void main ( String[] args){
System.out.println(“Hello World”);
}
}

Output:

Page no: 1
Practical-2
Aim : Write a program to perform arithmetic and bitwise operations in a
single source program without object creation.
Code :
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
float a, b;
System.out.println("Enter the first number:");
a = sc.nextFloat();
System.out.println("Enter the second number:");
b = sc.nextFloat();
System.out.println("Arithmetic operations:");
System.out.println("a+b= " + (a + b));
System.out.println("a-b= " + (a - b));
System.out.println("a*b= " + (a * b));
System.out.println("a/b= " + (a / b));
System.out.println("a%b= " + (a % b));
System.out.println("Bitwise operations:");
int c, d;
System.out.println("Enter the first number");
c = sc.nextInt();
System.out.println("Enter the second number");
d = sc.nextInt();
System.out.println("c|d= " + (c | d));
System.out.println("c&d= " + (c & d));
System.out.println("c^d= " + (c ^ d));
System.out.println("~c= " + (~c));
}
}

Page no: 1
Output:

Page no: 1
Practical-3
Aim : Write a program to perform arithmetic and bitwise operations by
creating individual methods and classes then create an object to execute the
individual methods of each operation.
Code :
import java.util.Scanner;
class Arithmetic {
float num1, num2;
Arithmetic(float num1, float num2) {
this.num1 = num1;
this.num2 = num2;
}
float sum() {
return num1 + num2;
}
float multiply() {
return num1 * num2;
}
float sub() {
return num1 - num2;
}
float div() {
return num1 / num2;
}
float mod() {
return num1 % num2;
}
}
class Bitwise {
int num1, num2;
Bitwise(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
int bitOr() {
return num1 | num2;
}

Page no: 1
int bitAnd() {
return num1 & num2;
}
int bitXOR() {
return num1 ^ num2;
}
int bitNeg() {
return ~num1;
}
}

Output:

Page no: 1
Practical-4
Aim: Write a java program to display employee details using Scanner class.
Code :
import java.util.Scanner;
class Employee {
String name;
int empId, salary;
Employee(int empId, String name, int salary) {
this.name = name;
this.empId = empId;
this.salary = salary;
}
void display() {
System.out.println("Employee Id: " + empId);
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}
}
public class p4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name;
int empId, salary;
System.out.println("Enter the employee name:");
name = sc.nextLine();
System.out.println("Enter the employee ID:");
empId = sc.nextInt();
System.out.println("Enter the employee salary:");
salary = sc.nextInt();
Employee emp = new Employee(empId, name, salary);
emp.display();
}
}
Output:

Page no: 1
Practical-5
Aim : Write a Java program that prints all real solutions to the quadratic
equation ax2+bx+c = 0. Read in a, b, c and use the quadratic formula. If the
discriminant b2 -4ac is negative, display a message stating that there are no
real solutions.
Code :
import java.util.Scanner;
public class p5 {
public static void main(String[] args) {
int a, b, c;
float d;
double x1, x2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the coefficients:");
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
d = b * b - 4 * a * c;
if (d < 0) {
System.out.println("No real roots");
} else {
x1 = (-b + Math.sqrt(d)) / 2 * a;
x2 = (-b - Math.sqrt(d)) / 2 * a;
System.out.println("Roots are: " + x1 + "," + x2);
}
}
}

Output:

Page no: 1
Practical-6
Aim : The Fibonacci sequence is defined by the following rule. The first 2
values in the sequence are 1, 1. Every subsequent value is the sum of the 2
values preceding it. Write a Java program that uses both recursive and
nonrecursive functions to print the nth value of the Fibonacci sequence.
Code :
import java.util.Scanner;
class Fibonacci {
int recursiveFibonacci(int num) {
if (num == 1 || num == 2) {
return 1;
}
return recursiveFibonacci(num - 1) + recursiveFibonacci(num - 2);
}
int iterativeFibonacci(int num) {
int nthTerm, num1 = 1, num2 = 1;
for (int i = 1; i < num; i++) {
nthTerm = num1 + num2;
num1 = num2;
num2 = nthTerm;
}
return num1;
}
}
public class Practice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Fibonacci fib = new Fibonacci();
System.out.println("Enter the number of terms:");
int num = sc.nextInt();
System.out.println(num + "th term of fibonacci series by recursive method is " +
fib.recursiveFibonacci(num));
System.out.println(num + "th term of fibonacci series by non-recursive method is " +
fib.iterativeFibonacci(num));
}
}
Output:

Page no: 1
Practical-7
Aim : Write a Java program that prompts the user for an integer and then
prints out all the prime numbers up to that Integer.
Code :
import java.util.Scanner;
class PrimeNum {
private boolean isPrime(int num) {
if (num < 2) {
return false;
}
boolean flag = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return flag;
}
void getPrimeSeries(int num) {
for (int i = 0; i <= num; i++) {
if (isPrime(i)) {
System.out.print(i + ",");
}
}
}
}
public class p7 {
public static void main(String[] args) {
PrimeNum p = new PrimeNum();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int num = sc.nextInt();
p.getPrimeSeries(num);
}
}

Output:

Page no: 1
Practical-8
Aim : Write a Java program to multiply two given matrices.
Code :
public class matrixmultiplication {
public static void main(String args[]) {
int a[][] = { { 1, 1, 1 }, { 2, 2, 2 }, { 3, 3, 3 } };
int b[][] = { { 1, 1, 1 }, { 2, 2, 2 }, { 3, 3, 3 } };
int c[][] = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
c[i][j] = 0;
for (int k = 0; k < 3; k++) {
c[i][j] += a[i][k] * b[k][j];
}
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}

Output:

Page no: 1
Practical-9
Aim : Write a Java program for sorting a given list of names in ascending
order
Code :
class names {
public static void main(String[] args) {
int n = 4;
String names[] = {
"Devashish",
"Jaimeen",
"Hitanshi",
"Tirth"
};
String temp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (names[i].compareTo(names[j]) > 0) {
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.println("The names in alphabetical order are: ");
for (int i = 0; i < n; i++) {
System.out.println(names[i]);
}
}
}

Output:

Page no: 1
Practical-10
Aim : Write a java program for Method overloading and Constructor
overloading.
Code :
public class cube {
double width, height, depth;
int cubeNo;
cube(double w, double h, double d, int num) {
width = w;
height = h;
depth = d;
cubeNo = num;
}
cube() {
width = height = depth = 0;
}
cube(int num) {
this();
cubeNo = num;
}
public static void main(String[] args) {
cube cube1 = new cube(1, 2, 3, 4);
System.out.println(cube1.width);
}
}

Output:

Page no: 1
Practical-11
Aim : Write a java program to represent an Abstract class with examples.
Code :
abstract class intro {
abstract void speech();
}
class abstractclass extends intro {
void speech() {
System.out.println("I am BATMAN");
}
public static void main(String args[]) {
intro obj = new abstractclass();
obj.speech();
}
}

Output:

Page no: 1
Practical-12
Aim : Write a program to implement multiple Inheritances.
Code :
interface Backend {
public void connectServer();
}
class Frontend {
public void responsive(String str) {
System.out.println(str + " can also be used as frontend.");
}
}
class Language extends Frontend implements Backend {
String language = "Java";
public void connectServer() {
System.out.println(language + " can be used as backend language.");
}
public static void main(String[] args) {
Language java = new Language();
java.connectServer();
java.responsive(java.language);
}
}

Output:

Page no: 1
Practical-13
Aim : Write program to demonstrate method overriding and super
keyword
Code :
class ABC {
public void myMethod() {
System.out.println("Overridden method");
}
}
class overriding extends ABC {
public void myMethod() {
super.myMethod();
System.out.println("Overriding method");
}
public static void main(String args[]) {
overriding obj = new overriding();
obj.myMethod();
}
}

Output:

Page no: 1
Practical-14
Aim : Write a java program to implement Interface using extends keyword
Code :
interface printable {
void print();
}
class one implements printable {
public void print() {
System.out.println("I Am Vengence");
}
public static void main(String args[]) {
one obj = new one();
obj.print();
}
}

Output:

Page no: 1
Practical-15
Aim : Write a java program to create inner classes.
Code :
class outerClass {
int x = 20;
class innerClass {
int y = 49; }
}
class Main {
public static void main(String[] args) {
outerClass myOuter = new outerClass();
outerClass.innerClass myInner = myOuter.new
innerClass();
System.out.println(myInner.y + myOuter.x);
}
}

Output:

Practical-16
Aim : Write a java program to create a user defined package.
Code :
package mypackage;
public class Hello {
public void display() {
System.out.println("Hello from Package");
}
}
import mypackage.Hello;
public class Main {
public static void main(String[] args) {
Hello hello = new Hello();
hello.display();
}
}

Output:

Page no: 1
Practical-17
Aim : Write a Java program that displays the number of characters, lines
and words in a text
Code :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a text: ");
String text = scanner.nextLine();
int characters = text.length();
int words = text.split("\\s+").length;
int lines = text.split("\n").length;
System.out.println("Number of characters: " + characters);
System.out.println("Number of words: " + words);
System.out.println("Number of lines: " + lines);
}
}

Output:

Page no: 1
Practical-18
Aim : Write a Java program that checks whether a given string is a
palindrome or not. Ex: MADAM is a palindrome
Code :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String input = scanner.nextLine();
StringBuffer buffer = new StringBuffer(input);
buffer.reverse();
if (input.equals(buffer.toString())) {
System.out.println("The given string is a palindrome.");
} else {
System.out.println("The given string is not a palindrome.");
}
}
}

Output:

Page no: 1
Practical-19
Aim : Write a Java program that reads a line of integers and then displays
each integer and the sum of all integers. (Use StringTokenizer class)
Code :
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a line of integers separated by spaces: ");
String input = scanner.nextLine();
StringTokenizer tokenizer = new StringTokenizer(input);
int sum = 0;
while (tokenizer.hasMoreTokens()) {
int num = Integer.parseInt(tokenizer.nextToken());
System.out.println("Integer: " + num);
sum += num;
}
System.out.println("Sum: " + sum);
}
}

Output:

Page no: 1
Practical-20
Aim : Write a java program for creating a single try block with multiple
catch blocks.
Code :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two numbers: ");
try {
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int result = num1 / num2;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: Cannot divide by zero.");
} catch (Exception e) {
System.out.println("Exception: Invalid input.");
} finally {
scanner.close();
System.out.println("Scanner closed.");
}
}
}

Output:

Page no: 1
Practical-21
Aim : write a program for multiple try blocks and multiple catch blocks
including finally.
Code :
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number: ");
int num1;
try {
num1 = scanner.nextInt();
} catch (Exception e) {
System.out.println("Exception: Invalid input for first number.");
return;
}
System.out.println("Enter second number: ");
int num2;
try {
num2 = scanner.nextInt();
} catch (Exception e) {
System.out.println("Exception: Invalid input for second number.");
return;
}
try {
int result = num1 / num2;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: Cannot divide by zero.");
} finally {
scanner.close();
System.out.println("Scanner closed.");
}
}
}

Output:

Page no: 1
Practical-22
Aim : write a program to create user defined exception
Code :
import java.util.Scanner;
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your age: ");
int age;
try {
age = scanner.nextInt();
if (age < 0) {
throw new InvalidAgeException("Age cannot be negative.");
}
System.out.println("Age: " + age);
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("Exception: Invalid input for age.");
} finally {
scanner.close();
System.out.println("Scanner closed.");
}
}
}

Output:

Page no: 1
Practical-23
Aim : Write a java program for producer and consumer problems using
Threads.
Code :
package test;
public class Producer implements Runnable {
public StringBuffer sb = null; //Instance variable
public Producer() //0-argument Constructor
{
sb = new StringBuffer();
}
public void run() {
try {
synchronized(sb) {
for (int i = 1; i <= 10; i++) {
sb.append(i + ":");
System.out.println("Producer appending data..");
Thread.sleep(1000);
} //end of loop
sb.notify(); //sending msg_to_Waiting thread
} //end of lock
} catch (Exception e) {
e.printStackTrace();
}
}
}
Consumer.java
package test;
public class Consumer implements Runnable {
public Producer prod = null;
public Consumer(Producer prod) {
this.prod = prod;
}
public void run() {
try {
synchronized(prod.sb) {
System.out.println("Consumer Activated..and Blocked");
prod.sb.wait(); //Blocked
System.out.println("====Display using Consumer===");
System.out.println(prod.sb.toString());
Page no: 1
} //end of lock
} catch (Exception e) {
e.printStackTrace();
}
}
}
DemoThread.java(MainClass)
package maccess;
import test.*;
public class DemoThread {
public static void main(String[] args) {
Producer p = new Producer();
Consumer c = new Consumer(p);

Thread t1 = new Thread(p);


Thread t2 = new Thread(c);

t2.start(); //Consumer activated


t1.start();
}
}

Output:

Page no: 1
Practical-24
Aim : Write a java program that implements a multi-thread application
that has three threads. First thread generates a random integer every 1
second and if the value is even, the second thread computes the square of
the number and prints. If the value is odd, the third thread will print the
value of the cube of the number.
Code :
import java.util.Random;
class Main {
public static void main(String[] args) {
NumberGenerator numberGenerator = new NumberGenerator();
Thread t1 = new Thread(numberGenerator);
SquareCalculator squareCalculator = new SquareCalculator();
Thread t2 = new Thread(squareCalculator);
CubeCalculator cubeCalculator = new CubeCalculator();
Thread t3 = new Thread(cubeCalculator);
t1.start();
t2.start();
t3.start();
}
}
class NumberGenerator implements Runnable {
public void run() {
Random random = new Random();
while (true) {
int number = random.nextInt(100);
System.out.println("Generated Number: " + number);
if (number % 2 == 0) {
synchronized(SquareCalculator.class) {
SquareCalculator.number = number;
SquareCalculator.class.notify();
}
} else {
synchronized(CubeCalculator.class) {
CubeCalculator.number = number;
CubeCalculator.class.notify();
}
}
try {

Page no: 1
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SquareCalculator implements Runnable {
static int number;
public void run() {
while (true) {
synchronized(SquareCalculator.class) {
try {
SquareCalculator.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
int square = number * number;
System.out.println("Square of " + number + " is: " + square);
}
}
}
}
class CubeCalculator implements Runnable {
static int number;
public void run() {
while (true) {
synchronized(CubeCalculator.class) {
try {
CubeCalculator.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
int cube = number * number * number;
System.out.println("Cube of " + number + " is: " + cube);
}
}
}
}

Output:

Page no: 1
Practical-25
Aim : : write a program to create a dynamic array using ArrayList class
and then print the contents of the array object.
Code :
mport java.util.ArrayList;
import java.util.Scanner;
public class DynamicArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList < Integer > array = new ArrayList < > ();
System.out.println("Enter number of elements: ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("Enter element " + (i + 1) + " : ");
int element = sc.nextInt();
array.add(element);
}
System.out.println("Contents of ArrayList: " + array);
}
}

Output:

Page no: 1

You might also like