-
Java String to Date Example.This Java String to Date example shows how to convert Java String to Date object.*/import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;
public class JavaStringToDate {public static void main(String args[]){
//Java String having dateString strDate = “21/08/2011”;
/** To convert Java String to Date, use* parse(String) method of SimpleDateFormat class.** parse method returns the Java Date object.*/
try{
/** Create new object of SimpleDateFormat class using* SimpleDateFormat(String pattern) constructor.*/
SimpleDateFormat sdf = new SimpleDateFormat(“dd/MM/yyyy”);
//convert Java String to Date using parse method of SimpleDateFormatDate date = sdf.parse(strDate);
//Please note that parse method throws ParseException if the String date could not be parsed.
System.out.println(“Date is: “ + date);
}catch(ParseException e){System.out.println(“Java String could not be converted to Date: “ + e);}}}
/*Output of Java String to Date example would beFri Jan 21 00:00:00 IST 2011*/
Friday, 13 April 2018
String to Lower Case example
Irawen April 13, 2018 Java No comments
-
/*Java String to Lower Case example.This Java String to Lower Case example shows how to change the string to lower caseusing toLowerCase method of String class.*/public class StringToLowerCaseExample {
public static void main(String[] args) {
String str = “STRING TOLOWERCASE EXAMPLE”;
/** To change the case of string to lower case use,* public String toLowerCase() method of String class.**/
String strLower = str.toLowerCase();
System.out.println(“Original String: “ + str);System.out.println(“String changed to lower case: “ + strLower);}}
/*Output would beOriginal String: STRING TOLOWERCASE EXAMPLEString changed to lower case: string tolowercase example*/
String to UpperCase example
Irawen April 13, 2018 Java No comments
-
/*Java String to Upper Case example.This Java String to Upper Case example shows how to change the string to upper caseusing toUpperCase method of String class.*/
public class StringToUpperCaseExample
{
public static void main(String[] args)
{
String str = “string touppercase example”;
/** To change the case of string to upper case use,* public String toUpperCase() method of String class.**/
String strUpper = str.toUpperCase();
System.out.println(“Original String: “ + str);System.out.println(“String changed to upper case: “ + strUpper);}}
/*Output would beOriginal String: string touppercase exampleString changed to upper case: STRING TOUPPERCASE EXAMPLE*/
String Trim Example
Irawen April 13, 2018 Java No comments
-
/*Java String Trim Example.This Java String trim example shows how to remove leading and trailing spacefrom string using trim method of Java String class.*/
public class RemoveLeadingTrailingSpace
{
public static void main(String[] args)
{
String str = ” String Trim Example “;
/** To remove leading and trailing space from string use,* public String trim() method of Java String class.*/
String strTrimmed = str.trim();
System.out.println(“Original String is: “ + str);System.out.println(“Removed Leading and trailing space”);System.out.println(“New String is: “ + strTrimmed);}}
/*Output would beOriginal String is: String Trim ExampleRemoved Leading and trailing spaceNew String is: String Trim Example*/
String Split Example
Irawen April 13, 2018 Java No comments
*
-
Java String split example.This Java String split example describes how Java String is split into multipleJava String objects.*/
public class JavaStringSplitExample{
public static void main(String args[]){/*Java String class defines following methods to split Java String object.String[] split( String regularExpression )Splits the string according to given regular expression.String[] split( String reularExpression, int limit )Splits the string according to given regular expression. The number of resultantsubstrings by splitting the string is controlled by limit argument.*//* String to split. */String str = “one-two-three”;String[] temp;
/* delimiter */String delimiter = “-“;/* given string will be split by the argument delimiter provided. */temp = str.split(delimiter);/* print substrings */for(int i =0; i < temp.length ; i++)System.out.println(temp[i]);
/*IMPORTANT : Some special characters need to be escaped while providing them asdelimiters like “.” and “|”.*/
System.out.println(“”);str = “one.two.three”;delimiter = “\\.”;temp = str.split(delimiter);for(int i =0; i < temp.length ; i++)System.out.println(temp[i]);
/*Using second argument in the String.split() method, we can control the maximumnumber of substrings generated by splitting a string.*/System.out.println(“”);temp = str.split(delimiter,2);for(int i =0; i < temp.length ; i++)System.out.println(temp[i]);
}
}
/*OUTPUT of the above given Java String split Example would be :onetwothreeonetwothreeonetwo.three*/
String Replace Example
Irawen April 13, 2018 Java No comments
-
/*Java String replace example.This Java String Replace example describes how replace method of java String classcan be used to replace character or substring can be replaced by new one.*/public class JavaStringReplaceExample{
public static void main(String args[]){
/*Java String class defines three methods to replace character or substring fromthe given Java String object.1) String replace(int oldChar, int newChar)This method replaces a specified character with new character and returns anew string object.2) String replaceFirst(String regularExpression, String newString)Replaces the first substring of this string that matches the given regularexpression with the given new string.3) String replaceAll(String regex, String replacement)Replaces the each substring of this string that matches thegiven regular expression with the given new string.*/
String str=“Replace Region”;
/*Replaces all occourances of given character with new one and returns newString object.*/System.out.println( str.replace( ‘R’,‘A’ ) );
/*Replaces only first occourances of given String with new one andreturns new String object.*/System.out.println( str.replaceFirst(“Re”, “Ra”) );
/*Replaces all occourances of given String with new one and returnsnew String object.*/System.out.println( str.replaceAll(“Re”, “Ra”) );
}
}
/*OUTPUT of the above given Java String Replace Example would be :Aeplace AegionRaplace RegionRaplace Ragion*/
String Length Example
Irawen April 13, 2018 Java No comments
-
/*Java String Length ExampleThis example shows how to get a length of a given String object.*/
public class StringLengthExample
{
public static void main(String[] args)
{//declare the String objectString str = “Hello World”;
//length() method of String returns the length of a String.int length = str.length();System.out.println(“Length of a String is : “ + length);}}
/*Output of a program would be:Length of a String is : 11*/
String Contains example
Irawen April 13, 2018 Java No comments
-
This Java String contains examples shows how to use contains method of Java String class.*/public class JavaStringContains {public static void main(String args[]){String str1 = “Hello World”;String str2 = “Hello”;
/** To check whether the string contains specified character sequence use,* boolean contains(CharSequence sq)* method of Java String class.** This method returns true if the string contains given character sequence.* Please note that contains method is added in Java 1.5*/boolean blnFound = str1.contains(str2);System.out.println(“String contains another string? : “ + blnFound);
/** Please also note that the comparison is case sensitive.*/}}
/*Output of Java String contains example would beString contains another string? : true*/
String Concat Example
Irawen April 13, 2018 Java No comments
-
/*Java String Concat Example.This Java String concat example shows how to concat String in Java.*/public class JavaStringConcat {public static void main(String args[]){/** String concatenation can be done in several ways in Java.*/
String str1 = “Hello”;String str2 = ” World”;
//1. Using + operatorString str3 = str1 + str2;System.out.println(“String concat using + operator : “ + str3);
/** Internally str1 + str 2 statement would be executed as,* new StringBuffer().append(str1).append(str2)** String concatenation using + operator is not recommended for large number* of concatenation as the performance is not good.*///2. Using String.concat() methodString str4 = str1.concat(str2);System.out.println(“String concat using String concat method : “ + str4);
//3. Using StringBuffer.append methodString str5 = new StringBuffer().append(str1).append(str2).toString();System.out.println(“String concat using StringBuffer append method : “ + str5);}
}
/*Output of Java String concat example would beString concat using + operator : Hello WorldString concat using String concat method : Hello WorldString concat using StringBuffer append method : Hello World*/
String Compare Example
Irawen April 13, 2018 Java No comments
-
/*Java String compare example.This Java String compare example describes how Java String is compared with anotherJava String object or Java Object.*/
public class JavaStringCompareExample{
public static void main(String args[]){
/*Java String class defines following methods to compare Java String object.1) int compareTo( String anotherString )compare two string based upon the unicode value of each character in the String.Returns negative int if first string is less than anotherReturns positive int if first string is grater than anotherReturns 0 if both strings are same.2) int compareTo( Object obj )Behaves exactly like compareTo ( String anotherString) if the argument objectis of type String, otherwise throws ClassCastException.3) int compareToIgnoreCase( String anotherString )Compares two strings ignoring the character case of the given String.*/
String str = “Hello World”;String anotherString = “hello world”;Object objStr = str;
/* compare two strings, case sensitive */System.out.println( str.compareTo(anotherString) );/* compare two strings, ignores character case */System.out.println( str.compareToIgnoreCase(anotherString) );/* compare string with object */System.out.println( str.compareTo(objStr) );
}
}
/*OUTPUT of the above given Java String compare Example would be :-3200*/
String Array Length Example
Irawen April 13, 2018 Java No comments
-
/*Java String Array Length ExampleThis Java String Array Length example shows how to find number of elementscontained in an Array.*/
public class JavaStringArrayLengthExample {
public static void main(String args[]){
//create String arrayString[] strArray = new String[]{“Java”, “String”, “Array”, “Length”};
/** To get length of array, use length property of array.*/int length = strArray.length;
System.out.println(“String array length is: “ + length);
//print elements of an arrayfor(int i=0; i < length; i++){System.out.println(strArray[i]);}}}
/*Output of above given Java String length example would beString array length is: 4JavaStringArrayLength*/
String Array Contains Example
Irawen April 13, 2018 Java No comments
-
/*Java String Array Contains ExampleThis Java String Array Contains example shows how to find a String inString array in Java.*/
import java.util.Arrays;
public class StringArrayContainsExample {
public static void main(String args[]){
//String arrayString[] strMonths = new String[]{“January”, “February”, “March”, “April”, “May”};
//Strings to findString strFind1 = “March”;String strFind2 = “December”;
/** There are several ways we can check whether a String array* contains a particular string.** First of them is iterating the array elements and check as given below.*/boolean contains = false;
//iterate the String arrayfor(int i=0; i < strMonths.length; i++){
//check if string array contains the stringif(strMonths[i].equals(strFind1)){
//string foundcontains = true;break;
}}
if(contains){System.out.println(“String array contains String “ + strFind1);}else{System.out.println(“String array does not contain String “ + strFind1);}
/** Second way to check whether String array contains a string is to use* Arrays class as given below.*/
contains = Arrays.asList(strMonths).contains(strFind1);System.out.println(“Does String array contain “ + strFind1 + “? “ + contains);
contains = Arrays.asList(strMonths).contains(strFind2);System.out.println(“Does String array contain “ + strFind2 + “? “ + contains);
}}
/*Output of above given Java String Array Contains example would beString array contains String MarchDoes String array contain March? trueDoes String array contain December? false*/
Stack trace to String Example
Irawen April 13, 2018 Java No comments
-
/*Java Stacktrace to String ExampleThis Java Stacktrace to String example shows how to get Stacktrace of any exceptionto String.*/import java.io.PrintWriter;import java.io.StringWriter;
public class StackTraceToStringExample {
public static void main(String args[]){
try{
//this will throw NumberFormatExceptionInteger.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 objectStringWriter sWriter = new StringWriter();
//create PrintWriter for StringWriterPrintWriter pWriter = new PrintWriter(sWriter);
//now print the stacktrace to PrintWriter we just createde.printStackTrace(pWriter);
//use toString method to get stacktrace to String from StringWriter objectString strStackTrace = sWriter.toString();
System.out.println(“Stacktrace converted to String: “ + strStackTrace);}}
}
/*Output of above given Java Stacktrace to String would beStacktrace 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
Irawen April 13, 2018 Java No comments
-
/*Java Sort String Array ExampleThis Java Sort String Array example shows how to sort an array of Stringsin Java using Arrays.sort method.*/import java.util.Arrays;
public class SortStringArrayExample
{
public static void main(String args[])
{
//String arrayString[] 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 methodArrays.sort(strNames);
System.out.println(“String array sorted (case sensitive)”);
//print sorted elementsfor(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 sortArrays.sort(strNames);
System.out.println(“String array sorted (case insensitive)”);//print sorted elements againfor(int i=0; i < strNames.length; i++)
{System.out.println(strNames[i]);}
}}
/*Output of above given Java Sort String Array example would beString array sorted (case sensitive)BobChrisJohnMarkalexwilliamsString array sorted (case insensitive)BobChrisJohnMarkalexwilliams*/
Popular Posts
-
Exploring Python Web Scraping with Coursera’s Guided Project In today’s digital era, data has become a crucial asset. From market trends t...
-
What does the following Python code do? arr = [10, 20, 30, 40, 50] result = arr[1:4] print(result) [10, 20, 30] [20, 30, 40] [20, 30, 40, ...
-
Explanation: Tuple t Creation : t is a tuple with three elements: 1 → an integer [2, 3] → a mutable list 4 → another integer So, t looks ...
-
What will the following code output? a = [1, 2, 3] b = a[:] a[1] = 5 print(a, b) [1, 5, 3] [1, 5, 3] [1, 2, 3] [1, 2, 3] [1, 5, 3] [1, 2, ...
-
What will the following Python code output? What will the following Python code output? arr = [1, 3, 5, 7, 9] res = arr[::-1][::2] print(re...
-
What will be the output of the following code? import numpy as np arr = np.array([1, 2, 3, 4]) result = arr * arr[::-1] print(result) [1, ...
-
Through a recent series of breakthroughs, deep learning has boosted the entire field of machine learning. Now, even programmers who know c...
-
Code Explanation: range(5): The range(5) generates numbers from 0 to 4 (not including 5). The loop iterates through these numbers one by o...
-
What will the following code output? import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Age': [25, 3...
-
What will the output of the following code be? def puzzle(): a, b, *c, d = (10, 20, 30, 40, 50) return a, b, c, d print(puzzle()) ...
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)