The document contains code snippets in Java for getting different types of information. This includes code to get the hostname, month from a date, IP address, memory size and usage, and more. The code uses various Java classes and methods like InetAddress, DateFormat, Runtime etc. to retrieve the desired information and print/return the output.
1. 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:
2. Java code to Get Month from Date
import 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. Here is the code of Java Get IP Address Example
import 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. Code to Get Memory Size in Java
public 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. Java Code to Get Memory Usage
public 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 ();
}
7. Code for Java Get Method
import 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. Code for Java Get Method
import 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. Syntax for getting mime type in Java
import 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. Syntax for Getting the current month in Java
import 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. Java Syntax to get time in milliseconds
import 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. 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. Absolute Value
public 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. 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. 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 their
type 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 given
index 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. GetClassDirectory.java
import 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.java
C:javaexamples>java GetClassDirectory
jar:file:/C:/Java/jdk1.6.0_03/jre/lib/rt.jar!/java/lang/Object.class
17. In this code we have first created an object of "Class" by the String class. Following code does
this for us.
Class cls = java.lang.String.class; now we can get the full class name with the method
getName(). It can be done as follows:
String clsname= cls.getName(); It will return string java.lang.String and from here we have to
get 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 of
GetClassWithoutPackage.java as follows:
GetClassWithoutPackage.java
import 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>javac
GetClassWithoutPackage.java
C:javaexamples>java
GetClassWithoutPackage
Full class name =java.lang.String
String
C:javaexamples>
18. In this java example program we have to write code for getting the pixel color of an image. 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.
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 will
read this file with the static method of ImageIO read(). Now we can get the pixel color with the
getRGB() method with the image object.
Here is the example code of GetPixelColor.java as follows:
GetPixelColor.java
import 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.java
C:javaexamples>java GetPixelColor
Red Color value = 33
Green Color value = 50
20. 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.
In our example program we have created a database connection with the data table within the
MySQL database. 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.
ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol = rsmd.getColumnCount();
Above lines of code creates an object of ResultSetMetaData and we can get the number of
columns with the use of getColumnCount() methods. Now we can get the column names with
the index value by the method getColumnName().Here is the example code of
GetColumnName.java as follows:
GetColumnName.java
import 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. System.out.println("Name of ["+i+"] Column="+rsmd.getColumnName(i));
}
st.close();
conn.close();
}
}
Output:
C:javaexamples>javac
GetColumnName.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
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 a
Blob object by using getBlob() method.
4. Write data on standard output device.
Table Structure:
CREATE TABLE pictures
( image_id
int(10) NOT NULL
auto_increment,
image blob
)
Here is the code of GetBlob.java
import 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];
24. Here is the code of GetCollingClass.java
class 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. Here is the code of GetCharMethod
import 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: