Java SE Notes

Basics

	// Array Declarations

	int arr[]; // 1D Array
	int []arr; // 1D Array
	int[] arr; // 1D Array

	int[] []arr1, arr2[]; // 2D Array
	int[] []arr3, arr4[][]; // 3D Array
	javac -source 1.4 filename.java // 1.4 version compiler

	javac -source 1.5 filename.java // 1.5 version compiler

OOPS

	// Array of references

	public abstract class AbsClass {

	}

	interface Interface {

	}

	public class Main {
		public static void main(String args[]) {
			AbsClass[] absRef = new AbsClass[10]; // Array of references to abstract class
			Interface[] intRef = new Interface[10]; // Array of references to interface
		}
	}
	// Method overloading special behaviour w.r.t. inheritance

	class Parent {

	}

	class Child extends Parent {

	}

	class GrandChild extends Child {

	}

	class GreatGrandChild extends GrandChild {

	}

	class Test {
		public void meth(Parent p) {
			System.out.println("Parent-arg");
		}

		public void meth(Child c) {
			System.out.println("Child-arg");
		}

		public static void main(String[] args) {
			Test t = new Test();

			t.meth(new Parent()); // Parent-arg

			t.meth(new Child()); // Child-arg

			t.meth(new GrandChild()); // Child-arg

			t.meth(new GreatGrandChild()); // Child-arg
		}
	}
	// This program will not compile

	public class Test {
		public void meth(String s) {
			System.out.println("String version");
		}

		public void meth(StringBuffer s) {
			System.out.println("StringBuffer version");
		}

		public static void main(String[] args) {
			Test t = new Test();

			t.meth("Hello"); // String version

			t.meth(new StringBuffer("Hi")); // StringBuffer version

			t.meth(null); // Compile-time error
		}
	}

Packages & Exception Handling

	// How implicit import statements reduce readability

	import com.hdfc.*; // import com.hdfc.Account;
	import com.icici.*; // import com.icici.Loan;

	class Demo {
		Account a = new Account(); // It is not clear these classes
		Loan l = new Loan();      // belongs to which package
	}

Multithreading

	// Setting the thread priority using constant fields

	t1.setPriority(NORM_PRIORITY+2); // extending Thread class
	t1.getPriority(); // 7

	t2.setPriority(Thread.MAX_PRIORITY-3); // implementing the Runnable interface
	t2.getPriority(); // 7

Inner Classes

	// Aceesing private members of inner class in outer class

	class Outer {
		private int x = 10;

		class Inner {
			private int y = 20;
			public void meth() {
				x = 100;
				System.out.println(x); // 100
			}
		}

		public void display() {
			Inner i = new Inner();
			i.meth();
			i.y = 200;
			System.out.println(i.y); // 200
			System.out.println(y); // Invalid
		}
	}

	class Test {
		public static void main(String[] args) {
			Outer o = new Outer();
			o.display();
		}
	}
	// Creating Inner class object outside the outer class

	class Outer {
		private int x = 10;
		private static int y = 20;

		class Inner1 {
			public void display_x() {
				System.out.println(x);
			}
		}

		static class Inner2 {
			public void display_y() {
				System.out.println(y);
			}
		}
	}

	class Test {
		public static void main(String[] args) {
			Outer o = new Outer();
			Outer.Inner1 i = o.new Inner1();

			Outer.Inner1 i1 = new Outer().new Inner1();
			i1.display_x();

			Outer.Inner2 i2 = new Outer.Inner2();
			i2.display_y();
		}
	}

Java.lang Package

	// Enum constants creation w.r.t. constructors

	enum Fruit {
		Apple(100), Banana(60), Orange(80), Guava;

		protected int price;

		private Fruit() {
			price = -1;
			System.out.println("Non Parameterized Constructor Called");
		}

		private Fruit(int price) {
			this.price = price;
			System.out.println("Parameterized Constructor Called");
		}

		public int getPrice() {
			return price;
		}
	}

	class Test {
		public static void main(String[] args) {
			for(Fruit f : Fruit.values()){
				System.out.println(f.getPrice());
			}
		}
	}
	// Order of execution in enums

	enum Fruit {
		Apple, Banana, Orange, Guava;

		static {
			System.out.println("Static block called");
		}

		{
			System.out.println("Instance block called");
		}

		private Fruit() {
			System.out.println("Constructor called");
		}

		public static void main(String[] args) {
			Fruit f1 = Fruit.Apple;
		}
	}
	// 3 Ways to obtain a Class object

	import java.lang.reflect.*;

	class Demo {
        private int a;

        public Demo() {
	        // logic
        }

        public void meth() {
	        // logic
        }
}

	class Test {
        public static void main(String[] args) throws Exception {
            Class clz = Class.forName("Demo");

            Field[] fld = clz.getDeclaredFields(); // method 1
            for (Field f: fld) {
                 System.out.println(clz.getName() + " : : " + f);
            }

            clz = Demo.class; // Method 2
            Method[] meth = clz.getDeclaredMethods();
            for (Method m: meth) {
                 System.out.println(clz.getName() + " : : " + m);


            Demo d = new Demo();
            clz = d.getClass(); // Method 3
            Constructor[] con = clz.getDeclaredConstructors();
            for (Constructor c: con) {
                System.out.println(clz.getName() + " : : " + c);
            }
        }
    }

Files & IO Streams

	// Use of available method

	import java.io.FileInputStream;

	class Test {
	    public static void main(String[] args) {
	        try (FileInputStream fis = new FileInputStream("Test.txt")) {
	            byte[] b = new byte[fis.available()];
	            fis.read(b);
	            String str = new String(b);
	            System.out.println(str);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	}
	// Use of SequenceInputStream

	import java.io.FileInputStream;
	import java.io.FileOutputStream;
	import java.io.SequenceInputStream;

	class Test {
	    public static void main(String[] args) throws Exception {
	        FileInputStream fis1 = new FileInputStream("Demo.txt");
	        FileInputStream fis2 = new FileInputStream("Test.txt");

	        SequenceInputStream sis = new SequenceInputStream(fis1, fis2);

	        FileOutputStream fos = new FileOutputStream("Des.txt");

	        byte[] b = new byte[sis.available()];
	        sis.read(b);
	        fos.write(b);
	        sis.read(b);
	        fos.write(b);

	        fos.flush();
	        fos.close();
	        sis.close();
	        fis1.close();
	        fis2.close();
    }
}
	// Marking and resetting bytes in buffered input streams

	import java.io.*;

	class Test {
	    public static void main(String[] args) throws Exception {
	        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("Test.txt"));
	        System.out.println(bis.markSupported());

	        System.out.println((char) bis.read());
	        System.out.println((char) bis.read());
	        System.out.println((char) bis.read());

	        bis.mark(3);

	        System.out.println((char) bis.read());
	        System.out.println((char) bis.read());

	        bis.reset();

	        System.out.println((char) bis.read());
	        System.out.println((char) bis.read());
	    }
	}
	// Use of Piped Input/Output Stream

	import java.io.*;

	class Test {
	    public static void main(String[] args) throws IOException {
	        PipedInputStream pis = new PipedInputStream();
	        PipedOutputStream pos = new PipedOutputStream();

	        pis.connect(pos);

	        new Thread() {
	            OutputStream os = pos;

	            public void run() {
	                int count = 1;

	                try {
	                    while (true) {
	                        os.write(count);
	                        os.flush();
	                        System.out.println("Producer : " + count);
	                        count++;
	                        Thread.sleep(500);
	                    }
	                } catch (Exception e) {
	                    e.printStackTrace();
	                }
	            }
	        }.start();

	        new Thread() {
	            InputStream is = pis;

	            public void run() {
	                try {
	                    int x;
	                    while (true) {
	                        x = is.read();
	                        System.out.println("Consumer : " + x);
	                        Thread.sleep(500);
	                    }
	                } catch (Exception e) {
	                    e.printStackTrace();
	                }
	            }
	        }.start();
	    }
	}
	// Use of RandomAccessFile stream methods

	import java.io.RandomAccessFile;

	class Test {
		public static void main(String[] args) throws Exception {
			// File Contains -> ABCDEFGH
			RandomAccessFile rf = new RandomAccessFile("Test.txt", "rw");

			System.out.println((char)rf.read());
			System.out.println((char)rf.read());
			System.out.println((char)rf.read());
			System.out.println((char)rf.read());

			System.out.println(rf.getFilePointer());
			rf.write('e');
			rf.seek(rf.getFilePointer()-5);

			System.out.println((char)rf.read());
			rf.skipBytes(3);
			System.out.println((char)rf.read());
		}
	}

Collections

	// Java Program to implement cache using LinkedHashMap

	import java.util.*;
	import java.util.Map;
	import java.util.Map.Entry;

	// Test class extending LinkedHashSet
	class Test<K, V> extends LinkedHashMap<K, V>{
		Test(int size, float loadFactor, boolean accessOrder){
			super(size, loadFactor, accessOrder);
		}

		protected boolean removeEldestEntry(Map.Entry e) {
			return size() > 4;
		}

		public static void main(String[] args) {
			Test<Integer, String> lhm = new Test<>(10, 0.75f, true);

			lhm.put(1, "A");
			lhm.put(2, "B");
			lhm.put(3, "C");
			lhm.put(4, "D");
			lhm.put(5, "E");

			lhm.put(2, "BB");
			lhm.put(3, "CC");

			lhm.put(6, "F");

			for(Entry<Integer, String> entry : lhm.entrySet()) {
				System.out.println(entry.getKey()+" : "+entry.getValue());
			}
		}
	}

Java 8

	// This code will not compile

	@FunctionalInterface
	interface MyInterface {
		int meth(int x, int y);
	}

	class Test {
		public static void m1(int a, int b) {
			System.out.println("Sum :: "+(a+b));
		}

		public static void main(String[] args) {
			MyInterface mi = Test::m1; // Compilation Error

			mi.meth(1, 2);
		}
	}

	// This code will successfully compile

	@FunctionalInterface
	interface MyInterface {
		double meth(int x, int y);
	}

	class Test {
		public static int m1(int a, int b) {
			return a+b;
		}

		public static void main(String[] args) {
			MyInterface mi = Test::m1;

			mi.meth(1, 2);
		}
	}
	// How to check for equality using isEqual()

	import java.util.Arrays;
	import java.util.List;
	import java.util.function.Predicate;

	class Demo {
		public static boolean check(Predicate<String> p, String str) {
			return p.test(str);
		}

		public static void main(String[] args) {
			List<String> list = Arrays.asList("C", "C++", "Java", "Python", null);
			Predicate<String> pred = Predicate.isEqual("Java");
			for(String name : list) {
				System.out.println(name+" : "+check(pred, name));
			}
		}
	}
	// Functional interface with more than one abstract methods

	@FunctionalInterface
	interface MyInterface {
		void meth(int n);
		boolean equals(Object obj);
		String toString();
	}
	// Special Syntax for method references with multiple parameters

	@FunctionalInterface
	interface MyInterface {
		int meth(String str1, String str2);
	}

	class Test {
		public static void main(String[] args) {
			MyInterface mi = String::compareTo;
			System.out.println(mi.meth("Hello", "Hello"));
		}
	}

Others

	// Client.java

	package socketprogramming;

	import java.io.BufferedReader;
	import java.io.InputStreamReader;
	import java.io.PrintStream;
	import java.net.Socket;

	class Client {
		public static void main(String[] args) throws Exception {
			System.out.println("Client Program Started ...");

			Socket st = new Socket("localhost", 2000);

			BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
			BufferedReader is = new BufferedReader(new InputStreamReader(st.getInputStream()));
			PrintStream os = new PrintStream(st.getOutputStream());

			String msg;
			do {
				System.out.println("Enter msg, type \"end\" to quit : ");
				msg = kb.readLine();
				os.println(msg);
				if(msg.equalsIgnoreCase("end"))
					break;
				msg = is.readLine();
				System.out.println("From Server : "+msg+"\n");
			} while(true);

			st.close();
			System.out.println("Client Program Ended ...");
		}
	}

	// Server.java

	package socketprogramming;

	import java.io.BufferedReader;
	import java.io.InputStreamReader;
	import java.io.PrintStream;
	import java.net.ServerSocket;
	import java.net.Socket;

	public class Server {
		public static void main(String[] args) throws Exception {
			System.out.println("Server Program Started ...");

			ServerSocket ss = new ServerSocket(2000);
			Socket st = ss.accept();

			BufferedReader is = new BufferedReader(new InputStreamReader(st.getInputStream()));
			PrintStream os = new PrintStream(st.getOutputStream());

			String msg;

			do {
				msg = is.readLine();
				if(msg.equalsIgnoreCase("end"))
					break;
				msg = new String(new StringBuffer(msg).reverse());
				os.println(msg);
			} while(true);

			ss.close();
			System.out.println("Server Program Ended ...");
		}
	}
	// Java Program to fetch data from database using JDBC

	import java.sql.Connection;
	import java.sql.DriverManager;
	import java.sql.ResultSet;
	import java.sql.Statement;

	class Test {
		public static void main(String[] args) throws Exception {
			Class.forName("oracle.jdbc.driver.OracleDriver"); // Driver class

			Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","MYDB","ARPIT"); // Connection url, Username, Password

			Statement stm = con.createStatement();
			ResultSet eq = stm.executeQuery("SELECT * FROM DEPT");

			while (eq.next()) {
				System.out.println(eq.getInt(1)+" "+eq.getString(2)+" "+eq.getString(3));
				// System.out.println(eq.getInt(1)+" "+eq.getString(2)+" "+eq.getString(3));
			}

			stm.close();
			con.close();
		}
	}

Java SE Notes