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



Monday, 13 May 2013

How to create user defined unchecked Exception

We have to create a class extending from RuntimeException like below.

Code
--------
public class InvalidInputException extends RuntimeException {

public InvalidInputException() {
super();
}

public InvalidInputException(String message) {
super(message);
}
}


As java.lang.Exception class is by deafult a  checked Exception class, the subclass we derive from this will be by default a checked Exception. If you want to make an unchecked exception class you have to create a class extending from java.lang.RuntimeException

Java - Association Vs Aggregation Vs Composition


Both Composition and Aggregation are Associations.
Composition IS-A Association.
Aggregation IS-A Association.

Composition is a strong association.
Aggregation is a weak association.

Association is an 'Has-A' relationship. In Java you can think of any time a class has an member of of a different type, then there is an Association between them. So for example:

public class Person
{
    private final Name name;
    private Costume currentClothes;

    //...
}

In this case, the Person Has-A name and Has-A Costume, so there is an Association between Person and Name, and Person and Costume.

Aggregation and Composition are specializations of the Association relationship - they are both Has-A relationships, but the difference is the length of that relationship. In the above example, a Person probably has a single Name for the live of the Person, while the Person may have different Costumes depending on the situation. If this is the case then the relationship between Person and Name is Composition, and the relationship between Person and Costume is Aggregation.

Composition is an Association where the containing Object is responsible for the lifetime of the contained Object. To show this in Java Person might have a constructor like this:
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
public class Person
{
    private final Name name;

    public Person (String fName, String lName)
    {
        name = new Name(fName, lName);
    }

    //...
}

Typically there would be no 'setName(Name)' methods. The Person is responsible for creating the Name, and when the Person is destroyed then the Name should (usually) be as well.

Aggregation is an Association relationship where the Association can be considered the containing class 'Owning' the contained class, and the lifetime of that relationship is not defined. 'Owning' can be determined as a single-direction Association. In the above example, the Person Has-A Costume, but the Costume would not Have-A Person. More importantly the Person to Costume Association is transient. In Java you can usually tell this because there are setter methods, or other means of adding / replacing the contained Object. So for the Person class you might have:
view plaincopy to clipboardprint?
Note: Text content in the code blocks is automatically word-wrapped
public class Person
{
    private Costume currentClothes;

    public void setClothes(Costume clothes)
    {
        currentClothes = clothes;
    }

    //...
}

Friday, 10 May 2013

An Introduction to Android

Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.

Features of Android
-----------------------------------

1) Application framework enabling reuse and replacement of components
2) Dalvik virtual machine optimized for mobile devices
3) Integrated browser based on the open source WebKit engine
4) Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
5) SQLite for structured data storage
6) Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
7) GSM Telephony (hardware dependent)
8) Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
9) Camera, GPS, compass, and accelerometer (hardware dependent)
10) Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE

Android Architecture
------------------------------
The following diagram shows the major components of the Android operating system. Each section is described in more detail below.






Applications
--------------------
Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.
Application Framework
---------------------------
Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user.

Underlying all applications is a set of services and systems, including:

  • A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser
  • Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data
  • A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files
  • A Notification Manager that enables all applications to display custom alerts in the status bar
  • An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack

Libraries
------------
Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below:

  • System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices
  • Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
  • Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications
  • LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view
  • SGL - the underlying 2D graphics engine
  • 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer
  • FreeType - bitmap and vector font rendering
  • SQLite - a powerful and lightweight relational database engine available to all applications
Android Runtime
--------------------
Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.

Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.

The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.

Linux Kernel
-----------------
Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.

Sunday, 5 May 2013

Why java has one public class per java file restriction?


It forces all Java code to be organized a certain way, which in the long run helps improve code readability. The Java designers chose a strict approach that enforces their idea of good design practices, and this is part of that theme.

Imagine you have a source file that references a lot of classes. If public classes were allowed to be defined in a file without name restrictions, you would have to inspect every file in every package until you find the correct definition. 

Right now the compiler only has to look for one file per package, and all files in the same package. That's a lot faster.