Java programs

940 views
876 views

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
940
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Java programs

  1. 1. Java code to get host nameimport 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:
  2. 2. Java code to Get Month from Dateimport java.text.*;import java.util.*;public class GetMonthFromDate {public 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:
  3. 3. Here is the code of Java Get IP Address Exampleimport java.net.*;import java.io.*;public class GetIPAddress {public static void main(String [] args) {try {InetAddress thisIp =InetAddress.getLocalHost();System.out.println("IP:"+thisIp.getHostAddress());}catch(Exception e) {e.printStackTrace();}}}Output will be displayed as:
  4. 4. Code to Get Memory Size in Javapublic class Memory { public static void main(String[] args) { System.out.println("Total Memory"+Runtime.getRuntime().totalMemory()); System.out.println("Free Memory"+Runtime.getRuntime().freeMemory());}}Output will be displayed as:
  5. 5. Java Code to Get Memory Usagepublic class GetMemoryUsage{ public static void main (String [] args) throws Exception { run (); memoryUsed (); final int count = 100000; Object [] object = new Object [count]; long heap1 = 0; for (int i = -1; i < count; ++ i) { Object obj = null; obj = new Object (); if (i >= 0) object [i] = obj; else { obj = null; run (); heap1 = memoryUsed (); } } run (); long heap2 = memoryUsed (); System.out.println ("before heap: " + heap1 + ", after heap: " + heap2); System.out.println ("heap delta: " + (heap2 - heap1) ); for (int i = 0; i < count; ++ i) object [i] = null; object = null; } static void run () throws Exception { for (int j = 0; j < 4; ++ j) _run (); } static void _run () throws Exception { long mem1 = memoryUsed (), mem2 = Long.MAX_VALUE; for (int i = 0; (mem1 < mem2) && (i < 500); ++ i) { runtime.runFinalization (); runtime.gc (); Thread.currentThread ().yield (); mem2 = mem1; mem1 = memoryUsed (); } } static long memoryUsed () { return runtime.totalMemory () - runtime.freeMemory (); } static final Runtime runtime = Runtime.getRuntime ();}
  6. 6. Output will be displayed as:
  7. 7. Code for Java Get Methodimport java.util.Calendar;public class GetMethod { public static void main(String[] av) { Calendar cal = Calendar.getInstance(); System.out.println("Year: " + cal.get(Calendar.YEAR)); System.out.println("Month: " + cal.get(Calendar.MONTH)); System.out.println("Day: " + cal.get(Calendar.DAY_OF_MONTH)); System.out.println("Day of week = " + cal.get(Calendar.DAY_OF_WEEK)); System.out.println("Day of year = " + cal.get(Calendar.DAY_OF_YEAR)); System.out.println("Week in Year: " + cal.get(Calendar.WEEK_OF_YEAR)); System.out.println("Week in Month: " + cal.get(Calendar.WEEK_OF_MONTH)); System.out.println("Day of Week in Month: " + cal.get(Calendar.DAY_OF_WEEK_IN_MONTH)); System.out.println("Hour (24-hour clock): " + cal.get(Calendar.HOUR_OF_DAY)); System.out.println("Minute: " + cal.get(Calendar.MINUTE)); System.out.println("Second: " + cal.get(Calendar.SECOND)); }}Output will be displayed as:
  8. 8. Code for Java Get Methodimport java.util.Calendar;public class GetMethod { public static void main(String[] av) { Calendar cal = Calendar.getInstance(); System.out.println("Year: " + cal.get(Calendar.YEAR)); System.out.println("Month: " + cal.get(Calendar.MONTH)); System.out.println("Day: " + cal.get(Calendar.DAY_OF_MONTH)); System.out.println("Day of week = " + cal.get(Calendar.DAY_OF_WEEK)); System.out.println("Day of year = " + cal.get(Calendar.DAY_OF_YEAR)); System.out.println("Week in Year: " + cal.get(Calendar.WEEK_OF_YEAR)); System.out.println("Week in Month: " + cal.get(Calendar.WEEK_OF_MONTH)); System.out.println("Day of Week in Month: " + cal.get(Calendar.DAY_OF_WEEK_IN_MONTH)); System.out.println("Hour (24-hour clock): " + cal.get(Calendar.HOUR_OF_DAY)); System.out.println("Minute: " + cal.get(Calendar.MINUTE)); System.out.println("Second: " + cal.get(Calendar.SECOND)); }}Output will be displayed as:
  9. 9. Syntax for getting mime type in Javaimport java.net.*;public class GetMimeType {public static void main(String[] args) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor("alert.gif"); System.out.println("mimeType="+ mimeType); }}Output will be displayed as:
  10. 10. Syntax for Getting the current month in Javaimport java.util.Calendar;public class GetMonth{ public static void main(String[] args) { String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; Calendar cal = Calendar.getInstance(); String month = months[cal.get(Calendar.MONTH)]; System.out.println("Month name: " + month); }}Output will be displayed as:
  11. 11. Java Syntax to get time in millisecondsimport java.util.Calendar;public class GetTimeInMilliSeconds {public static void main(String[] args) {Calendar cal = Calendar.getInstance();System.out.println("Current milliseconds since 13 Oct, 2008 are :"+ cal.getTimeInMillis());}}Output will be displayed as:
  12. 12. public class SizeOfArray { public static void main (String args []) { int num[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; String days[] = {"Sunday","Monday","Tuesday", "Wednesday", "Thursday","Friday","Saturday"}; System.out.println("size of num[]: " + num.length); System.out.println("size of days[]: " + days.length); }}Output will be displayed as:
  13. 13. Absolute Valuepublic class GetAbsoluteValue { public static void main(String args[]) throws Exception { double value = Math.abs(-10); double value1=Math.abs(1 - 50); System.out.println("The absolute value of -10 is: "+value); System.out.println("The absolute value for the condition is: "+value1); }}Output will be displayed as:
  14. 14. Date & Time Code:import java.util.Calendar;import java.text.SimpleDateFormat;public class DateAndTime { public static final String date = "yyyy-MM-dd HH:mm:ss"; public static String now() { Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat(date); return dateFormat.format(calendar.getTime());} public static void main(String arg[]) { System.out.println("Date and Time : " + DateAndTime.now()); }}Output will be displayed as:
  15. 15. To print ascii value of a character this is the the simplest way to change the type a character.Here in the example given below we will select character from a given string and change theirtype to integer that will be their ascii value.Method charAt() of String class is used to select character in the given string on basis of givenindex value as argument.public class GetAsciiValue {public static void main(String[] args) {String s = "Java";for (int i=0; i<s.length();i++)System.out.println("ASCII value of: "+s.charAt(i) + " is:"+ (int)s.charAt(i) );}}Output will be displayed as:
  16. 16. GetClassDirectory.javaimport java.util.*;import java.lang.*;import java.net.*;public class GetClassDirectory{ public static void main(String args[]) { URL url=new Object().getClass().getResource("Object.class"); System.out.println(url); }}Output:C:javaexamples>javac GetClassDirectory.javaC:javaexamples>java GetClassDirectoryjar:file:/C:/Java/jdk1.6.0_03/jre/lib/rt.jar!/java/lang/Object.class
  17. 17. In this code we have first created an object of "Class" by the String class. Following code doesthis for us.Class cls = java.lang.String.class; now we can get the full class name with the methodgetName(). It can be done as follows:String clsname= cls.getName(); It will return string java.lang.String and from here we have toget the "String" by removing "java.lang".int mid=clsname.lastIndexOf (.) + 1;String finalClsName = clsname.substring(mid);Above lines of code gets the class name without package.Here is the example code ofGetClassWithoutPackage.java as follows:GetClassWithoutPackage.javaimport java.util.*;import java.lang.*;import java.net.*;public class GetClassWithoutPackage{ public static void main(String args[]) { Class cls = java.lang.String.class; String clsname= cls.getName(); System.out.println("Full class name ="+clsname); int mid=clsname.lastIndexOf (.) + 1; String finalClsName = clsname.substring(mid); System.out.println(finalClsName); }}Output:C:javaexamples>javacGetClassWithoutPackage.javaC:javaexamples>javaGetClassWithoutPackageFull class name =java.lang.StringStringC:javaexamples>
  18. 18. In this java example program we have to write code for getting the pixel color of an image. Toget the pixel color we need to first have an image and then we will be able to get the pixel colorof any specific or particular pixel in the RGB format.File file= new File("rockface.jpg");BufferedImage image = ImageIO.read(file);Above line of code creates an object of File with the image named "rockface.jpg" now we willread this file with the static method of ImageIO read(). Now we can get the pixel color with thegetRGB() method with the image object.Here is the example code of GetPixelColor.java as follows:GetPixelColor.javaimport java.io.*;import java.awt.*;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;public class GetPixelColor{ public static void main(String args[]) throws IOException{ File file= new File("rockface.jpg"); BufferedImage image = ImageIO.read(file); // Getting pixel color by position x=100 and y=40 int clr= image.getRGB(100,40); int red = (clr & 0x00ff0000) >> 16; int green = (clr & 0x0000ff00) >> 8; int blue = clr & 0x000000ff; System.out.println("Red Color value = "+ red); System.out.println("Green Color value = "+ green); System.out.println("Blue Color value = "+ blue); }}Output of the above Code:C:javaexamples>javac GetPixelColor.javaC:javaexamples>java GetPixelColorRed Color value = 33Green Color value = 50
  19. 19. Blue Color value = 60
  20. 20. In this example of getting the columns names we need to have connection with the database andthen after we will get metadata of this table and find the columns name within the metadata.In our example program we have created a database connection with the data table within theMySQL database. The data table view is as follows:To have metadata related manipulation we need to have an object of ResultSetMetaData andthereafter we can do the manipulation on the table related information.ResultSetMetaData rsmd = rs.getMetaData();int NumOfCol = rsmd.getColumnCount();Above lines of code creates an object of ResultSetMetaData and we can get the number ofcolumns with the use of getColumnCount() methods. Now we can get the column names withthe index value by the method getColumnName().Here is the example code ofGetColumnName.java as follows:GetColumnName.javaimport java.sql.*;public class GetColumnName { public static void main(String[] args) throws Exception { String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/"; String username = "root"; String password = "root"; String dbName= "any"; Class.forName(driver); Connection conn = DriverManager.getConnection(url+dbName, username, password); System.out.println("Connected"); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM webpages"); ResultSetMetaData rsmd = rs.getMetaData(); int NumOfCol = rsmd.getColumnCount(); for(int i=1;i<=NumOfCol;i++) {
  21. 21. System.out.println("Name of ["+i+"] Column="+rsmd.getColumnName(i)); } st.close(); conn.close(); }}Output:C:javaexamples>javacGetColumnName.javaC:javaexamples>java GetColumnNameConnectedName of [1] Column=idName of [2] Column=titleName of [3] Column=urlName of [4] Column=pageContent
  22. 22. Description of the code: 1. First create connection to the database from where you want to retrieve image saved as blob. 2. Create a mysql query to retrieve image value from table column. 3. Retrieves the value of the designated column in the current row of this ResultSet object as aBlob object by using getBlob() method. 4. Write data on standard output device.Table Structure:CREATE TABLE pictures( image_id int(10) NOT NULLauto_increment,image blob)Here is the code of GetBlob.javaimport java.io.*;import java.sql.*;class GetBlob {FileOutputStream image;Connection con = null;PreparedStatement pstmt = null;Statement stmt= null;ResultSet res = null;StringBuffer query=null;String driverName = "com.mysql.jdbc.Driver";String url = "jdbc:mysql://localhost:3306/";;String dbName = "register";String userName = "root";String password = "root";public GetBlob(){try{Class.forName(driverName);con = DriverManager.getConnection(url+dbName,userName,password);stmt=con.createStatement();ResultSet rs=stmt.executeQuery("select * from picture where image_id=3");if (rs.next()) {Blob test=rs.getBlob("image");InputStream x=test.getBinaryStream();int size=x.available();OutputStream out=new FileOutputStream("C:anu.jpg");byte b[]= new byte[size];
  23. 23. x.read(b);out.write(b);}}catch(Exception e){System.out.println("Exception :"+e);}finally{try{stmt.close();con.close();}catch(Exception e){System.out.println(e);}}}public static void main(String args[]) throws IOException{GetBlob blob = new GetBlob();}}Image retrieved from the database:
  24. 24. Here is the code of GetCollingClass.javaclass GetCallingClass{ public static void main(String args[]){ new GetCallingClass().hello(); } void hello() { try { throw new Exception("Error"); } catch( Exception e ) { System.out.println( e.getStackTrace()[1].getClassName()); }}}Output will be displayed as:
  25. 25. Here is the code of GetCharMethodimport java.io.*; public class GetCharMethod { public static void main(String args[]) throws IOException { char c; System.out.println("Enter any character or Enter the charater E to exit"); while ( ( c = getChar() ) != E ) { System.out.println("You have entered " + c); } } static public char getChar() throws IOException { char ch = (char) System.in.read(); input(); return ch; } static public void input() throws IOException { while ( (char) System.in.read() != n ); } }Output will be displayed as:

×