Java Programs
Java Programs
Java Programs
CSPCB 2021 Batch (Group A)
[1]
class CommandArgs
int a= Integer.parseInt(args[0]);
int b= Integer.parseInt(args[1]);
int sum=a+b;
System.out.println("Sum is "+sum);
OUTPUT
D:\Program>javac CommandArgs.java
D:\Program>java CommandArgs 12 18
Sum is 30
import java.util.Scanner;
public class factorial
{
public static void main(String fact[])
{
int i,n,f=1;
System.out.println("Enter any number to find factorial");
Scanner s=new Scanner(System.in);
n=s.nextInt();
for( i=n ; i>=1 ; i-- )
{ f=f*i; }
System.out.println("Factorial of given number is "+f);
} }
OUTPUT
D:\Program>javac factorial.java
D:\Program>java factorial
Enter any number to find factorial
7
Factorial of given number is 5040
import java.util.Scanner;
int i=1,b=0,rem;
while(num!=0)
{ rem=num%2;
b=b+(i*rem);
num=num/2;
i=i*10;
OUTPUT
D:\Program>javac DecimalToBinary.java
D:\Program>java DecimalToBinary
Enter a decimal number
56
Binary form is : 111000
D:\Program>java DecimalToBinary
Enter a decimal number
39
Binary form is : 100111
import java.util.Scanner;
int i,n,c=0;
System.out.println("Enter a number");
n=s.nextInt();
for(i=2;i<n;i++)
{ if(n%i==0)
c++; }
if(c==0)
else
OUTPUT
D:\Program>javac prime.java
D:\Program>java prime
Enter a number
92
92 is not a prime number
D:\Program>java prime
Enter a number
5
5 is a prime number
class SumAll
{
public static void main(String args[])
{
int i,s=0,l;
l=args.length;
for(i=0;i<l;i++)
{ int n=Integer.parseInt(args[i]);
s=s+n; }
System.out.println("Sum of these numbers : "+" "+s); } }
OUTPUT
D:\Program>javac SumAll.java
D:\Program>java SumAll 32 45 780 12
Sum of these numbers is :
869
D:\Program>java SumAll 4580 6735 765
Sum of these numbers is :
12080
import java.io.*;
import java.util.Scanner;
class Dist {
{ this.feet=feet;
this.inches=inches; }
void showDistance() {
} }
int x=sc.nextInt();
int y= sc.nextInt();
obj.getDistance(x,y);
sc.close();
obj.showDistance();
OUTPUT
D:\Program>javac Distance.java
D:\Program>java Distance
feet = 5
inches = 6
import java.io.*;
OUTPUT
D:\Program>javac BoxingUnboxing.java
D:\Program>java BoxingUnboxing
package protection;
int getX()
{ return x; }
ad.display();
OUTPUT
D:\Program>javac Protection.java
D:\Program>java Protection
The Value of x is 20
The Value of z is 10
import java.io.*;
import java.util.Scanner;
int a=sc.nextInt();
int b=sc.nextInt();
int c;
sc.close();
try{
c=a/b;
System.out.println("Value of "+a+"/"+b+"="+c);
catch(ArithmeticException e)
{ System.out.println(e); }
OUTPUT
D:\Program>javac DividebyZero.java
D:\Program>java DividebyZero
Enter value of a:
Enter value of b:
Value of 5/2=2
D:\Program>java DividebyZero
Enter value of a:
Enter value of b:
java.lang.ArithmeticException:/by zero