Skip to main content

Posts

Showing posts with the label Core Java

Getting all the method and variable name from class object using reflection in java

  The java.lang.Class have some useful methods for getting information about class at run time. In this example I am going to get the all field name and variable name present in particular class using reflection. import java.lang.reflect.Field; import java.lang.reflect.Method; class TestReflection {       public int field1 ;       public int field2 ;             public void addField() {             System. out .println( "Addition of two fields: " + ( field1 + field2 ));       } } public class ReflectionDemo {       public static void main(String[] args) {             try {                 ...

Copying an array to another array using System.arraycopy() method

  The method System.arraycopy() present in System class is used for copying one array into another array.   Parameters: System.arraycopy(sourceArray,sourceArrayStartPos,destArray,destArrayStartPos,numberOfElements) Example. public class CopyArray {     public static void main(String[] args) {         try{             int array1[] = {1,3,4,5,6,7,8};             int array2[] = new int[7];             System.arraycopy(array1, 0, array2, 0, 7);             for(int i=0;i<array2.length;i++) {                 System.out.println(array2[i]);             }         }         catch (Exc...

Java code for opening installed application of the system

  The method exec() present in java.lang.Runtime class is used for opening application that are installed in your system. See the below example. public class ExecDemo {   public static void main(String args[]) {     try{ Runtime.getRuntime().exec("notepad.exe ExecDemo.java");     }     catch(Exception e) { e.printStackTrace();     }   } } Here the " notepad.exe " refer the name of the exe name and "ExecDemo.java" refer the file name. The file present in some other directory then you need to give the full path of the file.

Methods for getting currently running JVM memory details

  The Runtime class have lot of useful function for getting information about JVM. In this example I am going get the memory details of currently running JVM. See the below example. public class JvmMemoryDemo {   public static void main(String args[]) {     try{ System.out.println("Maximum amount of memory that JVM will attempt to use: " +   Runtime.getRuntime().maxMemory() + " bytes."); System.out.println("Total amount of memory used by JVM: " + Runtime.getRuntime().totalMemory() + " bytes."); System.out.println("Total amount free memory available in JVM: " + Runtime.getRuntime().freeMemory() + " bytes.");     }     catch(Exception e) { e.printStackTrace();     }   } }   The Runtime.getRuntime().maxMemory()  method return the maximum memory that JVM can able to use in bytes.   The  Runtime.getRuntime().totalMemory()  method returns the memory that JVM currently used in byt...

Terminating currently running JVM

  You can able to kill the JVM using Runtime.getRuntime().exit() method. Yes, the System.exit() method also used for terminating current JVM. The System.exit() method is equivalent to Runtime.getRuntime().exit() method. For better understanding try with following example. public class KillJVM {   public static void main(String args[]) {     try{ System.out.println("Divide by zero: " + (1/0));     }     catch(Exception e) { System.out.println("Error details: " + e.getMessage()); Runtime.getRuntime().exit(1);     }   } }

Comparing two java class objects using equals() method

  The equals() method present in Object class is used for comparing two objects are pointed out the same memory or not. See the below example. public class EqualsDemo { public static void main(String[] args) { EqualsDemo obj1 = new EqualsDemo(); EqualsDemo obj2 = new EqualsDemo();   // The obj3 just refer the obj1 memory EqualsDemo obj3 = obj1; if(obj1.equals(obj2)) { System.out.println("The object1 and object2 are equals"); } else{ System.out.println("The object1 and object2 are not equals"); } if(obj1.equals(obj3)) { System.out.println("The object1 and object3 are equals"); } else{ System.out.println("The object1 and object3 are not equals"); } } }  In this example I have created the two objects (obj1, obj2) for class EqualsDemo. The obj3 is just pointed out the obj1 memory. Finally I compared the object1 and object2 as well as object1 and object3. The result should be like this. ...

Creating Copy of the Existing Object in Java Using Clone Method

  In Java, The "Object" class is the root class for all java classes, It means by default all the java classes inherit the Object class. The Object class have some useful methods for performing operation on the class object like clone(), getClass(), equals(), toString(), wait(), etc..,   The clone() methods is used for creating copy of the existing object. It's means it allocated the new memory for object with values and methods present in which object you are going to copy. For performing this clone() operation you have to implement the Cloneable interface and you have to override the clone() method. See the below example. public class CloneDemo implements Cloneable { public int testValue; public CloneDemo(int value) { this.testValue = value; } //Override the clone() method  protected Object clone() { Object newObject = null; try{ newObject = super.clone(); } catch(CloneNotSupportedException e){ e.printStackTrace...

Converting list into set in java

import java.util.List; import java.util.Set; import java.util.ArrayList; import java.util.HashSet; public class list2Set{  public static void main(String args[]) {    try{        // Creating one sample list        List sampleList=new ArrayList();        // Adding some element into list        sampleList.add("One");        sampleList.add("Two");        sampleList.add("Three");        sampleList.add("One");       // Converting list in set. During this conversion all the duplicate elements are removed.       Set mySet=new HashSet(sampleList);       System.out.println(mySet);    }   catch(Exception e){     e.printStackTrace();    } ...

Converting queue into list in java

import java.util.List; import java.util.Queue; import java.util.LinkedList; import java.util.ArrayList; public class queue2List {   public static void main(String args[])   {     try{           //Creating queue           Queue queue1=new LinkedList();           //Adding some elements into queue           queue1.add("One");           queue1.add("Two");           queue1.add("Three");           //Converting queue into list            List list1=new ArrayList( queue1 );            System.out.println(list1);      ...

Java code for creating menu.

import java.awt.*; import java.awt.event.*; import javax.swing.*; import static java.awt.event.InputEvent.CTRL_DOWN_MASK; public class sampleMenu extends JFrame implements ActionListener { private JMenuBar menuBar; private JMenu File,Edit; private JMenuItem nw,openFile,clse; private JMenuItem cut,copy,paste; public sampleMenu(){ super("Sample Menu!"); //Creating Menu bar menuBar=new JMenuBar(); //Creating File Menu... File=new JMenu("File"); //Creating shortcut for file.... File.setMnemonic('f'); //Creating sub menu related to File.... nw=new JMenuItem("New"); //Adding short cut for file new nw.setAccelerator(KeyStroke.getKeyStroke('N',CTRL_DOWN_MASK)); nw.addActionListener(this); openFile=new JMenuItem("Open File"); //Adding short cut for file open openFile.setAccelerator(KeyStroke.getKeyStroke('O',CTRL_DOWN_MASK)); openFile.addActionListener(this); clse=n...

Java code for creating buttons and adding some action for buttons.

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class mainWindow extends JFrame implements ActionListener{ private JButton Button1; private JButton Button2; public mainWindow(){ //Set the name of window.... super("Window Name"); //Getting container handle Container container=getContentPane(); //Adding layout .... container.setLayout(null); //Set the background color of the window... container.setBackground(new Color(111,143,170)); //Creating first button..... Button1=new JButton("Button1"); //Set the position of button1..... Button1.setBounds(new Rectangle(10,30,80,30)); //Adding action listener for button1.. Button1.addActionListener(this); //Add the button1 to window.... container.add(Button1); Button2=new JButton("Button2"); Button2.setBounds(new Rectangle(100,30,80,30)); Button2.addActionListener(this); container.add(Button2); } //Adding action for button ...

Getting current screen resolution using java

import java.awt.*; public class screenDim { public static void main(String[] args) { try{ Toolkit newTollKit=Toolkit.getDefaultToolkit(); Dimension screenDim=newTollKit.getScreenSize(); System.out.println("Screen height in pixels: "+screenDim.height); System.out.println("Screen width in pixels: "+screenDim.width); } catch(Exception e){ e.printStackTrace(); } } }

Converting html content into PDF

import java.io.*; import java.io.FileOutputStream; import org.xhtmlrenderer.pdf.ITextRenderer; public class pdfCreation { /** *  @Purpose : Converting html file into PDF. *   External jar file used iText-2.0.8.jar, core-renderer.jar          *   xml-apis-xerces-2.9.1.jar */ public static void main(String[] args) { try{            //html file path String inputFile="C:\\workspace\\html2Pdf\\src\\pack1\\sample.html"; //Output pdf file path String outputFP="C:\\sample.pdf"; File inputHTMLFile=new File(inputFile); if(!inputHTMLFile.exists()){ System.out.println("Input html File does not exists!"); System exit(0); } String url=inputHTMLFile.toURI().toURL().toString(); OutputStream os=new FileOutputStream(outputFP); ITextRenderer  render...