Java Full Stack 2.0: Introduction To JAVA Day - 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 265

JAVA FULL STACK 2.

0
Introduction to JAVA

DAY -1
Hi There....

ABOUT PANTECH?
Educational Equipment Manufacturer | Technical Training | DIY Project

A. IOT
B. PROGRAMMABLE SOLUTION PROVIDER – AI , ML & JAVA
C. AI/ROBOTICS/AUTONOMOUS ROBOT,
MICROPROCESSOR/MICROCONTROLLER
D. DSP,VLSI, EMBEDDED SYSTEM/
E. POWER ELECTRONICS & DRIVES, FUEL CELL TRAINER KIT
F. RENEWABLE ENERGY LAB, ELECTRIC VEHICLE LAB
OUR VISION

Students to
Help 10 Million
Learn the Technology in Easy Way
NANDHINI.S
•5 year of Industry Experience
•Expertise in JAVA , Python and ML Implementations
•Language – Python , Java , HTML ,CSS.
•Tools – ANACONDA NAVIGATOR, JUPYTER NOTEBOOK
•GOOGLE COLAB.
WHAT IS MASTER CLASS ?
👍This is the 30 Days Industrial Learning Activity.

👍 Its Online YouTube Live Class

👍 If you Invest 45 minutes daily, U will become Master in Java

👍 You will get E-Certificate

WEBINAR PARTICIPATION CERTIFICATE


HOW TO MARK YOUR
ATTENDANCE IN YOUTUBE
LIVE CLASS?

organizer will post
Ans : During the Live Class,
Google Form link in Live Chat Only
NOTE : THE LINK WILL BE AVAILABLE DURING THE LIVE. FROM
THE LIVE CLASS DATE, THE LIVE VIDEO WILL GET REMOVED
FROM THE YOUTUBE IN 3 DAYS.

Associate Partner
PARTICIPATION
CERTIFICATE OF
CERTIFICATE PARTICIPATION
25 DAYS YOUR NAME
YOUR COLLEGE NAME
has Successfully Completed
30 DAYS JAVA FULL STACK PROGRAM
at Pantech e Learing Pvt Ltd, Chennai

Director, Pantech
WHAT U WILL
LEARN FROM THIS
MASTERCLASS
JAVA
Introduction To Java and OOPS
Concepts

HTML
Basic elements, Paragraphs,
JAVA FULL Colors, Forms, Input Types

STACK SERVLETS
Introduction, Exceptions,
LEARNING Database Access

PLAN MYSQL JDBC


Mysql Introduction, JDBC
Components, Examples
Create A web app
JAVA WEB APP
Project Building
OUR AGENDA
Day 1- Java Introduction | Installation
Day 2- Java Variables – Identifiers , Datatype, Classes and Objects
Day 3- Java Comments – Single line comments , multi-line comments
Day 4- Loops – Different types of loops , Decision Making Statements
Day 5- Ternary Operator , switch statement , Arrays and methods in Java
Day 6- Java Package , Access Modifiers , Java Strings, String Methods.
Day 7- Inheritance , Method Overloading , Method Overriding.
Day 8- Java – Type Casting , Abstract Class , Interface.
Day 9- Java Package , Access Modifiers, Encapsulation, Wrapper Class.
Day 10- Java Regular Expressions, Exception Handling .
Day 11- HTML Basic, Elements , Attributes , Headings
Day 12- HTML – Colors , CSS, links, images ,tables
Day 13- HTML – Forms, Form Attributes , Form Elements

Day wise Learning Day 14- Servlet – Introduction, Life Cycle


Day 15- Servlets – Examples, Form Data, Client Request

Plan 1 -15
OUR AGENDA
Day 16- Servlets – Server Response , Http Codes , Writing Filters
Day 17- Servlets – Exceptions , Cookies Handling , Session Tracking
Day 18- Servlets – Database Access, File Uploading , Handling Date.
Day 19- MySQL – Introduction, Installation, Create Database, Drop database.
Day 20- MySQL – Data Types , Create Tables, Drop Tables, Insert Query
Day 21-MySQL – Select Query , Where Clause, Update Query , Delete Query, Like
Clause , Sorting Results , Using Join.
Day 22-Introduction To JDBC, Jdbc Components , Driver Connections.
Day 23-JDBC Examples.
Day 24-JDBC Transactions.
Day 25- Erasure Coding
Day 26-Public Auditing
Day 27-Counselling Management System

Day wise Learning


Day 28 -Software Puzzle
Day 29 - Crime Management System.

Plan 16 - 30
Day 30 -Secure Multi-Owner Data Sharing.
OUR AGENDA
1. Erasure Coding(Day 25)
2. Public Auditing(Day 26)
List of Projects for 3. Counselling Management System(Day 27)
Demo in YouTube 4. Software Puzzle(Day 28)
5. Crime Management System(Day 29)
Live 6. Secure Multi-Owner Data Sharing(Day 30)

ALL PROJECTS IN NETBEANS


INTRODUCTION TO JAVA
WHAT IS JAVA?
It is an Object-Oriented Programming Language developed by
Sun Microsystems and released in the year 1995.
Platform independent(i.e. , it can run on any platform).
Mainly based on the OOPS concept(Object Oriented
Programming Systems).
It can be combined with other technologies like Spring ,
Hadoop and Android.
WHY JAVA?
Easier to code and more secure than other programming languages.
Supports multithreading(i.e. , it can handle more than one request at a
time).
Supports method reusability(i.e, a method can be written only once and
used anywhere in the program which results in the reduction of code).

Other features of Java like Polymorphism , Abstraction, Encapsulation and Inheritance


makes the programming language more robust and efficient.
WHY JAVA?
Scalability:
We can achieve scalability by increasing the resources such as RAM and
CPU in a single system.

Memory – Management:
Java provides its own mechanism for managing the memory is known as
garbage collection.
It automatically deletes the objects when they no longer used by the
application. It improves the speed of the application.
REASONS TO LEARN JAVA
It is one of the hottest programming languages in today’s world.
Millions of applications can be built with Java Programming Language.
Java is used in a variety of industries like tech , government , finance ,
healthcare , insurance , education and more.
The entry-level salary of a Java Developer is $59,053. With more
experience , the salary can exceed $100,000.
So, Java developers make more money.
COMPONENTS OF JAVA
JVM: It provides an environment for executing Java
Programs.
JDK: It is a software development environment and it contains
the compiler , debugger and other classes to compile and debug
a software program.
JRE: It provides a runtime environment to execute the Java
programs and other applications.
APPLICATIONS OF JAVA:
Mobile App Development:
Most of the android applications build using Java.
The most popular android app development IDE Android
Studio also uses Java for developing android applications.
APPLICATIONS OF JAVA:
Desktop GUI Applications:
We can also develop a GUI application using Java.
Java provides AWT, JavaFX, and Swing for
developing the GUI based desktop application.
APPLICATIONS OF JAVA:
Web - Based Applications
It is also used for developing the web-based application
because it provides vast support for web development
through Servlet, JSP, and Struts.
It is the reason that Java is also known as a server-side
programming language. Using these technologies,
we can develop a variety of applications.
The most popular frameworks Spring, Hibernate, Spring
Boot, used for developing web-based applications.
APPLICATIONS OF JAVA:
Game Development
Java is widely used by game development companies
because it has the support of the open-source most
powerful 3D engine.
The engine provides unparalleled capacity when it
comes to the context of the designing of 3D games.
APPLICATIONS OF JAVA:
Big Data Technology:

The tool Hadoop HDFS platform for processing and storing big
data applications is written in Java.
In big data, Java is widely used in ETL applications such as
Apache Camel and Apache Kafka.
APPLICATIONS OF JAVA:
IOT Application
IoT is a technology that connects the devices in its network
and communicates with them.
IoT has found almost in all the small devices such as health
gears, smartphones, wearables, smart lighting, TVs, etc.

For developing the IoT application there is a lot of programming languages that can be
used but Java offers an edge to developers that is unparalleled.
ECLIPSE AND JDK INSTALLATION
Installation of jdk and adt bundle.
Steps involved in setting the jdk path.

1. Right Click My Computer-> Properties


2.Next Click-> Advanced System Settings
3.Click Environment variables
4.Click new
5.Write the variable name as path
6.Copy the jdk path till bin folder
7.Paste the path of bin folder in the variable value.
8.Click on the OK button.
9.Click on the OK button.
ECLIPSE INSTALLATION
Download Eclipse
Unzip the Eclipse file.
EXERCISE:
Write a program that stores a byte value and
displays the result to the screen.
YOU HAVE THE OPTION
TO CHOOSE WITH A
WEBINAR CERTIFICATE
OR GET ANY
INTERNSHIP
CERTIFICATE…
ON DEMAND
You can get chance to apply 1 Month

Internship on Java Full Stack Masterclass

https://imjo.in/gHNkDr
WHAT IS INTERNSHIP ?
OBJECTIVE OF THIS 30 DAYS
MASTER CLASS

PANTECH WILL
MAKE YOU TO
CREATE 6
PROJECTS IN JAVA
IN 30 DAYS
1 MONTH INTERNSHIP IN JAVA
INTERNSHIP E-Certificate (30Days Internship on Java Full Stack)
Highly organized Video content
Download Project Files
Download PPTs
Assignments
Weekly Hackathons
Flexible Time.
Access Period: 60 Days from the date of payment
Community or Forum Support
HOW TO ENROLL INTO
1 MONTH INTERNSHIP?
https://imjo.in/gHNkDr

COUPON CODE : JFSMC2


REG FEE : RS.1999
DISCOUNTED FEE: RS.999
Internship Last Date - 13.12.2022
ADD-ON
CORE JAVA CONCEPTS
Java Variables :
Variables are used to store values.
Variable Types determine the memory required to store
that variable.
JAVA IDENTIFIERS

Variable names must be a unique name.


Unique names are called identifiers. Identifiers can be small names(like a and b) or
some other name which provides information about what that variable contains.

Consider the following example


int totalSum = 60;


String color = “Red”
DATA TYPES IN JAVA
Consider the following example

int num1 = 10; // Integer (whole number)


float numFloat = 10.55f; // Floating point number
char firstCh = ‘R'; //
Character boolean firstBl = true; // Boolean
String firstTxt = "Hello"; // String

There are two different Data types in Java


Primitive data types - byte, short, int, long, float, double, boolean and char
Non-primitive data types – String , arrays and classes come under non-primitive datatype
JAVA FULL STACK 2.0
Comments in JAVA

DAY -3
PREVIOUS SESSION

CORE JAVA CONCEPTS

JAVA IDENTIFIERS

DATA TYPES IN JAVA


TODAY SESSION

JAVA COMMENTS

SINGLE LINE COMMENTS

MULTI LINE COMMENTS


EXERCISE:
Write a program that concatenates two strings and displays the result to the screen.
Solution:

public class Combinestr {


public static void main(String[] args) {
/* The line Welcome To India will be printed at the output*/
String a1= “Beautiful";
String a2= “Garden";
String gname = a1 + a2;
System.out.println(gname);
}}
Classes and Objects In Java
EXAMPLE
public class Person {
public void drink(){
System.out.println("Drinking milk");
}

public static void main(String[] args) {


Person p1 = new Person();
String name = "John";
System.out.println(name);
p1.drink();
}

}
OUTPUT

John
Drinking milk
EXERCISE
Find the error in the following code.
public class Flower{
public void blossom{
System.out.println(“Flowers blossom);
}

public static void main(String[] args) {


Flower f1 = Flower();
String name = “Rose";
System.out.println(name);
f1. blossom()
}

}
Solution:

public class Flower{


public void blossom(){
System.out.println(“Flowers blossom");
}

public static void main(String[] args) {


Flower f1 = new Flower();
String name = “Rose";
System.out.println(name);
f1. blossom();
}

}
Java Comments(Single Line Comments)

Comments provide a brief description of the java code.


Comments can be added to a particular part of the program so that that
part will not get executed while executing another part of the program.
SINGLE LINE COMMENTS

// Example Comment
System.out.println(“My First Comment");

ØAs you can see , in the above example , a comment is included before the code.

ØIn the below example , a comment is included at the end of the code.

System.out.println(“Second Comment"); // Comment at the end


Java Multi-line Comments:

Multi-line comments are represented by /* and */.


Java cannot see anything written between /* and */.
Example Program :
public class Multicomment {

public static void main(String[] args) {


/* The lineWelcome To India will be printed at the output*/
System.out.println("Welcome To India");

}
}
Task:
Exercise:
Write one sample program to illustrate single-line comment.
Find the error in the following program.
*/This is my first multi-line comment gets printed at the output*/ /
System.out.println(“This is my first multi-line comment");
Solution:
public class Commexample{
public static void main(String[] args) {
//Sample Comment
System.out.println(“Welcome to the world of JavaProgramming");
System.out.println(“Learning Java is fun");//End of line Comment
}
}

Correct Code:
/*This is my first multi-line comment gets printed at the output*/
System.out.println(“This is my first multi-line comment");
JAVA DOCUMENTATION COMMENT

Documentation comments are usually used to write large programs


for a project or software application as it helps to create
documentation API.
These APIs are needed for reference, i.e., which classes, methods,
arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool.
The documentation comments are placed between /** and */.
Syntax

/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/
ARE JAVA COMMENTS EXECUTABLE

As we know, Java comments are not executed by the compiler or


interpreter, however, before the lexical transformation of code in
compiler, contents of the code are encoded into ASCII in order to
make the processing easy.
Test.java

public class Test{


public static void main(String[] args) {
//the below comment will be executed
//
System.out.println("Java comment is executed!!");
}
}
Test.java
public class Test{
public static void main(String[] args) {
//the below comment will be executed
//
System.out.println("Java comment is executed!!");
}
}
Loop

When a set of statements is executed number of


times, then it is called as a loop statement.
THREE TYPES OF LOOPS:

While loop: Used for executing a set of statements repeatedly.


The condition is tested at the beginning before entering the loop.
For loop: It executes a set of statements number of times. Here ,
the variable initialisation , conditional statement and the variable
incrementation all takes place in a single line.
do...While loop: It executes like a while loop except that the
condition is tested at the end.
While loop
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Java do-while Loop:

public class DoWhileExample {


public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
TASK
Write a program to print the numbers from 60 to 53
using while loop.
Decision Making:

When a statement needs to be executed based on a


condition, then if statement is used and else block will
be executed when the condition is false.
There are four types of conditional statements:
if statement: First , as the program flows, the
condition will be tested and then a statement or
group of statements will be executed.
if-else statement: The program checks for the
condition.
Decision Making:

If the condition is true ,then the if block will be


executed otherwise the else block will be executed.
nested if statement: When a if statement is used
within another if or elseif statement, then it is
called as nested if statement.
Example:
EXERCISE:
Write a program using if else structure to find
whether the number is divisible by 5 or not.
SOLUTION:
public class Numdivby5{

public static void main(String[] args){


int num1 = 5;

if(num1 % 5 == 0)
{
System.out.println("Number is divisible by 5");
}
else
SOLUTION:
{
System.out.println("Number is not divisible by 5");
}
}}
Java if-else-if ladder Statement:

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
}
Java if-else-if ladder Statement:

//Java Program to demonstrate the use of If else-if


ladder.
//It is a program of grading system for fail, D grade, C
grade, B grade, A grade and A+.
Example:
//Java Program to demonstrate the use of If else-if
ladder.
//It is a program of grading system for fail, D grade, C
grade, B grade, A grade and A+.
Example:
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;

if(marks<50){
System.out.println("fail");
}
Example:
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
Example:
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
Program to check POSITIVE, NEGATIVE or
ZERO:
public class PositiveNegativeExample {
public static void main(String[] args) {
int number=-13;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
}
//Java Program to demonstrate the use of Nested If
Statement.

public class JavaNestedIfExample {


public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
} }}
// Break statement :

•As the name suggests, the break statement is used to break the
current flow of the program and transfer the control to the next
statement outside a loop or switch statement.
•However, it breaks only the inner loop in the case of the nested
loop.
•The break statement cannot be used independently in the Java
program, i.e., it can only be written inside the loop or switch
statement.
// Continue statement:

Unlike break statement, the continue statement doesn't


break the loop, whereas, it skips the specific part of the
loop and jumps to the next iteration of the loop
immediately.
// Ternary Operators:

Unlike break statement, the continue statement doesn't


break the loop, whereas, it skips the specific part of the
loop and jumps to the next iteration of the loop
immediately.
// Switch statement:

The condition will be checked and based on the condition,


any one of the cases will be executed.
A break statement is used at the end of each case to exit from
that block.
Default block is executed when the condition does not match
any of the cases.
Example Program:

public class Examplesw {

public static void main(String[] args) {


int choice = 1;

switch(choice) {

case 1:System.out.println("The number is one");


break;
Example Program:

case 2:System.out.println("The number is two");


break;

case 3:System.out.println("The number is three");


break;

case 4:System.out.println("The number is four");


break;

default:System.out.println("Choice does not match any of the


case statements");
}
Arrays:
ARRAY EXAMPLE:

public class Exarray {

public static void main(String[] args) {


int numArr[] = new int[5];
numArr[0] = 1;
numArr[1] = 2;
numArr[2] = 3;
numArr[3] = 4;
numArr[4] = 5;
for(int i=0;i<numArr.length;i++)
System.out.println(numArr[i]);
}

}
Output:

1
2
3
4
5
Multi-Dimensional Array:

class Multiarrex{
public static void main(String args[]){
//declaring and initializing 2D array
int numarr[][]={{1,2,3},{4,5,6},{7,8,9}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(numarr[i][j]+" ");
}
System.out.println();
}
}}
Output:

123
456
789
Exercise:
Find the error in the following code:
public class sampArr{
public static void main(String[] args){
int arr1[5] = new arr1[];
arr1[1] = 10;
arr1[2] = 11;
arr1[3] = 12;
arr1[4] = 13;
arr1[5] = 14;
for(int i=0;i<arr1;i++){
System.out.println(arr1[i]);
}}
Correct Code:
public class sampArr{
public static void main(String[] args){
int arr1[] = new int[5];
arr1[0] = 10;
arr1[1] = 11;
arr1[2] = 12;
arr1[3] = 13;
arr1[4] = 14;
for(int i=0;i<arr1.length;i++){
System.out.println(arr1[i]);
}}
Exercise:
Find the error in the following code:
public class sampArr{
public static void main(String[] args){
int arr1[5] = new arr1[];
arr1[1] = 10;
arr1[2] = 11;
arr1[3] = 12;
arr1[4] = 13;
arr1[5] = 14;
for(int i=0;i<arr1;i++){
System.out.println(arr1[i]);
}}
SOLUTION:
public class sampArr{
public static void main(String[] args){
int arr1[] = new arr1[5];
arr1[0] = 10;
arr1[1] = 11;
arr1[2] = 12;
arr1[3] = 13;
arr1[4] = 14;
for(int i=0;i<arr1.length;i++){
System.out.println(arr1[i]);
}}
Methods In Java:

A method in java is a group of statements which is used to per


form a specific task.
Example Program:

public class Predfn


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The squareroot is: " + Math.sqrt(9));
}
}
SOLUTION:
The squareroot is: 3.0
User-defined method:

Methods which are manually written by the user are called user-
defined methods.
Example Program:
public class Division
{
public static void main(String[] args)
{
int num1 = 20;
int num2 = 2;
Division d1 = new Division();
int num3 = d1.div(num1,num2);
System.out.println("The division of num1 and num2 is= " + num3);
}
Example Program:

public int div(int a, int b)


{
int c;
c=a/b;
return c;
}
}
Exercise:
Find the error in the following program:
public class Mxfn
{
public static void main(String[] args)
{
int num1 = 20;
int num2 = 2;
int num3 = mxf(num1,num2);
System.out.println("The maximum of num1 and num2 is= ", num3);
}
Exercise:

public int mxf ()


{
int c;
if(num1 > num2){
System.out.println("num1 is greater");
c=num1;
}
else{
System.out.println("num2 is greater");
c=num2;
}
return c;
}
}
Correct Code:

public class Mxfn


{
public static void main(String[] args)
{
int num1 = 20;
int num2 = 2;
Mxfn m = new Mxfn();
int num3 = m.mxf(num1,num2);
System.out.println("maximum of two numbers is:"+num3);
}
Correct Code:

public int mxf(int a,int b)


{
int c;
if(a > b){
c=a;
}
else{
c=b;
}
return c;
}
}
Correct Code:

public int mxf(int a,int b)


{
int c;
if(a > b){
c=a;
}
else{
c=b;
}
return c;
}
}
Java Package

A java package is a collection of classes, interfaces and sub-packages.


There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.

Example:
package mypack;
public class B{
public void msg(){System.out.println("Hello");
}
}
TASK:

Write a program to illustrate the use of packages.


ACCESS MODIFIERS:

Access Modifiers specifies the access level of the fields , methods, classes and constructors.
DEFAULT ACCESS MODIFIERS:

If we do not mention any access modifiers for classes, methods , variables etc , then by default
the default access modifiers are used.

package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
}
}
PRIVATE ACCESS MODIFIERS:

When the variables and methods are declared private , they cannot be accessed outside the
class.
PRIVATE ACCESS MODIFIERS:

class Data {
// private variable
private String name;
}

public class Main {


public static void main(String[] main){

// create an object of Data


Data d = new Data();

// access private variable and field from another class


d.name = “Java Program";
}
}
PROTECTED ACCESS MODIFIERS:
class Animal {
// protected method
protected void display() {
System.out.println("I am an animal");
}
}

class Dog extends Animal {


public static void main(String[] args) {

// create an object of Dog class


Dog dog = new Dog();
// access protected method
dog.display();
}
}
OUTPUT:

I am an animal.
Public access modifier:

When the methods , variables and classes are declared public , we can access them
from anywhere.
Public access modifier:
// Animal.java file
// public class
public class Animal {
// public variable
public int legCount;

// public method
public void display() {
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}
Public access modifier:
// Main.java
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();

// accessing the public variable


animal.legCount = 4;
// accessing the public method
animal.display();
}
}
Output:

I am an animal.
I have 4 legs.
TASK:
Write a program to illustrate the use of private access modifiers.
Java string:

A Java string is nothing but a sequence of character values.


Char[] ch={‘h’,’e’,’l’,’l’,’o’};
String s = new String(ch);
Is same as
String s = “hello”;
String methods:
Java String class contains a lot of methods to
Perform operations on strings such as
compare(),concat(),equals(),split(),length(),
Replace(),compareTo(),substring()etc.
The java.lang.String class implements
Serializable, comparable and char sequence
Interfaces.
Strings in JAVA

A string is an object that represents a sequence


of characters.
There are two ways to create string object.

1)By String Literal.


2)By new keyword.
STRING LITERAL
A java string literal is created by using double
quotes.
String st1 = “Hello”;
String st2 = “Hello”;
BY NEW KEYWORD
String sd = new String(“Harris”);
(Creates two objects and one reference variable)
JVM will create a string object in the heap memory
and the literal “welcome” will be placed in the string
constant pool.
Java STRING CLASS
METHODS
String sd = new String(“Harris”);
(Creates two objects and one reference variable)
JVM will create a string object in the heap memory
and the literal “welcome” will be placed in the string
constant pool.
Java STRING CLASS
METHODS
The java. lang.String class contains many
methods to do operations on sequence
of character values.
For Eg:,
int length() – returns string length
String toLowerCase() – Returns a string in
lowercase.
IMMUTABLE STRINGS IN
JAVA
String objects can’t be changed. It means that
they are immutable.
Once a string object is created, its state can’t be
changed but a new string object gets created.
Example:
class Testimmutablestring1{
public static void main(String[] args){
String s=“Beautiful";
s=s.concat(" Garden");
System.out.println(s);
}
}
String comparison
It is used to compare two strings in Java.
Java strings are compared on the basis of value and
reference variable.
There are three ways to compare strings in Java.
By equals() method
By = = operator
By compareTo() method
COMPARE TWO STRINGS BY EQUALS
METHOD:
The string equals method is used to compare the
values of two strings.
Syntax:
*********
Public boolean equals(Object s2)-Compares this
string to another object.
Public boolean equalsIgnoreCase(String another)-
Compares this string with another string ignoring
case.
EXAMPLE:
class Teststringcomparison1{  
 public static void main(String args[]){  
   String s1="Sachin";  
   String s2="Sachin";  
   String s3=new String("Sachin");  
   String s4="Saurav";  
   System.out.println(s1.equals(s2));//true  
   System.out.println(s1.equals(s3));//true  
   System.out.println(s1.equals(s4));//false  
 }  
}  
Example 2:
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";

System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
STRING COMPARE BY == OPERATOR

It is used to compare two strings based on references not by values.

class Teststringcomparison3{
public static void main(String args[]){
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)
}
}
FILL IN THE MISSING CODE:
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String ____="Sachin";
String s3=____ String("Sachin");
System.out.println(s1=______);
System.out.println(s1==s3);
}
}
CORRECT CODE:
class Teststringcomparison3{  
public static void main(String args[]){  
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 nonp
ool)  
 }  
}  
CORRECT CODE:
class Teststringcomparison3{  
public static void main(String args[]){  
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 nonp
ool)  
 }  
}  
STRING COMPAREBY COMPARETO
METHOD
The string compareto method compares two string values and returns an
integer value if string1 is greater than, less than or equal to the second
string.
STRING EXAMPLE
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
TASK:
Write a program to illustrate the use of compareTo operator
STRING CONCATENATION:
String concatenation is used to combine two strings.
There are two ways to concat strings in Java.
1)By string concatenation(+) operator.
2)By concat() method.
STRING CONCATENATION:
String Concatenation operator(+) is used to add two strings.
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
FIND THE ERROR IN THE FOLLOWING
CODE:
class TestStringConcatenation1{
public static void main(String args[]){
String s=“Big"" Circle";
Systemout.println(s);
}
Correct code:
class TestStringConcatenation1{
public static void main(String args[]){
String s=“Big"+" Circle";
System.out.println(s);
}
}
STRING CONCATENATION
String concatenation is achieved through stringbuilder or stringbuffer class
and its append method.

String s=(new StringBuilder()).append("Sachin").append("


Tendulkar”).toString();
STRING CONCATENATION
String concatenation can concat not only concat string but primitive values
too.
class TestStringConcatenation2{
public static void main(String args[]){
String s=80+20+“Flag"+10+10;
System.out.println(s);//100Flag1010
}
}
Find the error in the following code:
class TestStringConcatenation2{
public static void main(String args[]){
String s=10+11+“Simple+1+1
System.out.println(s
}
}
CORRECT CODE:

class TestStringConcatenation2{
public static void main(String args[]){
String s=10+11+“Simple”+1+1;
System.out.println(s);
}
}
Output:
Beautiful Flower
Task:
1)Write a program to illustrate the use of string concat operator.
Substring in java:
A part of string is called a substring.
Substring is a subset of another string.
Index starts from zero.
Start index is inclusive and end index is exclusive.
You can get the substring from the string object by one of the two methods.
Syntax:
*********
public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
public String substring(int startIndex, int endIndex): This method returns new
String object containing the substring of the given string from specified startIndex to
endIndex.
EXAMPLE:
String s="hello";
System.out.println(s.substring(0,2));//he
Example of java substring:
public class TestSubstring{
public static void main(String args[]){
String s="SachinTendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}
Java string class methods:
The java.lang.String class provides a lot of methods to work on
strings. With the help of these methods,we can perform lot of
operations on strings like concatenating, trimming and comparing
strings.
Everything we submit in a form is treated as a string and so Java
Strings is a powerful concept.
STRING touppercase and tolowercase
methods:
The toUpperCase() method converts the string into uppercase letter and
toLowerCase() method converts the string into lowercase letter.
Example:
String s="State";
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s);
Output:
STATE
state
State
INHERITANCE:
When a childclass inherits the properties of the parent class , then this
concept is called as inheritance.
INHERITANCE:
Example
class Employee3{
float salary=40000;
}
class Programmer extends Employee3{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Parrots are screeching
flying
MULTI-LEVEL INHERITANCE:
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance:

class Bird{
void fly(){System.out.println("Birds are flying");}
}
class Parrot extends Bird{
void screech(){System.out.println("Parrots are screeching");}
}

class Peacock extends Bird {


void scream(){System.out.println("Peacocks are screaming");}
}
public class ExInherit1{
public static void main(String args[]){
Peacock c = new Peacock();
c.scream();
c.fly();
}}
Output:

Peacocks are screaming


Birds are flying
METHOD OVERLOADING:
When two or more methods have the same name but different
number of parameters,then it is called as method overloading.
It can be achieved in two ways.
By changing the number of arguments.
By changing the datatype of the arguments.
METHOD OVERLOADING:
1)By changing the number of arguments:
class Multiplier{
static int multiply(int a,int b){return a*b;}
static int multiply (int a,int b,int c){return a*b*c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Multiplier.multiply (5,5));
System.out.println(Multiplier.multiply (3,3,3));
}}
Exercise:
Find the error in the following program.
class MulOverloading{
int multiply(int a, b){System.out.println(a*b);}
float multiply(int a,int b,int c){System.out.println(a*b*c)

public static void main(String args[]){


MulOverloading m1=new MulOverloading ();
m1.multiply(6,8);
m1.multiply(5,5,5);
}
}
Correct Program:
class MulOverloading{
void multiply(int a, int b){System.out.println(a*b);}
void multiply(int a,int b,int c){System.out.println(a*b*c); }

public static void main(String args[]){


MulOverloading m1=new MulOverloading ();
m1.multiply(6,8);
m1.multiply(5,5,5);
}
}
class Multiplier{
static int multiply(int a, int b){return a*b;}
static double multiply (double a, double b){return a*b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Multiplier. multiply(6,6));
System.out.println(Multiplier. multiply (5.3,5.6));
}}
OUTPUT:
36
29.679999999999996
Exercise:
Write a program to illustrate function overriding.
Solution:
class SweetStall{
String getSweetPrice(){return null;}
}
class A2B extends SweetStall{
String getSweetPrice(){return "1kg of sweets cost Rs.250";}
}

class SreeMithai extends SweetStall {


String getSweetPrice(){return "1kg of sweets cost Rs.200";}
}
class GrandSweets extends SweetStall {
String getSweetPrice(){return "1kg of sweets cost Rs.300";}
}
public class SampSweet {
public static void main(String args[]){
A2B a=new A2B();
SreeMithai s=new SreeMithai();
GrandSweets gs=new GrandSweets();
System.out.println("A2B SweetPrice: "+ a.getSweetPrice());
System.out.println("SreeMithai SweetPrice: "+s.getSweetPrice());
System.out.println("GrandSweets SweetPrice:"+gs.getSweetPrice());
}
}
Output:
A2B SweetPrice: 1kg of sweets cost Rs.250
SreeMithai SweetPrice: 1kg of sweets cost
Rs.200
GrandSweets SweetPrice:1kg of sweets cost
Rs.300
Method Overriding:

When the methods in the child class has the same name as the
methods in the parent class but different method implementations
,then it is called as method overriding..
class Aeroplane{

void fly(){System.out.println("Aeroplane is flying");}


}

class FighterJets extends Aeroplane{

void fly(){System.out.println("FighterJets are flying at high speed");}

public static void main(String args[]){


FighterJets flob = new FighterJets();
flob.fly();
}
OUTPUT:
FighterJets are flying at high speed.
EXERCISE:
class Strad{
static _______ strex(String a,String b){return a+b;}
static String strex (String a, String b, String c){________ a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(_____.strex(“hi”,”Jay”));
System.out.println(______.strex(“Welcome”,”to”,”India”));
}}
SOLUTION:
class Strad{
static String strex(String a,String b){return a+b;}
static String strex (String a, String b, String c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Strad.strex(“hi”,”Jay”));
System.out.println(Strad.strex(“Welcome”,”to”,”India”));
}}
Java Type Casting:
When the value of one primitive data type is assigned to another type,
then it is called as typecasting. There are two types of typecasting:
Widening Casting: process of converting smaller data type to larger
type.
byte -> short -> char -> int -> long -> float -> double.
Narrowing Casting: process of converting larger data type to smaller
type.
double -> float -> long -> int -> char -> short -> byte.
Example Program:

public class Sampcst {


public static void main(String[] args) {
int firstVal = 9;
double valDb = firstVal;
System.out.println(firstVal);
System.out.println(valDb);
double valDb1 = 9.78;
int firstVal1 = (int) valDb1 ;
System.out.println(valDb1);
System.out.println(firstVal1);
}}
Output:

9
9.0
9.78
9
Exercise:

Write a program to illustrate both the types of casting.


Solution:
public class Excst {
public static void main(String[] args) {
char firstCh = 'H';
int valNum = firstCh;
System.out.println(firstCh);
System.out.println(valNum);
float valFl = 9.7f;
int firstVal = (int) valFl ;
System.out.println(valFl);
System.out.println(firstVal);

}}
ABSTRACT CLASS:

An abstract class is declared with the abstract keyword.


An abstract method contains only the method declaration , it does
not contain the method body.
An abstract class can contain non-abstract methods as well.
EXAMPLE:
abstract class Fruit{
abstract void colour();
}
//In real scenario, implementation is provided by others i.e. unknown by end
user
class Apple extends Fruit{
void colour(){System.out.println("colour of apple is red");}
}
class Mango extends Fruit{
void colour(){System.out.println("colour of mango is yellow");}
}
class Banana extends Fruit{
void colour(){System.out.println("colour of banana is yellow");}
}
//In real scenario, method is called by programmer or user
class SampAbs1{
public static void main(String args[]){
Apple ap=new Apple();
Mango m=new Mango();
Banana b=new Banana();
ap.colour();
m.colour();
b.colour();
OUTPUT:
colour of apple is red
colour of mango is yellow
colour of papaya is orange
EXERCISE:
Find the error in the following code:
abstract class Fish{
abstract void swim
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class F1 extend Fish{
void swim(){System.out.println(“F1 is swimming in the sea");
}
class F2 extends Fish{
void swim(){System.out.println(“F2 isswimming in the pond");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Fish f=new ();
f. swim();
}
}
Solution:

abstract class Fish{


abstract void swim();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class F1 extends Fish{
void swim(){System.out.println(“F1 is swimming in the sea");}
}
class F2 extends Fish{
void swim(){System.out.println(“F2 isswimming in the pond");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Fish f=new F1();
f. swim();
}
}
Iterface:
An interface is declared by using the interface keyword.
It contains only abstract methods(i.e. methods without body).
Example:
interface drinking{
void drink();
}
class A1 implements drinking{
public void drink(){System.out.println("Drinking water");}

public static void main(String args[]){


A1 obj = new A1();
obj. drink();
}
}
OUTPUT:

Drinking water
Find the Error:
interface Walking{
void walk;
}
interface Slow{
void walk;
}
class TestInterfac1 implements Walking, Slow{
public void walk(){
System.out.println("Hello");
}
public static void main(String args[]){
TestInterfac1 obj = new TestInterfac1();
obj. walk();
}
}
Constructors:
Whenever an object is created , the constructor gets called.
Example Program:
public class Human {
int age;
String name;
Human(int a,String n){
age = a;
name = n;
}
void display(){System.out.println(age+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Human h1 = new Human(20,"Mala");
Human h2 = new Human(22,"Kala");
//calling method to display the values of object
h1.display();
h2.display();
}
}
Output:

20 Mala
22 Kala
Exercise:
Write a program to illustrate the use of constructors.
public class Car{
Car(){
System.out.println("New Car");
}
public static void main(String args[]){
Car c = new Car ();
}
}
Instance Variables:

Variables that are declared within the class but outside any method are called
instance variables.
For instance variables , the memory is allocated at runtime rather than at
compile time.
Example Program:
public class Bike {
String Colour;
String name;

public void drive() {


System.out.println("Driving Bike");
}

public static void main(String[] args) {


Bike b = new Bike();
b.Colour = "Red";
b.name = "Pulsar";
System.out.println(b.Colour+" "+b.name);
b.drive();

}
Output:

Red Pulsar
Driving Bike
ENCAPSULATION:

It is the process of grouping the code and data together as a single unit.
package mypack;
public class Person{
private int age;
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age ;
}
}

package mypack;
class Test{
public static void main(String[] args){
Person s=new Person();

s.setAge(30);

System.out.println(s.getAge());
Output:

30
Wrapper Classes in Java:
A wrapper class is used to convert the primitive datatypes into object type and
object type into primitive type.
Example:
public class WrapperExample1{
public static void main(String args[]){
int a=10;
Integer i=Integer.valueOf(a);
Integer j=a;

System.out.println(a+" "+i+" "+j);


}}
Output:
10 10 10
Regular Expression - Introduction:

•A regular expression is a sequence of characters which is used to


find other strings using a specialized syntax held in a pattern.
•They can be used to search ,edit or manipulate text and data.
•Java provides java.util.regex package for pattern matching with
regular expressions.
•The java.util.regex package contains the following three classes:
Regular Expression - Introduction:

Pattern Class: A pattern Object is a compiled representation of a regular


expression.
•To create a pattern , we must first invoke one of the public static compile()
methods , which will then return a pattern object.
•These methods accept the regular expression as the first argument.

Matcher Class:
•A Matcher object is an engine that interprets the pattern and performs match
operation against an input string.
Regular Expression - Introduction:

Matcher Class:
• A Matcher object is obtained by invoking a matcher() method on a
Pattern object.
Regular Expression - Introduction:

•Capturing Groups: They are a way to treat multiple characters as a single unit.
•They are created by placing the characters to be grouped inside a set of
parentheses.
•The regular expression (dog) creates a single group containing the letters “d”, “o”
and “g”.
•Consider the following example.
• There are four such groups:
((A)(B(C)))
(A)
(B(C))
(C)
Capturing Groups:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {

public static void main( String args[] ) {


// String to be scanned to find the pattern.
String line = "This order was placed for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";
Capturing Groups:
•// Create a Pattern object
• Pattern r = Pattern.compile(pattern);

•// Now create matcher object.
• Matcher m = r.matcher(line);
• if (m.find( )) {
• System.out.println("Found value: " + m.group(0) );
• System.out.println("Found value: " + m.group(1) );
• System.out.println("Found value: " + m.group(2) );
• }
Capturing Groups:
•else {
• System.out.println("NO MATCH");
• }
•}
•}
Output:
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0
Regular Expression Syntax:

^ Matches the beginning of the line.


$ Matches the end of the line.
\z End of the entire string.
re+ Matches 1 or more of the previous thing.
\w Matches the word characters.
\d Matches the digits . Equivalent to [0-9].
\A Matches the beginning of the string.
Methods Of Matcher Class:
Public int start():
Returns the start index of the previous match.

Public int start(int group):


Returns the start index of the subsequence captured by the given
group during the previous match operation.

Public int end():


Returns the offset after the last character matched.
The Start and End Methods:
•Following is an example that shows the number of times the word “cat”
appears in the input string-----.

•Example:

•import java.util.regex.Matcher;
•import java.util.regex.Pattern;

•public class RegexMatches {

•private static final String REGEX = "\\bcat\\b";
•private static final String INPUT = "cat cat cat cattie cat";
The Start and End Methods:

public static void main( String args[] ) {


Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
int count = 0;
The Start and End Methods:

while(m.find()) {
count++;
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());
}
}
}
Output:
Match number 1
start(): 0
end(): 3
Match number 2
start(): 4
end(): 7
The Start And End Methods:

The above example uses word boundaries to ensure that the letters “c”
“a” “t” are not merely a substring in a longer word.
It also gives some information about where in the input string the match
has occurred.

The start method returns the start index of the subsequence captured by
the given group during the previous match operation.

The end returns the index of the last character matched , plus one.
The Matches and lookingAt Methods:

•The matches and lookingAt methods attempt to match an input sequence


against a pattern.

•Matches requires the entire input sequence to be matched , while lookingAt
does not.

•Both methods always start at the beginning of the input string.
The Matches and lookingAt Methods:
Example:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {

private static final String REGEX = "foo";


private static final String INPUT = "fooooooooooooooooo";
private static Pattern pattern;
private static Matcher matcher;
The Matches and lookingAt Methods:
public static void main( String args[] ) {
pattern = Pattern.compile(REGEX);
matcher = pattern.matcher(INPUT);

System.out.println("Current REGEX is: "+REGEX);


System.out.println("Current INPUT is: "+INPUT);

System.out.println("lookingAt(): "+matcher.lookingAt());
System.out.println("matches(): "+matcher.matches());
}
}
Output:
Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
lookingAt(): true
matches(): false
The replaceFirst and replaceAll Methods:

The replaceFirst and replaceAll methods replace the text that matches a given regular
expression.
•As their names indicate , replaceFirst replaces the first occurrence and replaceAll
replaces all occurences.

•Example:

•import java.util.regex.Matcher;
•import java.util.regex.Pattern;

•public class RegexMatches {


The replaceFirst and replaceAll Methods:
•private static String REGEX = "dog";
•private static String INPUT = "The dog says meow. " + "All dogs say meow.";
•private static String REPLACE = "cat";
The replaceFirst and replaceAll Methods:

public static void main(String[] args) {


Pattern p = Pattern.compile(REGEX);

// get a matcher object


Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
Output:
The replaceFirst and replaceAll Methods.
EXCEPTION HANDLING:

An exception is nothing but something abnormal happens in a program while the


program is executed.
If the exceptions are not handled, then it disrupts the program execution and
program flow will not be maintained.
Suppose if there are ten lines in a program, if there is an exception at line5,then
program stops there and remaining part will not get executed if the exception is not
handled.
TYPES OF JAVA EXCEPTIONS:

There are three types of exceptions:


1)Checked Exceptions
2)Unchecked Exceptions
3)Errors
DIFFERENCE BETWEEN CHECKED AND UNCHECKED EXCEPTIONS:
1)Checked Exceptions:
The classes which directly inherit the Throwable class
are called as checked exceptions.e.g.,IO Exceptions,SQL Exceptions,etc. Checked Exceptions
are checked at compile-time.
2)UnChecked Exceptions:
The classes which inherit RuntimeExceptions are called as UnChecked Exceptions.Eg,
Arithmetic Exceptions,NullPointerException,ArrayIndexOutOfBounds Exception.UnChecked
Exceptions are checked at run-time and not at compile-time.
3)Errors:
Error is irrecoverable,i.eOutOfMemoryError,VirtualMachine Error and AssertionError.
Java Exception Keywords:
Five keywords are used for handling exceptions in Java.
Try:
1)The exception code should be placed inside the try block.
2)The try block should be followed by catch or finally.
3)Try block can’t be used alone.
Catch:
1)The catch block is used for handling the exception.
2)It can’t be used alone and it must be preceded by the try block.
3)It can be followed by finally block
Finally:
1)The prominent code is placed inside the finally block.
2)It will be executed if the exception is handled or not.
Java Exceptions:

Throw:
1)Throw keyword is used for throwing an exception.
Throws:
1)Used for declaring exceptions.
2)Doesn’t throw an exception.
3)Specifies that there may occur an exception in the method.
4)Always used with method signature.
Java Exception Handling Example:

public class ExcEx {


public static void main(String args[]){
try{
int data=10/0;
}catch(ArithmeticException e){System.out.println(e);}
//remaining program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Find the Error in the Following Code:
public class ExEx1 {
public static void main(String args[]){
int num1=10/0;
}
catch(ArithmeticException e){System.out.println(“e”);
//remaining program
System.out.println("rest of the code...");
}
}
Correct Program:
public class ExEx1 {
public static void main(String args[]){
Try{
int num1=10/0;
}
catch(ArithmeticException e){System.out.println(e); }
//remaining program
System.out.println("rest of the code...");
}
}
Fill in the Missing Code:
class ExcepEx{
public static void main(String args[]) {
try{
int a[]=new int[10];
____[11] = 10;
}
catch(____________ e){ System.out.println("ArrayIndexOutOfBounds");
}
}}
Correct Program:
class ExceptionDemo2 {
public static void main(String args[]) {
try{ int a[]=new int[10];
a[11] = 10; }
catch(ArrayIndexOutOfBoundsException e){ System.out.println
("ArrayIndexOutOfBounds"); }
}}
Situations Where Java Exceptions Occur:
1)A Situation Where Arithmetic Exception Occurs:
If the number is divided by zero, then it causes an arithmetic exception.
Example:
int a = 10/0;//This is an example of arithmetic exception.
2)A Situation Where Null Pointer Exception Occurs:
If the variable has a null value and if we perform any operation on the
variable , then it causes a null pointer exception.
Example:
String sg = null;
System.out.println(sg.length());//This is an example of NullPointerException.
Situations Where Java Exceptions Occur:
3)A Situation Where NumberFormat Exception Occurs:
Wrong Formatting of any value may cause
NumberFormatException.
For example , if we have a String variable and if we convert this to
number format , then it causes a NumberFormatException.
4)A Situation Where ArrayIndexOutOfBounds Exception Occurs:
If we try to insert any value in the wrong index, then it causes an
ArrayIndexOutOfBounds Exception.
Java try-catch block:
Java try block:
It contains the code that causes an exception. It must be used
within the method.
If an exception occurs at a particular statement of try block ,then
rest of the block will not be executed.
Java try block must be followed by either catch or finally block.
Syntax Of Java Try-Catch Block:
Try{
//code that may cause an exception
}
Syntax Of try-finally block:
Try{
//code that may cause an exception
}finally{}
Java Catch Block:
It is used to handle the exception by declaring the type of exception
within the parameter.
The declared exception must be of the parent class type or the
generated exception type.
The catch block must be used only after the try block.
Multiple catch blocks can be used within a single try block.
Example Without Exception Handling:
public class TryCatchExample1 {

public static void main(String[] args) {

int data=50/0; //may throw exception

System.out.println("rest of the code");

}
Output:
Exception in thread "main" java.lang.ArithmeticException:
/ by zero .
Example:
public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
Output:
java.lang.ArithmeticException: / by zero rest of the code
Example 2:
Here , the exception is handled by using the parent-class exception.
public class TryCatchExample4 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

}
INTERNAL WORKING OF TRY-CATCH BLOCK:

JVM checks if the exception is handled or not. If the exception is not handled, it provides
a default exception handler to perform the following tasks.
Prints the exception description.
Prints the stack trace(hierarchy of methods where the exception occurred).
Causes the program to terminate.
JAVA CAN CATCH MULTIPLE EXCEPTIONS:

A try block can contain multiple catch blocks. Each catch block must contain a different
exception handler.
To perform different tasks when different exception occurs , we have to go for multi-catch
blocks.
At a time , only one exception occurs and only one catch block will be executed.
Catch blocks must be ordered from most specific to most general.
Example 1:
public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:

Arithmetic Exception occurs


rest of the code
WHAT U WILL
LEARN FROM THIS
MASTERCLASS
REACT - JSX
Introduction To Java and OOPS
Concepts

HTML
Basic elements, Paragraphs,
REACT JS Colors, Forms, Input Types

LEARNING SERVLETS
Introduction, Exceptions,
PLAN Database Access

MYSQL JDBC
Mysql Introduction, JDBC
Components, Examples
Create A web app
REACT WEB APP
Project Building
OUR AGENDA
1.Core Java Concepts
2.Classes and Objects , Inheritance , Method Overloading , Method
Overriding
3.Abstract Class , Interface , Encapsulation , Wrapper Class
4.Javascript – Overview , Syntax, Placement, Variables
5.Javascript – Operators , If…Else, Switch Case , While Loop
6.JavaScript – For loop , For…in, Loop Control, Functions
7.Javascript - Events , Cookies , Page Redirect
8.Javascript - Dialog Boxes , Void Keyword , Page Printing
9.Javascript – Objects , Number , Boolean Strings
10.Javascript – Arrays , Date , Math , Regular Expressions , HTML DOM.
11.HTML Basic, Elements , Attributes , Headings
12.HTML Paragraphs , Styles , Formatting , Comments
13.HTML – Colors , CSS , links , images , tables
Day wise Learning 14.HTML – Forms , Form Attributes , Form Elements
Plan 1 -15 15.HTML – Input Types , Input Attributes , Input Form Attributes.
OUR AGENDA
16.VSCode Introduction , React Introduction, React Installation
17.Create React-App , React Features , Pros and Cons
18.ReactJS Vs AngularJS , ReactJS Vs ReactNative , React JSX
19.React Components , React State , React Props
20.React Props Validation , React State Vs Props , React Constructor
21.React Component API , Component Life Cycle , React Forms
22.Controlled Vs Uncontrolled , React Events , Conditional Rendering
23.React Lists , React Keys , React Refs
24.React Fragments , Router , CSS, React Table , Hooks
25.E Store Book Management System
26.Chat Application
27.Tour
28.Calculator App
Day wise Learning 29.Plant e Commerce
30.Quiz App
Plan 16 -30
TO LEARN
REACT JS
ALL PROJECTS IN NETBEANS
NEED SOME
BASICS OF JAVA
BEFORE THAT

ALL PROJECTS IN NETBEANS


LETS DISCUSS
INTERNSHIP
YOU HAVE THE OPTION
TO CHOOSE WITH A
WEBINAR CERTIFICATE
OR GET ANY
INTERNSHIP
CERTIFICATE…
ON DEMAND

You can get chance to apply 1

Month Internship on REACT JS

'https://imjo.in/BJGJ4g
WHAT IS INTERNSHIP ?
OBJECTIVE OF THIS 30 DAYS
MASTER CLASS

PANTECH WILL MAKE


YOU TO CREATE 6
PROJECTS IN REACT JS
IN 30 DAYS
1 MONTH INTERNSHIP IN REACT JS
INTERNSHIP E-Certificate (30Days Internship on REACT JS)
Highly organized Video content
Download Project Files
Download PPTs
Assignments
Weekly Hackathons
Flexible Time.
Access Period: 90 Days from the date of payment
Community or Forum Support
HOW TO ENROLL INTO
1 MONTH INTERNSHIP?

https://imjo.in/BJGJ4g

COUPON CODE : REACTJS1


REG FEE : RS.1999
DISCOUNTED FEE: RS.999

Internship Last Date - 14.04.2023


HOW TO ENROLL INTO 1 MONTH
INTERNSHIP?

DISCOUNTED FEE: RS.999

Internship Last Date - 14.04.2023

WE WILL PAY GST FOR YOU in Ist Week

Its RS.1179 ( Rs.999+ 18% GST from


15th April2023 )

COUPON CODE : REACTJS1


ALL PROJECTS IN NETBEANS
LETS C SOME
BASIC JAVA