Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, 11 May 2016

Converting char (Primitive Character) to String in Java.

Hi, Today I'm going to tell you 3 ways to convert a primitive char to a String.

First Method:
This one is the simplest a person can think.
String str = "" + 'c';

This internally compiles down to :
String str = new StringBuilder().append("").append('c').toString();

This one is less efficient due to StringBuilder class.

Second Method:
As we cannot invoke toString() on the primitive type char or any other primitive, so we  can create a wrapper class Character and then we can eaily invoke toString() to it.
ex.
char c = 'c';
Character ch = Character.valueOf(c);
String str = ch.toString();

Third Method:
char c = 'c';
String str = String.valueOf(c);

Thanks

Sunday, 8 May 2016

Reference variable of parent class can access the overridden method in child class.

Hi,
As we know that the reference variable of parent class storing the object of child class can only access the members of its own class(i.e. the parent class). But you should keep in mind that it can access the overridden method in the child class.

The famous example is given here on oracle docs : - click here

I'm pasting that code snippet here also : -
public class Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Animal");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Animal");
    }
}
//The second class, a subclass of Animal, is called Cat:

public class Cat extends Animal {
    public static void testClassMethod() {
        System.out.println("The static method in Cat");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method in Cat");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;
        Animal.testClassMethod();
        myAnimal.testInstanceMethod();
    }
}

The output is : 


The static method in Animal
The instance method in Cat

This proves.

Saturday, 19 March 2016

Stone Paper Scissor game in Java


import java.util.Random;
import java.util.Scanner;

public class Game
{
    private static int userWinningCount, computerWinningCount;
    private int userInput, computerInput;
    public void setUserInput(int userInput)
    {
        this.userInput = userInput;
    }
    public void setComputerInput()
    {
        Random r = new Random();
        computerInput = r.nextInt(3-1+1)+1;// corresponding to r.nextInt(max-min+1)+min;
    }
    public String computerChoice()
    {
        if(computerInput == 1)
            return "Stone";
        else if(computerInput == 2)
            return "Paper";
        else
            return "Scissor";
    }
    public String getResult()
    {
        if(userInput == computerInput)
            return "Tie ";
        else if(userInput == 1 && computerInput == 2)// stone = 1, paper = 2, scissor = 3;
            return "Computer won";
        else if(userInput == 1 && computerInput == 3)
            return "You won";
        else if(userInput == 2 && computerInput == 1)
            return "You won";
        else if(userInput == 2 && computerInput == 3)
            return "Computer won";
        else if(userInput == 3 && computerInput == 1)
            return "Computer won";
        return "You won";// i.e. user has scissor and computer has paper.
    }
    public static void main(String []args)
    {
        String s = "yes";
        Game obj = new Game();
        Scanner input = new Scanner(System.in);
        while(s.equalsIgnoreCase("yes"))
        {
            System.out.println("Ener your choice (Stone, Paper, Scissor)");
            String choice = input.next();
            choice = choice.toLowerCase();
            if(choice.equals("stone"))
                obj.setUserInput(1);
            else if(choice.equals("paper"))
                obj.setUserInput(2);
            else if(choice.equals("scissor"))
                obj.setUserInput(3);
            else
                System.out.println("Enter valid option");
            obj.setComputerInput();
            System.out.println("The computer chose : "+obj.computerChoice());
            if(obj.getResult().equals("You won"))
                userWinningCount++;
            else if(obj.getResult().equals("Computer won"))
                computerWinningCount++;
            System.out.println(obj.getResult());
            System.out.print("Your winning count = "+userWinningCount);
            System.out.print(" and Computer winning count = "+computerWinningCount);
            System.out.println("\n Wanna continue playing game ? (enter yes) ");
            s = input.next();
        }
        input.close();
    }
}

Java program to multiply any number with 7 without using * and + operator


import java.util.Scanner;

public class MultiplyWith7
{
    private Integer num, res;
        //private double res1;// for another solution to this problem
    public void getNum(Integer n)
    {
        num = n;
    }
    public void CalculateResult()
    {
                //res1 = num/((double)1/7);// then print res1
        res = num<<3;
        res = res-num;
    }
    public void showResult()
    {
        System.out.println("The result of "+num+"*7 is : "+res);
    }
    public static void main(String []args)
    {
        MultiplyWith7 obj = new MultiplyWith7();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number : ");
        obj.getNum(input.nextInt());
        obj.CalculateResult();
        obj.showResult();
        input.close();
    }
}

hexadecimal to octal conversion program in java


import java.util.Scanner;

public class HexadecimalToOctal 
{
    private String hex;
    private int dec;
    private String oct;
    public void setHex(String hex)
    {
        this.hex = hex;
    }
    public void getDec()
    {
        dec = Integer.parseInt(hex, 16);
    }
    public void setOct()
    {
        oct = Integer.toOctalString(dec);
    }
    public String getOct()
    {
        return oct;
    }
    public static void main(String []args)
    {
        HexadecimalToOctal obj = new HexadecimalToOctal();
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a hexadecimal number : ");
        obj.setHex(input.next());
        obj.getDec();
        obj.setOct();
        System.out.println("The octal equivalent is : "+obj.getOct());
        input.close();
    }
}