[go: up one dir, main page]

0% found this document useful (0 votes)
25 views31 pages

Jprpracc (1) (AutoRecovered)

The document contains examples of Java programs demonstrating the use of various Java concepts like conditional statements, loops, operators, threads, constructors, methods of core classes like String and StringBuffer. The programs cover concepts like if-else, switch-case, for loop, while loop, logical operators, ternary operator, threads, constructors, methods of String class and StringBuffer class.

Uploaded by

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

Jprpracc (1) (AutoRecovered)

The document contains examples of Java programs demonstrating the use of various Java concepts like conditional statements, loops, operators, threads, constructors, methods of core classes like String and StringBuffer. The programs cover concepts like if-else, switch-case, for loop, while loop, logical operators, ternary operator, threads, constructors, methods of String class and StringBuffer class.

Uploaded by

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

1. Write any program to check multiple conditions using if statement.

public class MultipleConditions {

public static void main(String[] args) {


int num = 10;
if (num > 0 && num % 2 == 0) {
System.out.println("Number is positive and even.");
}
else
{
System.out.println("Number is negative and odd");
}
}
}

2. Write a program to make the use of logical operators.


public class LogicalOperators {
public static void main(String[] args) {
// Initialize variables
int a = 5;
int b = 10;
int c = 15;

// Logical AND (&&) operator


if (a < b && b < c) {
System.out.println("Condition (a < b && b < c) is true");
} else {
System.out.println("Condition (a < b && b < c) is false");
}

// Logical OR (||) operator


if (a > b || b < c) {
System.out.println("Condition (a > b || b < c) is true");
} else {
System.out.println("Condition (a > b || b < c) is false");
}

// Logical NOT (!) operator


boolean condition = !(a < b);
System.out.println("Logical NOT of (a < b) is: " + condition);
}
}

3. Create three threads and run these threads according to set priority
public class ThreadPriority {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> System.out.println("Thread 1"), "Thread 1");
Thread thread2 = new Thread(() -> System.out.println("Thread 2"), "Thread 2");
Thread thread3 = new Thread(() -> System.out.println("Thread 3"), "Thread 3");

thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.NORM_PRIORITY);
thread3.setPriority(Thread.MAX_PRIORITY);

thread1.start();
thread2.start();
thread3.start();
}
}

4. Write a program to make use of ternary operator.


public class TernaryOperator {

public static void main(String[] args) {

int num = 10;

String result = (num % 2 == 0) ? "Even" : "Odd";

System.out.println(result);

}
5. Write any program to check switch-case statement using character data type.
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("Average");
break;
default:
System.out.println("Invalid grade");
}
}
}

6. Java Program to Check Whether an Alphabet is Vowel or Consonant


import java.util.Scanner;

public class VowelOrConsonant {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||


ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
System.out.println("It is a vowel.");
} else {
System.out.println("It is not a consonant.");
}
}
}
7. Write any program using if condition with for loop.
public class IfConditionWithForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
System.out.println(i + " is even.");
}
}
}
}

8. Write any program to display pyramids of stars/ patterns using increment/decrement.


public class PyramidPattern {

public static void main(String[] args) {

int rows = 5;

for (int i = 1; i <= rows; i++) {

for (int j = 1; j <= rows - i; j++) {

System.out.print(" ");

for (int k = 1; k <= i; k++) {

System.out.print("* ");

System.out.println();

}
}

9 . The program calculate the sum of two Numbers inputted as command line argument
public class SumCommandLine {

public static void main(String[] args) {

if (args.length >= 2) {

int num1 = Integer.parseInt(args[0]);

int num2 = Integer.parseInt(args[1]);

int sum = num1 + num2;

System.out.println("Sum: " + sum);

} else {

System.out.println("Please provide two numbers as command line arguments.");

}// here we added input with java commandline statement with space

10 Develop a program to show the use of implicit typecasting

public class ImplicitTypecasting {


public static void main(String[] args) {

int intValue = 10;


double doubleValue = intValue;
System.out.println("Implicitly converted double value: " + doubleValue);

float floatValue = 20.5f;


double anotherDoubleValue = floatValue;
System.out.println("Implicitly converted double value: " + anotherDoubleValue);
char charValue = 'A';
int intValueFromChar = charValue;
System.out.println("Implicitly converted int value from char: " + intValueFromChar);
}
}

Write a program to implicitly typecast lower range data type to larger storage size data type.

public class ImplicitTypecastingRange {

public static void main(String[] args) {

byte byteValue = 10;


short shortValue = byteValue;
int intValue = byteValue;
long longValue = byteValue;
float floatValue = byteValue;
double doubleValue = byteValue;

System.out.println("byteValue: " + byteValue);


System.out.println("shortValue: " + shortValue);
System.out.println("intValue: " + intValue);
System.out.println("longValue: " + longValue);
System.out.println("floatValue: " + floatValue);
System.out.println("doubleValue: " + doubleValue);
}
}

Develop a program to show the use of explicit type casting.

public class ExplicitTypecasting {


public static void main(String[] args) {
double doubleValue = 10.5;
int intValue = (int) doubleValue;

System.out.println("Original double value: " + doubleValue);


System.out.println("Explicitly casted int value: " + intValue);
}
}

13. Demonstrate use of at least two types of constructors.


public class ConstructorsDemo {
public ConstructorsDemo() {
System.out.println("Default constructor called.");
}

public ConstructorsDemo(int num) {


System.out.println("Parameterized constructor called with value: " + num);
}

public static void main(String[] args) {


ConstructorsDemo obj1 = new ConstructorsDemo();
ConstructorsDemo obj2 = new ConstructorsDemo(10);
}
}

14. Write a program to implement different types of constructors to perform addition of complex
numbers.
class Complex {
double real, imaginary;

Complex() {
real = 0;
imaginary = 0;
}

Complex(double r, double i) {
real = r;
imaginary = i;
}
Complex add(Complex c) {
Complex temp = new Complex();
temp.real = real + c.real;
temp.imaginary = imaginary + c.imaginary;
return temp;
}

void display() {
System.out.println("Sum = " + real + " + " + imaginary + "i");
}

public static void main(String[] args) {


Complex num1 = new Complex(2.5, 3.0);
Complex num2 = new Complex(4.5, 4.5);
Complex sum = num1.add(num2);
sum.display();
}
}

15. Write a program to show the use of all methods of String class.
public class StringMethodsExample {
public static void main(String[] args) {
String str = "Hello, World!";

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

System.out.println("Character at index 7: " + str.charAt(7));

System.out.println("Substring from index 2 to 7: " + str.substring(2, 7));

System.out.println("Concatenated string: " + str.concat(" Welcome"));

System.out.println("Is the string equal to 'Hello, World!'? " + str.equals("Hello, World!"));

System.out.println("Index of 'W' in the string: " + str.indexOf('W'));

System.out.println("Uppercase string: " + str.toUpperCase());

System.out.println("Lowercase string: " + str.toLowerCase());

System.out.println("Replacing 'o' with 'x': " + str.replace('o', 'x'));


String str2 = " Hello, World! ";
System.out.println("Trimmed string: " + str2.trim());
}
}

26. Write a program to implement all methods of StringBuffer class


public class StringBufferMethodsExample {
public static void main(String[] args) {
StringBuffer stringBuffer = new StringBuffer();

// 1. append() method
stringBuffer.append("Hello");

// 2. insert() method
stringBuffer.insert(5, ", World");

// 3. delete() method
stringBuffer.delete(5, 11);

// 4. deleteCharAt() method
stringBuffer.deleteCharAt(5);

// 5. reverse() method
stringBuffer.reverse();

// 6. replace() method
stringBuffer.replace(0, 5, "Hola");

// 7. capacity() method
int capacity = stringBuffer.capacity();

// 8. charAt() method
char charAt = stringBuffer.charAt(0);

// 9. indexOf() method
int indexOf = stringBuffer.indexOf("la");

// 10. substring() method


String substring = stringBuffer.substring(0, 4);
// 11. length() method
int length = stringBuffer.length();

// 12. setCharAt() method


stringBuffer.setCharAt(1, 'i');

// 13. ensureCapacity() method


stringBuffer.ensureCapacity(30);

// 14. toString() method


String string = stringBuffer.toString();

System.out.println("Final StringBuffer content: " + string);


}
}

17. Write a program to implement all methods of Vector class

import java.util.*;
public class Comeg
{
public static void main(String args[])
{
Vector v1 = new Vector();

v1.addElement("Java is Robust");
System.out.println("After the AddElement method
Implementation="+v1);

v1.insertElementAt("Kotlin",0);
System.out.println("After the InsertElement
method Implementation = "+v1);

System.out.println("Size of Vector is ="+v1.size());

v1.removeElementAt(0);
System.out.println("After Removing the Element
="+v1);
}
}

18. Write a program to implement multidimensional array.


public class MultiDimensionalArray {
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}

19. Write a program to display array elements using for-each loop.


public class ArrayForEach {
public static void main(String[] args) {
int[] array = {10, 20, 30, 40, 50};
for (int num : array) {
System.out.print(num + " ");
}
}
}

23. Write a program to convert String value into Integer Wrapper class object
public class StringToInteger {

public static void main(String[] args) {

String str = "123";

Integer intValue = Integer.valueOf(str);

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

20. Write a program to make use of Character Wrapper class methods.


public class CharacterWrapperDemo {
public static void main(String[] args) {
char ch = 'A';

// isDigit() method
System.out.println("Is 'A' a digit? " + Character.isDigit(ch));

// isLetter() method
System.out.println("Is 'A' a letter? " + Character.isLetter(ch));

// toLowerCase() method
System.out.println("Lowercase of 'A': " + Character.toLowerCase(ch));

// toUpperCase() method
System.out.println("Uppercase of 'a': " + Character.toUpperCase('a'));

// isUpperCase() method
System.out.println("Is 'A' uppercase? " + Character.isUpperCase(ch));

// isLowerCase() method
System.out.println("Is 'a' lowercase? " + Character.isLowerCase('a'));
}
}

21. Write a program to convert Integer object value into primitive datatype byte, short and double
value.
public class IntegerToPrimitive {
public static void main(String[] args) {
Integer intValue = 100;
byte byteValue = intValue.byteValue();
short shortValue = intValue.shortValue();
double doubleValue = intValue.doubleValue();
System.out.println("Byte value: " + byteValue);
System.out.println("Short value: " + shortValue);
System.out.println("Double value: " + doubleValue);
}
}

22. Develop a program to display the rate of interest of banks by method overriding method.
class Bank {
double getRateOfInterest() {
return 0;
}
}

class SBI extends Bank {


@Override
double getRateOfInterest() {
return 8.5;
}
}
class ICICI extends Bank {
@Override
double getRateOfInterest() {
return 7.5;
}
}

class AXIS extends Bank {


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

public class BankInterest {


public static void main(String[] args) {
SBI sbi = new SBI();
ICICI icici = new ICICI();
AXIS axis = new AXIS();
System.out.println("SBI Rate of Interest: " + sbi.getRateOfInterest());
System.out.println("ICICI Rate of Interest: " + icici.getRateOfInterest());
System.out.println("AXIS Rate of Interest: " + axis.getRateOfInterest());
}
}

23. 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 {


@Override
void move() {
super.move(); // Calls the move() method of parent class
System.out.println("Dogs can walk and run");
}
}

public class DogDemo {


public static void main(String[] args) {
Dog dog = new Dog();
dog.move();
}
}

28. Develop a program to implement the multilevel inheritance.


class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog is barking");
}
}

class BabyDog extends Dog {


void weep() {
System.out.println("Baby dog is weeping");
}
}

public class MultilevelInheritance {


public static void main(String[] args) {
BabyDog babyDog = new BabyDog();
babyDog.eat();
babyDog.bark();
babyDog.weep();
}
}

24. Develop a program to calculate the room area and volume to illustrate the concept of single
inheritance (Assume suitable data wherever necessary)
class Room {
double length;
double width;
double height;

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


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

double calculateArea() {
return length * width;
}

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

public class RoomDemo {


public static void main(String[] args) {
Room room = new Room(10, 5, 3);
System.out.println("Area of the room: " + room.calculateArea() + " sq units");
System.out.println("Volume of the room: " + room.calculateVolume() + " cubic units");
}
}

25. Develop a program to find area of rectangle and circle using interfaces.
interface Shape {
double area();
}

class Rectangle implements Shape {


double length;
double width;

Rectangle(double length, double width) {


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

@Override
public double area() {
return length * width;
}
}

class Circle implements Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}

@Override
public double area() {
return Math.PI * radius * radius;
}
}

public class AreaDemo {


public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 3);
System.out.println("Area of rectangle: " + rectangle.area());

Circle circle = new Circle(4);


System.out.println("Area of circle: " + circle.area());
}
}

26. Define a package named myInstitute include class named as department with one method to
display the staff of that department. Develop a program to import this package in a java application
and call the method defined in the package.

program to import this package in a java application


and call the method defined in the package.

package my_institute1;
public class Department
{
public void display()
{
System.out.println("Staff are :");
System.out.println("Yash , harsh , ishan , amey ,
eshan");
}
}

import my_institute1.Department;

class Main123
{
public static void main(String args[])
{
Department dep = new Department();
dep.display();
}
}
27. Develop a program which consists of the package named let_me_calculate4 with class named
calculator and a method named add to add two integer numbers. Import let_me_calculate package
in another program( class named Demo) to add two numbers.

package let_me_cal;

public class calculator {


public void add() {
int a = 10;
int b = 20;
int c = a + b;
System.out.println("Addition result: " + c);
}
}
import let_me_cal.calculator;

class Main123
{
public static void main(String args[])
{
calculator cal = new calculator();
cal.add();
}
}

28. Write a program to create two thread one to print odd number only and other to print even
numbers.

class OddThread extends Thread {


public void run() {
for (int i = 1; i <= 10; i += 2) {
System.out.println("Odd number: " + i);
}
}
}

class EvenThread extends Thread {


public void run() {
for (int i = 2; i <= 10; i += 2) {
System.out.println("Even number: " + i);
}
}
}

public class ThreadExample {


public static void main(String[] args) {
OddThread oddThread = new OddThread();
EvenThread evenThread = new EvenThread();
oddThread.start();
evenThread.start();
}
}

29. Write a program to demonstrate the ArithmeticException.


public class ArithmeticExceptionDemo {

public static void main(String[] args) {


try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException occurred: " + e.getMessage());
}
}
}

30. Develop a program to accept a password from the user and throw "Authentication Failure"
exception if the password is incorrect.
import java.util.Scanner;
class PasswordException extends Exception {
PasswordException (String msg) {
super(msg);
}
}
class PassCheck {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
try {
System.out.println("Enter Password: ");
if (scanner.nextLine().equals("abc123")) {
System.out.println("Authenticated ");
} else {
throw new PasswordException("Authentication failure");
}
} catch (PasswordException e) {
System.out.println(e);
}
}
}

31. Define an Exception called "NotMatchException" that is thrown when a string is not equal to
"India". Write a program that uses this exception.
class NotMatchException extends Exception {
NotMatchException(String message) {
super(message);
}
}

public class CustomException {


public static void main(String[] args) {
String country = "USA";
try {
if (!country.equals("India")) {
throw new NotMatchException("String does not match expected value");
}
System.out.println("String matches expected value.");
} catch (NotMatchException e) {
System.out.println(e.getMessage());
}
}
}
32. Develop a basic applet to display "Welcome to the World of Applet".
import java.applet.*;
import java.awt.*;
public class world extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to the world of applets",10,100);
}
}
/*<applet code= "world.class" width=500 height=500></applet>*/

33. Develop a program to implement all methods of applet.

import java.applet.Applet;
import java.awt.*;

public class MyApplet extends Applet {

public void init() {


// Initialization code here
}

public void start() {


// Start code here
}

public void stop() {


// Stop code here
}

public void destroy() {


// Cleanup code here
}

public void paint(Graphics g) {


// Drawing code here
g.drawString("Hello, World!", 50, 50);
}
}

/*<applet code= "MyApplet.class" width=500 height=500></applet>*/

34. Write a program to create animated shape using graphics and applets. You may use following
shapes: Polygons with fill polygon method

35. Develop a program to draw a polygon.


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

public class PolygonApplet extends Applet {

public void paint(Graphics g) {


// Create a polygon with specified coordinates
int[] xPoints = {100, 200, 300, 200};
int[] yPoints = {100, 200, 100, 50};
int nPoints = 4;

// Create the Polygon object


Polygon polygon = new Polygon(xPoints, yPoints, nPoints);

// Draw the polygon


g.drawPolygon(polygon);
}

public static void main(String[] args) {

}
}
/* <applet code="PolygonApplet.class" width=500 height=500>
</applet> */

36. Develop an applet for drawing a human face.


import java.applet.Applet;

import java.awt.*;

public class HumanFaceApplet extends Applet {

public void paint(Graphics g) {

setBackground(Color.white);

g.setColor(Color.black);

g.drawOval(50, 50, 200, 200);

g.fillOval(110, 120, 25, 25);

g.fillOval(175, 120, 25, 25);

g.drawArc(100, 150, 100, 50, 180, 180);

Polygon p = new Polygon();

p.addPoint(150, 135);

p.addPoint(130, 175);

p.addPoint(170, 175);
g.drawPolygon(p);

public String getAppletInfo() {

return "HumanFaceApplet - A simple Java applet for drawing a human face";

/* <applet code="HumanFaceApplet.class" width=500 height=500>

</applet> */

37. Develop a program to draw any 2 of the following shapes: a. Cone b. cone c. cylinder
import java.applet.Applet;
import java.awt.*;

public class CylinderApplet extends Applet {


public void paint(Graphics g) {
setBackground(Color.white);
g.setColor(Color.blue);

// Draw the top circle of the cylinder


g.drawArc(50, 50, 200, 100, 0, 360);

// Draw the bottom circle of the cylinder


g.drawArc(50, 250, 200, 100, 0, 360);

// Draw the lines connecting the circles


g.drawLine(50, 100, 50, 300);
g.drawLine(250, 100, 250, 300);
}

public String getAppletInfo() {


return "CylinderApplet - A simple Java applet for drawing a cylinder";
}
}

/* <applet code="CylinderApplet.class" width=500 height=500>


</applet> */

38. Develop a program to draw any one of the following:

a. Square inside a circle b. Circle inside a square.


import java.applet.*;
import java.awt.*;

public class AppletCircle extends Applet {


public void paint(Graphics g) {
// Draw square
g.drawRect(50, 50, 100, 100);

// Draw circle inside the square


g.drawOval(50, 50, 100, 100);

g.drawString("Circle inside Square", 30, 170);


}
}
/* <applet code="AppletCircle.class" width=500 height=500>
</applet> */

39. Develop a program to copy characters from one file to another.

import java.io.*;

class FileCopy {
public static void main(String args[]) {
int b;
FileReader infile;
FileWriter outfile;

try {
infile = new FileReader("Copy.txt");
outfile = new FileWriter("Copied.txt");
while ((b = infile.read())>0) {
outfile.write(b);
}
// Close the file streams
infile.close();
outfile.close();
System.out.println("File Copied Successfully");

} catch (IOException e) {
System.out.println("An Error occurred: " +
e.getMessage());
}
}
}

40. Develop a program to write bytes to a file.

import java.io.*;

public class FileCopy {


public static void main(String args[]) {
byte b[] = new byte[100];
FileInputStream in = null;
FileOutputStream out = null;

try {
System.out.println("Enter the text to be
saved in the file:");

int bytes = System.in.read(b);

out = new FileOutputStream("Copied.txt");

out.write(b, 0, bytes);
System.out.println("Data written to file
successfully.");
} catch (IOException e) {
System.out.println("An error occurred: " +
e.getMessage());
} finally {
try {
// Close the output file stream
if (out != null) {
out.close();
}
} catch (IOException e) {
System.out.println("Error closing file: " +
e.getMessage());
}
}
}
}

You might also like