You are on page 1of 184

Welcome in Core Java

Java Introduction

• Java is one of the world's most important and widely used


computer languages
• Java is a high level, robust, object-oriented and secure
programming language
• Java is a platform-independent language
• Currently, Java is used in internet programming, mobile
devices, games, e-business solutions, etc.
• As of 2020, Java is one of the most popular programming
languages in use, especially for client-server web applications.
History of Java

• Java was developed in Sun Microsystem by James Ghosling in 1991.


• which is now a subsidiary of Oracle Corporation
• It took 18 months to develop the first working version. James
Ghosling is also known as the Father of Java.
• Initially, Java was called "Greentalk" by James Gosling and at that
time the file extension was .gt.
• The initial name was Oak but it was renamed to Java in 1995 as
OAK was a registered trademark of another Tech company.
• Java is an island in Indonesia, here the first coffee was produced or
we call Java coffee
Prerequisites

• The following are prerequisites for Java to work properly:


• Java SE Development Kit (JDK) 1.7 or greater
• The latest Eclipse IDE for Java Developers
• NetBeans IDE
Difference Between C++ and java
c++ Java
C++ is platform-dependent. Java is platform-independent.

Java is used for application programming.


C++ is mainly used for system programming. It is mostly used in window, web-based,
enterprise and mobile applications.

Java doesn't support multiple inheritance


C++ supports multiple inheritance. through class. It can be achieved by interfaces in
java.

Java supports pointer internally. However, you


C++ supports pointers. You can write pointer
can't write the pointer program in java. It means
program in C++.
java has restricted pointer support in java.

C++ supports both call by value and call by


Java supports call by value only. There is no call
reference.
by reference in java.
What is Java Bytecode?
• Java bytecode is the instruction set for the Java Virtual Machine.
• java program is compiled, java bytecode is generate
• java bytecode is the machine code in the form of a .class file.
• With the help of java bytecode we achieve platform independence
in java. what does it mean ? It means same Java program can be
run on any platform or operating system

• Example:
• person taking red carpet with him and instead of walking on floor,
he always walks on red carpet, no matter where he is walking.
That red carpet is the JVM, your Java program runs on JVM rather
on any particular platform or machine.
How byte code work?
What is JVM, JRE & JDK
JVM
• java Virtual Machine (JVM) is an abstract computer machine
that is responsible for executing java byte code.
• The JVM performs the following main tasks:
• Loads code
• Verifies code
• Executes code
JRE & JDK

• Java Runtime Environment


• The Java Runtime Environment is a set of software tools
which are used for developing Java applications. It is
used to provide the runtime environment.
• It contains a set of libraries + other files that JVM uses
at runtime.
• Java Development Kit (JDK) is a software development
environment which is used to develop Java applications
• It contains JRE + development tools.
Structure of Java Programs

class class-name {
public static void main(String args[]) {
statement1;
statement2;


}
}
Example Program

“First.java”
class First {

public static void main(String args[]) {


System.out.println(“Hello World”);
}

}
Compiling & Running the Program

Compiling: is the process of translating source code written in a particular


programming language into computer-readable machine code that can be
executed.
$ javac First.java
This command will produce a file ‘First.class’, which is used for running the
program with the command ‘java’.

Running: is the process of executing program on a computer.


$ java First
About Printing on the Screen

1. System.out.println(“Hello World”); – outputs the string


“Hello World” followed by a new line on the screen.
2. System.out.print(“Hello World”); - outputs the string “Hello
World” on the screen. This string is not followed by a new
line.
3. Some Escape Sequence –
• \n – stands for new line character
• \t – stands for tab character
Some Tips About Programming

• Some common errors in the initial phase of learning programming:


- Mismatch of parentheses
- Missing ‘;’ at the end of statement
- Case sensitivity

• The best way to learn programming is writing a lot of programs on your


own.
Storing data
In Java, Data can be stored as
• Numbers
2, 6.67, 0.009
• Characters
‘c’, ‘p’, ‘?’, ‘2’
• Strings
“data”, “Hindi language”, “$99”, “www.rediff.com”

6 June 2021 Java Tutorial series part 2 16


Program
// this program will declare and print a number
class int2
{
public static void main(String[] arguments)
{
int weight = 68;
System.out.println("your weight is " + weight);
}
}
//end of program

6 June 2021 Java Tutorial series part 2 17


Comments(double slash)
• Not executed
• For documentation
• Can be placed on any line
• Anything written after // is not executed
• E.g.
// this is a comment
• Used to explain/describe what is done in the program
• Good practice

6 June 2021 Java Tutorial series part 2 18


Types of numbers
• int
Whole numbers like 0, 575, -345 etc.

• double
Numbers with decimal point
like 12.453, 3.432, 0.0000002

6 June 2021 Java Tutorial series part 2 19


Variable declaration
• Variable is the name of the memory location reserved for
storing value.

6 June 2021 Java Tutorial series part 2 20


Data types in Java

• A data type in java is a term that specifies memory size and


type of values that can be stored into the memory location.
• Let’s take some examples to understand better.
• 1. Variable x can store an integer number like 100 as: x = 100; //
Here, = represents that value 100 is stored into x.
• 2. String name = “Deep”; // Here, String is a data type and
name is a variable that can take only string values.
char1

Character data char2

• Characters
‘a’, ‘A’, ‘c’ , ‘?’ , ‘3’ , ‘ ’
(last is the single space)
• Enclosed in single quotes
• Character variable declaration
char ch;
• Character assignment
ch = ‘k’;

6 June 2021 Java Tutorial series part 2 23


string
1
String data string
2
string
3
• Strings are sequence of characters enclosed in double quotes
• Declaration
String name;
String address;
String line;
• Assignment
name = “ram”;
line = “this is a line with spaces”;
name = “a”; // single character can be stored
name = “”; // empty string
• The sequence of characters enclosed in double quotes, printed in println() are also
strings.
• E.g. System.out.println( “Welcome ! “ );

6 June 2021 Java Tutorial series part 2 24


Practice problem
• Try to print these two figures on the screen using println and least number of
strings

*******
*****
***
*
***
*****
*******

**********
* *
* *
* *
**********

6 June 2021 Java Tutorial series part 2 25


Java Operators
Java Operators | A programmer generally makes a program to perform some operation. For example, we
can perform the addition of two numbers just by using + symbol in a program.
Types of Operators in Java

• Arithmetic operators: +, -, *, /, etc.


• Relational operators: <, >, <=, >=, = =, !=.
• Logical operators: &&, ||, !.
• Assignment operators: =,
• Increment and decrement operators: + +, – –
• Conditional operators: ?:
• Bitwise operators: &, !, ^, ~, <<, >>, >>>
• Shift operators: <<, >>, >>>.
Java Control Statement
Types:
• Decision Making
• Looping Statement
• Branching Statement
Decision Making-Statement
• if statement
• if-else statement
• if-else-if ladder
• Switch case
Java if Statement

• The Java if statement tests the condition. It executes the if block if


condition is true.

if(condition){
//code to be executed
}
Java if-else Statement
• The Java if-else statement also tests the condition. It executes
the if block if condition is true otherwise else block is executed.
• Syntax
if(condition){
//code if condition is true
}
else{
//code if condition is false
}
Java if-else-if ladder
• The if-else-if ladder statement executes one condition from multiple
statements.

• Syntax
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{
//code to be executed if all the conditions are false
Java Switch Statement
• The Java switch statement executes one statement from
multiple conditions. It is like if-else-if ladder statement.
switch(expression){
case value1:statement;
break;
case value2:statement;
break;
default:
//code to be executed if all cases are not matched;
}
Type Conversion/Casting
• Type Conversion or Type Casting is the process of converting a
variable of one predefined type into another. If these data types
are compatible with each other, the compiler automatically
converts them and if they are not compatible, then the
programmer needs to typecast them explicitly
1.Implicit (Automatic) Type Conversion
2.Explicit Type Conversion
Implicit Type Conversion
• Implicit Type Conversion or Automatic type conversion is a
process of automatic conversion of one data type to another by
the compiler, without involving the programmer.
• This process is also called Widening Conversion because the
compiler converts the value of smaller size into a value of a
larger size data type without loss of information.
Conversions:
• Byte(size 1 byte) ——— is convertible to ————-> short, int,
long, float, or double
Short(2 byte) ——— is convertible to ————-> int, long, float,
or double
char(2 byte) ——— is convertible to ————-> int, long, float,
or double
int (4 byte)——— is convertible to ————-> long, float, or
double
long (8 byte)——— is convertible to ————-> float or double
float(4 byte)——— is convertible to ————-> double
Example:
int intVariable = 25;
long longVariable = intVariable;
float floatVariable = longVariable;
double doubleVariable = floatVariable;
System.out.println("Integer value is: " +intVariable);//25
System.out.println("Long value is: " +longVariable);//25
System.out.println("Float value is: " +floatVariable);//25.0
System.out.println("Double value is: " +doubleVariable);//25.0
Explicit Type Conversion

• The Explicit Type Conversion is a process of explicitly


converting a type to a specific type. We also call it Narrowing
Conversion. The typecasting is done manually by the
programmer, and not by the compiler
• We need to do explicit or narrowing type conversion when the
value of a (higher size) data type needs to be converted to a
value of a (lower size) data type. For example, double data
type explicitly converted into int type.
Example:
double doubleVariable = 135.78;
//explicit type casting
long longVariable = (long)doubleVariable;
//explicit type casting
int intVariable = (int)longVariable;
System.out.println("Double value: "+doubleVariable); //135.78
System.out.println("Long value: "+longVariable);//135
System.out.println("Integer value: "+intVariable);//135
• Upcasting in Java
• Upcasting is casting a subtype to a supertype, upward to
the inheritance tree. Upcasting happens automatically and
we don’t have to explicitly do anything
Looping Statement
• In programming languages, loops are used to execute a set of
instructions/functions repeatedly when some conditions become
true. There are three types of loops in Java.
• for loop
• While loop
• Do while loop

44
For Loop
• The Java for loop is used to iterate a part of the program several times.
If the number of iteration is fixed, it is recommended to use for loop.
• Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
e.g
For(i=1;i<=5;i++)
{
Sop(“Hello”);
}
While Loop
• The java while loop is used to iterate a part of
the program several times. If the number of iteration is not fixed,
it is recommended to use while loop.

Syntax:
while(condition){
//code to be executed
}
Do-while Loop
• The Java do-while loop is used to iterate a part of the program
several times. If the number of iteration is not fixed and you
must have to execute the loop at least once, it is recommended
to use do-while loop.
do{
//code to be executed
}while(condition);
Java Break

• When a break statement is encountered inside a loop, the


loop is immediately terminated and the program control
resumes at the next statement following the loop.
• E.g
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
Java Arrays
• Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory
location.
• Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.

Sami Infotech Java Basics 49


Advantages of Array & Types
• Code Optimization: It makes the code optimized, we
can retrieve or sort the data efficiently.
• Random access: We can get any data located at an
index position.

• There are two types of array.


• Single Dimensional Array
• Multidimensional Array

Sami Infotech Java Basics 50


single dimensional array
• A single dimensional array is a normal array that you will use most
often. This type of array contains sequential elements that are of the
same type, such as a list of integers.
• Array declaration
• int a[]=new int[5];
• a[0]=1;
• a[1]=2;
• a[2]=3;
• a[3]=4;
• a[4]=5;

• int a[]= {1,2,3,4,5};


Multi dimensional Array
• In such case, data is stored in row and column based index (also known as matrix
form).
e.g.int[][] arr=new int[3][3];//3 row and 3 column

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Array of Objects in Java
• Java is an object-oriented programming language. Most of the
work done with the help of objects. We know that an array is a
collection of the same data type that dynamically creates
objects and can have elements of primitive types.
• An array that conations class type elements are known as
an array of objects.
• Syntax:

ClassName obj[]=new ClassName[array_length]; //declare and in


stantiate an array of objects
OOPs Concepts in Java
• Object oriented programming is a new approach to overcome the drawbacks
of a procedural oriented approach. It divides programs into the number of
entities called objects that contain data (variables) and functions/tasks
(known as methods in java).

54
Object
• Object: A real-world entity that has state and behavior is called
object in java. Here, state represents properties and behavior
represents actions and functionality. For example, a person,
chair, pen, table, keyboard, bike, etc.
• The object is an instance of a class.
Class
• Class: A class is basically user-defined data types. It
represents the common properties and actions (functions) of an
object.
• For example, bus and car are objects of vehicle class. Sparrow
and parrot are objects of birds class. Similarly, MS Dhoni,
Sachin Tendulkar, and Virat Kohali are objects of cricketer
class.
Syntax:
Class:
• <access-modifier> class <ClassName>
•{
• //Class body containing variables and methods
•}

• Object:
• ClassName objectName = new ClassName();
Methods in Java
• method is a way to perform some task. Similarly, the method in
Java is a collection of instructions that performs a specific task.
It provides the reusability of code. We can also easily modify
code using methods.
• The main() method is the first method that is executed by JVM
(Java Virtual Machine) in java program.
Method Declaration
Constructor in Java

• In Java, 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.
• Characteristics of Constructor
1.Constructor’s name must be the same as its name of the class
in which it is declared and defined.
2.A Constructor must have no explicit return type
3.A Java constructor cannot be abstract, static, final
Types of Java constructors

There are two types of constructors in Java:


1.Default constructor (no-arg constructor)
2.Parameterized constructor
Default Constructor
Parameterized constructor
S
Constructor Method
N
Constructor is a special type of
Method is used to expose the behaviour of
1. method that is used to initialize the
an object.
state of an object.
2. It has no return type even void also. It has both void and return type.
If we don’t provide any constructor in
Method is not provided by the compiler in
3. the class, Java Compiler provides a
any case.
default constructor for that class.
Constructor name must be the same Method name may or may not be the
4.
as name of the class. same name as the class name.
The purpose of a constructor is to The purpose of a method is to execute the
5.
create an object of a class. functionality of the application.
6. They are not inherited by subclasses. They are inherited by subclasses.
Method Overloading Java
• When there are two or more than two methods in a class that
have the same name but different parameters, it is known as
method overloading
• void divide(int a, int b){...}
• Void divide(int a, int b, int c){…}
• void divide(double x, double y){...}
Constructor Overloading in Java
Java Static keyword
• The static keyword in java is used for memory management
mainly. We can apply static keyword with variables methods,
blocks
• The static can be:
1.Variable (also known as a class variable)
2.Method (also known as a class method)
3.Block
1) Java static variable
If you declare any variable as static, it is known as a static variable.
• The static variable can be used to refer to the common property of all objects.
for example, the company name of employees, college name of students, etc.
e.g:
class Employee{
int id;
String name;
String company=“TCS”,
}
Suppose there are 500 Employee in my company, now all instance data members
will get memory each time when the object is created. All Employee have its
unique id and name, so instance data member is good in such case. Here,
company refers to the common property of all objects. If we make it static, this
field will get the memory only once;
2) Java static method

• If you apply static keyword with any method, it is known as static


method.
• Rules:
• A static method belongs to the class rather than the object of a
class.
• 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.
• 3) Java static block
• It is executed before the main method at the time of classloading.

class Demo{
static{
System.out.println(“this is static block");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Can we execute a program without main() method?

• Ans) No, one of the ways was the static block, but it was
possible till JDK 1.6. Since JDK 1.7, it is not possible to execute
a Java class without the main method.
class A3{
static{
System.out.println("static block is invoked");
}
}
What is Inheritance?
• Inheritance is one of the main four pillars (core concepts) of
OOPs (Object Oriented Programming) concepts in Java. It is a
technique of organizing information in a hierarchical form.
• Inheritance is a mechanism in which one class acquires the
property of another class. For example, a child inherits the traits
of his/her parents. With inheritance, we can reuse the fields and
methods of the existing class.

• The existing class is called parent class (a more general class)


and the new class is called child class (a more specialized
class). The child class inherits data and behavior from the
parent class
Types of Inheritance in Java
Method Overriding
1.The method must have the same name as in the
parent class
2.The method must have the same parameter as in the
parent class.
3.There must be an IS-A relationship (inheritance).
Final Keyword In Java
• The final keyword in java is used to restrict the user.
• Final can be:
1.variable
2.method
3.class
• If you make any variable as final, you cannot change the
value of final variable
• If you make any method as final, you cannot override it.
• If you make any class as final, you cannot extend it.
Abstraction in Java

• Abstraction in Java is another OOPs principle that manages


complexity. It is a process of hiding complex internal
implementation details from the user and providing only
necessary functionality to the users.
• A class which is declared as abstract is known as an abstract
class. It can have abstract and non-abstract methods.
• There are two ways to achieve or implement abstraction in java
program. They are as follows:
1.Abstract class (0 to 100%)
2.Interface (100%)
• Realtime Examples of Abstraction in Java
Interface
• It is much similar to the Java class but the only difference is
that it has abstract methods. There can be only abstract
methods in an interface, that is there is no method body inside
these abstract methods.
• interface interface-name
•{
• //abstract methods
•}
Example:
• interface Animal
•{
• public void eat();
• public void travel();
•}
How to achieve multiple inheritance…

Class A Class B

Class C
Package
• PACKAGE in Java is a collection of classes, sub-packages,
and interfaces. It helps organize your classes into a folder
structure and make it easy to locate and use them. More
importantly, it helps improve code reusability.
• Package in java can be categorized in two form, built-in
package and user-defined package.
• There are many built-in packages such as java, lang,
awt, javax, swing, net, io, util, sql etc.
• E.g package Demopkg2;
• package Demopkg;
import Demopkg.*;
public class B {
• public class A {

public static void


main(String[] args) {
• public void get() { A a1=new A();
• System.out.println("hi"); a1.get();
}
• }
• } }
Wrapper class in Java

• A Wrapper class in Java is the type of class that provides a


mechanism to convert the primitive data types into the objects
and vice-versa.
• autoboxing and unboxing feature convert primitives into
objects and objects into primitives automatically.
• The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.
Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double
Use of Wrapper classes in Java
• Java is an object-oriented programming language, so we need
to deal with objects many times like in Collections,
Synchronization, etc.
1) Synchronization: Java synchronization works with objects in
Multithreading.
2) Collection Framework: Java collection framework works with
objects only. All classes of the collection framework (ArrayList,
LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.
Primitive to Wrapper

//Converting int into Integer


int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//
autoboxing, now compiler will write Integer.valueOf(a) internally
Wrapper to Primitive

Integer a=new Integer(3);


int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
Real use in collection
• List<Integer> list = new ArrayList<>(); list.add(1); // autoboxing
Integer val = 2; // autoboxing

• Number[] arr=new Number[10];


• arr[0]=new Integer(12);
• arr[1]=new Double(22.22); //and so on
Access modifiers
• Java provides four explicit access modifiers in object-oriented
programming languages. They are private, default, protected,
and public as shown in the below figure.

Access within class within package outside outside


Modifier package by package
subclass only

Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
• The access modifiers in Java specifies the accessibility or
scope of a field, method, constructor, or class.
• There are four types of Java access modifiers:
1.Private: The access level of a private modifier is only within
the class. It cannot be accessed from outside the class.
2.Default: The access level of a default modifier is only within
the package. It cannot be accessed from outside the
package. If you do not specify any access level, it will be the
default.
3.Protected: The access level of a protected modifier is within
the package and outside the package through child class. If
you do not make the child class, it cannot be accessed from
outside the package.
4.Public: The access level of a public modifier is everywhere.
It can be accessed from within the class, outside the class,
within the package and outside the package.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Example of default access modifier
In this example, we have created two packages pack and mypack. We are
accessing the A class from outside its package, since A class is not public, so it
cannot be accessed from outside the package.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
The protected access modifier is accessible within package and outside the package
but through inheritance only.
In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg method of
this package is declared as protected, so it can be accessed from outside the class only
through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
Encapsulation in Java
• The process of binding data and corresponding methods
(behavior) together into a single unit is called encapsulation in
Java.
• Every Java class is an example of encapsulation because we
write everything within the class only that binds variables and
methods together.
• Realtime Example 1:
School bag is one of the most real examples of Encapsulation.
School bag can keep our books, pens, etc.
package encapPrograms;
public class Student
{
private String name;
public String getName()
{
return name;
}
public void setName(String studentName)
{
name = studentName;
}
}
• We can create a fully encapsulated class in Java by making
all the data members of the class private. Now we can use
setter and getter methods to set and get the data in it.
• Private variable can only be accessed within the same
class(an outside class has no access to it).
• It is possible to access them if we provide public get and
set method.
• get method returns the variable value and set method sets
the value.
class EncapsulationTest
{
public static void main(String[] args)
{
Student obj = new Student();// Creating object of Student class
by using new keyword.
obj.setName("Amit"); // setting the value of variable.
String studentName = obj.getName(); // reading the value of
variable.
System.out.println(studentName);
}
}
Solve Ex:

Customer
TestClass
Al member
private
Id Access all
Name members of
Age
customer class
Phone no

getter/setter
• Polymorphism in java is one of the core concepts of object-oriented
programming language. The word polymorphism is derived from two
Greek words: poly and morphs.
Aggregation
• Aggregation represents HAS-A relationship.
• which means when a class contains reference of another class
known to have aggregation.

Student
Name
Address
Address
City
State
country
• Solve this one

Book
Name
Price
Author
author

Author name
Age
place
Java String
Java String is basically an array of characters.
The java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:
By string literal
String s="welcome";

By new keyword
String s=new String("Welcome")
Immutable String in Java

• In java, string objects are immutable. Immutable simply means


unmodifiable or unchangeable.
• Once string object is created its data or state can't be changed but a new
string object is created.

String s=“Java";
• s.concat(" program");
• System.out.println(s);//will print java
because strings are immutable objects
String memory management
• Strings created using new keyword, always creates a new string
object in the heap memory.

• When a string is created using string literals, jvm checks if the string
object is already present in the string constant pool or not.

• If the object is not present, then jvm creates a new object, else if the
object is already present, jvm creates a new reference to the previous
object.
Java String compare
There are three ways to compare string in java:
1) By equals() method
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true

2) By = = operator
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3)
/false(because s3 refers to instance created in nonpool)
compareTo() method

String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}}
Java StringBuffer class
Java StringBuffer class is used to create mutable (modifiable)
string. The StringBuffer class in java is same as String class
except it is mutable i.e. it can be changed.
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java

Java StringBuffer class is thread-safe i.e. multiple threads cannot


access it simultaneously. So it is safe and will result in an order
Java StringBuilder class

Java StringBuilder class is used to create mutable (modifiable)


string. The Java StringBuilder class is same as StringBuffer class
except that it is non-synchronized.
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
Difference between String Buffer and
StringBuilder
StringBuffer StringBuilder

1) StringBuffer StringBuilder is non-


is synchronized i.e. thread synchronized i.e. not thread
safe. It means two threads safe. It means two threads
can't call the methods of can call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.

2) StringBuffer is less StringBuilder is more


efficient than StringBuilder. efficient than StringBuffer.
Exception Handling in Java
• The Exception refers to some unexpected or contradictory situation or
an error that is unexpected.
• These are the situations where the code-fragment does not work right.
• There are two types of errors
• 1. Compile-time errors in Java
• Compile-time errors are the errors resulting from a violation of
programming language’s grammar rules e.g., writing syntactically
incorrect statements like
• System.out.println “A Test”;
• will result in a compile-type error because of invalid syntax.
• 2. Run-time errors in Java
• Runtime errors occur during runtime or execution of the
program because of unexpected situations. We use Exception
handling routines of Java to handle .
• Some common examples of Exception are:
• Divide by zero errors
• Accessing the array elements beyond the range.
• Invalid input
• Hard disk crash
• Opening a non-existent file
1. Checked Exceptions in Java
Checked Exception which is also called compile-time exceptions occurs at
the compile time.E.g:IOException, SQLException, etc.

2. Unchecked Exceptions in Java


Java Unchecked Exception which is also called Runtime Exceptions occurs
at runtime.E.g: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc.

3. Error in Java
Error is not an exception but it is an issue that emerges out of the control of
the user or the developer. VirtualMachineError,
Keyword Description

try The "try" keyword is used to specify a block


where we should place exception code. The
try block must be followed by either catch or
finally. It means, we can't use try block
alone.

catch The "catch" block is used to handle the


exception. It must be preceded by try block
which means we can't use catch block alone.
It can be followed by finally block later.

finally The "finally" block is used to execute the


important code of the program. It is
executed whether an exception is handled or
not.
throw The "throw" keyword is used to throw an
exception.
throws The "throws" keyword is used to declare
exceptions. It doesn't throw an exception. It
specifies that there may occur an exception
in the method. It is always used with method
signature.
throws keyword
• The Java throws keyword is used to declare an
exception. 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
Java throw example

void m(){
throw new ArithmeticException("sorry");
}

Java throws example

void m()throws ArithmeticException{

//method code

}
Java throw and throws example
void m()throws ArithmeticException{

throw new ArithmeticException("sorry");

}
Nested Classes
• A class created inside another class in known as nested or inner
class.
• It is a way of grouping classes that are used only at one place.
• Using nested classes increases encapsulation and creates more
readable and maintainable code.
Types of nested class

1. Member inner class


2. Static inner class
3. Anonymous inner class
4. Lambda expression
Static inner class:

A static inner class is like any other static member of class (Common
for all instances).
• Static inner class can access only the static members of class (can
be private).
• Static methods can be declared inside a static inner class.
Member inner class :

• A member inner class is like any other non-static member of class.


• Just like any member (non-static) of class, member inner class is also
accessed with the object of outer class.
• Member inner class can access the private members of the class
• Static methods cannot be declared inside a member inner class.
Anonymous Classes in Java
• A class that have no name is known as anonymous inner class in
java. It should be used if you have to override method of class or
interface.
• Java anonymous inner classes are useful when we need only
one object of the class.
• Since an anonymous inner class does not have a name, it cannot
have a constructor because we know that a constructor name is
the same as the class name.
• Java Anonymous inner class can be created by two ways:
1.Class (may be abstract or concrete).
2.Interface
When to use Anonymous Inner class in Java?

• An anonymous inner class can be used if the class has a very


short body.
• It can be useful if only one object of the class is required.
• An anonymous inner class is useful when you are writing
implementation classes for listener interfaces in graphics
programming.
• An anonymous inner class is the best suitable for GUI based
applications to implement event handling.
Restriction on Anonymous Inner class
1.We cannot create more than one object of the anonymous
inner class in Java.
2.Since an anonymous inner class has no name. Therefore, we
cannot declare a constructor for it within the class body.
Difference between Normal/Regular
class and Anonymous Inner class
• 1. A normal Java class can implement any number of interfaces
simultaneously but an anonymous inner class can implement only
one interface at a time.
• 2. A normal Java class can extend a class and can implement any
number of interfaces simultaneously but an anonymous inner class
can extend a class or can implement an interface but not both
simultaneously.
• 3. In a normal Java class, we can define any number of constructors
but in an anonymous inner class, we cannot write any constructor
explicitly (because the name of the class and name of the constructor
must be the same but anonymous inner class not having any name).
Multithreading
• Multithreading in java is a process of executing multiple
threads simultaneously. Multithreading is a Java feature
that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such
program is called a thread.
Advantages of Java Multithreading

1. It doesn’t block the user because threads are independent


and you can perform multiple operations at same time.
2. You can perform many operations together so it saves
time.
3. Threads are independent so it doesn’t affect other threads if
exception occur in a single thread.
• 1) New
• The thread is in new state if you create an instance of Thread class but before
the invocation of start() method.
• 2) Runnable
• The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
• 3) Running
• The thread is in running state if the thread scheduler has selected it.
• 4) Non-Runnable (Blocked/Wait)
• This is the state when the thread is still alive, but is currently not eligible to run.
• 5) Terminated
• A thread is in terminated or dead state when its run() method exits.
• Commonly used methods of Thread class:
1. public void run():
2. public void start():
3. public void sleep(long miliseconds):
4. public void join(long miliseconds): waits for a thread to die
5. public int getPriority(): returns the priority of the thread.
6. public int setPriority(int priority): changes the priority of the thread.
7. public String getName(): returns the name of the thread.
8. public void setName(String name): changes the name of the thread.
9. public Thread currentThread(): returns the reference of currently executing thread.
10. public void stop()
• Thread Class vs Runnable Interface
• 1. If we extend the Thread class, our class cannot extend
any other class because Java doesn’t support multiple
inheritance. But, if we implement the Runnable interface,
our class can still extend other base classes.
• 2. We can achieve basic functionality of a thread by
extending Thread class because it provides some inbuilt
methods like yield(), interrupt() etc. that are not available in
Runnable interface.
Thread Pool

• Normally, server creates a new thread when a new request


comes. This approach have several disadvantages. For creating
a new thread for every new request will take more time and
resources. Thread pool concept is introduced to resolve these
problems
• Thread pool in java
• A thread pool represents a group of threads which are waiting
the job and can be used many times. In case of thread pool,
when a new request comes then instead of creating a new
thread, the job can be passed to thread pool.
• Note: Thread pool helps us to limit the number of threads
running in our application.
• thread pool is a group of threads that we can reuse for various tasks
in a multithreading environment. The thread pool may be of a fixed
size where each thread performs a task and once it completes it again
goes back to the pool. In this way, each thread can execute more than
1 task. This reduces the overhead of creating multiple threads for
different tasks.
• Advantages of a Thread pool
• Better performance
• Less resource required
• Reduced overhead
• Disadvantages of a Thread pool
• Chances of deadlock
• Thread leakage
Key Daemon User Threads
Threads
Nature Daemon thread is low in priority i.e JVM User threads are recognized as high
does not care much about these types priority thread i.e. JVM will wait for any
1 of threads. active user thread to get completed.

CPU It is not guaranteed that Daemon User thread always gets preference in
availability thread always gets CPU usage getting CPU usage because of its
2 whenever it requires due to its low higher priority.
priority.

Creation Daemon threads are executed in the While user thread is usually created by
background state so generally named the application for executing some
3
as background threads. tasks concurrently.

Execution Daemon threads are executed in the User threads are called foreground
Ground background state so generally named threads on another hand.
4
as background threads.
What is File Handling in Java?

• File handling in Java implies reading from and writing data


to a file. The File class from the java.io package, allows us
to work with different formats of files.
• What is a Stream?
• In Java, Stream is a sequence of data.
• 1. Byte Stream
• This mainly incorporates with byte data. When an input is
provided and executed with byte data, then it is called the file
handling process with a byte stream.
• 2. Character Stream
• Character Stream is a stream which incorporates with
characters. Processing of input data with character is called
the file handling process with a character stream.
It tests whether the file
canRead()
is readable or not

It tests whether the file


canWrite()
is writable or not

This method creates an


createNewFile()
empty file

delete() Deletes a file

It tests whether the file


exists()
exists

Returns the name of the


getName()
file

Returns the absolute


getAbsolutePath()
pathname of the file

Returns the size of the


length()
file in bytes
Some imp syntax….
• 1) for creating new file…
• File f=new File(“path”)
• if(f.createNewFile())

2) Write Data into file…


• FileWriter f=new FileWriter(“path”);
• f.write("welcome in my java file");
Reading data into file…
• Algorithm……
File f=new File(“path");
Scanner sc=new Scanner(f);
while(sc.hasNextLine())
{
String s=sc.nextLine();
System.out.println(s);
}
sc.close();
}
Serialization and Deserialization in Java
• Serialization is a mechanism of converting the state of an
object into a byte stream. Deserialization is the reverse
process where the byte stream is used to recreate the actual
Java object in memory.
• To make a Java object serializable we implement
the java.io.Serializable interface.

• The serializable interface in java is a marker


interface(method with no body).
• The ObjectOutputStream class contains writeObject() method
for serializing an Object.

• The ObjectInputStream class contains readObject() method


for deserializing an object.
Steps to serialization…..
• FileOutputStream fos=new FileOutputStream(“file path”);
• ObjectOutputStream oos=new ObjectOutputStream(fos);
• oos.writeObject(obj);
Map Interface

• A map contains values on the basis of key, i.e. key and


value pair. Each key and value pair is known as an
entry. A Map contains unique keys.
• A Map is useful if you have to search, update or delete
elements on the basis of a key.
TreeMap
• ava TreeMap contains values based on the key.
• Java TreeMap contains only unique elements.
• Java TreeMap cannot have a null key but can have
multiple null values.
difference between List and Set

• The List can contain duplicate elements whereas Set


includes unique items.
• The List is an ordered collection which maintains the
insertion order whereas Set is an unordered collection
which does not preserve the insertion order.
• The List interface contains a single legacy class which is
Vector class whereas Set interface does not have any
legacy class.
• The List interface can allow n number of null values
whereas Set interface only allows a single null value.
difference between HashSet and TreeSet

• HashSet maintains no order whereas TreeSet


maintains ascending order.
• HashSet impended by hash table whereas TreeSet
implemented by a Tree structure.
• HashSet performs faster than TreeSet.
difference between Set and Map?

• Set contains values only whereas Map contains key and


values both.
• Set contains unique values whereas Map can contain
unique Keys with duplicate values.
• Set holds a single number of null value whereas Map
can include a single null key with n number of null
values.
• Java Comparable interface is a member of the collection
framework which is used to compare objects and sort them
according to the natural order.
• It use the compareTo() method which is defined as
comparable interface.
Imp:toString() method returns the String representation of the object.
String class and Wrapper classes implement the Comparable
interface by default.
Comparator Interface

In Java, Comparator interface is used to order(sort) the objects in


the collection in your own way. It gives you the ability to decide
how elements will be sorted and stored within collection and
map.
Comparator Interface defines compare() method. This method
has two parameters.
JDBC
• Java Database Connectivity(JDBC) is an Application
Programming Interface(API) used to connect Java
application with Database. JDBC is used to interact with
various type of Database such as Oracle, MS Access, My SQL
and SQL Server.
JDBC Driver

• Type-1 Driver or JDBC-ODBC bridge


• Type-2 Driver or Native API Partly Java Driver
• Type-3 Driver or Network Protocol Driver
• Type-4 Driver or Thin Driver
• Type-1 Driver act as a bridge between JDBC and other
database connectivity mechanism(ODBC).
• In Java 8, the JDBC-ODBC Bridge has been removed.
• Native API Driver
• This type of driver makes use of Java Native Interface(JNI)
call on database-specific native client API.
• Network Protocol Driver
• This driver translates the JDBC calls into a database server
independent and Middleware server-specific calls.
• Thin Driver
• This is Driver called Pure Java Driver because. This driver
interact directly with database. It does not require any native
database library, that is why it is also known as Thin Driver.
• DriverManager class
• This class is used to have a watch on driver which is been
used for establishing the connection between a database and
a driver.
• Connection interface
• The Connection interface is used for creating the session
between the application and the database. This interface
contains Statement, PreparedStatement and
DatabaseMetaData.
• Statement interface
• The Statement interface is used for executing queries using
the database. This interface is a factory of ResultSet. It is
used to get the Object of ResultSet.
• ResultSet interface
• the ResultSet Interface is used for maintaining the pointer to a
row of a table. In starting the pointer is before the first row.
The object can be moved forward as well as backward
direction
• PreparedStatement interface
• The PreparedStatement interface is a subinterface of
Statement. It is mainly used for the parameterized queries. A
question mark (?) is passed for the values. The values to this
question marks will be set by the PreparedStatement.
• ResultSetMetaData Interface
• The ResultSetMetaData interface is used to get metadata
from the ResultSet object.
Steps to connect a Java Application to Database
Design Patterns in Java
• A design patterns are well-proved solution for solving the specific
problem/task.
• Problem Given:
Suppose you want to create a class for which only a single instance
(or object) should be created and that single object can be used by
all other classes.
• Solution:
Singleton design pattern is the best solution of above specific
problem. So, every design pattern has some specification or set
of rules for solving the problems.
Categorization of design patterns:

Core Java (or JSE) Design Patterns.


1.Creational Design Pattern
2. Structural Design Pattern
3.Behavioral Design Pattern
JEE Design Patterns.
1. Presentation Layer Design Pattern
2. Business Layer Design Pattern

You might also like