Friday, 13 April 2018

Search String using index Of Example



  1. /*
      Java Search String using indexOf Example
      This example shows how we can search a word within a String object using
      indexOf method.
    */

    public class SearchStringExample  
    {

      public static void main(String[] args)  
    {
        //declare a String object
        String strOrig = “Hello world Hello World”;

        /*
          To search a particular word in a given string use indexOf method.
          indexOf method. It returns a position index of a word within the string
          if found. Otherwise it returns -1.
        */

        int intIndex = strOrig.indexOf(“Hello”);

        if(intIndex == 1){
          System.out.println(“Hello not found”);
        }else{
          System.out.println(“Found Hello at index “ + intIndex);
        }

        /*
          we can also search a word after particular position using
          indexOf(String word, int position) method.  
        */

        int positionIndex = strOrig.indexOf(“Hello”,11);
        System.out.println(“Index of Hello after 11 is “ + positionIndex);

        /*
          Use lastIndexOf method to search a last occurrence of a word within string.
        */
        int lastIndex = strOrig.lastIndexOf(“Hello”);
        System.out.println(“Last occurrence of Hello is at index “ + lastIndex);

      }
    }

    /*
    Output of the program would be :
    Found Hello at index 0
    Index of Hello after 11 is 12
    Last occurrence of Hello is at index 12
    */

Reverse String Array Example



  1. /*
            Java Reverse String Array Example
            This Java Reverse String Array example shows how to find sort an array of
            String in Java using Arrays and Collections classes.
     */

    import java.util.Collections;
    import java.util.List;
    import java.util.Arrays;

    public class ReverseStringArrayExample {

            public static void main(String args[]){

                    //String array
                    String[] strDays = new String[]{“Sunday”, “Monday”, “Tuesday”, “Wednesday”};

                    /*
                     * There are basically two methods, one is to use temporary array and
                     * manually loop through the elements of an Array and swap them or to use
                     * Arrays and Collections classes.
                     *
                     * This example uses the second approach i.e. without temp variable.
                     *
                     */
                   
                    //first create a list from String array
                    List<String> list = Arrays.asList(strDays);

                    //next, reverse the list using Collections.reverse method
                    Collections.reverse(list);

                    //next, convert the list back to String array
                    strDays = (String[]) list.toArray();

                    System.out.println(“String array reversed”);

                    //print the reversed String array
                    for(int i=0; i < strDays.length; i++){
                            System.out.println(strDays[i]);
                    }

            }

    }

    /*
    Output of above given Java Reverse String Array example would be
    String array reversed
    Wednesday
    Tuesday
    Monday
    Sunday
    */

Input Stream to String Example



  • /*
            Java InputStream to String Example
        This Java InputStream to String example shows how to convert InputStream to String in Java.
     */
    public class ConvertInputStreamToStringExample  
    {

            public static void main(String args[]) throws IOException{

                    //get InputStream of a file
                    InputStream is = new FileInputStream(“c:/data.txt”);
                    String strContent;

                    /*
                     * There are several way to convert InputStream to String. First is using
                     * BufferedReader as given below.
                     */

                    //Create BufferedReader object
                    BufferedReader bReader = new BufferedReader(new InputStreamReader(is));
                    StringBuffer sbfFileContents = new StringBuffer();
                    String line = null;

                    //read file line by line
                    while( (line = bReader.readLine()) != null) 
    {
                            sbfFileContents.append(line);
                    }

                    //finally convert StringBuffer object to String!
                    strContent = sbfFileContents.toString();

                    /*
                     * Second and one liner approach is to use Scanner class. This is only supported
                     * in Java 1.5 and higher version.
                     */

                    strContent = new Scanner(is).useDelimiter(\\A”).next();
            }
    }

Date to String Example



  1. /*
            Java Date to String Example
            This Java Date to String example shows how to convert java.util.Date to
            String in Java.
     */

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class ConvertDateToStringExample
     {

            public static void main(String args[]) 
    {

                    //create new java.util.Date object
                    Date date = new Date();

                    /*
                     * To convert java.util.Date to String, use SimpleDateFormat class.
                     */

                    /*
                     * crate new SimpleDateFormat instance with desired date format.
                     * We are going to use yyyy-mm-dd hh:mm:ss here.
                     */
                    DateFormat dateFormat = new SimpleDateFormat(“yyyy-mm-dd hh:mm:ss”);

                    //to convert Date to String, use format method of SimpleDateFormat class.
                    String strDate = dateFormat.format(date);

                    System.out.println(“Date converted to String: “ + strDate);

            }
    }

    /*
    Output of above given java.util.Date to String example would be
    Date converted to String: 2011-17-10 11:17:50
    */

Char Array To String Example






ArrayList to String Array Example



  1. /*
            Java ArrayList to String Array Example
            This Java ArrayList to String Array example shows how to convert ArrayList to String array
            in Java.
     */

    import java.util.ArrayList;
    import java.util.Arrays;

    public class ArrayListToStringArrayExample {

            public static void main(String args[]){

                    //ArrayList containing string objects
                    ArrayList<String> aListDays = new ArrayList<String>();
                    aListDays.add(“Sunday”);
                    aListDays.add(“Monday”);
                    aListDays.add(“Tuesday”);

                    /*
                     * To convert ArrayList containing String elements to String array, use
                     * Object[] toArray() method of ArrayList class.
                     *
                     * Please note that toArray method returns Object array, not String array.
                     */
                   
                    //First Step: convert ArrayList to an Object array.
                    Object[] objDays = aListDays.toArray();

                    //Second Step: convert Object array to String array
                    String[] strDays = Arrays.copyOf(objDays, objDays.length, String[].class);

                    System.out.println(“ArrayList converted to String array”);

                    //print elements of String array
                    for(int i=0; i < strDays.length; i++){
                            System.out.println(strDays[i]);
                    }
            }
    }

    /*
    Output of above given ArrayList to String Array example would be
    ArrayList converted to String array
    Sunday
    Monday
    Tuesday
    */

Convert String to Character Array Example



  1. /*
     Convert String to Character Array Example
     This example shows how to convert a given String object to an array
     of character
     */

    public class StringToCharacterArrayExample  
    {

      public static void main(String args[]) 
    {
        //declare the original String object
        String strOrig = “Hello World”;
        //declare the char array
        char[] stringArray;

        //convert string into array using toCharArray() method of string class
        stringArray = strOrig.toCharArray();

        //display the array
        for(int index=0; index < stringArray.length; index++)
          System.out.print(stringArray[index]);

      }

    }

    /*
    Output of the program would be :
    Hello World
    */

Check if string contains valid number example


  1. /*
            Check if string contains valid number example.
            This example shows how to check if string contains valid number
            or not using parseDouble and parseInteger methods of
            Double and Integer wrapper classes.
    */

    public class CheckValidNumberExample {

            public static void main(String[] args) {

                    String[] str = new String[]{“10.20”, “123456”, “12.invalid”};

                    for(int i=0 ; i < str.length ; i ++)
                    {

                            if( str[i].indexOf(“.”) > 0 )
                            {

                                    try
                                    {
                                            /*
                                             * To check if the number is valid decimal number, use
                                             * double parseDouble(String str) method of
                                             * Double wrapper class.
                                             *
                                             * This method throws NumberFormatException if the
                                             * argument string is not a valid decimal number.
                                             */
                                            Double.parseDouble(str[i]);
                                            System.out.println(str[i] + ” is a valid decimal number”);
                                    }
                                    catch(NumberFormatException nme)
                                    {
                                            System.out.println(str[i] + ” is not a valid decimal number”);
                                    }

                            }
                            else
                            {
                                    try
                                    {
                                            /*
                                             * To check if the number is valid integer number, use
                                             * int parseInt(String str) method of
                                             * Integer wrapper class.
                                             *
                                             * This method throws NumberFormatException if the
                                             * argument string is not a valid integer number.
                                             */

                                            Integer.parseInt(str[i]);
                                            System.out.println(str[i] + ” is valid integer number”);
                                    }
                                    catch(NumberFormatException nme)
                                    {
                                            System.out.println(str[i] + ” is not a valid integer number”);
                                    }
                            }
                    }

            }
    }


    /*
    Output would be
    10.20 is a valid decimal number
    123456 is valid integer number
    12.invalid is not a valid decimal number
    */

A program to find whether no. is palindrome or not



Example : Input – 12521 is a palindrome no. Input – 12345 is not a palindrome no. */

class Palindrome
{
public static void main(String args[])

{
int num = Integer.parseInt(args[0]);
int n = num; //used at last time check
int reverse=0,remainder;
while(num > 0)

{
remainder = num % 10;
reverse = reverse * 10 + remainder;
num = num / 10;
}
if(reverse == n)
System.out.println(n+” is a Palindrome Number”);
else
System.out.println(n+” is not a Palindrome Number”);
}
}

A program to Find whether number is Prime or Not



class PrimeNo
{
public static void main(String args[])

{
int num = Integer.parseInt(args[0]);
int flag=0;
for(int i=2;i<num;i++)

{
if(num%i==0)
{
System.out.println(num+” is not a Prime Number”);
flag = 1;
break;
}
}
if(flag==0)
System.out.println(num+” is a Prime Number”);
}
}

Display Triangle as follow



1 2 3 4 5 6 7 8 9 10 … N */

class Output1{
public static void main(String args[])

{
int c=0;
int n = Integer.parseInt(args[0]);
loop1: for(int i=1;i<=n;i++)

{
loop2: for(int j=1;j<=i;j++)

{
if(c!=n)

{
c++;
System.out.print(c+” “);
}
else
break loop1;
}
System.out.print(“\n”);
}
}
}

A program to find average of consecutive N Odd no. and Even no



class EvenOdd_Avg{
public static void main(String args[]){
int n = Integer.parseInt(args[0]);
int cntEven=0,cntOdd=0,sumEven=0,sumOdd=0;
while(n > 0){
if(n%2==0){
cntEven++;
sumEven = sumEven + n;
}
else{
cntOdd++;
sumOdd = sumOdd + n;
}
n–;
}
int evenAvg,oddAvg;
evenAvg = sumEven/cntEven;
oddAvg = sumOdd/cntOdd;
System.out.println(“Average of first N Even no is “+evenAvg);
System.out.println(“Average of first N Odd no is “+oddAvg);
}
}

A program to generate Harmonic Series



Example : Input – 5 Output – 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */
 

class HarmonicSeries
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
double result = 0.0;
while(num > 0)

{
result = result + (double) 1 / num;
num–;
}
System.out.println(“Output of Harmonic Series is “+result);
}
}

Switch case demo



Example : Input – 124 Output – One Two Four */

class SwitchCaseDemo{
public static void main(String args[])

{
try

{
int num = Integer.parseInt(args[0]);
int n = num; //used at last time check
int reverse=0,remainder;
while(num > 0)

{
remainder = num % 10;
reverse = reverse * 10 + remainder;
num = num / 10;
}
String result=””; //contains the actual output
while(reverse > 0)

{
remainder = reverse % 10;
reverse = reverse / 10;
switch(remainder)

{
case 0 :
result = result + “Zero “;
break;
case 1 :
result = result + “One “;
break;
case 2 :
result = result + “Two “;
break;
case 3 :
result = result + “Three “;
break;
case 4 :
result = result + “Four “;
break;
case 5 :
result = result + “Five “;
break;
case 6 :
result = result + “Six “;
break;
case 7 :
result = result + “Seven “;
break;
case 8 :
result = result + “Eight “;
break;
case 9 :
result = result + “Nine “;
break;
default:
result=””;
}
}
System.out.println(result);
}catch(Exception e){
System.out.println(“Invalid Number Format”);
}
}
}


A program to find whether given no. is Armstrong or not



Example : Input – 153 Output – 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no. */

class Armstrong
{
public static void main(String args[])

{
int num = Integer.parseInt(args[0]);
int n = num; //use to check at last time
int check=0,remainder;
while(num > 0)

{
remainder = num % 10;
check = check + (int)Math.pow(remainder,3);
num = num / 10;
}
if(check == n)
System.out.println(n+” is an Armstrong Number”);
else
System.out.println(n+” is not a Armstrong Number”);
}
}

A program to Display Invert Triangle using while loop



Example: Input – 5 Output : 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1
class InvertTriangle
{
public static void main(String args[])

{
int num = Integer.parseInt(args[0]);
while(num > 0)

{
for(int j=1;j<=num;j++)

{
System.out.print(” “+num+” “);
}
System.out.print(“\n”);
num–;
}
}
}

 

Thursday, 12 April 2018

A program to convert given no. of days into months and days.(Assume that each month is of 30 days)


Example : Input – 69 Output – 69 days = 2 Month and 9 days */

class DayMonthDemo
{
public static void main(String args[])
{
int num = Integer.parseInt(args[0]);
int days = num%30;
int month = num/30;
System.out.println(num+” days = “+month+” Month and “+days+” days”);
}
}

A program to Swap the values



class Swap{
public static void main(String args[]){
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.println(“\n***Before Swapping***”);
System.out.println(“Number 1 : “+num1);
System.out.println(“Number 2 : “+num2);
//Swap logic
num1 = num1 + num2;
num2 = num1 – num2;
num1 = num1 – num2;
System.out.println(“\n***After Swapping***”);
System.out.println(“Number 1 : “+num1);
System.out.println(“Number 2 : “+num2);
}
}

A program to find SUM AND PRODUCT of a given Digit



class Sum_Product_ofDigit{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
//taking value as command line argument.
int temp = num,result=0;
//Logic for sum of digit
while(temp>0){
result = result + temp;
temp–;
}
System.out.println(“Sum of Digit for “+num+” is : “+result);
//Logic for product of digit
temp = num;
result = 1;
while(temp > 0){
result = result * temp;
temp–;
}
System.out.println(“Product of Digit for “+num+” is : “+result);
}
}

A program to display a greet message according to Marks obtained by student



class SwitchDemo{
public static void main(String args[]){
int marks = Integer.parseInt(args[0]); //take marks
as command line argument.
switch(marks/10){
case 10:
case 9:
case 8:
System.out.println(“Excellent”);
break;
case 7:
System.out.println(“Very Good”);
break;
case 6:
System.out.println(“Good”);
break;
case 5:
System.out.println(“Work Hard”);
break;
case 4:
System.out.println(“Poor”);
break;
case 3:
case 2:
case 1:
case 0:
System.out.println(“Very Poor”);
break;
default:
System.out.println(“Invalid value Entered”);
}
}
}

A Program that will read a float type value from the keyboard and print the following output



/*Small Integer not less than the number. Given Number. Largest Integer not greater than the number. */
class ValueFormat{
public static void main(String args[]){
double i = 34.32; //given number
System.out.println(“Small Integer not greater than the number :”+Math.ceil(i));
System.out.println(“Given Number : “+i);
System.out.println(“Largest Integer not greater than the number :”+Math.floor(i));
}

To Find Minimum of Two Numbers using conditional operator


/* To find minimum of 2 Numbers using ternary operator */
class Minoftwo{
public static void main(String args[]){
//taking value as command line argument. //Converting String format to Integer value
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int result = (i<j)?i:j;
System.out.println(result+” is a minimum value”);
}
}

Find Maximum of Two Numbers



/* To Find Maximum of 2 Numbers using if else */
class Maxoftwo{
public static void main(String args[]){
 
//taking value as command line argument. //Converting String format to Integer value
 

int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
if(i > j)
System.out.println(i+” is greater than “+j);
else
System.out.println(j+” is greater than “+i);
}
}

pyramid of numbers using for loops



/* Generate Pyramid For a Given Number Example This Java example shows how to generate a pyramid of numbers for given number using for loop example. */
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class GeneratePyramidExample {
public static void main (String[] args) throws Exception{
BufferedReader keyboard = new BufferedReader (new
InputStreamReader(System.in));
System.out.println(“Enter Number:”);
int as= Integer.parseInt (keyboard.readLine());
System.out.println(“Enter X:”);
int x= Integer.parseInt (keyboard.readLine());
int y = 0;
for(int i=0; i<= as ;i++){
16
for(int j=1; j <= i ; j++){
System.out.print(y + “\t”);
y = y + x;
}
System.out.println(“”);
}
}
}
/* Output of this example would be Enter Number: 5 Enter X: 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ———————————————- Enter Number: 5 Enter X: 2 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 ———————————————- Enter Number: 5 Enter X: 3 0 3 6 9 12 15 18 21 24 27 30 33 36 39 42 */

Factorial of a number using recursion


/*This program shows how to calculate Factorial of a number using recursion function. */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class JavaFactorialUsingRecursion {
public static void main(String args[]) throws NumberFormatException,
IOException{
System.out.println(“Enter the number: “);
//get input from the user
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int a = Integer.parseInt(br.readLine());
//call the recursive function to generate factorial
int result= fact(a);
System.out.println(“Factorial of the number is: ” + result);
}
static int fact(int b)
{
if(b <= 1)
//if the number is 1 then return 1
return 1;
else
//else call the same function with the value – 1
return b * fact(b-1);
}
}
/* Output of this Java example would be Enter the number: 5 Factorial of the number is: 120 */

Calculate Circle Area using radius


This program shows how to calculate
area of circle using it’s radius.
 
Example:-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CalculateCircleAreaExample {
public static void main(String[] args) {
int radius = 0;
System.out.println(“Please enter radius of a circle”);
try
{
//get the radius from console
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
radius = Integer.parseInt(br.readLine());
}
//if invalid value was entered
catch(NumberFormatException ne)
{
System.out.println(“Invalid radius value” + ne);
System.exit(0);
}
catch(IOException ioe)
{
System.out.println(“IO Error :” + ioe);
System.exit(0);
}
/*
* Area of a circle is
* pi * r * r
* where r is a radius of a circle.
*/
//NOTE : use Math.PI constant to get value of pi
double area = Math.PI * radius * radius;
System.out.println(“Area of a circle is ” + area);
}
}

Output:-
Please enter radius of a circle
19
Area of a circle is 1134.1149479459152

Nested Switch


This example shows how to use nested switch statements in a
java program.
Example:-
public class NestedSwitchExample {
public static void main(String[] args) {
/*
* Like any other Java statements, switch statements
* can also be nested in each other as given in
* below example.
*/
int i = 0;
int j = 1;
switch(i)
{
case 0:
switch(j)
{
case 0:
System.out.println(“i is 0, j is 0”);
break;
case 1:
System.out.println(“i is 0, j is 1”);
break;
default:
System.out.println(“nested default
case!!”);
}
break;
default:
System.out.println(“No matching case found!!”);
}
}
}

Output:-
i is 0, j is 1

Popular Posts

Categories

100 Python Programs for Beginner (53) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (358) Python Quiz (23) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses