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

Java Practicals

The document provides an overview of Java, including its definition, history, and key features such as platform independence and object-oriented programming. It also includes practical examples demonstrating various Java concepts, including condition statements, loops, switch cases, arrays, and string methods, with sample code for each. Additionally, it covers practical applications like a simple calculator, banking system, and binary search.

Uploaded by

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

Java Practicals

The document provides an overview of Java, including its definition, history, and key features such as platform independence and object-oriented programming. It also includes practical examples demonstrating various Java concepts, including condition statements, loops, switch cases, arrays, and string methods, with sample code for each. Additionally, it covers practical applications like a simple calculator, banking system, and binary search.

Uploaded by

Electronic Idea
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Java Practicals

1. Introduction to Java
Java is a high-level, object-oriented programming language developed
by Sun Microsystems (now owned by Oracle Corporation). It is widely
used for building web applications, mobile applications, enterprise
applications, and more. Java is known for its platform independence,
security, and robustness.
 Definition:
Java is a general-purpose, class-based, object-oriented
programming language that follows the "Write Once, Run
Anywhere" (WORA) principle, meaning that Java programs can run
on any platform with a Java Virtual Machine (JVM).

 Brief History:
Java was developed by James Gosling and his team at Sun
Microsystems in the early 1990s. Initially called "Oak," it was later
renamed Java in 1995. Java gained popularity due to its portability
and security features, leading to its widespread adoption in
various domains, including web development, mobile applications
(Android), and enterprise software.

 Features:
Java offers several key features:
1. Platform Independence – Java programs run on any device with
a JVM.
2. Object-Oriented – Supports concepts like classes, objects,
inheritance, and polymorphism.
3. Simple and Easy to Learn – Java's syntax is similar to C and C++.
4. Robust and Secure – Provides strong memory management and
security mechanisms.
5. Multithreading – Supports concurrent execution of multiple
threads.
6. High Performance – Uses Just-In-Time (JIT) compilation for
better performance.
7. Automatic Garbage Collection – Manages memory efficiently
by removing unused objects.
8. Rich API – Offers a wide range of built-in libraries for
networking, I/O, and more.

 Compilation and Execution of Java


2. Demonstrate the use of condition statement of Java
 WAP to check whether a person is valid or not

import java.util.Scanner;

public class voter {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter your age:");

int age = sc.nextInt();

if (age >= 18) {

System.out.println("You are a valid voter");

} else {

System.out.println("You are not a valid

voter");

Output:

 WAP to find largest number among 3 using nested if


import java.util.Scanner;

public class three_num {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter first number: ");

int num1 = sc.nextInt();

System.out.print("Enter second number: ");

int num2 = sc.nextInt();

System.out.print("Enter third number: ");

int num3 = sc.nextInt();

if (num1 > num2) {

if (num1 > num3) {

System.out.println(num1+" is the greatest number among three");

} else {

System.out.println(num3 + " is the greatest number among

three");

} else if (num2 > num1) {

if (num2 > num3) {

System.out.println(num2 + " is the greatest number among

three");

} else {

System.out.println(num3 + " is the greatest number among

three");

Output:
3. Demonstrate the use of loops
 WAP to find the factorial of a number using ‘For loop’
import java.util.Scanner;
public class factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int temp = 1;
for (int i = 1; i <= num; i++) {
temp *= i;
}
System.out.println("Factorial is " +
temp);
}
}

Output:
 WAP to find the first 10 number of Fibonacci series

public class fibonacci {


public static void main(String[] args)
{
int n1 = 0;
int n2 = 1;
int temp = 0;
System.out.print(0+" "+1+" ");
for (int i = 0; i < 10; i++) {
temp = n1 + n2;
System.out.print(temp+" ");
n1 = n2;
n2 = temp;
}
}
}

Output:
 WAP to print the table by user input

import java.util.Scanner;

public class table {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter your number:");

int num = sc.nextInt();

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

System.out.println(num + " X " + i + " = " + (num *

i));

Output:
 WAP to find the sum of harmonic series

import java.util.Scanner;

public class harmonic_sum {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("First term:");

int a = sc.nextInt();

System.out.print("Comman difference:");

int d = sc.nextInt();

System.out.print("Number of terms:");

int n = sc.nextInt();

int numerator = (2*a) + (2*n + 1)*d;

int denominator = 2*a - d;

float temp = 1 / (float)d;

double num = temp * Math.log(numerator /

denominator);

String value = String.format("%.2f", num);

System.out.println(value);
}

}
Output:

 WAP to find prime number between 1 to 100

public class PrimeNumbers {

public static void main(String[] args) {

System.out.print("2 3 5 7 ");

for (int i = 4; i < 101; i++) {

if ((i % 2 != 0) && (i % 3 != 0) && (i % 5 != 0) && (i % 7 != 0)) {

System.out.print(i+" ");

Output:
 WAP to find the LCM of two numbers

import java.util.Scanner;

public class lcm {

public static int findHCF(int a, int b) {

while (b != 0) {

int temp = b;

b = a % b;

a = temp;

return a;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter two numbers: ");

int num1 = sc.nextInt(), num2 = sc.nextInt();

int lcm_value = (num1 * num2) / findHCF(num1, num2);

System.out.printf("LCM of %d and %d is %d", num1, num2,

lcm_value);

}
}

Output:

 WAP to convert decimal to binary number


import java.util.Scanner;
public class binary {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your number:");
int num = sc.nextInt();
int temp = num;
int[] bin = new int[10];
int i = 0;
while (num != 1){
if (num % 2 == 0) {
bin[i] = 0;
i++;
} else {
bin[i] = 1;
i++;
}
num /= 2;
}
bin[i++] = 1;

System.out.print(temp + " -> ");


for (int j = bin.length-1; j >= 0; j--) {
System.out.print(bin[j]);
}

}
Output:

4. Switch Case
 WAP to make Simple Calculator
import java.util.Scanner;
public class calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("+ -> 1 - -> 2 x -> 3 / -> 4");
System.out.println("Choose from given options");
System.out.print("Enter your choice:");
int choice = sc.nextInt();
System.out.print("Enter your first number:");
int num1 = sc.nextInt();
System.out.print("Enter your second number:");
int num2 = sc.nextInt();

switch (choice) {
case 1 -> System.out.printf("%d + %d = %d", num1, num2, num1 +
num2);
case 2 -> System.out.printf("%d - %d = %d", num1, num2, num1 -
num2);
case 3 -> System.out.printf("%d * %d = %d", num1, num2, num1 *
num2);
case 4 -> System.out.printf("%d / %d = %d", num1, num2, num1 /
num2);
}
}
}
Output:

 WAP to get numbers in words


import java.util.Scanner;
public class counting_word {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] word = {"one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten"};
String[] duo = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty",
"Seventy", "Eighty", "Ninety", "Hundred"};

System.out.print("Enter your number:");


int num = sc.nextInt();
int len = String.valueOf(num).length();
if (len == 1) {
switch (num) {
case 1 -> System.out.println("One");
case 2 -> System.out.println("Two");
case 3 -> System.out.println("Three");
case 4 -> System.out.println("Four");
case 5 -> System.out.println("Five");
case 6 -> System.out.println("Six");
case 7 -> System.out.println("Seven");
case 8 -> System.out.println("Eight");
case 9 -> System.out.println("Nine");
case 10 -> System.out.println("Ten");
}
} else if (num % 10 == 0) {
int a = num / 10;
switch (a) {
case 2 -> System.out.println(duo[0]);
case 3 -> System.out.println(duo[1]);
case 4 -> System.out.println(duo[2]);
case 5 -> System.out.println(duo[3]);
case 6 -> System.out.println(duo[4]);
case 7 -> System.out.println(duo[5]);
case 8 -> System.out.println(duo[6]);
case 9 -> System.out.println(duo[7]);
case 10 -> System.out.println(duo[8]);
}
} else {
int a = num / 10;
switch (a) {
case 2 -> System.out.println(duo[0] + " " +word[(num % 10) -
1]);
case 3 -> System.out.println(duo[1] + " " +word[(num % 10) -
1]);
case 4 -> System.out.println(duo[2] + " " +word[(num % 10) -
1]);
case 5 -> System.out.println(duo[3] + " " +word[(num % 10) -
1]);
case 6 -> System.out.println(duo[4] + " " +word[(num % 10) -
1]);
case 7 -> System.out.println(duo[5] + " " +word[(num % 10) -
1]);
case 8 -> System.out.println(duo[6] + " " +word[(num % 10) -
1]);
case 9 -> System.out.println(duo[7] + " " +word[(num % 10) -
1]);
case 10 -> System.out.println(duo[8] + " " +word[(num % 10) -
1]);
default -> System.out.println("Unknown Number");
}
}
}
}

Output:
 WAP to create banking system for deposit and withdrawal
of money
import java.util.Scanner;
public class banking_system {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Banking System");
System.out.println("Please select a option given below");
System.out.println("Deposit - 1 Withdrawal - 2");
System.out.print("Enter your choice:");
int choice = sc.nextInt();
int amt = 1000;
switch (choice) {
case 1:
System.out.print("Enter your amount for deposit:");
int temp = sc.nextInt();
amt += temp;
System.out.println("Amount Deposited successfully");
System.out.println("Do you want to see updated
amount?");
System.out.println("Press '1' for Yes and '2' for No");
System.out.print("Enter:");
int ch = sc.nextInt();
if (ch == 1) {
System.out.println("Amount: "+amt);
System.out.println("Thank you for banking with
us!");
} else if (ch == 2) {
System.out.println("Thank you for banking with
us!");
} else {
System.out.println("Wrong input entered");
}
break;

case 2:
System.out.print("Enter your amount for withdrawal:");
int temp1 = sc.nextInt();
amt -= temp1;
System.out.println("Amount Withdrawal successfully");
System.out.println("Do you want to see updated
amount?");
System.out.println("Press '1' for Yes and '2' for No");
System.out.print("Enter:");
int ch1 = sc.nextInt();
if (ch1 == 1) {
System.out.println("Amount: "+amt);
System.out.println("Thank you for banking with
us!");
} else if (ch1 == 2) {
System.out.println("Thank you for banking with
us!");
} else {
System.out.println("Wrong input entered");
}
break;
}
}

Output:

5. Arrays
 WAP to do binary search in an array
import java.util.Scanner;
public class binary_search {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your number for search:");
int value = sc.nextInt();
int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90};
int lb = 0, ub = arr.length;
int temp = 0;
while (true) {
temp = (lb + ub) / 2;
if (arr[temp] == value){
System.out.println("Number is found at: "+ temp);
break;
} else if (arr[temp] > value) {
ub = temp;
} else if (arr[temp] < value) {
lb = temp;
}
}
}
}

Output:

 WAP to do sorting of an array element


import java.util.Scanner;
public class sorting {
public static void main(String[] args) {
int[] arr = {34, 2, 589, 39, 90, 43, 22};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - i - 1; j++)
{
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

for (int i : arr) {


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

Output:

6. Develop a program in java to demonstrate the string class


and its methods
public class string_methods {
public static void main(String[] args) {
String str = "Hello World";
String new_str = " coders";
System.out.println("Length:"+str.length());
System.out.println("Lower Case:"+str.toLowerCase());
System.out.println("Upper Case:"+str.toUpperCase());
System.out.println("Substring:"+str.substring(1, 4));
System.out.println("Replace:"+str.replace('l', 'x'));
System.out.println("Index of Character:"+str.charAt(4));
System.out.println("Character at index:"+str.indexOf('l'));
System.out.println("Concatenate:"+str.concat(new_str));
System.out.println("Join strings:"+str.join(" ", "world", "chai",
"code"));
System.out.println("Is Starts with:"+str.startsWith("hel"));
System.out.println("Is Starts with:"+str.endsWith("ld"));
System.out.println("Hash code:"+str.hashCode());
System.out.println("Contain:"+str.contains("ld"));
System.out.println("Equal:"+str.equals("Hello World"));
System.out.println("Equal:"+str.equalsIgnoreCase("hello world"));

}
}

Output:

7. Develop a program for the implementation of class,


methods and objects
 WAP to create a student class which takes student data
from the user and calculate percentage then print it
import java.util.Scanner;

class student {
float english, hindi, maths, science, sst;

public void setData(int e, int h, int m, int sc, int sst) {


english = e;
hindi = h;
maths = m;
science = sc;
this.sst = sst;
}

public void getData() {


float value =
((english+hindi+maths+science+sst)/500)*100;
System.out.println("Percentage: "+ String.format("%.2f",
value));
}
}
public class student_data {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
student s1 = new student();

System.out.print("Enter English marks: ");


int english = sc.nextInt();

System.out.print("Enter Hindi marks: ");


int hindi = sc.nextInt();

System.out.print("Enter Maths marks: ");


int maths = sc.nextInt();

System.out.print("Enter Science marks: ");


int science = sc.nextInt();

System.out.print("Enter Social Studies marks: ");


int sst = sc.nextInt();

s1.setData(english, hindi, maths, science, sst);


s1.getData();

}
}
Output:

 WAP to get area and perimeter of circle, square and


rectangle
import java.util.Scanner;
class square {
int side;
public void setSide(int side) {
this.side = side;
}

public void area() {


System.out.println("Area of square: " + side*side);
}

public void perimeter() {


System.out.println("Perimeter of square: " + 4*side);
}
}
class rectangle {
int l, b;
public void setSide(int l, int b) {
this.l = l;
this.b = b;
}

public void area() {


System.out.println("Area of rectangle: " + l*b);
}

public void perimeter() {


System.out.println("Perimeter of rectangle: " + 2*(l+b));
}
}

class circle {
int r;
public void setRadius(int r) {
this.r = r;
}

public void area() {


System.out.println("Area of circle: " + 3.14*r*r);
}

public void circumference() {


System.out.println("Circumference of circle: " + String.format("%.2f",
2*3.14*r));
}
}
public class shapes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Choose a shape (1-square, 2-rectangle, 3-circle):");
int choice = sc.nextInt();
switch (choice) {
case 1:
square sq = new square();
System.out.print("Enter side length: ");
sq.setSide(sc.nextInt());
sq.area();
sq.perimeter();
break;
case 2:
rectangle rt = new rectangle();
System.out.print("Enter length and breadth: ");
rt.setSide(sc.nextInt(), sc.nextInt());
rt.area();
rt.perimeter();
break;
case 3:
circle cr = new circle();
System.out.print("Enter radius: ");
cr.setRadius(sc.nextInt());
cr.area();
cr.circumference();
break;
default:
System.out.println("Invalid choice!");
}
}
}

Output:

 WAP to get
sorted reverse array in a class
class arr_rev {
int[] a;
public void setArray(int[] ls) {
this.a = ls;
}

public void reverseArray() {


for (int i = a.length-1; i >= 0;
i--) {
System.out.print(a[i] + " ");
}
}
}
public class reverse {
public static void main(String[] args)
{
arr_rev obj = new arr_rev();
int[] arr = {10, 20, 30, 40, 50,
60};
obj.setArray(arr);
obj.reverseArray();
}
}

Output:

 WAP of binomial theorem by taking input of n and r


import java.util.Scanner;

public class BinomialTheorem {


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

System.out.print("Enter value of a: ");


int a = sc.nextInt();
System.out.print("Enter value of b: ");
int b = sc.nextInt();
System.out.print("Enter value of n: ");
int n = sc.nextInt();

System.out.print("Expansion: ");
for (int k = 0; k <= n; k++) {
int coeff = 1;

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


coeff = coeff * (n - i) / (i + 1);
}

int termA = (int) Math.pow(a, n - k);


int termB = (int) Math.pow(b, k);

System.out.print(coeff + " * " + termA + " * " +


termB);
if (k < n) {
System.out.print(" + ");
}
}

sc.close();
}
}

Output:

 WAP to calculate compound interest and take input


import java.util.Scanner;
public class compound_int {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the principal amount: ");
int principle = sc.nextInt();
System.out.print("Enter the rate of interest per annum:
");
double rate = sc.nextDouble();
System.out.print("Enter the number of years: ");
int years = sc.nextInt();

double ci = principle * (Math.pow((1 + rate), years) -


1);

System.out.printf("Compound Interest: %.2f", ci);


}
}

Output:

9. Develop a program to demonstrate method overloading.


public class method_overloading {
public static int sum(int a, int b) {
return a + b;
}

public static int sum(int a, int b, int c) {


return a + b + c;
}

public static int sum(int a, int b, int c, int d)


{
return a + b + c + d;
}
public static void main(String[] args) {
System.out.println(sum(1, 2));
System.out.println(sum(1, 2, 3));
System.out.println(sum(1, 2, 3, 4));
}
}

Output:

10. Develop a Program to demonstrate constructor overloading.


class Student {
String name;
int age;
Student() {
name = "Unknown";
age = 0;
}

Student(String studentName) {
name = studentName;
age = 0;
}

Student(String studentName, int studentAge) {


name = studentName;
age = studentAge;
}

void display() {
System.out.println("Name: " + name + ", Age: " +
age);
}
}

public class ConstructorOverloading {


public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Tanishq");
Student s3 = new Student("Ravi", 20);

s1.display();
s2.display();
s3.display();
}
}
Output:

11. Develop a program to


demonstrate multilevel inheritance
class Animal {
void eat() {
System.out.println("Animals can eat");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dogs can bark");
}
}

class Puppy extends Dog {


void weep() {
System.out.println("Puppies weep");
}
}

public class MultilevelInheritance {


public static void main(String[] args) {
Puppy myPuppy = new Puppy();

myPuppy.eat();
myPuppy.bark();
myPuppy.weep();
}
}

Output:

13. Develop a program to demonstrate method overriding.


class A {
int a = 384;
public A() {
System.out.println("A's constructor called");
}

void display() {
System.out.println("A's display method
called");
}
}

class B extends A {
int b = 512;

public B() {
System.out.println("B's constructor called");
}

@Override
void display() {
System.out.println("B's display method
called");
}
}

public class overriding {


public static void main(String[] args) {
B obj = new B();
obj.display();
}
}

Output:

16. Develop a program to


demonstrate abstract method and classes.
abstract class yoyo {
public yoyo() {
System.out.println("This is a constructor of yoyo
class");
}
abstract void greet();
abstract void move();
}

class poo extends yoyo {


public void greet() {
System.out.println("Hello guyz!");
}
public void move() {
System.out.println("I'm moving like a yo-yo!");
}
}

class boo extends yoyo {


public void greet() {
System.out.println("Namaste ji");
}
public void move() {
System.out.println("I'm moving like a boo-boo!");
}
public void info() {
System.out.println("What are doing");
}
}

public class abstract_class {


public static void main(String[] args) {
poo p = new poo();
p.greet();
p.move();

boo b = new boo();


b.greet();
b.move();
b.info();
}
}

Output:

You might also like