Study Anytime Any Where We Will Open The Knowledge For You Anish Sir 24x7 Learning solution It Is Time to join JOB
23 October 2017

Study Anytime Any Where

23 October 2017

We Will Open The Knowledge For You

23 October 2017

Anish Sir 24x7 Learning solution

23 October 2017

It Is Time to join JOB

C Programming

C++ Programming

JAVA Programming

Android Language

Android-logo.png

.Net Programming

net-logo-b55c217213ae49991589ed43d7ed58a7.png

c# Programming

photo_1389636992_quiz_image_temp.png

Asp .Net

asplogo-square.png

PHP Programming

58481791cef1014c0b5e4994.png

Search Your Topic

config
Anish Sir

Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

Website URL: http://toshiyas.in
Monday, 24 July 2017 03:56

Java String concat

The java string concat() method combines specified string at the end of this string. It returns combined string. It is like appending another string.


Signature

The signature of string concat() method is given below:

 
  1. public String concat(String anotherString)  

Parameter

anotherString : another string i.e. to be combined at the end of this string.


Returns

combined string


Java String concat() method example

 
  1. public class ConcatExample{  
  2. public static void main(String args[]){  
  3. String s1="java string";  
  4. s1.concat("is immutable");  
  5. System.out.println(s1);  
  6. s1=s1.concat(" is immutable so assign it explicitly");  
  7. System.out.println(s1);  
  8. }}  
  9. java string
    java string is immutable so assign it explicitly
Monday, 24 July 2017 03:54

Java String compareTo()

The java string compareTo() method compares the given string with current string lexicographically. It returns positive number, negative number or 0.

It compares strings on the basis of Unicode value of each character in the strings.

If first string is lexicographically greater than second string, it returns positive number (difference of character value). If first string is less than second string lexicographically, it returns negative number and if first string is lexicographically equal to second string, it returns 0.

 
  1. if s1 > s2, it returns positive number  
  2. if s1 < s2, it returns negative number  
  3. if s1 == s2, it returns 0  

Signature

 
  1. public int compareTo(String anotherString)  

Parameters

anotherString: represents string that is to be compared with current string


Returns

an integer value


Java String compareTo() method example

 
  1. public class CompareToExample{  
  2. public static void main(String args[]){  
  3. String s1="hello";  
  4. String s2="hello";  
  5. String s3="meklo";  
  6. String s4="hemlo";  
  7. String s5="flag";  
  8. System.out.println(s1.compareTo(s2));//0 because both are equal  
  9. System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"  
  10. System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"  
  11. System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"  
  12. }}  

Output:

0
-5
-1
2

Java String compareTo(): empty string

If you compare string with blank or empty string, it returns length of the string. If second string is empty, result would be positive. If first string is empty, result would be negative.

 
  1. public class CompareToExample2{  
  2. public static void main(String args[]){  
  3. String s1="hello";  
  4. String s2="";  
  5. String s3="me";  
  6. System.out.println(s1.compareTo(s2));  
  7. System.out.println(s2.compareTo(s3));  
  8. }}  

Output:

5
-2
Monday, 24 July 2017 03:53

Java String charAt()

The java string charAt() method returns a char value at the given index number. The index number starts from 0. It returns StringIndexOutOfBoundsException if given index number is greater than this string or negative index number.


Signature

The signature of string charAt() method is given below:

 
  1. public char charAt(int index)  

Parameter

index : index number, starts with 0


Returns

char value


Specified by

CharSequence interface


Throws

StringIndexOutOfBoundsException : if index is negative value or greater than this string length.


Java String charAt() method example

 
  1. public class CharAtExample{  
  2. public static void main(String args[]){  
  3. String name="javatpoint";  
  4. char ch=name.charAt(4);//returns the char value at the 4th index  
  5. System.out.println(ch);  
  6. }}  

Output:

t

StringIndexOutOfBoundsException with charAt()

Let's see the example of charAt() method where we are passing greater index value. In such case, it throws StringIndexOutOfBoundsException at run time.

 
  1. public class CharAtExample{  
  2. public static void main(String args[]){  
  3. String name="javatpoint";  
  4. char ch=name.charAt(10);//returns the char value at the 10th index  
  5. System.out.println(ch);  
  6. }}  

Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 10
at java.lang.String.charAt(String.java:658)
at CharAtExample.main(CharAtExample.java:4)

 

Monday, 24 July 2017 03:41

Java String

In java, string is basically an object that represents sequence of char values. An array of characters works same as java string. For example:

 
  1. char[] ch={'j','a','v','a'};  
  2. String s=new String(ch);  

is same as:

 
  1. String s="java";  

Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The java.lang.String class implements SerializableComparable and CharSequence interfaces.

string implements serializable, comparable, charsequence


CharSequence Interface

The CharSequence interface is used to represent sequence of characters. It is implemented by String, StringBuffer and StringBuilder classes. It means, we can create string in java by using these 3 classes.

charsequence

The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new instance is created. For mutable string, you can use StringBuffer and StringBuilder classes.

We will discuss about immutable string later. Let's first understand what is string in java and how to create the string object.

What is String in java

Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of characters. The java.lang.String class is used to create string object.

How to create String object?

There are two ways to create String object:
  1. By string literal
  2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

 
  1. String s="welcome";  

Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:

 
  1. String s1="Welcome";  
  2. String s2="Welcome";//will not create new instance  

java string literal

In the above example only one object will be created. Firstly JVM will not find any string object with the value "Welcome" in string constant pool, so it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create new object but will return the reference to the same instance.

Note: String objects are stored in a special memory area known as string constant pool.


Why java uses concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).


2) By new keyword

 
  1. String s=new String("Welcome");//creates two objects and one reference variable  

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).


Java String Example

 
  1. public class StringExample{  
  2. public static void main(String args[]){  
  3. String s1="java";//creating string by java string literal  
  4. char ch[]={'s','t','r','i','n','g','s'};  
  5. String s2=new String(ch);//converting char array to string  
  6. String s3=new String("example");//creating java string by new keyword  
  7. System.out.println(s1);  
  8. System.out.println(s2);  
  9. System.out.println(s3);  
  10. }}  
java
strings
example

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

No. Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object... args) returns formatted string
4 static String format(Locale l, String format, Object... args) returns formatted string with given locale
5 String substring(int beginIndex) returns substring for given begin index
6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index
7 boolean contains(CharSequence s) returns true or false after matching the sequence of char value
8 static String join(CharSequence delimiter, CharSequence... elements) returns a joined string
9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string
10 boolean equals(Object another) checks the equality of string with object
11 boolean isEmpty() checks if string is empty
12 String concat(String str) concatinates specified string
13 String replace(char old, char new) replaces all occurrences of specified char value
14 String replace(CharSequence old, CharSequence new) replaces all occurrences of specified CharSequence
15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
16 String[] split(String regex) returns splitted string matching regex
17 String[] split(String regex, int limit) returns splitted string matching regex and limit
18 String intern() returns interned string
19 int indexOf(int ch) returns specified char value index
20 int indexOf(int ch, int fromIndex) returns specified char value index starting with given index
21 int indexOf(String substring) returns specified substring index
22 int indexOf(String substring, int fromIndex) returns specified substring index starting with given index
23 String toLowerCase() returns string in lowercase.
24 String toLowerCase(Locale l) returns string in lowercase using specified locale.
25 String toUpperCase() returns string in uppercase.
26 String toUpperCase(Locale l) returns string in uppercase using specified locale.
27 String trim() removes beginning and ending spaces of this string.
28 static String valueOf(int value) converts given type into string. It is overloaded.

Question:

Write a Program in Java to input a number and check whether it is a Disarium Number or not.

Note: A number will be called DISARIUM if sum of its digits powered with their respective position is equal to the original number.

For example 135 is a DISARIUM
(Workings 11+32+53 = 135, some other DISARIUM are 89, 175, 518 etc)

 

Programming Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* The class Disarium inputs a number and checks whether
* it is a Disarium number or not
* @author : www.anishsir.in
* @Program Type : BlueJ Program - Java
*/
 
import java.io.*;
class Disarium
    {
    public static void main(String[] args)throws IOException
        {
            BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
            System.out.print("Enter a number : ");
            int n = Integer.parseInt(br.readLine());
            int copy = n, d = 0, sum = 0;
            String s = Integer.toString(n); //converting the number into a String
            int len = s.length(); //finding the length of the number i.e. no.of digits
             
            while(copy>0)
            {
                d = copy % 10; //extracting the last digit
                sum = sum + (int)Math.pow(d,len);
                len--;
                copy = copy / 10;
            }
             
            if(sum == n)
                System.out.println(n+" is a Disarium Number.");
            else
                System.out.println(n+" is not a Disarium Number.");
        }
    }

 

Output:

Enter a Number : 135
135 is a Disarium Number.

Enter a Number : 219
219 is not a Disarium Number.

Enter a Number : 89
89 is a Disarium Number.

Question:

Write a program to input a word from the user and remove the duplicate characters present in it.

Example:

INPUT – abcabcabc
OUTPUT – abc

INPUT – javaforschool
OUTPUT – javforschl

INPUT – Mississippi
OUTPUT – Misp

 

Programming Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * The class RemoveDupChar inputs a word and removes duplicate characters
 * @author : www.anishsir.in
 * @Program Type : BlueJ Program - Java
 */
 
import java.io.*;
class RemoveDupChar
{
    public static void main(String args[])throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter any word : ");
        String s = br.readLine();
        int l = s.length();
        char ch;
        String ans="";
         
        for(int i=0; i<l; i++)
        {
            ch = s.charAt(i);
            if(ch!=' ')
                ans = ans + ch;
            s = s.replace(ch,' '); //Replacing all occurrence of the current character by a space
        }
 
       System.out.println("Word after removing duplicate characters : " + ans);
    }
}

 

Output:

Example 1:
Enter any word : Mississippi
Word after removing duplicate characters : Misp

Example 2:
Enter any word : Attitude
Word after removing duplicate characters : Atiude

Question:

Write a Program in Java to input 2 numbers and find their Greatest Common Divisor (GCD).

Note: If the 2 numbers are 54 and 24, then the divisors (factors) of 54 are: 1, 2, 3, 6, 9, 18, 27, 54.

Similarly the divisors (factors) of 24 are: 1, 2, 3, 4, 6, 8, 12, 24.

The numbers that these two lists share in common are the common divisors (factors) of 54 and 24: 1, 2, 3, 6.

The greatest (highest) of these is 6. That is the greatest common divisor or the highest common factor of 54 and 24.

Calculating HCF / GCD by Prime Factorisation Method is long and more time-consuming, and due to these disadvantages new method was evolved by Mathematician namely, Successive Division Method

Under Successive Division Method, HCF / GCD = The Last Divisor of the given numbers .

Following example can guide you How to calculate HCF / GCD by Successive Division Method ?

Example : By using Successive Division Method, find the GCD of 24 & 18 ?

Answer : Steps and the way of finding GCD by Successive Division Method is as :-

Step 1 = Divide the larger number 24 by the smaller number 18. And this division will give remainder 6.
Step 2 = Now, divide 18 (divisor of step 1) with 6 (remainder of step 1)
Step 3 = Division in Step 2 give us remainder 0 (Zero). And The Last Divisor is the GCD of 24 & 18.
Hence, GCD = 6

18 | 24 | 1                
     18
   ______ 
            
      6 | 18 | 3          
          18
        ______
 
           0

 

Programming Code [Method 1]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* The class Gcd inputs two numbers and finds their Gcd
* @author : www.anishsir.in
* @Program Type : BlueJ Program - Java
*/
 
import java.util.*;
class Gcd
    {
        public static void main(String args[])throws Exception
        {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter the First no : ");
            int n1=sc.nextInt();
            System.out.print("Enter the Second no : ");
            int n2=sc.nextInt();
            int r;
             
            while(n2 != 0)
            {
                r = n1 % n2;
                n1 = n2;
                n2 = r;
            }
            System.out.print("GCD = "+n1);
        }
    }

 

Programming Code [Method 2]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* The class Gcd inputs two numbers and finds their Gcd
* @author : www.anishsir.in
* @Program Type : BlueJ Program - Java
*/
 
import java.util.*;
class Gcd
    {
        public static void main(String args[])throws Exception
        {
            Scanner sc = new Scanner(System.in);
            System.out.print("Enter the First no : ");
            int n1=sc.nextInt();
            System.out.print("Enter the Second no : ");
            int n2=sc.nextInt();
             
            while(n1 != n2)
            {
                if(n1 > n2)
                    n1 = n1-n2;
                else
                    n2 = n2-n1;
            }
            System.out.print("GCD = "+n1);
        }
    }

 

Output:

Enter the First no : 54
Enter the Second no : 24
GCD = 6

 

 

Question:

Write a Program in Java to input a number and check whether it is a Harshad Number or Niven Number or not..

Harshad Number : In recreational mathematics, a Harshad number (or Niven number), is an integer (in base 10) that is divisible by the sum of its digits.

Let’s understand the concept of Harshad Number through the following example:

 

  • The number 18 is a Harshad number in base 10, because the sum of the digits 1 and 8 is 9 (1 + 8 = 9), and 18 is divisible by 9 (since 18 % 9 = 0)
  • The number 1729 is a Harshad number in base 10, because the sum of the digits 1 ,7, 2 and 9 is 19 (1 + 7 + 2 + 9 = 19), and 1729 is divisible by 19 (1729 = 19 * 91)
  • The number 19 is not a Harshad number in base 10, because the sum of the digits 1 and 9 is 10 (1 + 9 = 10), and 19 is not divisible by 10 (since 19 % 10 = 9)

The first few Harshad numbers in base 10 are:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, 45, 48, 50, 54, 60, 63, 70, 72, 80, 81, 84, 90, 100, 102, 108, 110, 111, 112, 114, 117, 120, 126, 132, 133, 135, 140, 144, 150, 152, 153, 156, 162, 171, 180, 190, 192, 195, 198, 200 etc.

 

Programming Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* The class HarshadNumber inputs a number and checks if it a Harshad Number or not
* @author : www.anishsir.in
* @Program Type : BlueJ Program - Java
*/
 
import java.util.*;
class HarshadNumber
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
         
        System.out.print("Enter a number : ");
        int n = sc.nextInt();
        int c = n, d, sum = 0;
         
        //finding sum of digits
        while(c>0)
        {
            d = c%10;
            sum = sum + d;
            c = c/10;
        }
         
        if(n%sum == 0)
            System.out.println(n+" is a Harshad Number.");
        else
            System.out.println(n+" is not a Harshad Number.");     
    }
}

 

Output:

Enter a number : 195
195 is a Harshad Number.
 
Enter a number : 194
194 is not a Harshad Number.
 
Enter a number : 190
190 is a Harshad Number.
 
Enter a number : 111
111 is a Harshad Number.

Question:

Write a Program in Java to input a number and check whether it is a Pronic Number or Heteromecic Number or not.

Pronic Number : A pronic number, oblong number, rectangular number or heteromecic number, is a number which is the product of two consecutive integers, that is, n (n + 1).

The first few pronic numbers are:
0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462 … etc.

 

Programming Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* The class HarshadNumber inputs a number and checks if it a Pronic Number or not
* @author : www.anishsir.in
* @Program Type : BlueJ Program - Java
*/
 
import java.util.*;
class PronicNumber
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
         
        System.out.print("Enter a number : ");
        int n = sc.nextInt();
        int flag = 0;
    
        for(int i=0; i<n; i++)
        {
            if(i*(i+1) == n)
            {
                flag = 1;
                break;
            }
        }
         
        if(flag == 1)
            System.out.println(n+" is a Pronic Number.");
        else
            System.out.println(n+" is not a Pronic Number.");     
    }
}

 

Alternate Programming Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* The class HarshadNumber inputs a number and checks if it a Pronic Number or not
* @author : www.anishsir.in
* @Program Type : BlueJ Program - Java
*/
 
import java.util.*;
class PronicNumber
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
         
        System.out.print("Enter a number : ");