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

Codes

Uploaded by

muskanbhushan2
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Codes

Uploaded by

muskanbhushan2
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

//palindrome number

import java.util.Scanner;

public class PalindromeNumberChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter a number:");
int number = scanner.nextInt();

if (isPalindrome(number)) {
System.out.println("The number " + number + " is a palindrome.");
} else {
System.out.println("The number " + number + " is not a palindrome.");
}

scanner.close();
}

public static boolean isPalindrome(int num) {


int originalNumber = num;
int reversedNumber = 0;

while (num != 0) {
int digit = num % 10;
reversedNumber = reversedNumber * 10 + digit;
num /= 10;
}

return originalNumber == reversedNumber;


}
}

// prime or not

import java.util.Scanner;

public class PrimeNumberChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter a number:");
int number = scanner.nextInt();

if (isPrime(number)) {
System.out.println("The number " + number + " is a prime number.");
} else {
System.out.println("The number " + number + " is not a prime number.");
}
scanner.close();
}

public static boolean isPrime(int num) {


// Prime numbers are greater than 1
if (num <= 1) {
return false;
}
// Check divisibility from 2 to the square root of the number
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}

//Fibonacci nos.

import java.util.Scanner;

public class FibonacciSequence {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the number of terms:");


int n = scanner.nextInt();

System.out.println("Fibonacci sequence up to " + n + " terms:");


for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}

scanner.close();
}

public static int fibonacci(int n) {


if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

//method overloading (volume)


import java.util.Scanner;

public class VolumeCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Choose the shape to calculate volume:");


System.out.println("1. Cube");
System.out.println("2. Cylinder");
System.out.println("3. Sphere");
int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.println("Enter the side length of the cube:");
double side = scanner.nextDouble();
System.out.println("Volume of the cube: " + calculateVolume(side));
break;
case 2:
System.out.println("Enter the radius of the cylinder:");
double radius = scanner.nextDouble();
System.out.println("Enter the height of the cylinder:");
double height = scanner.nextDouble();
System.out.println("Volume of the cylinder: " +
calculateVolume(radius, height));
break;
case 3:
System.out.println("Enter the radius of the sphere:");
double sphereRadius = scanner.nextDouble();
System.out.println("Volume of the sphere: " +
calculateVolume(sphereRadius));
break;
default:
System.out.println("Invalid choice.");
}

scanner.close();
}

// Overloaded method to calculate the volume of a cube


public static double calculateVolume(double side) {
return Math.pow(side, 3);
}

// Overloaded method to calculate the volume of a cylinder


public static double calculateVolume(double radius, double height) {
return Math.PI * Math.pow(radius, 2) * height;
}

// Overloaded method to calculate the volume of a sphere


public static double calculateVolume(double radius) {
return (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);
}
}
//method overriding

class Animal {
// Method to be overridden
public void makeSound() {
System.out.println("Some generic animal sound");
}
}

class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Woof");
}
}

class Cat extends Animal {


@Override
public void makeSound() {
System.out.println("Meow");
}
}

public class MethodOverridingExample {


public static void main(String[] args) {
Animal myAnimal;

myAnimal = new Dog();


myAnimal.makeSound(); // Outputs: Woof

myAnimal = new Cat();


myAnimal.makeSound(); // Outputs: Meow
}
}

//callbyvalueandrefernce

class ValueChanger {
// Method to demonstrate call by value for primitives
public void changePrimitive(int num) {
num = 10;
System.out.println("Inside changePrimitive method, num = " + num);
}

// Method to demonstrate call by value for object references


public void changeObject(MyObject obj) {
obj.value = 20;
System.out.println("Inside changeObject method, obj.value = " + obj.value);
}

// Method to demonstrate reassigning the reference


public void reassignObject(MyObject obj) {
obj = new MyObject();
obj.value = 30;
System.out.println("Inside reassignObject method, obj.value = " +
obj.value);
}
}

class MyObject {
int value;

MyObject() {
this.value = 0;
}
}

public class CallByValueReferenceExample {


public static void main(String[] args) {
ValueChanger changer = new ValueChanger();

// Demonstrating call by value with a primitive type


int num = 5;
System.out.println("Before changePrimitive method, num = " + num);
changer.changePrimitive(num);
System.out.println("After changePrimitive method, num = " + num);

// Demonstrating call by value with an object reference


MyObject obj = new MyObject();
System.out.println("Before changeObject method, obj.value = " + obj.value);
changer.changeObject(obj);
System.out.println("After changeObject method, obj.value = " + obj.value);

// Demonstrating reassigning the reference


System.out.println("Before reassignObject method, obj.value = " +
obj.value);
changer.reassignObject(obj);
System.out.println("After reassignObject method, obj.value = " +
obj.value);
}
}

//this keyword

class Student {
private String name;
private int age;

// Constructor with parameters


public Student(String name, int age) {
// Using 'this' keyword to differentiate between instance variables and
constructor parameters
this.name = name;
this.age = age;
}

// Method to display student details


public void displayDetails() {
System.out.println("Student Name: " + this.name);
System.out.println("Student Age: " + this.age);
}

// Method to compare the age of the current object with another object
public boolean isOlderThan(Student otherStudent) {
return this.age > otherStudent.age;
}
}

public class ThisKeywordExample {


public static void main(String[] args) {
// Creating two student objects
Student student1 = new Student("Alice", 20);
Student student2 = new Student("Bob", 22);

// Displaying details of both students


System.out.println("Details of Student 1:");
student1.displayDetails();
System.out.println();

System.out.println("Details of Student 2:");


student2.displayDetails();
System.out.println();

// Comparing the age of the two students


if (student1.isOlderThan(student2)) {
System.out.println("Student 1 is older than Student 2.");
} else {
System.out.println("Student 2 is older than or the same age as Student
1.");
}
}
}

//studentclass

public class Student {


private String name;

// Constructor with optional name parameter


public Student(String name) {
if (name != null && !name.isEmpty()) {
this.name = name;
} else {
this.name = "Unknown";
}
}

// Method to get the name of the student


public String getName() {
return name;
}

public static void main(String[] args) {


// Creating a student with a name
Student student1 = new Student("John Doe");
// Creating a student without a name
Student student2 = new Student("");

// Printing the names of the students


System.out.println("Student 1 name: " + student1.getName());
System.out.println("Student 2 name: " + student2.getName());
}
}

assignmet5
//recursion

public class FactorialCalculator {


public static void main(String[] args) {
int number = 5; // Number whose factorial to calculate
long factorial = calculateFactorial(number);
System.out.println("Factorial of " + number + " is: " + factorial);
}

// Recursive method to calculate factorial


public static long calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}

//star pascal triangle

public class PascalTriangle {


public static void main(String[] args) {
int numRows = 5; // Number of rows in Pascal's triangle

// Loop to iterate through each row


for (int i = 0; i < numRows; i++) {
// Printing spaces to center-align the triangle
for (int j = 0; j < numRows - i; j++) {
System.out.print(" ");
}

// Printing stars for the current row


for (int j = 0; j <= i; j++) {
System.out.print("* ");
}

System.out.println();
}
}
}

//string palindrome

import java.util.Scanner;

public class PalindromeChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter a string:");
String input = scanner.nextLine();

if (isPalindrome(input)) {
System.out.println("The string \"" + input + "\" is a palindrome.");
} else {
System.out.println("The string \"" + input + "\" is not a
palindrome.");
}

scanner.close();
}

public static boolean isPalindrome(String str) {


int left = 0;
int right = str.length() - 1;

while (left < right) {


if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}

return true;
}
}

//hierrarchial inheritance

// Parent class
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}

// Child class 1
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}

// Child class 2
class Cat extends Animal {
@Override
public void sound() {
System.out.println("Cat meows");
}
}

public class HierarchicalInheritanceExample {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Dog barks

Cat cat = new Cat();


cat.sound(); // Output: Cat meows
}
}

//access specifier

class AccessSpecifierExample {
// Public variable
public int publicVariable = 10;

// Private variable
private int privateVariable = 20;

// Public method accessing both public and private variables


public void displayValues() {
System.out.println("Public variable: " + publicVariable);
System.out.println("Private variable: " + privateVariable);
}
}

public class AccessSpecifierDemo {


public static void main(String[] args) {
AccessSpecifierExample example = new AccessSpecifierExample();

// Accessing public variable and method


System.out.println("Accessing public variable: " + example.publicVariable);
example.displayValues();

// Trying to access private variable (will cause compilation error)


// System.out.println("Accessing private variable: " +
example.privateVariable);
}
}

//static keyword

public class StaticExample {


// Static variable
static int staticVariable = 10;

// Static block to initialize static variables


static {
System.out.println("Static block: Initializing static variables");
staticVariable = 20;
}

// Static method
public static void staticMethod() {
System.out.println("Static method: Accessing static variable = " +
staticVariable);
}

public static void main(String[] args) {


// Accessing static variable directly
System.out.println("Static variable: " + staticVariable);

// Calling static method


staticMethod();
}
}

//superuse

// Superclass
class Animal {
String sound = "Generic sound";

// Constructor
Animal() {
System.out.println("Animal constructor");
}

// Method
void makeSound() {
System.out.println("Animal makes a sound: " + sound);
}
}

// Subclass
class Dog extends Animal {
String sound = "Bark";
// Constructor
Dog() {
// Call superclass constructor using super keyword
super();
System.out.println("Dog constructor");
}

// Method overriding
@Override
void makeSound() {
// Call superclass method using super keyword
super.makeSound();
System.out.println("Dog makes a sound: " + sound);
}
}

public class SuperKeywordExample {


public static void main(String[] args) {
// Create an instance of subclass
Dog dog = new Dog();

// Call method of subclass


dog.makeSound();
}
}

//outer innerclass

class Outer {
void display() {
System.out.println("Outer class display method");
}

class Inner {
void display() {
System.out.println("Inner class display method");
}
}
}

public class OuterInnerExample {


public static void main(String[] args) {
// Creating an instance of the outer class
Outer outer = new Outer();
// Calling the display method of the outer class
outer.display();

// Creating an instance of the inner class


Outer.Inner inner = outer.new Inner();
// Calling the display method of the inner class
inner.display();
}
}
assignment7
//arithmetic

public class ExceptionExample {


public static void main(String[] args) {
// Arithmetic Exception
try {
int result = 10 / 0; // Division by zero
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurred: " + e.getMessage());
}

// Array Index Out of Bound Exception


try {
int[] numbers = {1, 2, 3};
System.out.println("Value at index 3: " + numbers[3]); // Accessing
index out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bound Exception occurred: " +
e.getMessage());
}
}
}

//final
class Main {
public static void main(String[] args) {

// create a final variable


final int AGE = 32;

// try to change the final variable


AGE = 45;
System.out.println("Age: " + AGE);
}
}

//finally

class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of phe code...");


}
}

//throws

import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}

You might also like