Drop Down

Showing posts with label Point to Remember. Show all posts
Showing posts with label Point to Remember. Show all posts

Sunday, January 12, 2020

Different ways to create objects in Java

ways to create objects in Java


1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.
MyObject object = new MyObject();

2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

 3. Using clone()The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject(); 
MyObject object = anotherObject.clone();

4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream ); 
MyObject object = (MyObject) inStream.readObject();
------------------------------------------------------------------------------------------------------------------------------------.

Tuesday, February 5, 2019

Mixed String

Java String toCharArray()
-------------------------
The java string toCharArray() method converts this string into character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.
==========================================
Character.toUpperCase(char ch)
----
char a = 'a';
char upperCase = Character.toUpperCase(a);

===========================================
Character.isLetter('c')
Character.isLowerCase('c')

public class Test {

   public static void main(String args[]) {
      System.out.println(Character.isLetter('c'));
      System.out.println(Character.isLetter('5'));
  System.out.println(Character.isLowerCase('c'));
      System.out.println(Character.isLowerCase('C'));
   }
}

output:-
true
false
true
false
============================================

if(Character.isLetter(charmessage[counter]) &&
 Character.isLowerCase(charmessage[counter]))
{
    charmessage[counter] = Character.toUpperCase(charmessage[counter]);
}
================
 String str = "This is what is this world in world";
  String[] strarray = str.split(" ");
=============================================
Arrays.sort(ch1);
Arrays.sort(ch2);
if(Arrays.equals(ch1,ch2))
=============================================
public StringBuffer deleteCharAt(int index)
----
StringBuffer buff = new StringBuffer("Java lang package");
      System.out.println("buffer = " + buff);

      // deleting character from index 4 to index 9
      buff.delete(4, 9);
      System.out.println("After deletion = " + buff);

      buff = new StringBuffer("xxxx);
      System.out.println("buffer = " + buff);
   
      // deleting character at index 2
      buff.deleteCharAt(2);
      System.out.println("After deletion = " + buff);
==============================================

// create StringBuffer object
        StringBuffer sb = new StringBuffer();

        // 1. append some string values
        sb.append("Google is top search-engine. ");

        // 2. again, append some more string values
        sb.append("To get latest topics on Core Java.");

        // 3. third time, append String-3 and
        // add newline '\n'
        sb.append("\nAnd it can search contents in real-time.");

        // convert StringBuffer to String using toString() method
        String str = sb.toString();

===============================================
--Covert char to String
------------------------
char a ='t';
String s = ""+a;
String ss = Character.toString(a);
String sss = String.valueOf(a);
================================================
copyOf()
--------
Syntax:

 copyOf(int[] original, int newLength)
----eg.
public static void main(String args[])
    {
        // initializing an array original
        int[] org = new int[] {1, 2 ,3};

        System.out.println("Original Array");
        for (int i = 0; i < org.length; i++)
            System.out.print(org[i] + " ");

        // copying array org to copy
        int[] copy = Arrays.copyOf(org, 5);

        // Changing some elements of copy
        copy[3] = 11;
        copy[4] = 55;

        System.out.println("\nNew array copy after modifications:");
        for (int i = 0; i < copy.length; i++)
            System.out.print(copy[i] + " ");
    }


-----------------------------------------------------------------------------------------
--System.arraycopy()
--
Syntax :

public static void
arraycopy(Object source_arr, int sourcePos,Object dest_arr, int destPos, int len)
---eg.
 public static void main(String[] args)
    {
        int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
        int d[] = { 15, 25, 35, 45, 55, 65, 75, 85, 95, 105};

        int source_arr[], sourcePos, dest_arr[], destPos, len;
        source_arr = s;
        sourcePos = 3;
        dest_arr = d;
        destPos = 5;
        len = 4;

        // Print elements of source
        System.out.print("source_array : ");
        for (int i = 0; i < s.length; i++)
            System.out.print(s[i] + " ");
        System.out.println("");

        System.out.println("sourcePos : " + sourcePos);
       
        // Print elements of source
        System.out.print("dest_array : ");
        for (int i = 0; i < d.length; i++)
            System.out.print(d[i] + " ");
        System.out.println("");
       
        System.out.println("destPos : " + destPos);
       
        System.out.println("len : " + len);
       
        // Use of arraycopy() method
        System.arraycopy(source_arr, sourcePos, dest_arr,
                                            destPos, len);
       
        // Print elements of destination after
        System.out.print("final dest_array : ");
        for (int i = 0; i < d.length; i++)
            System.out.print(d[i] + " ");
    }
-----------------------------------------------------------------------------------------
Object[] obj = list.toArray();//ArrayList to Array
for copying arraylist to array
---------------------------
---------------------------
1.List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));  //copy
2.List<Integer> list2 = Arrays.asList(ia);

import java.util.*;

public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {

        try {

            // creating Arrays of String type
            String a[] = new String[] { "A", "B", "C", "D" };

            // getting the list view of Array
            List<String> list = Arrays.asList(a);

            // printing the list
            System.out.println("The list is: " + list);
        }

        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
Output:
The list is: [A, B, C, D]
----------------------------------
=========================================================

----------------------------------string to char[]
String s1="hello";
char[] ch1 = s1.toCharArray();
----------------------------------to sort char []
Arrays.sort(ch1);
----------------------------------
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);
//concatenating string with 10
//o/p :- 3010
----------------------------------
String s1 = "java";
String s2 = "ajav";
StringBuffer sb = new StringBuffer(s2);
int index = sb.indexOf(String.valueOf(c));
sb.deleteCharAt(index);
-------------------------------------
String s2 ="avaj";
StringBuffer sb = new StringBuffer(s2);
int index = sb.indexOf(String.valueOf(c)); --or
int index = sb.indexOf(Character.toString(c));
sb.deleteCharAt(index);
---------------------------------------
----------- char array to a string in Java?

class CharArrayToString
{
   public static void main(String args[])
   {
      // Method 1: Using String object
      char[] ch = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'};
      String str = new String(ch);
      System.out.println(str);

      // Method 2: Using valueOf method
      String str2 = String.valueOf(ch);
      System.out.println(str2);
   }
}
---------------------------------------

=================================================
package comparator.Emp;
//When we are not allowed to change Class Employee code (i.e we can't implement Comparable)
//We use comparator Interface.
public class Employee
{
 int empid;
 String name;
 int deptid;
 public Employee(int empid, String name, int deptid)
 {
  super();
  this.empid = empid;
  this.name = name;
  this.deptid = deptid;
 }
 /*@Override
 public String toString() {
  return "Empid=" + empid + ", Name=" + name + ", Deptid=" + deptid;
 }*/


}
==========================================
package comparator.Emp;
import java.util.*;
//Sort the Employeee Class using empid -- Use Comparator
public class Emp_Runner {

 public static void main(String[] args)
 {
  Employee emp1  = new Employee(111,"Amit",549);
  Employee emp2  = new Employee(674,"Dinesh",549);
  Employee emp3  = new Employee(352,"Manohar",667);
  Employee emp4  = new Employee(642,"Dilip",889);
  Employee emp5  = new Employee(133,"Govind",667);

  List list = new ArrayList();
  list.add(emp1);
  list.add(emp2);
  list.add(emp3);
  list.add(emp4);
  list.add(emp5);
 
  Comparator comp = new Emp_Comp(); //Comparator is Interface so we can't instanciate it.

  Collections.sort(list,new Emp_Comp());  //call to compare() .... from here

  Iterator itr = list.iterator();
  while(itr.hasNext())
  {
   Employee emp = (Employee) itr.next();
   System.out.println("Empid=" + emp.empid + ", Name=" + emp.name + ", Deptid=" + emp.deptid);
 
  }



 }



}
==========================================
package comparator.Emp;

import java.util.Comparator;

public class Emp_Comp implements Comparator<Employee>
{

 @Override
 public int compare(Employee e1, Employee e2)
 {

  if(e1.empid > e2.empid)
  {
   return 1;
  }
  else return
    -1;

 }

}
============================================
============================================

Sunday, February 3, 2019

CharToString

public class CharToStringExample {

       public static void main(String args[]) {
              char ch = 'U';

              // char to string using Character class
              String charToString = Character.toString(ch);
              System.out.println("Converting Char to String using Character class: " + charToString);

              // char to String using String concatenation
              String str = "" + ch;
              System.out.println("Converting Char to String using String concatenation: " + str);

              // char to String using anonymous array
              String fromChar = new String(new char[] { ch });
              System.out.println("Converting Char to String using anonymous array: " + fromChar);

              // char to String using String valueOf
              String valueOfchar = String.valueOf(ch);
              System.out.println("Converting Char to String using String valueOf: " + valueOfchar);

       }

}

Output:
Converting Char to String using Character class: U
Converting Char to String using String concatenation: U
Converting Char to String using anonymous array: U
Converting Char to String using String valueOf: U


Read more: https://javarevisited.blogspot.com/2012/02/how-to-convert-char-to-string-in-java.html#ixzz5eT208uoa

Thursday, January 17, 2019

PICS





Top 10 Methods for Java Arrays

0. Decalre an array
String[] aArray = new String[5];
String[] bArray = {"a","b","c", "d", "e"};
String[] cArray = new String[]{"a","b","c","d","e"};

1. Print an array in Java
int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);
 
// print directly will print reference value
System.out.println(intArray);
// [I@7150bd4d
 
System.out.println(intArrayString);
// [1, 2, 3, 4, 5]
2. Create ArrayList from array
String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
System.out.println(arrayList);
// [a, b, c, d, e]
3. Check if an array contains a certain value
String[] stringArray = { "a", "b", "c", "d", "e" };
boolean b = Arrays.asList(stringArray).contains("a");
System.out.println(b);
// true
4. Concatenate two arrays
int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
// Apache Commons Lang library
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
5. Declare array inline
method(new String[]{"a", "b", "c", "d", "e"});
6. Joins the elements of the provided array into a single String
// containing the provided list of elements
// Apache common lang
String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
System.out.println(j);
// a, b, c
7. Covnert ArrayList to Array
     Arrays.asList
String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
String[] stringArr = new String[arrayList.size()];
arrayList.toArray(stringArr);
for (String s : stringArr)
System.out.println(s);
8. Convert Array to Set
Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
System.out.println(set);
//[d, e, b, c, a]
9. Reverse an array
int[] intArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(intArray);
System.out.println(Arrays.toString(intArray));
//[5, 4, 3, 2, 1]
10. Remove element of an array
int[] intArray = { 1, 2, 3, 4, 5 };
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
System.out.println(Arrays.toString(removed));
One more – convert int to byte array
byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
 
for (byte t : bytes) {
System.out.format("0x%x ", t);
}
===================================================

Converting List to Array

-----------------------------------------------------
1)The list interface comes with the toArray() method that returns an array containing all of the elements in this list in proper sequence (from the first to last element). 


Converting List to Array

Wednesday, January 16, 2019

Important Methods

copyOf()
--------
Syntax:

 copyOf(int[] original, int newLength) 
----eg.
public static void main(String args[]) 
    { 
        // initializing an array original 
        int[] org = new int[] {1, 2 ,3}; 
  
        System.out.println("Original Array"); 
        for (int i = 0; i < org.length; i++) 
            System.out.print(org[i] + " "); 
  
        // copying array org to copy 
        int[] copy = Arrays.copyOf(org, 5); 
  
        // Changing some elements of copy 
        copy[3] = 11; 
        copy[4] = 55; 
  
        System.out.println("\nNew array copy after modifications:"); 
        for (int i = 0; i < copy.length; i++) 
            System.out.print(copy[i] + " "); 
    } 
-----------------------------------------------------------------------------------------
--System.arraycopy()
--
Syntax :

public static void 
arraycopy(Object source_arr, int sourcePos,Object dest_arr, int destPos, int len)
---eg.
 public static void main(String[] args) 
    { 
        int s[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; 
        int d[] = { 15, 25, 35, 45, 55, 65, 75, 85, 95, 105}; 
  
        int source_arr[], sourcePos, dest_arr[], destPos, len; 
        source_arr = s; 
        sourcePos = 3; 
        dest_arr = d; 
        destPos = 5; 
        len = 4; 
  
        // Print elements of source 
        System.out.print("source_array : "); 
        for (int i = 0; i < s.length; i++) 
            System.out.print(s[i] + " "); 
        System.out.println(""); 
  
        System.out.println("sourcePos : " + sourcePos); 
         
        // Print elements of source 
        System.out.print("dest_array : "); 
        for (int i = 0; i < d.length; i++) 
            System.out.print(d[i] + " "); 
        System.out.println(""); 
         
        System.out.println("destPos : " + destPos); 
         
        System.out.println("len : " + len); 
         
        // Use of arraycopy() method 
        System.arraycopy(source_arr, sourcePos, dest_arr,  
                                            destPos, len); 
         
        // Print elements of destination after 
        System.out.print("final dest_array : "); 
        for (int i = 0; i < d.length; i++) 
            System.out.print(d[i] + " "); 
    } 
-----------------------------------------------------------------------------------------
Object[] obj = list.toArray();//ArrayList to Array 
for copying arraylist to array
---------------------------
---------------------------
1.List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia));  //copy
2.List<Integer> list2 = Arrays.asList(ia);

import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // creating Arrays of String type 
            String a[] = new String[] { "A", "B", "C", "D" }; 
  
            // getting the list view of Array 
            List<String> list = Arrays.asList(a); 
  
            // printing the list 
            System.out.println("The list is: " + list); 
        } 
  
        catch (NullPointerException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
Output:
The list is: [A, B, C, D]
----------------------------------

Java 8 Notes Pics