Way To Java
Java , Android, C , C++, J2EE, Data Structure, Python, HTML,CSS, JavaScript, MS Office Enhance your skills in Java and Android.
Set the AUTO_INCREMENT value MySQL
--------------------------------------------------------
- By default MySQL will generate the value of AUTO_INCREMENT column value to 1.
- To start with an AUTO_INCREMENT value other than 1, set that value with CREATE TABLE or ALTER TABLE.
- For New Table
mysql> CREATE TABLE student
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 1000,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL
);
- For Existing Table-
mysql> ALTER TABLE tbl AUTO_INCREMENT = 1000;
Convert LocalDateTime object to Date object
----------------------------------------------------------------
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
Date output = Date.from(zdt.toInstant());
Note -
1. Import Date class form the package -
java.util.Date not java.sql.Date
2. LocalDateTime class is present in the java.time package.
Converting JSON to Java Object and Java object to JSON.
-----------------------------------------------------------------------------
Complete example.
Employee.java
--------------------
import org.codehaus.jackson.map.ObjectMapper;
import java.io.Serializable;
class Employee implements Serializable{
private int id;
private String name;
private int salary;
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getSalary(){
return salary;
}
public void setSalary(int salary){
this.salary = salary;
}
}
Utils.java
-------------
class Utils{
private static ObjectMapper mapper = null;
static{
mapper = new ObjectMapper();
}
public static String javaObjectToJSON(Object obj){
String jsonObject = "";
try{
jsonObject = mapper.writeValueAsString(obj);
}catch(Exception e){}
return jsonObject;
}
public static Object jsonToJavaObject(String jsonObject, Class cls){
Object obj = "";
try{
obj = mapper.readValue(jsonObject, cls);
}catch(Exception e){}
return obj;
}
}
Test.java
------------
class Test{
public static void main(String[]args){
Employee emp = new Employee();
emp.setId(1002);
emp.setName("Mukesh Kumar");
emp.setSalary(20000);
String str = Utils.javaObjectToJSON(emp);
System.out.println(str);
System.out.println("------ JSON to Java Object -------");
Object ob1 = Utils.jsonToJavaObject(str, Employee.class);
Employee emp1 = (Employee)ob1;
System.out.println("ID : "+ emp1.getId()+"\nNAME : "+emp1.getName()+"\nSALARY : "+emp1.getSalary());
}
}
Output -
{"id":1002,"name":"Mukesh Kumar","salary":20000}
------ JSON to Java Object -------
ID : 1002
NAME : Mukesh Kumar
SALARY : 20000
Convert Java object to JSON
---------------------------------------
- Jackson API is used to convert java object to JSON.
- Set class path of jackson.jar file.
- Jackson API provides a class ObjectMapper, that having method writeValueAsString().
- String writeValueAsString(Object obj)
- This method takes object as argument and returns String representation of JSON
- Remember java class must implements Serializable interface whose object we want to convert into JSON.
- Jackson API can access only those data members that are public, but it is not possible to make each and every instance member as public. Hence create getter() and setter() of that class.
--------------
Example :
--------------
Employee.java
--------------------
import org.codehaus.jackson.map.ObjectMapper;
import java.io.Serializable;
class Employee implements Serializable{
private int id;
private String name;
private int salary;
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getSalary(){
return salary;
}
public void setSalary(int salary){
this.salary = salary;
}
}
Test.java
------------
class Test{
public static void main(String[]args){
Employee emp = new Employee();
emp.setId(1002);
emp.setName("Mukesh Kumar");
emp.setSalary(20000);
try{
ObjectMapper mapper = new ObjectMapper();
String jsonObject = mapper.writeValueAsString(emp);
System.out.println("Employee Object In JSON Form : "+ jsonObject);
}catch(Exception e){
System.out.println(e);
}
}
}
Output -
-----------
Employee Object In JSON Form : {"id":1002,"name":"Mukesh Kumar","salary":20000}
Java program to read JSON file.
------------------------------------------
Employee.json
--------------------
{
"empno":1001,
"empname": "Vikash Kumar",
"salary": 20000
}
ReadJSON.java
--------------------
import org.json.simple.parser.JSONParser;
import org.json.simple.JSONObject;
import java.io.FileReader;
class ReadJSON{
public static void main(String[]args){
JSONParser parser = new JSONParser();
try{
Object obj = parser.parse(new FileReader("Employee.json"));
JSONObject jObj = (JSONObject)obj;
long empNo = (Long)jObj.get("empno");
String empName = (String)jObj.get("empname");
long salary = (Long)jObj.get("salary");
System.out.println("EMP NO : "+ empNo);
System.out.println("EMP NAME : "+ empName);
System.out.println("SALARY : "+ salary);
}catch(Exception e){
System.out.println(e);
}
}
}
Note - To run this example, first download "json-simple-1.1.1.jar"
file and set classpath of this jar file.
Android - Generate Hash Code (Key Hashes) to enable Login with Facebook feature in Android application -
-Create a method in MainActivity.java. Call getHashKey() method and print output to the Log.d(). This will show the Hash Key for development environment.
----------------------------------------------------------------------------
public String getHashKey(){
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(this.getPackageName(), PackageManager.GET_SIGNATURES);
for(Signature signature : packageInfo.signatures){
MessageDigest messageDigest = MessageDigest.getInstance("SHA");
messageDigest.update(signature.toByteArray());
return Base64.encodeToString(messageDigest.digest(), Base64.DEFAULT);
}
} catch (PackageManager.NameNotFoundException e) {
return "Package Not Found !!";
} catch (NoSuchAlgorithmException e) {
return "Algorithm Not Found";
}
return "SHA-1 : Key Generation Error";
}
Important points about Generics
-------------------------------------------
Generics concept is only applicable at compile time, not at run time.
At the time of compilation, as last step generics syntax will be removed.
Hence for the JVM, generics syntax will not be available.
Example :
-------------
import java.util.ArrayList;
class My{
public static void main(String[]args){
ArrayList al = new ArrayList();
al.add(10);
al.add(20.5);
al.add(true);
System.out.println(al);
}
}
Output - [10, 20.5, true]
Note -
Since JVM is unknown to the generics template.
Hence all those declarations are valid.
For these ArrayList object we can add any type of objects.
All these declarations are exactly same.
----------------------------------------------------
ArrayList al = new ArrayList();
ArrayList al = new ArrayList();
ArrayList al = new ArrayList();
ArrayList al = new ArrayList();
ArrayList al = new ArrayList();
static variables do not participate in Serialization. Hence declaring static variable as transient there is no use.
Declaring final variables as transient there is no use at all.
i.e. Declaring static and final variable as transient there is no impact on serialization.
Serialization in Java
---------------------------
The process of saving the state of an object to a file is known as Serialization.
OR
The process of converting an object from normal java supported form to file supported form or network supported form. This conversion process is called Serialization.
Example :
import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
class Student implements Serializable{
int rollNo;
int age;
Student(int rollNo, int age){
this.rollNo = rollNo;
this.age = age;
}
}
class SerializationDemo{
public static void main(String[]args){
Student st1 = new Student(1001, 15);
try{
FileOutputStream fout = new FileOutputStream("student.txt");
ObjectOutputStream os = new ObjectOutputStream(fout);
os.writeObject(st1);
}catch(IOException e){}
System.out.println("Object Written Successfully !!");
}
}
HashSet and LinkedHashSet class
-----------------------------------------------
Both the classes are present in java.util package.
HashSet is the implementation class for Set interface.
LinkedHashSet is the child class of HashSet class.
Insertion order is not preserved in HashSet, but insertion order is preserved in LinkedHashSet.
Data structure for HashSet is hash table, but data structure for LinkedHashSet is linked list + hash table.
HashSet class is introduced in 1.2 version of Java, but LinkedHashSet class is introduced in 1.4 version of Java.
Note -
LinkedHashSet is used to develop cache based applications.
import java.util.ArrayList;
import java.util.Iterator;
class IteratorTest{
public static void main(String[]args){
ArrayList al = new ArrayList();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
al.add(50);
System.out.println(al);
System.out.println("--------------------");
Iterator itr = al.iterator();
while(itr.hasNext()){
Integer i = (Integer)itr.next();
System.out.println(i);
}
}
}
Enumeration interface in java
---------------------------------------
Enumeration interface is present in java.util package.
Enumeration object is created by elements() method of Vector class.
Vector v = new Vector();
Enumeration e = v.elements();
StringTokenizer is the only implementation class for Enumeration interface.
There are only two methods present in Enumeration interface-
1. boolean hasMoreElements()
2. public Object nextElement()
Example :
-------------
import java.util.Vector;
import java.util.Enumeration;
class EnumerationDemo{
public static void main(String[]args){
Vector v = new Vector();
v.addElement("A");
v.addElement("B");
v.addElement("C");
v.addElement("D");
v.addElement("E");
System.out.println(v);
System.out.println("------------------------------");
Enumeration e = v.elements();
while(e.hasMoreElements()){
String s = e.nextElement().toString();
System.out.println(s);
}
}
}
Click here to claim your Sponsored Listing.
Category
Website
Address
Noida