This page contains basic beginner and more advanced Java snippets; the purpose of this page is for those who are learning and like to learn via pure code as well as a location for mpettersson to keep snippets and Java related links. This pages subsections are:
Java 101
Miscellaneous Java Code
Java Resources
As always, please contact us with comments, concerns, questions, etc. about Java!
Java 101
For the complete set of Java development tools, such as the Java compiler, download the JDK from the Standard Edition (SE) Java download page. For the Java SE documentation, such as tutorials, visit Oracle’s documentation page. For an Integrated Development Environment (IDE) checkout Eclipse or NetBeans.
Keywords
abstract | assert | boolean | break | byte | case |
catch | char | class | const | continue | default |
do | double | else | enum | extends | final |
finally | float | for | goto | if | implements |
import | instanceof | int | interface | long | native |
new | package | private | protected | public | return |
short | static | strictfp | super | switch | synchronized |
this | throw | throws | transient | try | void |
volatile | while |
The first snippet, Java101.java, is complete Java source file which demonstrates the Java basics.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.List; public class Java101 { private static List list; public static final int SIZE = 10; public static void main(String[] args) { // A single line comment. /* * A multiline comment */ char aChar = 'c'; char anotherChar = '\u0101'; String aString = "How to declare a string."; boolean trueValue = true; boolean falseValue = false; int anInteger = -1; float aFloat = .0025f; double aDouble = 2.1415; short aShort = 12; long aLong = 100000000; byte aByte = 0x0; int[] intArray = new int[10]; System.out.println("How to print to standard out a variable: " + aString); if (trueValue) { System.out.println("The flag is true."); } if (!trueValue) { System.out.println("This will not be printed."); } else { System.out.println("The flag is false."); } while (anInteger < 5) { anInteger++; } do { System.out.println("This will always be printed once."); } while (falseValue); for (int x = 0; x < 10; x++) { intArray[x] = x; } for (int x : intArray) { System.out.print(x); } int someIntVar = 4; switch (someIntVar) { case 1: aString = "January"; break; case 2: aString = "February"; break; case 3: aString = "March"; break; case 4: aString = "April"; break; case 5: aString = "May"; break; case 6: aString = "June"; break; case 7: aString = "July"; break; case 8: aString = "August"; break; case 9: aString = "September"; break; case 10: aString = "October"; break; case 11: aString = "November"; break; case 12: aString = "December"; break; default: aString = "Invalid month"; break; } aMethod(trueValue, aByte, aFloat, aDouble); System.exit(0); } public static void aMethod(boolean trueValue, byte aByte, float aFloat,double aDouble) { PrintWriter out = null; try { System.out.println("Entered try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) { out.println("Value at: " + i + " = " + list.get(i)); } throw new Exception(); } catch (IndexOutOfBoundsException | IOException e) { System.err.println("IndexOutOfBoundsException or IOException: " + e.getMessage()); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } } } } |
Use javac to compile java source (i.e., “javac Java101.java”) and java to run compiled source (i.e., “java Java101”). The next snippet contains commonly used basic calls.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
String aString = "Some String"; aString.contains("Some"); aString.equals("Some String"); aString.equalsIgnoreCase("SoME sTRing"); String stringArraySplitOnLines[] = someOtherString.split("[\\r\\n]+"); String stringArraySplitOnSpaces[] = someOtherString.split("\\s+"); System.out.println("KB: " + (double) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024); System.runFinalization(); System.gc(); String[] words = instring.replaceAll("[^a-zA-Z0-9 ]", "").toLowerCase().split("\\s+"); Random rand = new Random(); int randomNum = rand.nextInt((max - min) + 1) + min; String completeFileName = "/Path/To/A/File.java";; System.out.println(completeFileName); String directoryNameOnly = completeFileName.substring(0, completeFileName.lastIndexOf("/") + 1); System.out.println(directoryNameOnly); String fileNameOnly = completeFileName.substring(completeFileName.lastIndexOf("/") + 1); System.out.println(fileNameOnly); InetAddress inet = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }); System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable"); InetAddress address = InetAddress.getByName("www.yahoo.com"); System.out.println(address.getHostAddress()); InetAddress[] ipAddress = DNSNameService.lookupAllHostAddr("hostName"); DateFormat dateFormat0 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); System.out.println(dateFormat0.format(date)); DateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); System.out.println(dateFormat1.format(cal.getTime())); String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println(timeStamp); |
Miscellaneous Java Code
This section contains random Java snippets and source code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.HashMap; import java.util.Set; import java.util.Map; import java.util.TreeMap; import java.util.Iterator; class MapExample { public static void main(String[] args) { System.out.println("Using HashMap:"); HashMap<String, String> hm = new HashMap<String, String>(); hm.put("3", "three"); hm.put("1", "one"); hm.put("4", "four"); hm.put("2", "two"); printMap(hm); System.out.println("Using TreeMap:"); Map<String, String> treeMap = new TreeMap<String, String>(hm); printMap(treeMap); System.exit(0); } public static void printMap(Map<String, String> map) { Set s = map.entrySet(); Iterator it = s.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); System.out.println(key + " => " + value); } return; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public class SftpExample { public static void main(String[] args){ String remoteHost = "host||IP"; int port = 22; String remoteUsername = "username"; String remotePassword = "password"; String remoteDirectory = "/remote/directory/"; String remoteFileName = "remote.file"; String localFileName = "local.file"; String localDirectory = "C:/local/directory/"; System.out.println("Try to copy " + remoteDirectory + remoteFileName + " on " + remoteHost + " to " + localDirectory + localFileName + " on 127.0.0.1." ); System.out.println(copyToLocalMachine(remoteHost, port, remoteUsername, remotePassword, remoteDirectory, remoteFileName, localDirectory, localFileName) ? "Copy file to local machine worked!" : "Rubbish! Copy to local machine failed..."); localFileName = "anotherLocal.file"; remoteFileName = "anotherRemote.file"; System.out.println("Try to copy " + localDirectory + localFileName + " from 127.0.0.1 to " + remoteDirectory + remoteFileName + " on " + remoteHost + "." ); System.out.println(copyToRemoteMachine(remoteHost, port, remoteUsername, remotePassword, remoteDirectory, remoteFileName, localDirectory, localFileName) ? "Copy file to remote machine worked!" : "Aww Nawww, copy to remote machine failed..."); System.exit(0); } public static boolean copyToRemoteMachine(String remoteHost, int port, String remoteUsername, String remotePassword, String remoteDirectory, String remoteFileName, String localDirectory, String localFileName) { boolean result = true; Session session = null; Channel channel = null; ChannelSftp channelSftp = null; try { JSch jsch = new JSch(); session = jsch.getSession(remoteUsername, remoteHost, port); session.setPassword(remotePassword); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); channel = session.openChannel("sftp"); channel.connect(); channelSftp = (ChannelSftp) channel; channelSftp.cd(remoteDirectory); File f = new File(localDirectory + localFileName); channelSftp.put(new FileInputStream(f), remoteFileName); }catch(Exception e) { System.out.println("O Bother! copyToRemoteMachine caught an Exception: " + e.getMessage()); result = false; }finally{ channelSftp.exit(); channel.disconnect(); session.disconnect(); } return result; } public static boolean copyToLocalMachine(String host, int port, String username, String password, String remoteDirectory, String remoteFileName, String localDirectory, String localFileName) { boolean result = true; Session session = null; Channel channel = null; ChannelSftp channelSftp = null; try { JSch jsch = new JSch(); session = jsch.getSession(username, host, port); session.setPassword(password); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); channel = session.openChannel("sftp"); channel.connect(); channelSftp = (ChannelSftp) channel; channelSftp.cd(remoteDirectory); File localFile = new File(localDirectory + localFileName); FileOutputStream fos = new FileOutputStream(localFile); channelSftp.get(remoteFileName, fos); fos.close(); }catch(Exception e) { System.out.println("O Nooo! copyToLocalMachine caught an Exception: " + e.getMessage()); result = false; }finally{ channelSftp.exit(); channel.disconnect(); session.disconnect(); } return result; } } |
The next snippet is a simple program to replace specified text in a file with some other specified text.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class ReplaceTextInFiles { public static void replaceTextInFile(String directory, String fileName, String target, String replacement){ String line = null; BufferedReader br = null; FileReader reader = null; PrintWriter writer = null; try { writer = new PrintWriter(new BufferedWriter(new FileWriter(directory + fileName + ".temp"))); reader = new FileReader(directory + fileName); br = new BufferedReader(reader); while ((line = br.readLine()) != null) { if (line.contains(target)){ line = line.replace(target, replacement); } writer.println(line); } }catch(FileNotFoundException e){ System.out.println("Crikey! replaceTextInFile caught a FileNotFoundException: " + e.getMessage()); }catch(IOException e) { System.out.println("Fiddlesticks! replaceTextInFile caught an IOException: " + e.getMessage()); }finally{ try { if(writer != null){ writer.close(); } if(reader != null){ reader.close(); } }catch(IOException e){ System.out.println("Holy Schnikies! replaceTextInFile caught an IOException: " + e.getMessage()); } File realName = new File(directory + fileName); realName.delete(); new File(directory + fileName + ".temp").renameTo(realName); } } public static void main(String[] args) { String directory = "C:/the/directory/the/files/are/in/"; File path = new File(directory); File [] files = path.listFiles(); for (int i = 0; i < files.length; i++){ if (files[i].isFile()){ System.out.println("File: " + files[i].getName()); String target = "The targeted text."; String replacement = "The replacement text."; replaceTextInFile(directory, files[i].getName(), target, replacement); } } } } |
Java Resources
Java Interview Questions and Answers – List of must-know (Java) concepts, rules, and principles.
Programming Methodology – A Stanford Java-based course on the fundamentals of programming.
ExpectIt – Yet another expect for Java.
log4j – Java-based logging utility.
TestNG – A testing framework inspired from JUnit and NUnit, but wait, there’s more…
JUnit – A framework to write repeatable tests, an instance of the xUnit architecture.
JUnit Cookbook – A cookbook for writing and organizing tests using JUnit.
JSch – A pure Java implementation of SSH2.
Apache Commons Codec – Encoders and decoders; such as Base64, Hex, Phonetic and URLs.