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

Friday 13 April 2018

Stack trace to String Example



  1. /*
            Java Stacktrace to String Example
            This Java Stacktrace to String example shows how to get Stacktrace of any exception
            to String.
     */
    import java.io.PrintWriter;
    import java.io.StringWriter;

    public class StackTraceToStringExample {

            public static void main(String args[]){

                    try{

                            //this will throw NumberFormatException
                            Integer.parseInt(“Not a number”);

                    }catch(NumberFormatException e){

                            /*
                             * To convert Stacktrace to String in Java, use
                             * printStackTrace(PrintWrite pw) method of Throwable
                             * class.
                             */
                           
                            //create new StringWriter object
                            StringWriter sWriter = new StringWriter();

                            //create PrintWriter for StringWriter
                            PrintWriter pWriter = new PrintWriter(sWriter);

                            //now print the stacktrace to PrintWriter we just created
                            e.printStackTrace(pWriter);

                            //use toString method to get stacktrace to String from StringWriter object
                            String strStackTrace = sWriter.toString();

                            System.out.println(“Stacktrace converted to String: “ + strStackTrace);
                    }
            }

    }

    /*
    Output of above given Java Stacktrace to String would be
    Stacktrace converted to String: java.lang.NumberFormatException: For input string: “Not a number”
            at java.lang.NumberFormatException.forInputString(Unknown Source)
            at java.lang.Integer.parseInt(Unknown Source)
            at java.lang.Integer.parseInt(Unknown Source)
            at StackTraceToStringExample.main(StackTraceToStringExample.java:16)
    */

Sort String Array Example



  1. /*
            Java Sort String Array Example
            This Java Sort String Array example shows how to sort an array of Strings
            in Java using Arrays.sort method.
     */
    import java.util.Arrays;

    public class SortStringArrayExample 
    {

            public static void main(String args[]) 
    {

                    //String array
                    String[] strNames = new String[]{“John”, “alex”, “Chris”, “williams”, “Mark”, “Bob”};

                    /*
                     * To sort String array in java, use Arrays.sort method.
                     * Sort method is a static method.               *
                     */

                    //sort String array using sort method
                    Arrays.sort(strNames);

                    System.out.println(“String array sorted (case sensitive)”);

                    //print sorted elements
                    for(int i=0; i < strNames.length; i++)
     {
                            System.out.println(strNames[i]);
                    }

                    /*
                     * Please note that, by default Arrays.sort method sorts the Strings
                     * in case sensitive manner.
                     *
                     * To sort an array of Strings irrespective of case, use
                     * Arrays.sort(String[] strArray, String.CASE_INSENSITIVE_ORDER) method instead.
                     */

                    //case insensitive sort
                    Arrays.sort(strNames);

                    System.out.println(“String array sorted (case insensitive)”);
                    //print sorted elements again
                    for(int i=0; i < strNames.length; i++) 
    {
                            System.out.println(strNames[i]);
                    }

            }
    }

    /*
    Output of above given Java Sort String Array example would be
    String array sorted (case sensitive)
    Bob
    Chris
    John
    Mark
    alex
    williams
    String array sorted (case insensitive)
    Bob
    Chris
    John
    Mark
    alex
    williams
    */

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);
}
}

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (114) C (77) C# (12) C++ (82) Course (60) Coursera (176) coursewra (1) Cybersecurity (22) data management (11) Data Science (89) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (741) Python Coding Challenge (191) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

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