0% found this document useful (0 votes)
37 views

Javaese Ansbook

Uploaded by

Piush Gogi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Javaese Ansbook

Uploaded by

Piush Gogi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1. Write a program to find greatest among 3 numbers using nested if-else.

import java.util.Scanner;

public class GreatestAmongThree {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter three numbers: ");
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();

if (a > b) {
if (a > c) {
System.out.println("Greatest number is: " + a);
} else {
System.out.println("Greatest number is: " + c);
}
} else {
if (b > c) {
System.out.println("Greatest number is: " + b);
} else {
System.out.println("Greatest number is: " + c);
}
}
}
}
2. Write a program to check if user entered password contains Uppercase, Lowercase, and no. Characters
using logical operators.
import java.util.Scanner;

public class PasswordChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your password: ");
String password = scanner.nextLine();

boolean hasUpperCase = false;


boolean hasLowerCase = false;
boolean hasNumber = false;

for (char c : password.toCharArray()) {


if (Character.isUpperCase(c)) {
hasUpperCase = true;
} else if (Character.isLowerCase(c)) {
hasLowerCase = true;
} else if (Character.isDigit(c)) {
hasNumber = true;
}
}

if (hasUpperCase && hasLowerCase && hasNumber) {


System.out.println("Password is valid.");
} else {
System.out.println("Password is invalid. Make sure it contains uppercase, lowercase, and
numeric characters.");
}
}
}
3. Write any program to check switch-case statement using character datatype.
public class SwitchCaseChar {
public static void main(String[] args) {
char grade = 'B';

switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
System.out.println("Good!");
break;
case 'C':
System.out.println("Fair!");
break;
case 'D':
System.out.println("Needs Improvement!");
break;
default:
System.out.println("Invalid Grade!");
}
}
}

4. Develop a program to print command line argument using for loop.


public class CommandLineArguments {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}

5. Write a program to display the following star pattern using for loop.

*
**
***
****

public class StarPattern {


public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
6. Write a program to display multiplication table of 7 using do-while loop.
public class MultiplicationTableSeven {
public static void main(String[] args) {
int num = 7;
int i = 1;
do {
System.out.println(num + " x " + i + " = " + (num * i));
i++;
} while (i <= 10);
}
}

7. Write a program to implicitly typecast lower range data type to larger storage size data type.
public class TypeCasting {
public static void main(String[] args) {
int numInt = 100;
long numLong = numInt;
float numFloat = numLong;

System.out.println("Integer value: " + numInt);


System.out.println("Implicitly casted to long: " + numLong);
System.out.println("Implicitly casted to float: " + numFloat);
}
}

8. Write a program to convert variable of basic data types and shows result of explicit typecasting.
public class TypeCastingExplicit {
public static void main(String[] args) {
double numDouble = 10.5;
int numInt = (int) numDouble;
long numLong = (long) numDouble;

System.out.println("Double value: " + numDouble);


System.out.println("Explicitly casted to int: " + numInt);
System.out.println("Explicitly casted to long: " + numLong);
}
}
9. Write a program to perform constructor overloading.
public class ConstructorOverloading {
private int value;

// Default constructor
public ConstructorOverloading() {
this.value = 0;
}

// Parameterized constructor
public ConstructorOverloading(int value) {
this.value = value;
}

public int getValue() {


return value;
}

public static void main(String[] args) {


ConstructorOverloading obj1 = new ConstructorOverloading();
ConstructorOverloading obj2 = new ConstructorOverloading(10);

System.out.println("Value of obj1: " + obj1.getValue());


System.out.println("Value of obj2: " + obj2.getValue());
}
}

10. Write a program to show the use any 6 methods of string class.
public class StringMethods {
public static void main(String[] args) {
String str = "Hello, World!";

System.out.println("Length: " + str.length());


System.out.println("Substring: " + str.substring(7));
System.out.println("Index of 'o': " + str.indexOf('o'));
System.out.println("Uppercase: " + str.toUpperCase());
System.out.println("Lowercase: " + str.toLowerCase());
System.out.println("Replace: " + str.replace("World", "Java"));
}
}
11. Write a program to use 4 methods string buffer class.
public class StringBufferMethods {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer("Hello");

System.out.println("Initial Buffer: " + buffer);


buffer.append(" World");
System.out.println("Appended Buffer: " + buffer);
buffer.insert(6, ", Java");
System.out.println("Inserted Buffer: " + buffer);
buffer.delete(5, 10);
System.out.println("Deleted Buffer: " + buffer);
buffer.reverse();
System.out.println("Reversed Buffer: " + buffer);
}
}

12. Write a program to implement 3 X 3 matrix multiplication.


public class MatrixMultiplication {
public static void main(String[] args) {
int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] matrix2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int[][] result = new int[3][3];

// Perform matrix multiplication


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Display the result


System.out.println("Resultant Matrix:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
13. Write a program to display elements of array using for-each loop.
public class DisplayArray {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};

for (int element : array) {


System.out.print(element + " ");
}
}
}

14. Write a program to insert different elements in the vector and display it.
import java.util.Vector;

public class VectorExample {


public static void main(String[] args) {
Vector<Integer> vector = new Vector<>();

// Inserting elements into the vector


vector.add(10);
vector.add(20);
vector.add(30);
vector.add(40);

// Displaying elements of the vector


System.out.println("Elements of the vector:");
for (int i = 0; i < vector.size(); i++) {
System.out.println(vector.get(i));
}
}
}

15. Write a program to convert

(I) Primitive data type into string object


(II) String value into Integer Wrapper class object.
public class TypeConversion {
public static void main(String[] args) {
// (I) Primitive data type to string object
int num = 10;
String str = Integer.toString(num);
System.out.println("String representation of primitive data type: " + str);

// (II) String value into Integer Wrapper class object


String numberStr = "100";
Integer integerObj = Integer.valueOf(numberStr);
System.out.println("Integer wrapper class object: " + integerObj);
}
}
16. Develop a program to extend ‘dog’ from ‘animal’ to override ‘move()’ method using super keyword.
class Animal {
void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal {


void move() {
super.move(); // Calling move() method of super class
System.out.println("Dogs can walk and run");
}
}

public class SuperExample {


public static void main(String[] args) {
Dog dog = new Dog();
dog.move(); // This will call overridden move() method of Dog class
}
}
17. Write a program to display rate of interest of bank using method overriding.
class Bank {
double getRateOfInterest() {
return 0;
}
}

class SBI extends Bank {


@Override
double getRateOfInterest() {
return 7.5;
}
}

class ICICI extends Bank {


@Override
double getRateOfInterest() {
return 8.0;
}
}

public class MethodOverridingExample {


public static void main(String[] args) {
SBI sbi = new SBI();
ICICI icici = new ICICI();

System.out.println("Rate of interest in SBI: " + sbi.getRateOfInterest());


System.out.println("Rate of interest in ICICI: " + icici.getRateOfInterest());
}
}
18. Write a program to calculate area and volume of room using single inheritance.
class Room {
double length;
double width;

Room(double length, double width) {


this.length = length;
this.width = width;
}

double calculateArea() {
return length * width;
}
}

class Room3D extends Room {


double height;

Room3D(double length, double width, double height) {


super(length, width);
this.height = height;
}

double calculateVolume() {
return length * width * height;
}
}

public class SingleInheritanceExample {


public static void main(String[] args) {
Room3D room = new Room3D(10, 5, 3);
System.out.println("Area of the room: " + room.calculateArea());
System.out.println("Volume of the room: " + room.calculateVolume());
}
}
19. Develop a program for implementation of multiple inheritance using interface.
interface A {
void methodA();
}

interface B {
void methodB();
}

class MyClass implements A, B {


public void methodA() {
System.out.println("Method A");
}

public void methodB() {


System.out.println("Method B");
}
}

public class MultipleInheritanceExample {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.methodA();
obj.methodB();
}
}

20. Define a package named ‘College’ include class named as ‘Dept’ with one method to display the name
of the department. Develop a program to import this package in a java application and call the method
defined in the package.
// College/Dept.java
package College;

public class Dept {


public void displayDepartment() {
System.out.println("Computer Science Department");
}
}
// Importing package in Java application
import College.Dept;

public class PackageImportExample {


public static void main(String[] args) {
Dept department = new Dept();
department.displayDepartment();
}
}
21. Develop a program to implement multithreading by creating two threads “even” and “odd”.
public class EvenOddThread {
public static void main(String[] args) {
EvenThread evenThread = new EvenThread();
OddThread oddThread = new OddThread();

evenThread.start();
oddThread.start();
}
}

class EvenThread extends Thread {


public void run() {
for (int i = 2; i <= 10; i += 2) {
System.out.println("Even: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class OddThread extends Thread {


public void run() {
for (int i = 1; i <= 10; i += 2) {
System.out.println("Odd: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
22. Write a program to implement the different priorities in multithreading.
public class ThreadPriorityExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread(), "Thread 1");
Thread t2 = new Thread(new MyThread(), "Thread 2");

// Setting priorities
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);

t1.start();
t2.start();
}
}

class MyThread implements Runnable {


public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(500); // Sleep for 0.5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

23. Develop a program to catch “DivideByZeroException”.


public class DivideByZeroExceptionExample {
public static void main(String[] args) {
int numerator = 10;
int denominator = 0;

try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
24. Define a Exception called “NotMatchException” that is thrown when a string is not equal to “msbte”.
Write a program that uses this exception.
import java.io.*;
class NoMatchException extends Exception
{
NoMatchException(String s)
{
super(s);
}
}
class test1
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in) );
System.out.println("Enter a word:");
String str= br.readLine();
try
{
if (str.compareTo("MSBTE")!=0) // can be done with equals()
throw new NoMatchException("Strings are not equal");
else
System.out.println("Strings are equal");
}
catch(NoMatchException e)
{
System.out.println(e.getMessage());
}
}
}

25. Develop a basic applet to display “Welcome to the world of Applet”.


import java.applet.Applet;
import java.awt.Graphics;

public class WelcomeApplet extends Applet {


public void paint(Graphics g) {
g.drawString("Welcome to the world of Applet", 50, 50);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Applet Example</title>
</head>
<body>
<applet code="WelcomeApplet.class" width="300" height="200">
</applet>
</body>
</html>
26. Develop a program to accept username and password and check if password is greater than 8 letters
using <param> tag.
import java.applet.Applet;
import java.awt.Graphics;

public class PasswordApplet extends Applet {


String username, password;

public void init() {


username = getParameter("username");
password = getParameter("password");

if (password.length() > 8) {
System.out.println("Password length is greater than 8 characters.");
} else {
System.out.println("Password length is not greater than 8 characters.");
}
}

public void paint(Graphics g) {


g.drawString("Username: " + username, 50, 50);
g.drawString("Password: " + password, 50, 70);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Password Applet</title>
</head>
<body>
<applet code="PasswordApplet.class" width="300" height="200">
<param name="username" value="john">
<param name="password" value="password123">
</applet>
</body>
</html>
27. Write a program to draw a polygon.
import java.awt.*;
import javax.swing.*;

public class PolygonDrawing extends JPanel {


public void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xPoints = {50, 100, 150, 100};
int[] yPoints = {50, 100, 50, 0};
int nPoints = 4;

g.drawPolygon(xPoints, yPoints, nPoints);


}

public static void main(String[] args) {


JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PolygonDrawing());
frame.setSize(200, 200);
frame.setVisible(true);
}
}

28. Write a program to draw circle inside a square.


import java.awt.*;
import javax.swing.*;

public class CircleInSquare extends JPanel {


public void paintComponent(Graphics g) {
super.paintComponent(g);
int squareSize = 100;
int circleDiameter = 80;
int squareX = (getWidth() - squareSize) / 2;
int squareY = (getHeight() - squareSize) / 2;

g.drawRect(squareX, squareY, squareSize, squareSize);


g.drawOval(squareX + (squareSize - circleDiameter) / 2, squareY + (squareSize - circleDiameter)
/ 2, circleDiameter, circleDiameter);
}

public static void main(String[] args) {


JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CircleInSquare());
frame.setSize(200, 200);
frame.setVisible(true);
}
}
29. Develop a program to copy the content of one file into another.
import java.io.*;

public class FileCopy {


public static void main(String[] args) {
try {
FileReader source = new FileReader("source.txt");
FileWriter destination = new FileWriter("destination.txt");
int c;
while ((c = source.read()) != -1) {
destination.write(c);
}
source.close();
destination.close();
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

30. Write a program to count the number of words in file.


import java.io.*;

public class WordCount {


public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("input.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
int wordCount = 0;
while ((line = bufferedReader.readLine()) != null) {
String[] words = line.split("\\s+");
wordCount += words.length;
}
bufferedReader.close();
System.out.println("Number of words in the file: " + wordCount);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

You might also like