Saturday, 8 June 2013

Listing nested classes and implemented interfaces names

Code
import java.util.Arrays;

class NestedInfoDemo {

public static void main(final String[] args) {
printMemberClasses(Class1.class);

}

public static void printMemberClasses(final Class dataType) {
final Class[] nestedClasses = dataType.getClasses();
final Class[] declaredNestedClasses = dataType.getDeclaredClasses();
final Class[] nestedInterfaces = dataType.getInterfaces();
final Class declaringClass = dataType.getDeclaringClass();

System.out.println("Member Class info for: " + dataType.getName());
System.out.println("Nested Classes: " + Arrays.asList(nestedClasses));
System.out.println("Declared Nested Classes: " + Arrays.asList(declaredNestedClasses));
System.out.println("Interfaces: " + Arrays.asList(nestedInterfaces));
System.out.println("Declaring Class: " + declaringClass);
System.out.println();
}

interface Int1 {

}

interface Int2 {

}

interface Int3 {

}

class Class1 implements Int1, Int2, Int3 {
public class Class4 {

}
}

class Class2 {
}

class Class3 {
}
}


Sample Output
Member Class info for: org.reflection.NestedInfoDemo$Class1
Nested Classes: [class org.reflection.NestedInfoDemo$Class1$Class4]
Declared Nested Classes: [class org.reflection.NestedInfoDemo$Class1$Class4]
Interfaces: [interface org.reflection.NestedInfoDemo$Int1, interface org.reflection.NestedInfoDemo$Int2, interface org.reflection.NestedInfoDemo$Int3]
Declaring Class: class org.reflection.NestedInfoDemo

Java Code to search a file

Code
import java.io.File;
import java.util.Vector;

class JavaSearchFile {
static Vector<File> v;

public static void main(String args[]) throws Exception {

File f = new File(args[0]);
v = new Vector<File>();
System.out.println("\nStarting search....\n-------------------------\n");
search(f, args[1]);
print();

}

public static void search(File file, String name) {
System.out.println("Searching in " + file.getAbsolutePath());
if (file.isDirectory()) {
if (file.getName().contains(name)) {
v.addElement(file);
}
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
try {
if (files[i].isDirectory()) {
search(files[i], name);
} else {
if (files[i].getName().toLowerCase().contains(name.toLowerCase())) {
v.addElement(files[i]);
}
}
} catch (Exception e) {
}
}
}
}

public static void print() {
File[] f = new File[v.size()];
v.copyInto(f);
System.out.println("\nResults");
System.out.println("------------------------------------------");
for (File k : f) {
System.out.println("Found at " + k.getAbsolutePath());
}
}

}


Sample Output
Starting search....
-------------------------

Searching in c:\Java

Results
------------------------------------------
Found at c:\Java\Notes.txt

Different ways to read and display file content

Code
--------
import java.io.FileInputStream;

class FileRead {
public static void main(String args[]) throws Exception {
// Way-1
FileInputStream fin = new FileInputStream("FileRead.java");
byte[] b = new byte[fin.available()];
fin.read(b);
for (int i = 0; i < b.length; i++) {
System.out.print((char) b[i]);
}
// Way-2
int k = 0;
FileInputStream fin1 = new FileInputStream("FileRead.java");
System.out.println("\n\nWay-2\n");
while ((k = fin1.read()) != -1) {
System.out.print((char) k);
}
// Way-3
FileInputStream fin2 = new FileInputStream("FileRead.java");
byte b1[] = new byte[fin2.available()];
fin2.read(b1, 0, b1.length);
System.out.println("\n\nWay-3\n");
for (int i = 0; i < b1.length; i++) {
System.out.print((char) b1[i]);
}
fin.close();
fin1.close();
fin2.close();
}
}

Code to get file extensions

Code
----------
import java.io.File;

class GetFileExt {

public static void main(String args[]) {

File f = new File("C:/java");
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
String name = files[i].getName();
if (!files[i].isDirectory()) {
if (name.contains(".")) {
System.out.println("Extension for " + name + " is " + name.substring(name.lastIndexOf('.'), name.length()));
}
}
}
}
}

Sample Output
------------------
Extension for Notes.txt is .txt
Extension for One.html is .html

Different ways to write data into file

Code
---------
import java.io.FileOutputStream;

class FileWrite {
public static void main(String args[]) throws Exception {
String st = "I am going to be written in the file.";

// Way-1
FileOutputStream fout = new FileOutputStream("output.txt");
byte[] b = st.getBytes();
fout.write(b);
fout.close();

// Way-2
FileOutputStream fout1 = new FileOutputStream("output1.txt");
// Convert string to char array
char[] c = st.toCharArray();
for (int i = 0; i < c.length; i++) {
fout1.write(c[i]);
}
fout1.close();

// Way-3
FileOutputStream fout2 = new FileOutputStream("output2.txt");
byte[] b1 = st.getBytes();
fout2.write(b1, 0, b1.length);
fout2.close();
}
}

Code to verify the given path is file or directory

Code
---------------
import java.io.File;

class CheckFile {

public static void main(String args[]) {
File file = new File("C:/java");

// Way-1
if (file.isDirectory())
System.out.println(file.getName() + " is a directory");
else
System.out.println(file.getName() + " is a file");

// Way-2
if (file.isFile())
System.out.println(file.getName() + " is a file");
else
System.out.println(file.getName() + " is a directory");
}

}

Sample Output
------------------
java is a directory
java is a directory

Java Samples

Java code to display local hard drive details

Code
----------
import java.io.File;

class GetLocalDrives {
public static void main(String args[]) {
File[] f = File.listRoots();
for (File k : f)
System.out.println(k);
System.out.println("The file separator is " + File.separatorChar);
}
}

Sample output
------------------
C:\
D:\
E:\
F:\
H:\
The file separator is \

Explanation
----------------
 listRoots(): It is a static method of the java.io.File class and is used to get all the roots (local drives).

 Note: The file separator depends upon your OS. If windows \ is the output, for linux like OS / is the file separator.

Java code to display memory satus

Code
-----------
class MemoryDetails {
public static void main(String args[]) {

// Create Runtime object
Runtime r = Runtime.getRuntime();

// Free memory in JVM
System.out.println("Free memory: " + r.freeMemory());

// Total memory in JVM
System.out.println("Total memory: " + r.totalMemory());

// Max memory JVM uses
System.out.println("Max memory: " + r.maxMemory());
}
}

Sample output
-------------------------
Free memory: 15964992
Total memory: 16252928
Max memory: 259522560



Explanation
-----------------
Memory is given in the form of bytes

Java code to reverse the digits of Integer

Code
---------
import java.util.Scanner;

class ReverseDigits {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int i = reverseDigits(s.nextInt());
System.out.println(i);
}

public static int reverseDigits(int k) {
String st = k + "";
StringBuffer sb = new StringBuffer(st).reverse();
return new Integer(sb.toString()).intValue();
}
}

Sample output
-------------------
Please enter a number
1234
4321


Explanation
---------------------
 reverseDigits(): This is a method that takes an integer and then convert to string and then reverse it and then return an int.
 st=k+""; This is an easy way of converting an int to string. Appending "".
 Nothing in fact is appended, an open and close of the double quotes just does the thing.

 sb=new StringBuffer(st).reverse(); This statement creates a StringBuffer object of the string (which is the given int) and then the reverse method reverses the string.

 new Integer(sb.toString()).intValue(): Gives the int value of string. The java.lang.Integer class contains this. The constructor here takes a java.lang.String as parameter.

Java code to swap two integer values

Code
-----------
class SwapDemo {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter 2 numbers to swap");

int a = s.nextInt();
int b = s.nextInt();

swap(a, b);
}

public static void swap(int a, int b) {

// Store a in a temporary variable
int temp = a;

// Store b variable value in a
a = b;

// Store temp (a original) value in b
b = temp;

// Print the variables
System.out.println("a is " + a + " & b is " + b);
}
}

Java code to know Java version & OS details

Code
---------
public class SystemProperties {
public static void main(String[] args) {
System.out.println(System.getProperty("java.home"));
System.out.println(System.getProperty("os.name"));
System.out.println(System.getenv("windir"));

}
}

Sample output
------------------
C:\Program Files\Java\jre7
Windows 7
C:\Windows


Explanation
--------------------
java.home: It is the property for which the value is the java home, the directory where Java is installed in the PC in which this program is executed.

getProperty(): This is a method of java.lang.System class which takes property name and returns property values.

System.getProperty("os.name"): This method is used for getting the value of specified property in Java. The os.name property means the name of the OS.

System.getenv(): Takes a property name and returns its value. env means environment.

Passing variable length of arguments to java methods (varargs)

Code
--------
public class VarArgs {
public static void main(String[] args) {
System.out.println("Sum: " + Calc.add(10, 20, 30));
System.out.println("Sum: " + Calc.add(10, 20, 30, 40));
}
}

class Calc {
public static int add(int... a) {
int result = 0;
for (int i : a)
result += i;
return result;
}
}


Sample output
-------------------------
Sum: 60
Sum: 100




Concept of varargs
-----------------------
In Java varargs is a unique concept. Let us learn about the main reason behind the origin. 
What will happen if you don't know how many arguments you need to pass to a method?
What will happen if you want to pass unlimited variables to a method?
There is an answer for these questions in Java. It is simple, and there is varargs. Using this concept you can send as many as parameters of the same type without any restriction. An example will give you a better understand.

Normal Method
public void MyMeth(int a,int b){....}


VarArg Method
public void MyMeth(int... a) {....}


Explanation
The normal method above takes no more than 2 parameters of int type.
The varargs method takes as many number of parameters as you give of int type only*

As discussed earlier, the use of varargs is this one. You cannot write as many as parameters for a method and also if you do, you must ensure that values to every parameter is sent when you make the method call. This is a drawback of the normal methods but not for the varargs method not only in Java but in any programming language.

Not only for primitive types, varargs in java is applicable for classes also. Simply, applicable for all kinds of parameters.

How it works?
In the above varargs method, parameter acts as an int array with a reference name a. To check this, you can call the length property of the arrays and that works.

Varargs is not just a simple concept in Java, it is highly important at critical times for the developers. This tutorial demonstrates the main part necessary for developers to fire. You'll have to note that not only in Java but C/C++ do support varargs. This feature in Java is implemented from Java 5 (Java 1.5) version.

Java program to count number of words and letters

Code
--------
import java.util.Scanner;
import java.util.StringTokenizer;

class WordCount {
public static void main(String args[]) {
// Create Scanner object
Scanner s = new Scanner(System.in);

System.out.println("Please eneter a statement");
// Read a string
String st = s.nextLine();

// Split string with space
String words[] = st.trim().split(" ");

//way 1
System.out.println("No. of words " + words.length);

//way 2
System.out.println("No. of words " + new StringTokenizer(st).countTokens());

System.out.println("No. of letters " + st.length());

}
}


Sample output:
-------------------------------------------
Please eneter a statement
This is a test message entered by Admin
No. of words 8
No. of words 8
No. of letters 39