[go: up one dir, main page]

0% found this document useful (0 votes)
249 views353 pages

Core Java: MODULE:-1

This document provides an introduction and overview of the Java programming language. It discusses: 1) The origins and history of Java, which was created by Sun Microsystems in the 1990s and is now maintained by Oracle. 2) Key features of Java like being platform independent, object oriented, portable, robust, and multi-threaded. 3) Common uses of Java including standalone applications, client-server applications, web applications, and mobile applications. 4) The basic structure of a Java program including package declaration, import statements, class declaration, the main method, and printing statements. 5) Other Java concepts like comments, variables, control flow statements, and looping statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
249 views353 pages

Core Java: MODULE:-1

This document provides an introduction and overview of the Java programming language. It discusses: 1) The origins and history of Java, which was created by Sun Microsystems in the 1990s and is now maintained by Oracle. 2) Key features of Java like being platform independent, object oriented, portable, robust, and multi-threaded. 3) Common uses of Java including standalone applications, client-server applications, web applications, and mobile applications. 4) The basic structure of a Java program including package declaration, import statements, class declaration, the main method, and printing statements. 5) Other Java concepts like comments, variables, control flow statements, and looping statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 353

CORE JAVA

MODULE:-1

INTRODUCTION TO JAVA
BASIC PROGRAM STURCTURE
COMMENTS
ARCHITECTURE OF JAVA
DATA TYPES
VARIABLES
OPERATORS AND TYPES
KEYWORDS & LIST OF KEYWORDS
IDENTIFIERS & RULES OF IDENTIFIERS
CONTROL FLOW STATEMEMTS
LOOPING STATEMENTS
PATTEN PROGRAMMING
MODLE-1 MOKE INTERVIEW

INTRODUCTION TO JAVA
Organization Started SUN MICRO SYSTEM

Started By JAMES GOSWLIN

Team GREEN TEAM

Project GREEN PROJECT

Started Year 1990

Reason to start A Project to Develop an Electronic S/W

Completed Early 1996

Current Vendor ORACLE (2010-11)

First Version JDK 1.0 (MARCH-1996)

Last Version JDK 18(MARCH-2022)

Initial Name OAK

Final Name JAVA

Software To Develop JDK (1.8 to 18v)


BASIS C++

PRINCPILE WRITE ONCE RUN ANY WHERE

OPERATING SYSETEM INDEPENDENT

JAVA is one of the most widely used programming language, due to its various
characteristics.

SOME OF FEATURES / CHARACTERISTICS OF JAVA:

Simple to learn
Platform independent:-- java program does not depend on any operating system. i.e
program written under one operating system can be run on any other operating system.
Object Oriented Programming Langauge:- It is one of the programming strategy which
is required to fulfill every project requirement.
It has 4 concept:-
 IN-HERITENCE
 ABSTRACTION
 ENCAPSULATION
 POLYMORPHISM
Portable:- Along with JAVA, we use any other programming language as a supporting
language
Multi-Threaded:- We can run 2 different part of our same program parallelly.
Robust:- Most of the important things will happen automatically (Robotic Nature).
Over –Loaded:- One thing doing multi task.

USES OF JAVA:

 JAVA is widely used in many applications.


1. Stand Alone Application:-
No dependency on Internet Server.

Ex: Calender, Calculator, Notepad.

2. Client – Server Application:-


Which requires server access.

Ex: Banking Application, Gmail, What’s up…..etc

3. Web Based Application:-


 without installing the app
 direct URL type and use

Ex: YouTube, Face book


4. Mobile Application:-
Ex: What’s up, Face book, Instagram…….etc.
5. SAP:- (SOFWARE APPLICATION PRODCUT)
GERMAN BASED APPLICATION

BASIC STURCTURE OF THE PROGRAM:

A set of instruction given to a machinery following Syntax of any programming language


is called as program.
A group of program will make one application.
An application is basically a communication b/w human & machine.
Software is a type of applications.
Every Java program consists of following 5 steps:-
1. PACKAGE DECLARATION
2. IMPORT STATEMENT
3. CLASS DECLARATION
4. MAIN METHOD
5. PRINTING DECLARATION

CLASS DECLARATION:- Class declaration is the starting point of a Java program.

Syntax:-
ACCESSMODIFIER CLASS CLASSNAME

Public, Private, Protected & Default Key Word (imp word of Java)

To start a program

Ex: Public class sample

Public class Demo


Access Modifier:- It provides accessing permission to different files in our program. We
4 access modifiers
1. PUBLIC
2. PRIVATE
3. PROTECTED
4. DEFAULT
Public:- Public is an access modifiers which indicate openly accessible.
Class:- Class is defined as key word (important words of Java) which used start
program.
ClassName:- Class Name is a an identifier, it can only be combination of (A-Z i.e a-z)
Ex: Public class sample
Public class Demo
 NOTE POINTS:-
{ Start of Logic
} End of Logic
; End of Line

Public Class Sample


{

Logic

}
In Java we will never write a logic directly inside a class in order develop any logic we
will use main method.

MAIN METHOD:

Syntax:

Public Static Void Main (String arngs [ ] )

Main method is defined as heart of the java program without that program will not be
executed.
Public: Public is access modifier which indicate main method is freely accessible.
Static: Static is key word which indicate no need of object creation.
Void: Void is the return type which indicate main is not returning any specific value.
Main: Main is a identifier (Method Name)
String argns[ ]: It is said as string arngs of arrays which is called command line
arguments.(This related to array programming)
Ex:
Public Class Sample
{
Public Static Void Main (String arngs [ ] )
{
System.Out.Println(“HELLO”);

PRINTING STATEMENT:

Syntax:

System.Out.println(“Hello world”)

If we want to print any message on the output screen then will use this statement.
System: System is a pre-define class.
Out: Out is a pre-define Object.
println: println is a pre-define Method.
Dot: DOT is an operator which is used for connecting multiple things at one place.
// Pre define class
Class System
{

Object. Out

println( )
}

NOTE:

Public Class Sample


{
Public Static Void Main (String arngs [ ] )
{
System.Out.Println(“Hello world”);

}
 In above program all the word starting with smaller case expect
String – S System – S

DIFFERENT SOFTWARE IN JAVA:-

JAVA Software is available in 3 different parts

1. JME Java Micro Edition Embedded S/W.


2. J2SE/JSE Java Standard Edition Core Java.
3. J2EE Java to Enterprise Edition Advance Java.

ARCHITECTURE OF JAVA:
 Every Java app should follow following 5 steps
1. Select an Editor:- A place to develop a program
Ex: Notepad, Notepad++, Edit plus (or) Eclipse.
2. Develop a code.
3. Save a code:- Always save program with classname. Java
Ex: Sample Java
4. Compilation:-
Why to complie?
To convert our program to system understandable format.
Who will complie?
Javac compliers will complie.
How to complie?
Go to command prompt and type command as javac classname.java
What happens during compilation?
Compiler will checks Syntax error if no Syntax errors are there program complies
successfully.
What happen after compilation?
A class file (or) byte code file will be created.

5. Execution:-
Why to executive?
For getting Output.
How to executive?
Go to command prompt and type command as java classname.
Who will executive?
JVM-java virtual machine.
What happen during execution?
JVM will identified any logical mistake is there (or) not.
What happen after execution?
Output will be displayed.
100100001
1. Select the editor 100100000 5 O
ut
Notepad 1000100001
pu
4 Compilation 1110000110
Public class Arch
Java Arch
{ 2 (Complier)
Arch.class Logical
Public Static Void Main error
(String arngs[ ] )

{ Command PMT

System.Out.println(“Arch of Java Arch.Java (),,;


Java) “”spelling, case sensitivity

Arch.Java

COMMENTS:
Comments are used for two different purposes

1.For excluding for any line or line from execution.

2. To Make a program more readable.

1. Single line
Syntax:
// statement
2. Multiple lines:
Syntax:
/*
statement1
statement2
statement3
statement4
statementN

*/

3. Documentation comment:-
We will discuss in eclipse.

VARATIONS IN PRINTING:

Print (“Message”): first print message then be in same line.


Print (“Message”): first print message then go to new line.
SOP (“\n”): ln indicate break the line immediately.

Ex:--1

public class Info

public static void main(String arngs[])

System.out.println(“Mr John is data Scientist”);

System.out.print(“in AT&T Labs”);

System.out.print(“Since 2010”);

System.out.println(“and he worked for research\n as well as development department”);

}
DATA TYPES:- Data is defined as same useful information

Ex: Name, Age, Email-id, Date of birth, Contact No, Aadhar no, Pan no…

 In above example data is off different types two represent different type of data in our
program we use data types.
 Every data type is pre-defined word which represents of particular thing in our program.
 Data types are divided into two categories
1. PREMETIVE DATA TYPE
2. NON- PREMETIVE DATA TYPE

PREMETIVE DATA TYPE:

o Also called as system define


o They are 8 in number
o All 8 of them have specific name, size and usage.

S.NO NAME MEMORY SIZE USAGE

NUMERIC

1 BYTE 1-BYTE -128 TO +127

2 SHORT 2-BYTE -32768 TO +32767

3 INT 4-BYTE -2147483648 TO +2147483647

4 LONG 8-BYTE >2147483647

FORMULA:

MIN:- -2^(NO::OF BITS-1) -2^(8-1) -128

MAX:- +(2^(NO::OF BITS-1)) +(2^(8-1))-1 +127

(DECIMALS)

5 FLOAT 4-BYTE If we want upto 6 digits after decimal.

6 DOUBLE 8-BYTE If we want more than 6 digits after decimal (15 dec)

(SINGLE-CHARACTER)

7 CHAR 2-BYTE a-z, A-Z, Single digits, Single Special Symbol.

(CONSTANTS)
8 BOOLEAN 1-BYTE TURE / FLASE.

NOTE:- If premetive data type does not satisfy our requirement then we will go for non-
premetive data type.

NON-PREMETIVE DATA TYPE:-

 When premetive does not fullfill our requirement then we have non premetive data type.
 These are also called as user define data type.
 They do not have specific memory size.

Ex:- String, Arrays, Classes, Collection etc.

String Group of characters, Alphanumeric, Decimals, Numeric etc…

VARIABLES:-

o Variables are used to store the data.


o Every Variable have 4 things.
Name, Size, Type and Value
o For using Variables, we should follow two steps
o Variable name can be a-z

1. VARIABLE DECLARATION:
o Declaration means reserving a memory block.

Syntax:-
DATA TYPE, VARIABLE NAME

Ex:- Byte a;
Short b;
2. VARIABLE DECLARATION-RULE WHEN WE INITIALISE:
o Initialization means storing value into memory block.

Syntax:-

VARIABLE NAME = VALUE;

Byte a; a = 120 No rule for byte.

Short b; b = 3000 No rule for short.

Int c; c = 5000 No rule for int.

Long d; d = 67890004589L Keep “L / l” after value.


Float e; e = 455.6789F Keep “F / f” after value.

Double f; f = 89898.67676767 No rule.

Char g; g = “@” Keep value in single quotes.

Boolean h; h = Ture No rule for Boolean.

String k; k = “JAVA” Keep value in double quotes.

3. VARIABLE UTILISATION:-
Syntax:-
SYSTEM.OUT.PRINTLN(VARIABLE NAME WITHOUT DOUBLE QUOTES)

Ex: int age VAR DECLARACTION

Age = 24 VAR INITILISATION

System.out.println(Age) VAR UTILISATION

/* WAP TO PRINT BOOK_INFO NAME,AUTHOR,PAGES,COLOR,PRICE*/

public class Bookinfo

public static void main(String arngs[])

//var dec-> datatype varname;

String bname;

String author;

short pages;

String color;

short price;

//var initi-> varname=value;

bname = "Java";

author="james goswlin";
pages = 5000;

color ="Black";

price = 5000;

//var utilisation

System.out.println(bname);

System.out.println(author);

System.out.println(color);

System.out.println(price);

/* WAP TO PRINT STUDENTINFO USING DATATPYES & VARIABLES */

public class Studentinfo

public static void main(String arngs[])

//var dec-> datatype varname;

String name;

int age;

int sscyop;

float sscper;

String sklname;
int interyop;

float interper;

String interclg;

int gradyop;

float gardper;

String gardclg;

//var initi-> varname=value;

name = "K.Sri Sai Vignesh";

age = 23;

sscyop = 2015;

sscper = 63.65f;

sklname = "Vigana High School";

interyop = 2017;

interper = 70;

interclg ="VJG";

gradyop =2022;

gardper =60;

gardclg ="VLITS";

//var utilisation

System.out.println("STUDENT DATA ACCORDING TO RECORDS : " );

System.out.println(name );

System.out.println(age);

System.out.println(sscyop);

System.out.println(sscper);

System.out.println(sklname);
System.out.println(interyop );

System.out.println(interper);

System.out.println(interclg);

System.out.println(gradyop);

System.out.println(gardper);

System.out.println(gardclg);

/* WAP TO PRINT PRODUCT DETAILS WHICH YOU PURCHASED RECENTLY */

public class Purchasedinfo

public static void main(String arngs[])

//var dec-> datatype varname;

String productname;

String productbrand;

String color;

int price;

float discount;
String modeofpurchase;

String dateofpurchase;

//var initi-> varname=value;

productname = "IPHONE";

productbrand = "APPLE";

color = "RED";

price = 50000;

discount = 50.0F;

modeofpurchase = "APPTONIX storenmae";

dateofpurchase = "06-NOV-2020";

//var utilisation

System.out.println(productname);

System.out.println(productbrand);

System.out.println(color);

System.out.println(price);

System.out.println(discount);

System.out.println(modeofpurchase);

System.out.println(dateofpurchase);

}
RENITSATION OF A VARIABLIE:-

 What ever value initialization we can change it this process re-initialization of variable.
 We reinitiase the old value will be replaced with new one.
public class Reinitiase
{
public static void main(String arngs[])
{
float per =76.56F;//var initialisation
System.out.println(per);//76.56

per =87.65F;//reinitialisation
System.out.println(per);//87.65

per =97.67F;//reinitialisation
System.out.println(per);//97.67
}
}

OPERATORS:-

 Operators are used performance some operations in our program.


 In java we have different types of operators

1. ASSIGNMENT OPERATOR:
 It is used assign (or) initialize the value into variable
 It is denoted as “=”

Ex:- a = 100;

Assignment operators works right side to left side. If always stores right side value in left
variable.

2. COMPARSION OPERATOR:
 It is used to compare two value & return result in Boolean format.
 If value matches if return true otherwise if return false.
 It is represented as = =

NOTE: Every character in java represented in UTF (UNICODE TRANSFER FORMAT)


where every character have some Unicode associated to it.
Ex: A-65,B-66,C-67 Z-90

a-97,b-98,c-99 z-122

public class Comp

public static void main(String arngs[])

int a = 100,b=100;

boolean c;

c = a==b;

System.out.println(c);

char ch = 'A',sh = 'a';

boolean d;

d = ch==sh;

System.out.println(d);

3. ARITHMETIC OPEATOR:
 Arithmetic it is used to perform some arithmetic operator.
 +,-,*,/,%.

10+2 12

10-2 8

10*2 20

10/2 5 (quotient)

10%2 0 (remainder)

4. CONCATENATION OPEATOR:

Among all arithmetic operator + operator is working as addition and concatenation.


CONCATENATION:

 Will works as concatenations if any of the one operand is of String type &
provide result also in String format.

Ex: a + b

String Int String


Int String String
String Decimal String
Decimal String String
String Any Data Type String
Any Data Type String String

Ex:

“JAVA” + 18 JAVA18

“JAVA” + C JAVAC

“JAVA”+500+300 “JAVA500”+300 JAVA500300

100 + 200 + “JAVA” 300JAVA

Ex:-

String Name = “Pooja”;

System.out.println(“Name :”+Name);

O/P : Name : Pooja

Ex:

String Name = “Pooja”;

Int age = 22;

System.out.println(“Name :”+Name+”\nage: “ +age);

O/P : Name : Pooja

Age : 22

Ex:-1

public class ProductDetails


{

public static void main(String arngs[])

String pname="Shoes",brand="Adidas",color="White",

mode="Adidas store",date="07-Sept-2022";

int price=5999,dis=499;

System.out.println("Product Details are : ");

System.out.println("Product Name : "+pname);

System.out.println("Product Brand : "+brand);

System.out.println("Product Color : "+color);

System.out.println("Purcase from : "+mode);

System.out.println("Purcase On : "+date);

System.out.println("Product Price : "+price+" rs/-");

System.out.println("Discount avail: "+dis+" rs/-");

Ex:-2

public class Student


{

public static void main(String arngs[])

String name = "Pooja",skl="St mary's high school",clg="Shantiniketan Jr Collge",

gradclg="CBIT Engg & Sciene";

int age=22,sscyop=2014,interyop=2016,gradyop=2020;

float sscper=98.78F,interper=96.78F,gradper=65.76F;

System.out.println("STUDENT DATA ACCORDING TO RECORDS : ");

System.out.println(name+"\n"+age+"\n"+skl+"\n"+sscyop+"\n"+sscper+"\n"+clg+"\n"+i
nteryop+"\n"+interper+"\n"+gradclg+"\n"+gradyop+"\n"+gradper);

5. RELATION OPERATOR:
It is defines relationship b/w two operators and return the result in Boolean format.

> Greater Than

< Lesser Than


>= Greater Than

<= Lesser Than

!= Not Equal

6. LOGICAL OPERATOR:-
 It is defines logical relationship b/w two inputs and return result in Boolean.
1. LOGICAL AND (&&):-
 And operator return true if and only if both the inputs are true otherwise it
return false.

IP-1 IP-2 IP-1 && IP-2


T T T
F F F
T F F
F T F

2. LOGICAL OR (||):-
 OR operator return true of any of the input is true if return false of both the
input are false.

IP-1 IP-2 IP-1 || IP-2


T T T
F T T
T F T
F F F

3. LOGICAL NOT(! ):-


 NOT operator make our result as opposite.

I/P O/P
TRUE FALSE
FALSE TRUE

EXAMPLE PROGRAME:-

public class Op

public static void main(String arngs[])


{

int a=10,b=20,c=10,d=10;

boolean e = a>b;

boolean f = a<b;

boolean h = a<b && c<d;

boolean i = a>b || c>d;

System.out.println(e+"\n"+f+"\n"+h+"\n"+i);

7. INCREMENT OPERATOR:
 It increases the value by 1
 It represented as ++
 It is divided into 2 types

1. PRE-INCREMENT:
Represented as ++ variable name;
Rule:
 Increment the Value.
 Assign the Value.
 Update the Value.

2. POST INCREMENT:
Represented as variable name ++;
Rule:
 Assign the Value.
 Increment the Value.
 Update the Incremented Value.

Ex Program Pre – Increment

Ex-1:

public class Opr

public static void main(String arngs[])

int a = 10,b;

b = ++a;

System.out.println(a+"\n"+b);

Output:

11

11

Ex-2:

public class Opr

public static void main(String arngs[])

int a = 50,b,c,d;

b = ++a;

c = ++b;

d = c;

System.out.println(a+"\n"+b+"\n"+c+"\n"+d);
}

Output:

51

52

52

52

Ex-3:

public class Opr

public static void main(String arngs[])

int a = 30,b,c;

b = ++a + ++a;

c = ++b;

boolean d = c>b;

System.out.println(a+"\n"+b+"\n"+c+"\n"+d);

Output:

32

64

64

False

Ex Program Post – Increment


Ex-1:

public class Opr

public static void main(String arngs[])

int a = 30,b;

b = a++;

System.out.println(a+"\n"+b);

Output:

31

30

Ex-2:

public class Opr

public static void main(String arngs[])

int a = 20,b,c,d;

b = a++;

c = b++;

d = c++;

System.out.println(a+"\n"+b+"\n"+c+"\n"+d);

}
Output:

21

21

21

20

Ex-3:

public class Opr

public static void main(String arngs[])

int a = 15,b,c;

b = a++;

c = b++;

System.out.println(a+"\n"+b+"\n"+c);

a++;

b++;

c++;

System.out.println(a+"\n"+b+"\n"+c);

Output:

16

16

15

17
17

16

8. DECREMENT OPERATOR:
 It increases the value by 1
 It represented as ++
 It is divided into 2 types
1. PRE-DECREMENT:
Rule:
 Decrement the Value.
 Assign the Value.
 Update Decremented the Value.

2. POST DECREMENT:

Rule:

 Assign the Value.


 Decrement the Value.
 Update the Decrement the Value.

Ex Program Pre – Decrement

Ex-1:

public class Opr

public static void main(String arngs[])

int a = 100;

int b = ++a + a++;

int c = --b + b--;

System.out.println(a+"\n"+b+"\n"+c);

Output
102

200

402

Ex-2:

public class Opr

public static void main(String arngs[])

int a = 50;

int b = --a + a--;

int c = ++b + b++;

System.out.println(a+"\n"+b+"\n"+c);

Output:

48

100

198

COMBINATIONAL OPERATOR:

It is a combination of arithmetic operator and assignment operator.

+= a=a+b a+=b

-= a=a–b a-=b

*= a=a*b a*=b

/= a=a/b a/=b

%= a=a%b a%=b
Examples:

Count = Count+1; Count + = 1

i = i +1; i+=1

a = b+c; NA Because operand is not common in left and right

Ex-1:

public class Opr

public static void main(String arngs[])

int a = 50;

int b = 100;

b+= ++a;

System.out.println(a+"\n"+b);

Output:

51

151

PRECEDENCE OF OPERATOR (Priority):

 If two operands share a common operator then execution will take place based on
priority.

LIST OF PRECEDENCE:

Post Increment and Post Decrement.


Pre-Increment and Pre-Decrement.
*,%,/
+,-
Relational
Logical
Comparison
Combinational
Assignment

Example-1:

public class Opr

public static void main(String arngs[])

int a = 10,b = 5,c = 7;

int d;

d = a-++b-++c*2;

System.out.println(d);

Output:

-12

Example-2:

public class Opr

public static void main(String arngs[])

int x = 5;

x = x++ * 2 + 3 * - x;

System.out.println(x);

}
}

Output

-8

KEYWORDS:

“Keyword are defined as pre-defined word or reserve word java”.


All the key all available in java library.
In java we have 58 keywords where very keyword will perform some take for a ‘Pr’.
So in simple keyword are given to make programmer task easier.
All the keyword in java must start with smaller case.

INDENTIFIERS:

Identifier are the name given by the programmer as per convention.

Example:

Class Name
Variable Name
Method Name
Package Name
Project Name
Interface Name

RULE FOR WRITING IDENTIFIER (COMPULSARY TO FOLLOW):

1. An identifier can only be a combination of A-Z,a-z,0-9,$.....


2. An identifier cannot start with a digit
3. An identifier cannot be a keyword
4. If an identifier has more than one word cannot use space between the

STANDARD FOR WIRTING IDENTIFIER (OPTIONAL):

1. An identifier length should not cross 15 characters.


2. A class name should start with capital.
3. A variable name should start with smaller.
4. If class name have more than one word for every word first letter keep capital.
5. If variable name have more than one word for starting word first letter keep small from
second word every word first letter capital.

RULE:

 A-Z,a-z,0-9,$,…
Class $ample Valid
Class S@mple Invalid
Class S#ample Valid
 Do not start with digit
Class 1sample Invalid
Class s1ample Valid
 Keyword
Class static Invalid
Int if; Invalid
Class String Valid
 Does not allows spaces
Class My Program Invalid
Class My_Program Valid

STANDARD:

 Class MyFirstProgramIsToDisplayDetails
Valid but not according to standard.
 Class Sample
Valid but not according to standard.
 Int Age;
Valid but not according to standard.

 Class MyDetails acc to standard


Class myDetails acc to standard
 Int myAgeIs; acc to standard
Int MyAgeis; acc to standard

TAKING THE I/P FROM THE USER WHILE EXECUTING THE PROGRAM:

 In java we can take an I/P from the USER while running the program by using
“SCANNER CLASS”
 Scanner is a per-defined class which is there java library using this we can take an
input from the “USER”
 For using scanner class we have to follow following rules (or) steps

STEP:1:- WRITE FIRST STATEMENT IN PROGRAM AS

import java.util.Scanner;

import java.util.*;

STEP:2:- CERATE AN OBJECT OF SCANNER CLASS

Scanner sc = new Scanner (System.in)

STEP:-3: USING SCANNER CLASS REFERENCE CALL SCANNER CLASS METHOD

Methods of Scanner Class are:

Byte Var = sc.nextByte() For Taking Byte Value as I/P

Boolean Var = sc.nextBoolean() For Taking Boolean Value as I/P

Short Var = sc.nextShort() For Taking Short Value as I/P


Int Var = sc.nextInt() For Taking Integer Value I/P

Float Var = sc.nextFloat For Taking Float Value I/P

Double Var = sc.nextDouble For Taking Double Value I/P

Long Var = sc.nextLong For Taking Long Value I/P

String Var = sc.next() For Taking String Value I/P

(without space)

String Var = sc.nextLine() For Taking String Value I/P

(with space)

Example:1:-

/* WAP TO ADD TWO NUMDERS */

import java.util.Scanner;

public class Added

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER TWO NUMBERS");

int a =sc.nextInt(),b =sc.nextInt(),c;

c = a+b;

System.out.println("Sum of two numbers : "+c);

}
Example:2:-

/* WAP TO CALCULATE AREA OF RECTANGLE BY TAKING INPUT FROM THE


USER */

import java.util.Scanner;

public class Added

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER LENGTH AND BREADTH ");

int a =sc.nextInt(),b =sc.nextInt(),c;

c = a*b;

System.out.println("Area of rectangle is : "+c);

Example:3:-

/* WAP TO CALCULATE SIMPLE INTEREST BY TAKING THE INPUT BY USER*/

FORMULA:- (P*R*T)/100
P Principle amt

R Rate of Interest

T Time in year

import java.util.Scanner;

public class SimpleInt

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter the amount ");

int p = sc.nextInt();

System.out.println("Enter time duration");

int t = sc.nextInt();

System.out.println("Enter rate of interest");

float r = sc.nextFloat(),si;

si = (p*r*t)/100;

System.out.println("Simple rate of Interest : "+si);

Example:4:-

/* WAP TO ADD TWO DECIMAL NUMBER BY TAKING INPUT FROM USER */


import java.util.Scanner;

public class Added

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER TWO DECIMAL VALUE");

Float a = sc.nextFloat(),b = sc.nextFloat(),c;

c = a+b;

System.out.println("SUM OF TWO DECIMAL NUMBER ARE: "+c);

Example:5:-

/ * WAP TO CALCLUATE AREA OF CIRCLE, CIRCUMFERENCE A CIRCLE, AREA


OF SQURE BY USING INPUTS FROM USER * /

import java.util.Scanner;

public class Areas

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter the radius"+"\n"+"Enter side of square");


float pie =3.14f,a,c;

int r=sc.nextInt(),s=sc.nextInt(),area;

a= pie*r*r;

c= 2*pie*r;

area=s*s;

System.out.println("area of circle is:"+a+ "\n"+"circumference of circles is:"+c+


"\n"+"area of square is:"+area);

CONTROL FLOW SYSTEM:-


These are system which controls the flow of execution.

It is classified into types:

CONDITIONAL STATEMENT
SWITCH CASE STATEMENT

CONDITIONAL STATEMENT:

 These are statements which check condition an execute accordingly.


 Whenever we want to check any condition, then will go conditional statement.
if (condition)

{
Syntax:
// body of if

Else

// body of else

}
WORKING:

 JVM WILL CHECK CONDITION GIVEN AT if & INCASE IF CONDITION if-body


WILL BE EXECUTED AND ELSE WILL BE SKIPPED
 INCASE IF CONDITION IS FALSE if-body WILL BE SKIPPED ELSE WILL BE
EXECUT.

/ * WAP TO CHECK WETHER A PERSON IS ELIGIBLE TO CAST THE VOTE OR NOT


TAKE THE AGE VALE THROUGH SCANNER CLASS */

import java.util.Scanner;

public class Voting

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter the age");

int age = sc.nextInt();

if(age>=18)

System.out.println(" person is eligible to vote");

}
else

System.out.println("person is not eligible to vote");

/ * WAP TO PRINT GREATEST OF TWO NUMBER */

import java.util.Scanner;

public class Greatest

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter Two Numbers");

int a = sc.nextInt(), b = sc.nextInt();

if (a>b)

System.out.println(a+" Is greatest");

else

{
System.out.println(b+" Is greatest");

/ * WAP TO CHECK WHETHER THE NUMBER IS EVEN OR ODD NUMBER */

import java.util.Scanner;

public class Even

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter the Numbers");

int a = sc.nextInt();

if (a%2 == 0)

System.out.println( a+" Is EVEN");

else

System.out.println(a+" Is ODD");
}

When we want check multiple conditions, then we will use.

Syntax:

If/else if/else statement

If (condition)

// body of if

Else if (condition)

// body of else if 1

Else if (condition)

// body of else if 2

Else

// body of else
}

/* WAP TO CHECK WHEATHER A POSITIVE NUMBER, NEGATIVE NUMBER OR


ZERO*/

import java.util.Scanner;

public class Positive

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter Numbers");

int a = sc.nextInt();

if(a>0)

System.out.println(a+" Is Postive");

else if(a<0)

System.out.println(a+" Is Negative");

else

System.out.println(a+" Is Zero");

}
ASSIGNMENT

/*WAP TO CHECK FOLLOWING CONDITIONS IN SIMPLE PROGRAM*/

Print Tom if number is even and in between 10 and 25.


Print Jerry if number is odd and in between 10 and 25.
Print Tom and Jerry if above two conditions are false

import java.util.Scanner;

public class TomJerry

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter a Number");

int a = sc.nextInt();

if (a%2==0 && a>10 && a<25)

System.out.println(" IS TOM ");

else if (a%2!=0 && a>10 && a<25)

System.out.println(" IS JERRY ");

else

System.out.println(" TOM AND JERRY ");


}

/*WAP TO CHECK WEATHER 23 IS DIVISIBLE IN 13 AND 17 (IF/ELSE) */

public class Div

public static void main(String args[])

int a = 23;

if (a%13==0 && a%17==0)

System.out.println(a+ " IS Div ");

else

System.out.println(a+ " IS NOT DIV");

/*WAP TO PRINT GREATEST OF 3 NUMBER 33,66,17 (IF/ELSE IF/ELSE) */

public class GR
{

public static void main(String args[])

int a = 33,b = 17,c = 66;

if (a>b && a>c)

System.out.println(a+" Is greatest");

else if(b>a && b>c)

System.out.println(b+" Is greatest");

else

System.out.println(c+" Is greatest");

/*WAP TO CHECK 25 IS DIVISIBLE IN 5 OR 3. (IF/ELSE)*/

public class Divisible

public static void main(String args[])

int a = 25;

if (a%5==0 || a%3==0)

System.out.println(a+ " IS DIVISIBLE ");


else

System.out.println(a+ " IS NOT DIVISIBLE ");

/*WAP TO CHECK WEATHER A PERSON IS ELIGIBLE FOR IAS OR NOT CRITERIA


IS AGE IS BETWEEN 22 TO 35. (IF/ELSE) */

public class IAS

public static void main(String args[])

int age = 25;

if (age>22 && age<35)

System.out.println("THE PERSON IS ELIGIBLE FOR IAS");

else

System.out.println("THE PERSON IS NOT ELIGIBLE FOR IAS");

}
If we have single statement in (if or else) body then we can skip flower braces. But if we have
more than one system it is compulsory flower braces.

SWITCH CASE STATEMENT: When we want to test multiple condition we will go for switch
case statement.

Switch (Variable whose value you want to check)

Syntax:

Case Value 1 : Statement

Break;

Case Value 2 : Statement

Break;

Case Value 3 : Statement

Break;

Case Value 4 : Statement

Break;

Default : Statement

Break;

BREAK:

It is a keyword which indicates us to stop the current operation and make JVM to come out of
currently executing body.

What if we skip break key word?

Situation – 1: If value matches and skip break keyword then JVM will execute all remaining
cases until it finds break keyword/statements.

Situation – 2 : If value does not matches and we skip break keyword it will not effect our output.

/*WAP TO PRINT DAYNAME USING DAYNUMBER*/


DAYNUM DAYNAME

1 MONDAY
2 TUESDAY
3 WEDNESDAY

7 SUNDAY

< 1 OR >7 INVALID DAY

import java.util.Scanner;

public class Dayn

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter a Number");

int dn = sc.nextInt();

switch(dn)

case 1 : System.out.println("MONDAY");

break;

case 2 : System.out.println("TUESDAY");

break;

case 3 : System.out.println("WEDNESDAY");

break;

case 4 : System.out.println("THURSDAY");

break;

case 5 : System.out.println("FRIDAY");

break;
case 6 : System.out.println("SATURDAY");

break;

case 7 : System.out.println("SUNDAY");

break;

default : System.out.println("INVALID DAY");

break;

/*WAP TO PRINT DAYTYPE USING DAYNUMBER*/

DAYNUM DAYTYPE

1,2,3,4,5 WEEKDAY

6 WEEKDAY-1

7 WEEKDAY-2

>7 OR <1 INVALID DAY

import java.util.Scanner;

public class Dayn

public static void main(String args[])

{
Scanner sc = new Scanner(System.in);

System.out.println("Enter a Number");

int dn = sc.nextInt();

switch(dn)

case 1,2,3,4,5 : System.out.println("WEEKDAY");

break;

case 6 : System.out.println("WEEKDAY-1");

break;

case 7 : System.out.println("WEEKDAY-2");

break;

default : System.out.println("INVALID DAY");

break;

/*WAP TO PRINT MONTHYPE USING DAYNUMBER*/


DAYNUM DAYTYPE

3,4,5,6 SUMMER

7,8,9,10 RAINY

11,12,1,2 WINTER

12>OR <1 INVALID DAY

import java.util.Scanner;

public class Monthtype

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter a Number");

int dn = sc.nextInt();

switch(dn)

case 3,4,5,6 : System.out.println("SUMMER");

break;

case 7,8,9,10 : System.out.println("RAINY");

break;

case 11,12,1,2 : System.out.println("WINTER");

break;

default : System.out.println("INVALID DAY");

break;

}
}

/*WAP TO PRINT WEATHER A CHARACTER IS VOWEL OR NOT*/

CHARACTER TYPE

A,E,I,O,U CAPTIAL VOWEL

a,e,i,o,u SMALLER VOWEL

Other CONSONANT

import java.util.Scanner;

public class Vowel

public static void main(String args[])

//char ch = 'e';

Scanner sc = new Scanner(System.in);

System.out.println("ENTER CHARACTER");

char ch = sc.next().charAt(0);

switch(ch)
{

case 'A','E','I','O','U' : System.out.println(" CAPITAL VOWEL ")

break;

case 'a','e','i','o','u' : System.out.println("SMALL VOWEL ");

break;

default : System.out.println("MAY BE CONSONANT OR SPECIAL SYMBOL");

break;

NOTE:

 In switch case statement case value can’t be Boolean, float, double & long.
 In switch case statement case value can’t be duplicate irrespective of its match (or) not
that is all the case value must be unique.

DIFFERENCE B/W SWITCH CASE AND CONDITIONAL STATEMENTS

CONDITIONAL SWITCH

1. Syntax: 1. Syntax:
If (condition) Switch(variable whose value you
{ want take)
// body of if {
} case value 1,2,3,4, : statement
Else break;
{ default : statement
// body of else break;
} }
2. In conditional statements 2. Switch case statement execution
execution will happen based will happen based on switch
on condition. expression.
3. If none of condition satisfies else 3. If none if the case value match
will be executed. default will be executed.
4. Conditional statement supports all 4. Switch case support only byte,
the data type. short,int,char & string data type.
5. Using conditional statement we can 5. Using switch case we can evaluate
check multiple condition at same only one expression at a time
time.

LOOPING STATEMENT:

If any part of a code is repeatedly executing than rather than developing it repeatedly
we can keep it once in a loop & make it to run multiple times.
Loop Repetition
We have 4 types of loop in JAVA, FOR WHILE AND FOR EACH LOOP.
/*WAP TO PRINT YOUR NAME 10 TIMES*/

public class Name

public static void main(String args[])

for(int i=1;i<=10;i++)

System.out.println("java");

/*CREATE A FOR LOOP TO PRINT THE NUMBERS FROM 1 TO 10 */

public class Sri

public static void main(String args[])

for(int i=1;i<=10;i++)

System.out.println(i);
}

/* CREATE A FOR LOOP TO PRINT THE NUMBER FROM 10 TO 1 */

public class Sri

public static void main(String args[])

for(int i=10;i>=1;i--)

System.out.println(i);

}
/* CREATE A FOR LOOP TO PRINT A TO Z CHARACTER */

public class Alphabet

public static void main(String args[])

for(char i='A';i<='Z';i++)

System.out.print(i+" ");

System.out.println();

for (char ch=97;ch<=122;ch++)

System.out.print(ch+" ");

/* WAP TO PRINT ALL THE EVEN NUMBER FROM 1 TO N TAKE THE N VALUE
FROM USER */

import java.util.Scanner;

public class EN

{
public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter N-Value");

int n = sc.nextInt();

for(int i=1;i<=n;i++)

if(i%2==0)

System.out.print(i+" ");

/* WAP TO COUNT ALL THE EVEN NUMBERS FROM 1 TO N TAKE N VALUE FROM
USER */

import java.util.Scanner;

public class ENs

public static void main(String args[])


{

Scanner sc = new Scanner(System.in);

System.out.println("Enter N-Value");

int n = sc.nextInt(),count=0;

for(int i=1;i<=n;i++)

if(i%2==0)

count++;

System.out.println("Final Count : "+count);

/* WAP TO PRINT SUM OF ALL THE EVEN NUMBERS FROM 1 TO N VALUE


FROM USER */

import java.util.Scanner;

public class Sum

public static void main(String args[])

{
Scanner sc = new Scanner(System.in);

System.out.println("ENTER NUMBER");

int n = sc.nextInt(),sum=0;

for(int i=1;i<=n;i++)

if(i%2==0)

sum=i+sum;

System.out.println("SUM OF EVEN IS : "+sum);

/* WAP TO PRINT PRODUCT OF EVEN NUMBERS FROM 1 TO N (N VALUE MUST


BE LESS THAN 15) */

import java.util.Scanner;

public class Sum

public static void main(String args[])

Scanner sc = new Scanner(System.in);


System.out.println("ENTER NUMBER");

int n = sc.nextInt(),p=1;

for(int i=1;i<=n;i++)

if(i%2==0)

p=p*i;

System.out.println("PRODUCT OF EVEN IS : "+p);

/* WAP TO PRINT SUM OF EVEN AND PRODUCT OF ODD FROM 1 TO N (N


VALUE MUST BE LESS THAN 15) */

import java.util.Scanner;

public class Sums

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter N-Value");
int n = sc.nextInt(),sum=0,p=1;

for(int i=1;i<=n;i++)

if(i%2==0)

sum=i+sum;

else

p=i*p;

System.out.println("sum of even numbers is:" +sum + "\n "+"product of odd numbers


is:" +p);

/* WAP TO PRINT COUNT OF EVEN AND COUNT OF ODD FROM 1 TO N */

import java.util.Scanner;

public class SumE

public static void main(String args[])


{

Scanner sc = new Scanner(System.in);

System.out.println("Enter Number");

int n = sc.nextInt(),count_e=0,count_o=0;

for(int i=1;i<=n;i++)

if(i%2==0)

count_e++;

else

count_o++;

System.out.println("COUNT OF EVEN = "+count_e);

System.out.println("COUNT OF ODD = "+count_o);

/* WAP PROGRAM TO PRINT MUITPLE TABLE FROM N NUMBER TAKE N


VALUE FROM USER */

import java.util.Scanner;

public class Table

public static void main(String args[])


{

Scanner sc = new Scanner(System.in);

System.out.println("Enter Number");

int n = sc.nextInt();

for(int i=1;i<=10;i++)

System.out.println(n+ "*" +i+" ="+(n*i));

/*WAP TO SWAP TWO NUMBERS*/


SWAP USING EXTRA VARIABLE
SWAP USING WITHOUT EXTRA VARIABLE
SWAP USING EXTRA VARIABLE

import java.util.Scanner;

public class Swap1

public static void main(String args[])

{
Scanner sc = new Scanner(System.in);

System.out.println("BEFORE SWAPPING");

System.out.println(" THE VALUE OF A: ");

System.out.println(" THE VALUE OF B: ");

int A = sc.nextInt();

int B = sc.nextInt();

int C ;

C = A;

A = B;

B = C;

System.out.println(" AFTER SWAPPING");

System.out.println(" NOW THE VALUE OF A IS: "+A+"\n NOW THE VALUE OF B


IS : "+B);

SWAP USING WITHOUT EXTRA VARIABLE

import java.util.Scanner;

public class Swap

public static void main(String args[])

{
Scanner sc = new Scanner(System.in);

System.out.println(" THE VALUE OF A: ");

System.out.println(" THE VALUE OF B: ");

int A = sc.nextInt();

int B = sc.nextInt();

A = A + B;

B = A - B;

A = A - B;

System.out.println(" NOW THE VALUE OF A IS: "+A+"\n NOW THE VALUE OF B


IS : "+B);

/* WAP TO PRINT FIBNOCCI SERIES */

FIBNOCCI SERIES: A series of number whose first two terms are 0 & 1, from third term is
every number sum of pervious two number.

import java.util.Scanner;

public class Swap2

public static void main(String args[])

{
Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

int A = 0,B = 1,C;

System.out.print(A+" ");

System.out.print(B+" ");

for(int i=1;i<=n;i++)

C = A + B;

System.out.print(C+" ");

A = B;

B = C;

/* WAP TO CHECK WEATHER A NUMBER IS PRIME OR NOT */

PRIME NUMBER: Prime number is a number which is divisible only in 1 & itself.

import java.util.Scanner;

public class Prime

public static void main(String args[])

{
Scanner sc = new Scanner(System.in);

System.out.println("ENTER NUMBER");

int n = sc.nextInt();

int count = 0;

for(int i=1;i<=n;i++)

if(n%i==0)

count++;

if(count==2)

System.out.println(n+" IS PRIME");

else

System.out.println(n+" IS NOT PRIME");

/* WAP TO PRINT ALL THE PRIME NUMBERS FROM N1 TO N2 TAKE N1 & N2


VALUE FROM USER */

import java.util.Scanner;
public class Prime1

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("Enter Number");

int n1 = sc.nextInt(),n2 = sc.nextInt();

for(int i=n1;i<=n2;i++)

int count=0;

for(int j=1;j<=i;j++)

if(i%j==0)

count++;

if(count==2)

System.out.println(i+" IS A PRIME NUMBER");

}
/* WAP SUM AND COUNT OF ALL THE PRIME NUMBERS FROM N1 TO N2 */

import java.util.Scanner;

public class Sum1

public static void main (String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER NUMBER");

int n1=sc.nextInt(),n2=sc.nextInt();

int countP=0,sum=0;

for (int i=n1;i<=n2;i++)

int count=0;

for(int j=1;j<=i;j++)

if(i%j==0)

count++;

if(count==2)

countP++;

sum=sum+i;

System.out.println("SUM OF PRIME : "+sum);


System.out.println("COUNT OF PRIME : "+countP);

WHILE LOOP:

Syntax:

WORKING OF WHILE LOOP:

STEP – 1 : INITIALISATION

STEP – 2 : CHECKING OF CONDITION

IF CONDITION TRUE GO TO STEP – 3

IF CONDITION FALSE, COME OUT OF THE LOOP

STEP – 3 : EXECUTE BODY OF THE LOOP


STEP – 4 : PERFORM UPDATION, GO TO STEP – 2

/* CREATE A WHILE TO PRINT THE NUMBER FROM 1 TO 10 */

public class Loop2

public static void main(String args[])

int i = 1;

while(i<=10)

System.out.println(i);

i++;

/* CREATE A WHILE TO PRINT THE NUMBER FROM 10 TO 1 */

public class Loop3

public static void main(String args[])


{

int i = 10;

while(i<=1)

System.out.println(i);

i--;

/* CREATE A WHILE LOOP TO PRINT -11 TO +11 */

public class Loop4

public static void main(String args[])

int i = -11;

while(i<=11)

System.out.print(i+“ “);
i++;

/* WAP TO PRINT A TO Z USING WHILE LOOP */

public class Loop5

public static void main(String args[])

char ch = 'A';

while(ch<='Z')

System.out.print(ch+" ");

ch++;

/* WAP TO PRINT REVERSE OR NUMBER*/

import java.util.Scanner;

public class Reverse


{

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER A NUMBER");

int num = sc.nextInt(),rem,rev=0;

while(num>0)

rem = num%10;

num = num/10;

rev = rev*10+rem;

System.out.println("REVERSE OF NUMBER IS : "+rev);

NOTE:-

If we divided an ‘n’ digit number with 10 will we will remainder as last digit & remaining
digits as Quotient.

PALINDROME NUMBER:- If original number & reverse of an number is same such


number is called as palindrome number.
Ex 121,111,323,1221 …………etc.

/* WAP TO CHECK WEATHER A NUMBER PALINDROME OR NOT */

import java.util.Scanner;

public class Palindrome

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER A NUMBER");

int num = sc.nextInt(),rem,rev=0,temp=num;

while(num>0)

rem = num%10;

num = num/10;

rev = rev*10+rem;

System.out.println("ACTUAL NUMBER IS : "+temp);

System.out.println("REVERSE OF A NUMBER IS : "+rev);

if(rev==temp)

System.out.println(temp+" IS PALINDROME NUMBER ");

else

System.out.println(temp+" IS NON PALINDROME NUMBER");

}
/* WAP TO CHECK WEATHER A NUMBER IS ARMSTRONG */

ARMSTRONG:- A number is armstrong number if we individually cube evey digits of a


number & add them in case if we get a sum number such is called armstrong number.

Ex 153 = 𝟏𝟑 + 𝟑𝟑 + 𝟓𝟑 .

import java.util.Scanner;

public class Armstrong

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER A NUMBER");

int num = sc.nextInt();

int rem,arm=0,temp=num;

while(num>0)

rem = num%10;

num = num/10;

arm = arm+rem*rem*rem;

if(arm == temp)

System.out.println(temp+" IS AN ARMSTRONG NUMBER ");

else
System.out.println(temp+" IS NOT AN ARMSTRONG NUMBER");

/* WAP TO ALL THE ARMSTONG NUMBER FROM 1 TO 1000 */

import java.util.Scanner;

public class Armstrong1

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER FROM NUMBER AND TO NUMBER");

int n1=sc.nextInt(),n2=sc.nextInt();

for(int i=n1;i<=n2;i++)

int arm=0,temp=i,rem;

while(temp>0)

rem = temp%10;
temp = temp/10;

arm = arm+rem*rem*rem;

if(arm==i)

System.out.println(i+" IS AN ARMSTRONG NUMBER ");

/* WAP TO ALL THE PALINDROME NUMBER FROM 1 TO 1000 */

import java.util.Scanner;

public class Palindrome1

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER A NUMBER");

int n1=sc.nextInt(),n2=sc.nextInt();

for(int i=n1;i<=n2;i++)

{
int rev=0,rem,temp=i;

while(temp>0)

rem = temp%10;

temp = temp/10;

rev = rev*10+rem;

if(rev==i)

System.out.println(i+" IS PALINDORME NUMBER");

/* WAP TO SUM OF THE AMSTRONG NUMBER FROM 1 TO 1000 */

import java.util.Scanner;

public class Armstrong

public static void main(String args[])

{
Scanner sc = new Scanner(System.in);

System.out.println("ENTER FROM NUMBER AND TO NUMBER");

int n1=sc.nextInt(),n2=sc.nextInt(),sum=0;

for(int i=n1;i<=n2;i++)

int arm=0,temp=i,rem;

while(temp>0)

rem = temp%10;

temp = temp/10;

arm = arm+rem*rem*rem;

if(arm==i)

sum = sum +i;

System.out.println(" sum of armstromg numbers:"+sum);

/* WAP TO SUM OF THE PALINDROME NUMBER FROM 1 TO 1000 */

import java.util.Scanner;

public class Palindrome


{

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER A NUMBER");

int n1=sc.nextInt(),n2=sc.nextInt(),sum=0;

for(int i=n1;i<=n2;i++)

int rev=0,rem,temp=i;

while(temp>0)

rem = temp%10;

temp = temp/10;

rev = rev*10+rem;

if(rev==i)

sum=sum+i;

System.out.println("SUM OF PALINDORME NUMBERS :"+sum)

}
/* WAP TO PRINT SUM OF EVEN DIGITS FROM THE GIVEN NUMBER */

Ex:- IF THE INPUT IS ‘54321’ OUTPUT SHOULD BE ‘6’ LOGIC SHOULD BE ‘4+2’

import java.util.Scanner;

public class Digits

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER A NUMBER");

int n=sc.nextInt(),rem,sum=0;

while(n>0)

rem = n%10;

n = n/10;

if(rem%2==0)

sum=sum+rem;

System.out.println("SUM OF EVEN DIGITS IS :"+sum);

}
/* WAP TO PRINT SUM OF ODD DIGITS FROM THE GIVEN NUMBER */

import java.util.Scanner;

public class Digits1

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER A NUMBER");

int n=sc.nextInt(),rem,sum=0;

while(n>0)

rem = n%10;

n = n/10;

if(rem%2!=0)

sum=sum+rem;

System.out.println("SUM OF ODD DIGITS IS :"+sum);

}
/* WAP BY TAKING INPUT FROM USER AND CHECK WHETHER THAT NUMBER
IS PALINDROME OR NOT */

a) IF IT IS PALINDROME , FIND SUM OF EVEN DIGITS.


b) IF IT IS NON-PALINDROME , FIND SUM OF ODD DIGIT.

import java.util.Scanner;

public class PEO

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER A NUMBER");

int n=sc.nextInt(),rem,rev=0,temp=n,evensum=0,oddsum=0;

while(temp>0)

rem = temp%10;

temp = temp/10;

rev = rev*10+rem;

if(rem%2==0)

evensum = evensum+rem;

else

oddsum = oddsum+rem;

if(rev==n)

System.out.println(n+" IS A PALINDROME NUMBER");

System.out.println("SUM OF EVEN :"+evensum);


}

else

System.out.println(n+" IS NON PALINDROME NUMBER");

System.out.println("SUM OF ODD :"+oddsum);

/* WAP TO CHECK COUNT OF PRIME DIGITS FROM GIVEN NUMBER */

For Example: Input is 12345678

Output Cout is 4

import java.util.Scanner;

public class PD

public static void main(String args[])

Scanner sc = new Scanner(System.in);

System.out.println("ENTER A NUMBER");
int num=sc.nextInt(),rem,countp=0;

while(num>0)

rem = num%10;

num = num/10;

int count=0;

for(int i=1;i<=rem;i++)

if(rem%i==0)

count++;

if(count==2)

countp++;

System.out.println(" THE COUNT OF PD IS : "+countp);

}
DIFFERENCE B/W FOR LOOP & WHILE LOOP

FOR LOOP WHILE LOOP

1. Syntax: 1. Syntax:
For(initialization;condition;updation) initialization
{ While(condition)
// body of the loop {
// statement to be executed //body of whlie loop
} updation
//statement outside the loop. }

2. We will go for ‘for loop’ when we 2.We will go for ‘while loop’ when we
Knows exact number of iteration. don’t know exact number of iteration.
iteration

3. In‘forloop’ initializtion,condition & 3.In while loop,Initialization is not a


updation is not mandatory. compulsory,Condition is compulsory,
Updation is not compulsory.

4. If we didn’t give the condition,compiler 4.If we didn’t give the condition,we


will by default condition if as true. will get compile time error.

Ex: for(; ;) Ex: int i = 1;


{ while()
System.out.println(“JAVA”); {
} System.out.println(“JAVA”);
Output: }

JAVA Output:

JAVA JAVA

Compile Time Error

Infinite Times
DO WHILE LOOP:

NOTE:- We will go for do while loop when we want our loop body to be executed at least
onces.

/* WAP TO PRINT 1 TO 10 USING DO WHILE LOOP */

public class Do

public static void main(String args[])

int i=1;

do

System.out.println(i);

i++;

while(i<=10);
}

COMPEMENTS OF JDK:-

JDK STANDS FOR (JAVA DEVELOPMENT KIT)

 It is a software which is responsible to develop and execute every java application.

JDK = JRE + DEV TOOLS

JRE (JAVA RUN TIME ENVIRONMENT)

 It is a part of JDK which provide all the facilities to exectue every java application.

JRE = JVM + PREDEFINE CLASSES / LIBRARY CLASSES

JVM (JAVA VIRTUAL MACHINE)

 It is a part of JRE, which is responsible to run every java application.


 Jvm having one inner thing – JIT.

JIT (JAVA IN TIME)

It is used to read one-one line of code and give it to operating system for execution
1.IS JAVA AN PLATFORM INDEPENDENT LANGUAGE?

Yes ! Java is platform independent language i.e. program written under one operation system,
can be run on any other operating system but to run them.

We need JVM of that paticular operating system. Therefore, java language is


platform independent but jvm is platform dependent.
// BYTE LINUX
//SOURE
(J( CODE
CODE COMPILER UBNTD

MAC

WINDOWS CLASS FILE

Ex:-1 - FIRST 50 PRIME NUMBERS

public class Prim3s

public static void main(String args[])

int countp=0;

for(int i=1;countp<50;i++)

int count=0;

for(int j=1;j<=i;j++)

if(i%j==0)

count++;
}

if(count==2)

countp++;

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

Ex:-2

public class Prim2s

public static void main(String args[])

int rem,count=0;

for(int i=1;i<=100;i++)
{

int temp=i;

while(temp>0)

rem=temp%10;

temp=temp/10;

if(rem==2)

count++;

System.out.println("COUNT OF 2'S : "+count);

Ex:-3 /* WAP TO PRINT FIRST 50 PALINDROME NUMBER */

public class Palindrome


{
public static void main(String[] args)
{
int count=0;
for (int i=1;count<50;i++)
{
int rev=0,rem,temp=i;
while(temp>0)
{
rem = temp%10;
temp = temp/10;
rev = rev*10+rem;
}
if (rev==i)
{
count++;
System.out.println(i+" IS A PALINDROME NUMBER ");
}
}
}
}
Differences between C and JAVA :
C JAVA

C is a Procedural Programming Language. Java is an Object-Oriented Language.

C was developed by Dennis M.Ritchie in 1972. Java language was developed by James Gosling
in 1995.

In the C declaration variable are declared at In Java, you can declare a variable anywhere.

the beginning of the block.

C does not support multithreading. Java has a feature of threading.

C support pointers. Java does not support pointers.

Memory allocation can be done by malloc. Memory allocation can be done by new

keyword.

Garbage collector needs to manage manually. Garbage collector is managed automatically.

C does not have a feature of overloading Java supports method overloading.

functionality.

C is platform dependent language. Java is platform independent language.

C is library Oriented language. Java is package and class based language.


#include<Stdio.h> package java.util;

Operating system is responsible to call JVM is responsible to call main( ).

main( ).
MODULE-2

USER DEFINE METHODS


METHOD OVER LOADING
TYPES OF VARAIABLES
-Local, Static, Non-Static
EXECUTION PROCESS
-Multiple ways to access static
-Accessing members of one class info another class
CONSTRUCIONS
-Types of constructions, This keyword, constructor overloading, constructor
chaining.
UML

USER DEFINE METHODS:-

In java, we will never write a logic directly inside the class. In order to develop any
logic, we will define main method then we will start developing the logic.
In case, if the code is lengthly, it is recommended to create separate user define method
and split the logic, which makes our program clear & more understandable.

METHOD:-

A method is define as a set of statement which is kept inside flower braces { }, which is
having header, signature & body & which gets executed whenever we make a call to it.

USER DEFINE METHODS HAS 3 JOB

To break logic
To make logic more clear
Easy to understand

SYNTAX OF CREATING USER DEFINE METHOD


ACCESSMODIFIER STATIC/NON-STATIC RETURN TYPE METHOD NAME (WITH ARGS /
WITHOUT ARGS)

METHOD HEADER METHOD SIGNATURE


// METHOD BODY

METHOD IMPLEMENTATION / BODY

It is compulsory to call every user define method.


For calling purpose we use “Method Signature”.
In our program, we can create as many number method as we want.
We can not create me method inside another method.
A method can be develop once, and calls multiple times.

CREATING A USER-DEFINE METHOD WITHOUT ARGUMENTS:-

public class Areas

//user define method without args

public static void areaCircle()

int r = 6;

float areac = 3.14F*r*r;

System.out.println("AREA OF CIRCLE IS : "+areac);

public static void areaRectangle()

int l=12,b=25,arear;

arear = l*b;

System.out.println("AREA OF RECTANGLE IS : "+arear);

public static void main(String args[])


{

areaCircle();

areaRectangle();

NOTE:- Using method without arguments we can write a method onece & call it multiple
times but the disadvantage is every time we call execution will happen in same values to over
this we can, use method with argument.

We can call user define method in another


User define method, like

public class Areas2

public static void areaCircle()

areaRectangle();

int r = 6;

float areac = 3.14F*r*r;

System.out.println("AREA OF CIRCLE IS : "+areac);

public static void areaRectangle()

int l=12,b=25,arear;

arear = l*b;
System.out.println("AREA OF RECTANGLE IS : "+arear);

public static void main(String args[])

areaCircle();

METHOD WITH SOME ARGUMENTS:-

Arguments are define as input given to any method.

Syntax:

METHODHEADER METHODNAME(DATATYPE VAR, DATATYPE VAR……………………………DATATYPE


VAR)

Ex:- public static void add(int i, char c, String d)

A method can have any number of inputs in the form of arguments.


When we call any method with argument we have to pass that paticular type of value.
While passing arguments we have to make sure it will be as per sequence define in
method declaration.

public class Areas1

public static void main(String args[])

areaCircle (7); areaCircle(24); areaCircle(67);

areaRectangle(10,20); areaRectangle(12,24); areaRectangle(20,60);


}

public static void areaCircle(int r)

float areac = 3.14F*r*r;

System.out.println("AREA OF CIRCLE IS : "+areac);

public static void areaRectangle(int l,int b)

int arear;

arear = l*b;

System.out.println("AREA OF RECTANGLE IS : "+arear);

/* WAP TO SWAP TWO NUMBERS USING USER DEFINE METHOD WITH


ARGUMENTS */

public class Swap

public static void main(String args[])

swap(10,20);swap(35,67);

}
public static void swap(int a,int b)

int c;

c = a;

a = b;

b = c;

System.out.println("AFTER SWAPPED VALUES ARE : "+a+" "+b);

/* WAP TO CALCUATE FACTORIAL OF A NUMBER USING METHOD WITH


ARGUMENT */

public class Factorial

public static void main(String args[])

factorial(2);

factorial(8);

factorial(9);

// user define method without args

public static void factorial(int num)

{
int fact = 1;

for(int i=num;i>=1;i--)

fact = fact*i;

System.out.println("FACTORIAL OF A NUMBER IS : "+fact);

METHOD OVER LOADING:-

The process of developing multiple methods with same name but different arguments
list is called as method over loading.

RULES FOR DEFINING ARGUMENT LIST:

NO :: OF ARGUMENT MUST BE DIFFERENT


Ex:- Swiggy()
Swiggy(String Name)
Swiggy(String Name, Int order id)
TYPES (DATA TYPE) OF ARGUMENT MUST BE DIFFERENT
Ex:- Add(int i, int j)
Add(Double d, Double D1)
Add(String S1, String S2)
SEQUENCE (OR) POSITION OF ARGUMENT MUST BE DIFFERENT
Ex:- log in (String url, int id)
log in (int id, String pwd)
WE GO FOR METHOD OVER LOADING WHEN WE WANT TO PERFORM ONE
TASK IN MULTIPLE WAYS:

EXAMPLES:

NON-TECHNICAL

Travelling ------- Hyd --- Bang

Bus

Train

Aeroplane

Bike

Car

KEEPING PHONE PASSWORD

Number Lock

Dawing Pattern

Finger Print

Face Sensor

TECHNICAL EXAMPLE:

-Payment in any Ecommerce

Credit

Debit

Wallets ( G-pay, P-pay, Amazon pay, Paytm)

Cash on Delivery

EXAMPLE –2

-Banking
Online Banking
Physical Banking
ATM Banking
App Baking
1.CREATE A CLASS AS PAYMENT APP

2.CREATE AN OVER LOADED METHOD AS PAYMENT

Payment(String wallettype, String uid)

Print walltype, uid

Payment(String cardtype, Long cardno, String expdate, int cvv)

Print cardtype, cardno, expdate, cvv

Payment(Long accno, String uname, String pwd)

Payment accno, uname, pwd (related online baking)

3.CREATE MAIN ( ) & MAKE A CALL TO ALL 3 PAYMENT METHOD’S

public class PaymentApp

public static void main(String args[])

payment("GOOGLE PAY","vignesh@sbi");

payment("CREDIT",62341205678L,"JAN-98",333);

payment(38908235692L,"vignesh chowadary","VIGNE1234");

public static void payment(String wallettype,String uid)

System.out.println("WALLET TYPE:"+wallettype+"\nuid: "+uid);

public static void payment(String cardtype,long cardno,String expdate,int cvv)

{
System.out.println("CARD TPYE : " +cardtype +"\ ncard no: "+cardno+ "\nexpdate:
"+expdate+"\ncvv:"+cvv);

public static void payment(long accno,String uname,String pwd)

System.out.println("ACC NO:"+accno+"\nuname:"+uname+"\npwd:"+pwd);

1.CREATE A CLASS AS TRAVELLING APP

2.CREATE AN OVER LOADED METHOD AS

Travel (String Bustype, String Source, String Destination)

Print Values

Travel (String Flighttype, int Price, Sting Source, String Dest)

Print Values

Travel (String Traintype, int Price, int Platform, String Source, String Dest)

Print Values

3.CREATE MAIN ( ) & MAKE CALL TO ALL 3 TRAVEL’S.

public class TravelApp

{
public static void main(String args[])

travel("AMARAVATHI A/C","VIJ","HYD");

travel("OMANAIR",50000,"HYD-AIRPORT","MCT-AIRPORT");

travel("DURONTO SPL",2000,1," MAS ","VIJ");

public static void travel(String bustype,String source, String destination)

System.out.println("BUS TYPE:"+bustype+"\nsource: "+source+"\ndestination:


"+destination);

public static void travel(String flighttype,int price,String source,String dest)

System.out.println("FLIGHT TPYE : "+flighttype+ "\nprice:"+price+"\nsource:


"+source+"\ndet:"+dest);

public static void travel(String traintype,int price,int platform,String source,String dest)

System.out.println("TRAIN TYPE:"+traintype+" \nprice:"+price+" \nplatform:


"+platform+"\nsource:"+source+"\ndest:"+dest);

}
TYPES OF VARAIABLES:

Based on the place of decleration, variables are divied into 2 types


1. LOCAL VARIABLES
2. GLOBAL VARIABLES:
Global variables are again divided into two types:
STATIC VARIABLES
NON-STAIC VARIABLES

LOCAL VARIABLES:

Variable which are declared inside a method and within the class, such variables are
called as Local variables.
Local variables are accessible only inside a method in which they are present. If we try
to access them outside of the method, we will get the compilation error (compile time
error)
It is compulsory to initialise local variables before we use them.
All the local variable are present in ‘Stack Memory Area’.

GLOBAL VARIABLES:

Variables which are declared outside a method and within the class, such variables
are called Global variables.
Global variable are accsessible any where with in the scope of a class.
It is not compulsory to initialise global varirables.
If we did not initialize, compiler, will consider default values based on datatype.
Global variabes are present in ‘Heap Memory Area’.
Global variable are divided into two types
STATC VARIABLES
NON STATIC VARIABLES

DATATYPE DEFVALUE

BYTE,SHORT,INT,LONG 0

FLOAT,DOUBLE 0.0

CHAR EMPTY SPACE

BOOLEAN FALSE

STRING NULL
DIFFERENCE B/W LOCAL & GLOBAL VARIABLES

LOCAL VARIABLES GLOBAL VARIABLES

1. Local variable are those, which are 1. Global variables are declared outside
declared inside a method and within method and with in a class.
the class

2. Local variable are accessible only inside 2. Global variables are accessible any
a method, in which they are present. where within the scop of a class.

3. It is compulsory to initialise local 3. It is not compulsory to initialise global


variables before we use them. variables.

4. There is no types in local variables 4. There are 2 types in global variables


1.Static Variable
2.Non Static Variables

5. Local variables are present in Stack 5. Global variables are present in Heap

Memory Area. Memory Area.

STATIC VARIABLES:-

A variables which is present outside a method and with in the class and having static
keyword such variables is Static Variables.
Syntax:
STATIC DATATYPE VAR = VALUE;

1. CREATE A CLASS AS SHOPPING

2. DECLARE SOME STATIC VARIABLE AS

STORENAME
PRODUCT NAME
BRAND
COLOR
PRICE

3.CREATE A STATIC METHOD AS SHOPPING DETAILS ( ) & PRINT ALL

STATIC VARIABLE.
4.CREATE MAIN ( ) & MAKE A CALL TO SHOPPING DETAILS ( )

public class Shopping

static String Storename = "APTRONIX";

static String Productname = "IPHONE-14PLUS";

static String Brand = "APPLE";

static String Color = "RED";

static int price = 75000;

public static void main(String args[])

ShoppingDetails();

public static void ShoppingDetails()

System.out.println("STORE NAME: "+Storename+"\nproduct name: "+Productname


+"\nbrand: "+Brand+"\ncolor: "+Color+"\nprice: "+price);

1.CREATE A CLASS AS BOOK STORE

2.DECLEARE & INITIALSE STATIC VARIABLE AS

STORENAME
BOOKNAME
AUTHOR
PAGES
COLOR
PUBLISHER
PRICE

3.CREATE A STATIC METHOD AS BOOK DETAILS ( ) & PRINT ALL STATIC


VARIABLES HERE

4.CREATE MAIN ( ) & MAKE A ALL TO BOOK DETAILS ( )

public class BookStore

static String Storename = "LIBRARY";

static String Bookname = "DMM-2";

static String Author = "R.S.KHURMI";

static String pages = "5000";

static String Color = "BLUE";

static String Publisher = "RAM NAGAR,NEW DELHI-110 055";

static int Price = 670;

public static void main(String args[])

BookStore();

public static void BookStore()

System.out.println("STORENAME: "+Storename+"\nbook name: "+Bookname+"


\nauthor:"+Author+"\npages: "+pages+"\ncolor: "+Color+"\npublisher: "+Publisher);

}
NON STATIC VARIABLE:-

A variable which is present out side method with in the class & does’t have static
keyword, such variable are called as Non Static Variable.

Syntax: DATATYPE VAR = VALUE;

NON STATIC METHOD:-

If a method does not have static keyword such method are called as Non Static Method.

NOTE:

Non static variables can not be accessible directly inside a static method, if we want
them to access we have to create an object.
Non static method can not be call directly inside a static method, if we want them to
call we have to create an object.

public class Addition

int i = 100, j = 300; // non static variables

public static void Addition()

System.out.println(i+j);//(CTE as i and j cannot be reffered directly inside static)

public static void main(String args[])

{
Addition();

SYNTAX OF OBJECT CREATION:-

CLASSNAME REFERENCE VARIABLE = NEW KEYWORD CLASS NAME ( );

(OR)

CLASSNAME REFERENCE VARIABLE = NEW KEYWORD CONSTRUCTOR ( );

New is a keyword which creates an objects.


New keyword will loads all non static members ( non static method & non static
variables inside an object)
After loading, reference variable will be assigned to that object.
Using reference variables & dot operator we can access all non static menber present
inside that object.

ACCESSING NON-STATIC VARIABLE INSIDE STATIC METHOD BY CREATING


AN OBJECT

public class Addition

int i = 100, j = 300; // non static variables

public static void Addition()

Addition A1 = new Addition( );

System.out.println(A1.i+A1.j);

public static void main(String args[])

Addition();
}

CALLING NON STATIC METHOD INSIDE STATIC METHOD THROUGH OBJECT

public class Addition

public void Addition() // non static method

System.out.println(“Addition Method)

public static void main(String args[])

Addition A1 = new Addition( );

A1.Addition();

CONCLUSION POINT:

SITUATIONS WHERE WE NEED TO CREATE AN OBJECT:

Non static variables inside static method


Non static method inside static method

SITUATIONS WHERE WE NEED NOT TO CREATE AN OBJECT

Static variable inside static method


Static method inside static method
Static variable inside non static method
Non static method inside non static method
Non static variable inside non static method
Static method inside non static method

/*WAP TO PRINT ADDITION USING STATIC VARIABLES & NON STATIC


VARIABLES THROUGH OBJECT CREATION */

public class Addition

static int i = 100; // Static Variables

int j = 200; // Non Static Variables

public static void Addition() // Static Variabes

Addition A1 = new Addition(); // Non Static Var Inside Static Method Access Through Object

System.out.println(i+A1.j); // Static & Non Static Inside Static

public void Subtraction() //Non Static Method

System.out.println(i-j); // Static & Non Static Inside Non Static

public static void main(String args[])

Addition();

Addition A2 = new Addition();

A2.Subtraction(); // Non Static Method Inside Static Call Through Object

OUTPUT

300
-100

1.CREATE AN FOODORDER APP

2.DECLARE & INITIALISE SOME STATIC VARIABLES

Restaurant_Name
No_of_dishes_order
Price

3.DECLARE & INITIALISE SOME NON STATIC VARIABES

Order_id
Discount_amt

4.CREATE A STATIC METHOD AS ORDER_DETAILS ( )

& PRINT ALL STATIC & NON STATIC VARIABLES

5.CREATE AN NON STATIC METHOD AS DELIVERY_PERSON ( STRING


ADDRESS, INT WAIT_CHARGES)

AND PRNIT ADDRESS & WAIT_CHARGES

AND MAKE A CALL TO ORDER_DETILS ( )

6.CREATE AN NON STATIC METHOD AS ZOMATO _PARTNER ( )

DECLARE AND INITIALISE SOME LOCAL VARIABLES AS

Food_rating

Delivery_rating

Hygenic_rating

PRINT THESE LOCAL VARIABLES

MAKE A CALL TO DELIVERY_PERSON METHOD

7.CREATE A MAIN ( ) AND MAKE A CALL TO ZOMATO_PATNER ( )

public class FoodOrderApp

static String Restaurant_Name = "NAIDU GARI KUNDA BIRYANI";

static int No_of_dishes_order = 25;


static int price = 20000;

int order_id = 234518990;

int discount_amt = 200;

public static void OrderDetails()

FoodOrderApp A1 = new FoodOrderApp();

System.out.println("Restaurant_Name:"+Restaurant_Name+"\nno_of_dishes_order: "+
No_of_dishes_order+"\nprice:"+price+" \norder _id:" +A1.order_id+" \ndiscount_amt:
"+A1.discount_amt);

public void delivery_person(String address,int wait_charges)

System.out.println("Address: "+address+"\nwait_charges: "+wait_charges);

OrderDetails();

public void Zomto_panter()

int food_rating = 3;

int delivery_rating = 5;

int hygenic_rating = 3;

System.out.println("food_rating: "+food_rating+"\ndelivery_rating: "+delivery_rating+"


\nhygenic_rating: "+hygenic_rating);

delivery_person("VIJAYAWADA",50);

public static void main(String args[])

{
FoodOrderApp A2 = new FoodOrderApp();

A2.Zomto_panter();

1.CREATE AN GROCERY_APP

2.DECLARE & INITIALISE SOME STATIC VARIABLES

Item_name
Brand_name

3.DECLARE & INITIALISE SOME NON STATIC VARIABLES

Amount
Quantity

4.CREATE A STATIC METHOD AS CUSTOMER_ORDER( )

& PRINT ALL DETAILS

5.CREATE A NON STATIC METHOD AS DELIVERY _PARTNER( )

& CREATE SOME LOCAL VARIABLES AS

Mask_charges

Sanitise_charges

PRINT ALL LOCAL VARIABLES VALUES.

6.CREATE MAIN ( ) AND MAKE A CALL TO CUSTOMER_ORDER ( )


public class Grocery_App

static String item_name = "BISCUIT";

static String brand_name = "BRITANNIA";

int Amount = 2000;

int Quantity = 10;

public static void customer_order()

System.out.println("ORDER DETAILS :");

Grocery_App A1 = new Grocery_App();

System.out.println("item_name:"+item_name+"\nbrand_name:"+brand_name+"\nAmou
nt:"+A1.Amount+"\nQuantity:"+A1.Quantity);

public void delivery_panter()

int mask_charges = 245;

int scanitise_charges = 65;

System.out.println("mask_charges: "+mask_charges+"\nscanitise_cahrges:"+scanitise
_charges);

public static void main(String args[])

customer_order();

Grocery_App A2 = new Grocery_App();

A2.delivery_panter();

}
}

EXECUTION PROCESS:-

-Whenever we execute any program there will be two memory blocks that gets created.

1.Stack area also called as Execution Area.

2.Heap area also called as Storage Area.

POINTS:-

1.First JVM will enter into stack area and make a call to class Loader.

2.Class loader is like a developing tool whose job is to load all static members into static pool
area (SPA).

3.SPA is a part of heap area and its name is same as class name.

4.Once class loader loads all static members into SPA its job is completed so it will come out of
stack area.

5.Next JVM will make a call to main method.

6.Upon call to anymethod, that method will get loaded in stack area.

7.Next Execution of main method will start

8.Once entire execution is completed main( ) also come out of stack are

9.Next JVM before coming out of stack area it will make a call to garbage collector whose job
is to cleanup entire memory for next execution.
GARBAGE COLLECTOR:

Is a pre-defined method of system class JVM will call it internally.

Syntax: PUBLIC STATIC VOID GC( );

In case if we want to call garbage collector we can call it with the syntax as

SYSTEM.GC( )
CONCLUSION:-

Static methods & static variables are available (SPA) before execution starts that’s why
they are accessible without object creation.
Non static members are not available before execution so to access them we have to
create an oject. With new keyword object will get created & loads all non static
members inside it.
All static members together present at one place and all non static members together
present at one place so we can access direectly.
Static member will get loaded only once in SPA that’s why they are reffered as single
copy.
Since non static member will get loaded whenever we created an object that’s why they
reffered as multiple copies.
Local variables are present in stack area & global variables present in heap area.
Static variables are present in SPA(Heap)
Non static variables are present in object(Heap)
DIFFERENCE B/W STATIC & NON-STATIC

STATIC NON STATIC

1.Static refers to sigle copy 1.Non static refers to multiple copies

2.Static members will be loaded only 2.Non static members will be loaded

once in static pool area. whenever we create an object.

3.Static member are present in static pool 3.Non static member are present inside

area. an object.

4.Class loader is responsible to load static 4.New keyword is responsible to load

members. non static member.

5.Static member can be access in 3 ways 5.Non static can be access through

Directly object.
Through object
Though class name

6.If i change the value of static variable, it 6.If i change the value of non static

will affect entire class that’s why static variable, it will affect only one object,

variables are also called as class variables. that’s why non static variable is also

called as Instance variables.

7.We will go for static, if the data is 7.We will go for non static, if the data is

fixed. varying.

Ex: PAN NO, PASSPORT NO Ex: EMAIL ID (CHANGING)

8.Static members can not be inherited. 8.Non static members can be inherited.

9.Static members can not be over ridden. 9. Non static members can be over

ridden.
MULTIPLE WAYS TO ACCESS STATIC MEMBERS.

Static members can be accessed in 3 ways

DIRECTLY:-

Because they will get loaded only once in static pool area (SPA).

THROUGH CLASS NAME:-

Because class name and static pool area name are same.

THROUGH OBJECT:-

Because there is a one way connection b/w object & static pool area (SPA).

class A

static int i = 100;

public static void main (String args[])

System.out.println(i);

System.out.println(A.i);

A a1 = new A();

System.out.println(a1.i);

WORKING WITH ECLIPSE:

Install eclipse from google


Click on icon & wait untill it launches
Provide workspace (place to store prgram)

STEP-1 CRAETION OF PROJECT:-

1.Click on file new java project provide project name click on finish
click on don’t create for module we can see one project folder is created left side.
STEP-2 CRAETION OF PACKAGE:-

Package Is used to keep all classes together at one place

1.Click on file new package name provide package name verify source folder
name click on finish we can see that under project folder one pakage folder is
created.

STEP-3 CRAETION OF CLASS :-

1.Click on file new class provide class name verify source folder name &
package name select checkbox for main method click on finish we can see that
a class is created to develop logic.

STEP-4 EXECUTION PROGRAM :-

Click on Run Button

Ex:-1

class Demo

static int i = 100;

public static void main (String args[])

System.out.println(i);

System.out.println(Demo.i);

Demo d1 = new Demo();

System.out.println(d1.i);

ACCESSING MEMBERS OF ONE CLASS INTO ANOTHER CLASS:-

We can access both static as well as non static members of one class into another class.
Static members of one class can be accessed in another class through class name.
Non static members of one class can be accessed in another class by creating an object.
When we have more than one class, we have conisder following points.
1. Only one class can have main method.
2. File name must be same as class name of main method.
3. The class which is having main method, only that class should be public.

Ex:2:-

class A

static int i = 100;

int j = 400;

public class B

public static void main (String args[])

System.out.println(A.i);

A a1 = new A();

System.out.println(a1.j);

In above program, classs loader will first load static member of ‘B’ class, because it
contains main method & execution start with main method.
Once, JVM notice ‘A’ class, again it makes a call to class loader & this time class
loader will load static member of A class.

NEED OF CONSTRUCTOR:

Avoiding For initialisation of non static variables in multiple times (through


object creation), we need constructor.
public class student

static String inst_name;

String batchcode;

public static void main(String args[])

Student s1 = new Student();

Student s2 = new Student();

Student s3 = new Student();

From the above memory diagram, we can observe that static variable have single
memory. Where as, non static variable have separate memory for each object which
means, we can initialise single value for static variable but multiple values for non
static variable.
Initialising separate value for each object is a greedy aporch. Therefore to overcome
this java has introduce constructors.

CONSTRUCTOR:

DEFINITION:

Constructor is a special type of method which gets executed whenever we created an


object.
The main purpose of constructor is to initialise a non static variable.

Syntax:
ACCESSMODIFIER CONSTRUCTOR NAME (WITH ARGUMENTS / WITH OUT ARUGUMENTS

RULES FOR DEFINING CONSTRUCTOR:

Constructor can be public,private,protected or default.


Constructor cannot be static, non static, final or abstract.
Constructor name must be same as that of classname.
Constructor does not have any return type not even void
Constructor can be with arguments or without arguments.
We have 3 types of constructors:
1. NO ARGUMENTS CONSTRUCTOR
2. WITH ARGUMENTS CONSTRUCTOR
3. DEFAULT CONSTRUCTOR

1. NO ARGUMENTS CONSTRUCTOR:

public class Dog

String dname;

public Dog()

dname = "Tommy";

public static void main(String args[])

Dog D1 = new Dog();

System.out.println(D1.dname);

Dog D2 = new Dog();

System.out.println(D2.dname);

If a constructor does not have arguments, it is called No Argument Constructor.


With no argument constructor, one of the disadvantages is same value will be initialse
for each object. To overcome this, we will use with argument constructor (or)
Parameterized constructor.

2.WITH ARGUMENT CONSTRUCTOR:

If a constructor have any arguments, it is called as with argument constructor.

public class Dog

String dname;

public Dog(String DogName)

dname = DogName;

public static void main(String args[])

Dog D1 = new Dog("Tommy");

System.out.println(D1.dname);

Dog D2 = new Dog("Fluffy");

System.out.println(D2.dname);

}
2.CREATE A CLASS AS BOOK

-DECLARE SOME INSTANCE VARIABLE AS

bname
bcolor
bprice

-TO INITIALISE THEM USE WITH ARGUMENT CONSTRUCTOR

-CREATE MAIN ( ) & MAKE A CALL TO CONSTRUCTOR ATLEAST 3 TIMES TO


PRINT INFORMATION OF 3 BOOKS

public class Book

String bname,bcolor;

int bprice;

public Book(String bookname,String bookcolor,int bookprice)

bname = bookname;

bcolor = bookcolor;

bprice = bookprice;

public static void main(String args[])

Book A1= new Book("JAVA","BULE",600);

System.out.println("bname:"+A1.bname+"\nbcolor:"+A1.bcolor+"\nbprice:"+A1.bprice);

Book A2 = new Book("SQL","RED",400);

System.out.println("bname:"+A2.bname+"\nbcolor:"+A2.bcolor+"\nbprice:"+A2.bprice);

Book A3= new Book("MANUAL","BULE",200);


System.out.println("bname:"+A3.bname+"\nbcolor:"+A3.bcolor+"\nbprice:"+A3.bprice);

3.CREATE A CLASS AS EMPLOYEE

-DECLARE SOME INSTANCE VARIABLES AS

Ename
Eid
Esal

-TO INITIALISE THEM WE USE PARAMETENISED CONSTRUCTOR

-IN CONSTRUCTOR KEEP ARGUMENTS NAME SAME ACTUAL VARIARBLE

NAME.

-CREATE MAIN METHOD & CREATE 3 OBJECTS TO CALL CONSTRUCTOR 3

TIMES.

public class Employee

String ename;

int eid,esal;

public Employee(String ename,int eid,int esal)

{
ename = ename;

esal = esal;

eid = eid;

public static void main(String args[])

Employee E1 = new Employee("SUNIL",7689,20000);

System.out.println(E1.ename+" "+E1.eid+" "+E1.esal);

Employee E2 = new Employee("MAHESH",7765,4000);

System.out.println(E2.ename+" "+E2.eid+" "+E2.esal);

Employee E3= new Employee("TARUN",7135,20023);

System.out.println(E3.ename+" "+E3.eid+" "+E3.esal);

NOTE:

Generally, we will keep different names for argument variables & actual variables.
In case, if we keep same name we are getting default value as output.
Inorder to overcome this,we will use ‘This’ keyword.

4.CREATE A CLASS AS EMPLOYEE

-DECLARE SOME INSTANCE VARIABLES AS

Ename
Eid
Esal
-TO INITIALISE THEM WE USE PARAMETENISED CONSTRUCTOR

-IN CONSTRUCTOR KEEP ARGUMENTS NAME SAME ACTUAL VARIARBLE

NAME.

-CREATE MAIN METHOD & CREATE 3 OBJECTS TO CALL CONSTRUCTOR 3

TIMES.

public class Employee

String ename;

int eid,esal;

public Employee(String ename,int eid,int esal)

this.ename = ename;

this.esal = esal;

this.eid = eid;

public static void main(String args[])

Employee E1 = new Employee("SUNIL",7689,20000);

System.out.println(E1.ename+" "+E1.eid+" "+E1.esal);

Employee E2 = new Employee("MAHESH",7765,4000);

System.out.println(E2.ename+" "+E2.eid+" "+E2.esal);

Employee E3= new Employee("TARUN",7135,20023);

System.out.println(E3.ename+" "+E3.eid+" "+E3.esal);

}
THIS KEYWORD:-

This key word indicate current object reference name.


We will use ‘This’ Keyword to differentiate between argument variables and actual
variables.
We will use ‘This’ Keyword inside a constructor and inside a method.

5.CREATE A CLASS AS SHOPPING

-DECLARE INSTANCE VARIABLES AS

Product
Brand
Price
Color

-TO INITIALISE USE CONSTRUCTOR WITH ARGUMEMT & ARGUMENT SAME

AS ACTUAL VARIABLE NAME.

-CREATE MAIN ( ) & MAKE A CALL TO CONSTRUCTOR ATLEAST 3 TIMES.

public class Shopping

String product,brand,color;

int price;

public Shopping(String product,String brand,String color,int price )

this.product = product;

this.brand = brand;

this.color = color;
this.price = price;

public static void main(String args[])

Shopping A1= new Shopping("I-PHONE","APPLE","BULE",75000);

System.out.println(A1.product+" "+A1.brand+" "+A1.color+" "+A1.price);

Shopping A2 = new Shopping("LAP-TOP-5","DELL","GRAY",50000);

System.out.println(A2.product+" "+A2.brand+" "+A2.color+" "+A2.price);

Shopping A3= new Shopping("SHIRT","US-POLO","BULE",2000);

System.out.println(A3.product+" "+A3.brand+" "+A3.color+" "+A3.price);

CONSTRUCTOR OVER LOADING:-

This process developing mutiple constructor with same name but different arguments is called
as a Constructor Over loading.

RULES FOR DEFINING ARGUMENT LIST:

Between Constructor,number of arguments must be different.


Between Constructor, types of arguments must be different.
Betwwen Constructor, sequence or position of argument must be different.

6.CREATE A CAR CLASS

2.DECLAE 5 INSTANCE VARIABLE

Name
Color
Price
Capacity
Model

3.CREATE WITH ARGUMENT CONSTRUCTORS

CAR(String Name, String Color)

CAR(String Name, String Color, Double Price)

CAR(String Name, String Color, Double Price, Int Capactiy, String Model)

public class Car

String name,color,model;

int capacity;

double price;

public Car(String name,String color)

this.name = name;

this.color = color;

public Car(String name,String color,double price)

this.name = name;

this.color = color;

this.price = price;

public Car(String name,String color,double price,int capacity,String model )

this.name = name;
this.color = color;

this.price = price;

this.model = model;

this.capacity = capacity;

public static void main(String args[])

Car C1 = new Car("BMW","RED");

System.out.println(C1.name+" "+C1.color);

Car C2 = new Car("AUDI","BULE",6000000.75);

System.out.println(C2.name+" "+C2.color+" "+C2.price);

Car C3 = new Car("TATA","WHITE",2000000.35,4,"TATA NEXON");

System.out.println(C3.name+" "+C3.color+" "+C3.price+" "+C3.capacity+"


"+C3.model);

7.CREATE A BOOK CLASS

2.DECLARE SOME INSTANCE VARIABLES

Name
Price
Author
Pages

3.CREATE OVER LOADED CONSTRUCTORS


Book(Sting Name, Int Price)

Book(String Name, String Author, Int Price)

Book(String Name, String Author, Int Price,Int Pages)

4.CREATE DISPLAY-1( ), DISPLAY-2( ), DISPLAY-3( )

5.CREATE MAIN ( ) & CREATE 3 OBJECTS ON EACH OBJECT CALL DISPLAY ( ).

The main purpose of constructor overloading is to create an object in mutiple ways.

public class Book

String name,author;

int price,pages;

public Book(String name,int price)

this.name = name;

this.price = price;

public Book(String name,String author,int price)

this.name = name;

this.author = author;

this.price = price;

public Book(String name,String author,int price,int pages )

this.name = name;

this.author = author;
this.price = price;

this.pages = pages;

public void display1()

System.out.println(name+" "+price);

public void display2()

System.out.println(name+" "+author+" "+price);

public void display3()

System.out.println(name+" "+author+" "+price+" "+pages);

public static void main(String args[])

Book B1 = new Book("KOM",565);

B1.display1();

Book B2 = new Book("DESIGN DATA BOOK","S.MD.JALALUDEEN",989);

B2.display2();

Book B3 = new Book("MACHINE DARWING","N.D BHATT",400,345);

B3.display3();

}
CONSTRUCTOR CHAINING:

The process of calling one constructor from another constructor is called as Constructor
Chaining

CONSTRUCTOR CHAINING CAN BE ACHIEVED IN TWO WAYS:

1. Call to This Represented as This ( )


2. Call to Super Represented as Super ( )

CALL TO THIS-THIS ( )

The process of calling one constructor from another constructor of same class is called
as a Call to This.
The main rule for this ( ) is – Call to this must be first statement of a constructor.

Example:1:-

public class Add

public Add()

this(100,200);//call to this->call another constructor of same class with 2 int args

System.out.println("CONSTRUCTOR WITHOUT ARGUMENTS");

public Add(int i,int j)

this("java");// call to this->call another constructor of same class with String args

System.out.println("CONSTRUCTOR WITH 2 INT ARGUMENTS");

}
public Add(String s)

System.out.println("CONSTRUCTOR WITH STRING ARGUMENTS");

public static void main(String args[])

Add A1 = new Add();

Example:2:-

public class Add

public Add()

System.out.println("CONSTRUCTOR WITHOUT ARGUMENTS");

public Add(int i,int j)

this("java");

System.out.println("CONSTRUCTOR WITH 2 INT ARGUMENTS");

}
public Add(String s)

this();

System.out.println("CONSTRUCTOR WITH STRING ARGUMENTS");

public static void main(String args[])

Add A1 = new Add(100,200);

Example:3:-

public class Add

public Add()

this(800,1000);

System.out.println("CONSTRUCTOR WITHOUT ARGUMENTS");

public Add(int i,int j)

System.out.println("CONSTRUCTOR WITH 2 INT ARGUMENTS");

}
public Add(String s)

this();

System.out.println("CONSTRUCTOR WITH STRING ARGUMENTS");

public static void main(String args[])

Add A1 = new Add("java");

DEFAULT CONSTRUCTOR:-

If we created object & did not defined a constructor then in that situation compiler will add
one constructor by itself such costructor is called as Default Constructor.

Ex: WHAT WE WRITE

class A

public static void main(String args[])

A a1 = new A();

WHAT IS ACTUALLY MEANS


class A

//@ added by compiler-----> default constructor

public Add

public static void main(String args[])

A a1 = new A();

METHOD WITH RETURN TYPE:-

Void means no specific return type – it indicates that method is not returing any value.
In place of void we can give any specific return type for returning speific value.
We can use any primitive or non primitive data type as a return specific value.
Whenever we give method with specific return type it is complsory to add return
statement.

RETURN STATEMENT:-

Return is a keyword which is used to return specific value


Syntax is return value;
Return keyword will provide data to JVM and make it to exit from the method
In one method there should only be one return statement.
Return statement must be the last statement of a method.

// static method without return type without arguments

public static void Add()

{ Add();

// static method without return type with arguments


public static void Add(int i)

{ Add(1000);

// static method with intger return type without arguments

public static int Add()

{ int v = Add();

return int value;

// static method with string return type with intger arguments

public static String Add(int i)

{ String v = Add(1000);

return string value;

// non static method without return type without arguments

class A

public void Add() A a1 = new A();

{ a1.add();

// non static method without return type with arguments

public void Add(String s)

{ a1.add("java");

// non static method with boolean return type without arguments

public boolean Add()


{ boolean v = a1.Add();

return boolean value;

// non static method with float return type with arguments

public float Add(int i,int j)

{ float v = a1.Add(100,200);

return float value;

Example-1:-

1.CREATE A CLASS AS AREAS

2.CREATE A STATIC METHOD WTH ARGUMENTS & RETURN TYPE AS

Area of Cricle (int radius) : float calculate area of circle

3.CREATE MAIN ( ) & MAKE A CALL TO AREA OF CIRCLE METHOD

public class Areas

public static float areaofcircle(int radius)

return 3.14F*radius*radius;

public static void main(String args[])

float areaR = areaofcircle(5);

System.out.println("Area of circle is :"+areaR);

}
}

Example-2:-

1.CREATE A CLASS AS FACTORIAL

2.CREATE A NON STATIC METHOD WITH ARGUMENT & WITH RETURN TYPE
AS

Fact (int num) : int develop logic of factorical of number

3.CREATE MAIN ( ) & MAKE A CALL TO FACT METHOD

public class Factorial

public int fact(int num)

int fact =1 ;

for(int i=num;i>=1;i--)

fact = fact*i;

return fact;

public static void main(String args[])

Factorial f = new Factorial();

int ft = f.fact(5);

System.out.println("Factroical of number is :"+ft);


}

UML:- (UNIFIED MODELING LANGUAGE)

It is a pictoral representation of a program

+ Public

- Private

# Protected

~ Default

Extends Implements
MODULE:-3 (OBJECT ORIENTED PROGRAMMING)

OOPS
CLASS
OBJECT
INHERITANCE
SUPER( )
METHOD OVER RIDING
SUPER AND FINAL KEYWORD
ENCAPSULATION
TYPE CASTING
OBJECT CASTING
ABSTRACTION
INTERFACE
POLYMORPHISM
METHOD BINDING

OOPS:- (OBJECT ORIENTED PROGRAMMING)

It is a programming methodolgy or programming strategy which is required to fullfill


every project requirement.
It has 4 pillars

PILLARS PURPOSE

1.Inheritance Code Reusability

2.Abstraction Hiding Internal Details

3.Encapsulation Securing Data

4.Polymorphism One Thing Showing Multiple Behaviour

CLASS:-

Class is define as logical entity because it represent logic of an application.

OBJECT:-

An object is defined as physical entity because physically it stores non static members in
each object.
CLASS OBJECT

1. logical entity 1.Physical entity


2. Class is defined as blue print or 2.Object is defined as reflection of a class.
Templet of an application.
3. Class is created by using class key 3.Object is created by using new key word.
Word.
4. Class contains any type of members 4.Object contains only Non-Static Members.
(Static / Non Static).
5. Class does not occpy any memory 5.With evey object memory will be reserved
in heap area. in heap area.

INHERITANCE:

It is the first pillar of oops concept.


One class Acquiring properties of another class is called as Inheritance.
(Or)
One class containing members of another class without rewriting is called as
Inheritance.
Inheritance is also called is-a-relationship.
Extends is a keyword which indicate that we are creating new class from an existing
class.
Extends keyword indicate about inheritance.

Syntax:
Class A

Class B Extends A

The class whose properties is are acquired is called as Parent class (or) Super class
(or) Base class.
The class who is acquiring the properties is called as Child class (or) Sub class (or)
Drived class.
In the above synatx, “A” class is a parent class, “B” class is a child class.
Parent class contains only it’s own property.
Child class contains it’s own properties as well as properties of parent class.
Therefore if we create an object of parent class, we can access only parent class
properties, but if we create an object of child class, we can access both parent class as
well as child class properties.

NOTE:-

Here properties are nothing but methods & variables.


We can inherit only non static members.
We can not inherit static member because they will always be located only once in
static pool area (SPA).
We can not inherit constructors because they are not a proper member of a class. They
will just use for initialization purpose.

Ex:-

class Youtub V1 Parent / Super / Base

Search()

Channels

Downloads() 44 4

Vidoes() is-a-relationship

class Youtub V2 Extends Youtub V1 Child / Sub / Drive

Subscription()

Reaction() 6 4 (P) + 2 (Own)

Every application can two types of class


1.BUSINESS LOGIC CLASS
2.USER LOGIC CLASS
The class which does not have main method is called as Business logic class.
The class which have main method is called as User logic class.
We should always save the application with userlogic.java

Ex:-

class op1

public void Withdraw() Business logic

class op2

public void Deposit() Business logic

public class ATM User logic class What user is expecting

{ having main()

public static void main(String args[])

Withdraw();

Deposit();

}
TYPES OF INHERITANCE:-

We have five types of inheritance.

1.SINGLE LEVEL INHERITANCE

2.MULTI LEVEL INHERITANCE

3.HIERARCHICAL INHERITANCE

4.MULTIPLE INHERITANCE

5.HYBRID INHERITANCE

1.SINGLE LEVEL INHERITANCE:-

One parent class and one chlid class is called single level inheritance.

PROGRAM:-

class Animal

public void Eat()

System.out.println("Animal Eats");
}

class Dog extends Animal

public void Brak()

System.out.println("Dog Brak");

public class Forest

public static void main(String args[])

Dog F1 = new Dog();

F1.Eat();

F1.Brak();

}
2.MULTI LEVEL INHERITANCE:-

One grand parent,one parent,one child is called multi level inheritance.

PROGRAM:

class Animal

public void Eat()

System.out.println("Animal Eats");

class Dog extends Animal

public void Brak()

System.out.println("Dog Brak");

class Cat extends Dog

public void Meow()

System.out.println("Cat Meow");

}
public class Forest

public static void main(String args[])

Cat C1 = new Cat();

C1.Eat();

C1.Brak();

C1.Meow();

3.HIERARCHICAL INHERITANCE:-

One parent and two child class is called hierarchical


inheritance

PROGRAM:-

class Animal

public void Eat()

System.out.println("Animal Eats");

}
class Dog extends Animal

public void Brak()

System.out.println("Dog Brak");

class Cat extends Dog

public void Meow()

System.out.println("Cat Meow");

public class Forest

public static void main(String args[])

Dog D1 = new Dog();

D1.Eat();

D1.Brak();

Cat C1 = new Cat();

C1.Eat();

C1.Meow();

}
}

4.MULTIPLE INHERITANCE:-

One class inheriting two parent class at the same time is called as multiple inheritance
i.e. one child having two parent is said to be Multiple Inheritance Relationship.
Multiple inheritance is not possible through class due to following problems
1.AMBIGUITY PROBLEM
2.DIAMOND PROBLEM
3.CONSTRUCTR CHAINING PROBLEM

1.AMBIGUITY PROBLEM:-

As per multiple inheritance, one child is having two parent. In case, if both the parent
have same method then while calling a method through child class there is a confusion
which parent class method to call.
This problem is called as Ambiguity problem

Example:-

class Carni

public void Eat()

System.out.println("Carni Eats");

class Herbi

{
public void Eat()

System.out.println("Herbi Eat");

class Animals extends Carni,Herbi

public class Forest

public static void main(String args[])

Animals A1 = new Animals();

A1.Eat();

} problem is here only, JVM can’t understand that which eat( ) method

should go for call.

So, Ambiguity Problem

2.DIAMOND PROBLEM:-

Since, the shape of a class diagram is in diamond sturcture, so due to this reason one
of the problem is considered as Diamond shape class diagram problem.

CALL TO SUPER / SUPER ( ):


The process of calling parent class constructor through child class constructor is called
as call to super.
We have to call parent class constructor through child class because constructors can
not be inherited.
Call to super, is implicit as well as explicit in nature.
Call to super will be implicit optional if class constructor does not have arguments
(Here implicit means added by compiler).
Call to super, is explicit if parent class constructor have arguments (Here explicit
means we shouldd only added compulsorily).
Call to super, must be the first statement in a constructor. We can’t write it in any other
line except first line.

//CALL TO SUPER IS IMPLICIT(OPTIONAL) CLASS CONSTRUCTOR DOES


NOT HAVE ARGUMENTS.

class A

public A ()

System.out.println("A-class Constructor");

class B extends A

public B ()

//super() ---> default call to super added by compiler.

System.out.println("B-class Constructor");

public class C
{

public static void main(String args[])

B b1 = new B();

//SUPER( ) IS EXPLICIT THAT MANDATORY SINCE PARENT CLASS CONSTRUCT


OR HAVE ARGUMENT.

class A

public A (int i)

System.out.println("A-class Constructor");

class B extends A

public B ()

super(10000);

System.out.println("B-class Constructor");

}
}

public class C

public static void main(String args[])

B b1 = new B();

3.CONSTRUCTOR CHAINING PROBLEM:

class A

public A ()

class B

public B ()

class C extends A,B //Class C having only one constructor i.e C( ) constuctor. Because can’t
{ inherit.

public B ()

super();

super();//Invalid -It is not in first statement constructor chaining problem.

As per multiple inheritance one child is having two parent & if both the parent have
constructor, we need to call them by using multiple call to super, which is not possible
& this lead to constructor chaining problem.
Therfore, due to ambiguity, diamond & constructor chaining problem, multiple
inheritance is not possblie through class. But, it is possible through interface.

5.HYBRID INHERITANCE:

It is combination of hierarchical inheritance & multiple inheritance. Since, multiple


inheritance is not possible, hyrid inheritance is also not possible.

ADVANTAGES OF INHERITANCE:

Code Reusability
Connecting multiple logic at one place.
Easy to understand

REAL TIME EXAMPLES:

Updating any application from one verison to another is an example of inheritance,


where in without re-coding pervious verison features will be inherited.
(Facebook, Youtube App…)
Back up data
Banking Application (One Time You Give Your Details)
E-commerce Application(One Time You Fill Your Details)

METHOD OVER RIDING:

Parent class & child class are having same method but implementation is different
process is called Method Over Riding.
(Or)
During inheritance, sub class have complete privilege to change method implemen
tation of super class. This is called as a Method Over Riding.

RULES FOR METHOD OVER RIDING:

1.Inheritance is compulsory.

2.Method header of super & sub class is same.

3.Method signature of super & sub class is same.

4.Super class method should not be final.

WHY DO WE GO FOR OVER RIDING?

When we want parent’s property/feature but does not want there implementation rather
we want to give our own implementation then we go for over riding.

PROGRAM:

class Parent

public void getmarried()

System.out.println("arrange marriage");

class Kids extends Parent

public void getmarried()

System.out.println("Love marriage");

}
public class Socity

public static void main(String args[])

Kids K1=new Kids();

K1.getmarried();

METHOD RESOLUTION:

When we call any method, method resolution will happen at two different stages
compilation & execution
During compilation, compiler will see reference i.e. whatever class we give for
reference variable, compiler will go to that class & just verify whether that method is
present or not.

NOTE:

Compiler will not decide body of the method.


During execution, JVM will see object type (right side whatever we gave after new
keyword).

NOTE:

JVM will decide body of the method.


EXAMPLE:-1:

class Telecom

public void getcallertune()

System.out.println("TRING TRING .......");

class Govt extends Telecom

public void getcallertune()

System.out.println("IPPUDU CORANA VIRUS........");

class Boys extends Telecom

public void getcallertune()

System.out.println("CHITTI NA BUL BUL CHITTI...........");

class Girls extends Telecom

{
public void getcallertune()

System.out.println("JHONY JHONY YES PAPA .............");

public class User

public static void main(String args[])

Girls G1=new Girls();

G1.getcallertune();

Govt G2=new Govt();

G2.getcallertune();

Boys B1=new Boys();

B1.getcallertune();

EXAMPLE:-2:

class Zomato

public void getresturant()


{

System.out.println("ACCORDING TO LOCATION");

class User extends Zomato

public void getresturant()

System.out.println("ACCORDING TO RATING AND REVIEWS");

public class Zomatouser

public static void main(String args[])

User U1=new User();

U1.getresturant();

Example:-1

class A

{
public void M1()

System.out.println("M1 method of A-class");

class B extends A

public void M1()

System.out.println("M1 method of B-class");

public void M2()

M1();

public class Demo

public static void main(String args[])

B b1 = new B();

b1.M2();

}
Example:-2

class A

public void M1()

System.out.println("M1 method of A-class");

class B extends A

public void M1()

System.out.println("M1 method of B-class");

public void M2()

super.M1();//? Which M1 ( )

} if you add super keyword then parent class M1( ) first loaded.

public class Demo

public static void main(String args[])


{

B b1 = new B();

b1.M2();

SUPER KEYWORD:-

Super keyword is used to call super class instance members.


We will use super keyword in child class method.
With the help of super keyword, we can get parent class implenentation even after over
riding happened.

PROGRAM:

class A

int i = 100;

public void M1()

System.out.println("M1 method of A-class");

class B extends A

int i =500;
public void M1()

System.out.println("M1 method of B-class");

public void M2()

M1(); // Current Class M1 ( )

System.out.println(i); // Current Class i value

super.M1(); // Parent class M1( )

System.out.println(super.i); // Parent class i value

public class Demo

public static void main(String args[])

B b1 = new B();

b1.M2();

FINAL KEYWORD:
Final is keyword, which indicate no more changes are allowed.
In a program, final keyword is applicable with
1.VARIABLE
2.METHOD
3.CLASS

FINAL VARIABLE:

If a variable is declared as final, two rules will be applicable.

RULE:-1:

If a variable is declared as final, we should compulsorily initialize the value, before we use it.

RULE:-2:

If a variable is declared as final, we can not change the value of it.

SYNTAX:

FINAL DATATYPE VARIABLE = VALUE;

EXAMPLE:-1:

class Sample

final static int i;

public static void main(String args[])

System.out.println(i);

EXAMPLE:-2:

class Sample
{

final static int i =500;

public static void main(String args[])

i = 1000; // CTE because i is a final variable

System.out.println(i);

FINAL WITH A CLASS:-

If a class is declared as final, we can not inherit that class, if we do we will get compile time
error (CTE).

SYNTAX:

FINAL CLASS CLASSNAME

EXAMPLE:-1:

final class A

class B extends A

public class Sample


{

A final class can inherit non-final class i.e. parent class should not be final but child
class can be final.

EXAMPLE:-2:

class A

Final class B extends A

public class Sample

FINAL WITH A METHOD:-

If a method is declared as final, we can not over ride it, because final method can not be over
ridden.

SYNTAX:

FINAL METHOD HEADER METHOD SIGNATURE


EXAMPLE:-1:

class Amazon

final public void logo()

System.out.println("Amazon's logo");

class Flipkart extends Amazon

public void logo()

System.out.println("Flipkart's logo");

public class Sample

TYPE CASTING:-

Converting one type of primitive data type into another type of primitive data type is
called as type casting.
(OR)
Assigning one type of value into another type is called as type casting.
It is divided into two types
1.WIDENING
2.NARROWING

1.WIDENING:-

Converting smaller primitive data type into bigger primitive data type is called as
Widening.
Widening is also called as Implicit Casting.
Byte Short Int Long Float Double
Since we are converting a smaller type into bigger type there is no loss of data.

2.NARROWING:-

Converting bigger primitive data type into smaller primitive data type is called as
Narrowing.
Narrowing is also called as Explicit Casting.
Byte Short Int Long Float Double
Since we are converting a bigger type into smaller type there is loss of data.

EXAMPLE:- PROGRAME OF WIDENING

public class Widening

public static void main(String args[])

byte b = 127;

short s = b; Implicit in value, directly we can convert

int i = s;

long L = i;

System.out.println(b);

System.out.println(s);

System.out.println(i);
System.out.println(L);

EXAMPLE:-1:- PROGRAME OF NARROWING

public class Narrowing

public static void main(String args[])

long L = 76543211;

int i = L ;

short s = i;

byte b = s;

System.out.println(b);

System.out.println(s);

System.out.println(i);

System.out.println(L);

}
EXAMPLE:-2:- PROGRAME OF NARROWING

public class Narrowing

public static void main(String args[])

long L = 76543211;

int i = (int) L ; // Explicitly Converting Long to Int

short s = (short) i; // Explicitly Converting Int to Short

byte b = (byte) s; // Explicitly Converting Short to Byte

System.out.println(b);

System.out.println(s);

System.out.println(i);

System.out.println(L);

OUT PUT

-21 Byte (-21 means garbage value, because byte size small)

-2837 Short (minimum because, size of short is small so it goes to garbage value)

76543211 Int

76543211 Long

OBJECT CASTING:

Converting one class type of object into another class type of object is called as
Object Casting.
Object casting is divided into two types
1.UP CASTING
2.DOWN CASTING
1.UP CASTING

Converting sub class object type into super class object type is called as Up Casting.
(OR)
Create an object of sub class and store it into a reference of super class is called as Up
Casting.
During Up-Casting only super class behviour is visible sub class behviour is hidden.

2.DOWN CASTING

Converting super class object type into sub class object type is called as Down Casting.
(OR)
Converting an upcasted object into normal form is called as Down Casting.
During Down Casting both sub class and super class behviour is visible.
Since super class does not contains property of sub class directly down casting is not
possible rather explicitly we have to convert it.
So that why down casting is explicit in nature.
Only upcasted object is down casted, i.e direct down casted object creation is not
possible if we do we will get ClassCastException.
EXAMPLE:-UPCASTING PROGRAM

class A

public void M1()

System.out.println("M1 METHOD");

class B extends A

public void M2()

System.out.println("M2 METHOD");

public class UpCasting

public static void main(String args[])

A a1 = new A(); // Parent Class Object

a1.M1();

B b1 = new B(); // Child Class Object

b1.M1();

b1.M2();

A a2 = new B(); // UpCasted


a2.M1(); // compiler check a2 which class reference then go ‘A’ class & M1() method

is parent are not ?

EXAMPLE:-DOWNCASTING PROGRAM

class A

public void M1()

System.out.println("M1 METHOD");

class B extends A

public void M2()

System.out.println("M2 METHOD");

public class DownCasting

{
public static void main(String args[])

A p = new A(); // Parent Class Object

p.M1();

B c = new B(); // Child Class Object

c.M1();

c.M2();

A a1 = new B(); // UpCasted

a1.M1

B b1 = (B) a1; // DownCasting Take reference of upcasting & explicitly Converting to

child class type.

b1.M1();

b1.M2();

NEED FOR OBJECT CASTING

If i want parent class properties & child class properties (both) then i should create
2times object for each parent & child.
But, here using object casting (UP+DOW N) i can access all into by using 1 object.
EXAMPLE:-1

QspiderApp

Viewing Editing

Student Yes No(Hidden)// UpCasting

Admin Yes Yes // DownCasting

class Student

public void Viewing()

System.out.println("Student can view details");

class Admin extends Student

public void Editing()

System.out.println("Admin can edit student data");

public class QspiderApp

public static void main(String args[])

Student A1 = new Admin();

A1.Viewing();
Admin A2 = (Admin) A1;

A2.Viewing();

A2.Editing();

EXAMPLE:-2

Aeroplane

Tyres Wings

Takeoff Hidden Visible // UpCasting

Landing Visible Visible // DownCasting

class Takeingoff

public void Tyres()

System.out.println("Tyers are Hidden");

class Landing extends Takeingoff

public void Wings()

{
System.out.println("Tyers and wings are visible");

public class Aeroplane

public static void main(String args[])

Takeingoff A1 = new Landing();

A1.Tyres();

Landing A2 = (Landing) A1;

A2.Tyres();

A2.Wings();

EXAMPLE:-3

Hotstar

Tvshows Liveshows

Normaluser Visible Hidden // UpCasting

Vipuser Visible Visible // DownCasting

class Normaluser

{
public void Tvshows()

System.out.println("Tvshows are Visible");

class Vipuser extends Normaluser

public void Liveshows()

System.out.println("Tvshows and Liveshows both are Visible");

public class Hotstar

public static void main(String args[])

Normaluser N1 = new Vipuser();

N1.Tvshows();

Vipuser V1 = (Vipuser) N1;

V1.Tvshows();

V1.Liveshows();

}
EXAMPLE:-4

LeaveApp

View Edit

Member Visible Hidden // UpCasting

Manager Visible Visible // DownCasting

class Member

public void View()

System.out.println("Employee apply a leave and view");

class Manager extends Member

public void Edit()

System.out.println("Manager to edit and view a leave");

public class LeaveApp

{
public static void main(String args[])

Member M1 = new Manager();

M1.View();

Manager M2 = (Manager) M1;

M2.View();

M2.Edit();

POLYMORPHISM:-

DEFINITION:

It is a greek word
Poly means many, morphism means forms.
One thing showing multiple behaviour is called as polymorphism.
(Or)
One entity shows different behaviour is called as polymorphism.

PolyTechnique Poly ---- Many


Technique ------- Technologies
PolyClinic Poly ---- Many
Clinic ------ Treatment

TYPES:

COMPILE TIME POLYMORPHISM

RUN TIME POLYMORPHISM

COMPILE TIME POLYMORPHISM


During compile time one thing showing multiple behaviour is called as compile time
polymorphism.

EXAMPLE:

Method over loading, where during compilation compiler will decide which behaviour

Implemented. So here, we will call to same method but depending on arguments it shows
different behaviour.

Public static void Add( ) Add( )

Public static void Add(int i) Add(1000)

Public static void Add(Double d, String s) Add(890.789,“JAVA”)

Public static void Add(String s,int j) Add(Ture

CTE, because compiler will decide which method should be execuit.

Add (True) there is boolean, so error occurred.

So, one compiler showing mutiple behaviour so,it is polymorphism.

It is also called as static polymorphism or compile time binding.

RUN TIME POLYMORPHISM

During Run / Execution time one thing showing mutiple behaviour, is called as Run
Time polymorphism

EXAMPLE:

Method Over Riding

Where there are multiple methods with same name, during execution
time only JVM will come to known which method to be executed depending on type of object.

class A

public void Run()


{

System.out.println("A class Method");

class B extends A

public void Run()

System.out.println("B class Method");

public class Main

public static void main(String args[])

A a1 = new A();

a1.Run();

B b1 = new B();

b1.Run();

A a2 = new B();

a2.Run();

}
ENCAPSULATION:

DEFINITION: The process of warpping methods & variables into a single unit class in order
protect them is called as Encapsulation

PURPOSE:

Protecting the data members by keeping them private and accessing through some special
method is nothing but Encapsulation.

RULES FOR ACHIEVING ENCAPSULATION:

1.Declare all the data members as provide (if a data members is provide it is not accessible
outside of class)

2.Define separate setter and getter methods (it’s not mandatory to define only setter and
getter)

We can define any user define methods

SETTER METHOD:

It is public in nature
Setter method does not have specific return type.
Setter method contains arguments same as data member
Name of method is set followed by data members name.

GETTER METHOD:

It is public in nature
Return type must be same as that of data member
Name of method is get followed by data member name.
Getter method does not have arguments.

NOTE:

For every data member we have define separate setter & getter method

PROGRAM OF ENCAPSULATION:

package OOPS.Encapsulation;
class Gmail
{
private String uname;
private String pwd;
// setter and getter method
public void setUname(String uname)
{
this.uname = uname;
}
public String getUname()
{
//verification logic
if(uname=="qspkphb@gmail.com")
return "User Name is Verified";
else
return "User Not Found";
}
public void setPwd(String pwd)
{
this.pwd = pwd;
}
public String getPwd()
{
//verification logic
if(pwd=="kphb123")
return "Password Verified";
else
return "Invalid Password";
}
}
public class GmailUser
{
public static void main (String[] args)
{
Gmail g1 = new Gmail ();
g1.setUname ("qspresumes@gmail.com");
g1.setPwd("kphb100");
System.out.println (g1.getUname ());
System.out.println (g1.getPwd ());
}
}

EXAMPLES:

1. Protecting bank details from an invalid user to access is an example of encapsulation.


2. Keeping a password for mobile to protect data is an example of encapsulation
3. Protecting an online documents by keeping password is an example of encapsulation.
4. Securing home by keeping lock is an example of encapsulation.
EXAMPLE PROGRAM OF ENCAPSULATION
2.CREATE AN ENCAPUSLTED CLASS AS SCHOLARSHIP
2.1 DECLARE PRIVATE VARIABLES AS APPID(STRING), SSCNO(STRING)
2.2 CREATE SETTER FOR APPID & SSCNO
2.3 CREATE GETTER METHOD FOR VERIFYING APPID ACTUAL APPID IS
TS20224856
2.4 CREATE GETTER METHOD FOR VERIFYING SSCNO ACTUAL SSCNO IS
2022984563
2.5 CREATE USERSCHOLARSHIP CLASS
CREATE MAIN ( )
CALL TO SETTER & GETTER
package oops.Encapsulation;

class Scholarship
{
private String appid;
private String sscno;
public void setAppid(String appid)
{
this.appid = appid;
}
public String getAppid()
{
if(appid=="TS20224856")
return"Application is verified";
else
return "invalid Application id";
}
public void setsscno(String sscno)
{
this.sscno = sscno;
}
public String getsscno()
{
if(sscno=="202245553962")
return"ssc number is verified";
else
return "invalid ssc number";
}
}
public class UserScholarship
{
public static void main(String[] args)
{
Scholarship s1 = new Scholarship ();
s1.setAppid ("TS4567899");
s1.setsscno("2022456789");
System.out.println (s1.getAppid ());
System.out.println (s1.getsscno ());
}
}

METHOD BINDING:-
The process of connecting method call with the method body is called as Method
Binding
Method binding is divided into 2 types
1.COMPILE TIME BINDING
2.RUN TIME BINDING
1. COMPILE TIME BINDING:
During compilation, method will connecting to method body, is called as compile time
binding
Since the binding is happening at early stage it is also called as early binding.
All the static & final methods will be binded during compile time.
2. RUN TIME BINDING:
During execution, method call connecting with the method body is called as Run Time
Binding
Since the binding is happening at later stage it is called as late binding.
All the non-static & abstract methods will be binded during run time.
DIFFERENCE BETWEEN STATIC & FINAL
STATIC FINAL
1.Static is Keyword which represent 1.Final is Keyword which indicate no more
Single memory copy because it Loaded changes are allowed.
once in SPA
2.Static keyword is applicable for variables, 2.Final keyword is applicable with variables,
method, blocks & nested classes methods, classes.
3.We will go for static, if there is a single 3.We will go for final, if the value is constant
Value for particular situation every where.
Ex: College name, University Name Ex: 𝝅 = 3.14
4.Static variables can be re-initialize 4. Final variables can not be re-initialize

DIFFERENCE BETWEEN THIS, SUPER, SUPER ( ), THIS ( ), NEW


THIS SUPER THIS( ) SUPER( ) NEW

1. This keyword is 1. Super keyword is 1. Call to this is used 1.Call to super for the 1.New is a keyword
used to different used to call super class to call a constructor process of calling to load all non-
between actual member even after From another parent class static
variable & overriding happened. constructor within constructor by using member & create
argument variable. the same class. child class an object.
constructor.

2.We can use this 2.We can use super 2.Call to this must be 2.Call to super must 2.New keyword, we
keyword at any keyword at any the first statement of be the first statement can use any
statement inside a statement inside non- a constructor of a child class statement whatever
method & a static method of child constructor. we want to create
constructor class. an object.
3.Call to super ( ) is
3.This keyword is 3.Super keyword is 3.Call to this ( ) is implicit & explicit in 3.New keyword is
explicit in nature explicit in nature. explicit in nature. Nature. explicit in nature
ABSTRACTION:
The process of hiding internal details & showing necessary data to the end user, is
called as Abstraction.
(Or)
The process of showing what we are doing but not how we are doing is called as
Abstraction.
(Or)
The process of giving method header & method signature, but not giving method
implementation is called as Abstraction.
ABSTRACTION CAN BE ACHIEVED IN TWO WAYS

1.USING ABSTRACT CLASS

2.USING INTERFACE

EXAMPLE OF ABSTRACTION:

1.Sending an email where send button is visible but how the email is sending is not visible.

2.ATM application where in we enter the pin & choose the transcation. But, how the
transaction is happening is not visible.

3.Driver knows only to apply breaks & accelerate but how it is working is hidden.

4.Remote of TV & AC, where we can operate through button, but how it is being operated is
hidden.

ABSTRACT CLASS:

Abstract is a keyword which indiactes incompleteness.


Abstract class is a class which contains at least one abstract method.

Ex:

Abstract class Vechicle

Abstract public void noofwheels();

}
It is mandatory to mention abstract keyword for abstract class & abstract class.

NORMAL/CONCRETE/COMPLETE METHOD:-

If a method have method signature as well as method body method is called complete
or concrete method.

SYNTAX: METHOD HEADER METHOD SIGNATURE

// METHOD BODY / IMPLEMENTAT

Ex:

public void Run()

System.out.println("In RUN");

public void Fly()

System.out.println("FLY AWAY");

CONCRETE CLASS:-

A class with all the methods as concrete.

ABSTRACT/INCOMPLETE METHOD:-

If a method contains only method signature but not method implementation, is called
as Abstract/Incomplete method.

SYNTAX: METHOD HEADER METHOD SIGNATURE

Ex: public void Run ( )

public void Fly ( )


Abstract method has to be represented with abstract keyword & we have to add; in the
end of method declaration.

Ex: abstract public void Run ( );

abstract public void Fly ( );

If we didn’t add abstract keyword or semicolon, we will get compile time error
It is mandatory to mention the abstract keyword for abstract method & abstract class.

Ex:-1

abstract class furit

Abstract public void taste( );

Ex:-2

abstract class loans

abstract public void type( );

abstract public void rate of intertest( );

Q.CAN WE CREATE OBJECT OF ABSTRACT CLASS?

A.No, we can not create an object because it contains abstract methods & abstract methods
does not have any body to execute.

Ex:

Abstract class Vechicle

Abstract public void noofwheels();

public class A
{

Public static void main(Sting args[])

Vechicle V1 = new Vechicle(); // INSTANTIATION IS NOT POSSIBLE

V1. noofwheels(); // Since Vechicle is a abstract class, we can’t create object.

Q.CAN WE INHERIT ABSTRACT CLASS OR NOT?

A.Yes, we can. If any child classes are there for abstract class that child class has to udergo
with any of the one rule.

1.Complete all abstract incomplete method of abstract class by means of overriding.

2.Declare your class also as abstract class.

Abstract class can contains abstract method & concrete method (both).

Ex:

Abstract class A Abstract clas

public void Add( ) Concrete method

Abstract public void Add( ); Abstract method

PURPOSE OF ABSTRACT:-

1.To make simple information for end user to make user friendly (App should be simple in
nature)

2.To make the application secure.

Eg:
Suppose, one user send Hi ( in whatup app) to another that othter person get only ‘Hi’, not
the coding of Hi

So, it is user friendly

TIGHT COUPLING & LOOSE COUPING:-

TIGHT COUPLING:-

When one application is completely depends on another application for business


purpose is called Tight coupling.

LOOSE COUPLING:-

When one application is not completely depends on another application for business
purpose, is called Loose copling.

RBI

TIGHT COUPLUNG LOOSE COUPLING

HDFC

AXIS
ICICI
SBI

HDFC,AXIS...all are depends on RBI but RBI is not depends on HDFC.

STEPS SHOULD PERFORM FOR TIGHT & LOOSE COUPLING:-

1.Create an abstract class with abstract method.

2.Create implemenation class with requried method implemenations.

EXAMPLES:-

In this example we’ve created

a) Switch class (Abstract)


b) Light class (Concrete)
c) Fan class (Concrete)

Ex:

package practice;

abstract public class Switch


{
abstract void on();
abstract void off();
}
public class Fan extends Switch
{
public void on()
{
System.out.println();

}
public void off()
{
System.out.println();
}
}
public class light extends Switch
{
public void on()
{
System.out.println ("light on");
}
public void off()
{
System.out.println ("light off");
}
}
public class Executions
{
public static void main(String[] args)
{
light l1 = new light();
l1.on();
l1.off();
}
}
public class Execution
{
public static void main(String[] args)
{
Fan f1 = new Fan();
f1.on();
f1.off();
}
}

1. CREATE AN ABSTRACT CLASS AS CALCULATOR


2. CREATE ABSTRACT METHOD
Add(int i, int j)
Sub(int i, int j)
3. CREATE CHILD CLASS AS CALCIDEV SHOULD IMPLEMENT ALL ABSTRACT
METHODS.
4. CREATE MAIN ( ) IN USERCALCI & CREATE UPCASTED OBJECT TO ALL
METHODS.
package Abstract;
abstract public class Calculator
{
abstract public void add(int i,int j);
abstract public void sub(int i,int j);
}
class DevCalci extends Calculator
{
public void add(int i, int j)
{
System.out.println(i+j);
}
public void sub(int i, int j)
{
System.out.println(i-j);
}
}
public class UserCalci
{
public static void main(String[] args)
{
Calculator c1 = new DevCalci();
c1.add(100,200);
c1.sub(100,200);
}
}
1. CRETAE AN ABSTRACT CLASS AS CAR
2. CREATE ABSTRACT METHOD AS ENGINE( ), COMFORTS( ), DESIGN( )
3. CREATE CHILD CLASS AS AUDI & IMPLEMENT ENGINE( ) & COMFORT( )
4. CREATE ANOTHER CHILD FOR AUDI CLASS AS AUDI CLASS AS
AUDIDESIGNER & IMPLEMENT DESGIN( ).
5. CREATE USERLOGIC CLASS AS AUDICAR
CARETE MAIN ( ) & CREATE UPCASTED OBJECT
package Abstract;
abstract class Car
{
abstract public void engine();
abstract public void comforts();
abstract public void design();
}
abstract class Audi extends Car
{
public void engine() {
System.out.println("AUDI ENGINE");
}
public void comforts()
{
System.out.println("AUDI IS COMFORTABLE");
}
}
class AudiDesigner extends Audi
{
public void design()
{
System.out.println("AUDI IS DESIGNED");
}
}
public abstract class AudiCar
{
public static void main(String[] args)
{
Car c1 = new AudiDesigner();
c1.engine();
c1.comforts();
c1.design();
}
}

From the above program, we can observe that abstract class does not guarantees that it
contains only abstract methods, due to this reason we cannot achieve 100% abstraction
through abstract class in order to achieve 100% abstraction we will for interface.
Example:-1
package Abstraction;
abstract class RBI
{
abstract public void getdesposit();
abstract public void getwithdraw();
abstract public void getloans();
}
abstract class SBI extends RBI
{
public void getwithdraw()
{
System.out.println("MONEY IS WITHDRAW");
}
public void getdesposit()
{
System.out.println("MONEY IS DEPOSITED");
}
}
class SBILoans extends SBI
{
public void getloans()
{
System.out.println("LOANE IS DONE!");
}
}
public class Customers
{
public static void main(String args[])
{
RBI r = new SBILoans();
r.getloans();
r.getdesposit();
r.getwithdraw();
}
}

Example:-2
package Abstraction;
abstract class Car
{
abstract public void Accelerate();
abstract public void Brakes();
}
class Honda extends Car
{
public void Accelerate()
{
System.out.println("ACc TO DESIGN OF HONDA ARCHITECTURE");
}
public void Brakes()
{
System.out.println("ACC TO DESIGN OF HONDA ARCHITECTURE");
}
}
public class Showroom
{
public static void main(String args[])
{
Car c1 = new Honda();
c1.Accelerate();
c1.Brakes();
}
}

CAN WE DECLARE A CLASS AS ABSTRACT EVEN THROUGH IT DOES NOT


HAVE ANY ABSTRACT METHOD?
Yes! We can declare the class as abstract even through it does not have any abstract method,
in two different situation.
SITUATION:-1
If all the members of a class is static we need not to create any object.
In that situation, we can declare the class as abstract. Because, abstract class says
object creation is not possible. By doing this we can restricted the user from un-necessary
object creation
(we can save area of memory (Heap))
So, efficiency also
abstract class Sample
{
static int i = 100;
public static void Add()
{
System,out.println(i);
}
public static void main(String args[])
{
Add();
}
}
SITUATION:-2
We can access parent class members through child class object. So, therefore we can declare
parent class as abstract.
CAN WE HAVE CONSTRUCTOR IN ABSTRACT CLASS SINCE WE CAN NOT
CREATE AN OBJECT OF IT?
Yes, we can create a constructor in abstract class even though we cannot create an object of it
by using call to super i.e. through child class constructor, we can call to parent class
constructor.
abstract class A
{
A()
{
System.out.println("A-CLASS CONSTRUCTOR");
}
}
class B extends A
{
B()
{
System.out.println("B-CLASS CONSTRUCTOR");
}
}

public class User


{
public static void main(String[] args)
{
A a1 = new B();
}
}

INTERFACE:
DEFINITION: An interface is a type definition block (block of codes) whose type convention
is same as that of class.
interface Animals
{
void Eat();
void Makenoise();
void Color():
void Species();
}
An interface has to be represented with interface keyword.
SYNTAX:-
INTERFACE KEYWORD INTERFACE NAME

// BODY OF INTERFACE

}
By default all methods of interface are public and abstract, whether we write or don’t
write.
interface A interface A
{ {
void run(); public abstract void run();
public void fly(); public abstract void fly();
abstract public void cry(); public abstract void cry();
} }
By default all the variables of interface are public, static & final. Whether you write or
you don’t write it.
interface A
{
int i = 9; // public static final int i = 9;
static String s = "java"; // public static final String s = “java”;
final int k = 88; // public static final int k = 88;
public static final float fq = 99.9f;
}
Q.CAN WE INSTANTIATE AN INTERFACE?
(Or)
Q.CAN WE CREATE AN OBJECT OF INTERFACE?
No, we cannot create an object of interface because all methods are by default abstract, but we
can create a reference of interface.
IMPLEMENTS:-
Implements is the keyword, we will use if any class want to form a relationship with Interface.

INTERFACE CAR

VOID PRICE ( );
SYNTAX:-
}

CLASS AUDI IMPLEMENTS CAR

}
POSSIBLE RELATIONSHIP WITH KEYWORDS:
PARENT CHILD KEYWORD SYNTAX
CLASS CLASS EXTENDS CLASS B EXTENDS A
INTERFACE INTERFACE EXTENDS INTERFACE B EXTENDS A

INTERFACE INTERFACE IMPLEMENTS CLASS B IMPLEMENTS A

ABSTRACT CLASS EXTENDS CLASS B EXTENDS A

CLASS, CLASS CLASS NOT NOT POSSIBLE


POSSIBLE
INTERFACE,INTERFACE CLASS IMPLEMENTS CLASS C IMPLEMENTS A,B

INTERFACE,INTERFACE INTERFACE EXTENDS INTERFACE C EXTENDS A,B

EXAMPLE:-1
package practice;
interface Car
{
public void Engine();
public void Comforts();
}
class Audi implements Car
{
public void Engine()
{
System.out.println("AS PER AUDI STANDRAD");
}
public void Comforts()
{
System.out.println("AS PER AUDI DESIGN");
}
}
public class Showroom
{
public static void main(String args[])
{
Car c1 = new Audi();
c1.Engine();
c1.Comforts();
}
}

EXAMPLE:-2
package Aneesh;
interface Calculator
{
public abstract void Add();
public abstract void Sub();
public abstract void Div();
public abstract void Multi();
public abstract void Mod();
}
class Dev_calculator implements Calculator
{
static int i = 900, j = 600;
public void Add()
{
System.out.println(i+j);
}
public void Sub()
{
System.out.println(i-j);
}
public void Div()
{
System.out.println(i/j);
}
public void Multi()
{
System.out.println(i*j);
}
public void Mod()
{
System.out.println(i%j);
}
}
public class User
{
public static void main(String args[])
{
Calculator c1 = new Dev_calculator();
c1.Add();
c1.Sub();
c1.Div();
c1.Multi();
c1.Mod();
}
}
EXAMPLE:-3
package Sri;
interface Automoblie
{
public abstract void Engine();
public abstract void Accelerate();
public abstract void Brakes();
public abstract void Comfort();
public abstract void Design();
}
abstract class Honda implements Automoblie
{
public void Engine()
{
System.out.println("ENGINE CONDITION IS GOOD");
}
public void Accelerate()
{
System.out.println("SPEED CONTROL");
}
public void Brakes()
{
System.out.println("BREAKS WILL WORKS");
}
}
class Honda_Designer extends Honda
{
public void Comfort()
{
System.out.println("COMFORTS ARE GOOD");
}
public void Design()
{
System.out.println("INTER LINKED DESIGN");
}
}
public class CarApp
{
public static void main(String args[])
{
Automoblie a1 = new Honda_Designer();
a1.Engine();
a1.Accelerate();
a1.Brakes();
a1.Comfort();
a1.Design();
}
}
DIFFERENCE B/W ABSTRACT & INTERFACCE
ABSTRACT INTERFACCE
1. Abstract is class having abstract keyword 1.Interface is block of codes represents as
word & having at least one abstract interface keyword.
method.
2. In abstract class, we can have concrete as 2. In interface, all the methods are public &
well as abstract method. abstract.
3. In abstract class, we can have any type of 3.In interface, all the variables are public,
variables. static & final.
4.In abstract class, we can have constructor 4.In interface, we can not have constructor
which is executed through child class because all the variables are static
constructor.
5.We can achieve partial abstraction through 5.We can achieve 100% abstraction through
abstract class. interface.
6.We can not achieve multiple inheritance 6.We can achieve multiple inheritance
through abstract class. through interface.

ADVANCE ENHANCEMENT ALONG WITH INSIDE INTERFACE:-


From JDK 1.8, it starts…………
1. Complete static methods are allowed
public static void M1()
{

}
2. Default non-static methods are also allowed
default void M2()
{

}
Object class is super most class in java because it by default present
(In java. Language package)
public class A extends object()
{ By default it is parent

}
Constructor is responsible for inheritance.
One by default constructor always there.
Multiple inheritance not in java class.
DIAMOND AMBIGUITY PROBLEM:-

A,B are confuse that who will give properties to C Multiple inheritance not possible.
In Interface, no object class So no diamond shap problem

So, multiple inheritance possible


Compile Time Polymorphism Method Over Loading
Run Time Polymorphism Method Over Riding
4 class members Constructor, Methods, Variables, Blocks
class A
{
A() Constructor
{

}
public void M1() Methods
{

}
int x = 100; Variables
} Blocks
EXAMPLE:-1
package Sri;
interface A
{
void Car();

}
interface B
{
void CarAudi();
}
interface C extends A,B
{

}
class D implements A,B
{
public void Car()
{
System.out.println("CAR IS");
}
public void CarAudi()
{
System.out.println("AUDI IS");
}
}
class E extends D
{

}
public class User
{
public static void main(String args[])
{
D a1 = new E();
a1.Car();
a1.CarAudi();
}
}

EXAMPLE:-2
package Sri;
interface A
{
void Car();
}
abstract class B implements A
{
abstract public void CarAudi();
}
class C extends B implements A
{
public void Car()
{
System.out.println("CAR IS HIGH COST");
}
public void CarAudi()
{
System.out.println("AUDI NEW MODEL");
}
}
public class Sri
{
public static void main(String args[])
{
C a1 = new C();
a1.Car();
a1.CarAudi();
}
}

EXAMPLE:-3
package practice;
interface VENU
{
void Car();
}
interface BOBBY extends VENU
{
void CarAudi();
}
class RAM implements BOBBY,VENU
{
public void Car()
{
System.out.println("CAR IS WOKING");
}
public void CarAudi()
{
System.out.println("AUDI IS NEW MODELS");
}
}
public class Armili
{
public static void main(String args[])
{
BOBBY a1 = new RAM();
a1.Car();
a1.CarAudi();
}
}

MULITIPLE INHERITANCE THROUGH INTERFACE


package Sri;
interface RAM
{
void M1();
}
interface SRI
{
void M2();
}
interface VENKI extends RAM,SRI
{
}
class SRINU implements VENKI
{
public void M1()
{
System.out.println("M1 IS METHOD");
}
public void M2()
{
System.out.println("M2 IS METHOD");
}
}
public class Venu
{
public static void main(String args[])
{
VENKI a1 = new SRINU();
a1.M1();
a1.M2();
}
}

WHY MULITIPLE INHERITANCE POSSIBLE THROUGH INTERFACE?


Through interface there is no ambiguity problem even though both the parents have same
method because when class is going to implements those methods it will implements only once.
Because in one class we can not have multiple methods same & arguments. Because it leads to
duplicate method error.
package Sri;

interface RAM
{
void M1();
}
interface SRI
{
void M2();
}
interface VENKI extends RAM,SRI
{

}
class SRINU implements VENKI
{
public void M1()
{
System.out.println("M1 IS METHOD");
}
}
public class Srikar
{
public static void main(String args[])
{
VENKI a1 = new SRINU();
a1.M1();
}
}

In interface there is no possibility of constructor chaining problem. Because interface does not
allows constructor. When therefore ambiguity & constructor chaining it is possible to achieve
multiple inheritance.
PRACTISING PROGRAMS
CREATE A PROJECT AS “PRACTISINGSESSION”
CREATE A PACKAGE AS “MODULE_1”
P-1: CREATE A CLASS MULTIPLE LOGIC
TAKE AN INPUT FROM USER USING SCANEER CLASS
IF USER IS 1 EXECUTE SWAP OF TWO NUMBERS
2 EXECUTE FIBNOCCI SERIES
3 EXECUTE FACTORIAL
4 EXECUTE MULTIPLICATION TABLE OF 5
ANY OTHER IP PRINT AS NO LOGIC FOUND
HINT: USE SWITCH CASE STATEMENTS
package Module_1;
import java.util.*;
public class MultipleLogic
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number");
int n = sc.nextInt();
switch (n)
{
case 1 : System.out.println("BEFORE SWAPPING");
int a = 20,b = 10, c;
c=a;
a=b;
b=c;
System.out.println("The Valve Of a:"+a+"/nthe value of b:"+b);
break;
case 2: System.out.println("FIBNICCO SERIES");
int x = 0, y = 1,z;
System.out.println(x+"");
System.out.println(y+"");
for (int i=1;i<=5;i++)
{
z=x+y;
System.out.println(z+"");
x=y;
y=z;
}
break;
case 3: System.out.println("FACTROIAL");
int fact = 1;
for (int k=5;k>=1;k--)
{
fact = fact * k;
}
System.out.println("FACTROIAL OF 5:"+fact);
break;
case 4: System.out.println("MUTIPLATION TABLE");
for (int r=1;r<=10;r++)
{
System.out.println(5+"*"+r+"="+(5*r));
}
break;
default : System.out.println("NO LOGIC FOUND");
break;
}
}
}
OUTPUT:-1

OUTPUT:-2
OUTPUT:-3

OUTPUT:-4

P-2: CREATE A CLASS MULTIPLE LOGIC_2


CREATE FOLLOWING USER DEFINE METHODS
public static String is Prime(int num) Develop prime number logic
public void is Armstrong(int num) Develop armstrong logic
public String is Palindrome(int num) Develop palindrome logic
CREATE MAIN( ) & MAKE A CALL TO USERDEFINE METHODS.
package Module_2;
public class MultipleLogic_2
{
public static String prime(int n)
{
int count=0;
for(int i=1; i<=n; i++)
{ if(n%i==0)
{
count++;
}
}
if(count==2)
{
return (n+" IS A PRIME NUMBER");
}
else
return (n + " IS NOT A PRIME NUMBER");
}
public void Armstrong(int num)
{
int rem,arm=0,temp=num;
while(num>0)
{
rem=num%10;
num=num/10;
arm=arm+(rem*rem*rem);
}
if(arm==temp)
System.out.println(temp+" IS A ARMSTRONG NUMBER");
else
System.out.println(temp+" IS NOT A ARMSTRONG NUMBER");
}
public String palendromic(int num)
{

int rem,rev=0,temp=num;
while(num>0)
{
rem=num%10;
num=num/10;
rev=rev*10+rem;
}
if(temp==rev)
return (temp+ "IS A PALINDORME NUMBER");
else
return (temp+ " IS A NOT PALINDORME NUMBER ");
}
public static void main (String args[])
{
MultipleLogic_2 m1= new MultipleLogic_2();
System.out.println( m1.palendromic(121));
m1.Armstrong(153);
System.out.println(m1.prime(5));
}
}
MODULE:-4

OBJECT CLASS
STRING CLASS
ARRAY PROGRAMMING
EXCEPTION HANDLING
WRAPPER CLASSES
COLLECTION FRAME WORK
MAPS
MULTI THREADING

EXCEPTIONAL HANDLING:-

An exception is defined as an unexpected (or) abnormal statement of a program, due to


which program terminates abnormally.
(Or)
An exception is defined as logical mistake due to which immediately program
terminates.
If a program is terminating with main method, it is called as Normal Termination. But,
in case if it is terminating any where in between it is called Abnormal Termination.

REAL TIME EXAMPLE:-

Everything is going well but COVID-19 came then everything went abnormally….

Untill exception occurs, everything will be executing. Once exception occurred,


remaining part of a program will not be executed.
Ex:-
class A
{
Statement 1
Statement 2 Executed
Statement 3
Statement 4 Handle the Exception
Statement 5 Exception
(Program Terminates)

Abnormal
Statement 6
Statement 7 Un Executed
Statement 8
Statement 9
} Normal
For executing all i.e. for normal termination, we should correct the
exception (which is occurred for statement 5)
i.e. we handle the exception.
Once exception occurred, remaining program will not be executed untill we handle
that exception.
In practically, we can not resolve the exception but we can find an alternative solution
for that exception.
So, finding an alternate solution is called as Exception Handling.

In the above hierarchy, different class of exception is given, all these are pre-defined
classes, which are present in java.lang package
DIFFERENT STAGES OF EXCEPTION:-
THROWABLE:-
Throwable class is a parent class for Error & Exception class.
EXCEPTION:-
Exception is a parent class of RuntimeException & all the checked type of Exception.
RUN TIME EXCEPTION:-
Run time exception is a parent class for all the checked type of Exception.
TYPES OF EXCEPTION:
Based on hierarchy, exception are divided into two types
1. CHECKED EXCEPTION
2. UN-CHECKED EXCEPTION
CHECKED EXCEPTION :-
Exception which are checked(identified or found out) during compiletime by compiler,
such type of exception are called as Checked Exceptions.
Checked Exceptions are also called as Compile time Exception.
For all checked Exception parent class is “Exception”
EXAMPLES(CLASSES) OF CHECKED EXCEPTIONS ARE :-

InterruptedException
ClassNotFoundException
SQLException
FileNotFoundException

UN-CHECKED EXCEPTION :-

Exception which are checked (identified or found out) during Runtime or


execution time, such type of exception are called as Unchecked
Exceptions.
Incase of Unchecked Exception our program will atleast compiles
successfully.
Unchecked Exceptions are also called as Runtime Exceptions.
For all unchecked Exceptions parent class is “RunTimeException”
EXAMPLES (CLASSES) OF CHECKED EXCEPTIONS ARE :-

ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
StringIndexOutofBoundsException
ClassCastException
NumberFormatException
WHAT HAPPENS WHEN EXCEPTION OCCURS:-

Until exception occurs everything executed normally once exception occurred, an


exception object gets created.
Inside that object three things will be loaded name of an
1.EXCEPTION
2. DESCRIPTION
3. LOCATION
And that object will be hand over to JVM, now JVM looks for exception handling code.
(Try / Catch / Block).
In case JVM did not try / catch / block that exception object is hand over to default
exception handler.
Default exception handler is one of the predefined method of throwable class

SYNTAX:-
PUBLIC VOID PRINTSTACKTRACE ( )
Ex:

package Sravanthi;
public class Sample E Executed
{
public static void main(String args[])
{
int a = 10,b = 0,c;
c = a/b; Exception
System.out.println(c); UnExecuted
}
}

EXCEPTION CAN BE HANDLE BY USING TRY / CATCH BLOCK:-


TRY BLOCK:-
Try block is used to keep a risky code (A code which causes Exception)
TRY
SYNTAX
{

// RISKY CODE

}
One Exception occurred in try block JVM will go to corresponding catch block. Therefore we
should keep only risky code in try block & avoid writing normal code in try block.
CATCH BLOCK:-
Catch block is used to caught the Exception in another words catch block is used to keep an
alternate solution for the Exception.
In catch block we will also give reference for the exception object which is created in
try block.
SYNTAX:- CATCH ( EXCEPTIONNAME REFERENCE VARIABLE)

// ALTERNATE SOLUTION

PROGRAM ON EXCEPTION HANDLING:-


package Sri;
public class Sample
{
public static void main(String args[])
{
int a = 10,b = 0,c;
try
{
c = a/b;
}
catch(ArithmeticException e)
{
System.out.println("EXCEPTION CAUGHT");
}
}
}
Ex:-2
package Sri;
public class Sample
{
public static void main(String[] args)
{
System.out.println("MAIN START");
int a = 10,b = 0,c;
try
{
System.out.println("TRY START");
c = a/b;
System.out.println("TRY ENDS");
}
catch(ArithmeticException e)
{
System.out.println("CATCH BLOCK");
}
System.out.println("MAIN ENDS");
}
}

Q.IN CASE IF WE DON’T KNOW WHAT TYPE OF EXCEPTION IS OCCURING?


WHICH CLASS REFERENCE WE WILL GIVE IN CATCH BLOCK?
A. In that situation, we will give the reference of parent class i.e. exception class, because
parent class reference can handle any type of child object.
Example:-3
package Sri;
public class Sample
{
public static void main(String[] args)
{
int a = 10,b = 0,c;
try
{
c = a/b;
}
catch(Exception e)
{
System.out.println("EXCEPTION CATCH");
}
}
}

EXCEPTION E = NEW ARITHMETIC EXCEPTION ( );

PARENT CLASS E = NEW CHILD CLASS ( );


UP-CASTED OBJECT

Q.CAN WE WRITE SINGLE TRY WITH MUTIPLE CATCH BLOCK?


A. Yes, we can write single try with multiple catch block but the sequence must be specific
catch block first, general catch block next.
Specific catch block can handle only one type of exception. General catch block can
handle any type of exception.
SYNTAX:-
TRY

CATCH (ARITHMETICEXCEPTION D) Only specific type of except

}
Any type of Exception
CATCH (EXCEPTION D)

SINGLE TRY WITH MULTIPLE RISKY STATEMEMT:-

In is possible that one try block can have multiple exception statements. Whichever exception
occurred first only that exception will be handle. In case if we want, all the exceptions to be
taken care then we should must write separate try & catch block for every exception.

Example:-1

package Exception;
class A
{

}
class B extends A
{

}
public class C
{
public static void main(String[] args)
{
try
{
int a = 100/0;
B B1 = (B) new A ();
}
catch (ArithmeticException A)
{
System.out.println("Exception Caught / by ZERO");
}
catch (ClassCastException A)
{
System.out.println("ClassException Caught");
}
}
}

If we want both exception to be handle then we should write separate try & catch block
like

SINGLE PROGRAM WITH MUILTIPLE TRY CATCH BLOCK:-

package Exception;
class A
{

}
class B extends A
{
}

public class MultipleException


{
public static void main(String[] args)
{
try
{
int a = 100/0;
}
catch (ArithmeticException A)
{
System.out.println("Exception Caught of Arithmetic Exception");
}
try
{
B B1 = (B) new A ();
}
catch (ClassCastException A)
{
System.out.println("Catch for ClassCastException");
}
}
}

FINALLY BLOCK WILL BE EXCEUTED IRRESPECTIVE OF

1. Exception did not occurred


2. Exception occurred & did not handle

3. Exception occurred & handle

NOTES:

Finally block we can write only after try block or try catch block.
Finally block is used to keep the most important part of program which should be
executed for sure.
For example, if we are using data base & fetching some records & in between
exception occurs, in such situation if data base connection is not closed we will lose
entire records.
Therefore, closing of data base logic we can keep in finally block so that it should be
executed in every situation.

EXCEPTION DID NOT OCCURRED:-

package Exception;
class A
{

}
class B extends A
{

public class MultipleException


{
public static void main(String[] args)
{
try
{
int a = 10/10; No Exception occur. So, no need of catch block
}
catch (ArithmeticException A)
{
System.out.println("CATCH FOR ArithmeticException");
}
finally
{
System.out.println("FINALLY BLOCK");
}
}
}

EXCEPTION OCCURRED & DID NOT HANDLE:-


package Exception;
class A
{

}
class B extends A
{

}
public class MultipleException
{
public static void main(String[] args)
{
try
{
int a = 10/0; No Exception occurred.
} but no catch block So we did not handle
/*catch (ArithmeticException A)
{
System.out.println("CATCH FOR ArithmeticException");
}
*/
finally
{
System.out.println("FINALLY BLOCK");
}
}
}

EXCEPTION OCCURRED & HANDLE:-

package Exception;
class A
{

}
class B extends A
{

public class MultipleException


{
public static void main(String[] args)
{
try
{
int a = 10/0; Exception occurred
}
catch (ArithmeticException A) Exception Handled
{
System.out.println("CATCH FOR ArithmeticException");
}

finally
{
System.out.println("FINALLY BLOCK");
}
}
}

THROW KEYWORD:-

Throw keyword is used to create an exception object explicitly i.e. naturally exception
is not occurring but we want an exception to occur based on our choice.

SYNTAX:- THROW NEW EXCEPTIONNAME (DESCRIPTION);

Throw keyword is mainly used for operating a user defined exception


(If we want immediate termination from current working like in ATM We use
our wish able exception)

Intentionally, we want
To create an exception
Suppose as an example in ATM, ATM can give only 5000

Ex:-1
package Voting;
public class Throwvoting
{
public static void voting(int age)
{
if (age<=18)
throw new ArithmeticException("NOT ELIGIBLE TO VOTE");
else
System.out.println("eligible to vote");
}
public static void main(String[] args)
{
voting(15);
}
}

Ex:-2

package Voting;
public class Throwvoting
{
public static void voting(int age)
{
if (age<=18)
throw new ArithmeticException("NOT ELIGIBLE TO VOTE");
else
System.out.println("eligible to vote");
}
public static void main(String[] args)
{
voting(35);
}
}

THROWS KEYWORD:-

Throws keyword is used to transfer exception from one method to another method.
We will use throws keyword when current method cannot handle exception &
transferring the exception to the caller of that method.
So, now it is responsibility of a caller to handle the exception.
This process where exception is transferring from one method is called as Exception
propagation.
So, whenever exception, we have two choices
1. WRITE TRY CATCH BLOCK
2. USE THROWS KEYWORD

SYNTAX:- METHODHEADER METHODSIGNATURE THROWS EXCEPTIONSNAME

Ex:-1

public class Throwvoting


{
public static void voting(int age) throws ArithmeticException
{
if (age<18)
throw new ArithmeticException("NOT ELIGIBLE TO VOTE");
else
System.out.println("eligible to vote");

}
public static void main(String[] args)
{
try
{
voting(15);
}
catch(ArithmeticException e)
{
System.out.println("EXCEPTION CAUGHT");
}
}
}

EXAMPLE FOR PRE DEFINED EXCEPTION:-

NullPointerException

String s = null;

System.out.println (s.length());

ArrayIndexOutOfBondsException

int a [ ] = new int [ 3 ];

a [ 3 ] = 500;
StringIndexOutOfBoundsException

String s = “java”;

s.charAt(5);

ClassCastException

Child c = (Child) new Parent ( );

InterruptedException

Thread.sleep(5000);

OBJECT CLASS:-

It is a pre-defined class which is present in java.lang Package.


Object class is a default parent class to the user define as well as pre-define class of
java.

WHAT WE WRITE WHAT ACTUALLY IT IS

class A class A extends object

{ {

} }

MEMBERS OF OBJECT CLASS:-

getclass ( ) : class Final Collection Frame Work


object1.equals(object2) : Boolean String
toString ( ) : String Return Type
hashCode ( ) : int Return Type
notify ( ) : void Final
notifyAll ( ) : void Final
wait ( ) : void Final Multi-Threading
wait(Long timeout) : void Final
wait(Long timeout, int nanos) : void Final
finalise ( ) : void String Program
clone ( ) : void Advance Java

toString ( ) : String :-
It is a method of object class
It return complete information of an object

Packagenane.classname@object address

Example:- myPackage.Sample@ZZh33453

SYNTAX:- Public String toString ( )

// return packagename.classname@objectaddress;

Object address is unique hexadecimal representation of hashCode of an object.


It cannot be same for two objects.
Whenever we print reference variable, internally it calls to toSting ( ).

hashCode ( ) : int :-

It is a method of object class. It prints the hashCode number for given object.
HashCode number is 32 bit integer number
It is a unique number allocated to every object by JVM
If the object address are same, they will have same hashcode number or vice versa.

SYNTAX:-
public int hashCode ( )

// return hashCode of object ;

PROGRAM OF TOSTRING ( )

package OBJECTCLASSMETHODS;

public class A
{
public static void main(String[] args)
{
A a1 = new A();
String s = a1.toString();
System.out.println(s);
}
}

NOTE:-
Whenever we point reference variable, internally it will make a call to toString ( )
PROGRAM OF TOSTRING ( )

package OBJECTCLASSMETHODS;
public class A
{
public static void main(String[] args)
{
A a1 = new A();
String s1 = a1.toString();
A a2 = new A();
String s2 = a2.toString();
System.out.println(s1);
System.out.println(s2);
}
}

PROGRAM OF TOSTRING ( )
package OBJECTCLASSMETHODS;
public class A
{
public static void main(String[] args)
{
A a1 = new A();
//String s1 = a1.toString();
A a2 = new A();
//String s2 = a2.toString();
System.out.println(a1); // internally call a1.toString();
System.out.println(a2); // internally call a2.toString();
}
}

CONCLUSION:-
The output we are getting from toString ( ) there is no use of it in practical because if class
name changes or package changes, it will effect our output to overcome this we have an option
of overriding.
Ex:-1
package OBJECTCLASSMETHODS;
public class Student
{
String name; // Non – Static variables So, we use Constructor
Student(String name)
{
this.name = name;
}
public static void main(String[] args)
{
Student s1 = new Student ("TARUN");
String s = s1.toString();
System.out.println(s);
}
}

Ex:-2
package OBJECTCLASSMETHODS;
public class Student
{
String name;
Student(String name)
{
this.name = name;
}
//@overriding to toString()
public String toString() In background (i.e. in Parent class) toString( ) consists package..
{ So, now as child class toString( ) is override that
return name;
}
public static void main(String[] args)
{
Student s1 = new Student ("TARUN");
String s = s1.toString();
System.out.println(s);
}
}
-CREATE A CLASS AS PRODUCT
-DECLARE INSTANCE VARIABLES AS
Name, Color, Type
-INITIALISE THEM USING CONSTRUCTOR
-OVER RIDE TOSTRING ( ) & RETRUN Name, Color, Type
-CREATE MAIN ( ) & CALL TOSTRING ( )
package OBJECTCLASSMETHODS;
public class Product
{
String name,color,type;
public Product (String name,String color,String type)
{
this.name = name;
this.color = color;
this.type = type;
}
public String toString()
{
return name+" "+color+" "+type;
}

public static void main(String[] args)


{
Product p1 = new Product("ADIDAS","WHITE","SHOES");
String s = p1.toString();
System.out.println(s);
}
}
PROGRAM OF HASHCODE( ) Ex:-1

package OBJECTCLASSMETHODS;
public class A
{
public static void main(String[] args)
{
A a1 = new A();
int s1 = a1.hashCode();
A a2 = new A();
int s2 = a2.hashCode();
System.out.println(s1);
System.out.println(s2);
}
}

The output, we are getting from hashCode( ) there is no use of it in practical. To overcome
this, we have option of Overriding.
PROGRAM OF HASHCODE( ) Ex:-2
package OBJECTCLASSMETHODS;
public class Student
{
int sid;
Student(int sid)
{
this.sid = sid;
}
/*@overriding to hashCode()
public int hashCode()
{
return sid;
}
*/
public static void main(String[] args)
{
Student s1 = new Student (45632179);
int i = s1.hashCode();
System.out.println(i);
}
}

PROGRAM OF HASHCODE( ) Ex:-3


package OBJECTCLASSMETHODS;
public class Student
{
int sid;
Student(int sid)
{
this.sid = sid;
}
//@overriding to hashCode()
public int hashCode()
{
return sid;
}
public static void main(String[] args)
{
Student s1 = new Student (45632179);
int i = s1.hashCode();
System.out.println(i);
}
}

WHY WE GO FOR OBJECT CLASS?


class Object
{

EQUALS (
)
A,L, Po …..
Clone
String Str.B g – wc’s
}

Suppose, equal ( ) is present in String, String.Buffer, Wrapper, clone……. Every class.

So, instead of studying all classes….. we should study only object class because object class
contains 11 methods.

MULTI-THREADING:-

The process of executing more than one task parallely, is called “Multi-Tasking”.
The process of executing two different paths of a program parallely is called as
Thread Base Multi-Tasking.
As an example, let’s says we have 500 lines of code to execute, that JVM is taking 10
hrs of time. But, what we observe is if 250 & next 250 lines of code are independent
on each other but then also next 250 lines will not be executed until 𝟏𝒔𝒕 250 lines
completes it’s execution. Due to this execution time is more, efficiency is less.
Therefore to overcome that we can use Thread Base Multi-Tasking.
For the above situation we can create a thread for first 250 lines & another thread for
next 250 lines. And run both the threads parallely with this we can reduce the
execution time & increase the efficiency.

EXAMPLE:

If any user want to send a message to the 10 people then he will send that message by creating
a group within 20 sec.

THREAD:-

Thread is defined as a light weight process (or) A thread is a small part of our program.

Creating multiple thread & executing them parallely is called Multi-Threading.


The main purpose of multi-threading is reducing the execution time & increasing the
efficiency.
A thread can be created in two ways
1. BY EXTENDING THREAD CLASS
2. BY IMPLEMENTING RUNNABLE INTERFACE.

PROCEDURE TO CREATE A THREAD BY EXTENDING THREAD CLASS:-

1. Create a class

2. Extend thread class

3. Note:- Thread is a pre-define class belongs to java.lang package

4. Override public void run ( ) of thread class

5. develop some code in run ( )

6. run ( ) is actually a our thread

7. Start a thread by calling start ( ) of thread class

PROCEDURE TO CREATE A THREAD BY IMPLEMENTING RUNNABLE


INTERFACE:-

1. Create a class
2. Implementing thread class
3. Note:-Runnable is pre-define interface belongs to java.lang package.
4. Override public void run ( ) of runnable interface.
5. Develop some code in run ( )
6. Run ( ) is actually our thread
7. Create object of thread class
8. Start a thread by calling start ( ) of thread class

EXAMPLE:-1

package practice;
class Sample extends Thread
java.lang package

public void run ( )


public synchronized void start ( )
{
public void run()
{ Creating Thread
for(int i=1;i<=5;i++)
{ Jobs of the Thread (Logic)
System.out.println("SAMPLE THREAD");
}
} Creating Thread
}
public class UserLogic
{
public static void main(String[] args)
{
Sample s1 = new Sample();
s1.start(); Create a thread by calling run ( )
for(int i=1;i<=5;i++)
{
System.out.println("USER LOGIC THREAD");
}
}
}

OUT PUT:-1

OUT PUT:-2

OUT PUT:-3

Thread is a pre-define class (Here it is parent class), present in java.lang package


which has two methods.
1. PUBLIC VOID RUN ( )
2. PUBLIC SYNCHRONISED VOID START ( )
Mythread is a child class here, want is-a-relationship with thread class.
In this program, untill start ( ) invokes there is only main ( ) method under execution.
Once start ( ) method invoke, it internally creates a thread by calling run ( ).
Now, we have two thread main ( )
run ( )
Both the thread execute parallely. Here, when 2 different parts are executing parallely.
We can not predict which one will execute first / last
The decision is taken by thread scheduler. Suppose, time taken for execution of
Thread 1 + Thread 2 (parallely)

GIVING PRIORITY TO THREAD:-

package practice;
class Sample extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("SAMPLE THREAD");
}
}
}
public class UserLogic
{
public static void main(String[] args) throws InterruptedException
{
Sample s1 = new Sample();
s1.start(); // Create a thread by calling to run & make it ready for execution.
Thread.sleep(2000); // Current thread (Main()) goes to sleeping state for 2 sec
for(int i=1;i<=5;i++)
{
System.out.println("USER LOGIC THREAD");
}
}
}
REAL TIME EXAMPLE:-

When we click chrome browser……it will take about 2 sec to open ( Depends on Internet
Speed )

Actually here JVM will do Thread.sleep(2000);

CREATING THREAD BY IMPLEMENTING RUNNABLE INTERFACE:-

package practice;
class Sample implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("SAMPLE THREAD");
}
}
}
public class UserLogic
{
public static void main(String[] args) throws InterruptedException
{
Sample s1 = new Sample();
Thread t1 = new Thread(s1);
t1.start();
for(int i=1;i<=5;i++)
{
System.out.println("USER LOGIC THREAD");
}
}
}
ACCESS SPECIFIERS:-

It provides access permission to various fields like class, method, variables,


constructors & interface.
We have Four access specifiers
1. Public
2. Private
3. Protected
4. Default (No Modifier)

PUBLIC: public fields are accessible

Within the class


Within subclass of same package
Within other class of same package
Within subclass of another package but after writing import statement
Within nonsubclass of another package but after writing import statement

PRIVATE: private fields are accessible only within the class

It is applicable for method, variables & constructor only.


Private members are accessible within the class
They are not accessible outside of the class
Private is only applicable for method, variables & constructor
Private is not applicable for class, why because class loader will loads all the static
members of class, of we keep as private class loader can’t load

PROTECTED:- protected fields are accessible

Within the class


Within subclass of same package
Within other class of same package
Within subclass of another package but after writing import statement
It is applicable with method, variables & constructors

DEFAULT: if we did not mention public, private, protected the access modifier is default
Within the class
Within subclass of same package
Within other class of same package

PUBLIC:

WITHIN THE SAME CLASS

package abc;
public class Sample
{
public static int i = 100;
public static void main(String[] args)
{
System.out.println(i);
}
}

WITHIN SUBCLASS OF SAME PACKAGE

package abc;
public class Sample1 extends Sample
{
public static void main(String[] args)
{
System.out.println(i);
}
}
WITHIN NON SUBCLASS OF SAME PACKAGE
package abc;
public class Sample2
{
public static void main(String[] args)
{
System.out.println(Sample.i);
}
}

WITHIN SUBCLASS OF ANOTHER PACKAGE

package def;
import abc.Sample;
public class Demo extends Sample
{
public static void main(String[] args)
{
System.out.println(i);
}
}

WITHIN NONCLASS OF ANOTHER PACKAGE

package def;
import abc.Sample;
public class Demo1
{
public static void main(String[] args)
{
System.out.println(Sample.i);
}
}

PRIVATE:
package abc;
public class Sample
{
private static int i = 100;
public static void main(String[] args)
{
System.out.println(i);
}
}

PROTECTED:-
WITHIN THE SAME CLASS

package abc;
public class Sample
{
protected static int i = 100;
public static void main(String[] args)
{
System.out.println(i);
}
}

WITHIN SUBCLASS OF SAME PACKAGE

package abc;
public class Sample1 extends Sample
{
public static void main(String[] args)
{
System.out.println(i);
}
}

WITHIN NON SUBCLASS OF SAME PACKAGE

package abc;
public class Sample2
{
public static void main(String[] args)
{
System.out.println(Sample.i);
}
}

WITHIN SUBCLASS OF ANOTHER PACKAGE

package def;
import abc.Sample;
public class Demo extends Sample
{
public static void main(String[] args)
{
System.out.println(i);
}
}

WITHIN NON SUBCLASS OF DIFFERENT PACKAGE NOT ACCESSIBLE


DEFAULT:

WITHIN THE SAME CLASS

package abc;
public class Sample
{
static int i = 100;
public static void main(String[] args)
{
System.out.println(i);
}
}

WITHIN SUBCLASS OF SAME PACKAGE

package abc;
public class Sample1 extends Sample
{
public static void main(String[] args)
{
System.out.println(i);
}
}

WITHIN NON SUBCLASS OF SAME PACKAGE

package abc;
public class Sample2
{
public static void main(String[] args)
{
System.out.println(Sample.i);
}
}
WITHIN SUBCLASS OF ANOTHER PACKAGE NOT ACCESSIBLE
WITHIN NON SUBCLASS OF DIFFERENT PACKAGE NOT ACCESSIBLE
WITH SAME PACKAGE IN DIFFERENT PACKAGE

Withinclass Subclass NonSubclass Subclass NonSubclass

Public Yes Yes Yes Yes Yes

Private Yes No No No No

Protected Yes Yes Yes Yes Yes

Default Yes Yes Yes No No

ARRAY PROGRAMMING:-

An array is defined as an object which stores group of homogenous value in


continuous manner.
(Or)
An array is defined as collection of of homogenous values.
Every value in array object will have an index position starting from 0 (0,1,2,3,4….)
An array represented with [ ] square bracket.
Every array object is of finite size.
When creating an array object, we should compulsory give the size.
Size should must be numeric value.
We can stores the value only upto given size if we crosses the size of an array, we will
get ArrayIndexOutofBandException.

LENGTH VARIABLE:-

Length is a variable which returns number of values started in an array (Size of an array).

USING ARRAY:-

For using array we need to follows three steps

1. ARRAY CREATION
2. ARRAY INITIALISATION
3. ARRAY UTILIZATION
ARRAY CREATION:-
SYNTAX:- SIZE = SIZE OF AN ARRAY

ARRAY TYPE ARRAY NAME [ ] = NEW ARRAY TYPE [SIZE];

(Or)

ARRAY TYPE [ ] ARRAY NAME = NEW ARRAY TYPE [SIZE OF ARRAY];

ARRAY INITIALISATION:-
SYNTAX:- ARRAY NAME [INDEX] = VALUE;

ARRAY UTILIZATION:-
SYNTAX:- System.out.println (Array name[index]);

NOTE: We can declare & initialize our array in single statement also
SYNTAX:- ARRAY TYPE ARRAY NAME = {VALUE-1, VALUE-2, VALUE-3….VALUE-N}
EXAMPLE:-1
package practice;
public class Array
{
public static void main(String[] args)
{
int a [] = new int [5];
a[0]= 100;
a[1]= 200;
a[2]= 300;
a[3]= 500;
a[4]= 600;
System.out.println(a[0]+" "+a[1]+" "+a[2]+" "+a[3]+" "+a[4]);
}
}

/*WAP TO CERATE A STRING ARRAY OF SIZE 7 & PRINT ALL THE ARRAY VALUES*/

package practice;
public class Array1
{
public static void main(String[] args)
{
String s [] = new String [7];
s[0]= "JAVA";
s[1]= "SQL";
s[2]= "MANUAL";
s[3]= "J2EE";
s[4]= "PYTHON";
s[5]= "AUTOMATION";
s[6]= "DEVOPS";
System.out.println(s[0]);
System.out.println(s[1]);
System.out.println(s[2]);
System.out.println(s[3]);
System.out.println(s[4]);
System.out.println(s[5]);
System.out.println(s[6]);
}
}
/* WAP TO CERATE 2 ARRAY STRING & FLOAT OF SIZE 5. IN STRING ARRAYS
ADD STUDENT NAME IN FLOAT ARRAY ADD THEIR PERCENTAGE & PRINT
THEM TOGETHER (SIDE BY SIDE) */

Ex: STUDENT NAME PERCENTAGE

package practice;
public class Array2
{
public static void main(String[] args)
{
String a [] = new String [5];
a[0]="Sri";
a[1]="Venu";
a[2]="Ram";
a[3]="Aneesh";
a[4]="Shyam";
float f [] = new float [5];
f[0] = 98.8f;
f[1] = 89.9f;
f[2] = 78.9f;
f[3] = 67.9f;
f[4] = 59.1f;
System.out.println(a[0]+"-"+f[0]+"%");
System.out.println(a[1]+"-"+f[1]+"%");
System.out.println(a[2]+"-"+f[2]+"%");
System.out.println(a[3]+"-"+f[3]+"%");
System.out.println(a[4]+"-"+f[4]+"%");
}
}
/*WAP BY TASKING CHARACTER ARRAY, STORE VOWEL IN THAT ARRAY &
PRINT THEM USING FOR LOOP*/
package practice;
public class Array3
{
public static void main(String[] args)
{
char Ch[] = new char[5];
Ch[0] = 'A';
Ch[1] = 'E';
Ch[2] = 'I';
Ch[3] = 'O';
Ch[4] = 'U';
for(int i=0;i<5;i++)
{
System.out.println(Ch[i]);
}
}
}

/* WAP TO CREATE AN INTERGER ARRAY & PRINT THEM USING FOR LOOP*/

package practice;
public class Array4
{
public static void main(String[] args)
{
int a [] = {11,33,55,67,98,76};
for (int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}

/* WAP TO REVERSE AN INTEGER ARRAY */


package practice;
public class Array5
{
public static void main(String[] args)
{
int a [ ] = {11,22,33,44,55,66};
int l = a.length-1;
for (int i=l;i>=0;i--)
{
System.out.println(a[i]);
}
}
}
/* WAP TO READ THE ARRAY VALUE FROM SCANNER CLASS & PRINT IT */
package practice;
import java.util.*;
public class Arrray6
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter Array Size");
int size = s.nextInt(); // 5
int a [] = new int [size]; // a[0] = 100 Create Array
for(int i=0;i<size;i++) // a[1] = 200
{ // a[2] = 300
a [i] = s.nextInt(); // a[3] = 400
} // a[4] = 500
System.out.println("Array Value are:");
for (int j=0;j<size;j++)
{
System.out.println(a[j]); Printing
}
s.close(); To Close Scanner Class
}
}
/* WAP TO PRINT
A. ONLY EVEN NUMBERS FROM THE ARRAY
B. ONLY ODD NUMBERS FROM AN ARRAY
BY READING THE ARRAY VALUE THROUGH SCANNER CLASS */
ONLY EVEN NUMBERS FROM THE ARRAY
package practice;
import java.util.*;
public class Array7
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter Array Size");
int size = s.nextInt();
int a [] = new int [size];
for(int i=0;i<size;i++)
{
a [i] = s.nextInt();
}
System.out.println("Array Value are:");
for (int j=0;j<size;j++)
{
if (a[j]%2==0)
System.out.println(a[j]);
}
s.close();
}
}
ONLY ODD NUMBERS FROM AN ARRAY
package practice;
import java.util.*;
public class Array7
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter Array Size");
int size = s.nextInt();
int a [] = new int [size];
for(int i=0;i<size;i++)
{
a [i] = s.nextInt();
}
System.out.println("Array Value are:");
for (int j=0;j<size;j++)
{
if (a[j]%2!=0)
System.out.println(a[j]);
}
s.close();
}
}
/* WAP TO PRINT
A. EVEN INDEX POSITION VALUE
B. ODD INDEX POSTION VALUE */
EVEN INDEX POSITION VALUE
package practice;
import java.util.*;
public class Array8
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter Array Size");
int size = s.nextInt();
int a [] = new int [size];
for(int i=0;i<size;i++)
{
a [i] = s.nextInt();
}
System.out.println("Array Value are:");
for (int j=0;j<size;j++)
{
if (j%2==0)
System.out.println(a[j]);
}
s.close();
}
}
ODD INDEX POSTION VALUE
package practice;
import java.util.*;
public class Array8
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter Array Size");
int size = s.nextInt();
int a [] = new int [size];
for(int i=0;i<size;i++)
{
a [i] = s.nextInt();
}
System.out.println("Array Value are:");
for (int j=0;j<size;j++)
{
if (j%2!=0)
System.out.println(a[j]);
}
s.close();
}
}
/* WAP TO PRINT SUM & AVERAGE OF AN ARRAY BY READING THE ARRAY
VALUES THROUGH THE SCANNER CLASS */
package practice;
import java.util.*;
public class Array9
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter Array Size");
int size = s.nextInt(),sum=0;
int a [] = new int [size];
for(int i=0;i<size;i++)
{
a [i] = s.nextInt();
}
System.out.println("Array Value are:");
for (int j=0;j<size;j++)
{
sum = sum + a[j];
}
double avg = sum/size;
System.out.println(sum+" "+avg);
s.close();
}
}
/* WAP TO PRINT AVERAGE OF EVEN NUMBERS & ODD NUMBERS FROM THE
GIVEN ARRAY */
package practice;
import java.util.*;
public class Array10
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter Array Size");
int size = s.nextInt(),sumE=0,sumO=0,countE=0,countO=0;
int a [] = new int [size];
for(int i=0;i<size;i++)
{
a [i] = s.nextInt();
}
System.out.println("Array Value are:");
for (int j=0;j<size;j++)
{
if (a[j]%2==0)
{
sumE = sumE+a[j];
countE++;
}
else
{
sumO = sumO+a[j];
countO++;
}
}
double avgE = sumE/countE;
double avgO = sumO/countO;
System.out.println(sumE+" "+avgE);
System.out.println(sumO+" "+avgO);
s.close();
}
}

/* WAP TO PRINT MAXIMUM NUMBER FROM AN ARRAY


HINT : ASSUME FIRST NUMBER AS MAXIMUM
MAX = A [ 0 ]
COMPARE THAT WITH NEXT NUMBER IF YOU FIND ANY NEXT NUMBER
GREATEST THAN ASSUMED NUMBER ASSIGN IT */
IP {12,33,45,1,78,20}
OP 78
package practice;
public class Maximum
{
public static void main(String[] args)
{
int a [] = {12,33,45,1,78,20};
int max = a [0];
for(int i=0;i<a.length;i++)
{
if(a[i]>max)
max = a[i];
}
System.out.println("Maximum is: "+max);
}
}

/* WAP TO PRINT MINIMUM NUMBER FROM AN ARRAY


HINT : ASSUME FIRST NUMBER AS MINIMUM
MIN = A [ 0 ]
COMPARE THAT WITH NEXT NUMBER IF YOU FIND ANY NEXT NUMBER
GREATEST THAN ASSUMED NUMBER ASSIGN IT */
IP {12,33,45,1,78,20}
OP 1
package practice;
public class Minimum
{
public static void main(String[] args)
{
int a [] = {12,33,45,1,78,20};
int min = a [0];
for(int i=0;i<a.length;i++)
{
if(a[i]<min)
min = a[i];
}
System.out.println("Minimum is: "+min);
}
}
/* WAP TO PRINT MINIMUM & MAXIMUM NUMBER FROM GIVEN ARRAY */
package practice;
public class Array11
{
public static void main(String[] args)
{
int a [] = {12,35,45,1,76,20};
int max = a [0],min = a [0];
for(int i=0;i<a.length;i++)
{
if(a[i]>max)
max = a[i];

else if(a[i]<min)
min = a[i];
}
System.out.println("Maximum is: "+max);
System.out.println("Minimum is: "+min);
}
}

/* WAP TO PRINT
A. MAXIMUM & SECOND MAX FROM AN ARRAY
B. MINIMUM & SECOND MIN FROM AN ARRAY */
I/P {12,33,45,1,76,20}
MAXIMUM & SECOND MAX FROM AN ARRAY
package practice;
public class SecondMaximum
{
public static void main(String[] args)
{
int a [] = {10,21,30,45,4,25};
int max = a [0],smax = a [1];
for(int i=1;i<a.length;i++)
{
if(a[i]>max)
{
smax = max;
max = a[i];
}

else if(a[i]>smax)
{
smax = a[i];
}
}
System.out.println("Maximum is: "+max);
System.out.println("Second Maximum is: "+smax);
}
}

MINIMUM & SECOND MIN FROM AN ARRAY


package practice;
public class Array15
{
public static void main(String[] args)
{
int a [ ] = {12,85,36,1,10,3};
int min = a[0],smin = a[1];
for(int i=1;i<a.length;i++)
{
if(a[i]<min)
{
smin = min;
min = a[i];
}

else if(a[i]<smin)
{
smin= a[i];
}
}
System.out.println("Minimum is: "+min);
System.out.println("Second Minimum is: "+smin);
}
}

/*WAP TO SORT THE ARRAY IN


A. INCREASING ORDER
B. DECREASING ORDER */
INCREASING ORDER
package practice;
public class SortIncreasing
{
public static void main(String[] args)
{
int a[]={10,25,35,12,14,97};
int temp;
for (int i=0;i<a.length;i++)
{
for (int j=0;j<a.length-1;j++)
{
if (a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1]= temp;
}
}
}
for (int k=0;k<a.length;k++)
{
System.out.println(a[k]);
}
}
}

DECREASING ORDER
package practice;
public class ScortDecreasing
{
public static void main(String[] args)
{
int a[]={10,25,35,12,14,97};
int temp;
for (int i=0;i<a.length;i++)
{
for (int j=0;j<a.length-1;j++)
{
if (a[j]<a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1]= temp;
}
}
}
for (int k=0;k<a.length;k++)
{
System.out.println(a[k]);
}
}

}
/* WAP TO PRINT MAXIMUM, SECOND MAXIMUM, MINIMUM, SECOND
MINIMUM FROM AN SORTED ARRAY */
package array;
public class Array11
{
public static void main(String[] args)
{
int a[]={10,25,35,12,14,97};
int temp;
for (int i=0;i<a.length;i++)
{
for (int j=0;j<a.length-1;j++)
{
if (a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1]= temp;
}
}
}
for (int k=0;k<a.length;k++)
{
System.out.println("MAXIMUM: "+a[a.length-1]);
System.out.println("SECOND MAXIMUM :"+a[a.length-2]);
System.out.println("MINIMUM :"+a[0]);
System.out.println("SECOND MINIMUM :"+a[1]);
}
}
}
/* WAP TO DELETE DUPLICATE NUMBER FROM AN ARRAY */
package practice;
public class DeleteDuplicate
{
public static void main(String[] args)
{
int a [ ] = {2,3,4,2,3,1,1,5,6,5};
int temp;
for (int i=0;i<a.length;i++)
{
for (int j=0;j<a.length-1;j++)
{
if (a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
int b [ ] = new int[a.length];
int k = 0;
for (int i=0;i<a.length-1;i++)
{
if(a[i]!=a[i+1])
{
b[k] = a[i];
k++;
}
}
b[k] = a[a.length-1];
for (int j=0;j<=k;j++)
{
System.out.println(b[j]);
}
}
}

/* WAP TO PRINT PRIME NUMBER FROM AN ARRAY */


package practice;
public class PrimeArray
{
public static void isprime(int arr[])
{
for(int i=0;i<arr.length;i++)
{
int count=0;
for (int j=1;j<=arr[i];j++)
{
if (arr[i]%j==0)
count++;
}
if(count==2)
System.out.println(arr[i]+" IS A PRIME ");
}
}
public static void main(String[] args)
{
int a [ ] = {10,13,17,12,24,27};
isprime(a);
int b[ ] = {15,65,95,127,225,43};
isprime(b);
int c[ ] = {9,129,1001,2225,30};
isprime(c);
}
}

/* WAP TO PRINT PALINDROME NUMBER FROM THE ARRAY USING USER


DEFINE METHOD */
package practice;
public class PalindromeArray
{
public static void main (String[] args)
{
int a [] = {10,111,121,125,55};
ispalindrome(a);
int b [] = {243432,1221,1664,5353};
ispalindrome(b);
}
public static void ispalindrome(int a[])
{
for(int i=0;i<a.length;i++)
{
int rev=0,rem,temp=a[i];
while(temp>0)
{
rem = temp%10;
temp = temp/10;
rev = rev*10+rem;
}
if(rev==a[i])
System.out.println(" IS A PALINDROME NUMBER : "+a[i]);
}
}
}

COMMAND LINE ARGUMENTS:-


Main method is containing one special type of arguments which is called as command line
arguments i.e. during execution through command prompt we can enter sum inputs & those
inputs will be stored in string type of array with the array name args
Example:-1
public class CommandLineArgs
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
{
System.out.println(args[i])
}
}
}

PASSING COMMAND LINE ARGUMENTS IN ECLIPSE:-


After completing logic click on run drop down select run configuration. Click on argument &
provide values under program arguments, click on apply then click on run.
Example:-1
package array;
public class ArrayCLA
{
public static void main(String[] args)
{
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}

Example:-2
package array;
public class ArraySum
{
public static void main(String[ ] args)
{
int sum=0;
for(int i=0;i<args.length;i++)
{
int num = Integer.parseInt(args[i]);
sum = sum + num;
}
System.out.println(sum);
}
}

NOTE:-
Whatever argument we enter command prompt will be stored in string format if we want to
convert string value to integer we have pre-define method as Integer.paserInt
STRING PROGRAMMING:-
String is the pre-defined class which is present in java.lang.package
String class contains multiple pre-defined methods which is used to Manipulate /
Modify string data.
We use those method, we have to create an object of string class
String class object can be created in two ways
1.USING NEW KEYEORD
Ex:- String s = new String (“Java”);
2.WITHOUT USING NEW KEYWORD
Ex:- String s = “Java”
SOME OF THE IMPORTANT METHOD OF STRING CLASS
Method : returntype ----- Definition
1.length ( ) : int – it return length of a string (no of character)
2.charAt(int index) : char – it return character at given index.
3.equals(String) : Boolean – it return true if string content matches
4.equalsIgnoreCase(String) : Boolean – it returns true string contents matches without
Considering case sensitivity
5.trim( ) : String – it returns string after removing white spaces.
6.subString(int startindex):String – it return subpart of a string
7.subString(int startindex,int endindex) : String – it returns subpart of a string from start
From start index till end index-1.
8.toUpperCase( ) : String – convert string to upper case
9.toLowerCase( ) : String – convert string lower case
10.indexOf(String) : int – it returns index of given string
11.indexOf(Char) : int – it retuns index of given character
12.indexOf(String,int from index) : int – it returns index of given string but search it from
given index.
13.indexOf(Char,int fromindex) : int – it returns index of given char but search it from
given index.
14.concat(String) : String – it adds string at the end.
15.contains(String) : boolean – it check whether string is present or not.
16.split(args) : Sting [ ] – it breaks the String & convert to array.
17.replace(char, char) : String – it replace given char with desire character.
18.toCharArray( ) : char [ ] – it breaks String & converts it into array character by
character.
DIFFERENCE B/W LENGTH VARIABLE & LENGTH METHOD
LENGTH VARIABLE LENGTH METHOD
1.Length is pre-defined variable, which 1.Length( ) is pre-defined method, which is
is used to find out length of array object used to find out length of a string
Ex: Ex: int = s.length ( );
public int length( )
{
return length of String; 4
} SOP(Length);

2.charAt(int index):-
public char charAt(int index)
{

return char;
}

Char ch = s.charAt(0);
Char ch = s.charAt(1);
Char ch = s.charAt(2);
Char ch = s.charAt(3);
Char ch = s.charAt(4);

StringIndexOutOfBoundException
/* WAP TO READ THE STRING VALUE FROM THE USER & PRINT ALL THE
CHARACTER USING FOR LOOP */ (length( ) + char (int index)
package program;
import java.util.Scanner;
public class String
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("ENTER STRING VALUE: ");
String ip = sc.next(); // String class object creation (using i/p from user)
for(int i=0;i<ip.length();i++)
{ Take length of String i.e. 13
char ch=ip.charAt(i);
System.out.println(ch+" ");
}
}
}

/* WAP TO READ YOUR NAME THROUGH SCANNER CLASS & PRINT ONLY
VOWELS FROM IT */
package program;
import java.util.Scanner;
public class String2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("ENTER STRING VALUE: ");
String ip = sc.next();
for(int i=0;i<ip.length();i++)
{
char ch=ip.charAt(i);
if (ch=='A'||ch=='E'||ch=='O'||ch=='U'||ch=='I')
System.out.println(ch+" ");
}
sc.close();
}
}

/* WAP TO PRINT COUNT OF VOWELS & COUNT OF CONSONANT FROM THE


GIVEN STRING TAKE THE STRING VALUE FROM USER */
package Program;
import java.util.Scanner;
public class String3
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("ENTER STRING VALUE: ");
String ip = sc.next();int countV= 0,countC=0;
for(int i=0;i<ip.length();i++)
{
char ch=ip.charAt(i);
if (ch=='A'||ch=='E'||ch=='O'||ch=='U'||ch=='I')
countv++;
else
countc++;
}
System.out.println(countV+" "+countC);
sc.close();
}
}

/* WAP TO PRINT REVERSE OF A STRING */


package Program;
public class Reverse
{
public static void main(String[] args)
{
String s = "Java Developer";
String rev="";
for(int i=s.length()-1;i>=0;i--)
{
char ch = s.charAt(i);
rev = rev+ch;
}
System.out.println("Reverse"+" of String is : "+rev);
}
}
/* WAP WHETHER THE STRING IS PALINDROME OR NOT */
package Program;
public class Palindrome
{
public static void main(String[] args)
{
String s = "mam";
String rev="";
for(int i=s.length()-1;i>=0;i--)
{
char ch = s.charAt(i);
rev = rev+ch;
}
if (rev.equals(s))
System.out.println(s+" is a palindrome");
else
System.out.println(s+" is not a palindrome");
}
}

Example:-2
package Program;
public class Palindomes
{
public static void main(String[] args)
{
String s = "Mom";
String rev="";
for(int i=s.length()-1;i>=0;i--)
{
char ch = s.charAt(i);
rev = rev+ch;
}
if (rev.equalsIgnoreCase(s))
System.out.println(s+" is a palindrome");
else
System.out.println(s+" is not a palindrome");
}
}

In String == not working properly. So, we should use equal(s) methods.

It return true of string


content matches
like “mom” (i/p) “mom” (it will work)
But if input is Mom in reverse it will not work similar

So, we should use equalIgnoreCase(String) method

It returns true if string content matches w/o considering case sensitivity


Line I/p = Mom
O/p = Mom is palindrome
/* WAP TO COUNT NUMBER OF WORDS PRESENT IN A STRING */
package Program;
public class CoutWord
{
public static void main(String[] args)
{
String s = "Manual Testing Eng";
int count=1;
s = s.trim();// Remove Space From Starting and ending
for(int i=0;i<s.length();i++)
{
if (s.charAt(i)==' ' && s.charAt(i+1)!=' ')
{
count++;
}
}
System.out.println("Count of Words :"+count);
}
}

NOTE:-
trim( ) will reverse space from starting and ending of a string, not from the middle.
SPLIT (ARGS) : STRING [ ]
package Program;
public class CountWords
{
public static void main(String[] args)
{
String s = "Manual Testing Engineer";
String str [ ] = s.split(" ");
for(int i=0;i<str.length;i++)
{
System.out.println(str[i]);
}
}
}
/* WAP TO PRINT WORDS IN REVERSE ORDER FROM THE GIVEN STRING */
Ex:- I/P MANUAL TEST ENGINEER
O/P ENGINEER TEST MANUAL
package Program;
public class ReverseWords
{
public static void main(String[] args)
{
String s = "Manual Testing Engineer";
String str [ ] = s.split(" ");
for(int i=str.length-1;i>=0;i--)
{
System.out.print(str[i]+" ");
}
}
}

/* WAP TO PRINT FIRST & LAST WORD FROM STRING */


package Program;
public class FLW
{
public static void main(String[] args)
{
String s = "Manual Testing Engineer";
String str [] = s.split(" ");
System.out.println(str[0]+" "+str[2]);
}
}

/* WAP TO PRINT LONGEST WORD FROM THEN GIVEN STRING */


package Program;
public class LongestWord
{
public static void main(String[] args)
{
String s = "We Are Test Engineers";
String str[ ] = s.split(" ");
String max = str[0];
for(int i=1;i<str.length;i++)
{
if(str[i].length()>max.length())
{
max = str[i];
}
}
System.out.println("Longest word is: "+max );
}
}

/* WAP TO PRINT SMALLEST WORD FROM THEN GIVEN STRING */


package Program;
public class SmallestWord
{
public static void main(String[] args)
{
String s = "We Are Test Engineers";
String str[ ] = s.split(" ");
String min = str[0];
for(int i=1;i<str.length;i++)
{
if(str[i].length()<min.length())
{
min = str[i];
}
}
System.out.println("Smallest word is: "+min );
}
}

/* WAP TO PRINT ALL THE WORDS FROM THE STRING USING FOR-EACH LOOP */
Array
String
SYNTAX:- FOR-EACH LOOP Collection
Map

FOR (ARRAY TYPE VARIABLE NAME : ARRAY NAME)

System.out.println(VARIABLE NAME );

package Program;
public class Word
{
public static void main(String[] args)
{
String s = "We Are Test Engineers";
String str[ ] = s.split(" ");
// foreach loop
for(String v : str)
{
System.out.println(v);
}
}
}

/* WAP TO PRINT FREQUENCY OF WORD FROM THE STRING */


package Program;
public class FrequencyWord
{
public static void main(String[] args)
{
String s = "we are happy we want be happy";
String word = "happy";
String str [] = s.split(" ");
int count = 0;
for(String v : str)
{
if (word.equalsIgnoreCase(v))
count++;
}
System.out.println("Count of happy words: "+count);
}
}

/* WAP TO PRINT COUNT OF PALINDROME NUMBER FROM THE STRING */


package Program;
public class PalindromeCount
{
public static void main(String[] args)
{
String s = "MOM IS A VERY PERTTY IN EACH LEVEL";
String str [] = s.split(" ");
int count = 0;
for (String v : str)
{
String word = v,rev= "";
for(int i=word.length()-1;i>=0;i--)
{
char ch = word.charAt(i);
rev = rev+ch;
}
if(rev.equalsIgnoreCase(word))
count++;
}
System.out.println("Count is :"+count);
}
}
/* WAP TO DELETE DULPICATE WORDS FROM A STRING */
STRING “We Are Testing Engineers We Testing Appliaction”
package Program;
public class DeleteDuplicate
{
public static void main(String[] args)
{
String s = "We Are Test Engineers We Test Application";
String str [] = s.split(" ");
for(int i=0;i<str.length;i++)
{
int count=0;
for(int j=i+1;j<str.length;j++)
{
if (str[i].equalsIgnoreCase(str[j]))
{
str [j] =" ";
count++;
}
}
if (count==0 && str[i]!=" ")
System.out.println(str[i]);
}
}
}

Example:-2
package Program;
public class DeleteDuplicate
{
public static void main(String[] args)
{
String s = "We Are Test Engineers We Test Application";
String str [] = s.split(" ");
for(int i=0;i<str.length;i++)
{
for(int j=i+1;j<str.length;j++)
{
if (str[i].equalsIgnoreCase(str[j]))
{
str [j] =" ";
}
}
if (str[i]!=" ")
System.out.println(str[i]);
}
}
}

TO CHARARRAY: : char [ ]
– it breaks String & converts it into array character by character.
Example:
package Program;
public class CharArray
{
public static void main (String[] args)
{
String s = "manual Testing";
char ch[] = s.toCharArray();
for(int i=0;i<ch.length;i++)
{
System.out.println(ch[i]);
}
}
}

/* WAP TO CALCULATE FREQUENCY OF EACH CHARACTER IN A GIVEN STRING */


IF STRING “ MANUAL TESTING”, WE NEED TO DISPLAY HOW MANY TIMES,
EACH CHARACTER OCCURS
package Program;
public class CharArray
{
public static void main(String[] args)
{
String s = "manual Testing";
s = s.toUpperCase();
char ch[] = s.toCharArray();
for(char c='A';c<='Z';c++)
{
int count = 0;
for(int i=0;i<ch.length;i++)
{
if(c==ch[i])
count++;
}
if(count>0)
System.out.println(c+"-"+count);
}
}
}

INDEX OF (METHOD-STRING): INT


- It returns index of given string
Example
package Program;
public class IndexOfDemo
{
public static void main(String[] args)
{
String s = "manual testing";
int i = s.indexOf('a');
int j = s.indexOf("tes");
int k = s.indexOf('a',2); //from '2' index , it will search where 'a' is
int l = s.indexOf("est",4); //0,1,2,3 skipped
int m = s.indexOf('z'); //int that string, no 'z' so will shows '-1'

System.out.println(i);//1
System.out.println(j);//7 (only first character's index)
System.out.println(k);//4
System.out.println(l);//8 ->index 0,1,2,3 will skip,count from 4
System.out.println(m);//1
}
}

/* WAP TO DELETE DUPLICATE CHARACTER FROM A STRING */


package Program;
public class DeleteDuplicate
{
public static void main(String[] args)
{
String s = "manual testing";
String un = "";
for (int i=0;i<s.length();i++)
{
char ch = s.charAt(i);
if(un.indexOf(ch)==-1)
{
un = un+ch;
}
}
System.out.println("Non Duplicate "+"String is "+un);
}
}

USING ALL STRING METHODS:


package Program;
public class Methods
{
public static void main(String[] args)
{
String s = " Java Development";
String s1 = s.trim();
String s2 = s.toLowerCase();
String s3 = s.concat(" is not soo easy");
String s4 = s.toUpperCase();
boolean s5 = s.contains("Testing");

System.out.println(s);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
}
}
REPLACE (CHAR, CHAR):
package Program;
public class Replacing
{
public static void main(String[] args)
{
String s = "Manual Testcase2245";

String s1 = s.replace('a','r');
String s2 = s.replace("Test","Rest");
String s3 = s.replaceAll("[A-Z]","");
String s4 = s.replaceAll("[a-z]","");
String s5 = s.replaceAll("[AEIOUaeiou]","");
String s6 = s.replaceAll("[0-9]","");
String s7 = s.replaceAll(" ","");

System.out.println(s);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);
}
}
SUBSTING (INT STARTINDEX) : String
– it return subpart of a string
SUBSTRING(INT STARTINDEX,INT ENDINDEX) : String
– it returns subpart of a string from start From start index till end index-1.
package Program;
public class SubStringDemo
{
public static void main(String[] args)
{
String s = "Manual Testing";

String s1 = s.substring(4); // it will give o/p from 4 index to last


String s2 = s.substring(0, 7); // it will give o/p from 0 index to 7𝑡ℎ index

System.out.println(s1);
System.out.println(s2);
}
}

STRING:
String is predefine class which is present in java.lang package
In java string is an -
 OBJECT
 DATATYPE
 CLASS
 GROUP OF CHARACTERS
OBJECTS
String objects can be created in two ways-
1.USING NEW KEYWORD - two objects will get created
 one is under heap area - reference variable assigned to it.
 another is under string constant pool(SCP) - it is smallpart of heap
area no reference assigned to it, it is only for backup.
2. USING LITERAL
first JVM will go to SCP and check if there is any object presentwith string data, if it is
there it will assign reference to it, if it is not there it creates new object and assign
reference.

IMMUTABILITY

For above examples, we understand that for one string object there can be multiple references
assigned to it, if we change data of one string object it will effect to multiple references that’s
why java says that string objects are immutable i.e. once we created we cannot modify it.

Example:-1

package Program;

public class SubStringDemo


{
public static void main(String[] args)
{
String s = "Manually Testing";
s.concat("the app");

System.out.println(s);
}
}

Example:-2

package Program;
public class SubStringDemo
{
public static void main(String[] args)
{
String s = "Manually Testing";

s = s.concat(" the app ");

System.out.println(s);
}
}

STRING BUFFER & STRING BUILDER

These are classes which are present in java.lang package


String buffer & String builder object can be created only by using new keyword

Ex : String Buffer b1 = new String Buffer("Java");


String Builder b2 = new String Builder("Java");
String Buffer b3 = "Java"; // invalid
String Builder b4 = "Java"; // invalid
String Buffer & String Builder objects are multiple i.e. once we created we can modify
it.
String Buffer & String Builder objects will get created in heap area only.

EQUALS ( ):

In String class equal ( ) compare based on string data.


In String Buffer & String Builder class equals ( ) compares based on reference
In String class equals ( ) is over ridden from object class to compare two strings object
based on content.
In String Buffer and String Builder class equals ( ) is not over ridden so it compares
based on reference (same like object class).
== Operator can't be applied for string builder and string buffer objects.

DIFFERENCES BETWEEN STRING, STRING BUFFER & STRING BUILDER

S.No STRING SRING BUFFER STRING BUILDER

1. String objects are immutable String buffer objects are mutable String builder objects are mutable

2. Objects can be created in two Objects can be created only using Objects can be created only using
ways new keyword new keyword

1.new

2.literal

3. Objects will created in SCP or Objects will created in heap Objects will created in heap
heap

4. Thread safe i.e. at a time only Thread safe i.e. at a tie only one Not a Thread safe
one thread is allowed to thread is allowed to operate on
operate on string object string buffer object

5. If context is fixed we will go If context is varying we will go for If context is varying we will go
for string string buffer for string

builder

6. equals()-compares two String equals()-compares two String by equals()-compares two String by


by seeing content seeing reference seeing reference

7. performance is faster performance is moderate performance is faster


8. For concatenation we have For concatenation we have For concatenation we have
concat() append() append()

PATTERN PROGRAMMING

1. ***
***
***
package Program;
public class Pattern
{
public static void main(String[] args)
{
for (int row=1;row<=3;row++)
{
for (int col=1;col<=3;col++)
{
System.out.print("*");
}
System.out.println( );
}
}
}
2. ****
****
****
****
package Program;
public class Patterns
{
public static void main(String[] args)
{
for (int row=1;row<=4;row++)
{
for (int col=1;col<=4;col++)
{
System.out.print("*");
}
System.out.println( );
}
}
}
3. ****
****
**#*
****
package Program;
public class Pattern
{
public static void main(String[] args)
{
for (int row=1;row<=4;row++)
{
for (int col=1;col<=4;col++)
{
if (row==3 && col==3)
System.out.print("#");
else
System.out.print("*");
}
System.out.println( );
}
}
}
4. *#*#
*#*#
*#*#
*#*#

package Program;
public class Pattern
{
public static void main(String[] args)
{
for (int row=1;row<=4;row++)
{
for (int col=1;col<=4;col++)
{
if (col%2==0)
System.out.print("#");
else
System.out.print("*");
}
System.out.println( );
}
}
}

5. ****
####
****
####
package Program;
public class Pattern
{
public static void main(String[] args)
{
for (int row=1;row<=4;row++)
{
for (int col=1;col<=4;col++)
{
if (row%2==0)
System.out.print("#");
else
System.out.print("*");
}
System.out.println( );
}
}
}

6. *****
* *
* *
* *
*****
package Program;
public class Parttern
{
public static void main(String[] args)
{
for (int row=1;row<=5;row++)
{
for (int col=1;col<=5;col++)
{
if (row==1 || row==5 || col==1 || col==5)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println( );
}
}
}

7. *
*
*****
*
*
package Program;
public class Pattern
{
public static void main(String[] args)
{
for (int row=1;row<=5;row++)
{
for (int col=1;col<=5;col++)
{
if (row==3 || col==3)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println( );
}
}
}

8. *
*
*
*
package Program;
public class Pattern
{
public static void main(String[] args)
{
for (int row=1;row<=4;row++)
{
for (int col=1;col<=4;col++)
{
if (row==col)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println( );
}
}
}

9. * *
* *
*
* *
* *
package Program;
public class Pattern
{
public static void main(String[] args)
{
for (int row=1;row<=5;row++)
{
for (int col=1;col<=5;col++)
{
if (row==col || row+col==6)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println( );
}
}
}
10. *
**
***
****
package Program;
public class Pattern9
{
public static void main(String[] args)
{
for (int row=1;row<=4;row++)
{
for(int col=1;col<=4;col++)
{
if (row>=col)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println( );
}
}
}

11. ****
***
**
*
package Program;
public class Pattern
{
public static void main(String[] args)
{
for (int row=4;row>=1;row--)
{
for(int col=1;col<=4;col++)
{
if (row>=col)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println( );
}
}
}
12. *
**
***
****

package Program;
public class Pattern
{
public static void main(String[] args)
{
for (int row=1;row<=4;row++)
{
for(int col=4;col>=1;col++)
{
if (row>=col)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println( );
}
}
}
13. ****
***
**
*
package Program;
public class Pattern12
{
public static void main(String[] args)
{
for(int row=1;row<=4;row++)
{
for(int col=1;col<=4;col++)
{
if (row<=col)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println( );
}
}
}
14. *
* *
* * *
* * * *
package Program;
public class patterns14
{
public static void main(String[] args)
{
for(int row=1;row<=4 ;row++)
{
for(int col=1;col<=4;col++)
{
if(row+col>=5)
System.out.print("* ");
else
System.out.print(" ");
}
System.out.println();
}
}
}
15.* * * *
* * *
* *
*
package Program;
public class Pattern
{
public static void main(String[] args)
{
for(int row=1;row<=4 ;row++)
{
for(int col=1;col<=4;col++)
{
if(row<=col)
System.out.print("* ");
else
System.out.print(" ");
}
System.out.println();
}
}
}
TYPE-2 (PATTERN PROGRAMMING)

1.1 1 1
222
333
444
package Type2;
public class Pattern
{
public static void main(String[] args)
{
for(int row=1;row<=4;row++)
{
for (int col=1;col<=3;col++)
{
System.out.print(row+" ");
}
System.out.println( );
}
}
}
2. 1 2 3
123
123
123
package Type2;
public class Pattern2
{
public static void main(String[] args)
{
for(int row=1;row<=4;row++)
{
for (int col=1;col<=3;col++)
{
System.out.print(col+" ");
}
System.out.println( );
}
}
}
3.1 2 3 4
5678
9 10 11 12
package Type2;
public class Pattern3
{
public static void main(String[] args)
{
int count = 1;
for(int row=1;row<=3;row++)
{
for (int col=1;col<=4;col++)
{
System.out.print(count+" ");
count++;
}
System.out.println( );
}
}
}
4.1
2 2
3 3 3
4 4 4 4
package Type2;
public class Pattern4
{
public static void main(String[] args)
{
for(int row=1;row<=4;row++)
{
for (int col=1;col<=row;col++)
{
System.out.print(row+" ");
}
System.out.println( );
}
}
}
5. 1
1 2
1 2 3
1 2 3 4

package Type2;
public class Pattern5
{
public static void main(String[] args)
{
for(int row=1;row<=4;row++)
{
for (int col=1;col<=row;col++)
{
System.out.print(col+" ");
}
System.out.println( );
}
}
}
6. 1
2 3
4 5 6
7 8 9 10
package Type2;
public class Pattern6
{
public static void main(String[] args)
{
int count = 1;
for(int row=1;row<=4;row++)
{
for (int col=1;col<=row;col++)
{
System.out.print(count+" ");
count++;
}
System.out.println( );
}
}
}
TYPE-3 (PATTERN PROGRAMMING)
1.A A A
B B B
C C C
D D D
package Type3;
public class Pattern
{
public static void main(String[] args)
{
for(char row='A';row<='D';row++)
{
for (char col='A';col<='C';col++)
{
System.out.print(row+" ");
}
System.out.println( );
}
}
}
2. A B C
A B C
A B C
A B C
package Type3;
public class Pattern2
{
public static void main(String[] args)
{
for(char row='A';row<='D';row++)
{
for (char col='A';col<='C';col++)
{
System.out.print(col+" ");
}
System.out.println( );
}
}
}
3. A B C
D E F
G H I
J K L
package Type3;
public class Pattern3
{
public static void main(String[] args)
{
char c = 'A';
for(char row='A';row<='D';row++)
{
for (char col='A';col<='C';col++)
{
System.out.print(c+" ");
c++;
}
System.out.println( );
}
}
}
4. A
A B
A B C
A B C D
package Type3;
public class Pattern4
{
public static void main(String[] args)
{
for(char row='A';row<='D';row++)
{
for (char col='A';col<= row;col++)
{
System.out.print(col+" ");
}
System.out.println( );
}
}
}
5. A
B B
C C C
D D D D
package Type3;
public class Pattern5
{
public static void main(String[] args)
{
for(char row='A';row<='D';row++)
{
for (char col='A';col<= row;col++)
{
System.out.print(row+" ");
}
System.out.println( );
}
}
}
6. A
B C
D E F
G H I J
package Type3;
public class Pattern6
{
public static void main(String[] args)
{
char c = 'A';
for(char row='A';row<='D';row++)
{
for (char col='A';col<= row;col++)
{
System.out.print(c+" ");
c++;
}
System.out.println( );
}
}
}
TYPE-4 (PATTERN PROGRAM)
1. *
***
*****
*******

package Type4;
public class Pattern
{
public static void main(String[] args)
{
int star = 1;
int space = 3;
for(int row=1;row<=4;row++)
{
for (int col=1;col<= space;col++)
{
System.out.print(" ");
}
for (int k=1;k<= star;k++)
{
System.out.print("*");
}
System.out.println( );
space = space-1;

star = star+2;
}
}
}
2. *******
*****
***
*
package Type4;
public class Pattern2
{
public static void main(String[] args)
{
int star = 7;
int space = 0;
for(int row=1;row<=4;row++)
{
for (int col=1;col<= space;col++)
{
System.out.print(" ");
}
for (int k=1;k<= star;k++)
{
System.out.print("*");
}
System.out.println( );
space = space+1;
star = star-2;
}
}
}
3. *
***
*****
*******
*****
***
*

package Type4;
public class Pattern3
{
public static void main(String[] args)
{
int star = 1;
int space = 3;
for(int row=1;row<=7;row++)
{
for (int col=1;col<= space;col++)
{
System.out.print(" ");
}
for (int k=1;k<= star;k++)
{
System.out.print("*");
}
if(row<=3)
{
star = star+2;
space = space-1;
}
else
{
star = star-2;
space = space+1;
}
System.out.println( );
}
}
}
4. *******
*****
***
*
***
*****
*******
package Type4;
public class Pattern4
{
public static void main(String[] args)
{
int star = 7;
int space = 0;
for(int row=1;row<=7;row++)
{
for (int col=1;col<= space;col++)
{
System.out.print(" ");
}
for (int k=1;k<= star;k++)
{
System.out.print("*");
}
if(row<=3)
{
star = star-2;
space = space+1;
}
else
{
star = star+2;
space = space-1;
}
System.out.println( );
}
}
}
5. *
**
***
****
***
**
*

package Type4;
public class Pattern5
{
public static void main(String[] args)
{
int star = 1;
int space = 3;
for(int row=1;row<=7;row++)
{
for (int col=1;col<= space;col++)
{
System.out.print(" ");
}
for (int k=1;k<= star;k++)
{
System.out.print("*");
}
if(row<=3)
{
star = star+1;
}
else
{
star = star-1;
}
System.out.println( );
}
}
}
6. *
**
***
****
***
**
*

package Type4;
public class Pattern6
{
public static void main(String[] args)
{
int star = 1;
int space = 3;
for(int row=1;row<=7;row++)
{
for (int col=1;col<= space;col++)
{
System.out.print(" ");
}
for (int k=1;k<= star;k++)
{
System.out.print("*");
}
if(row<=3)
{
star = star-2;
space = space+1;
}
else
{
star = star+2;
space = space-1;
}
System.out.println( );
}
}
7. *#
**##
***###
****####
*****#####
package Type4;
public class Pattern7
{
public static void main(String[] args)
{
int star = 2;
int space = 4;
for(int row=1;row<=5;row++)
{
for (int col=1;col<= space;col++)
{
System.out.print(" ");
}
int count = 0;
for (int k=1;k<= star;k++)
{
count++;
if(count<=star/2)
System.out.print("*");
else
System.out.print("#");
}
star = star+2;
space = space-1;
}
System.out.println( );
}
}
Example:-1
package Array;
public class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("Java"); // HEAP
StringBuilder s2 = new StringBuilder("Java"); // HEAP
String s3 = new String ("Java"); // 1.HEAP 2.SCP
String s4 = "Java";

s3.concat("Development");
s1.append("Development");
s2.append("Development");

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Example:-2
package Array;
public class Demo
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("Java"); // HEAP
StringBuilder s2 = new StringBuilder("Java"); // HEAP
String s3 = new String ("Java"); // 1.HEAP 2.SCP
String s4 = "Java";

s3.concat("Development");
s1.append("Development");
s2.append("Development");

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);

boolean b1 = s1.equals("JavaDevelopment");
boolean b2 = s2.equals("JavaDevelopment");
boolean b3 = s3.equals(s4);

System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
}
}
DIFFERENCE B/W EQUALS METHOD & EQUALS EQUALS TO METHOD
EQUALS METHOD EQUALS EQUALS TO METHOD
1.Equals method compare values 1. Equals equals to compare reference i.e. if two
object are referring to single object it returns true otherwise
it returns false.

Example:-3
package Array;
public class Demo
{
public static void main(String[] args)
{
String s1 = new String ("Java"); // 1.HEAP 2.SCP
String s2 = "Java";
boolean b1 = s1.equals("s2");
boolean b2 = s1==s2;
System.out.println(b1);
System.out.println(b2);
}
}

2D-ARRAY PROGRAMMING:-
In 2d array array value are represented in terms of rows & columns.
SYNTAX:-

Array type array name [ ] [ ] = new array type [row size] [col size];

(Or)

Array type [ ] [ ] array name = new array type [row size] [col size];

(Or)

Array type [ ] [ ] array name = new array type [row size] [col size];
ARRAY CREATION:-
FOR Ex:- int a [ ] [ ] = new int [2] [2];
col-1 col-2
row-1
row-2
ARRAY INITIALISATION:-
a[0][0] = 10
a[0][1] = 20
a[1][0] = 30
a[1][1] = 40
Stored as 10 20
30 40
ARRAY UTILISATION:-
System.out.prinln(array name [row index] [col index]);
Ex:- System.out.prinln(a[0][0]);
/*WAP TO CREATE 2X2 MATRIX STORE THE VALUES INTO IT AND PRINT THEM */
package Array2D;
public class A2D
{
public static void main(String[] args)
{
int a [] [] = new int [2] [2];
a[0][0] = 10;
a[0][1] = 20;
a[1][0] = 30;
a[1][1] = 40;
for(int row=0;row<2;row++)
{
for(int col=0;col<2;col++)
{
System.out.print(a[row][col]+" ");
}

System.out.println ( );

EXAMPLE:-2

package Array;
public class A3D
{
public static void main(String[] args)
{
int a [] [] = new int [3] [3];
a[0][0] = 100;
a[0][1] = 200;
a[0][2] = 1100;
a[1][0] = 300;
a[1][1] = 400;
a[1][2] = 1200;
a[2][0] = 600;
a[2][1] = 700;
a[2][2] = 1300;
for(int row=0;row<3;row++)
{
for(int col=0;col<3;col++)
{
System.out.print(a[row][col]+" ");
}
System.out.println( );
}
}
}

EXAMPLE:-3

package Array;
public class A1D
{
public static void main(String[] args)
{
int a [] [ ] = {{100,200,300},{400,500,600},{700,800,900}};
for(int row=0;row<3;row++)
{
for(int col=0;col<3;col++)
{
System.out.print(a[row][col]+" ");
}
System.out.println( );
}
}
}

/*WAP TO TAKE 2D ARRAY VALUES FROM SCANNER CLASS & PRINT THEN
USING FOR LOOP */
package Array;
public class A1D
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter row size & col size");
int rowsize = sc.nextInt();
int colsize = sc.nextInt();
int a [] [] = new int [rowsize][colsize];
for(int row=0;row<rowsize;row++)
{
for(int col=0;col<colsize;col++)
{
a[row][col] = sc.nextInt();
}
}
for(int row=0;row<rowsize;row++)
{
for(int col=0;col<colsize;col++)
{
System.out.print(a[row][col]+" ");
}
System.out.println( );
}
sc.close();
}
}
/* WAP TO PRINT SUM OF MARTICES *
package Array;
public class ArraySum
{
public static void main(String[] args)
{
int a[ ][ ] = {{100,200},{300,400}};
int b[ ][ ] = {{500,600},{700,800}};
int s [ ] [ ] = new int [2][2];
for(int row=0;row<2;row++)
{
for(int col=0;col<2;col++)
{
s[row][col] = a[row][col]+b[row][col];
}
}
for(int row=0;row<2;row++)
{
for(int col=0;col<2;col++)
{
System.out.print(s[row][col]+" ");
}
System.out.println( );
}
}
}
DIFFERENCE BETWEEN FINAL, FINALLY & FINALIZE

FINAL FINALLY FINALIZE

1.Final is keyword which indicate 1.Finally is a block of code 1. Finalize is method of object
no more changes are allowed. which will be executed for sure. class.

2.Final is keyword is applicable 2.Finally block is used to keep 2.Finalize method is get called by
with class, method & variable. an important code like closing garbage collector just before it
of database connect, closing deletes the memory from heap
open file etc.. because it make area.
sure that the code is executed
irrespective of exception
3.If a variable is final we cannot occurred, exception did not Finalize is used to keep the
re-initialize. occurred & exception did not backup copy of delete data a in a
heap area by calling garbage
Handle. collector
4.If a method is final we cannot
over ride it.

5.If a class is final we cannot


inherit

You might also like