Sunday, 19 November 2017

Practice Programs on String in java

Given below are all the possible programs that will help you get a good grasp on String concept in java. (Update in Progress)

Note: Follow all the business rules where applicable.

  1. Write a method that takes a String and calculates the total number of characters in the String. Business Rules :- 
    Rule 1 : If any special characters is present in the string , print -1. Rule 2 : String should contain only alphanumeric values and white spaces.
  2. Write a method which takes a string as input and returns true if its a valid IP address and false if not a valid IP.
    Business Rules :-                                                                                                                          Rule 1 : IP address should be like 10.10.23.56
    Rule 2 : All the digit must be between 0 to 255 except for the first digit which is 1 to 255.
    Rule 3 : Total 4 numbers would be there separated by only dots.
    Rule 4 : All the fields must be either dot or digits(no white space or symbols or alphabets allowed).
  3. Write a method that accepts a string and returns the total number of vowels in that string.
  4. Write a method that takes a string array and returns the count of palindromes in the string array.
  5. Write a method that will accept a string and will return the string after removing all characters other than alphabets.
  6. Write a method which accepts a string(ex. This is a pen and is used to write) and returns a list<int> where the index of all occurrences of "is" is stored. 
  7. Write a method that will take two strings and will return an integer which is the frequency of first string in second string .
    Input1:- is
    Input2:-He is a good boy,but his brother is not.
    Output:- 2
  8. Write a method that will take a string and will remove duplicate characters keeping only the first occurrence.
    Input:- Kolkataaaaa   Output:- Kolat
  9. Write a method that will take a string and will return an int array that contains the length of the largest and smallest words.
  10. Write a method that will take a string which will be the password for a very secured account.
    Business Rules:-The string should be maximum 10 characters long,minimum 8 characters long, should have a minimum 1 special character, 1 uppercase character , 1 lowercase character and 1 digit. The string should not start with digit or special symbols. No space is allowed. If all conditions satisfy return true and otherwise false.

Thursday, 2 November 2017

Can we keep more than one class in a single java source file?

We can have more than one class in a single java source file but with certain restriction.

Among multiple classes that you create in a single source file, only one can be public. Find an example given below,


package basic;

public class MultiplePublic {

      public static void main(String[] args) {
            //By java radar
            System.out.println("Executing main method");
            AnotherMultiplePublic amp = new AnotherMultiplePublic();
            amp.sampleMethod();
      }

}

class AnotherMultiplePublic {

      public void sampleMethod(){
            System.out.println("Print sample method");
      }

}

OUTPUT:
Executing main method

Print sample method


As shown above, write both classes in same source file with MultiplePublic class being public. As stated above if only one class is declared public then the code will run fine. So in this case the code will be executed without any glitches and produce output as stated under output header.

 Second Scenario:

Now, we will try to assign public access modifier to more than one class. Say two classes will have public modifier.

In this scenario, look at the below given screen-shot, to find out the result:

java radar examples
Multiple public class in same source file


See the red under line below AnotherMultiplePublic class in the screenshot above. Place the mouse cursor above it and you will see the error message:

                'The public type AnotherMultiplePublic must be defined in its own file'


Conclusion: That means in the same source file one cannot have more than one public class. 
Though there is no problem if you want to keep more than one class in same source file and you restrict the application of public modifier to only one class as we did in our first scenario.


Note for Readers: Please share your valuable thoughts on this post's question to help others.


You may also like to read:

Saturday, 28 October 2017

Pascal triangle in java

Program: Write a program to enter number of rows and create a Pascal Triangle.
Input: 5
Output:
     1               row=1
    1 1              row=2
   1 2 1             row=3
  1 3 3 1            row=4
 1 4 6 4 1           row=5



Source File: PascalTriangle.java

package triangle;

public class PascalTriangle
{
      public static void main(String args[])
      {
            int rows, i, k, number=1, j;
            rows = 5;  //change number of rows as per need

            for(i=0;i<rows;i++)
            {
                  for(k=rows; k>i; k--)
                  {
                        System.out.print(" ");
                  }
                  number = 1;
                  for(j=0;j<=i;j++)
                  {
                        System.out.print(number+ " ");
                        number = number * (i - j) / (j + 1);
                  }
                  System.out.println();
            }
      }
}



OUTPUT:

     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1




 You may also like to read about:

Friday, 20 October 2017

Calculator Application in java

Project Detail: Create calculator application which accepts two numbers from user and perform addition, subtraction, multiplication and division on given numbers.
                                     --------------------------  *  -----------------------------


Source: Calculation.java

package calculator;

public class Calculation {
      int result;
      //Method for addition
      public int add(int num1, int num2){
            result = num1+num2;
            return result;
      }
      //Method for subtraction
      public int substract(int num1, int num2){
            result = num1-num2;
            return result;
      }
      //Method for multiplication
      public int multiply(int num1, int num2){
            result = num1*num2;
            return result;
      }
      //Method for division
      public float divide(int num1, int num2){
            result = num1/num2;
            return result;
      }
     
}

Source: CalculatorVO.java

package calculator;

public class CalculatorVO {
      private int firstNumber;
      private int secondNumber;
     
      public int getFirstNumber() {
            return firstNumber;
      }
      public void setFirstNumber(int firstNumber) {
            this.firstNumber = firstNumber;
      }
      public int getSecondNumber() {
            return secondNumber;
      }
      public void setSecondNumber(int secondNumber) {
            this.secondNumber = secondNumber;
      }
     

}

Source: MainClass.java

package calculator;

public class MainClass {

      public static void main(String[] args) {
           
            CalculatorVO calVO = new CalculatorVO();
            //Input can be taken from user
            calVO.setFirstNumber(100);
            calVO.setSecondNumber(11);
           
            Calculation cal = new Calculation();
           
            int addResult = cal.add(calVO.getFirstNumber(), calVO.getSecondNumber());
            System.out.println("Addition Result ="+addResult);
           
            int subResult = cal.substract(calVO.getFirstNumber(), calVO.getSecondNumber());
            System.out.println("Subtraction Result ="+subResult);
           
            int mulResult = cal.multiply(calVO.getFirstNumber(), calVO.getSecondNumber());
            System.out.println("Multiplication Result ="+mulResult);
           
            float divResult = cal.divide(calVO.getFirstNumber(), calVO.getSecondNumber());
            System.out.println("Division Result ="+divResult);

      }

}


OUTPUT:
Addition Result =111
Subtraction Result =89
Multiplication Result =1100
Division Result =9.0

Tuesday, 17 October 2017

Can we overload main() in java?


Yes, the main() method in java can be overloaded.

Given below is the sample code snippet where main() method has been overloaded twice. If you want you can experiment by overloading main() as per your choice and requirement.

To prove our point that main() can be overloaded, below code is sufficient. Have a look,

Source File: MainOverloading.java 

package basic;

public class MainOverloading {

      public static void main(String[] args) {
            System.out.println("Overloaded methods will not be executed here");

      }
     
      public static void main(int x){
            System.out.println("x="+ x);
            main(5,54);
      }
     
      public static void main(int a, int b){
            System.out.println("a="+ a);
            System.out.println("b="+ b);
      }

}


OUTPUT:
Overloaded methods will not be executed here 

---------------------------------------------------------------------------------------------------

In the above code snippet JVM searches for public static void main(String[] args) type signature as regular. And anything inside public static void main(String[] args)  will be executed first. So if you want your overloaded main() method to get executed, you need to call it from inside actual main() which is entry point for all java program. 

Given below is modified version of above code snippet. Here overloaded main() is executed. Have a look,
---------------------------------------------------------------------------------------------------

Source File: MainOverloading.java 

package basic;

public class MainOverloading {

      public static void main(String[] args) {
        main(1);       //calling overloaded main

      }
     
      public static void main(int x){
            System.out.println("x="+ x);
            main(5,54);
      }
     
      public static void main(int a, int b){
            System.out.println("a="+ a);
            System.out.println("b="+ b);
      }

}


OUTPUT:
x=1    //output of main(int x)
a=5    //output of main(int a, int b) 
b=54
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.