Core Java: MODULE:-1
Core Java: MODULE:-1
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
JAVA is one of the most widely used programming language, due to its various
characteristics.
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:
Syntax:-
ACCESSMODIFIER CLASS CLASSNAME
Public, Private, Protected & Default Key Word (imp word of Java)
To start a program
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:
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:
}
In above program all the word starting with smaller case expect
String – S System – S
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
Arch.Java
COMMENTS:
Comments are used for two different purposes
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:
Ex:--1
System.out.print(“Since 2010”);
}
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
NUMERIC
FORMULA:
(DECIMALS)
6 DOUBLE 8-BYTE If we want more than 6 digits after decimal (15 dec)
(SINGLE-CHARACTER)
(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.
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.
VARIABLES:-
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:-
3. VARIABLE UTILISATION:-
Syntax:-
SYSTEM.OUT.PRINTLN(VARIABLE NAME WITHOUT DOUBLE QUOTES)
String bname;
String author;
short pages;
String color;
short price;
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);
String name;
int age;
int sscyop;
float sscper;
String sklname;
int interyop;
float interper;
String interclg;
int gradyop;
float gardper;
String gardclg;
age = 23;
sscyop = 2015;
sscper = 63.65f;
interyop = 2017;
interper = 70;
interclg ="VJG";
gradyop =2022;
gardper =60;
gardclg ="VLITS";
//var utilisation
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);
String productname;
String productbrand;
String color;
int price;
float discount;
String modeofpurchase;
String dateofpurchase;
productname = "IPHONE";
productbrand = "APPLE";
color = "RED";
price = 50000;
discount = 50.0F;
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:-
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 = =
a-97,b-98,c-99 z-122
int a = 100,b=100;
boolean c;
c = a==b;
System.out.println(c);
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:
Will works as concatenations if any of the one operand is of String type &
provide result also in String format.
Ex: a + b
Ex:
“JAVA” + 18 JAVA18
“JAVA” + C JAVAC
Ex:-
System.out.println(“Name :”+Name);
Ex:
Age : 22
Ex:-1
String pname="Shoes",brand="Adidas",color="White",
mode="Adidas store",date="07-Sept-2022";
int price=5999,dis=499;
System.out.println("Purcase On : "+date);
Ex:-2
int age=22,sscyop=2014,interyop=2016,gradyop=2020;
float sscper=98.78F,interper=96.78F,gradper=65.76F;
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.
!= 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.
2. LOGICAL OR (||):-
OR operator return true of any of the input is true if return false of both the
input are false.
I/P O/P
TRUE FALSE
FALSE TRUE
EXAMPLE PROGRAME:-
public class Op
int a=10,b=20,c=10,d=10;
boolean e = a>b;
boolean f = a<b;
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-1:
int a = 10,b;
b = ++a;
System.out.println(a+"\n"+b);
Output:
11
11
Ex-2:
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:
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
int a = 30,b;
b = a++;
System.out.println(a+"\n"+b);
Output:
31
30
Ex-2:
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:
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:
Ex-1:
int a = 100;
System.out.println(a+"\n"+b+"\n"+c);
Output
102
200
402
Ex-2:
int a = 50;
System.out.println(a+"\n"+b+"\n"+c);
Output:
48
100
198
COMBINATIONAL 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:
i = i +1; i+=1
Ex-1:
int a = 50;
int b = 100;
b+= ++a;
System.out.println(a+"\n"+b);
Output:
51
151
If two operands share a common operator then execution will take place based on
priority.
LIST OF PRECEDENCE:
Example-1:
int d;
d = a-++b-++c*2;
System.out.println(d);
Output:
-12
Example-2:
int x = 5;
x = x++ * 2 + 3 * - x;
System.out.println(x);
}
}
Output
-8
KEYWORDS:
INDENTIFIERS:
Example:
Class Name
Variable Name
Method Name
Package Name
Project Name
Interface Name
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.
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
import java.util.Scanner;
import java.util.*;
(without space)
(with space)
Example:1:-
import java.util.Scanner;
c = a+b;
}
Example:2:-
import java.util.Scanner;
c = a*b;
Example:3:-
FORMULA:- (P*R*T)/100
P Principle amt
R Rate of Interest
T Time in year
import java.util.Scanner;
int p = sc.nextInt();
int t = sc.nextInt();
float r = sc.nextFloat(),si;
si = (p*r*t)/100;
Example:4:-
c = a+b;
Example:5:-
import java.util.Scanner;
int r=sc.nextInt(),s=sc.nextInt(),area;
a= pie*r*r;
c= 2*pie*r;
area=s*s;
CONDITIONAL STATEMENT
SWITCH CASE STATEMENT
CONDITIONAL STATEMENT:
{
Syntax:
// body of if
Else
// body of else
}
WORKING:
import java.util.Scanner;
if(age>=18)
}
else
import java.util.Scanner;
if (a>b)
System.out.println(a+" Is greatest");
else
{
System.out.println(b+" Is greatest");
import java.util.Scanner;
int a = sc.nextInt();
if (a%2 == 0)
else
System.out.println(a+" Is ODD");
}
Syntax:
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
}
import java.util.Scanner;
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
import java.util.Scanner;
System.out.println("Enter a Number");
int a = sc.nextInt();
else
int a = 23;
else
public class GR
{
System.out.println(a+" Is greatest");
System.out.println(b+" Is greatest");
else
System.out.println(c+" Is greatest");
int a = 25;
if (a%5==0 || a%3==0)
else
}
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.
Syntax:
Break;
Break;
Break;
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.
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.
1 MONDAY
2 TUESDAY
3 WEDNESDAY
7 SUNDAY
import java.util.Scanner;
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;
break;
DAYNUM DAYTYPE
1,2,3,4,5 WEEKDAY
6 WEEKDAY-1
7 WEEKDAY-2
import java.util.Scanner;
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number");
int dn = sc.nextInt();
switch(dn)
break;
case 6 : System.out.println("WEEKDAY-1");
break;
case 7 : System.out.println("WEEKDAY-2");
break;
break;
3,4,5,6 SUMMER
7,8,9,10 RAINY
11,12,1,2 WINTER
import java.util.Scanner;
System.out.println("Enter a Number");
int dn = sc.nextInt();
switch(dn)
break;
break;
break;
break;
}
}
CHARACTER TYPE
Other CONSONANT
import java.util.Scanner;
//char ch = 'e';
System.out.println("ENTER CHARACTER");
char ch = sc.next().charAt(0);
switch(ch)
{
break;
break;
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.
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*/
for(int i=1;i<=10;i++)
System.out.println("java");
for(int i=1;i<=10;i++)
System.out.println(i);
}
for(int i=10;i>=1;i--)
System.out.println(i);
}
/* CREATE A FOR LOOP TO PRINT A TO Z CHARACTER */
for(char i='A';i<='Z';i++)
System.out.print(i+" ");
System.out.println();
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[])
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;
System.out.println("Enter N-Value");
int n = sc.nextInt(),count=0;
for(int i=1;i<=n;i++)
if(i%2==0)
count++;
import java.util.Scanner;
{
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;
import java.util.Scanner;
int n = sc.nextInt(),p=1;
for(int i=1;i<=n;i++)
if(i%2==0)
p=p*i;
import java.util.Scanner;
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;
import java.util.Scanner;
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++;
import java.util.Scanner;
System.out.println("Enter Number");
int n = sc.nextInt();
for(int i=1;i<=10;i++)
import java.util.Scanner;
{
Scanner sc = new Scanner(System.in);
System.out.println("BEFORE SWAPPING");
int A = sc.nextInt();
int B = sc.nextInt();
int C ;
C = A;
A = B;
B = C;
import java.util.Scanner;
{
Scanner sc = new Scanner(System.in);
int A = sc.nextInt();
int B = sc.nextInt();
A = A + B;
B = A - B;
A = A - B;
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;
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
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;
PRIME NUMBER: Prime number is a number which is divisible only in 1 & itself.
import java.util.Scanner;
{
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
import java.util.Scanner;
public class Prime1
System.out.println("Enter Number");
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)
}
/* WAP SUM AND COUNT OF ALL THE PRIME NUMBERS FROM N1 TO N2 */
import java.util.Scanner;
System.out.println("ENTER NUMBER");
int n1=sc.nextInt(),n2=sc.nextInt();
int countP=0,sum=0;
int count=0;
for(int j=1;j<=i;j++)
if(i%j==0)
count++;
if(count==2)
countP++;
sum=sum+i;
WHILE LOOP:
Syntax:
STEP – 1 : INITIALISATION
int i = 1;
while(i<=10)
System.out.println(i);
i++;
int i = 10;
while(i<=1)
System.out.println(i);
i--;
int i = -11;
while(i<=11)
System.out.print(i+“ “);
i++;
char ch = 'A';
while(ch<='Z')
System.out.print(ch+" ");
ch++;
import java.util.Scanner;
System.out.println("ENTER A NUMBER");
while(num>0)
rem = num%10;
num = num/10;
rev = rev*10+rem;
NOTE:-
If we divided an ‘n’ digit number with 10 will we will remainder as last digit & remaining
digits as Quotient.
import java.util.Scanner;
System.out.println("ENTER A NUMBER");
while(num>0)
rem = num%10;
num = num/10;
rev = rev*10+rem;
if(rev==temp)
else
}
/* WAP TO CHECK WEATHER A NUMBER IS ARMSTRONG */
Ex 153 = 𝟏𝟑 + 𝟑𝟑 + 𝟓𝟑 .
import java.util.Scanner;
System.out.println("ENTER A NUMBER");
int rem,arm=0,temp=num;
while(num>0)
rem = num%10;
num = num/10;
arm = arm+rem*rem*rem;
if(arm == temp)
else
System.out.println(temp+" IS NOT AN ARMSTRONG NUMBER");
import java.util.Scanner;
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)
import java.util.Scanner;
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)
import java.util.Scanner;
{
Scanner sc = new Scanner(System.in);
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)
import java.util.Scanner;
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;
}
/* 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;
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;
}
/* WAP TO PRINT SUM OF ODD DIGITS FROM THE GIVEN NUMBER */
import java.util.Scanner;
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;
}
/* WAP BY TAKING INPUT FROM USER AND CHECK WHETHER THAT NUMBER
IS PALINDROME OR NOT */
import java.util.Scanner;
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)
else
Output Cout is 4
import java.util.Scanner;
public class PD
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++;
}
DIFFERENCE B/W 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
JAVA Output:
JAVA JAVA
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.
public class Do
int i=1;
do
System.out.println(i);
i++;
while(i<=10);
}
COMPEMENTS OF JDK:-
It is a part of JDK which provide all the facilities to exectue every java application.
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.
MAC
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
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++;
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.
Memory allocation can be done by malloc. Memory allocation can be done by new
keyword.
functionality.
main( ).
MODULE-2
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.
To break logic
To make logic more clear
Easy to understand
int r = 6;
int l=12,b=25,arear;
arear = l*b;
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.
areaRectangle();
int r = 6;
int l=12,b=25,arear;
arear = l*b;
System.out.println("AREA OF RECTANGLE IS : "+arear);
areaCircle();
Syntax:
int arear;
arear = l*b;
swap(10,20);swap(35,67);
}
public static void swap(int a,int b)
int c;
c = a;
a = b;
b = c;
factorial(2);
factorial(8);
factorial(9);
{
int fact = 1;
for(int i=num;i>=1;i--)
fact = fact*i;
The process of developing multiple methods with same name but different arguments
list is called as method over loading.
EXAMPLES:
NON-TECHNICAL
Bus
Train
Aeroplane
Bike
Car
Number Lock
Dawing Pattern
Finger Print
Face Sensor
TECHNICAL EXAMPLE:
Credit
Debit
Cash on Delivery
EXAMPLE –2
-Banking
Online Banking
Physical Banking
ATM Banking
App Baking
1.CREATE A CLASS AS PAYMENT APP
payment("GOOGLE PAY","vignesh@sbi");
payment("CREDIT",62341205678L,"JAN-98",333);
payment(38908235692L,"vignesh chowadary","VIGNE1234");
{
System.out.println("CARD TPYE : " +cardtype +"\ ncard no: "+cardno+ "\nexpdate:
"+expdate+"\ncvv:"+cvv);
System.out.println("ACC NO:"+accno+"\nuname:"+uname+"\npwd:"+pwd);
Print Values
Print Values
Travel (String Traintype, int Price, int Platform, String Source, String Dest)
Print Values
{
public static void main(String args[])
travel("AMARAVATHI A/C","VIJ","HYD");
travel("OMANAIR",50000,"HYD-AIRPORT","MCT-AIRPORT");
}
TYPES OF VARAIABLES:
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
BOOLEAN FALSE
STRING NULL
DIFFERENCE B/W LOCAL & 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.
5. Local variables are present in Stack 5. Global variables are present in Heap
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;
STORENAME
PRODUCT NAME
BRAND
COLOR
PRICE
STATIC VARIABLE.
4.CREATE MAIN ( ) & MAKE A CALL TO SHOPPING DETAILS ( )
ShoppingDetails();
STORENAME
BOOKNAME
AUTHOR
PAGES
COLOR
PUBLISHER
PRICE
BookStore();
}
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.
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.
{
Addition();
(OR)
System.out.println(A1.i+A1.j);
Addition();
}
System.out.println(“Addition Method)
A1.Addition();
CONCLUSION POINT:
Addition A1 = new Addition(); // Non Static Var Inside Static Method Access Through Object
Addition();
OUTPUT
300
-100
Restaurant_Name
No_of_dishes_order
Price
Order_id
Discount_amt
Food_rating
Delivery_rating
Hygenic_rating
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);
OrderDetails();
int food_rating = 3;
int delivery_rating = 5;
int hygenic_rating = 3;
delivery_person("VIJAYAWADA",50);
{
FoodOrderApp A2 = new FoodOrderApp();
A2.Zomto_panter();
1.CREATE AN GROCERY_APP
Item_name
Brand_name
Amount
Quantity
Mask_charges
Sanitise_charges
System.out.println("item_name:"+item_name+"\nbrand_name:"+brand_name+"\nAmou
nt:"+A1.Amount+"\nQuantity:"+A1.Quantity);
System.out.println("mask_charges: "+mask_charges+"\nscanitise_cahrges:"+scanitise
_charges);
customer_order();
A2.delivery_panter();
}
}
EXECUTION PROCESS:-
-Whenever we execute any program there will be two memory blocks that gets created.
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.
6.Upon call to anymethod, that method will get loaded in stack area.
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:
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
2.Static members will be loaded only 2.Non static members will be loaded
3.Static member are present in static pool 3.Non static member are present inside
area. an object.
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
7.We will go for static, if the data is 7.We will go for non static, if the data is
fixed. varying.
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.
DIRECTLY:-
Because they will get loaded only once in static pool area (SPA).
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
System.out.println(i);
System.out.println(A.i);
A a1 = new A();
System.out.println(a1.i);
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:-
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.
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.
Ex:-1
class Demo
System.out.println(i);
System.out.println(Demo.i);
System.out.println(d1.i);
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
int j = 400;
public class B
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:
String batchcode;
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:
Syntax:
ACCESSMODIFIER CONSTRUCTOR NAME (WITH ARGUMENTS / WITH OUT ARUGUMENTS
1. NO ARGUMENTS CONSTRUCTOR:
String dname;
public Dog()
dname = "Tommy";
System.out.println(D1.dname);
System.out.println(D2.dname);
String dname;
dname = DogName;
System.out.println(D1.dname);
System.out.println(D2.dname);
}
2.CREATE A CLASS AS BOOK
bname
bcolor
bprice
String bname,bcolor;
int bprice;
bname = bookname;
bcolor = bookcolor;
bprice = bookprice;
System.out.println("bname:"+A1.bname+"\nbcolor:"+A1.bcolor+"\nbprice:"+A1.bprice);
System.out.println("bname:"+A2.bname+"\nbcolor:"+A2.bcolor+"\nbprice:"+A2.bprice);
Ename
Eid
Esal
NAME.
TIMES.
String ename;
int eid,esal;
{
ename = ename;
esal = esal;
eid = eid;
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.
Ename
Eid
Esal
-TO INITIALISE THEM WE USE PARAMETENISED CONSTRUCTOR
NAME.
TIMES.
String ename;
int eid,esal;
this.ename = ename;
this.esal = esal;
this.eid = eid;
}
THIS KEYWORD:-
Product
Brand
Price
Color
String product,brand,color;
int price;
this.product = product;
this.brand = brand;
this.color = color;
this.price = price;
This process developing mutiple constructor with same name but different arguments is called
as a Constructor Over loading.
Name
Color
Price
Capacity
Model
CAR(String Name, String Color, Double Price, Int Capactiy, String Model)
String name,color,model;
int capacity;
double price;
this.name = name;
this.color = color;
this.name = name;
this.color = color;
this.price = price;
this.name = name;
this.color = color;
this.price = price;
this.model = model;
this.capacity = capacity;
System.out.println(C1.name+" "+C1.color);
Name
Price
Author
Pages
String name,author;
int price,pages;
this.name = name;
this.price = price;
this.name = name;
this.author = author;
this.price = price;
this.name = name;
this.author = author;
this.price = price;
this.pages = pages;
System.out.println(name+" "+price);
B1.display1();
B2.display2();
B3.display3();
}
CONSTRUCTOR CHAINING:
The process of calling one constructor from another constructor is called as Constructor
Chaining
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 Add()
this("java");// call to this->call another constructor of same class with String args
}
public Add(String s)
Example:2:-
public Add()
this("java");
}
public Add(String s)
this();
Example:3:-
public Add()
this(800,1000);
}
public Add(String s)
this();
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.
class A
A a1 = new A();
public Add
A a1 = new A();
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:-
{ Add();
{ Add(1000);
{ int v = Add();
{ String v = Add(1000);
class A
{ a1.add();
{ a1.add("java");
{ float v = a1.Add(100,200);
Example-1:-
return 3.14F*radius*radius;
}
}
Example-2:-
2.CREATE A NON STATIC METHOD WITH ARGUMENT & WITH RETURN TYPE
AS
int fact =1 ;
for(int i=num;i>=1;i--)
fact = fact*i;
return fact;
int ft = f.fact(5);
+ 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
PILLARS PURPOSE
CLASS:-
OBJECT:-
An object is defined as physical entity because physically it stores non static members in
each object.
CLASS OBJECT
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:-
Ex:-
Search()
Channels
Downloads() 44 4
Vidoes() is-a-relationship
Subscription()
Ex:-
class op1
class op2
{ having main()
Withdraw();
Deposit();
}
TYPES OF INHERITANCE:-
3.HIERARCHICAL INHERITANCE
4.MULTIPLE INHERITANCE
5.HYBRID INHERITANCE
One parent class and one chlid class is called single level inheritance.
PROGRAM:-
class Animal
System.out.println("Animal Eats");
}
System.out.println("Dog Brak");
F1.Eat();
F1.Brak();
}
2.MULTI LEVEL INHERITANCE:-
PROGRAM:
class Animal
System.out.println("Animal Eats");
System.out.println("Dog Brak");
System.out.println("Cat Meow");
}
public class Forest
C1.Eat();
C1.Brak();
C1.Meow();
3.HIERARCHICAL INHERITANCE:-
PROGRAM:-
class Animal
System.out.println("Animal Eats");
}
class Dog extends Animal
System.out.println("Dog Brak");
System.out.println("Cat Meow");
D1.Eat();
D1.Brak();
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
System.out.println("Carni Eats");
class Herbi
{
public void Eat()
System.out.println("Herbi Eat");
A1.Eat();
} problem is here only, JVM can’t understand that which eat( ) method
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.
class A
public A ()
System.out.println("A-class Constructor");
class B extends A
public B ()
System.out.println("B-class Constructor");
public class C
{
B b1 = new B();
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
B b1 = new B();
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();
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:
ADVANTAGES OF INHERITANCE:
Code Reusability
Connecting multiple logic at one place.
Easy to understand
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.
1.Inheritance is compulsory.
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
System.out.println("arrange marriage");
System.out.println("Love marriage");
}
public class Socity
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:
NOTE:
class Telecom
{
public void getcallertune()
G1.getcallertune();
G2.getcallertune();
B1.getcallertune();
EXAMPLE:-2:
class Zomato
System.out.println("ACCORDING TO LOCATION");
U1.getresturant();
Example:-1
class A
{
public void M1()
class B extends A
M1();
B b1 = new B();
b1.M2();
}
Example:-2
class A
class B extends A
super.M1();//? Which M1 ( )
} if you add super keyword then parent class M1( ) first loaded.
B b1 = new B();
b1.M2();
SUPER KEYWORD:-
PROGRAM:
class A
int i = 100;
class B extends A
int i =500;
public void M1()
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:
RULE:-1:
If a variable is declared as final, we should compulsorily initialize the value, before we use it.
RULE:-2:
SYNTAX:
EXAMPLE:-1:
class Sample
System.out.println(i);
EXAMPLE:-2:
class Sample
{
System.out.println(i);
If a class is declared as final, we can not inherit that class, if we do we will get compile time
error (CTE).
SYNTAX:
EXAMPLE:-1:
final class A
class B extends A
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
If a method is declared as final, we can not over ride it, because final method can not be over
ridden.
SYNTAX:
class Amazon
System.out.println("Amazon's logo");
System.out.println("Flipkart's logo");
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.
byte b = 127;
int i = s;
long L = i;
System.out.println(b);
System.out.println(s);
System.out.println(i);
System.out.println(L);
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
long L = 76543211;
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
System.out.println("M1 METHOD");
class B extends A
System.out.println("M2 METHOD");
a1.M1();
b1.M1();
b1.M2();
EXAMPLE:-DOWNCASTING PROGRAM
class A
System.out.println("M1 METHOD");
class B extends A
System.out.println("M2 METHOD");
{
public static void main(String args[])
p.M1();
c.M1();
c.M2();
a1.M1
b1.M1();
b1.M2();
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
class Student
A1.Viewing();
Admin A2 = (Admin) A1;
A2.Viewing();
A2.Editing();
EXAMPLE:-2
Aeroplane
Tyres Wings
class Takeingoff
{
System.out.println("Tyers and wings are visible");
A1.Tyres();
A2.Tyres();
A2.Wings();
EXAMPLE:-3
Hotstar
Tvshows Liveshows
class Normaluser
{
public void Tvshows()
N1.Tvshows();
V1.Tvshows();
V1.Liveshows();
}
EXAMPLE:-4
LeaveApp
View Edit
class Member
{
public static void main(String args[])
M1.View();
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.
TYPES:
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.
During Run / Execution time one thing showing mutiple behaviour, is called as Run
Time polymorphism
EXAMPLE:
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
class B extends A
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.
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)
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:
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
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
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:
Ex:
}
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.
Ex:
System.out.println("In RUN");
System.out.println("FLY AWAY");
CONCRETE CLASS:-
ABSTRACT/INCOMPLETE METHOD:-
If a method contains only method signature but not method implementation, is called
as Abstract/Incomplete method.
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
Ex:-2
A.No, we can not create an object because it contains abstract methods & abstract methods
does not have any body to execute.
Ex:
public class A
{
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.
Abstract class can contains abstract method & concrete method (both).
Ex:
PURPOSE OF ABSTRACT:-
1.To make simple information for end user to make user friendly (App should be simple in
nature)
Eg:
Suppose, one user send Hi ( in whatup app) to another that othter person get only ‘Hi’, not
the coding of Hi
TIGHT COUPLING:-
LOOSE COUPLING:-
When one application is not completely depends on another application for business
purpose, is called Loose copling.
RBI
HDFC
AXIS
ICICI
SBI
EXAMPLES:-
Ex:
package practice;
}
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();
}
}
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();
}
}
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:-
}
}
POSSIBLE RELATIONSHIP WITH KEYWORDS:
PARENT CHILD KEYWORD SYNTAX
CLASS CLASS EXTENDS CLASS B EXTENDS A
INTERFACE INTERFACE EXTENDS INTERFACE B EXTENDS A
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.
}
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
}
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();
}
}
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
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:-
Everything is going well but COVID-19 came then everything went abnormally….
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 :-
ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
StringIndexOutofBoundsException
ClassCastException
NumberFormatException
WHAT HAPPENS WHEN EXCEPTION OCCURS:-
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
}
}
// 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
}
Any type of Exception
CATCH (EXCEPTION D)
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
package Exception;
class A
{
}
class B extends A
{
}
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.
package Exception;
class A
{
}
class B extends 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");
}
}
}
package Exception;
class A
{
}
class B extends A
{
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.
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
Ex:-1
}
public static void main(String[] args)
{
try
{
voting(15);
}
catch(ArithmeticException e)
{
System.out.println("EXCEPTION CAUGHT");
}
}
}
NullPointerException
String s = null;
System.out.println (s.length());
ArrayIndexOutOfBondsException
a [ 3 ] = 500;
StringIndexOutOfBoundsException
String s = “java”;
s.charAt(5);
ClassCastException
InterruptedException
Thread.sleep(5000);
OBJECT CLASS:-
{ {
} }
toString ( ) : String :-
It is a method of object class
It return complete information of an object
Packagenane.classname@object address
Example:- myPackage.Sample@ZZh33453
// return packagename.classname@objectaddress;
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 ( )
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;
}
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);
}
}
EQUALS (
)
A,L, Po …..
Clone
String Str.B g – wc’s
}
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.
1. Create a class
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
OUT PUT:-1
OUT PUT:-2
OUT PUT:-3
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 )
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:-
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:
package abc;
public class Sample
{
public static int i = 100;
public static void main(String[] args)
{
System.out.println(i);
}
}
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);
}
}
package def;
import abc.Sample;
public class Demo extends Sample
{
public static void main(String[] args)
{
System.out.println(i);
}
}
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);
}
}
package abc;
public class Sample1 extends Sample
{
public static void main(String[] args)
{
System.out.println(i);
}
}
package abc;
public class Sample2
{
public static void main(String[] args)
{
System.out.println(Sample.i);
}
}
package def;
import abc.Sample;
public class Demo extends Sample
{
public static void main(String[] args)
{
System.out.println(i);
}
}
package abc;
public class Sample
{
static int i = 100;
public static void main(String[] args)
{
System.out.println(i);
}
}
package abc;
public class Sample1 extends Sample
{
public static void main(String[] args)
{
System.out.println(i);
}
}
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
Private Yes No No No No
ARRAY PROGRAMMING:-
LENGTH VARIABLE:-
Length is a variable which returns number of values started in an array (Size of an array).
USING ARRAY:-
1. ARRAY CREATION
2. ARRAY INITIALISATION
3. ARRAY UTILIZATION
ARRAY CREATION:-
SYNTAX:- SIZE = SIZE OF AN ARRAY
(Or)
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) */
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]);
}
}
}
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);
}
}
else if(a[i]<smin)
{
smin= a[i];
}
}
System.out.println("Minimum is: "+min);
System.out.println("Second Minimum is: "+smin);
}
}
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]);
}
}
}
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();
}
}
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");
}
}
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 ALL THE WORDS FROM THE STRING USING FOR-EACH LOOP */
Array
String
SYNTAX:- FOR-EACH LOOP Collection
Map
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);
}
}
}
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]);
}
}
}
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
}
}
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";
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;
System.out.println(s);
}
}
Example:-2
package Program;
public class SubStringDemo
{
public static void main(String[] args)
{
String s = "Manually Testing";
System.out.println(s);
}
}
EQUALS ( ):
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
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
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.