JAVA Internship PROGRAMING
JAVA Internship PROGRAMING
Overview of Java
JAVA introduction:-
Author : James Gosling
Vendor : Sun Micro System
Project name : Green Project
Type : open source & free software
Initial Name : OAK language
Present Name : java
Extensions : java & .class & .jar
Initial version : jdk 1.0 (java development kit)
Présent version : java 10/11c
Operating System : multi Operating System
Implementation Lang : c, cpp……
Symbol : coffee cup with saucer
Objective : To develop web applications
SUN : Stanford Universally Network
Slogan/Motto : WORA(write once run anywhere)
Features of Java
Importance of core java:-
1) Java is used to develop Desktop Applications such as Media Player, Antivirus etc.
Advance
Java
Hadoop
and Big Android
data
Core
Java
Selenium Cloud
Testing Computing
Java categories
J2SE
• J2SE is used for developing client side applications.
J2EE
• J2EE is used for developing server side applications.
J2ME
• J2ME is used for developing mobile or wireless application by making use of a
predefined protocol called WAP(wireless Access / Application protocol).
Object Oriented Languages Comparison
Objective
Feature C++ C Ada Java
Define byte
Byte code is the set of optimized instructions generated during compilation phase and it is more
Define JRE
The Java Runtime Environment (JRE) is part of the Java Development Kit (JDK). It contains set of
libraries and tools for developing java application. The Java Runtime Environment provides the
Define JVM
JVM is set of programs developed by sun Micro System and supplied as a part of jdk for reading
line by line line of byte code and it converts into native understanding form of operating system.
JVMs are not same for all hardware and software, for
example for window os JVM is different and for Linux VJM is different.
JVM, JRE and JDK are platform dependent because configuration of each
OS differs. But, Java is platform independent.
JDK
• The Java Development Kit (JDK) is primary components. It physically exists.
It is collection of programming tools and JRE, JVM.
JRE
The Java Runtime Environment (JRE) is part of the Java Development
Kit (JDK). It contains set of libraries and tools for developing java application.
The Java Runtime Environment provides the minimum requirements for
executing a Java application. It contains set of libraries + other files that JVM
uses at runtime.
JRE
JVM Architecture in Java
JVM (Java Virtual Machine) is a software. It is a specification that provides
Runtime environment in which java bytecode can be executed
Working of Java
Platform Independent
Java Environment/Life Cycle of
Java Code
Runtime
Compile-time Environment Class
Environment Java
Loader
Class
Bytecode Libraries
Java Verifier
Source
(.java)
Just in
Java
Time
Interpreter Java
Java Compiler
Byte codes Virtual
Java move locally machine
Compiler or through
network
Runtime System
Java
Bytecod Operating System
e
(.class )
Hardware
First Java Program
Requirements for java Program
For executing any java program we need given things.
Install the JDK any version if you don't have installed it.
Set path of the jdk/bin directory.
Create the java program
Compile and run the java program
1: Digits:- (0-9)
2: Alphabets:- (A-Z,a-z)
3:Special symbols:- (+,-,/,*……..etc)
Keywords
Primitive Data Type Userdefined Access Exceptio Control Statements Modifiers Miscellaneous DataLiteral
data type Modifiers ns values
Handling
Break assert
Continue import
Return package
And goto (reservered)
IDENTIFIERS
• It is a name giving to variable,method,class,interface etc…
• It should contains alphabets,digitsand only 2 symbols.(_ underscore and $ dollar).
• 1st character should be alphabet, _ or $and it cannot be a digit.
• It can not have space.
• It can not be a keyword.
• Identifiers are casesensitive.
AVERAGE 123abc
abc123 if
$test &abc
Integer Floating
Data Type Data Type
Numeric Datatype
Integer Datatype
byte
short
int
long
byte DataType short DataType int DataType
Size: 8bits Size: 2 bytes Size: 4 bytes
Max-Size: 127 Range:- -32768 to Range:-
Min-Size:-128 32767 -2147483648 to
Range:-128 to 127 Ex: short s=32767; 2147483648
Ex: byte b=100; Ex: int i=100;
boolean DataType
byte b=127; float DataType
Size: not applicable
Size: 4 byte
Range:-not applicable
Range: -3.4e38 to
long DataType Ex: boolean b=true;
Size: 8 byte 3.4e38
Range:- -2pow(63) Ex: float f=10.10;
double DataType
to 2 pow(63)-1 char DataType
Size: 8 bytes
Ex: long Size: 2 bytes
Range:--1.7e308 to
l=10000000; Range:- 0 to 65535
1.7e308
Ex: char ch=‘a’;
Ex: double d=1254.215;
Literals
• It is a value.
a)Integer literal
c)Boolean literal
d)Character literal
e)String literal
Operators in Java
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Ternary or Conditional Operators
Operators in Java
Control Statements in Java
Decision
Looping
making
Statements
Statements
Transfer Statements
Decision making Statements Looping Statements
if while
if-else do-while
switch for
for each
Transfer Statements
• break
• continue
• return
• try
• catch
• final
System.out.println() in Java
• In java language print() and println() are the predefined non-static method of printStream class used to
display value or message either in the same line or line by line respectively. PrintStream class is having fixed
object reference in the System class (existing as a static properties) so that either print() or println() method
can be called with following syntax..
Syntax
System.out.print("--------------");
System.out.println("------------");
/* "out" is Object reference of printStream class existing in system class as a static
property. */
Java Variables
Variables are used to store the values. By storing that values we are
achieving the functionality of the project.
While declaring variable we must specify the type of the variable by using
data type’s concept.
1. Local variables
2. Instance variables
3. Static variables
Class vs. Object:-
PEN(object):-
State:- name raynolds,color red etc……
Behavior:- used to write
A simple class example
return-type methodName(parameter-
list)
{
//body of method
}
Example of a Method
Purpose of Inheritance
1. It promotes the code reusability i.e. the same methods and variables which are
defined in a parent/super/base class can be used in the child/sub/derived class.
2. It promotes polymorphism by allowing method overriding.
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance
NOTE :Multiple inheritance is not supported in java
Aggregation (HAS-A)
class Student {
String name;
Address ad;
}
Method Overriding
1. When a method in a sub class has same name, same number of arguments and
same type signature as a method in its super class, then the method is known as
overridden method.
2. Method overriding is also referred to as runtime polymorphism.
3. The key benefit of overriding is the abitility to define method that's specific to a
particular subclass type.
class Animal
{
public void eat()
{
System.out.println("Generic Animal eating");
}
}
class Dog extends Animal {
public void eat() //eat() method overriden by Dog
class.
{
System.out.println("Dog eat meat");
}
}
Difference between Overloading and Overriding
Syntax
import package1.package2.......*;
Array In Java
• Array is a collection of similar type of data. It is fixed in size that means you can't increase the
size of array at run time. It is collection of homogeneous data elements. It store the value on
the basis of index value.
Advantage of Array
One variable can store multiple value: The main advantage of array is we can represent
multiple value under the same name.
Code Optimization: No, need to declare a lot of variable of same type data, We can retrieve
and short data easily.
Random access: We can retrieve any data from array with the help of index value.
Disadvantage Of Array
The main limitation of array is Size Limit when once we declare array there is no chance to
increase and decrease the size of array according to our requirement, Hence memory point of
view array concept is not recommended to use. To over come this limitation in java introduce
collection concept.
Types of Array
There are two types of array in java.
Single Dimensional Array
Multidimensional Array
Single dimension array declaration. 2D Array declaration.
Syntax Syntax
1. int[][] a;
1. int[] a;
2. int a[][];
2. int a[]; 3. int [][]a;
3. int []a; 4. int[] a[];
5. int[] []a;
Note: At the time of array declaration we can not specify the size of array.
6. int []a[];
For Example int[5] a; this is wrong.
Array creation
Every array in a java is an object, Hence we can create array by using new keyword.
Syntax
int[] arr = new int[10]; // The size of array is 10
or
int[] arr = {10,20,30,40,50};
Syntax
arrayname[n-1];
Access Array Elements
int[] arr={10,20,30,40};
System.out.println("Element at 4th place"+arr[2]);
Example Of Array
length: It is a final variable and only applicable for array. It represent size of array.
Example
int[] a=new int[10];
System.out.println(a.length); // 10
System.out.println(a.length()); // Compile time error
length(): It is final method applicable only for String objects. It represent number
of character present in String.
Example
String s="Java";
System.out.println(s.length()); // 4
System.out.println(s.length); // Compile time error
Final Keyword In Java
It is used to make a variable as a constant, Restrict method overriding, Restrict inheritance. It is
used at variable level, method level and class level. In java language final keyword can be used in
following way.
Final at variable level
Final at method level
Final at class level
This Keyword In Java
this is a reference variable that refers to the current object. It is a keyword in java
language represents current class object
Usage of this keyword
It can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
It can be used to invoke current class method (implicitly)
It can be passed as an argument in the method call.
It can be passed as argument in the constructor call.
It can also be used to return the current class instance.
Static Block In Java
Static block is a set of statements, which will be executed by the JVM before execution of main
method.
At the time of class loading if we want to perform any activity we have to define that activity
inside static block because this block execute at the time of class loading.
In a class we can take any number of static block but all these blocks will be execute from top
to bottom.
Syntax
static {
........ //Set of
Statements ........
}
Abstract class in Java
We know that every java program must start with a concept of class that is without classes
concept there is no java program perfect. In java programming we have two types of classes
they are
Concrete class
Abstract class
class Helloworld {
void display()
Create an object
{
Helloworld obj=new Helloworld();
System.out.println("Good
obj.display();
Morning........");
}}
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class. An abstract class is
one which is containing some defined method and some undefined method. In java
programming undefined methods are known as un-Implemented or abstract method.
Syntax
Example
abstract class
abstract class Vachile
className
{
{
abstract void Bike();
......
}
}
Abstract Method
An abstract method is one which contains only declaration or prototype but it never contains body
or definition. In order to make any undefined method as abstract whose declaration is must be
predefined by abstract keyword.
Syntax
abstract ReturnType methodName(List of formal
parameter);
An object of base interface contains the details about those methods which are declared in that interface
only but it does not contain details about those methods which are specially available in either in derived
classes or in derived interfaces.
Interfaces should not be final.(because implement’s not possible)
An interface does not contain Constructors. (because no need of create objects)
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.
3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
4) Abstract class can have static methods, main Interface can't have static methods, main
method and constructor. method or constructor.
5) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
java.lang Package
We have mainly five classes in java.lang. Which are most commonly used in any java
program
1. Object
2. String
3. StringBuffer
4. StringBuilder
5. Wrapper Classes (AutoBoxing / AutoUnboxing)
Wrapper class
Wrapper class in java provides the mechanism to convert primitive into object
and object into primitive.Wrapper classes are basically used for converting the
string data into fundamental data type.
Primitive
Type Wrapper class String to Primitive Primitive to Wrapper
Constant String
Storage Area Pool Heap Heap
Differences Between
String StringBuffer
StringBuilder
Java Exception Handling
Exception Handling
•try
1. Try block is used to enclose the code that might throw an exception.
2. It must be used within the method
3. try block must be followed by either catch or finally block
4. If any exception is taking place the control will be jumped automatically to
appropriate catch block.
5. If any exception is taking place in try block, execution will be terminated and the rest
of the statements in try block will not be executed at all and the control will go to
catch block
•catch
1. Catch block is used to handle the Exception.
2. It must be used after the try block only
3. We can use multiple catch block with a single try.
4. If we write ‘n’ number of catch’s , then only one catch will be executing at any point
5. After executing appropriate catch block, control never goes to try block even if we
write return statement
3. Finally
1. This is the block which is executing compulsory whether the exception is taking place or
not.
2. This block contains statements like releases the resources are opening files, opening
databases, etc.
3. Writing the finally block is optional
4. Throws
This is the keyword which gives an indication to the calling function to keep the called function
under try and catch blocks.
It gives an information to the programmer that there may occur an exception so it is better for the
programmer to provide the exception handling code so that normal flow can be maintained
5. Throw
Throw keyword is used to explicitly throw an exception. In above we didn’t create any
Exception class Object in throws because JVM automatically creates Objects. If you want to
create Exception class object manually and throw exception using throw keyword
Java throw keyword is used to explicitly throw Java throws keyword is used to declare an
1) an exception.
exception.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions
Java .io package
Java.io is a package which contains number of classes by using that classes we are able to
send the data from one place to another place.
In java language we are transferring the data in the form of two ways:-
1. Byte format
2. 2. Character format
Stream/channel:-
It is acting as medium by using steam or channel we are able to send particular data
from one place to the another place.
Streams are two types:-
1. Byte oriented streams.(supports byte formatted data to transfer)
2. Character oriented stream.(supports character formatted data to transfer)
Byte oriented streams:-
Java.io.FileInputStream
To read the data from the destination file to the java application we have to use
FileInputSream class.
To read the data from the .txt file we have to read() method.
Java.io.FileOutputStream:-
To write the data to the destination file we have to use the FileOutputStream.
To write the data to the destination file we have to use write() method.
import java.io.*;
class Test {
static FileInputStream fis;
static FileOutputStream fos;
public static void main(String[] args) {
try{
fis=new FileInputStream("get.txt");
fos=new FileOutputStream("set.txt",true);
int c;
while ((c=fis.read())!=-1) {
fos.write(c);
}
fis.close();
fos.close();
}
catch(IOException io){
System.out.println("getting IOException"); } } }
Collections(java.util)
Limitations of array:-
Ex:-
Student[ ] s=new Student[100];
S[0]=new Student();
S[1]=new Student();
S[2]=new Customer();------compilation error
Collection Frameworks
Collections:-
Collections:-
If we want to represent group of as a single entity then we should go for collection.
1. Collection 2. List
3. Set 4. SortedSet
5. NavigablaSet 6. Queue
Creates an Empty ArrayList Object with default initial capacity 10.Once ArrayList
reaches its max capacity the new Arraylist object is created with newcapacity =
(currentcapacity *3/2)+1 & old one will give to Garbage collector
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList<>();
l.add("A");
l.add(10);
l.add("A");
l.add(null);
System.out.println(l); // [A, 10, A, null]
l.remove(2);
System.out.println(l); // [A, 10, null]
l.add(2, "M");
System.out.println(l); // [A, 10, M, null]
l.add("N");
System.out.println(l); // [A, 10, M, null, N]
}
}
LinkedList
Underlying data structure is DoubleLinkedList
Insertion order is preserved
Duplicates are allowed
Heterogeneous objects are allowed
Null insertion is allowed
LinkedList implements Serializable & Clonable interfaces but not RandomAccess
Best Choice for Insertion/Deletion, Worst for Retrieval operation
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("A");
l.add(10);
l.add("A");
l.add(null);
System.out.println(l); // [A, 10, A, null]
l.set(0, "Satya"); // replaces
System.out.println(l); // [Satya, 10, A, null]
l.add(0, "Johnny"); // just add
System.out.println(l); // [Johnny, Satya, 10, A, null]
l.removeFirst();
System.out.println(l); // [Satya, 10, A, null]
System.out.println(l.getFirst());// Satya
} }
Vector
The underlying data structure is ResizableArray or Growable
Array
Duplicates are allowed
Insertion order is preserved
Heterogeneous(different datatypes) Objects are allowed
Null is insertion is allowed
Vector implements Serializable, Clonable & RandomAccess
Vector is Synchronized
Creates an Empty Vector Object with default initial capacity 10.Once Vector
reaches its max capacity the new Vector object is created with
newcapacity = (currentcapacity*2) & old one will give to Garbz collector.
public class VectorDemo {
public static void main(String[] args) {
Vector v = new Vector();
for (int i = 1; i <=10; i++) {
v.addElement(i);
}
System.out.println("Before adding 11th
element -Capacity:"+v.capacity()); //
v.addElement("Satya");
System.out.println(v);
System.out.println("After adding 11th
element -Capacity:"+v.capacity());
System.out.println("size : "+v.size());
}
}
Stack
The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class
Vector with five operations (below 5 methods) that allow a vector to be treated as a
stack
1. Object push(Object o) -Insert an object into top of the stack
2. Object pop() -Removes & returns from top of the stack
3. Object peak() -Just returns Object from top of the stack
4. Boolean empty() -returns TRUE if stack is empty
5. int search(Object o) - returns offset if available otherwise -1
java.util.Set
Set is child interface of collection
If we want to represent group of individual objects as a single entity where
duplicates are Not allowed & insertion order Not be preserved then we should go
for List
Set Interface doesn’t contain any new method & we have to use only collection
interface methods
HashSet
The underlying datastructure is Hashtable
Duplicate Objects are Not Allowed
Insertion Order is Not preserved & it is based hash code of Objects
Null Insertion is possible(Only once)
Heterogeneous Objects are allowed
Implements Serializable & Clonable but not RandomAccess Interface
HashSet is the Best Choice for Search Operation
public class HashSetDemo {
public static void main(String[] args) {
HashSet h = new HashSet();
h.add("A");
h.add("B");
h.add("C");
h.add(10);
h.add(null);
System.out.println(h.add("A"));//False
System.out.println(h);
}
}
LinkedHashSet
LinkedHashSet is similar to HashSet (including constructors & methods) only difference
is it preserves Insertion Order.
public class HashSetDemo {
public static void main(String[] args) {
LinkedHashSet h = new LinkedHashSet();
h.add("A");
h.add("B");
h.add("C");
h.add(10);
h.add(null);
System.out.println(h.add("A"));
System.out.println(h);
}
}
java.util.SortedSet (Interface)
Is the child interface of Set
If we want to represent a group of individual objects according to some sorting order
without duplicates then we should go for SortedSet
SortedSet Interface defines following 6 methods.
TreeSet
Underlying D.S is BalancedTree
Duplicate Objects are Not Allowed
Insertion order Not Preserved but we can sort elements
Heterogeneous Objects are Not Allowed , if try it throws ClassCastException at
Runtime
Null Insertion allowed(Only once)
TreeSet implements Serializable & Clonable but not RandomAccess
All objects are inserted based on some sorting order either default or
customized sorting order
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet t = new TreeSet();
t.add("A");
t.add("N");
t.add("Z");
t.add("h");
t.add("X");
t.add("i");
//t.add(10);
//Exception in thread "main" java.lang.ClassCastException:
//java.lang.String cannot be cast to java.lang.Integer
//t.add(null); // java.lang.NullPointerException
System.out.println(t);
}
}
Map:-
2. Up to know we are working with single object and single value where as in
the map collections we are working with two objects and two elements.
3. The main purpose of the collection is to compare the key value pairs and
to perform necessary operation.