Uploaded by kratik.khiani

java coaching notes

James Gosling
Program File:Compile &Run Cycle
Program in JAVA:
• Case Sensitive.
• Method can not be independent means Method has to be member of a class .
• 4 Access specifier or modifier : public , private , protected & None(default/package)
• Outer class can be default or public only. Never private or protected.
• Inner class can have any of 4 access specifier.
• Access specifier can be written before class . No ; semicolon after body of the class like c++.
•Pascal case<FirstName>Uppercase first letter in each word ,used for Class Name .
•Camel case<firstName>Uppercase first letter in each word except the first (function name)
• Class name and file name should be same with .java extension.
•To call main function inside a class body :
Syntax : public static void main (String[] args) // Prototype in Java
{ System.out.println(“INDI SECURE”) ;}
•System is a class defined in the java.lang package. out is a public static member of
the System class, of type PrintStream.
•Thus, the expression System.out refers to an object of type PrintStream.
• PrintStream class have a public method println().
Ternary operator return value that need to be stored in a variable in Java
for Execution. String s = 5<6 ? “bhopal”: “Indore” ; Syso..(s);
Access Modifier Rule :
• There can be only 1 public outer class inside a single Java File.
• Name of the java file would be same as of Public Class.
• Only Public class can be accessed directly from outside of the package. No
other class of a package .
• When members (variable + method) are private they can not be accessed
from outside the class body.
• When members are protected , they can be accessed from any class of the
same package and child class from other package.
• When members are public , they can be accessed from any class of any
• When members are default they are accessible only from the class of same
package :
Grouping of Class as per their usage and domain e.g. Package java.io & Package java.net.
Just like various folders in Computer Drive C:\, D: \etc.
•It also help us avoid class name collision when we use same class name in different
:-> To compile a file under Package using cmd.exe
->To run a file under package using cmd.exe
F Q N: Fully Qualified Name
To use class of same name exist in different packages we need to use fully
qualified name of class for creating object( new package name . class name ()).
Java has min 2 classes in each package :Data class and Driver class
Keywords in Java:
Java Keywords
Parameter Vs Argument: Variable vs Value
A parameter is a variable in a method definition. When a method is called, the arguments are
the data you pass into the method's parameters. Parameter is variable in the declaration of
function. Argument is the actual value of this variable that gets passed to function.
Data Type :
By default, floating point numbers are double in
Java. In order to store them into float variable,
you need to cast them explicitly or suffix with 'f' .
float x=3.5 ; (error - default is double)
float x=3.5 f ; (no error).
Assigning a value of one type to a variable of
another type is known as Type Casting.
Example : int x = 65; char c = (char)x;
In Java, type casting is classified into two types,
Widening Casting(Implicit),Narrowing Casting
int k= Integer.parseInt (str,16);
int p = Scanner ref. nextInt(radix);
Casting Program
Reference Variable Vs Pointer :
Pointers can point nowhere ( NULL ), whereas a reference always refers to an
object. A very big difference between pointers and references is that
a pointer is an independent variable and can be assigned NEW address values;
whereas a reference once assigned can never refer to any new object .
However Java references are bound to one object at a time but can be assigned
other objects while the program executes.
Pointers: A pointer is a variable that holds memory address of another variable. A
pointer needs to be de referenced with * operator to access the memory location it
points to.
References : A reference variable is an alias, that is, another name for an already
existing variable. A reference, like a pointer is also implemented by storing the
address of an object.
A reference can be thought of as a constant pointer with automatic indirection, i.e.
the compiler will apply the * operator for you.
Object Creation in Java :
Inner Class Object Creation:
Outer .Inner in= Outer reference .new Inner(); // Normal access modifier
Outer.Inner in = new Outer.Inner ( ); //Static modifier.
Static Variables , Functions &Class:
Static member Functions do inherit
but static member variables do not
inherit in Java.
Wrapper Classes:
Wrapper class for every primitive data type in Java to make it 100 %
object oriented language.
Primitive Type Wrapper Class
Methods of Wrapper Classes:
•parseXxx (argument): static method and Xxx is
of primitive type int .
int i=Integer.parseInt("34",10); returns int decimal
int j=Integer.parseInt("11",2); returns int decimal
int k=Integer.parseInt("10”,16); returns int decimal
Prototype of parseXxx (argument ) ;
public static int parseInt(String val, int radix) throws
NumberFormatException .
Parameters : val : String representation of int
radix : base to be used while parsing
Autoboxing and Unboxing
•Autoboxing is the automatic conversion that the •xxx Value(): instance method of Wrapper class,xxx
can be of primitive type. It returns corresponding
Java compiler makes between the primitive
primitive type.
types and their corresponding object wrapper
classes. For example, converting an int to
Integer . toBinaryString ( int i);
an Integer, a double to a Double, and so on. If
Integer.toHexString(int i);
the conversion goes the other way, this is
Integer.toOctalString(int i);
called unboxing.
import : A Key Word to import classes of other packages
Syntax : import package name. class name;
• It is a member function of class.
• Name is same as class name.
• It has no return type.
• It has2 types (default, parameterized).
• Constructor is a special method that is used to initialize a newly
created object and called automatically just after memory is
allocated to an object.
• Constructor is used to initialize an object when parameters are
passed to it .
• Constructors do not Inherit.
Inheritance Rules:
• Each Class is allowed to have 1 direct super class and each super class
can have unlimited Subclasses. Multiple Inheritance not allowed.
• Private members of Super class are not accessible by Subclass directly
however can be accessed indirectly.
• Members with default access modifier in Super class are also
not accessible by sub classes of other packages.
Inheritance Types in JAVA:
• Single Level
• Multilevel
• Hierarchical
Inheritance : Syntax : Class Sub class extends Super Class
{ }
Parent Class or Super Class: Person
Child Class or SubClass : Student
Third Class having main method: Human
Method Overloading in JAVA:
• If 2 methods of a class have same name but arguments are different,it is called method
overloading in Java. Both methods may exist in same class, or both are in subclass or 1 in Super class
and 1 in sub class.
Method Overriding & Hiding in JAVA:
• A instance method in subclass with same signature to Super class but coding is different,it
is called overriding but If method is Static then it is called method hiding in Java.
Method Hiding & Overriding Program in JAVA:
final Keyword:
•A variable declared using key word final can be assigned only once.
• final instance variable-inside body of a class
• final static variable-inside body of a class
• final local variable-inside body of a method
• final class – means can not be extended or inherited
• final method -means can not be overridden
this Keyword:
•this object reference is a local variable in instance member method .
•this is used as reference to current object which is an instance of current class.
•this is useful where a local variable hide or shadow a field with the same name.
•If a method need to pass current object to another method , it can do so using this.
•this reference can not be used in static context.
super Keyword:
•Represent parent class object inside a child class instance member method.
super Key word :
•If a sub class method overrides super class method , we can invoke overridden method of
super class in subclass by using super key word .
•It also avoid name conflict between member variable of super class & subclass.
Class A
public void f1()
Class B extends A
public void f1()
{ super.f1();
Class C
Public static void main (String args [ ])
B obj =new B();
Calling super constructor and passing argument using Scanner
Anonymous Class in Java: Class without a Name
abstract Class:
public abstract class A
int a; Normal Variable declaration .
public void f1() {} Normal Method.
public abstract void f2(); abstract method declaration .
• Using abstract keyword.
• abstract class can not be instantiated but reference can be created.
•Vey helpful in Inheritance to use common properties and behavior in subclass
which inherit abstract class as Super class .
abstract Method:
• A method with no implementation inside a class and it should be declared as below
public abstract void f2();
• If a class has abstract method then it has to be abstract class (mandatory)
• It forces subclasses to override abstract method to use in subclasses .
interface : interface keyword
• interface can contain fields ( public ,static, final ),but method inside interface has only
declaration (public and abstract ) no definition.
• An interface is like Abstract class therefore it can not be instantiated but reference is possible.
• Object reference of interface can refer to any of subclasses type..
• Interface does not have Constructor.
• class can implement interface by using keyword implements .
• Multiple inheritance of interface is possible in JAVA. interface I3 extends I1,I2
public interface I1 {
public static final int a=8; public static and final with initialization.
public abstract void f1 (); abstract method declaration.
class A implements I1,I2 //Can have multiple implementations
public void f1() // overriding to ensure object get created else has to be declared abstract.
{ coding }
abstract class Vs interface :
• abstract
class can have default and public modifier whereas interface
has only public by default.
•abstract class may or may not contain abstract method and certain
methods can be defined whereas interface can not have definition of
any method means all are abstract methods.
•abstract class can have static and normal member variables whereas
interface has only static variables.
•abstract class may or may not have final member variable whereas
interface has only final .
•interface does not have constructor whereas abstract class do .
interface creation & implementation
Multiple interface Implementation :
package javaapplication5;
public interface NewInterface {
void f2();
package javaapplication5;
public interface NewInterface1 {
void f3();
Lambda Expression in Java
Interface with Single function declaration is called Functional Interface
Arrays :
int a[]=new int[5] ;// here a is reference variable .
• int a[]=new int [] {}; // while initializing array block should be left blank.
•Local variables by default are blank but Instance int variable by default has Zero Value in JAVA.
•length variable also exist inside Array body .
Array Initialization:
public class ArrayType{
Public static void main(String []args){
int array[]=new int[3];
int k [] = { 60,78,89,50};
Capacity declaration of
array not required.
2D [3][3]
3D Array : [2][2][2]
String Class : Available in java.lang package.
“String Object is Immutable in Java ”
Popular Methods in String Class:
equals() ,equalsIgnoreCase(),compareTo()
public static void main(String[] args)
String s=new String("COMPUTER");
When adding a number
and a string, Java will treat
the number as a string.
Generics enable types (classes and interfaces) to be parameters when defining classes,
interfaces and methods. Much like the more familiar formal parameters used in method
declarations, type parameters provide a way for you to re-use the same code with different
inputs. The difference is that the inputs to formal parameters are values, while the inputs to
type parameters are types. Type parameter is also called Type Variable.
Stronger type checks at compile time.<> is called Diamond .
A Java compiler applies strong type checking to generic code and issues errors if the code
violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which
can be difficult to find. A type variable can be any non-primitive type you specify: any class
type, any interface type, any array type.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T -Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
Generic Methods:
•Generic methods are methods that introduce their own type parameters.
•type parameter's scope is limited to the method where it is declared
•Static and non-static generic methods are allowed, as well as generic class constructors.
Data Collection Framework :
The Collections Framework is a
sophisticated hierarchy of interfaces and
classes that provide state-of-the-art
technology for managing groups of objects.
•Add objects to collection
•Remove objects from collection
•Search for an object in collection
•Retrieve/get object from collection
•Iterate through the collection
collection (lowercase c): It represents any of the data structures in which
objects are stored and iterated over.
Collection (capital C): It is actually the java.util.Collection interface from
which Set, List, and Queue extend.
Collections (capital C and ends with s): It is the java.util.Collections class
that holds a pile of static utility methods for use with collections
has 4 basic flavors:
The List interface extends Collection to define an ordered collection with
duplicates allowed. ArrayList, LinkedList and vector are classes
implementing List interface.
The Set interface extends the Collection interface. It will make sure that an
instance of Set contains no duplicate elements.
A queue is a first-in, first-out data structure. Elements are appended to the end
of the queue and are removed from the beginning of the queue.
A map is a container that stores the elements along with the
keys. The keys are like indexes.
ArrayList :
ListIterator extends Iterator to allow bidirectional traversal of a list, and the
modification of elements. boolean hasNext(): Returns true if there is at
least one more element in the collection being traversed.
object next() : This method returns the next object in the collection.
•The default constructor creates an ArrayList with a capacity of 10 items.
•ArrayList names = new ArrayList();
•ArrayList names = new ArrayList(int size);
•ArrayList names = new ArrayList(Collection c);
public void add(Object) public void add(int,
Adds an item to an ArrayList. The default version adds an item
at the next available location; an overloaded version allows you
to specify a position at which to add the item
public void remove(int)
Removes an item from an ArrayList at a specified location
public void set(int, Object)
Alters an item at a specified ArrayList location
Object get(int)
Retrieves an item from a specified location in an ArrayList
public int size()
Returns the current ArrayList size
ArrayList Program:
ArrayList and Vector are similar
classes only difference is Vector
has all method synchronized.
Both class simple terms can be
considered as a grow able array.
ArrayList should be used in an
application when we need to
search objects from the list
based on the index.
ArrayList performance
degrades when there is lots of
insert and update operation in
the middle of the list.
Linked list :It has a concept of nodes and data. Here Node is storing values
of next node while data stores the value it is holding.
LinkedList may iterate more slowly than an ArrayList, but it's a good choice
when you need fast insertion and deletion.
LinkedList( );
LinkedList(Collection<? extends E> c)
addFirst() or offerFirst( )
To add elements to the start of a list
addLast( ) or offerLast( ) or add()
To add elements to the end of the list
getFirst( ) or peekFirst( )
To obtain the first element of the list
getLast( ) or peekLast( )
To obtain the last element of the list
removeFirst( ) or pollFirst( ) or remove()
To remove the first element of the list
removeLast( ) or pollLast( )
To remove the last element of the list
LinkedList Program :
LinkedList is good for adding
elements to the ends, i.e.,
stacks and queues.
LinkedList performs best while
removing objects from middle
of the list
LinkedList implements List,
Deque, and Queue interfaces so
LinkedList can be used to
implement queues and stacks.
HashSet: A hash table stores information by using a mechanism called
hashing. In hashing, the informational content of a key is used to determine a
unique value, called its hash code. The hash code is then used as the index at
which the data associated with the key is stored. The transformation of the key
into its hash code is performed automatically.
A HashSet is an unsorted, unordered Set. It uses the hashcode of the object
being inserted, so the more efficient your hashCode() implementation the
better access performance. A Set cannot contain duplicate elements.
HashSet() // Default constructor, the default capacity is 16.
HashSet(Collection c) // It creates HashSet from collection c.
HashSet( int capacity) // it creates HashSet with initial capacity mentioned
public boolean add(Object o)
Adds an object to a HashSet if already not present in HashSet.
public boolean remove(Object o)
Removes an object from a HashSet if found in HashSet.
public boolean contains(Object o)
Returns true if object found else return false
public boolean isEmpty()
Returns true if HashSet is empty else return false
public int size()
Returns number of elements in the HashSet
HashSet Program :
HashSet provides collection of
unique objects.
HashSet is unsorted, unordered
and non-indexed based
collection class
HashSet can have only one Null
boolean add(object)
It is used to insert the specified element into this
queue and return true upon success.
boolean offer(object) It is used to insert the specified element into this
Object remove()
It is used to retrieves and removes the head of this
Object poll()
It is used to retrieves and removes the head of this
queue, or returns null if this queue is empty.
Object element()
It is used to retrieves, but does not remove, the
head of this queue.
Object peek()
It is used to retrieves, but does not remove, the
head of this queue, or returns null if this queue is
Priority Queue Program:
PriorityQueue in Java. A PriorityQueue is used when
the objects are supposed to be processed based on
the priority. It is known that a queue follows First-InFirst-Out algorithm, but sometimes the elements of
the queue are needed to be processed according to
the priority, that's when the PriorityQueue comes into
•It maintains key-value associations
(pairs) so you can look up a value using
a key. HashMap has implementation
based on a hash table.
•Keys of HashMap is like Set means no
duplicates allowed and unordered while
values can be any object even null or
duplicate is also allowed.
HashMap Constructors
HashMap( )
Default HashMap Constructor (with default capacity of 16 and load factor 0.75)
HashMap(Map<? extends KeyObject, ? extends ValueObject> m)
This is used to create HashMap based on existing map implementation m.
HashMap(int capacity)
This is used to initialize HashMap with capacity and default load factor.
HashMap(int capacity, float loadFactor)
45This is used to initialize HashMap with capacity and custom load factor.
HashMap Program :
Exception Handling :
• 2 Types of exceptions : checked & unchecked exceptions.
• Programmer Exceptions are raised using throw keyword and handled within catch block
other keywords are try & finally .
• For each try block there may be 1 or >1 catch block but only 1 finally block.
• catch block and finally block must always appear in conjunction (put together)with try block.
Throwable class define constructor
to set message and a function get
message() to retrieve an exception .
Type of Exception Handling :
•Default throw and catch built in (program ends).
• Default throw and programmer catch
• Programmer throw and default catch
• Programmer throw and Programmer catch.
Below 3 blocks can be used inside any method.
Try block {} where exception may occur.
• Catch block{} to ensure program does not end after exception.
• Finally {} :Guaranteed execution irrespective of exception in program.
Program : Default throw & programmer catch
Exception Program :Programmer Explicit Throw and Default Catch
Explicit throw: Programmer throw when programmer think it should be treated
as an exception.syntax : throw<throwable instance> ;exception reference must be of
throwable class or its subclass. A details message can be passed to constructor () when
exception object is created .
Programmer throw & Programmer Catch and Finally Block
Checked Exception : Compile time exception –to be
checked at compile time itself.
IO Exception
SQL Exception
:File handling
Forces programmers to deal with the exception that may be thrown (File
handling).Programmer must manage with try & catch block or inform Java to
handle it. throws keyword is required only to convince compiler and usage of
throws keyword does not prevent abnormal termination of program . By
throws keyword we can provide information to java about the exception.
Syntax : method name () throws <Exception 1> ,<Exception 2>
Checked Exception Program : Use of throws keyword
Threads :
Independent path of execution within a program , many threads can run concurrently
(virtually) within a program and multi threading means two or more tasks running
concurrently in a program . All this is done by a class of java.lang package.
2 ways to create threads in JAVA.
• By Implementing Runnable interface public interface Runnable{void run(); }(java.lang.Runnable)
• By extending Thread class (java.lang.Thread)
Process: create a thread , attach a code(s) to a thread and executing thread. thread ends
with execution of run method.
Threads States :
•Not Runnable
Threads Priority : Specifying the priority over other threads in a program
Threads having high priority get greater access to resources than lower one
Use setPriority () and getPriority()
Threads can be synchronized using synchronized key word and {}
Program -extending Thread class:
Setting Thread Priority:
•setPriority() method is called to set priority and
getPriority() is to retrieve value.
File Handling : Use of File class under java.io package to Create File
File Handling: Writing to File
f.write(c[i] ) ;
Constructor :
•FileOutputStream(File file)
•FileOutputStream(File file,boolean append)
•FileOutputStream(String name)
•FileOutputStream (String name , boolean append)
File Handling: Reading
from File
FileInputStream(File file)
• creates FileInputStream by opening a connection to actual file .
FileInput Stream(String filename)
•Creates FileInputStream by opening a connection to actual file.
File Reading :
A read() method reads the next byte of the data
from the input stream and returns int in the range
of 0 to 255 (ASCII Code). If no byte is available
because the end of the stream has been reached. the
returned value is -1.
Read(): Reading file
A read() method reads the
next byte of the data from the
input stream and returns int in
the range of 0 to 255 (ASCII
Code). If no byte is available
because the end of the stream
has been reached. the returned
value is -1.
GUI : Graphical User Interface allow user to interact with screen using graphical
component (visual indicators like picture) rather than normal text.
API (2 types): Application Programming Interface
1.AWT(Abstract Windowing Toolkit) 2.Swing
Classes in AWT:
Java.awt package contains the core AWT graphics classes.
•GUI Component classes such as Button ,TextField and
•GUI Container classes such as Frame,Panel,Dialog and Applet.
•Layout Manager classes such as FlowLayout,GridLayout,
•Custom Graphics classes such as Graphics,Color and Font.
AWT events:
Java.awt.event package supports event
handling .
•Event classes such as
•Event Listener classes such as
A Frame is the top level container of AWT GUI .
•A Frame has a title bar containing an icon,a title, min /max and close button and optional menu bar
and content display area.
•A Panel is a rectangular area or partition used to group GUI components.
•All components like Button ,Label must be kept inside a container, to do that Every container has an
method called add ( Button b).
GUI : applet
•Applet is java program runs in a web browser.
•Applet is a container class of AWT.
•Applets are designed to be embedded within HTML page.
•When a user views an HTML page the code for the applet get downloaded to the user PC automatically.
•To vies HTML page containing applet ,JVM is required.
Setting Component in applet:
• Create Basic applet. (Coding)
• Creating Component reference variable
• Initialize Component
• Adding Component to applet
• Setting Layout
• Using methods
start() Applet Class
stop() Functions
Set Layout :
Event Handling : Using Inner Class
• Click on button , Mouse movement, minimizing window etc.
• Is to make java code ready to respond any particular event.
Register your function/code to Button using
button.addActionListener(Action Listener action listener) function
i.e. object of a class which implements ActionListener Interface need to
be passed to add Action Listener () function & have to override actionPerformed()
Event Handling using Single Class which extends Applet
&Implement ActionListener Interface.
Swing : sub class of awt
Swing Event Handling :
•Event describes the change in state of any object. For Example : Pressing a button, Entering
a character in Textbox, Clicking or Dragging a mouse, etc.
Component of Handling:3 main components
•Events : An event is a change in state of an object.
•Events Source : Event source is an object that generates an event.
•Listeners : A listener is an object that listens to the event.
A source generates an Event and send it to one or more listeners registered with the source.
Once event is received by the listener, they process the event and then return.
Java packages used java.util, java.awt and java.awt.event.
Event Classes
generated when button is pressed, menu-item is selected, list-item is double clicked
generated when mouse is dragged, moved,clicked,pressed or released and also when it
enters or exit a component
generated when input is received from keyboard
generated when check-box or list item is clicked
generated when value of textarea or textfield is changed
generated when mouse wheel is moved
generated when window is activated, deactivated, deiconified, iconified, opened or
generated when component is hidden, moved, resized or set visible
generated when component is added or removed from container
generated when scroll bar is manipulated
generated when component gains or loses keyboard focus
Listener Interface
Steps for event handling
•Implements interface
•Register component
with listener
Swing Program : Using Inner Class
Advance Java:
Standalone Application : Standalone applications are also known as desktop
applications or window-based applications. Examples of standalone application are
Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone
Web Application :An application that runs on the server side and creates a dynamic
page is called a web application. Currently Servlet, JSP, Struts, Spring, Hibernate, JSF,
etc. technologies are used for creating web applications in Java.
Enterprise Application : An application that is distributed in nature, such as banking
applications, etc. is called enterprise application. It has advantages of the high-level
security, load balancing, and clustering. In Java, EJB is used for creating enterprise
Mobile Application :An application which is created for mobile devices is called a
mobile application. Currently, Android and Java ME are used for creating mobile
Application Programming Interface(API), which is a software intermediary
that allows two applications to talk to each other. Each time you use an app
like Facebook, send an instant message, or check the weather on your phone,
you're using an API.
Imagine you’re sitting at a table in a restaurant with a menu of choices to order
from. The kitchen is the part of the “system” that will prepare your order. What
is missing is the critical link to communicate your order to the kitchen and
deliver your food back to your table. That’s where the waiter or API comes in.
The waiter is the messenger – or API – that takes your request or order and
tells the kitchen – the system – what to do. Then the waiter delivers the
response back to you; in this case, it is the food.