".txt"
extension will be automatically
added to your file. To avoid this you must enclose your filename in
double quotes. Eg: "filename.java"
Otherwise you need to
uncheck the "Hide extension for known file types" option in the file
explorer options.
type filename.ext
command to display the
contents of the file on terminal.
javap packageName.className
command is used to get the
list of all available methods in that class. Here
javap
stands for java profiler.
\u0000
which
represents null value.
IEEE 754
floating point standards.
Eg: byte b = 50, b = b + 1;
Eg: z = 2 * a * b;
// Array Declarations
int arr[]; // 1D Array
int []arr; // 1D Array
int[] arr; // 1D Array
int[] []arr1, arr2[]; // 2D Array
int[] []arr3, arr4[][]; // 3D Array
main()
.
-source
flag.
javac -source 1.4 filename.java // 1.4 version compiler
javac -source 1.5 filename.java // 1.5 version compiler
javac -version
is used to check the java compiler version
and java -version
is used to check the JVM version.
main()
using static block from Java v1.7 onwards they
made mandatory to have a main()
.
// 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
}
}
main()
or its object is
created.
// 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
}
}
// 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
}
System.exit(0)
statement, numeric value indicates exit
codes, zero represents normal termination and any non-zero value
represents the abnormal termination.
Thread
class, in that case you
can call the start()
using your class object also. But if
your class is implementing Runnable
interface in that
case it is not possible to do so.
yield()
of the Thread
class causes the
currently executing thread to temporarily pause its execution and
allow other threads to execute. If there are no other threads
available for execution then the current thread will continue its
execution.
MIN_PRIORITY, MAX_PRIORITY or NORM_PRIORITY
to set the
thread priority, these constant fields are defined inside the
Thread
class and declared as
public static final
.
Thread
class, in that case
you can use these constant fields directly but if your class is
implementing the Runnable
interface in that case you need
to quantify the field name with class name Thread
.
setPriority()
.
// 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
getId()
.
isDaemon()
.
interrupt()
. If you
interrupt a waiting thread, it will cause an
InterruptedException
, and the thread will continue its
execution from where it left off.
isInterrupted()
.
notify()
executes, it can notify any of the waiting
thread. We can not predict which thread will be notified as it depends
on the current status of the blocked (waiting) queue.
Inner classes are generally used to reduce the complexity and length of the outer(enclosing) class.
There are four types of Inner classes:
1) Nested Inner Classes 2) Local Inner Classes 3) Anonymous Inner Classes 4) Static Inner Classes
Inner classes can access private members of outer class directly whereas outer class also can access inner class's private members but through objects only. This is possible because the inner class is considered part of the same enclosing scope as the outer class.
// 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();
}
}
As we know when we compile a java program, for each class a separate
.class
file will be generated. When we compile the
above program two separate .class
files will be
generated, one for the outer class and another one for the inner
class.
For outer class ---> Outer.class For inner class ---> Outer$Inner.class
Inner class object can be created outside the outer class as well. For the non-static inner classes, first you need to create the outer class object but for the static inner classes you don't need to do so.
// 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();
}
}
private
or
default
only.
main()
or a enum constant
is created.
// 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());
}
}
}
main()
, static block and instance block
as well. In the following example first instance block and then
constructor will be executed for each enum constant. After that static
block will be executed and then the main()
will execute.
// 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;
}
}
Class
object that
represents the class whose properties you want to obtain using
reflection api.
// 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);
}
}
}
If a directory contains any file then you can not delete that
directory using delete()
.
As static variables are not a part of the object's state, so they do not take part in the process of serialization.
Some important methods of file class:
canExecute() --> to check whether the file is executable or not canRead() --> to check whether the file is readable or not canWrite() --> to check whether the file is writable or not deleteOnExit() --> to create a temporary file, which will be deleted when the program exits listFiles() --> to get a list of files and directories getName() --> to get the name of file getPath() --> to get the path of file getAbsolutePath() --> to get the path of file shortcut getCanonicalPath() --> to get the actual path of shortcut getParent() --> to get the parent directory name setReadOnly() --> to make a file read-only setWritable() --> to make a read-only file writable lastModified() --> to get when a file is last-modified setLastModified() --> to set last modified time of file
Lecture entitled "InputStream and OutputStream Classes" from section "Java IO Streams".
getBytes()
is used to convert the string into a byte
array.
available()
returns number of remaining bytes that can
be read from the input stream.
// 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();
}
}
}
SequenceInputStream
is used to take input from more than
one files.
// 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();
}
}
readAllBytes()
which is first introduced in Java 9 is
used to read all available bytes in a
ByteArrayInputStream
.
toByteArray()
is used to convert the contents of
ByteArrayOutputStream
to a byte array.
writeTo()
writes the contents of theByteArrayOutputStream
to the specified output stream.
markSupported()
will return true if the invoking stream
supports marking and resetting the bytes otherwise it will return
false.
mark()
is used to mark a byte of the input stream and
reset()
is used to reset the mark.
// 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());
}
}
mark(), reset() and flush()
methods are supported by
buffered streams only.
PipedInputStream
and
PipedOutputStream
we use connect()
.
// 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();
}
}
RandomAccessFile
stream implements
DataInputStream
and DataOutputStream
.
RandomAccessFile
stream is used to both read and write
data from and to a file at the same time. The data can be read/write
in sequential as well as random fashion as the name suggests.
getFilePointer() --> to obtain the current position of the file pointer seek() --> to seek to a specific byte, generally used with getFilePointer() skipBytes(n) --> to move file pointer n bytes in forward direction
// 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());
}
}
DataOutputStream
can be read by
DataInputStream
only and the order of reading the data
must be same as writing. If the order is change then you may read a
junk value or exception will be thrown.
double forward slash (\\)
or
single backward slash (/)
.
LinkedList
is efficient,
because it does not require any shifting or reallocation operations
like ArrayList
.
LinkedList
is not recommended for storing large no of
objects as it requires extra space to store next & previous object
links.
ArrayDeque
are performed in constant
time.
PriorityQueue
will not allow null values because null can
not be compared with any other value.
Tree
, performs basic operations in the
log n
time.
Hashtable
as the internal
data structure performs the basic operations in the constant time.
LinkedHashMap
is not recommended for frequent traversal
operations as it uses Hashtable
+
DoublyLinkedList
as internal data structure.
removeEldestEntry()
of
LinkedHashSet
we can implement cache memory of the
specified size, which will follow LRU
principle.
// 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());
}
}
}
// 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);
}
}
IllegalStateException
will be
thrown.
isEqual()
is a static method which is defined inside the
predefined functional interface Predicate
. It is used for
creating Predicate
instances that check for equality or
null
values.
// 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));
}
}
}
Object
class as a abstract method without affecting its
functional interface status. In this scenario a functional interface
will contain more than one abstract method.
// 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"));
}
}
java.util.Date
class is mutable and it will maintain date
& time in milliseconds
whereas new Date & Time
API classes are immutable and will maintain date & time in form of
two variables seconds
and nanoseconds
.
java.util.Date
and new Date & Time API classes
consider 1st Jan 1970 00:00:00 UT
as
EpochDay(Reference)
to compute date & time values.
super
is not allowed in class or interface
definition, it can be used only inside the method parameter with
wildcard.
<>
operator can also be used
with anonymous classes.
// 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();
}
}