Tuesday, 26 December 2017

How to Convert String to int in Java

In Java we can convert string to integer with Integer.parseInt() function.

Syntax:
int in = Integer.parseInt(str); 

Example:


package com.tutorial4u;

public class StringToInt {
       public static void main(String[] args) {
             String str = "4";
              int in = Integer.parseInt(str);   
              System.out.println(in);
       }


}

Output:  4

Note:

In order to use Integer.parseInt() method, we should pass string numbers only. If input string contains other than numbers parseInt() function will throw java.lang.NumberFormatException.


Example:
package com.tutorial4u;

public class StringToInt {
       public static void main(String[] args) {
             String str = "Tutorial4u";
              int in = Integer.parseInt(str);   
              System.out.println(in);
       }


}

Output: 


Exception in thread "main" java.lang.NumberFormatException: For input string: "Tutorial4u"

at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.tutorial4u.StringToInt.main(StringToInt.java:6)

How to Convert String Array to List in Java

In java we have inbuilt function to convert String array to List.


Syntax :-

   Arrays.asList("Input string array");


Java String Array to List Example:

package com.tutorial4u;

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

public class ArrayToList {
       public static void main(String[] args) {
             String[] str = {"Tutorial4u","Ashish"};
             List<String> list = Arrays.asList(str);
             System.out.println(list);
       }

}


Output:  [Tutorial4u, Ashish]

Sunday, 10 September 2017

What is an immutable class?


Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class .

Ques: How to create an immutable class?



To create an immutable class following steps should be followed:


1.Create a final class so that it cannot be inherited.
2.Make the member variable private so that fields cannot be accessed outside class. 
3. Make the member variable final so that fields can be assigned only once. 
4.Set the values of properties using constructor only.
5.Provide only getter method().
6.Do not provide any setter() for these filed.


package com.tutorial4u;

final class Student {
  private final String name;
  private final int regNo;
  public Student(String name, int regNo) {
         this.name = name;
         this.regNo = regNo;
  }
  public String getName() {
         return name;
  }
  public int getRegNo() {
         return regNo;
  }
}


Ques: Which classes in java are immutable?


All wrapper classes in java.lang are immutable – String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger

Ques: What are the advantages of immutability?

• Immutable objects are automatically thread-safe, the overhead caused due to use of synchronization is avoided.

• Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.

• The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.

• The best use of the immutable objects is as the keys of a map. .

Ques: What is Advantages of using Immutable class ?

• Thread safe - Immutable classes are thread safe, they will never create race condition.

• Key in HashMap - Immutable classes are can be used as key in Map (HashMap etc.)

• HashCode is cached - JVM caches the HashCode of Immutable classes used in application. JVM need not to calculate hashcode again. Hence, performance of application is improved significantly.

• If Immutable class throws Exception - If Immutable class throws Exception, they are never left in undesirable state.

Ques: Benefits of Immutable Classes in Java.



As I said earlier Immutable classes offers several benefits, here are few to mention:

1) Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.

2) Immutable object simplifies development, because its easier to share between multiple threads without external synchronization.

3) Immutable object boost performance of Java application by reducing synchronization in code.

4) Another important benefit of Immutable objects is reusability, you can cache Immutable object and reuse them, much like String literals and Integers. You can use static factory methods to provide methods like valueOf(), which can return an existing Immutable object from cache, instead of creating a new one. .

Saturday, 10 June 2017

How To Remove Duplicate Value from an Array?


package com.tutorial4u;

public class RemoveDuplicate {
       public static void main(String[] args) {
              int array[] = {1,2,2,3,4,4,5,6,6,7};
              for(int i=0;i<array.length;i++){
                     for(int j=i+1;j<array.length;j++){
                            if(array[i]==array[j]){
                                  i++;
                                j=i+1;
                            }
                     }
                     System.out.print(" "+array[i]);
              }
       }


}

Output:
     
 1 2 3 4 5 6 7

Friday, 9 June 2017

Write a Java program if input array is like {10,20,30,40} then output should be like {90,80,70,60}

Ques: Write a Java program if input array is like {10,20,30,40} then output should be like {90,80,70,60}.



package com.tutorial4u;

import java.util.Scanner;

public class ArrayDemo {
       public static void main(String[] args) {
              Scanner sc = new Scanner(System.in);
              int sum=0;
              System.out.println("Enter size of an array");
              int num = sc.nextInt();
              System.out.println("Enter Element of an array");
              int[] a = new int[num];
              int[] b = new int[num];
              for(int i =0;i<num;i++){
                     a[i] = sc.nextInt();
              }
              for(int i=0;i<num;i++){
                     sum+= a[i];
              }
              for(int i=0;i<num;i++){
                     b[i]= sum-a[i];
              }
              System.out.println("Output is:");
              for(int number:b){
                     System.out.println(number);
              }
       }

}



Output :

Enter size of an array
4
Enter Element of an array
10
20
30
40
Output is:
90
80
70

60

Wednesday, 7 June 2017

Servlet Directory Structure

Servlet Directory Structure: 

For creating web application we should follow standard directory structure provided by sun Micro System. Sun Micro System has given directory structure to make a web application server independent.
Sun Micro System has given this directory structure to make a web application as server independent. A web application principle is write once deploy anywhere (WODA).

According to directory structure : 


  • An application contain root folder with any name.
  • Under root folder a sub folder is required with a name WEB-INF.
  • Under WEB-INF two sub folder are required classes and lib.
  • All jar files placed inside lib folder.
  • Under root folder src folder are place for .java files
  • Under root folder or under WEB-INF any other folders can exits.
  • All image, html, .js, jsp, etc files are placed inside root folder
  • All .class files placed inside classes folder.

Thursday, 1 June 2017

Encryption And Decryption Using AES Algorithm

1.AESEncryption.java


package com.tutorial4u;

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

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

/**
 * This example program shows how AES encryption and decryption can be done in
 * Java. Please note that secret key and encrypted text is unreadable binary and
 * hence in the following program we display it in hexadecimal format of the
 * underlying bytes.
 *
 * @author ashish
 */
public class AESEncryption {
       /**
        * gets the AES encryption key. In your actual programs, this should be
        * safely stored.
        *
        * @return
        * @throws Exception
        */
       public static SecretKey getSecretEncryptionKey() throws Exception {

             Date today = new Date();
             SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");

             // Key is last 8 digits of JFS CIS_NUMBER (i.e. U65923KA2006PTC040028) +
             // DDMMYYYY

             String stringKey = "TC040028" + dateFormat.format(today);

             byte[] keyBytes = stringKey.getBytes("UTF-8");

             SecretKey secretKey = new SecretKeySpec(keyBytes, 0, keyBytes.length, "AES");

             return secretKey;
       }

       /**
        * Encrypts plainText in AES using the secret key
        *
        * @param plainText
        * @return
        * @throws Exception
        */
       public static byte[] encryptText(String plainText) throws Exception {
             // AES defaults to AES/ECB/PKCS5Padding in Java 7
             Cipher aesCipher = Cipher.getInstance("AES");
             aesCipher.init(Cipher.ENCRYPT_MODE, getSecretEncryptionKey());

             byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
             return byteCipherText;
       }

       /**
        * Decrypts encrypted byte array using the key used for encryption.
        *
        * @param byteCipherText
        * @return
        * @throws Exception
        */
       public static String decryptText(byte[] byteCipherText) throws Exception {
             // AES defaults to AES/ECB/PKCS5Padding in Java 7
             Cipher aesCipher = Cipher.getInstance("AES");
             aesCipher.init(Cipher.DECRYPT_MODE, getSecretEncryptionKey());
             byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
             return new String(bytePlainText);
       }

       /**
        * Convert a binary byte array into readable hex form
        *
        * @param hash
        * @return
        */
       public static String bytesToHex(byte[] hash) {
             return DatatypeConverter.printHexBinary(hash);
       }

       /**
        * Convert a readable hex to String
        *
        * @param hash
        * @return
        */
       public static byte[] hexToBytes(String hash) {
             return DatatypeConverter.parseHexBinary(hash);
       }

}



2.AESTest.java



package com.tutorial4u;

public class AESTest {

       public AESTest() {
             try {
                    String originalText = "password@#";
                    String encryptedText = AESEncryption.bytesToHex(AESEncryption.encryptText(originalText));
                    String decryptedText = AESEncryption.decryptText(AESEncryption.hexToBytes(encryptedText));

                    System.out.println("Original Text : " + originalText);
                    System.out.println("Encrypted Text (Hex Form) : " + encryptedText);
                    System.out.println("Decrypted Text : " + decryptedText);
             } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
             }
       }
       public static void main(String[] args) {
             new AESTest();
       }

}

No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...