You are on page 1of 25

Java code to get host name

import java.net.*; import java.io.*; public class GetHostName{ public static void main(String [] args) { try { InetAddress addr = InetAddress.getLocalHost(); byte[] ipAddr = addr.getAddress(); String hostname = addr.getHostName(); System.out.println("hostname="+hostname); } catch (UnknownHostException e) { } } }

Output will be displayed as:

Java code to Get Month from Date
import import public public java.text.*; java.util.*; class GetMonthFromDate { static void main(String args[]) {

Date date = new Date(); SimpleDateFormat sdf; sdf = new SimpleDateFormat("MM"); System.out.println("Month " + sdf.format(date)); } }

Output will be displayed as:

*.Here is the code of Java Get IP Address Example import java. import java.getHostAddress()).*. } catch(Exception e) { e. System.println("IP:"+thisIp. public class GetIPAddress { public static void main(String [] args) { try { InetAddress thisIp =InetAddress.printStackTrace().getLocalHost().out.net.io. } } } Output will be displayed as: .

Code to Get Memory Size in Java public class Memory { public static void main(String[] args) { System.out. } } Output will be displayed as: .totalMemory()).println("Free Memory"+Runtime.freeMemory()). System.out.getRuntime().println("Total Memory"+Runtime.getRuntime().

currentThread (). for (int i = 0.getRuntime ().println ("'before' heap: " + heap1 + ". long heap2 = memoryUsed (). } static final Runtime runtime = Runtime. mem2 = mem1. 'after' heap: " + heap2). memoryUsed (). ++ i) { Object obj = null. runtime.runFinalization ().MAX_VALUE. obj = new Object ().out.out. Object [] object = new Object [count]. mem1 = memoryUsed (). run (). j < 4. } } static long memoryUsed () { return runtime. ++ i) { runtime. for (int i = 0. for (int i = -1. } static void _run () throws Exception { long mem1 = memoryUsed (). else { obj = null.gc (). heap1 = memoryUsed ().totalMemory () .yield (). } } run (). object = null. ++ j) _run (). mem2 = Long. } static void run () throws Exception { for (int j = 0.println ("heap delta: " + (heap2 . System. i < count. if (i >= 0) object [i] = obj. i < count.Java Code to Get Memory Usage public class GetMemoryUsage { public static void main (String [] args) throws Exception { run (). (mem1 < mem2) && (i < 500).heap1) ). System.runtime. final int count = 100000. Thread. ++ i) object [i] = null. long heap1 = 0.freeMemory (). } .

Output will be displayed as: .

System. System.DAY_OF_WEEK)). System.println("Day: " + cal.out.println("Second: " + cal.println("Minute: " + cal. System.println("Day of Week in Month: " + cal.get(Calendar.out.out. System.println("Week in Month: " + cal.DAY_OF_YEAR)).Code for Java Get Method import java.MONTH)).WEEK_OF_YEAR)). System.HOUR_OF_DAY)). public class GetMethod { public static void main(String[] av) { Calendar cal = Calendar.get(Calendar.out. System.YEAR)).println("Hour (24-hour clock): " + cal.get(Calendar. System.println("Month: " + cal.getInstance().get(Calendar.out.out.get(Calendar.out.out.DAY_OF_WEEK_IN_MONTH)).println("Year: " + cal. } } Output will be displayed as: .get(Calendar.out.get(Calendar.get(Calendar.println("Day of year = " + cal.WEEK_OF_MONTH)).println("Week in Year: " + cal.out.util. System.get(Calendar.println("Day of week = " + cal. System. System.DAY_OF_MONTH)).out.get(Calendar.MINUTE)).get(Calendar.Calendar.SECOND)).

System.println("Day of week = " + cal.println("Week in Month: " + cal. System.out.out.DAY_OF_WEEK)). System.get(Calendar.getInstance().out.Calendar.out. } } Output will be displayed as: .get(Calendar. System.out. System.println("Day: " + cal.DAY_OF_MONTH)).println("Month: " + cal.println("Day of Week in Month: " + cal.get(Calendar.get(Calendar.println("Day of year = " + cal.get(Calendar.out. System.out.MINUTE)).util.out.println("Hour (24-hour clock): " + cal.get(Calendar.get(Calendar.HOUR_OF_DAY)).out.println("Year: " + cal.println("Second: " + cal.out.MONTH)).SECOND)). System.DAY_OF_WEEK_IN_MONTH)). System. System.WEEK_OF_MONTH)).Code for Java Get Method import java.get(Calendar.get(Calendar.WEEK_OF_YEAR)). System.println("Minute: " + cal. public class GetMethod { public static void main(String[] av) { Calendar cal = Calendar.YEAR)).out. System.get(Calendar.get(Calendar.println("Week in Year: " + cal.DAY_OF_YEAR)).

println("mimeType="+ mimeType).gif").getContentTypeFor("alert. System. String mimeType = fileNameMap. } } Output will be displayed as: . public class GetMimeType { public static void main(String[] args) { FileNameMap fileNameMap = URLConnection.Syntax for getting mime type in Java import java.*.getFileNameMap().out.net.

"March". "May". System.Calendar. "October". "November".MONTH)]. public class GetMonth { public static void main(String[] args) { String[] months = {"January". Calendar cal = Calendar. "December"}.util. "February". "August".out. "September". "June". "April". String month = months[cal.println("Month name: " + month).getInstance().Syntax for Getting the current month in Java import java. "July". } } Output will be displayed as: .get(Calendar.

Calendar.getTimeInMillis()). } } Output will be displayed as: .out. System. public class GetTimeInMilliSeconds { public static void main(String[] args) { Calendar cal = Calendar. 2008 are :" + cal.Java Syntax to get time in milliseconds import java.util.getInstance().println("Current milliseconds since 13 Oct.

System. 2."Saturday"}.public class SizeOfArray { public static void main (String args []) { int num[] = {1. 4. 5. "Wednesday". "Thursday".println("size of days[]: " + days. 3.out."Tuesday". 7.println("size of num[]: " + num.length). String days[] = {"Sunday". System. } } Output will be displayed as: .out. 8."Friday".length)."Monday". 9}. 6.

System.Absolute Value public class GetAbsoluteValue { public static void main(String args[]) throws Exception { double value = Math.50).out.abs(1 .println("The absolute value for the condition is: "+value1).println("The absolute value of -10 is: "+value). System.abs(-10).out. } } Output will be displayed as: . double value1=Math.

import java. SimpleDateFormat dateFormat = new SimpleDateFormat(date). } public static void main(String arg[]) { System.getInstance(). return dateFormat. public static String now() { Calendar calendar = Calendar.format(calendar.text.util. public class DateAndTime { public static final String date = "yyyy-MM-dd HH:mm:ss".Calendar. } } Output will be displayed as: .println("Date and Time : " + DateAndTime.Date & Time Code: import java.now()).SimpleDateFormat.getTime()).out.

charAt(i) ). Method charAt() of String class is used to select character in the given string on basis of given index value as argument. } } Output will be displayed as: . Here in the example given below we will select character from a given string and change their type to integer that will be their ascii value. i<s.println("ASCII value of: "+s. public class GetAsciiValue { public static void main(String[] args) { String s = "Java".charAt(i) + " is:"+ (int)s.out. for (int i=0.To print ascii value of a character this is the the simplest way to change the type a character.i++) System.length().

GetClassDirectory.class").getResource("Object.java import java.util.println(url).*. System. import java.net.*.6. public class GetClassDirectory { public static void main(String args[]) { URL url=new Object(). import java.*.jar!/java/lang/Object.0_03/jre/lib/rt.class .java C:\javaexamples>java GetClassDirectory jar:file:/C:/Java/jdk1.out.lang.getClass(). } } Output: C:\javaexamples>javac GetClassDirectory.

getName().println("Full class name ="+clsname).In this code we have first created an object of "Class" by the String class. String clsname= cls.lang.String String C:\javaexamples> . } } Output: C:\javaexamples>javac GetClassWithoutPackage.lang. System. String finalClsName = clsname. Following code does this for us.substring(mid).lang.lang".String and from here we have to get the "String" by removing "java.java C:\javaexamples>java GetClassWithoutPackage Full class name =java.substring(mid). int mid=clsname. It can be done as follows: String clsname= cls.*.lastIndexOf ('.out. Above lines of code gets the class name without package.lang. now we can get the full class name with the method getName().class.class.out. System.lastIndexOf ('. It will return string java. import java. String finalClsName = clsname.*. public class GetClassWithoutPackage { public static void main(String args[]) { Class cls = java. int mid=clsname.println(finalClsName). Class cls = java.java as follows: GetClassWithoutPackage. import java.') + 1.java import java.*.String.') + 1.lang.net.String.getName().Here is the example code of GetClassWithoutPackage.util.

read(file).java as follows: GetPixelColor.ImageIO.image. java.jpg"). File file= new File("rockface.read(file). Now we can get the pixel color with the getRGB() method with the image object. java. public class GetPixelColor { public static void main(String args[]) throws IOException{ File file= new File("rockface. System.out. Here is the example code of GetPixelColor.io.imageio.awt.jpg"). int green = (clr & 0x0000ff00) >> 8.40).*.jpg" now we will read this file with the static method of ImageIO read().In this java example program we have to write code for getting the pixel color of an image. BufferedImage image = ImageIO. BufferedImage image = ImageIO. javax. To get the pixel color we need to first have an image and then we will be able to get the pixel color of any specific or particular pixel in the RGB format.getRGB(100.awt.*. System.out.println("Red Color value = "+ red).BufferedImage.println("Blue Color value = "+ blue). System.out. int blue = clr & 0x000000ff.java C:\javaexamples>java GetPixelColor Red Color value = 33 Green Color value = 50 .println("Green Color value = "+ green). Above line of code creates an object of File with the image named "rockface. // Getting pixel color by position x=100 and y=40 int clr= image.java import import import import java. } } Output of the above Code: C:\javaexamples>javac GetPixelColor. int red = (clr & 0x00ff0000) >> 16.

Blue Color value = 60 .

Driver". String dbName= "any". ResultSetMetaData rsmd = rs.mysql.getConnection(url+dbName. String url = "jdbc:mysql://localhost:3306/". Now we can get the column names with the index value by the method getColumnName(). ResultSetMetaData rsmd = rs. String username = "root". Class.sql. ResultSet rs = st. int NumOfCol = rsmd. for(int i=1. Connection conn = DriverManager. The data table view is as follows: To have metadata related manipulation we need to have an object of ResultSetMetaData and thereafter we can do the manipulation on the table related information.getColumnCount().createStatement().In this example of getting the columns names we need to have connection with the database and then after we will get metadata of this table and find the columns name within the metadata.getMetaData(). String password = "root".java as follows: GetColumnName. Statement st = conn.out.executeQuery("SELECT * FROM webpages"). Above lines of code creates an object of ResultSetMetaData and we can get the number of columns with the use of getColumnCount() methods.i<=NumOfCol.jdbc. username. public class GetColumnName { public static void main(String[] args) throws Exception { String driver = "com.forName(driver).java import java. password).i++) { .Here is the example code of GetColumnName.getColumnCount(). int NumOfCol = rsmd.*.getMetaData().println("Connected"). In our example program we have created a database connection with the data table within the MySQL database. System.

} } Output: C:\javaexamples>javac GetColumnName.close().println("Name of ["+i+"] Column="+rsmd.getColumnName(i)).System. conn.out.close().java C:\javaexamples>java GetColumnName Connected Name of [1] Column=id Name of [2] Column=title Name of [3] Column=url Name of [4] Column=pageContent . } st.

Create a mysql query to retrieve image value from table column.sql. ResultSet rs=stmt. . InputStream x=test. 4. String driverName = "com. 2..java import java.mysql. image blob ) Here is the code of GetBlob. StringBuffer query=null. Write data on standard output device. String url = "jdbc:mysql://localhost:3306/".createStatement().*. Retrieves the value of the designated column in the current row of this ResultSet object as a Blob object by using getBlob() method. class GetBlob { FileOutputStream image.next()) { Blob test=rs.available().password). if (rs. public GetBlob(){ try{ Class.Driver". PreparedStatement pstmt = null.getBinaryStream(). con = DriverManager. Statement stmt= null. stmt=con. First create connection to the database from where you want to retrieve image saved as blob.executeQuery("select * from picture where image_id='3'").forName(driverName). ResultSet res = null.io. String password = "root".jpg"). Table Structure: CREATE TABLE pictures ( image_id int(10) NOT NULL auto_increment. Connection con = null. byte b[]= new byte[size]. 3. String userName = "root". OutputStream out=new FileOutputStream("C:\\anu.getBlob("image").*.jdbc. import java. int size=x.getConnection(url+dbName. String dbName = "register".userName.Description of the code: 1.

println("Exception :"+e).out. } } } public static void main(String args[]) throws IOException{ GetBlob blob = new GetBlob(). } } catch(Exception e){ System.write(b).x. con. } finally{ try{ stmt. out.out.read(b). } catch(Exception e){ System. } } Image retrieved from the database: .close().println(e).close().

} } } Output will be displayed as: .println( e. } void hello() { try { throw new Exception("Error").java class GetCallingClass { public static void main(String args[]){ new GetCallingClass().hello(). } catch( Exception e ) { System.out.Here is the code of GetCollingClass.getClassName()).getStackTrace()[1].

} } Output will be displayed as: .*. } static public void input() throws IOException { while ( (char) System.println("You have entered " + c).io. while ( ( c = getChar() ) != 'E' ) { System.out.out.Here is the code of GetCharMethod import java.read() != '\n' ).println("Enter any character or Enter the charater E to exit"). input(). public class GetCharMethod { public static void main(String args[]) throws IOException { char c. return ch.in. } } static public char getChar() throws IOException { char ch = (char) System. System.read().in.