New Core Java
New Core Java
New Core Java
Simple
Object-Oriented
Platform independent
Secured
Interpreted
High Performance
Multithreaded
Installing Java in your machine
5
Installing Java in your machine
6
First java program
class Demo
{
public static void main(String args[])
{
System.out.println(“Hello World”);
}
}
Java Development Process
8
Data Types
Variables
class Demo
{
int data=50;//instance variable
void method()
{
int count=90;//local variable
}
}
13
Operators
if statement
if-else statement
if-else-if ladder
nested if statement
Flow diagram
if( condition ) {
// statement
} else {
// statement
}
Example
Ex. Even odd number
int num=10;
if(num%2==0)
{
System.out.println(“Even Number”);
}
else
{
System.out.println(“Odd Number”);
}
if-else-if
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
else
{
switch(expression)
{
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
code to be executed if all cases are not matched;
}
Example
int number=40;
switch(number)
{
case 10:
System.out.println("10");
break;
case 20:
System.out.println("20");
break;
case 30:
System.out.println("30");
break;
default:
System.out.println("Not match");
}
For loop
while(condition)
{
//code to be executed
}
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
do-while
Syntax:- Example:-
int i=1;
do
do{
{
System.out.println(i);
//code to be executed
i++;
} while(condition);
}while(i<=10);
Arrays
store the primitive type of data such as int, char, double, float, etc.
each data element can be randomly accessed by using its index number.
The lowest address corresponds to the first element and the highest address to the last element.
Multi-dimensional array
One dimensional array
import java.util.Scanner;
for(int i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}
Two dimensional array
import java.util.Scanner;
The character array or the string is used to manipulate text such as word or sentences.
String Object
33
Example
System.out.println(str1);
System.out.println(ch);
}
}
replace()
charAt()
toUpperCase()
concat()
String Functions
toLowerCase()
equals()
trim()
equalsIgnoreCase()
indexOf()
length() substring()
concat()
charAt()
//immutable string
str1.concat("world");
String str1="hello";
System.out.println(str1);
System.out.println(str1.charAt(0));
//solution
str1=str1.concat("world");
System.out.println(str1);
equals() equalsIgnoreCase()
System.out.println(str1.equals(str2)); System.out.println(str1.equalsIgnoreCase(str2));
indexOf()
length()
String str1="hello";
String str1="hello";
System.out.println(str1.indexOf('e'));
System.out.println(str1.length());
substring() trim()
System.out.println(str1); System.out.println(str1);
replace()
String str1="hello";
System.out.println(str1.replace("ello", "ii"));
System.out.println(str1);
OOP (Object-Oriented Programming )
Object
The main aim of object-oriented Class
programming is to implement real-world
entities, Abstraction
for example, object, classes, abstraction, Encapsulation
inheritance, polymorphism, etc. Inheritance
Polymorphism
Methods
Class
Constructors
Object
Age
Colour
State height
Dog
Behaviour Bark();
Sleep();
Eat ();
class <class name>{
Syntax:- field;
method;
}
class Student{
int id;
String name;
}
class Test{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“Karan";
System.out.println(s1.id+" "+s1.name);
}
}
HEAP Memory
Constructor
a constructor is a block of codes similar to the method.
It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is allocated in the
memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new keyword, at least one
constructor is called.
It calls a default constructor if there is no constructor available in the class. In
such case, Java compiler provides a default constructor by default.
Rules for creating constructor
The default constructor is used to provide the default values to the object like 0, null, etc., depending
on the type.
class sample
{
sample()
{
System.out.println("I am default constructor");
}
class sample{
int id; public static void main(String args[])
String name; {
sample m1=new sample(101,"abc");
sample(int i, String n) m1.show();
{ }
id = i; }
name = n;
}
void show()
{
System.out.println("Id="+id); Id=101
System.out.println("Name="+name); Output
Name=abc
}
Copy Constructor
There is no copy constructor in Java. we can copy the values from one object to another.
Parent
Child
Types of inheritance
Single
inheritance Multilevel
Hybrid
NOTE:-Multiple Inheritance is
Not possible.
Hierarchical
Hierarchical
Class A Class B
Class A
There can be only abstract methods in the Java interface, not method body.
interface test
{
void payment();
}
Class B implements
Interface B
Class B
Access Modifiers
The protected access modifier is accessible within class, package and outside the class, package but
through inheritance only.
The this keyword can be used to refer current class instance variable.
class sample{
int id;
String name;
public static void main(String args[])
sample(int id, String name) {
{ sample m1=new sample(101,"abc");
this.id = id; m1.show();
this.name = name; }
} }
void show()
{
System.out.println("Id="+id); Id=101
Output
System.out.println("Name="+name); Name=abc
}
Method
If you don't use the this keyword, compiler automatically adds this keyword while invoking the method.
class demo
{
void method1() class sample
{ {
System.out.println("I am method 1"); public static void main(String args[])
} {
demo d=new demo();
void method2() d.method2();
{ }
System.out.println("I am method 2"); }
this.method1();
}
} I am method 2
Output
I am method 1
Constructor
class demo
{
class sample
demo()
{
{
public static void main(String args[])
System.out.println("I am demo constructor");
{
}
demo d=new demo(10);
}
demo(int a)
}
{
this();
System.out.println("A="+a);
}
} I am demo constructor
Output
A=10
Static
static is used for a constant variable or a method that is same for every instance of a class.
When a member of the class is declared as static, it can be accessed before the objects of its
class are created, and without any object reference.
Nested
Variable Method Block
Class
Static Variable
The static variable can be used to refer to the common property of all objects.
The static variable gets memory only once in the class area at the time of class loading.
class Emp_stat
{
int id;
String name;
static String company_name="Wipro";
public class static_variable
Emp_stat(int id,String name) {
{ public static void main(String[] args)
this.id=id; {
this.name=name; Emp_stat e=new Emp_stat(1,"abc");
} e.emp_details();
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
class Abcd
{ public void emp_details()
int id; {
String name; System.out.println("Id="+id);
static String company_name="Wipro"; System.out.println("Name="+name);
System.out.println("Company
static void display() name="+company_name);
{ }
System.out.println("I am static method"); }
A1 a=new A1();
a.display();
}
}
Super Keyword
The most common use of the super keyword is to eliminate the confusion between superclasses and
subclasses that have methods with the same name.
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
Super variable
String name="Xyz";
void show()
{
System.out.println("Name="+super.name); Name=Abc
System.out.println("Name="+name); Name=Xyz
}
Note: super() is added in each class constructor automatically by compiler if there is no super()
Example
class demo
{
demo()
{
System.out.println("Super constructor");
} Output
}
sample()
{ Super constructor
super(); Sub class constructor
System.out.println("Sub class constructor");
}
If you make any variable as final, you cannot change the value of final variable(It will be constant)
Polymorphism
Runtime/Dynamic/
Method Overriding
Method Overloading
Class Demo{
It cannot be instantiated.
abstract interface
abstract and non-abstract methods. can have only abstract methods
can have final, non-final, static and non-static only static and final variables.
variables.
abstract class can be extended using keyword interface can be implemented using keyword
"extends". "implements".
A Java abstract class can have class members like Members of a Java interface are public by default.
private, protected, etc.
Example: Example:
public abstract class Shape{ public interface Shape{
public abstract void draw(); void draw();
} }
Encapsulation
Aggregation is a term which is used to refer one way relationship between two objects
In Java, aggregation represents HAS-A relationship, which means when a class contains
reference of another class known to have aggregation.
Code reuse is also best achieved by aggregation when there is no is-a relationship.
Example
Package
User-defined Ex. Employee or
Packages Com.bean
import package.*;
package pack2;
package pack1;
import pack1.*;
public class test1
class demo
{
{
public void show()
public static void main(String args[])
{
{
System.out.println(“pack1 – test1");
test1 t1= new test1();
}
t1.show();
}
}
}
Import package.classname
package pack1;
package pack2;
package pack1;
class demo
public class test1
{
{
public static void main(String args[])
public void show()
{
{
pack1.test1 t1= new pack1.test1();
System.out.println(“pack1 – test1");
t1.show();
}
}
}
}
Exception
Exception Handling
Handling
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException etc.
Types of Java Exceptions
Checked
Exception
Unchecked
Type Exception
Error
Hierarchy of Java Exception classes
Java Exception Keywords
try
catch
5 keywords
finally
throw
throws
try & catch blocks
Example
public class Demo{
public static void main(String args[]){
try{
int data=5/0;
}
catch(ArithmeticException e){
System.out.println(e);
}
System.out.println(“Last line");
}
}
finally block
class Demo{
public static void main(String args[]){
try
{ }
catch()
{ }
finally
{
System.out.println("finally block is always executed");
}
}
}
throw keyword
The throws keyword is used to declare which exceptions can be thrown from a method
while the throw keyword is used to explicitly throw an exception within a method or block of
code.
The throws keyword is used in a method signature and declares which exceptions can
be thrown from a method.
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.
Example
1) Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
3) Throw is used within the method. Throws is used with the method signature.
4) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException
Multithreading
Multithreading in Java is a process of executing multiple
threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of
processing.
Java Multithreading is mostly used in games, animation, etc.
Process-based
Multitasking
(Multiprocessing)
MultitaskingType
Thread-based
Multitasking
(Multithreading)
What is Thread in java
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
sleep() method
The sleep() method is a static method of Thread class and it makes the thread sleep/stop working for
a specific amount of time.
The sleep() method throws an InterruptedException if a thread is interrupted by other threads, that
means Thread.
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Example
System.out.println(i);
}
}
yield() method
The yield() method of thread class causes the currently executing thread object to temporarily
pause and allow other threads to execute.
A yield() method is a static method of Thread class and it can stop the currently executing thread
and will give a chance to other waiting threads of the same priority.
If in case there are no waiting threads or if all the waiting threads have low priority then the same
thread will continue its execution.
The advantage of yield() method is to get a chance to execute other waiting threads so if our
current thread takes more time to execute and allocate processor to other threads.
Example
t1.start();
t2.start();
for (int i=0; i<5; i++)
{
t1.yield();
System.out.println("yeild"+Thread.currentThread().getName() + " in control");
}
}
}
Difference between sleep() & yield() method
sleep() method takes duration as argument and ensures that the current thread suspends its execution for the
specified time.
yield() method is merely a hint to the scheduler that the current thread is willing to yield its current use of a
processor. Scheduler can even ignore this hint to yield.
When sleep() method is called current thread will definitely go to sleep for the specified time.
In case of yield() method first of all it is just a hint which can be ignored, even if the current thread yields the
CPU it can start running again if there is no other thread with the same or more thread priority.
sleep() method throws InterruptedException if sleeping thread is interrupted so call to sleep() method should
either be enclosed in try-catch block or it should be declared using throws clause.
yield() method doesn’t throw InterruptedException.
Collections
List
interfaces
Queue
Vector
ArrayList
Deque
LinkedList
PriorityQueue
classes
HashSet
LinkedHashSet TreeSet
Hierarchy of Collection Framework
ArrayList
Array lists are created with an initial size. When this size is exceeded, the collection is automatically
enlarged.
ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size
limit.
Important Points
ArrayList allows random access because array works at the index basis.
manipulation is little bit slower than the LinkedList because a lot of shifting needs to
occur if any element is removed from the array list.
Example
import java.util.*;
list.add("Abc");
list.add("Lmn");
list.add("Pqr");
[Abc, Lmn, Pqr]
System.out.println(list);
}
}
Iterator
An Iterator is an object that can be used to loop through collections, like ArrayList and
HashSet.
LinkedList should be used where modifications to a collection are frequent like addition/deletion
operations.
import java.util.*;
Iterator<String> itr=list.iterator();
while(itr.hasNext()) Abc
{ Lmn
System.out.println(itr.next()); Pqr
}
}
}
List
In Java, a list interface is an ordered collection of objects in which duplicate values can be stored.
The List interface is found in the java.util package and inherits the Collection interface.
Example
import java.util.*;
import java.util.*;
System.out.println("Array="+Arrays.toString(a));
System.out.println("List="+list);
}
}
Convert List to Array
import java.util.*;
list.set(1,“qwerty"); list.get(1)
Collections.sort() method
Output
List<String> list=new ArrayList<String>();
list.add("lmn");
list.add("pqr");
list.add("abc");
Collections.sort(list);
abc
lmn
for(String str:list)
pqr
{
System.out.println(str);
}
HashSet
Java HashSet class is used to create a collection that uses a hash table for storage.
The important points about Java HashSet class are: HashSet stores the elements 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.
Important Points
import java.util.*;
The LinkedHashSet class of the Java collections framework provides functionalities of both the
hashtable and the linked list data structure.
LinkedHashSet class provides all optional set operation and permits null elements.
import java.util.*;
TreeSet is one of the most important implementations of the SortedSet interface in Java that
uses a Tree for storage.
The ordering of the elements is maintained by a set using their natural ordering.
import java.util.*;
Iterator<String> itr=al.iterator();
Elijah
while(itr.hasNext()) Liam
{ Noah
System.out.println(itr.next()); Oliver
}
}
}
Map Interface
A map contains values on the basis of key, i.e. key and value pair.
A Map is useful if you have to search, update or delete elements on the basis of a key.
Important Points
A Map doesn't allow duplicate keys, but you can have duplicate values.
HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn't allow
any null key or value.
Example
import java.util.*;
for(Map.Entry m:map.entrySet())
{ 101 Abc
System.out.println(m.getKey()+" "+m.getValue()); 102 Lmn
} 103 Pqr
}
}
HashMap
It allows us to store the null elements as well, but there should be only one null key.
HashMap class implements the Map interface which allows us to store key and value pair
Important Points
HashMap may have one null key and multiple null values.
import java.util.*;
for(Map.Entry m : map.entrySet())
{ 1 Abc
System.out.println(m.getKey()+" "+m.getValue()); 2 qwerty
} 3 xyz
} 4 lmn
}
Hashtable
The Hashtable class implements a hash table, which maps keys to values.
import java.util.*;
HashMap Hashtable
1) HashMap is non synchronized. It is not-thread safe and Hashtable is synchronized. It is thread-safe and can be
can't be shared between many threads without proper shared with many threads.
synchronization code.
2) HashMap allows one null key and multiple null values. Hashtable doesn't allow any null key or value.
Java Generic methods and generic classes enable programmers to specify, with a single method
declaration, a set of related methods, or with a single class declaration, a set of related types,
respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types at
compile time.
Generic Methods Rules
All generic method declarations have a type parameter section delimited by angle brackets (< >)
that precedes the method's return type ( < E > ).
E is meant to be an Element
A generic method's body is declared like that of any other method. Note that type parameters
can represent only reference types, not primitive types (like int, double and char).
Example
System.out.println("\nCharacter Array=");
display(charArray);
}
}
Output
Integer Array=
1
2
3
4
5
Double Array=
1.1
2.2
3.3
4.4
Character Array=
H
E
L
L
O
Non-generic Collection Generic Collection
Can hold any type of data. Can hold only the defined type
Type-safety
Hence not type-safe. of data. Hence type safe.
JDBC API
JAVA DATABASE
JDBC DRIVER
APPLICATION
Database Connectivity Steps
Java IO is an API that comes with Java which is targeted at reading and writing data (input and
output).
For instance, read data from a file or over network, and write to a file or write a response back over
the network.
The java.io package contains all the classes required for input and output operations.
FileOutputStream is an outputstream for writing data/streams of raw bytes to file or storing data to
file.
byte b[]=s.getBytes();
fout.write(b);
fout.close();
System.out.println("Done");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data
(streams of raw bytes)
Example- Read Single Character
import java.io.FileOutputStream;
fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Example- Read All Characters
import java.io.FileInputStream;
It internally uses buffer to store data. It adds more efficiency than to write data directly into a
stream.
Example
import java.io.*;
String s="BufferedOutputStream";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
}
catch(Exception e)
{
System.out.println(e);
}
} }
BufferedInputStream Class
A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the
input and to support the mark and reset methods.
When the bytes from the stream are skipped or read, the internal buffer automatically refilled from
the contained input stream
import java.io.*;
int i;
while((i=bin.read())!=-1)
{
System.out.print((char)i);
}
bin.close();
fin.close();
}
catch(Exception e){
System.out.println(e);
}
} }
FileWriter Class
Java FileWriter class of java.io package is used to write data in character form to file.
import java.io.*;
It works much like the FileInputStream except the FileInputStream reads bytes, whereas
the FileReader reads characters.
import java.io.*;
int i;
while((i=fr.read())!=-1)
{
System.out.print((char)i);
}
fr.close(); }
catch(Exception e)
{
System.out.println(e);
}
}
}
BufferedWriter Class
BufferedWriter writes text to character output stream, buffering characters so as to provide for the
efficient writing of single characters, arrays, and strings.
Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance
fast.
Example
import java.io.*;
buff.write("I am BufferedWriter");
buff.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream.
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Example 2
import java.io.*;
System.out.println("I am "+name);
}
catch(Exception e)
{
System.out.println(e);
}
}
}