Java practical answers
1.
public class SumOfNumbers4
{
public static void main(String args[])
{
int x = Integer.parseInt(args[0]); //first arguments
int y = Integer.parseInt(args[1]); //second arguments
int sum = x + y;
System.out.println("The sum of x and y is: " +sum);
}
}
2.
class FactorialExample{
public static void main(String args[]){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
OUTPUT
Factorial of 5 is: 120
3.
To convert a decimal to binary number
public class Cnvrt {
public static void main(String[] args) {
int dec = 23;
int b1 = 0;
int rem;
int rev = 1;
while (dec > 0) {
rem = dec % 2;
// storing remainder
dec = dec / 2;
// dividing the given decimal value
b1 = b1 + rem * rev;
// reversing the remainders and storing it
rev = rev * 10;
}
System.out.println("Binary value of given decimal number: " + b1);
}
}
OUTPUT –
Binary value of given decimal number is 10111.
4.
Write a program that show working of different functions of String and StringBufferclasss like
setCharAt(, setLength(), append(), insert(), concat()and equals().
public class StringProgram {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("SIDDHARTH");
StringBuilder stbr = new StringBuilder("RAHUL IS A GOOD BOY");
System.out.println("Original String : " + stbr);
stbr.setCharAt(0, 'S'); // change the char
System.out.println("After using setCharAt(0,'S') : " + stbr);
stbr.append(true); // ret
System.out.println("After using append() " + stbr);
System.out.println("Original length : " + sb.length() + " string :" + sb);
sb.setLength(5);
System.out.println("After using setLength(5) length : " + sb.length() + " string :" + sb);
sb.insert(3, 'R');
System.out.println("After using insert(3,'R') " + sb);
String str1 = "AMAN", test = "AMAN";
String str2 = " KUMAR";
System.out.println(str1.equals(test)); // returns true
System.out.println(str1.equals(str2)); // returns false
System.out.println(str1.concat(str2));
OUTPUT _
Original String : RAHUL IS A GOOD BOY
After using setCharAt(0,'S') : SAHUL IS A GOOD BOY
After using append() SAHUL IS A GOOD BOYtrue
Original length : 9 string :SIDDHARTH
After using setLength(5) length : 5 string :SIDDH
After using insert(3,'R') SIDRDH
true
false
AMAN KUMAR