JAVA

Convert Binary to Decimal:
                 In this section, you will learn how to convert a binary number into a decimal number. The java.lang package provides the facility to convert the integer data into the binary to decimal.

Code Description:
                                           In this program, you will learn the use of parseLong()method. Define a class "BinaryToDecimal" using the parseLong() method. This method is used to parse the string argument as a signed decimal long. This method has been used for converting a long to a string and a String to a long.
--------------------------------------------------------------------------------------------------------------------------

import java.lang.*;
import java.io.*;

public class BinaryToDecimal{
public static void main(String[] args) throws IOException{
BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Binary value: ");
String str = bf.readLine();
long num = Long.parseLong(str);
long rem;
while(num > 0){
rem = num % 10;
num = num / 10;
if(rem != 0 && rem != 1){
System.out.println("This is not a binary number.");
System.out.println("Please try once again.");
System.exit(0);
}
}
int i= Integer.parseInt(str,2);
System.out.println("Decimal:="+ i);
}
}


Output of this program:
C:\corejava>java BinaryToDecimal
Enter the Binary value:
10010
Decimal:=18
C:\corejava>_                                                                                                                                      
------------------------------------------------------------------

Convert Decimal into Binary :
In this section, you will learn to convert decimal number into binary. The java.lang package provides the functionality to convert a decimal number into a binary number.
Description of program:
This program takes a decimal number from console and it converts it into binary format using the toBinaryString() method. Input number is taken as string so convert it into an integer data using the Integer.parseInt() method. To convert the Decimal number into binary number use toBinaryString() method.
toBinaryString():

This method takes an integer type value and returns its string representation of integer values which represents the data in binary. The base of binary number is 2.

------------------------------------------------------------------------------------------------------------------------
import java.lang.*;
import java.io.*;
public class DecimalToBinary{
public static void main(String args[]) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the decimal value:");
String hex = bf.readLine();
int i = Integer.parseInt(hex);
String by = Integer.toBinaryString(i);
System.out.println("Binary: " + by);
}
}

Output of this program:
C:\corejava>java DecimalToBinary
Enter the decimal value:
123
Binary: 1111011                                                                                                                                                                  
C:\corejava>_
--------------------------------------------------------------------  

Prime number program in java

In this example you will learn how to write a program to generate and check prime number in java. As we know prime number are those number which are divisible by 1 or itself, first define a class with class name prime number, using switch case, in case first using two for loop generating prime number up to the limit number entered by user and in second case checking whether the entered number is prime number or not.
Example : Here is the code for generating prime number and to check the prime number

import java.io.*;
import java.util.Scanner;
class Primenumber
{
public static void main(String args[])throws Exception
{
char st;
Scanner sin,stc;
String c;
do
{
System.out.println("Press 1 for generate prime number");
System.out.println("Press 2 for check prime number ");
sin
=new Scanner(System.in);
int s=sin.nextInt();
switch(s)
{
case 1:System.out.println("Enter the limit number");
int limit = new Scanner(System.in).nextInt();
System.out.println("Printing prime number from 1 to " + limit);
for(int number = 2; number<=limit; number++){
//print prime numbers only
if(Primegen(number)){
System.out.println(number);}}
break;

case 2: int n, i, res;
boolean flag=true;
Scanner scan= new Scanner(System.in);
System.out.println("Please Enter a No.");
n
=scan.nextInt();
for(i=2;i<=n/2;i++)
{
res
=n%i;
if(res==0)
{
flag
=false;
break;
}
}
if(flag)
System.out.println(n + " is Prime Number");
else
System.out.println(n + " is not Prime Number");
break;

default: System.out.println("Not Valid option");
break;
}

System.out.println("Do u want to Execute again(Y/N)");
stc
=new Scanner(System.in);
c
=stc.next();
st
=c.charAt(0);
} while(st!='N');
}
public static boolean Primegen(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false; //number is divisible so its not prime
}
}
return true;
}
}

1)
input1={'1','5','5','2','3','4'}-int array type
output={'1','2','3','4','0','0'}-int array type
rules:
.remove the digit 5.. move the next digit in the gaps
.add as many zeros equal to the number of 5's removed at the end

package mettlQuestions;

public class Prac1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
       
        int[] input1={1,5,5,2,3,4};
        int[] output=new int[input1.length];
        int j=0;
        for(int i=0;i<input1.length;i++)
        {
            if(input1[i]!=5)
            {
                output[j]=input1[i];
                j++;
            }
        }
        if(j<input1.length)
        {
            for(int k=j;k<input1.length;k++)
            {
                output[k]=0;
               
            }
        }
        for(int i=0;i<output.length;i++)
        {
            System.out.print(output[i]);
        }
    }

}
2)4)Age Validation
ex1:
input1=23;
input2=true;
package examPractice;

import java.util.regex.Pattern;

public class AgeValidation {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String input1="-42";
        boolean b = Pattern.matches("[2-4][0-9]", input1);
        if((b==true)&&(Integer.parseInt(input1)>=21)&&(Integer.parseInt(input1)<=45)){
            System.out.println("true");
        }
        else{
            System.out.println("false");
        }

    }

}
PAN CARD VALIDATION:

package mettlQuestions;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PanCard {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String s="AAA3456A";
        Pattern p= Pattern.compile("[A-Z]{3}[0-9]{4}[A-Z]{1}");
        Matcher S2=p.matcher(s);
        if(S2.find())
        {
            System.out.println(1);
           
        }
        else
        {
            System.out.println(-1);
        }
       

    }

}
MAXIMUM VOVELS:

import java.util.ArrayList;
import java.util.List;

public class VowelsRepeat {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String a = "asdfeioubcdae";
        boolean d = true;

        List<Character> l = new ArrayList<Character>();
        for (int i = 0; i < a.length(); i++) {
            char b = a.charAt(i);
            if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u') {
                    if(!(l.contains(b))){
                        l.add(b);
                    }
                    else{
                        d=false;
                    }
            }
        }System.out.println(d);
    }

}

HASH MAP CISCO WIPRO:
import java.util.*;


public class Hash {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Map<String,String> h = new HashMap<String,String>();
int sum=0;
        List<String> l = new ArrayList<String>();
        h.put("ram", "hari");
        h.put("cisco","barfi");
        h.put("honeywell","cs");
        h.put("cts", "hari");
        String input2="hari";
        String[] output =new String[5];
        Set keys = h.keySet();
        for(Object o:keys){
            String var=h.get(o);
            if(var.equalsIgnoreCase(input2)){
                //l.add((String) o);
                sum =sum+var;           
            }
        }
        for (int i = 0; i < l.size(); i++) {
            output[i]=l.get(i);
        System.out.println(output[i]);
        }
       

    }

}

GOA KERALA :
import java.util.*;


public class Cutting3 {
       
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] s={"goa","kerala","chennai"};
        Map<String,String> ref = new HashMap<String,String>();
        String[] out=new String[s.length];
        for (int i = 0; i < s.length; i++) {
            if(s[i].length()<=3){
                out[i]=s[i].toUpperCase();
            }
            else{
                String f=s[i].substring(0,3);
                out[i]=f.toUpperCase();
                    }
            ref.put(out[i],s[i]);
        }
//        Set keys=ref.keySet();
//        for(Object d:keys)
        System.out.println(ref);
    }

}
FIRST THREE CAPITAL
package examPractice;

import java.util.HashMap;

public class UserMainCode {

    static HashMap<String, String> output;

    static void capitalize(String input1[]) {
        output = new HashMap<String, String>();
        for (int i = 0; i < input1.length; i++) {
            String s = input1[i];
            String sub = s.substring(0, 3);
            output.put(sub.toUpperCase(), s);
        }
        System.out.println(output);
    }
}

LARGEST WORD:
package examPractice;

import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class LongestWord {

    String findMaxWordLength(String input) {
        String output = null;
        int max = 0;
        Set<String> inp = new TreeSet<String>();
        StringTokenizer tkn = new StringTokenizer(input, " ");
        while (tkn.hasMoreTokens()) {
            String s = tkn.nextToken();
            inp.add(s);
            if (s.length() > max) {
                max = s.length();
            }
        }
        System.out.println(inp);
        Iterator<String> it = inp.iterator();
        while (it.hasNext()) {
            String s = it.next();
            if (s.length() == max) {
                output = s;
                break;
            }
        }
        return output;
    }

    public static void main(String[] args) {
        System.out.println(new LongestWord()
                .findMaxWordLength("abcdefg honesty is my policy"));

    }

}

DAYS IN A MONTH:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class DaysInMonth {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String input1="20/06/2012";
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat sdf1 = new SimpleDateFormat("MMMM");
        Date d = new Date();
        try {
            d=sdf.parse(input1);
        } catch (ParseException e) {
       
        }
        String out=sdf1.format(d);
        if(out.equalsIgnoreCase("January")||out.equalsIgnoreCase("March")||out.equalsIgnoreCase("May")
    ||out.equalsIgnoreCase("July")||out.equalsIgnoreCase("August")||out.equalsIgnoreCase("October")
    ||out.equalsIgnoreCase("November"))
        {System.out.println(31);}
        else if(out.equalsIgnoreCase("February")){
            System.out.println(28);
        }else
        {
            System.out.println(30);
        }

    }

}

RAJ MGR ....RETURN KEY
package examPractice;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class ReturnKey {
    static String[] output1 = new String[100];

    /**
     * @param args
     */
    public static void main(String[] args) {
        int i=0;
        HashMap<String,String> input = new HashMap<String,String>();
        input.put("raj","MGR");
        input.put("ravi","CLK");
        input.put("ramu","MGR");
        input.put("sam","PRG");
        Set<String> keys = input.keySet();
        Iterator<String> it = keys.iterator();
        while(it.hasNext()){
            String s = it.next();
            if(input.get(s).equals("MGR")){
                output1[i]=s;
                i++;
            }
        }
        for(int j=0;j<i;j++){
            System.out.println(output1[j]);
        }
    }

}





2 comments:

  1. Really it was an awesome article. Very interesting to read. You have provided an nice article. Thanks for sharing this valuable blog.
    if you want learn more about Java Training visit us..

    ReplyDelete