Java

From Omnia
Jump to navigation Jump to search

Java

"Java is a programming language originally developed by Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture.

The original and reference implementation Java compilers, virtual machines, and class libraries were developed by Sun from 1995. As of May 2007, in compliance with the specifications of the Java Community Process, Sun made available most of their Java technologies as free software under the GNU General Public License. Others have also developed alternative implementations of these Sun technologies, such as the GNU Compiler for Java and GNU Classpath." [1]

Subpage Table of Contents

Browser Plugin Version Check

Verify Java Browser Plugin Version - http://www.java.com/en/download/installed.jsp

Duke - Mascot

Hello World

Hello.java:

public class Hello {
	public static void main(String args[]) {
		System.out.println("Hello World!\n");
	}
}

Compile and execute:

 javac Hello.java
 java Hello

Note: If your file has a "public" class, file name should match the public class name, or you will get this error:

HelloWorld.java:3: error: class Hello is public, should be declared in a file named Hello.java

Hello World Package Version

Package version:

World/Hello.java

package World;

public class Hello {
	public static void main(String args[]) {
		System.out.println("Hello World!\n");
	}
}

Compile and execute:

 javac World/Hello.java
 java World.Hello

Execution Commands

Compile:

java -cp [classpath] [package]\[class].java
java -cp . test.java

Execute:

java -cp [classpath] [package].[class]
java -cp . test

References:

Jar

Build jar:

jar cf jar-file input-files
jar cvf [NAME].jar [file.class] [folder] ...
jar cvf Hi.jar Hello.class

Execute a jar:

java -classpath Program.jar MyMainClass

Auto start main class using a manifest [2] [3]

Build with manifeset:

jar cfm app.jar manifest.txt *.class

manifest.txt:

Main-Class: MyMainClass

Execute:

java -jar app.jar

Compile

Layout:

\doc
\bin
\lib
\src

Compile:

set PATH=%PATH%;"c:\Program Files\Java\jdk1.7.0_17\bin"
C:\dev\risk\riskGamePlayer>  javac  -cp lib\gson-2.2.2.jar  -sourcepath src  -d bin  src\Main.java

Execute:

set PATH=%PATH%;"c:\Program Files\Java\jdk1.7.0_17\bin"
C:\dev\risk\riskGamePlayer>  java   -cp lib\gson-2.2.2.jar;bin  Main

Installation

Java SE JDK

sh jdk-6u25-linux-x64-rpm.bin

Installed to:

/usr/java/jdk1.6.0_25

Path:

export PATH=/usr/java/jdk1.6.0_25/bin:$PATH

Alternative

rpm -Uvh /path/to/binary/jdk-7u55-linux-x64.rpm
alternatives --install /usr/bin/java java /usr/java/latest/jre/bin/java 200000
/usr/sbin/alternatives --display java
/usr/sbin/alternatives --config java

References:

Editors

NetBeans IDE (The Java™ Tutorials > Getting Started > The "Hello World!" Application)]

Code

Comments

The Java programming language supports three kinds of comments: [4]

/* text */
The compiler ignores everything from /* to */.
/** documentation */
This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc, see the JavadocTM tool documentation .
// text
The compiler ignores everything from // to the end of the line.

Import

import java.util.*;	// Data structures (Collections), time, Scanner, etc classes.
import java.io.*;	// Input-output classes.

Print

System.out.print("Hello World");        // does not include new line
System.out.println("Hello World");      // includes new line
System.out.format("Hello %s\n", name);  // format output with format parameters

String

System.out.println("Hello World");
System.out.println("Hello " + "World");
String message = "Hello World";
System.out.println("Message: " + message);

For Each

for (String arg: args) {  System.out.format("Arg: %s", arg); }

Exit

System.exit(0);  // return code of 0
System.exit(1);  // return code of 1

Command Line Arguments

// Programmed by Kenneth Burgener <kenneth@kennethburgener.org> (2012)
public class ArgList {
        public static void main(String args[]) {
                String className = ArgList.class.getName();
                System.out.format("Program: %s\n", className);
                System.out.format("Arg Count: %d\n", args.length);
                if(args.length < 1) {
                        System.out.println("No Arguments");
                }
                for (String arg: args) {
                        System.out.format("Arg: %s\n", arg);
                }
        }
}

References:

Try Catch

try {
...
} catch (ExceptionType name) {
...
} catch (ExceptionType|ExceptionType name) {
...
} finally {
...
}
try {
    firstArg = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
    System.err.println("Argument" + " must be an integer");
    System.exit(1);
    //logger.log(ex);
    //throw ex;
}

System.out.print

System.out.println("enter an integer: ");
System.out.print("enter an integer: \n");
public void sayHello(String message) {
    System.out.println(message);
}

System.in.read

BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
String line=buffer.readLine();
Scanner scan=new Scanner(System.in);

ReadingLine class: http://terokarvinen.com/readline_in_java.html

import java.io.*;
class ReadingLine{
	public static String readLine()
	{
		String s = "";
		try {
			InputStreamReader converter = new InputStreamReader(System.in);
			BufferedReader in = new BufferedReader(converter);
			s = in.readLine();
		} catch (Exception e) {
			System.out.println("Error! Exception: "+e); 
		}
		return s;
	}
	public static void main(String[] args)
	{
		System.out.print("Hello, what's your name? ");
		String name=readLine();
		System.out.println("Hello "+name+"!");
	}
}

Advanced Code

Reflection

Object methodCaller(Object theObject, String methodName) {
    try {
        return theObject.getClass().getMethod(methodName).invoke(theObject);
    } catch (Exception e) {
        System.err.println("Exception caught: " + e);
        System.exit(1);
    }
    return null;
}

// use it
String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");

My example:

public class Test {
	public static void main(String args[]) {
		Test test = new Test();
		test.methodCaller(test, "callme", "test", 1);
	}
	
	public void callme(String message, int number) {
		System.out.println("Message: " + message);
		System.out.println("Number: " + number);
	}
	
	Object methodCaller(Object theObject, String methodName, String message, int number) {
    		try {
        		return theObject.getClass().getMethod(methodName, 
        			String.class, Integer.TYPE).invoke(theObject, message, number);
    		} catch (Exception e) {
        		System.err.println("Exception caught: " + e);
        		System.exit(1);
    		}
    		return null;
	}
}

References:

Callback Method

Callback functions in Java - Stack Overflow - http://stackoverflow.com/questions/443708/callback-functions-in-java

Pass a function as an argument

A common pattern would be to 'wrap' it within an interface, like Callable, for example, then you pass in a Callable:

public T myMethod(Callable<T> func) {
    return func.call();
}

This pattern is known as the Command Pattern.

---

You could use Java reflection to do this. The method would be represented as an instance of java.lang.reflect.Method.

import java.lang.reflect.Method;

public class Demo {

    public static void main(String[] args) throws Exception{
        Class[] parameterTypes = new Class[1];
        parameterTypes[0] = String.class;
        Method method1 = Demo.class.getMethod("method1", parameterTypes);

        Demo demo = new Demo();
        demo.method2(demo, method1, "Hello World");
    }

    public void method1(String message) {
        System.out.println(message);
    }

    public void method2(Object object, Method method, String message) throws Exception {
        Object[] parameters = new Object[1];
        parameters[0] = message;
        method.invoke(object, parameters);
    }

}

---

References:

CLI JUnit

Command Line Interface (CLI) JUnit

//Program: myTestSuite2.java

import junit.framework.*;

public class myTestSuite extends TestCase {

	public static Test suite() {
		TestSuite suite = new TestSuite();
		
		// TEST SUITES
		suite.addTest(myTestSuite2.suite());
		
		// TEST CASES
		suite.addSuite(myTestCase.class);
		
		return suite;
	}
	
	public static void main(String[] args) {
		try {
			Test test = suite();
			junit.text.ui.TestRunner.run(test);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
// myTestCase
import junit.framework.TestCase;
public class myTestCase extends TestCase {
	public void testMyTest() {
		// assert ...
	}
}

to run:

# javac -cp ./:./junit.jar myTestSuite.java
# java -cp ./:./junit.jar myTestSuite

Examples

Read Password

private String readLine(String format, Object... args) throws IOException {
    if (System.console() != null) {
        return System.console().readLine(format, args);
    }
    System.out.print(String.format(format, args));
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            System.in));
    return reader.readLine();
}

private char[] readPassword(String format, Object... args)
        throws IOException {
    if (System.console() != null)
        return System.console().readPassword(format, args);
    return this.readLine(format, args).toCharArray();
}

source: java - System.console() returns null - Stack Overflow - http://stackoverflow.com/questions/4203646/system-console-returns-null

Read Console

import java.util.Scanner;

Scanner in;
in = new Scanner(System.in);
String s = in.nextLine();
in.close();

This works in Eclipse too, where System.console() won't.

List Classes in JAR

You can use Java jar tool. List the content of jar file in a txt file and you can see all the classes in the jar. [5]

jar tvf jarfile.jar

keywords