Hello World
1 2 3 4 5 6 7 8 9 10 11 12 | // Start with the basics, Hello, World! public class MyApp { /* This is my first java program. * This will print 'Hello World' as the output */ public static void main(String []args) { System.out.println("Hello World"); // prints Hello World } } |
Comments
1 2 3 4 5 6 7 8 | // Single line comments count << "Hello, World!" << endl; // Inline comments /* Multi Line Comments */ |
Basic Types
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // Basic Data Types // Primitive byte short int long float double boolean char 'reference' //Not a type, rather a reference to an object // Examples int a, b, c; // Declares three ints, a, b, and c. int a = 10, b = 10; // Example of initialization byte B = 22; // initializes a byte type variable B. double pi = 3.14159; // declares and assigns a value of PI. char a = 'a'; // the char variable a iis initialized with value 'a' String s = "Hello" // Reference object to a string |
Java Literals
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // Java Literals int decimal = 100; int octal = 0144; int hexa = 0x64; char a = '\u0001'; String s1 = "Hello World" String s2 = "two\nlines" String se = "\"This is in quotes\"" // String escape sequences \n // Newline (0x0a) \r // Carriage return (0x0d) \f // Formfeed (0x0c) \b // Backspace (0x08) \s // Space (0x20) \t // tab \" // Double quote \' // Single quote \\ // backslash \ddd // Octal character (ddd) \uxxxx // Hexadecimal UNICODE character (xxxx) |
1 2 3 4 5 6 7 8 9 | // Arithmetic Operators + (Addition) // Adds values on either side of the operator. A + B will give 30 - (Subtraction) // Subtracts right-hand operand from left-hand operand. A - B will give -10 * (Multiplication) // Multiplies values on either side of the operator. A * B will give 200 / (Division) // Divides left-hand operand by right-hand operand. B / A will give 2 % (Modulus) // Divides left-hand operand by right-hand operand and returns remainder. B % A will give 0 ++ (Increment) // Increases the value of operand by 1. B++ gives 21 -- (Decrement) // Decreases the value of operand by 1. B-- gives 19 |
1 2 3 4 5 6 7 8 9 | // Bitwise Operators & (bitwise and) // Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100 | (bitwise or) // Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101 ^ (bitwise XOR) // Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001 ~ (bitwise compliment) // Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number. << (left shift) // Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000 >> (right shift) // Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 1111 >>> (zero fill right shift) // Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. |
1 2 3 4 5 6 7 8 | // Relational Operators == (equal to) // Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != (not equal to) // Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > (greater than) // Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < (less than) // Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= (greater than or equal to) // Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= (less than or equal to) // Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) i |
1 2 3 4 5 | // Logical Operators && (logical and). // Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false || (logical or) // Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. (A || B) is true ! (logical not) // Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Assignment Operators = // Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C += // Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A -= // Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C – A *= // Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand. C *= A is equivalent to C = C * A /= // Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand. C /= A is equivalent to C = C / A %= // Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand. C %= A is equivalent to C = C % A <<= // Left shift AND assignment operator. C <<= 2 is same as C = C << 2 >>= // Right shift AND assignment operator. C >>= 2 is same as C = C >> 2 &= // Bitwise AND assignment operator. C &= 2 is same as C = C & 2 ^= // bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2 |= // bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2 |
1 2 | // Conditional Operator variable x = (expression) ? value if true : value if false |
1 2 | // instanceOf Operator ( Object reference variable ) instanceof (class/interface type) |
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 | // Loops while(Boolean_expression) { // Statements } for(initialization; Boolean_expression; update) { // Statements } do { // Statements }while(Boolean_expression); for(int x : numbers ) { if( x == 30 ) { break; } for(int x : numbers ) { if( x == 30 ) { continue; } for(declaration : expression) { // Statements } int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { do_something(x); } |
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 | // Decision Making if(Boolean_expression) { // Statements will execute if the Boolean expression is true } if(Boolean_expression) { // Executes when the Boolean expression is true }else { // Executes when the Boolean expression is false } if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true } } switch(expression) { case value : // Statements break; // optional case value : // Statements break; // optional // You can have any number of case statements. default : // Optional // Statements } // ? : Operator Exp1 ? Exp2 : Exp3; |
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 | // Numbers Byte Short Integer Long Float Double // Convert to type value byte byteValue() short shortValue() int intValue() long longValue() float floatValue() double doubleValue() // Comparison public int compareTo( NumberSubClass referenceName ) // Equivalent boolean equals(Object o) // Convert to value static Object valueOf(primitive_data_type v) // Convert to String String toString() static String toString(int I) // Convert String to int static int parseInt(String s) static int parseInt(String s, int radix) // Absolute value primitive_data_type Math.abs(primitive_data_type v) // Ceiling, Floor & Rounding double Math.ceil(double d) double Math.ceil(float f) double Math.floor(double d) double Math.floor(float f) double Math.rint(double d) long Math.round(double d) int Math.round(float f) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // Booleans boolean isJavaFun = true; boolean isFishTasty = false; Boolean b = Boolean(iJavaFun) Boolean.parseBoolean("True") // Case ignored, everything else False // Boolean Methods boolean booleanValue() static int compare(boolean x, boolean y) int compareTo(Boolean b) boolean equals(Object obj) static boolean getBoolean(String name) int hashCode() static boolean parseBoolean(String s) String toString() static String toString(boolean b) static Boolean valueOf(boolean b) static Boolean valueOf(String s) |
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 | // Characters char ch = 'a'; // Unicode for uppercase Greek omega character char uniChar = '\u039A'; // an array of chars char[] charArray ={ 'a', 'b', 'c', 'd', 'e' }; Character ch = new Character('a'); // Escape Sequences \t Inserts a tab in the text at this point. \b Inserts a backspace in the text at this point. \n Inserts a newline in the text at this point. \r Inserts a carriage return in the text at this point. \f Inserts a form feed in the text at this point. \' Inserts a single quote character in the text at this point. \" Inserts a double quote character in the text at this point. \\ Inserts a backslash character in the text at this point. // Character Methods isLetter() isDigit() isWhiteSpace() isUpperCase() isLowerCase() toUpperCase() toLowerCase() toString() |
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 | // Strings String greeting = "Hello world!"; // String Methods char charAt(int index) int compareTo(Object o) int compareTo(String anotherString) int compareToIgnoreCase(String str) String concat(String str) boolean contentEquals(StringBuffer sb) static String copyValueOf(char[] data) static String copyValueOf(char[] data, int offset, int count) boolean endsWith(String suffix) boolean equals(Object anObject) boolean equalsIgnoreCase(String anotherString) byte[] getBytes() byte[] getBytes(String charsetName) void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) int hashCode() int indexOf(int ch) int indexOf(int ch, int fromIndex) int indexOf(String str) int indexOf(String str, int fromIndex) String intern() int lastIndexOf(int ch) int lastIndexOf(int ch, int fromIndex) int lastIndexOf(String str) int lastIndexOf(String str, int fromIndex) int length() boolean matches(String regex) boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) boolean regionMatches(int toffset, String other, int ooffset, int len) String replace(char oldChar, char newChar) String replaceAll(String regex, String replacement String replaceFirst(String regex, String replacement) String[] split(String regex) String[] split(String regex, int limit) boolean startsWith(String prefix) boolean startsWith(String prefix, int toffset) CharSequence subSequence(int beginIndex, int endIndex) String substring(int beginIndex) String substring(int beginIndex, int endIndex) char[] toCharArray() String toLowerCase() String toLowerCase(Locale locale) String toString() String toUpperCase() String toUpperCase(Locale locale) String trim() static String valueOf(primitive data type x) |
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 | // Arrays dataType[] arrayRefVar; // preferred way. dataType arrayRefVar[]; // works but not preferred way. arrayRefVar = new dataType[arraySize]; for (int i = 0; i < myList.length; i++) { // do something with myList[i] } for (double element: myList) { // do something with each element } // Reverse an array, passing as argument, receiving as return value public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; } // Sorting & Searching public static int binarySearch(Object[] a, Object key) public static boolean equals(long[] a, long[] a2) public static void fill(int[] a, int val) public static void sort(Object[] a) |
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 | // Date & Time // Constructors Date( ) Date(long millisec) // Current time in millis millis = System.currentTimeMillis(); // Date Methods boolean after(Date date) boolean before(Date date) Object clone( ) int compareTo(Date date) int compareTo(Object obj) boolean equals(Object date) long getTime( ) int hashCode( ) void setTime(long time) String toString( ) // Current Date & Time Date date = new Date(); // Date Comparison date1.getTime() > date2.getTime() new Date(99, 2, 12).before(new Date (99, 2, 18)) // True new Date(99, 2, 12).equals(new Date (99, 2, 12)) // True new Date(99, 2, 12).after(new Date (99, 2, 18)) // False // Date Format Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz"); System.out.println("Current Date: " + ft.format(dNow)); // Date Format Codes Character. Description Example G Era designator AD y Year in four digits 2001 M Month in year July or 07 d Day in month 10 h Hour in A.M./P.M. 12 H Hour in day (0~23) 22 m Minute in hour 30 s Second in minute 55 S Millisecond 234 E Day in week Tuesday D Day in year 360 F Day of week in month. 2 (second Wed. in July) w Week in year 40 W Week in month 1 a A.M./P.M. marker PM k Hour in day (1~24) 24 K Hour in A.M./P.M. 10 z Time zone Eastern Standard Time ' Escape for text Delimiter " Single quote ` // Format using print Date date = new Date(); System.out.printf(String.format("Current Date/Time : %tc", date )); // printf index System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date); // <flag System.out.printf("%s %tB %<te, %<tY", "Due date:", date); // Date Conversion flags c Complete date and time Mon May 04 09:51:52 CDT 2009 F ISO 8601 date 2004-02-09 D U.S. formatted date (month/day/year) 02/09/2004 T 24-hour time 18:05:19 r 12-hour time 06:05:19 pm R 24-hour time, no seconds 18:05 Y Four-digit year (with leading zeroes) 2004 y Last two digits of the year (with leading zeroes) 04 C First two digits of the year (with leading zeroes) 20 B Full month name February b Abbreviated month name Feb m Two-digit month (with leading zeroes) 02 d Two-digit day (with leading zeroes) 03 e Two-digit day (without leading zeroes) 9 A Full weekday name Monday a Abbreviated weekday name Mon j Three-digit day of year (with leading zeroes) 069 H Two-digit hour (with leading zeroes), between 00 and 23 18 k Two-digit hour (without leading zeroes), between 0 and 23 18 I Two-digit hour (with leading zeroes), between 01 and 12 06 l Two-digit hour (without leading zeroes), between 1 and 12 6 M Two-digit minutes (with leading zeroes) 05 S Two-digit seconds (with leading zeroes) 19 L Three-digit milliseconds (with leading zeroes) 047 N Nine-digit nanoseconds (with leading zeroes) 047000000 P Uppercase morning or afternoon marker PM p Lowercase morning or afternoon marker pm z RFC 822 numeric offset from GMT -0800 Z Time zone PST s Seconds since 1970-01-01 00:00:00 GMT 1078884319 Q Milliseconds since 1970-01-01 00:00:00 GMT 1078884319047 // Parsing Strings SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd"); Date t = ft.parse(input); // Gregorian Calendar GregorianCalendar() GregorianCalendar(int year, int month, int date) GregorianCalendar(int year, int month, int date, int hour, int minute) GregorianCalendar(int year, int month, int date, int hour, int minute, int second) |
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 | // Regular Expressions // Groups String line = "This order was placed for QT3000! OK?"; String pattern = "(.*)(\\d+)(.*)"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0) ); System.out.println("Found value: " + m.group(1) ); System.out.println("Found value: " + m.group(2) ); } // lookingAt & matches final String REGEX = "foo"; final String INPUT = "fooooooooooooooooo"; staticPattern pattern; static Matcher matcher; pattern = Pattern.compile(REGEX); matcher = pattern.matcher(INPUT); matcher.lookingAt(); // True, because match exists matcher.matches(); // False, because exact match does not exist // Start & End final String REGEX = "\\bcat\\b"; final String INPUT = "cat cat cat cattie cat"; Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); // get a matcher object while(m.find()) { System.out.println("start(): "+m.start()); System.out.println("end(): "+m.end()); } // Replace static String REGEX = "dog"; static String INPUT = "The dog says meow. " + "All dogs say meow."; static String REPLACE = "cat"; Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); INPUT = m.replaceAll(REPLACE); // Regular Expression Syntax ^ // Matches the beginning of the line. $ // Matches the end of the line. . // Matches any single character except newline. Using m option allows it to match the newline as well. [...] // Matches any single character in brackets. [^...] // Matches any single character not in brackets. \A // Beginning of the entire string. \z // End of the entire string. \Z // End of the entire string except allowable final line terminator. re* // Matches 0 or more occurrences of the preceding expression. re+ // Matches 1 or more of the previous thing. re? // Matches 0 or 1 occurrence of the preceding expression. re{n} // Matches exactly n number of occurrences of the preceding expression. re{n,} // Matches n or more occurrences of the preceding expression. re{n, m} // Matches at least n and at most m occurrences of the preceding expression. a| b // Matches either a or b. (re) // Groups regular expressions and remembers the matched text. (?: re) // Groups regular expressions without remembering the matched text. (?> re) // Matches the independent pattern without backtracking. \w // Matches the word characters. \W // Matches the nonword characters. \s // Matches the whitespace. Equivalent to [\t\n\r\f]. \S // Matches the nonwhitespace. \d // Matches the digits. Equivalent to [0-9]. \D // Matches the nondigits. \A // Matches the beginning of the string. \Z // Matches the end of the string. If a newline exists, it matches just before newline. \z // Matches the end of the string. \G // Matches the point where the last match finished. \n // Back-reference to capture group number "n". \b // Matches the word boundaries when outside the brackets. Matches the backspace (0x08) when inside the brackets. \B // Matches the nonword boundaries. \n, \t, // Matches newlines, carriage returns, tabs, etc. \Q // Escape (quote) all characters up to \E. \E // Ends quoting begun with \Q. |
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 | // Objects & Classes public class MyClass { int theAnswer; public MyClass () { // Default Constructor this.theAnswer = 42 } public MyClass (int value) { // Constructor this.theAnswer = value; } public int getTheAnswer() { return this.theAnswer; } protected void finalize( ) { // Clean up before destroying // finalization code here } } MyClass myClass = new MyClass() myClass.getTheAnswer() == 42 MyClass myClass2 = new MyClass(32) myClass.getTheAnswer() == 32 // Application Class public class MyApplication { public static void main(String args[]) { // Run you application here } } |
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 | // Methods modifier returnType nameOfMethod (Parameter List) { // method body } // Modifiers public protected private static // Return Types int doSomething( String arg ) // Returns an int // Void void doSomething( String arg ) // returns nothing // Parameters void doSomething( String arg ) void doSomething( final String arg ) // Stops reassignment of parameter // Method Overloading public class ExampleOverloading { public static void main(String[] args) { int result1 = minFunction(a, b); double result2 = minFunction(c, d); } // for integer public static int minFunction(int n1, int n2) { : } // for double public static double minFunction(double n1, double n2) { : } // Variable Parameters printMax(34, 3, 3, 2, 56.5); printMax(new double[]{1, 2, 3}); public static void printMax( double... numbers) { if (numbers.length == 0) { System.out.println("No argument passed"); return; } double result = numbers[0]; for (int i = 1; i < numbers.length; i++) if (numbers[i] > result) result = numbers[i]; System.out.println("The max value is " + result); } } |
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 | // Nested Classes class Outer_Demo { class Inner_Demo { } } // Inner Classes ( Non static ) class Outer_Demo { int num; // inner class private class Inner_Demo { public void print() { System.out.println("This is an inner class"); } } // Accessing he inner class from the method within void display_Inner() { Inner_Demo inner = new Inner_Demo(); inner.print(); } } public class My_class { public static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); // Accessing the display_Inner() method. outer.display_Inner(); } } // Aonymous Inner Classes AnonymousInner an_inner = new AnonymousInner() { public void my_method() { ........ ........ } }; // Static Inner Classes class MyOuter { static class Nested_Demo { } } public class Outer { static class Nested_Demo { public void my_method() { System.out.println("This is my nested class"); } } public static void main(String args[]) { Outer.Nested_Demo nested = new Outer.Nested_Demo(); nested.my_method(); } } |
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 | // Inheritance // Basic Inheritance class Super { ..... ..... } class Sub extends Super { ..... ..... } // super keyword // It is used to differentiate the members of superclass from the members of subclass, if they have same names. // It is used to invoke the superclass constructor from subclass. class Super { Super (int value) { // Do Something } void do_something () { } void do_something_else () { } } class Sub extends Super { Sub(int value1, int value2) { super(value1); // Invokes super class constructor // Do something } void do_something_else() {
super.do_something_else(); // Base class first do_something_else(); // Then sub class method } Sub mySub = new Sub(1, 2); mySub.do_something_else(); // Is_A Relationship public class Animal { } public class Mammal extends Animal { } public class Reptile extends Animal { } public class Dog extends Mammal { } Animal dog = new Dog (); Animal reptile = new Reptile (); // InstanceOf keyword System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); // Has_A Relationship public class Vehicle{} public class Speed{} public class Van extends Vehicle { private Speed sp; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // Overiding class MyBaseClass { public void do_something () { // Doing something } } class MyDerivedClass { public void do_something () { // Doing something different } } MyBaseClass myBase = MyBaseClass(); MyDerivedClass myDerived = MyDerivedClass(); myDerived.doSomething(); // Calls the derived class method |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // Polymorphism class MyBaseClass { public void do_something () { // Doing something } } class MyDerivedClass { public void do_something () { // Doing something different } } MyBaseClass myDerived1 = MyDerivedClass(); // Treat as Base Class MyBaseClass myDerived1 = MyDerivedClass(); // Treat as Base Class myDerived1.doSomething(); // Behaves as derived class myDerived2.doSomething(); // Behaves as derived class |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // Abstraction public abstract class MyAbstractClass { MyAbstractClass () { } public abstract double computeValue(); } public class MyConcreteClass { MyConcreteClass () { super(); } public double computeValue() {
// Computer value } } MyAbstractClass class1 = new MyAbstractClass(); // Compiler error MyConcreteClass class2 = new MyConcreteClass(); // Ok class2.computeValue(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | // Encapsulation public class MyEncapsulatedClass () { private int val1; // Private variables only vis within class private double val2; MyEncapsulatedClass () { } public void set val1(int val) this.val1 = val } public int getVal1() { return this.val1 } public void set val2(double val) this.val2 = val } public double getVal2() { return this.val2 } } |
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 | // Interfaces public interface NameOfInterface { // Any number of final, static fields // Any number of abstract method declarations\ } interface MyInterface { public void method1 (); public void method2 (); } public class MyClass implements MyInterface { public MyInterface() { } public void method1 () { // } public void method2 () { // } } // Extending interface interface MyInterface { public void method1 (); public void method2 (); } interface MyInterface2 extends MyInterface { public void method3 (); public void method4 (); } // Extending Multiple Interfaces interface MyInterface { public void method1 (); public void method2 (); } interface MyInterface2 { public void method3 (); public void method4 (); } public class MyClass implements MyInterface, MyInterface2 { } |
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 | // Packages javac -d Destination_folder file_name.java // In file Important.java package important; public class VeryImportant { } // In file UseImportant.java package important public class Work extends VeryImportant { } // After compilation these class will be placed in .\important\VeryImportant.class .\important\Work.class // Importing Packages import important.*. // Either import important.Work // Or of these 2 class MoreWork extends Work { } |
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 | // Exceptions try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block } finally { // Optional } // Catchmultiple exceptions try { } catch (IOException|FileNotFoundException ex) { } // Methods throw exceptions public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } // Try With try(FileReader fr = new FileReader("file path")) { // use the resource } catch () { // body of catch } } // Exception Methods public String getMessage() // Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. public Throwable getCause() // Returns the cause of the exception as represented by a Throwable object. public String toString() // Returns the name of the class concatenated with the result of getMessage(). public void printStackTrace() // Prints the result of toString() along with the stack trace to System.err, the error output stream. public StackTraceElement [] getStackTrace() // Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. public Throwable fillInStackTrace() // Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. |
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 | // Data Structures // Enumeration import java.util.Vector; import java.util.Enumeration; Enumeration days; Vector dayNames = new Vector(); dayNames.add("Sunday"); dayNames.add("Monday"); dayNames.add("Tuesday"); dayNames.add("Wednesday"); dayNames.add("Thursday"); dayNames.add("Friday"); dayNames.add("Saturday"); days = dayNames.elements(); while (days.hasMoreElements()) { System.out.println(days.nextElement()); } // BitSet import java.util.BitSet; BitSet bits1 = new BitSet(16); BitSet bits2 = new BitSet(16); // set some bits for(int i = 0; i < 16; i++) { if((i % 2) == 0) bits1.set(i); if((i % 5) != 0) bits2.set(i); } System.out.println(bits1); System.out.println(bits2); bits2.and(bits1); bits2.or(bits1); bits2.xor(bits1); // Vector Vector v = new Vector(3, 2); v.addElement(new Integer(1)); v.addElement(new Integer(2)); v.addElement(new Integer(3)); if(v.contains(new Integer(3))) System.out.println("Vector contains 3."); Enumeration vEnum = v.elements(); System.out.println("\nElements in vector:"); while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement() + " "); // Stack Stack st = new Stack(); // [] st.push(st, 1); // [1] st.push(st, 2); // [1,2] st.push(st, 3); // [1, 2, 3] st.pop(); // [1, 2] st.pop(); // [1] st.pop(); // [] // Hashtable Hashtable balance = new Hashtable(); Enumeration names; String str; double bal; balance.put("Zara", new Double(3434.34)); balance.put("Mahnaz", new Double(123.22)); balance.put("Ayan", new Double(1378.00)); balance.put("Daisy", new Double(99.22)); balance.put("Qadir", new Double(-19.08)); // Show all balances in hash table. names = balance.keys(); while(names.hasMoreElements()) { str = (String) names.nextElement(); System.out.println(str + ": " + balance.get(str)); } // Properties Properties capitals = new Properties(); Set states; String str; capitals.put("Illinois", "Springfield"); capitals.put("Missouri", "Jefferson City"); capitals.put("Washington", "Olympia"); capitals.put("California", "Sacramento"); capitals.put("Indiana", "Indianapolis"); // Show all states and capitals in hashtable. states = capitals.keySet(); // get set-view of keys Iterator itr = states.iterator(); while(itr.hasNext()) { str = (String) itr.next(); System.out.println("The capital of " + str + " is " + capitals.getProperty(str) + "."); } System.out.println(); // look for state not in list -- specify default str = capitals.getProperty("Florida", "Not Found"); System.out.println("The capital of Florida is " + str + "."); |
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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | // Collections /* Non generic collections hold elements of different datatypes, it hold all elements as object type. so it includes overhead of implicit and explicit conversions. There can be runtime errors */ // LinkedList LinkedList ll = new LinkedList(); // add elements to the linked list ll.add("F"); ll.add("B"); ll.add("D"); ll.add("E"); ll.add("C"); ll.addLast("Z"); ll.addFirst("A"); ll.add(1, "A2"); System.out.println("Original contents of ll: " + ll); // remove elements from the linked list ll.remove("F"); ll.remove(2); System.out.println("Contents of ll after deletion: " + ll); // remove first and last elements ll.removeFirst(); ll.removeLast(); System.out.println("ll after deleting first and last: " + ll); // get and set a value Object val = ll.get(2); ll.set(2, (String) val + " Changed"); // ArrayList ArrayList al = new ArrayList(); System.out.println("Initial size of al: " + al.size()); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " + al.size()); // display the array list System.out.println("Contents of al: " + al); // Remove elements from the array list al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); // HashSet HashSet hs = new HashSet(); // add elements to the hash set hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); // LinkedHashSet LinkedHashSet hs = new LinkedHashSet(); // add elements to the hash set hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); System.out.println(hs); // TreeSet TreeSet ts = new TreeSet(); // Add elements to the tree set ts.add("C"); ts.add("A"); ts.add("B"); ts.add("E"); ts.add("F"); ts.add("D"); // HashMap HashMap hm = new HashMap(); // Put elements to the map hm.put("Zara", new Double(3434.34)); hm.put("Mahnaz", new Double(123.22)); hm.put("Ayan", new Double(1378.00)); hm.put("Daisy", new Double(99.22)); hm.put("Qadir", new Double(-19.08)); // Get a set of the entries Set set = hm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } // TreeMap TreeMap tm = new TreeMap(); // Put elements to the map tm.put("Zara", new Double(3434.34)); tm.put("Mahnaz", new Double(123.22)); tm.put("Ayan", new Double(1378.00)); tm.put("Daisy", new Double(99.22)); tm.put("Qadir", new Double(-19.08)); // Get a set of the entries Set set = tm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } // WeakHashMap private static Map map; public static void main (String args[]) { map = new WeakHashMap(); map.put(new String("Maine"), "Augusta"); // LinkedHashMap // Create a hash map LinkedHashMap lhm = new LinkedHashMap(); // Put elements to the map lhm.put("Zara", new Double(3434.34)); lhm.put("Mahnaz", new Double(123.22)); lhm.put("Ayan", new Double(1378.00)); lhm.put("Daisy", new Double(99.22)); lhm.put("Qadir", new Double(-19.08)); // Get a set of the entries Set set = lhm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } // IdentityHashMap // Create a hash map IdentityHashMap ihm = new IdentityHashMap(); // Put elements to the map ihm.put("Zara", new Double(3434.34)); ihm.put("Mahnaz", new Double(123.22)); ihm.put("Ayan", new Double(1378.00)); ihm.put("Daisy", new Double(99.22)); ihm.put("Qadir", new Double(-19.08)); // Get a set of the entries Set set = ihm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } // Comparators import java.util.*; class Dog implements Comparator<Dog>, Comparable<Dog> { private String name; private int age; Dog() { } Dog(String n, int a) { name = n; age = a; } // Overriding the compareTo method public int compareTo(Dog d) { return (this.name).compareTo(d.name); } // Overriding the compare method to sort the age public int compare(Dog d, Dog d1) { return d.age - d1.age; } } public class Example { public static void main(String args[]) { // Takes a list o Dog objects List<Dog> list = new ArrayList<Dog>(); list.add(new Dog("Shaggy", 3)); list.add(new Dog("Lacy", 2)); list.add(new Dog("Roger", 10)); list.add(new Dog("Tommy", 4)); list.add(new Dog("Tammy", 1)); Collections.sort(list); // Sorts the array list // Sorts the array list using comparator Collections.sort(list, new Dog()); System.out.println(" "); } } // Algorithims static int binarySearch(List list, Object value, Comparator c) static int binarySearch(List list, Object value) static void copy(List list1, List list2) static Enumeration enumeration(Collection c) static void fill(List list, Object obj) static int indexOfSubList(List list, List subList) static int lastIndexOfSubList(List list, List subList) static ArrayList list(Enumeration enum) static Object max(Collection c, Comparator comp) static Object max(Collection c) static Object min(Collection c, Comparator comp) static Object min(Collection c) static List nCopies(int num, Object obj) static boolean replaceAll(List list, Object old, Object new) static void reverse(List list) static Comparator reverseOrder( ) static void rotate(List list, int n) static void shuffle(List list, Random r) static void shuffle(List list) static Set singleton(Object obj) static List singletonList(Object obj) static Map singletonMap(Object k, Object v) static void sort(List list, Comparator comp) static void sort(List list) static void swap(List list, int idx1, int idx2) static Collection synchronizedCollection(Collection c) static List synchronizedList(List list) static Map synchronizedMap(Map m) static Set synchronizedSet(Set s) static SortedMap synchronizedSortedMap(SortedMap sm) static SortedSet synchronizedSortedSet(SortedSet ss) static Collection unmodifiableCollection(Collection c) static List unmodifiableList(List list) static Map unmodifiableMap(Map m) static Set unmodifiableSet(Set s) static SortedMap unmodifiableSortedMap(SortedMap sm) static SortedSet unmodifiableSortedSet(SortedSet ss) |
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 | // Generics /* Generic collections - These are the collections that can hold data of same type and we can decide while initializing what type of data that collections can hold. Advantages - Type Safe, Secure, reduced overhead of implicit and explicit conversions. */ // Generic Methods public class GenericMethodTest { // generic method printArray public static < E > void printArray( E[] inputArray ) { // Display array elements for(E element : inputArray) { System.out.printf("%s ", element); } System.out.println(); } public static void main(String args[]) { // Create arrays of Integer, Double and Character Integer[] intArray = { 1, 2, 3, 4, 5 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println("Array integerArray contains:"); printArray(intArray); // pass an Integer array System.out.println("\nArray doubleArray contains:"); printArray(doubleArray); // pass a Double array System.out.println("\nArray characterArray contains:"); printArray(charArray); // pass a Character array } } // Bounded Types public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // assume x is initially the largest if(y.compareTo(max) > 0) { max = y; // y is the largest so far } if(z.compareTo(max) > 0) { max = z; // z is the largest now } return max; // returns the largest object } public static void main(String args[]) { System.out.printf("Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum( 3, 4, 5 )); System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 )); System.out.printf("Max of %s, %s and %s is %s\n","pear", "apple", "orange", maximum("pear", "apple", "orange")); } } // Generic Classes public class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); Box<String> stringBox = new Box<String>(); integerBox.add(new Integer(10)); stringBox.add(new String("Hello World")); System.out.printf("Integer Value :%d\n\n", integerBox.get()); System.out.printf("String Value :%s\n", stringBox.get()); } } |
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 | // File I/O // Byte Streams import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } // Character Streams import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } // Standard Streams Standard Input − This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in. Standard Output − This is used to output the data produced by the user's program and usually a computer screen is used for standard output stream and represented as System.out. Standard Error − This is used to output the error data produced by the user's program and usually a computer screen is used for standard error stream and represented as System.err. import java.io.*; public class ReadConsole { public static void main(String args[]) throws IOException { InputStreamReader cin = null; try { cin = new InputStreamReader(System.in); System.out.println("Enter characters, 'q' to quit."); char c; do { c = (char) cin.read(); System.out.print(c); } while(c != 'q'); }finally { if (cin != null) { cin.close(); } } } } // InputStream & OutputStream import java.io.*; public class fileStreamTest { public static void main(String args[]) { try { byte bWrite [] = {11,21,3,40,5}; OutputStream os = new FileOutputStream("test.txt"); for(int x = 0; x < bWrite.length ; x++) { os.write( bWrite[x] ); // writes the bytes } os.close(); InputStream is = new FileInputStream("test.txt"); int size = is.available(); for(int i = 0; i < size; i++) { System.out.print((char)is.read() + " "); } is.close(); } catch (IOException e) { System.out.print("Exception"); } } } // Directories // Make a Director String dirname = "/tmp/user/java/bin"; File d = new File(dirname); d.mkdirs(); // List files & directories File file = new File("/tmp"); // array of files and directory paths = file.list(); // for each name in the path array for(String path:paths) { // prints filename and directory name System.out.println(path) } |
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 | // Serialization public class Employee implements java.io.Serializable { public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println("Mailing a check to " + name + " " + address); } } import java.io.*; public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = "Reyan Ali"; e.address = "Phokka Kuan, Ambehta Peer"; e.SSN = 11122333; e.number = 101; try { FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in /tmp/employee.ser"); } catch (IOException i) { i.printStackTrace(); } } } import java.io.*; public class DeserializeDemo { public static void main(String [] args) { Employee e = null; try { FileInputStream fileIn = new FileInputStream("/tmp/employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return; } System.out.println("Deserialized Employee..."); System.out.println("Name: " + e.name); System.out.println("Address: " + e.address); System.out.println("SSN: " + e.SSN); System.out.println("Number: " + e.number); } } |