Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
✅ Practice + Quiz  ·  Lesson 27

Java Practical File Programs (50+)

In this lesson: 50+ Java practical file programs by topic for BCA, B.Tech & Class 12 — code, output and online compiler.

How to use this page

This page is a large, topic-wise collection of Java practical file programs. Instead of a flat list, the programs are grouped by the concept they teach - conditions, loops, arrays, strings, methods and classes, switch case, and exception handling. Each group has seven or eight short programs written in the same simple, exam-friendly style as a real Class 12 IT (802) practical file.

Every program shows its full code and expected output. Below the lesson you will find a built-in Live Code Editor - the programs load into it automatically, so you can pick any one, press Run, edit it, and see the result instantly without installing anything. For programs that read input with Scanner, type your values into the editor's input box.

if / if-else / if-else-if programs

Maximum of three integers

Reads three numbers and prints the largest using an if - else if chain.

Java
import java.util.Scanner;
public class BigThree {
    public static void main(String[] args) {
        int a,b,c;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter First Number");
        a=obj1.nextInt();
        System.out.println("Enter Second Number");
        b=obj1.nextInt();
        System.out.println("Enter Third Number");
        c=obj1.nextInt();
        if(a>b && a>c)
            System.out.println("Big number is "+a);
        else if(b>a && b>c)
            System.out.println("Big number is "+b);
        else
            System.out.println("Big number is "+c);
    }
}
Output:
Enter First Number
45
Enter Second Number
78
Enter Third Number
47
Big number is 78

Even or odd number

Uses the modulus operator to check if a number is divisible by 2.

Java
import java.util.Scanner;
public class EvenOdd {
    public static void main(String[] args) {
        int n;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a Number");
        n=obj1.nextInt();
        if(n%2==0)
            System.out.println("Number is Even");
        else
            System.out.println("Number is Odd");
    }
}
Output:
Enter a Number
10
Number is Even

Positive, negative or zero

Checks the sign of a number with an if-else-if chain.

Java
import java.util.Scanner;
public class SignCheck {
    public static void main(String[] args) {
        int n;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a Number");
        n=obj1.nextInt();
        if(n>0)
            System.out.println("Number is Positive");
        else if(n<0)
            System.out.println("Number is Negative");
        else
            System.out.println("Number is Zero");
    }
}
Output:
Enter a Number
-5
Number is Negative

Largest of two numbers

A simple if-else to compare two values.

Java
import java.util.Scanner;
public class BigTwo {
    public static void main(String[] args) {
        int a,b;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter First Number");
        a=obj1.nextInt();
        System.out.println("Enter Second Number");
        b=obj1.nextInt();
        if(a>b)
            System.out.println("Bigger is "+a);
        else
            System.out.println("Bigger is "+b);
    }
}
Output:
Enter First Number
12
Enter Second Number
20
Bigger is 20

Check leap year

A year is leap if divisible by 4 and not 100, unless divisible by 400.

Java
import java.util.Scanner;
public class LeapYear {
    public static void main(String[] args) {
        int year;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter an Year:");
        year=obj1.nextInt();
        if(((year%4==0) && (year%100!=0)) || (year%400==0))
            System.out.println("Year is a leap year");
        else
            System.out.println("Year is not a leap year");
    }
}
Output:
Enter an Year:
2024
Year is a leap year

Voting eligibility

Checks whether age is 18 or above.

Java
import java.util.Scanner;
public class VoteCheck {
    public static void main(String[] args) {
        int age;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter your Age");
        age=obj1.nextInt();
        if(age>=18)
            System.out.println("You are eligible to vote");
        else
            System.out.println("You are not eligible to vote");
    }
}
Output:
Enter your Age
20
You are eligible to vote

Grade using marks

Uses an if-else-if ladder to assign a grade from marks.

Java
import java.util.Scanner;
public class GradeCheck {
    public static void main(String[] args) {
        int marks;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter Marks");
        marks=obj1.nextInt();
        if(marks>=90)
            System.out.println("Grade A");
        else if(marks>=70)
            System.out.println("Grade B");
        else if(marks>=50)
            System.out.println("Grade C");
        else
            System.out.println("Fail");
    }
}
Output:
Enter Marks
75
Grade B

Number divisible by 5 and 11

Checks two conditions together with the AND operator.

Java
import java.util.Scanner;
public class DivCheck {
    public static void main(String[] args) {
        int n;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a Number");
        n=obj1.nextInt();
        if(n%5==0 && n%11==0)
            System.out.println("Divisible by both 5 and 11");
        else
            System.out.println("Not divisible by both");
    }
}
Output:
Enter a Number
55
Divisible by both 5 and 11

Loop programs (for, while, do-while)

Print even and odd 1 to 10

A for loop from 1 to 10 printing whether each number is even or odd.

Java
public class EvenOddList {
    public static void main(String[] args) {
        int i;
        for(i=1;i<=10;i++)
        {
            if(i%2==0)
                System.out.println("Number " +i+ " is Even");
            else
                System.out.println("Number "+i+ " is Odd ");
        }
    }
}
Output:
Number 1 is Odd
Number 2 is Even
...
Number 10 is Even

Factorial of a number

Multiplies all numbers from n down to 1 using a loop.

Java
import java.util.Scanner;
public class Factorial {
    public static void main(String[] args) {
        int n,fact=1,i;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a Number");
        n=obj1.nextInt();
        for(i=n;i>=1;i--)
        {
            fact=fact*i;
        }
        System.out.println("Factorial is "+fact);
    }
}
Output:
Enter a Number
5
Factorial is 120

Fibonacci series (10 terms)

Each number is the sum of the previous two, printed for 10 terms.

Java
public class Fibonacci {
    public static void main(String[] args) {
        int a,b,c,i;
        a=0;
        b=1;
        System.out.println(a);
        System.out.println(b);
        for(i=3;i<=10;i++)
        {
            c=a+b;
            System.out.println(c);
            a=b;
            b=c;
        }
    }
}
Output:
0
1
1
2
3
5
8
13
21
34

Sum of even numbers 1 to 100

Adds every even number between 1 and 100.

Java
public class SumEven {
    public static void main(String[] args) {
        int i,sum=0;
        for(i=1;i<=100;i++)
        {
            if(i%2==0)
                sum=sum+i;
        }
        System.out.println("Sum is "+sum);
    }
}
Output:
Sum is 2550

Multiplication table

Prints the table of a number using a for loop.

Java
import java.util.Scanner;
public class Table {
    public static void main(String[] args) {
        int n,i;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a Number");
        n=obj1.nextInt();
        for(i=1;i<=10;i++)
        {
            System.out.println(n+" x "+i+" = "+(n*i));
        }
    }
}
Output:
Enter a Number
5
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50

Reverse of a number

Uses a while loop to reverse the digits of a number.

Java
import java.util.Scanner;
public class ReverseNum {
    public static void main(String[] args) {
        int n,rev=0,r;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a number");
        n=obj1.nextInt();
        while(n>0)
        {
            r=n%10;
            rev=rev*10+r;
            n=n/10;
        }
        System.out.println(rev);
    }
}
Output:
Enter a number
123
321

Sum of digits

Adds all digits of a number using a while loop.

Java
import java.util.Scanner;
public class SumDigits {
    public static void main(String[] args) {
        int n,sum=0,r;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a number");
        n=obj1.nextInt();
        while(n>0)
        {
            r=n%10;
            sum=sum+r;
            n=n/10;
        }
        System.out.println("Sum of digits is "+sum);
    }
}
Output:
Enter a number
123
Sum of digits is 6

Print numbers with do-while

Shows the do-while loop, which always runs at least once.

Java
public class DoWhileDemo {
    public static void main(String[] args) {
        int i=1;
        do
        {
            System.out.println("Count "+i);
            i++;
        }
        while(i<=5);
    }
}
Output:
Count 1
Count 2
Count 3
Count 4
Count 5

Array programs

Largest element in an array

Stores 10 numbers and finds the biggest by scanning through.

Java
import java.util.Scanner;
public class ArrayMax {
    public static void main(String[] args) {
        int i;
        int [] arr = new int [10];
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter 10 numbers");
        for(i=0;i<10;i++)
        {
            arr[i]=obj1.nextInt();
        }
        int max = arr[0];
        for (i = 0; i < arr.length; i++)
        {
            if(arr[i] > max)
                max = arr[i];
        }
        System.out.println("Largest element is: " + max);
    }
}
Output:
Enter 10 numbers
25 78 28 22 45 90 34 59 12 5
Largest element is: 90

Smallest element in an array

Same scan pattern but keeps the minimum value.

Java
import java.util.Scanner;
public class ArrayMin {
    public static void main(String[] args) {
        int i;
        int [] arr = new int [10];
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter 10 numbers");
        for(i=0;i<10;i++)
        {
            arr[i]=obj1.nextInt();
        }
        int min = arr[0];
        for (i = 0; i < arr.length; i++)
        {
            if(arr[i] < min)
                min = arr[i];
        }
        System.out.println("Smallest element is: " + min);
    }
}
Output:
Enter 10 numbers
25 78 28 22 45 90 34 59 12 5
Smallest element is: 5

Sum of array elements

Adds all values stored in the array.

Java
import java.util.Scanner;
public class ArraySum {
    public static void main(String[] args) {
        int i,sum=0;
        int [] arr = new int [5];
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter 5 numbers");
        for(i=0;i<5;i++)
        {
            arr[i]=obj1.nextInt();
        }
        for(i=0;i<5;i++)
        {
            sum=sum+arr[i];
        }
        System.out.println("Sum is "+sum);
    }
}
Output:
Enter 5 numbers
10 20 30 40 50
Sum is 150

Average of array elements

Finds the sum then divides by the count.

Java
import java.util.Scanner;
public class ArrayAvg {
    public static void main(String[] args) {
        int i,sum=0;
        int [] arr = new int [5];
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter 5 numbers");
        for(i=0;i<5;i++)
        {
            arr[i]=obj1.nextInt();
            sum=sum+arr[i];
        }
        System.out.println("Average is "+(sum/5.0));
    }
}
Output:
Enter 5 numbers
10 20 30 40 50
Average is 30.0

Search an element in array

Linear search that checks each element for a match.

Java
import java.util.Scanner;
public class ArraySearch {
    public static void main(String[] args) {
        int i,key,f=0;
        int [] arr = new int [5];
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter 5 numbers");
        for(i=0;i<5;i++)
        {
            arr[i]=obj1.nextInt();
        }
        System.out.println("Enter number to search");
        key=obj1.nextInt();
        for(i=0;i<5;i++)
        {
            if(arr[i]==key)
            {
                f=1;
                break;
            }
        }
        if(f==1)
            System.out.println("Element found");
        else
            System.out.println("Element not found");
    }
}
Output:
Enter 5 numbers
10 20 30 40 50
Enter number to search
30
Element found

Reverse an array

Prints array elements from last to first.

Java
import java.util.Scanner;
public class ArrayReverse {
    public static void main(String[] args) {
        int i;
        int [] arr = new int [5];
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter 5 numbers");
        for(i=0;i<5;i++)
        {
            arr[i]=obj1.nextInt();
        }
        System.out.println("Reversed array:");
        for(i=4;i>=0;i--)
        {
            System.out.println(arr[i]);
        }
    }
}
Output:
Enter 5 numbers
10 20 30 40 50
Reversed array:
50
40
30
20
10

Count even and odd in array

Counts how many elements are even and how many are odd.

Java
import java.util.Scanner;
public class ArrayEvenOdd {
    public static void main(String[] args) {
        int i,ec=0,oc=0;
        int [] arr = new int [5];
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter 5 numbers");
        for(i=0;i<5;i++)
        {
            arr[i]=obj1.nextInt();
            if(arr[i]%2==0)
                ec++;
            else
                oc++;
        }
        System.out.println("Even count: "+ec);
        System.out.println("Odd count: "+oc);
    }
}
Output:
Enter 5 numbers
10 15 20 25 30
Even count: 3
Odd count: 2

String programs

Convert string to upper case

Uses the built-in toUpperCase() method.

Java
import java.util.Scanner;
public class UpperCase {
    public static void main(String[] args) {
        String myname;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a Name in lower case");
        myname=obj1.nextLine();
        System.out.println("Upper case string is :"+myname.toUpperCase());
    }
}
Output:
Enter a Name in lower case
alpine
Upper case string is :ALPINE

Convert string to lower case

Uses the built-in toLowerCase() method.

Java
import java.util.Scanner;
public class LowerCase {
    public static void main(String[] args) {
        String myname;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a Name in UPPER case");
        myname=obj1.nextLine();
        System.out.println("Lower case string is :"+myname.toLowerCase());
    }
}
Output:
Enter a Name in UPPER case
ALPINE
Lower case string is :alpine

Count vowels and consonants

Walks each character and counts vowels and consonants.

Java
import java.util.Scanner;
public class VowelCount {
    public static void main(String[] args) {
        int count_v = 0, count_c = 0;
        String mystring;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a String");
        mystring=obj1.nextLine();
        mystring = mystring.toLowerCase();
        for(int i = 0; i < mystring.length(); i++) {
            if(mystring.charAt(i) == 'a' || mystring.charAt(i) == 'e' ||
               mystring.charAt(i) == 'i' || mystring.charAt(i) == 'o' || mystring.charAt(i) == 'u')
                count_v=count_v+1 ;
            else if(mystring.charAt(i) >= 'a' && mystring.charAt(i)<='z')
                count_c=count_c+1;
        }
        System.out.println("Number of vowels: " + count_v);
        System.out.println("Number of consonants: " + count_c);
    }
}
Output:
Enter a String
alpine public school
Number of vowels: 7
Number of consonants: 11

Length of a string

Uses the length() method to count characters.

Java
import java.util.Scanner;
public class StringLength {
    public static void main(String[] args) {
        String s;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a String");
        s=obj1.nextLine();
        System.out.println("Length is "+s.length());
    }
}
Output:
Enter a String
alpine
Length is 6

Reverse a string

Builds the reversed text character by character from the end.

Java
import java.util.Scanner;
public class StringReverse {
    public static void main(String[] args) {
        String s,rev="";
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a String");
        s=obj1.nextLine();
        for(int i=s.length()-1;i>=0;i--)
        {
            rev=rev+s.charAt(i);
        }
        System.out.println("Reverse is "+rev);
    }
}
Output:
Enter a String
alpine
Reverse is enipla

Check palindrome string

Reverses the string and compares it with the original.

Java
import java.util.Scanner;
public class Palindrome {
    public static void main(String[] args) {
        String s,rev="";
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a String");
        s=obj1.nextLine();
        for(int i=s.length()-1;i>=0;i--)
        {
            rev=rev+s.charAt(i);
        }
        if(s.equals(rev))
            System.out.println("It is a Palindrome");
        else
            System.out.println("Not a Palindrome");
    }
}
Output:
Enter a String
madam
It is a Palindrome

Count words in a sentence

Splits the sentence by spaces and counts the parts.

Java
import java.util.Scanner;
public class WordCount {
    public static void main(String[] args) {
        String s;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a Sentence");
        s=obj1.nextLine();
        String[] words = s.split(" ");
        System.out.println("Number of words: "+words.length);
    }
}
Output:
Enter a Sentence
alpine public school
Number of words: 3

Method and Class programs

Area of circle using a method

Moves the area formula into its own method that returns a value.

Java
import java.util.Scanner;
public class CircleArea {
    public static double area_circle(double r)
    {
        double area;
        area=3.14*r*r;
        return(area);
    }
    public static void main(String[] args) {
        double r,area;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter Radius");
        r=obj1.nextDouble();
        area=area_circle(r);
        System.out.println("Area of Circle is :"+area);
    }
}
Output:
Enter Radius
4
Area of Circle is :50.24

Rectangle class and area method

Creates a separate class with a method and calls it via an object.

Java
class Rectangle{
    int length;
    int width;
    int area_calculate(int l, int w){
        int area;
        area=l*w;
        return area;
    }
}
public class RectangleArea {
    public static void main(String args[]){
        int area;
        Rectangle r1=new Rectangle();
        area=r1.area_calculate(11,5);
        System.out.println("Area is : "+area);
    }
}
Output:
Area is : 55

Sum of two numbers using a method

A method that takes two numbers and returns their sum.

Java
import java.util.Scanner;
public class SumMethod {
    public static int add(int a, int b)
    {
        return a+b;
    }
    public static void main(String[] args) {
        int x,y;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter two numbers");
        x=obj1.nextInt();
        y=obj1.nextInt();
        System.out.println("Sum is "+add(x,y));
    }
}
Output:
Enter two numbers
10 20
Sum is 30

Factorial using a method

Separates the factorial logic into a returnable method.

Java
import java.util.Scanner;
public class FactMethod {
    public static int fact(int n)
    {
        int f=1,i;
        for(i=n;i>=1;i--)
            f=f*i;
        return f;
    }
    public static void main(String[] args) {
        int n;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a Number");
        n=obj1.nextInt();
        System.out.println("Factorial is "+fact(n));
    }
}
Output:
Enter a Number
5
Factorial is 120

Student class with details

Defines a class with fields and a method to display them.

Java
class Student{
    int roll;
    String name;
    void show(){
        System.out.println("Roll: "+roll);
        System.out.println("Name: "+name);
    }
}
public class StudentDemo {
    public static void main(String[] args) {
        Student s1=new Student();
        s1.roll=1;
        s1.name="Aarav";
        s1.show();
    }
}
Output:
Roll: 1
Name: Aarav

Simple interest using a method

A method computes simple interest from p, r and t.

Java
import java.util.Scanner;
public class SimpleInterest {
    public static double si(double p, double r, double t)
    {
        return (p*r*t)/100;
    }
    public static void main(String[] args) {
        double p,r,t;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter Principal, Rate, Time");
        p=obj1.nextDouble();
        r=obj1.nextDouble();
        t=obj1.nextDouble();
        System.out.println("Simple Interest is "+si(p,r,t));
    }
}
Output:
Enter Principal, Rate, Time
1000 5 2
Simple Interest is 100.0

Check even using a method

A method returns true or false for even numbers.

Java
import java.util.Scanner;
public class EvenMethod {
    public static boolean isEven(int n)
    {
        if(n%2==0)
            return true;
        else
            return false;
    }
    public static void main(String[] args) {
        int n;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a Number");
        n=obj1.nextInt();
        if(isEven(n))
            System.out.println("Even");
        else
            System.out.println("Odd");
    }
}
Output:
Enter a Number
8
Even

switch case programs

Day name from number

Reads a day number 1 to 7 and prints its name.

Java
import java.util.Scanner;
public class DayName {
    public static void main(String[] args) {
        int day;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter Day Number");
        day=obj1.nextInt();
        switch(day)
        {
            case 1: System.out.println("Sunday"); break;
            case 2: System.out.println("Monday"); break;
            case 3: System.out.println("Tuesday"); break;
            case 4: System.out.println("Wednesday"); break;
            case 5: System.out.println("Thursday"); break;
            case 6: System.out.println("Friday"); break;
            case 7: System.out.println("Saturday"); break;
            default: System.out.println("Invalid Day Number");
        }
    }
}
Output:
Enter Day Number
5
Thursday

Simple calculator

Uses switch on an operator symbol to pick the operation.

Java
import java.util.Scanner;
public class Calculator {
    public static void main(String[] args) {
        int a,b;
        char op;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter two numbers");
        a=obj1.nextInt();
        b=obj1.nextInt();
        System.out.println("Enter operator (+ - * /)");
        op=obj1.next().charAt(0);
        switch(op)
        {
            case '+': System.out.println(a+b); break;
            case '-': System.out.println(a-b); break;
            case '*': System.out.println(a*b); break;
            case '/': System.out.println(a/b); break;
            default: System.out.println("Invalid operator");
        }
    }
}
Output:
Enter two numbers
10 5
Enter operator (+ - * /)
+
15

Month name from number

Prints the month name for a number 1 to 12.

Java
import java.util.Scanner;
public class MonthName {
    public static void main(String[] args) {
        int m;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter Month Number");
        m=obj1.nextInt();
        switch(m)
        {
            case 1: System.out.println("January"); break;
            case 2: System.out.println("February"); break;
            case 3: System.out.println("March"); break;
            case 4: System.out.println("April"); break;
            case 5: System.out.println("May"); break;
            case 6: System.out.println("June"); break;
            default: System.out.println("Enter 1 to 6");
        }
    }
}
Output:
Enter Month Number
3
March

Vowel or consonant

Uses switch to check if a character is a vowel.

Java
import java.util.Scanner;
public class VowelSwitch {
    public static void main(String[] args) {
        char ch;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a character");
        ch=obj1.next().charAt(0);
        switch(ch)
        {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u': System.out.println("Vowel"); break;
            default: System.out.println("Consonant");
        }
    }
}
Output:
Enter a character
e
Vowel

Grade from choice

Prints a message based on a grade letter using switch.

Java
import java.util.Scanner;
public class GradeSwitch {
    public static void main(String[] args) {
        char g;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter Grade (A B C)");
        g=obj1.next().charAt(0);
        switch(g)
        {
            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");
        }
    }
}
Output:
Enter Grade (A B C)
A
Excellent

Arithmetic menu

A menu-driven program using switch for choices.

Java
import java.util.Scanner;
public class MenuSwitch {
    public static void main(String[] args) {
        int choice,a=12,b=4;
        Scanner obj1=new Scanner(System.in);
        System.out.println("1.Add 2.Sub 3.Mul");
        System.out.println("Enter choice");
        choice=obj1.nextInt();
        switch(choice)
        {
            case 1: System.out.println("Sum = "+(a+b)); break;
            case 2: System.out.println("Diff = "+(a-b)); break;
            case 3: System.out.println("Product = "+(a*b)); break;
            default: System.out.println("Wrong choice");
        }
    }
}
Output:
1.Add 2.Sub 3.Mul
Enter choice
1
Sum = 16

Number in words (1-5)

Prints the word form of a small number using switch.

Java
import java.util.Scanner;
public class NumberWords {
    public static void main(String[] args) {
        int n;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter a number (1-5)");
        n=obj1.nextInt();
        switch(n)
        {
            case 1: System.out.println("One"); break;
            case 2: System.out.println("Two"); break;
            case 3: System.out.println("Three"); break;
            case 4: System.out.println("Four"); break;
            case 5: System.out.println("Five"); break;
            default: System.out.println("Enter 1 to 5");
        }
    }
}
Output:
Enter a number (1-5)
3
Three

Exception handling programs

Divide by zero exception

try-catch handles ArithmeticException so the program does not crash.

Java
import java.util.Scanner;
public class DivZero {
    public static void main(String[] args) {
        int divi,divis,sum;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter Dividend Number");
        divi=obj1.nextInt();
        System.out.println("Enter Divisor Number");
        divis=obj1.nextInt();
        try
        {
            System.out.println(divi/divis);
        }
        catch (ArithmeticException e)
        {
            System.out.println("Divided by zero operation cannot possible");
        }
        sum=divi+divis;
        System.out.println("sum is :"+sum);
    }
}
Output:
Enter Dividend Number
34
Enter Divisor Number
0
Divided by zero operation cannot possible
sum is :34

Array index out of bounds

Catches ArrayIndexOutOfBoundsException on invalid index.

Java
public class ArrayIndex {
    public static void main(String[] args) {
        int [] arr = {10,20,30};
        try
        {
            System.out.println(arr[5]);
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            System.out.println("Invalid array index");
        }
    }
}
Output:
Invalid array index

Number format exception

Catches an error when a non-number string is parsed.

Java
public class NumFormat {
    public static void main(String[] args) {
        try
        {
            int n=Integer.parseInt("abc");
            System.out.println(n);
        }
        catch (NumberFormatException e)
        {
            System.out.println("Not a valid number");
        }
    }
}
Output:
Not a valid number

Null pointer exception

Catches an error when using a null reference.

Java
public class NullDemo {
    public static void main(String[] args) {
        String s=null;
        try
        {
            System.out.println(s.length());
        }
        catch (NullPointerException e)
        {
            System.out.println("Null value cannot be used");
        }
    }
}
Output:
Null value cannot be used

try-catch-finally

Shows that the finally block always runs.

Java
public class FinallyDemo {
    public static void main(String[] args) {
        try
        {
            int x=10/0;
        }
        catch (ArithmeticException e)
        {
            System.out.println("Cannot divide by zero");
        }
        finally
        {
            System.out.println("This always runs");
        }
    }
}
Output:
Cannot divide by zero
This always runs

Throw a custom message

Uses throw to raise an exception with a message.

Java
import java.util.Scanner;
public class ThrowDemo {
    public static void main(String[] args) {
        int age;
        Scanner obj1=new Scanner(System.in);
        System.out.println("Enter age");
        age=obj1.nextInt();
        try
        {
            if(age<18)
                throw new ArithmeticException("Not an adult");
            System.out.println("You are an adult");
        }
        catch (ArithmeticException e)
        {
            System.out.println("Error: "+e.getMessage());
        }
    }
}
Output:
Enter age
15
Error: Not an adult

Multiple catch blocks

Handles two different exceptions with separate catch blocks.

Java
public class MultiCatch {
    public static void main(String[] args) {
        try
        {
            int [] arr = new int[3];
            arr[5]=10/0;
        }
        catch (ArithmeticException e)
        {
            System.out.println("Arithmetic problem");
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            System.out.println("Array problem");
        }
    }
}
Output:
Arithmetic problem

Summary

  • Programs are grouped by topic, with 7-8 in each group, for focused practice.
  • Every program has real code and output in the standard practical-file style.
  • The built-in Live Code Editor runs any program in your browser - no install needed.
  • Use the STDIN box for programs that read input with Scanner.

Build the fundamentals first with Introduction to Java, learn input in User Input using Scanner, or try more in 50 Java Practice Programs.

Frequently Asked Questions

Can I run these Java programs online without installing anything?
Yes. This page has a built-in Live Code Editor. The programs load into it automatically - just pick one from the dropdown or type your own and press Run, and it compiles and runs in your browser, so you do not need to install the JDK or NetBeans to practise.
How are the programs organised?
They are grouped by topic - if-else conditions, loops, arrays, strings, methods and classes, switch case, and exception handling. Each topic has seven or eight small programs, so you can practise one concept fully before moving to the next.
Do I need to enter input for these programs?
Many programs use the Scanner class to read input. When you run those in the editor, type the input in the STDIN or input box, and the program reads it just like it does in NetBeans. Programs without Scanner run directly.
Which class are these programs suitable for?
They follow the standard Class 12 Information Technology (802) practical file style, but they suit any beginner learning core Java, including BCA, diploma and first-year college students.
Why do the class names differ from Practical1, Practical2?
Here each program has a meaningful class name like BigThree or Factorial, which is clearer than numbered names. The logic and code flow are exactly the same simple style used in the practical file.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicstatic Keyword Your progress: 27 / 61 (44%) · Lesson 28 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free