Core Java
Core Java
01-01-2025
01-01-2025
EXECUTION IN JAVA:
2-1-2025
Thursday, January 2, 2025 7:45 PM
class AddTwoNumbers{
public static void main(String[] args){
int num1=2;
int num2=3;
int sum=num1+num2;
[Link](sum);
}
}
No, Program execution starts from main method. Main method is a mediator and it
will send our program to jvm during the execution time.
class AddTwoNumbers{
{
int num1=2;
int num2=3;
int sum=num1+num2;
[Link](sum);
}
}
[Link] we create a empty class file , can we compile and execute it?
class AddTwoNumbers
{
What is class?
To allocated memory inside the class,main method has the static keyword
main method doesnot return any value as output, main method will send the logic
to jvm. so main method has a keyword void
*** Any value can be represented as a string data type, further we can convert any
value from string data type to its own data type
For reading multiple values from the end user main method should be of array data
type
For reading the values from the end user, during the runtime, main method has args
parameter.
Download Link:
[Link]
step 2:
[Link]
step 3:
step 4:
Note:
steps internship
Variable name:path
Variable value:C:\Program Files\Java\jdk-21\bin;
java -version
Program 1:
class displaymessage
{
public static void main(String[] args)
{
[Link]("Welcome to java world");
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java displaymessage
Welcome to java world
full stack java batch-21 Page 1
Welcome to java world
step 2:save the program in a folder(folder name is as your wish) with language extension
name
[Link]
javac [Link]
syntax:
java class_name
Program 2:
class Addition
{ 3 4
public static void main(String[] args)
{
int a=3,b=4,c; a b
c=a+b;
[Link](c);
} 7
}
c
full stack java batch-21 Page 2
c
[Link]
Program:3
username
password
firstname
lastname
mailid
class UserDetails
{
public static void main(String[] args)
{
String username="codingbrains";
String password="codingbrains";
String firstname="coding";
String lastname="brains";
String mailid="codingbrainsofficial@[Link]";
[Link](username);
[Link](password);
[Link](firstname);
[Link](lastname);
[Link](mailid);
}
}
output:
D:\batch-21>java [Link]
codingbrains 9652592663
codingbrains
coding
brains
codingbrainsofficial@[Link]
Assignment
layout:
employname(String)
full stack java batch-21 Page 1
employname(String)
employid(int)
salary(int)
Develop a program to read student details like name, branch, rollno, marks, display
name,branch,rollno, marks, percentage
class Studentdetails
{
public static void main(String[] args)
{
String name="rajesh";
String branch="CSE";
int rollno=23456;
int s1=75;
int s2=88;
int s3=66;
int s4=55; Name=
int s5=77;
int s6=85;
int totalmarks=s1+s2+s3+s4+s5+s6;
float percentage=(s1+s2+s3+s4+s5+s6)/6; Name=rajesh
[Link]("Name="+name)
[Link]("Branch="+branch);
[Link]("Subject1="+s1);
[Link]("Subject2="+s2);
[Link]("Subject3="+s3);
[Link]("Subject4="+s4);
[Link]("Subject5="+s5);
[Link]("Subject5="+s6);
[Link]("TotalMarks="+totalmarks);
[Link]("Percentage="+percentage);
}
}
output:
D:\batch-21>java Studentdetails
Name=rajesh
Branch=CSE
Subject1=75
Subject2=88
Subject3=66
Subject4=55
Subject5=77
full stack java batch-21 Page 2
Subject5=77
Subject6=85
TotalMarks=446
Percentage=74.0
The types of data which we are expecting as input to a java program are known as
data types in java
"The single valued data types are called as primitive data types
The numeric data which is represented without decimal point is called as integer data
types
a)byte
b)short
c)int
d)long 0 or 1
a==>byte bit means 0 or 1
a)byte -8bits
range=-128 to 127
Program
full stack java batch-21 Page 3
range=-128 to 127
Program
Class Bytedata
{
public static void main(String[] args)
{
byte a=127;
[Link]("The value="+a);
}
}
short- 2bytes
short- 2*8(1byte=8 bits)
-16bits bit -->1 or 0
Example:
class Datatypes
{
public static void main(String[] args)
{
short a=32767;
[Link]("The value="+b);
}
}
int:
Example:
class Datatypes
{
public static void main(String[] args)
{
int i=123456789
[Link]("The value of i is"+i);
}
}
D:\batch-21>javac [Link]
full stack java batch-21 Page 1
D:\batch-21>javac [Link]
[Link]: error: no suitable method found for
println(String,int)
[Link]("The value of i is",+i);
^
method [Link]() is not applicable
(actual and formal argument lists differ in length)
method [Link](boolean) is not applicable
(actual and formal argument lists differ in length)
method [Link](char) is not applicable
(actual and formal argument lists differ in length)
method [Link](int) is not applicable
(actual and formal argument lists differ in length)
method [Link](long) is not applicable
(actual and formal argument lists differ in length)
method [Link](float) is not applicable
(actual and formal argument lists differ in length)
method [Link](double) is not applicable
(actual and formal argument lists differ in length)
method [Link](char[]) is not applicable
(actual and formal argument lists differ in length)
method [Link](String) is not applicable
(actual and formal argument lists differ in length)
method [Link](Object) is not applicable
(actual and formal argument lists differ in length)
1 error
class Datatypes
{
public static void main(String[] args)
{
int i=1234567896;
[Link]("The value of i is"+i);
}
}
long
The long data type stores data upto 16 digits. It occupies 8 bytes of memory.
In process of assigning long data type value we must use L or "l" in RHS of declaration
class Datatypes
{
public static void main(String[] args)
{
long creditcardNo=9898989898123L;
[Link]("The creditcard Number is="+creditcardNo);
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java Datatypes
The creditcard Number is=9898989898123
D:\batch-21>
The data types which are represented with decimal point are called as float data types
a)float
float occupies 4 bytes memory
class Datatypes
{
public static void main(String[] args)
{
float a=12.34567F;
[Link]("The float value is="+a);
}
}
Note: In java if we are taking decimal values and if we are declaring the value as float data
type, we have assign F or f in the RHS
b)double
==>8 bytes of memory
full stack java batch-21 Page 3
==>8 bytes of memory
example:
class Datatypes
{
public static void main(String[] args)
{
double a=12.6787654;
[Link]("The double value="+a);
}
}
output:
D:\batch-21>java Datatypes
The double value=12.6787654
Character values:
The single valued character which is represented in single quotes is known as character
data [Link] data types occupies 2 bytes of memory
Ex: 'a','h','j'.........
The following are the three different ways to represent character data types
[Link] quotes
class Datatypes
{
public static void main(String[] args)
{
char ch='a';
[Link]("The character is="+ch);
}
}
output: ascii
D:\batch-21>java Datatypes
The character is=a
class Datatypes
{
public static void main(String[] args)
{
char ch=76;
[Link]("The character is="+ch);
}
}
D:\batch-21>java Datatypes
The character is=L
[Link] format
Example:
class Datatypes
{
public static void main(String[] args)
{
char ch='\u0041';
[Link]("The character is="+ch);
}
}
output:
D:\batch-21>java Datatypes
The character is=A
In java character data type holds unicode characters, to allocate storage for unicode
characters java programming has 2 bytes of memory for character data type.
The boolean type which is existing in the form of "true" or "false" is known as
boolean [Link] data type occupies 1 bit of memory.
"true"
Class Datatypes
{ "false"
public static void main(String[] args)
{ 1
boolean b1=true;
boolean b2=false; 0
[Link]("boolean value="+b1);
[Link]("boolean value="+b2);
}
}
output:
D:\batch-21>java Datatypes
boolean value=true
boolean value=false
Type Casting:
Converting one data type into another data type is called as type casting. In java the
following are the two types of type casting
implicit type casting: The process of converting lower data type value into higher
data type value is called as implicit type casting.
explicit type casting:The process of converting higher data type value into lower data
type value is called as implicit type casting.
class Implicttype
{
public static void main(String[] args)
{
byte x=10;
int y;
y=x; //placing 1 byte x value into 4 bytes y value
[Link](x); //10
[Link](y);//10
}
}
output:
D:\batch-21>java Implicttype
10
10
class Implicittype
{
public static void main(String[] args)
{
char x='a';
int y;
y=x;//placing 2 bytes x value into 4 bytes of value;
[Link](x);//a
[Link](y);//97
}
}
output:
D:\batch-21>java Implicittype
a
97
[Link] higher data type value into lower data type value is called explicit type
casting.
[Link] is also called as narrowing.
[Link] will be loss of information
4. we can perform explicit type casting by using the following syntax
src_variable=(src_datatype)dest_variable
class Typecasting
{
public static void main(String[] args)
{
double x=12.345; //occupies 8 bytes of memory
int y; //occupies 4 bytes of memory
y=(int)x;
[Link](x); //12.345
[Link](y);//12
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java Typecasting
12.345
12
object:
object :
Syntax of object_creation:
The programming component which are declared with "static" keyword will get the
memory inside the class.
The programming component which are declared without static keyword will get the
memory within the object
[Link] variables
[Link] static variables
[Link] variables
The variables which are declared with "static keyword" outside the method are
known as static variables.
static variables will get memory with in the class.
The variables which are declared without static keyword are known as non static
variables
a)Instance variables
b)Local variables
Instance variable
full stack java batch-21 Page 1
Instance variable
The non static variables which are declared outside the method are known as instance
variables or object variables
These instance variables will get the memory within the object
Local variables
The nonstatic variable which are declared inside the method are known as local
variables or method variables
program:
class Variables
{
int a=12;
static int b=13;
public static void main(String[] args)
{
int c=23;
Variables ob=new Variables();
[Link]("b value="+Variables.b);
[Link]("a value="+ob.a);
[Link]("c value="+c);
}
}
D:\batch-21>javac [Link]
D:\batch-21>java Variables
b value=13
a value=12
c value=23
D:\batch-21>
9652592663
Define global variables in java?
Methods in Java
Methods are the actions and which are executed to generate results. Based on static
keyword methods are categorized into two types
[Link] methods
[Link] static methods(Instance methods)
[Link] methods
The methods which are declared with static keyword are called as static methods or
class methods
The static methods will get memory within the class , these methods can be accessed
with class name.
Syntax:
return_type method_name(para_list)
{ int a, int b;
method body int add(a,b)
} {
c=a+b;
class Methods return c;
{ }
static int x=123;
int y=124;
static void m1()
{
[Link]("m1 method");
[Link]("x value:"+x);
}
void m2()
{
[Link]("m2 method");
[Link]("y value:"+y);
}
public static void main(String[] args)
{
Methods.m1();
Methods ob=new Methods();
ob.m2();
}
}
output:
full stack java batch-21 Page 1
output:
D:\batch-21>java Methods
m1 method
x value:123
m2 method
y value:124
JVM Architecture:
[Link] area
[Link] area
[Link] stack area
VM Architecture:
[Link] area
[Link] area
[Link] stack area
Method area:
The memory location where the class is loaded is known as Method area or Class
area.
static programming components will get the memory within the class.
Among static components , main() is automatically copied to java stack area to start
the execution process.
Heap Area:
The memory location where objects are created is known as Heap area.
While object creation Instance members will get the memory within the object.
The memory location where the methods are executed is known as java stack area.
main() is first copied on to a java stack area, and this main() will call the remaining
full stack java batch-21 Page 1
main() is first copied on to a java stack area, and this main() will call the remaining
methods
Example:
class Customerdetails
{
String custId="abc-1234";
String custname="codingbrains";
String city="Bangalore";
static long phno=9898981234L;
static String mailid="codingbrainsofficial@[Link]";
static void m1()
{
[Link]("Mailid="+mailid);
[Link]("Phone Number="+phno);
}
void m2()
{
[Link]("Customer Id="+custId);
[Link]("Customer Name="+custname);
[Link]("Customer City="+city);
}
public static void main(String[] args)
{
Customerdetails.m1();
Customerdetails ob=new Customerdetails();
ob.m2();
}
}
output:
D:\batch-21>java Customerdetails
Mailid=codingbrainsofficial@[Link]
Phone Number=9898981234
Customer Id=abc-1234
Customer Name=codingbrains
Customer City=Bangalore
==>To read input values dynamically during runtime we use predefined class
"Scanner class". The Scanner class is available inside [Link] package.
The following are the some of the instance methods from Scanner class to read data to
java programs
syntax:
javap [Link]
C:\ProgramFiles\Java\jdk-21\lib\src
src-->[Link]-->java-->util
syntax:
nextByte()
byte var=[Link]()
nextShort()
short var=[Link]()
nextInt()
int var=[Link]()
nextLong()
long var=[Link]()
nextFloat()
full stack java batch-21 Page 1
nextFloat()
float var=[Link]()
nextDouble()
double var=[Link]();
nextBoolean()
boolean var=[Link]()
nextLine()
String var=[Link]()
import [Link];
class Userdetails
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the username:");
String username=[Link]();
[Link]("Enter the mailid:");
String mailid=[Link]();
[Link]("Enter the phoneno:");
long phoneno=[Link]();
[Link]("Username:"+username);
[Link]("Mailid:"+mailid);
[Link]("PhoneNo:"+phoneno);
}
}
output:
D:\batch-21>java Userdetails
Enter the username:
full stack java batch-21 Page 2
Enter the username:
codingbrains
Enter the mailid:
codingbrains@[Link]
Enter the phoneno:
9898981234
Username:codingbrains
Mailid:codingbrains@[Link]
PhoneNo:9898981234
import [Link];
class Bookdetails
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the bookname:");
String bookname=[Link]();
[Link]("Enter the author name:");
String author =[Link]();
[Link]("Enter the book price:");
int price=[Link]();
[Link]("Book name:"+bookname);
[Link]("Author name:"+author);
[Link]("Book price:"+price);
}
}
output:
D:\batch-21>java Bookdetails
Enter the bookname:
Java Complete Reference
Enter the author name:
Ashok
Enter the book price:
456
Book name:Java Complete Reference
full stack java batch-21 Page 3
Book name:Java Complete Reference
Author name:Ashok
Book price:456 codingbrainsofficial@[Link]
Assignment:
[Link] operators
[Link] operators operator
[Link] operators
[Link] decrement Operators
[Link] operator
[Link] operators
[Link] Operators
Operator Meaning
+ Addition 2)4(2 Quotient Value
- Substraction 4
* Multiplication -------
0 remainder
/ Division
% Modulo Division
Example:
import [Link];
class Addition
{
public static void main(String[] args)
{ EditPlus
Scanner s=new Scanner([Link]); Eclipse
[Link]("Enter first number:");
int a=[Link]();
[Link]("Enter the second number:");
int b=[Link]();
int c=a+b;
[Link]("The sum="+c);
}
}
full stack java batch-21 Page 1
}
output:
D:\batch-21>java Addition
Enter first number:
5
Enter the second number:
7
The sum=12
Program:
import [Link];
class Division
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter first number:");
int a=[Link]();
[Link]("Enter second number:");
int b=[Link]();
int c=a/b;
[Link]("The result="+c);
}
}
output:
D:\batch-21>java Division
Enter first number:
4
Enter second number:
2
The result=2
Program:
import [Link];
class ModuloDivision
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
full stack java batch-21 Page 2
Scanner s=new Scanner([Link]);
[Link]("Enter first number:");
int a=[Link]();
[Link]("Enter second number:");
int b=[Link]();
int c=a%b;
[Link]("The result="+c);
}
}
output:
D:\batch-21>java ModuloDivision
Enter first number:
4
Enter second number:
2
The result=0
Relational Operators
The operators which performs comparision between two values and generate boolean
result are known as Relational Operators
Operator Meaning
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== equal to
!= Not equal to
Program
import [Link];
class RelationalOperators
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter first number:");
int a=[Link]();
[Link]("Enter the second number:");
full stack java batch-21 Page 3
[Link]("Enter the second number:");
int b=[Link]();
boolean c=a>b;
[Link]("The result is:"+c);
}
}
output:
D:\batch-21>java RelationalOperators
Enter first number:
5
Enter the second number:
7
The result is:false
Program
import [Link];
class RelationalOperators
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter first number:");
int a=[Link]();
[Link]("Enter the second number:");
int b=[Link]();
boolean c=(a!=b);
[Link]("The result is:"+c);
}
}
output:
D:\batch-21>java RelationalOperators
Enter first number:
5
Enter the second number:
6
The result is:true
D:\batch-21>javac [Link]
D:\batch-21>java RelationalOperators
Enter first number:
full stack java batch-21 Page 4
Enter first number:
5
Enter the second number:
5
The result is:false
Logical Operators
The operators which perform comparision between boolean values and generate
boolean result are known as logical operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Logical AND:
In Logical AND if both the boolean values are true then the result is true, other wise
the resutl will be false
A B A&B
T T T
F T F
T F F
F F F
Program:
import [Link]
class booleanprogram
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the first value:");
boolean a=[Link]();
[Link]("Enter the second number:");
boolean b=[Link]();
boolean c=a&&b;
[Link]("The result is:"+c);
}
full stack java batch-21 Page 5
}
}
Logical OR(||)
In Logical OR if either one of the boolean values are true then the result is true
other wise the result is false
A B A||B
T T T
F T T
T F T
F F F
program:
import [Link];
class LogicalOperators
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the first value:");
boolean a=[Link]();
[Link]("Enter the second value:");
boolean b=[Link]();
boolean c=a||b;
[Link]("The result is:"+c);
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java LogicalOperators
Enter the first value:
True
Enter the second value:
False
The result is:true
full stack java batch-21 Page 1
The result is:true
D:\batch-21>java LogicalOperators
Enter the first value:
False
Enter the second value:
False
The result is:false
Logical NOT:
In Logical NOT if the boolean value is True then the result is false, if the boolean
value is False then the result is true
A !A
T F
F T
Program:
import [Link];
class LogicalOperators
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the value:");
boolean a=[Link]();
[Link](!a);
}
}
D:\batch-21>java LogicalOperators
Enter the value:
true
false
D:\batch-21>java LogicalOperators
Enter the value:
full stack java batch-21 Page 2
Enter the value:
false
true
Parameters are the variables which are used to transfer the data from one method
to another method
[Link] parameters
[Link] parameters.
Actual parameters
The parameters which recieve original values inside the called method are called
actual parameters
Formal Parameters
The parameters which recieve the value inside the method signature are called
formal parameters
Program:
import [Link];
class Addition
{
int add(int a, int b)
{
int c=a+b;
return c;
}
}
class Mainclass
{
public static void main(String[] args)
{ n1 n2
Scanner s=new Scanner([Link]);
[Link]("Enter the first number:");
full stack java batch-21 Page 3
{ n1 n2
Scanner s=new Scanner([Link]);
[Link]("Enter the first number:"); 5 6
int n1=[Link]();
[Link]("Enter the second number:");
int n2=[Link]();
Addition ob=new Addition();
int n3=[Link](n1,n2);
[Link]("The addition result is:",+n3);
}
}
import [Link];
class Addition
{
int add(int a, int b)
{
int c=a+b;
return c;
}
}
class Mainclass
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the first number:");
int n1=[Link]();
[Link]("Enter the second number:");
int n2=[Link]();
Addition ob=new Addition();
int n3=[Link](n1,n2);
[Link]("The addition result is:",+n3);
}
}
D:\batch-21>java Mainclass
Enter the first number:
5
Enter the second number:
6
The addition result is:11
Actual Arguments
n1,n2 are actual values, and these values are being passed to the add method.
These are called actual arguments
Formal arguments
Here a and b are called formal arguments that recieve values of n1 and n2 when
the method is called
Return type specify whether the method will return the value or not after execution
Based on the value the return types are classified into two types
a.non_return types
[Link] type
The method will not return any value after execution, such type are declared with
"void"
[Link] _type
import [Link];
class CheckEven
{
boolean verify(int n)
{
if(n%2==0)
{
return true;
}
else
{
return false;
}
}
}
class EvenOdd
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the n value:");
int v=[Link]();
CheckEven ob=new CheckEven();
full stack java batch-21 Page 2
CheckEven ob=new CheckEven();
boolean k=[Link](v);
if(k)
{
[Link]("Even number");
}
else
{
[Link]("Odd number");
}
}
}
D:\batch-21>java EvenOdd
Enter the n value:
5
Odd number
D:\batch-21>java EvenOdd
Enter the n value:
6
Even number
Operator Meaning
++ Increment by 1
-- Decrement by 1
For example
5 6
class Operators
{
public static void main(String[] args) a b
{ 6
int a=5;
int b=++a;
[Link](a);==>6
[Link](b);==>6
}
}
output:
D:\batch-21>java Operators
6
6
example: 5 5
class Operators
{ a
public static void main(String[] args)
{
int a=5;
int b=a++;
[Link](a);
full stack java batch-21 Page 1
int a=5;
int b=a++;
[Link](a);
[Link](b);
}
}
output:
D:\batch-21>java Operators
6
5
Example:
class Operators
{
public static void main(String[] args)
{
int a=5,b=3; a)6 3 9
int c=a++ +b; b)5 3 9
[Link](a); c)6 3 8
[Link](b); d)5 3 8
[Link](c);
}
int c=a++ + b
}
c=5+3
c=8
output:
D:\batch-21>java Operators
6
3
8
Assignment Operator
Operator Meaning
= Normal Assignment
a+=b a=a+b
a-=b a=a-b
a*=b a=a*b
a/=b a=a/b
a%=b a=a%b
full stack java batch-21 Page 2
a%=b a=a%b
example:
import [Link];
class Operators
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter first number:");
int a=[Link]();
[Link]("Enter second number:");
int b=[Link]();
a+=b;
[Link]("The result="+a);
}
}
output:
Enter first number:
5
Enter second number:
6
The result=11
import [Link];
class Operators
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter first number:");
int a=[Link]();
[Link]("Enter second number:");
int b=[Link]();
a*=b;
[Link]("The result="+a);
}
}
full stack java batch-21 Page 3
output:
Enter first number:
5
Enter second number:
6
The result=30
Bitwise Operators
0 or 1 is called as bit
[Link] AND(&)
[Link] OR(|)
[Link] XOR(^)
[Link] Complement(~) tilde Symbol
[Link] Leftshift operator(<<)
[Link] Rightshift Operator(>>)
Bitwise AND(&)
4 & 5
4-->1 0 0
5-->1 0 1
--------------
100
-----------------
100
4 & 5==>4
full stack java batch-21 Page 4
4 & 5==>4
class Operators
{
public static void main(String[] args)
{
int a=4, b=5;
int c=a&b;
[Link](c);
}
}
Output:
D:\batch-21>java Operators
4
Bitwise OR Operator(|):
Rule: If atleast one bit is 1 then the result is 1 otherwise the result is 0
4|5
4 ==>1 0 0
5==>1 0 1
-------------
1 0 1
101
4|5-->5
class Operators
{
public static void main(String[] args)
{
int a=4, b=5;
int c=a|b;
[Link](c);
full stack java batch-21 Page 5
[Link](c);
}
}
output:
5
Bitwise XOR(^)
Rule:
4^5
4-->1 0 0
5-->1 0 1
---------
0 0 1
0 0 1
4 ^ 5==> 0 0 1
class Operators
{ temp
public static void main(String[] args) temp
{
int a=4, b=5;
int c=a^b;
[Link](c);
}
}
output:
D:\batch-21>java Operators
1
full stack java batch-21 Page 6
1
This operator performs NOT [Link] operator takes single value as input
Rule:
Take the weights of 0s with -sign and add them and also add -1
Example
~12
12-->1100
~12->0011
0 0 1 1
Program:
class Operators
{
public static void main(String[] args)
{
int a=12;
int b=~a;
[Link](b);
}
}
output:
D:\batch-21>java Operators
full stack java batch-21 Page 1
D:\batch-21>java Operators
-13
~13
13-->1101
~13-->0010
0 0 1 0
Take the weights of 0s
with -sign and add
them and also add -1
Program:
class Operators
{
public static void main(String[] args)
{
int a=13; 9652592663
int b=~a;
[Link](b);
}
}
output:
D:\batch-21>java Operators
-14
x=12
x<<2
x=12-->12*2=24*2=48
class Operators
{
full stack java batch-21 Page 2
{
public static void main(String[] args)
{
int a=12;
[Link](a<<2);
}
}
D:\batch-21>java Operators
48
x=12
x<<3
x=12-->12*2=24*2=48*2=96
class Operators
{
public static void main(String[] args)
{
int a=12;
[Link](a<<3);
}
}
D:\batch-21>java Operators
96
x=12
x>>2
12/2=6/2=3
class operators
{
public static void main(String[] args)
{
int a=12;
[Link](a>>2);
full stack java batch-21 Page 3
[Link](a>>2);
}
}
output:
D:\batch-21>java operators
3
x=18
x>>3
18/2=9/2=4/2=2
class operators
{
public static void main(String[] args)
{
int a=18;
[Link](a>>3);
}
}
output:
D:\batch-21>java operators
2
Selection statement:
The statements which are used to execute a particular lines of a program based
on the condition are called selection statments.
import [Link];
class Biggest
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the first number:"); n1 n2
int n1=[Link]();
[Link]("Enter the second number:");
int n2=[Link]();
if(n1>n2)
{
[Link]("The first number is greater than second number");
}
else if(n2>n1)
{
[Link]("The second number is greater than first number");
}
else
{
[Link]("Both numbers are equal");
}
}
}
D:\batch-21>java Biggest
Enter the first number:
6
Enter the second number:
5
The first number is greater than second number
D:\batch-21>java Biggest
Enter the first number:
6
Enter the second number:
6
Both numbers are equal
D:\batch-21>
main class-> the class holding main() method is known as main class
subclass--> the class which are present in the application other than main class
are called as subclasses
Control statements in java are statements that help in determining the flow of
control from one statement to another in a program
Java supports
a)simple if statement
b)if-else statement
c)Nested if statement
d) if...else if statement
e) switch statement
simple if statement
===============
Syntax:
if(condition)
{
statement
}
If the condition is true then "statement" will be executed, otherwise it will not
execute.
Program:
class SimpleIf
{
public static void main(String[] args)
{
int number=10;
if(number>5)
{
[Link]("The number is greater than 5");
}
}
full stack java batch-21 Page 1
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java SimpleIf
The number is greater than 5
b)if-else statement
An if-else statement in java allows to execute one block of code if a condition is true
and another block of code if the condition is [Link] structure is used in handling
binary decisions.
Syntax:
if(condition)
{
statement-1
}
else
{
statement-2
}
Program:
class IfElse
{
public static void main(String[] args)
{
int number=10;
if(number%2==0)
{
[Link]("The number is even");
}
else
{
[Link]("The number is odd");
}
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java IfElse
full stack java batch-21 Page 2
D:\batch-21>java IfElse
The number is even
c)Nested-if statement
A nested if statement is when an if block contains another if block inside it. This
allows us to check multiple conditions sequentially. where the inner condition is
evaluated only if the outer condition is true. It is useful for scenarios requiring
hierarchical decision making
program
class NestedIf
{
public static void main(String[] args)
{
int number=15;
//outer if condition
if(number>0)
{
//Inner if condition
if(number%2==0)
{
[Link]("The number is positive and even");
}
else
{
[Link]("The number is positive and odd");
}
}
else
{
[Link]("The number is not positive");
}
}
}
d)if-else if statement
program:
class IfElseIf
{
public static void main(String[] args)
full stack java batch-21 Page 3
public static void main(String[] args)
{
int number=0;
if(number>0)
{
[Link]("The number is positive");
}
else if(number<0)
{
[Link]("The number is negative");
}
else
{
[Link]("The number is zero");
}
}
}
main class-> the class holding main() method is known main class
subclass--> the classes which are present in the application other then main class are
called subclasses
class Addition
{
int add(int x,int y)
{
return x+y;
}
}
class Substraction
{
int sub(int x,int y)
{
return x-y;
}
}
class Multiplication
{
int mul(int x,int y)
{
return x*y;
}
}
class Division
{
int div(int x,int y)
{
return x/y;
}
}
class ModDivision
{
int moddiv(int x,int y)
{
return x%y;
}
}
class Calculator
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
full stack java batch-21 Page 5
Scanner s=new Scanner([Link]);
[Link]("Enter the first value:");
int v1=[Link]();
[Link]("Enter the second value:");
int v2=[Link]();
[Link]("*********Choice**********");
[Link]("[Link]\n [Link]\n [Link]\n [Link]\n [Link]");
[Link]("Enter your choice:");
int choice=[Link]();
switch(choice)
{
case 1:
Addition ad=new Addition();
int r1=[Link](v1,v2);
[Link]("Sum result is:"+r1);
break;
}
}
}
Control statements in java are statements that help in determining the flow of
control from one statement to another in a program
Java supports
a)simple if statement
b)if-else statement
c)Nested if statement
d) if...else if statement
e) switch statement
simple if statement
===============
Syntax:
if(condition)
{
statement
}
If the condition is true then "statement" will be executed, otherwise it will not
execute.
Program:
class SimpleIf
{
public static void main(String[] args)
{
int number=10;
if(number>5)
{
[Link]("The number is greater than 5");
}
}
full stack java batch-21 Page 1
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java SimpleIf
The number is greater than 5
b)if-else statement
An if-else statement in java allows to execute one block of code if a condition is true
and another block of code if the condition is [Link] structure is used in handling
binary decisions.
Syntax:
if(condition)
{
statement-1
}
else
{
statement-2
}
Program:
class IfElse
{
public static void main(String[] args)
{
int number=10;
if(number%2==0)
{
[Link]("The number is even");
}
else
{
[Link]("The number is odd");
}
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java IfElse
full stack java batch-21 Page 2
D:\batch-21>java IfElse
The number is even
c)Nested-if statement
A nested if statement is when an if block contains another if block inside it. This
allows us to check multiple conditions sequentially. where the inner condition is
evaluated only if the outer condition is true. It is useful for scenarios requiring
hierarchical decision making
program
class NestedIf
{
public static void main(String[] args)
{
int number=15;
//outer if condition
if(number>0)
{
//Inner if condition
if(number%2==0)
{
[Link]("The number is positive and even");
}
else
{
[Link]("The number is positive and odd");
}
}
else
{
[Link]("The number is not positive");
}
}
}
d)if-else if statement
program:
class IfElseIf
{
public static void main(String[] args)
full stack java batch-21 Page 3
public static void main(String[] args)
{
int number=0;
if(number>0)
{
[Link]("The number is positive");
}
else if(number<0)
{
[Link]("The number is negative");
}
else
{
[Link]("The number is zero");
}
}
}
main class-> the class holding main() method is known main class
subclass--> the classes which are present in the application other then main class are
called subclasses
class Addition
{
int add(int x,int y)
{
return x+y;
}
}
class Substraction
{
int sub(int x,int y)
{
return x-y;
}
}
class Multiplication
{
int mul(int x,int y)
{
return x*y;
}
}
class Division
{
int div(int x,int y)
{
return x/y;
}
}
class ModDivision
{
int moddiv(int x,int y)
{
return x%y;
}
}
class Calculator
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
full stack java batch-21 Page 5
Scanner s=new Scanner([Link]);
[Link]("Enter the first value:");
int v1=[Link]();
[Link]("Enter the second value:");
int v2=[Link]();
[Link]("*********Choice**********");
[Link]("[Link]\n [Link]\n [Link]\n [Link]\n [Link]");
[Link]("Enter your choice:");
int choice=[Link]();
switch(choice)
{
case 1:
Addition ad=new Addition();
int r1=[Link](v1,v2);
[Link]("Sum result is:"+r1);
break; 9652592663
case 2:
Substraction sb=new Substraction();
int r2=[Link](v1,v2);
[Link]("Sub result is:"+r2);
break;
case 3:
Multiplication ml=new Multiplication();
int r3=[Link](v1,v2);
[Link]("Multiplication result is:"+r3);
break;
}
}
}
Switch statement
A switch statement in java is used to execute one block of code from multiple options
based on the value of a [Link] case represents a specific value to match and
the corresponding block executes if the match is found. The break statement exits
the switch block.
Looping statements are the statement which executes several number of time as long
as a specified condition is satisified
a)while loop
b)do while loop
c)for loop
d)Enhanced for loop( from java 1.5 version) /for each loop
a)while loop
In java, a while loop is used to repeatedly execute a block of code as long as the
specified condition is [Link] condition is evaluated before each iteration and if it
evaluates to false, the loop terminates.
Syntax:
while(condition)
{
//code to be executed
}
input:543
output:345
Logic:
======
Program:
import [Link];
class ReverseNumber
{
int k;
int r=0;
int rev(int n)
{
while(n!=0)
{
k=n%10;
r=(r*10)+k;
n=n/10;
}
return r;
}
}
class Reversemain
full stack java batch-21 Page 2
class Reversemain
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter n value:");
int v=[Link]();
ReverseNumber ob=new ReverseNumber();
int r= [Link](v);
[Link]("Reverse of number is:"+r);
}
}
output:
D:\batch-21>java Reversemain
Enter n value:
23
Reverse of number is:32
153=
370=
Logic:
sum=0
full stack java batch-21 Page 3
Logic:
sum=0
while(n!=0)
n%10
{
n/10
d=n%10
sum=sum+d*d*d
n=n/10
} n=153
Logic:
sum=0
while(n!=0)
{
d=n%10
sum=sum+d*d*d
n=n/10
}
n=153
step:1
n=153
d=n%10
=153%10
=3
sum=sum+d*d*d
=0+3*3*3
=0+27
=27
n=n/10
=153/10
=15
step:2
d=n%10
=15%10
=5
sum=sum+d*d*d
=27+5*5*5
=27+125
=152
n=n/10
=15/10
=1
d=n%10
=1%10
=1
sum=sum+d*d*d
=152+1
=153
n=n/10
=1/10
n=0
Program:
import [Link];
class Armstrong
{
int sum=0;
int arm(int n)
{
while(n!=0)
{
int d=n%10;
sum=sum+d*d*d;
n=n/10;
}
return sum;
}
}
class Armstrongmain
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter a number:");
int v=[Link]();
Armstrong ob=new Armstrong();
int z=[Link](v);
full stack java batch-21 Page 2
int z=[Link](v);
if(v==z)
{
[Link]("The given number is a armstrong number");
}
else
{
[Link]("The given number is not a armstrong number");
}
}
}
output:
D:\batch-21>java Armstrongmain
Enter a number:
153
The given number is a armstrong number
D:\batch-21>java Armstrongmain
Enter a number:
222
The given number is not a armstrong number
program:
import [Link];
class Designation
{
boolean k=false;
full stack java batch-21 Page 3
boolean k=false;
boolean verify(String desg)
{
switch(desg)
{
case "Developer":k=true;
break;
case "Tester":k=true;
break;
case "DBM":k=true;
break;
default:k=false;
}
return k;
}
}
class Totalsalary
{
int calculate(int bsal)
{
return bsal+(12*bsal);
}
}
class Empmain
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter emp name:");
String ename=[Link]();
[Link]("Enter the emp designation:");
String edesg=[Link]();
Designation b=new Designation();
boolean k=[Link](edesg);
if(k)
{
[Link]("Enter Emp id:");
int eid=[Link]();
[Link]("Enter bsal:");
full stack java batch-21 Page 4
[Link]("Enter bsal:");
int bsal=[Link]();
if(bsal>=12000)
{
Totalsalary ob=new Totalsalary();
int totsal=[Link](bsal);
[Link]("===========Employee Details========");
[Link]("Employee Name:"+ename);
[Link]("Employee Desg:"+edesg);
[Link]("Employee id:"+eid);
[Link]("Employee bsal:"+bsal);
[Link]("Employee Salary:"+totsal);
}
else
{
[Link]("Invalid Salary:");
}
}
else
{
[Link]("Invalid Designation");
}
}
}
[Link] pinno
==>The pinno must be 4 digits else "Invalid pinno".
[Link] pinno is validated successfully, then verify pinno
The pinno must be 1111 or 2222 or 3333 else "Incorrect pinno"
[Link] pinno is validated successfully, then read amount to withdraw
==>The amount must be greater than zero and multiples of 100,
else Invalid amount
[Link] the amount is validated successfully, then amount must be less than
2000(because the account of the customer contains only 2000)
Program:
import [Link];
class Countdigits
{
int count=0;
int getcount(int n)
{
while(n>0)
{
count++
n=n/10;
}
return count;
}
class Checkpinno
{
}
full stack java batch-21 Page 1
class Withdraw
{
class Bankmain
{
}
else
{
[Link]("Invalid Pinno");
}
}
10)234(23
230
10)2345(234
--------
2340
4
----------
5
step:1
n=2345
n>0(True) 10)23(2
count=1 20
n=2345/10 ----------
n=234 3
step:2
n=234
n>0(True)
count=2 10)2(0
n=234/10 0
full stack java batch-21 Page 3
n>0(True)
count=2 10)2(0
n=234/10 0
n=23 ------------
2
step:3
n=23
n>0(True)
count=3
n=n/10
=23/10
n=2
step:4
n=2
n>0(True)
count=4
n=2/10
n=0
Program:
[Link] pinno
==>The pinno must be 4 digits else "Invalid pinno".
[Link] pinno is validated successfully, then verify pinno
The pinno must be 1111 or 2222 or 3333 else "Incorrect pinno"
[Link] pinno is validated successfully, then read amount to withdraw
==>The amount must be greater than zero and multiples of 100,
else Invalid amount
[Link] the amount is validated successfully, then amount must be less than 2000(because the
account of the customer contains only 2000)
import [Link];
class Countdigits
{
int count=0;
int getcount(int n)
{
while(n>0)
{
count++;
n=n/10;
}
return count;
}
}
class Checkpinno
{
boolean k=false;
boolean verify(int pinno)
{
switch(pinno)
{
case 1111:k=true;
break;
case 2222:k=true;
break;
case 3333:k=true;
break;
default:k=false;
full stack java batch-21 Page 1
default:k=false;
}
return k;
}
}
class Withdraw
{
void Wdraw(int amt)
{
[Link]("Amount Withdrawn:"+amt);
[Link]("Balance Amount:"+(2000-amt));
[Link]("Transaction completed successfully");
}
}
class Bankmainclass
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter pinno:");
int pinno=[Link]();
Countdigits cd=new Countdigits();
int c=[Link](pinno);
if(c==4)
{
Checkpinno cpn=new Checkpinno();
boolean k=[Link](pinno);
if(k)
{
[Link]("Enter the amount to withdraw");
int amt=[Link]();
if(amt>=0 && amt%100==0)
{
if(amt<=2000)
{
Withdraw wd=new Withdraw();
[Link](amt);
}
else
{
[Link]("Insufficient funds");
}
full stack java batch-21 Page 2
}
}
else
{
[Link]("Invalid amount");
}
}
else
{
[Link]("Incorrect Pinno:");
}
}
else
{
[Link]("Invalid pinno");
}
}
}
Java for loop is a control statement that allows the code to be executed repeatedly
based on given condition.
syntax:
example:
class SumofNumbers
{
public static void main(String[] args)
{
int sum=0;
for(int i=1;i<=10;i++)
{
sum=sum+i;
}
[Link]("The sum of first 10 natural numbers is:"+sum);
} sum=sum+i
} i=1
full stack java batch-21 Page 3
[Link]("The sum of first 10 natural numbers is:"+sum);
} sum=sum+i
} i=1
1<=10(True)
output: sum=sum+i
D:\batch-21>java SumofNumbers =0+1
The sum of first 10 natural numbers is:55 =1
i=2
2<=10(True)
sum=sum+i
=1+2
=3
i=3
3<=10(True)
sum=sum+i
3+3
6
A for loop is a control flow statement used to repeat a block of code ,a certain number of
times until a condition is true
syntax:
for(initialization;condition;increment/decrement)
{
code to be executed
}
components
[Link]:This step is executed only once at the start of the loop, It typically
initializes a variable
[Link]:
This condition is evaluated before each iteration. If the condition is true the loop
continues, if the condition is false then the loop
[Link]/decrement
This step is executed for each iteration. It usually modifies the variable, typically increase
or decrease the value inside the variable.
import [Link];
class MultiplicationTable
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter a number to print its multiplication Table:");
int number=[Link]();
for (int i=1;i<=10;i++)
{
[Link](number+"*"+i+"="+(number*i));
full stack java batch-21 Page 1
[Link](number+"*"+i+"="+(number*i));
}
}
}
output:
Enter a number to print its multiplication Table:
5
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50
D:\batch-21>java MultiplicationTable
Enter a number to print its multiplication Table:
7
7*1=7
7*2=14
7*3=21
7*4=28
7*5=35
7*6=42
7*7=49
7*8=56
7*9=63
7*10=70
This enhanced for loop is used to process the data inside an array
full stack java batch-21 Page 2
This enhanced for loop is used to process the data inside an array
arr[]={12,23,44,56,78}
syntax:
for(data_type variable:array_name)
{
//code to be executed
}
class Enhancedforloop
{
public static void main(String[] args)
{
int arr[]={12,23,44,56,78};
for(int i:arr)
{
[Link](i);
}
}
}
output:
D:\batch-21>java Enhancedforloop
12
23
44
56
78
The do while loop is similar to while loop, but the key difference is that
the code inside the loop is guaranteed to execute atleast once,even if the
condition is false. This is because the condition is checked after the loop
full stack java batch-21 Page 3
condition is false. This is because the condition is checked after the loop
body is executed
Syntax
do{
//code to be executed
}while(condition);
class DoWhileExample
{ 9652592663
public static void main(String[] args)
{
int i=1;
do{
[Link](i);
i++;
}while(i<=5);
}
}
output:
D:\batch-21>java DoWhileExample
1
2
3
4
5
class DoWhileExample
{
public static void main(String[] args)
{
int i=10;
do{
[Link](i);
i++;
full stack java batch-21 Page 4
i++;
}while(i<=5);
}
}
output:
D:\batch-21>java DoWhileExample
10
Factorial of a number using do while loop
import [Link];
class Factorial 4!=4*3*2*1
{ =24
public static void main(String[] args) 5!
{ 5*4*3*2*1
Scanner s=new Scanner([Link]); 120
[Link]("Enter a number:");
int num=[Link]();
int factorial=1;
int i=1;
do{
factorial=factorial*i;
i++;
}while(i<=num);
[Link]("Factorial of"+num+"is:"+ factorial);
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java Factorial
Enter a number:
5
Factorial of5is:120
D:\batch-21>java Factorial
full stack java batch-21 Page 5
D:\batch-21>java Factorial
Enter a number:
4
Factorial of4is:24
D:\batch-21>
import [Link];
class Factorial
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]); Flow of execution
[Link]("Enter a number:");
int num=[Link](); step 1:
int factorial=1; num=4
int i=1; factorial=factorial*i
do{ factorial=1*1
factorial=factorial*i; factorial=1
i++==>2
i++;
while(i<=num)
}while(i<=num); 2<=4==>True
[Link]("Factorial of"+num+"is:"+ factorial);
} step 2:
} factorial=factorial*i
=1*2
output: factorial=2
D:\batch-21>javac [Link] i++==>3
while(i<=num)
3<=4(True)
D:\batch-21>java Factorial
Enter a number: step:
4! factorial=factorial*i
5 4*3*2*1 2*3
Factorial of5is:120 24 =6
factorial=6
D:\batch-21>java Factorial i++==>4
while(i<=num)
Enter a number: 4<=4
4 True
Factorial of4is:24
step:4
factorial=factorial*i
D:\batch-21 6*4=24
factorial=24
i++==>5
full stack java batch-21 Page 1
i++==>5
while(i<=num)
5<=4==>False
Yield Keyword
Program:
import [Link];
class CheckDay
{
boolean check(String day)
{
switch(day){
case "MON":
case "TUE":
case "WED":
case "THU":
case "FRI":
[Link]("It is a weekday");
return true;
case "SAT":
case "SUN":
full stack java batch-21 Page 2
case "SUN":
[Link]("It is a weekend");
return false;
default:
[Link]("Invalid day");
return false;
}
}
}
class SwitchReturnExample
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the day:");
String day=[Link]();
CheckDay ob=new CheckDay();
boolean result=[Link](day);
[Link]("The result is:"+result);
}
}
Yield Keyword
=============
class CheckDay{
class SwitchReturnExample{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the day:");
String day=[Link]();
CheckDay ob=new CheckDay();
boolean result=[Link](day);
[Link]("The result is:"+result);
}
}
output:
D:\batch-21>java SwitchReturnExample
Enter the day:
SUN
It is a weekend
The result is:false
D:\batch-21>java SwitchReturnExample
Enter the day:
SAT
It is a weekend
The result is:false
[Link] a value: Unlike break, which just exists the switch, yield returns a value from a
case block.
D:\batch-21>java Blocks
====Static Block=====
The value of k:10
=====Main()=====
The value of k:11
Program:
class Blocks
{
static int k=10;
public static void main(String[] args)
{
k++; //k=k+1;
[Link]("=====Main()======");
[Link]("The value of k:"+k);
}
static
{
[Link]("====Static Block====");
[Link]("The value of k:"+k);
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java Blocks
====Static Block====
The value of k:10
=====Main()======
The value of k:11
The set of statements which are declared within curly braces and executed
automatically is known block
[Link] blocks
[Link] static blocks(Instance Blocks)
Syntax:
static
{
//code
}
[Link] blocks executes with highest priority when the class is used for the first
time
[Link] static methods the static blocks will access only static variables and
cannot access instance variables.
class Blocks
{
int k=10;
public static void main(String[] args)
{
k++; //k=k+1;
[Link]("=====Main()======");
[Link]("The value of k:"+k);
}
static
{
[Link]("====Static Block====");
[Link]("The value of k:"+k);
}
}
D:\batch-21>javac [Link]
[Link]: error: non-static variable k cannot be referenced from a static context
k++; //k=k+1;
^
[Link]: error: non-static variable k cannot be referenced from a static context
[Link]("The value of k:"+k);
^
[Link]: error: non-static variable k cannot be referenced from a static
context
[Link]("The value of k:"+k);
^
3 errors
class Staticblock
{
static int k=10;
static
{
[Link]("======Static Block====");
[Link]("The value of k:"+k);
}
}
class Staticmain
{
public static void main(String[] args)
{
Staticblock.k=300;
[Link]("=========main()======");
[Link]("The value of k:"+Staticblock.k);
}
D:\batch-21>java Staticmain
======Static Block====
full stack java batch-21 Page 3
======Static Block====
The value of k:10
=========main()======
The value of k:300
The blocks which are declared without static keyword are known as non static
blocks or Instance Blocks
syntax:
//set of instructions
}
Example:
class Instanceblock
{
int a=10;
static int b=20;
{
a++;
b++;
[Link]("====Instance Block====");
[Link]("The value of a:"+a);
[Link]("The value of b:"+b);
}
void dis()
{
a++;
b++;
[Link]("Instance Method dis()=====");
[Link]("The value of a:"+a);
[Link]("The value of b:"+b);
full stack java batch-21 Page 4
[Link]("The value of b:"+b);
}
}
class Instancemain
{
public static void main(String[] args)
{
Instanceblock b1=new Instanceblock();
[Link]();
Instanceblock b2=new Instanceblock();
[Link]();
}
}
Output:
D:\batch-21>java Instancemain
====Instance Block====
The value of a:11
The value of b:21
Instance Method dis()=====
The value of a:12
The value of b:22
====Instance Block====
The value of a:11
The value of b:23
Instance Method dis()=====
The value of a:12
The value of b:24
Program:
class Blocks
{
static int k=10;
public static void main(String[] args)
{
k++; //k=k+1;
[Link]("=====Main()======");
[Link]("The value of k:"+k);
}
static
{
[Link]("====Static Block====");
[Link]("The value of k:"+k);
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java Blocks
====Static Block====
The value of k:10
=====Main()======
The value of k:11
The set of statements which are declared within curly braces and executed
automatically is known block
[Link] blocks
[Link] static blocks(Instance Blocks)
Syntax:
static
{
//code
}
[Link] blocks executes with highest priority when the class is used for the first
time
[Link] static methods the static blocks will access only static variables and
cannot access instance variables.
class Blocks
{
int k=10;
public static void main(String[] args)
D:\batch-21>javac [Link]
[Link]: error: non-static variable k cannot be referenced from a static context
k++; //k=k+1;
^
[Link]: error: non-static variable k cannot be referenced from a static context
[Link]("The value of k:"+k);
^
[Link]: error: non-static variable k cannot be referenced from a static
context
[Link]("The value of k:"+k);
^
3 errors
class Staticblock
{
static int k=10;
static
{
[Link]("======Static Block====");
[Link]("The value of k:"+k);
}
}
full stack java batch-21 Page 2
}
class Staticmain
{
public static void main(String[] args)
{
Staticblock.k=300;
[Link]("=========main()======");
[Link]("The value of k:"+Staticblock.k);
}
D:\batch-21>java Staticmain
======Static Block====
The value of k:10
=========main()======
The value of k:300
The blocks which are declared without static keyword are known as non static
blocks or Instance Blocks
syntax:
//set of instructions
}
Example:
class Instanceblock
{
int a=10;
static int b=20;
{
a++;
b++;
[Link]("====Instance Block====");
[Link]("The value of a:"+a);
[Link]("The value of b:"+b);
}
void dis()
{
a++;
b++;
[Link]("Instance Method dis()=====");
full stack java batch-21 Page 3
[Link]("Instance Method dis()=====");
[Link]("The value of a:"+a);
[Link]("The value of b:"+b);
}
}
class Instancemain
{
public static void main(String[] args)
{
Instanceblock b1=new Instanceblock();
[Link]();
Instanceblock b2=new Instanceblock();
[Link]();
}
}
Output:
D:\batch-21>java Instancemain
====Instance Block====
The value of a:11
The value of b:21
Instance Method dis()=====
The value of a:12
The value of b:22
====Instance Block====
The value of a:11
The value of b:23
Instance Method dis()=====
The value of a:12
The value of b:24
Constructor is a special method having same name as the class name and
execute while object creation
Constructor:
Constructor is a method having same name as the class name and execute while
object creation process
syntax:
class_name(para_list)
{
//set of instructions
}
program:
class Constructor
{
int a=100;
Constructor()
{
[Link]("=====Constructor=====");
[Link]("The value of a:"+a);
}
void dis(){
[Link]("=====dis()=====");
[Link]("The value of a:"+a);
}
}
class Constructormain
{
public static void main(String[] args)
{
Constructor ob=new Constructor();
[Link]();
}
}
D:\batch-21>java Constructormain
=====Constructor=====
The value of a:100
=====dis()=====
The value of a:100
class Constructor
{
int a=100;
Constructor()
{
[Link]("=====Constructor=====");
[Link]("The value of a:"+a);
}
{
[Link]("=====Instance Block=====");
[Link]("The value of a:"+a);
}
}
class Constructormain
{
public static void main(String[] args)
{
Constructor ob=new Constructor();
Constructor ob1=new Constructor();
}
}
Static block executes only once with highest priority when the class is used for the
first time and constructor is executed for each object while object creation
process.
class Constructor
{
int a=100;
Constructor()
{
[Link]("====Constructor====");
[Link]("The value of a:"+a);
}
static
{
[Link]("====Static block====");
[Link]("The value of a:"+a);
}
public static void main(String[] args)
{
Constructor ob=new Constructor();
}
}
output:
D:\batch-21>javac [Link]
[Link]: error: non-static variable a cannot be referenced from a static
full stack java batch-21 Page 3
[Link]: error: non-static variable a cannot be referenced from a static
context
[Link]("The value of a:"+a);
^
1 error
class Constructor
{
static int a=100;
Constructor()
{
[Link]("====Constructor====");
[Link]("The value of a:"+a);
}
static
{
[Link]("====Static block====");
[Link]("The value of a:"+a);
}
public static void main(String[] args)
{
Constructor ob=new Constructor();
}
}
D:\batch-21>java Constructor
====Static block====
The value of a:100
====Constructor====
The value of a:100
class Constructor
{
static int a=100;
Constructor()
{
full stack java batch-21 Page 4
{
[Link]("====Constructor====");
[Link]("The value of a:"+a);
}
static
{
[Link]("====Static block====");
[Link]("The value of a:"+a);
}
public static void main(String[] args)
{
Constructor ob=new Constructor();
Constructor ob1=new Constructor();
}
}
D:\batch-21>java Constructor
====Static block====
The value of a:100
====Constructor====
The value of a:100
====Constructor====
The value of a:100
class Constructor
{
static int a=100;
void Constructor()
{
[Link]("====Constructor=====");
[Link]("The value of a:"+a);
}
public static void main(String[] args)
{
Constructor ob=new Constructor();
[Link]();
full stack java batch-21 Page 5
[Link]();
}
}
output:
D:\batch-21>java Constructor
====Constructor=====
The value of a:100
The constructor which are declared with parameters are known as parameterized
constructor or constructor with parameters
import [Link];
class Userlogin
{
String username,password,mailid;
long phno;
Userlogin(String a,String b,String c,long d)
{
username=a;
password=b;
mailid=c;
phno=d;
}
void getuserlogin()
{
[Link]("=======Userdetails========");
[Link]("Username:"+username);
[Link]("Password:"+password);
[Link]("mailid:"+mailid);
[Link]("Phoneno:"+phno);
}
}
class Usermain
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
full stack java batch-21 Page 6
Scanner s=new Scanner([Link]);
[Link]("Enter the username:");
String uname=[Link]();
[Link]("Enter the password:");
String pword=[Link]();
[Link]("Enter the mailid:");
String mid=[Link]();
[Link]("Enter the PhoneNo:");
long pno=[Link]();
Userlogin ob=new Userlogin(uname,pword,mid,pno);
[Link]();
}
}
output:
D:\batch-21>java Usermain
Enter the username:
rajesh
Enter the password:
rajesh123
Enter the mailid:
rajesh@[Link]
Enter the PhoneNo:
9898981234
=======Userdetails========
Username:rajesh
Password:rajesh123
mailid:rajesh@[Link]
Phoneno:9898981234
Three friends, named Bunny, Vinny, Sunny are playing a game. The rules of a game
are, A random number is selected from a series of numbers. The person Who got a
number containing Zeros in it, has to quit the game. But provided that a person who
got a number containing only zero will not quit the game, and continue in the game.
Develop a code in which a number is given and display the output whether to quit
the game or continue in the game.
import [Link].*;
import [Link].*;
import [Link];
class Userlogin
{
String username,password,mailid;
long phno;
Userlogin(String username,String password,String mailid,long phno)
{
username=username;
full stack java batch-21 Page 1
username=username;
password=password;
mailid=mailid;
phno=phno;
}
void getuserlogin()
{
[Link]("=======Userdetails========");
[Link]("Username:"+username);
[Link]("Password:"+password);
[Link]("mailid:"+mailid);
[Link]("Phoneno:"+phno);
}
}
class Usermain
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the username:");
String uname=[Link]();
[Link]("Enter the password:");
String pword=[Link]();
[Link]("Enter the mailid:");
String mid=[Link]();
[Link]("Enter the PhoneNo:");
long pno=[Link]();
Userlogin ob=new Userlogin(uname,pword,mid,pno);
[Link]();
}
}
output:
D:\batch-21>java Usermain
Enter the username:
suresh
Enter the password:
suresh
full stack java batch-21 Page 2
suresh
Enter the mailid:
suresh@[Link]
Enter the PhoneNo:
9898981234
=======Userdetails========
Username:null
Password:null
mailid:null
Phoneno:0
import [Link];
class Userlogin
{
String username,password,mailid;
long phno;
Userlogin(String username,String password,String mailid,long phno)
{
[Link]=username;
[Link]=password;
[Link]=mailid;
[Link]=phno;
}
void getuserlogin()
{
[Link]("=======Userdetails========");
[Link]("Username:"+username);
[Link]("Password:"+password);
[Link]("mailid:"+mailid);
[Link]("Phoneno:"+phno);
}
}
class Usermain
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter the username:");
String uname=[Link]();
[Link]("Enter the password:");
String pword=[Link]();
[Link]("Enter the mailid:");
String mid=[Link]();
[Link]("Enter the PhoneNo:");
long pno=[Link]();
Userlogin ob=new Userlogin(uname,pword,mid,pno);
[Link]();
}
}
D:\>javac [Link]
D:\>java Usermain
Enter the username:
rajesh
Enter the password:
rajesh
Enter the mailid:
rajesh@[Link]
class in java can be declared with any number of constructors. we can call these
constructors during object creation process.
class Test
{
Test(int a)
{
[Link]("======Test(a)==========");
[Link]("The value of a:"+a);
}
Test(int x, int y)
{
[Link]("=====Test(x,y)============");
[Link]("The value of x:"+x);
[Link]("The value of y:"+y);
}
}
class Testmain
{
public static void main(String[] args)
{
Test ob1=new Test(12);
}
}
output:
D:\batch-21>java Testmain
======Test(a)==========
The value of a:12
class Test
{
Test(int a)
{
[Link]("======Test(a)==========");
[Link]("The value of a:"+a);
}
Test(int x, int y)
{
[Link]("=====Test(x,y)============");
[Link]("The value of x:"+x);
[Link]("The value of y:"+y);
}
}
class Testmain
{
public static void main(String[] args)
{
Test ob1=new Test(12);
Test ob2=new Test(14,15);
}
}
output:
D:\batch-21>java Testmain
======Test(a)==========
The value of a:12
=====Test(x,y)============
The value of x:14
The value of y:15
yes, we can execute the multiple constructors from another constructor by creating
a single object. This process is called "constructor chaining process"
class Test
{
Test(int a)
{
this(14,15);
[Link]("======Test(a)=======");
[Link]("The value of a:"+a);
}
Test(int x,int y)
{
[Link]("=====Test(x,y)=====");
[Link]("The value of x:"+x);
[Link]("The value of y:"+y);
}
}
class Testmain
{
public static void main(String[] args)
{
Test ob1=new Test(12);
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java Testmain
=====Test(x,y)=====
The value of x:14
The value of y:15
======Test(a)=======
The value of a:12
"this" keyword is a predefined keyword, if we want to laod the data from local
variables then we will use this keyword
import [Link];
class Bookdetails
{
String bcode,bname,bauthor;
void getbookdetails()
{
[Link]("======BookDetails=====");
[Link]("Bookcode:"+bcode);
[Link]("Bookname:"+bname);
[Link]("Bookauthor:"+bauthor);
}
}
class Bookmain
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
Bookdetails ob=new Bookdetails();
[Link]("Enter the bookcode:");
[Link]=[Link]();
[Link]("Enter the bookname:");
[Link]=[Link]();
[Link]("Enter the bookauthor:");
[Link]=[Link]();
[Link]();
}
}
output:
full stack java batch-21 Page 3
output:
D:\batch-21>java Bookmain
Enter the bookcode:
A-123
Enter the bookname:
C-Language
Enter the bookauthor:
B-Swamy
======BookDetails=====
Bookcode:A-123
Bookname:C-Language
Bookauthor:B-Swamy
import [Link];
class Product
{
String code,name;
float price;
void setcode(String code)
{
[Link]=code;
}
void setname(String name)
{
[Link]=name;
}
void setprice(float price)
{
[Link]=price;
}
String getcode()
{
return code;
}
String getname()
{
return name;
}
float getprice()
{
return price;
}
}
class Productmain
{
public static void main(String[] args)
{
full stack java batch-21 Page 1
{
Product ob=new Product();
Scanner s=new Scanner([Link]);
[Link]("Enter the product code:");
[Link]([Link]());
[Link]("Enter the product name:");
[Link]([Link]());
[Link]("Enter the product price:");
[Link]([Link]());
[Link]("======Displaying by using Getter methods====");
[Link]("Product code:"+[Link]());
[Link]("Product name:"+[Link]());
[Link]("Product price:"+[Link]());
}
}
D:\batch-21>java Productmain
Enter the product code:
A201
Enter the product name:
Mouse
Enter the product price:
500
======Displaying by using Getter methods====
Product code:A201
Product name:Mouse
Product price:500.0
The methods which are used to set the data to instance variables are known as setter
methods
The methods which are used to get the data from the instance variables are known as
getter methods.
Every instance variable in a class will have setter methods and getter methods
In IDE's we can develop, execute and we can use libraries at a same time
netbeans
Eclipse
Eclipse
website: [Link]/downloads
import [Link];
bsal=12000
class Employeesalary
total salary=Hr+pf
{
3*bsal=3*12000=36000
int totalsalary(int bsal)
{
return(3*bsal)
}
}
class Employeemain
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter bsal:");
int bsal=[Link]();
Employesalary ob=new Employeesalary();
int totalsal=[Link](bsal)
[Link]("Totalsalary:"+totalsal);
}
}
output:
D:\batch-21>javac [Link]
D:\batch-21>java Employeemain
Enter bsal:
12000
Totalsalary:36000
step 1: Open Eclipse IDE, while opening name the workspace and click
launch
step2:
step 3:
Rightclick on "src"-->new--->package
name the package and click on finish
step:4
Note:
[Link]
package p1;
[Link]
package p2;
import [Link];
import [Link];
package p1;
[Link]
package p2;
import [Link];
import [Link];
output:
Enter the bookcode:
A-121
Enter the bookname:
C Language
Enter the bookauthor:
BSWamy
======BookDetails=====
Bookcode:A-121
Bookname:C Language
Bookauthor:BSWamy
[Link] packages
[Link] packages
[Link] packages
The packages which are already available in java library are called as predefined
packages
[Link]
[Link]
[Link] packages
The packages which are defined by the user are called user defined packages
we use "package" keyword to define userdefined packages
syntax
package package_name
[Link]
==========
package p1;
[Link]
============
package p2;
import [Link];
import [Link];
output:
[Link]
package p1;
[Link]
package p2;
import [Link];
import [Link];
output:
Enter the customer Id:
A-234
Enter the customer name:
Krishna
Enter the customer City:
HYd
Enter the customer Mailid:
krishna@[Link]
Enter the customer Phone No:
9898981234
====Displaying by using Getter Methods
CustId:A-234
CustName:Krishna
CustCity:HYd
CustMailId:krishna@[Link]
CustPhNo:9898981234
Assignment
==========
ProjectName: Student_App
packages:
p1:Percentage,Totalmarks
full stack java batch-21 Page 2
p1:Percentage,Totalmarks
p2:StudentMainClass
Assignment
========
Project Name:ArithmeticOperations
Packages:
p1:Addition,Substraction,Multiplication,Division,ModDivision
p2:ArthimeticMainClass
Accessmodifiers in Java
[Link]
[Link]
[Link]
[Link]
[Link]:
[Link]
[Link]
[Link]
[Link]
package p1;
Accessmain
[Link]
package p2;
import [Link];
full stack java batch-21 Page 4
import [Link];
[Link]
package p1;
[Link]
package p2;
import [Link];
[Link]
package p1;
[Link]
package p2;
import [Link];
Example
[Link]
package p1;
Example:
Protected
package p1;
example:
default
package p1;
Question-2
A network protocol specifies how data is exchanged via transmission media. The protocol
converts each message into a stream of 1's and 0's. Given a decimal number, write an
algorithm to convert the number into a binary form.
From <[Link]
Solution:
import [Link];
public class DecimalToBinary
{
public static void main(String[] args)
{ "10001"
Scanner s=new Scanner([Link]); 10001
int x=[Link](); "10000"
String y=[Link](x); "5"==>5
[Link](y); 23-->"23"
}
}
"import" statement will make class available from one package to another package.
In this importing we will specify the class_name to make it available to the current
class.
Example:
import [Link];
In this importing process all the classes from the package are available to the current
program
example:
import [Link].*;
The process of decalaring class with package names in the programming code is
known as fully qualified name.
Example:
***TCS
Define a method which returns the value 1 if the given number is even, in other case
return 0
Argument: int
Return type: an integer value
example: if x=22 return 1, if x=35 return 0
[Link]
package p1;
[Link]
package p2;
import [Link];
import [Link];
output:
Enter the value:
22
*** Wipro
Define a method which returns the greatest number among two numbers
write the method with the following specifications
Name of the method: getGreatest() // which accepts two integer value as argument
and returns the greatest value.
Specifications
The value returned by the method getGreatest() is determined by the following rules:
package p1;
[Link]
package p2;
import [Link];
output:
Enter the value1:
33
Enter the value2:
44
Result:44
-2,23
-1
34,0
-2
23,44
44
***TCS
Define a method which returns the number if it is a even number, if the number is
odd then return the next multiple of 10
Name of the method: oddRounder() //which accepts an integer value as argument and
return the same value if it is even number., if the value is odd then return the next
multiple of 10
Logic:
k=n/10
return (k+1)*10
n=23
k=n/10
=23/10 n=41
=2 k=n/10
return (k+1)*10
(k+1)*10
(2+1)*10
3*10 k=4
=30 (4+1)*10
5*10
50
[Link]
package p1;
[Link]
package p2;
import [Link];
import p1.Rounder1;
}
}
[Link]
package p1;
[Link]
package p2;
import [Link];
full stack java batch-21 Page 2
import [Link];
import [Link];
output:
Static import
================
syntax
Ex:
Advantage:
package p1;
[Link]
import [Link];
output:
Enter the username:
rajesh
Enter the mailId:
rajesh@[Link]
Enter the phoneNo:
9898981234
Username:rajesh
Mailid:rajesh@[Link]
PhoneNo:9898981234
byte var=[Link]([Link]());
short var=[Link]([Link]());
int var=[Link]([Link]());
long var=[Link]([Link]());
float var=[Link]([Link]());
double var=[Link]([Link]());
[Link]
package p1;
import [Link];
Strings in java
0 1 2 3 4 5 6 7 index values
L ANGUAGE
The characters in the string are organized based on the index values.
The following are the predefined classes from [Link] package are used to create
String applications
[Link] class
[Link] Buffer class
[Link] Builder Class
To check predefined methods inside string class type the following command
javap [Link]
Program:
[Link]
package p1;
import [Link];
OUTPUT:
full stack java batch-21 Page 1
OUTPUT:
Enter a string:
language
The length of the string is:8
Define toString()?
[Link]
package p1;
import [Link];
output:
Enter a string:
language
The given string is:language
[Link]
import [Link];
output:
Enter a string:
lanugage
The character present at index 2:n
input:
language
output:
egaugnal
[Link]
package p1;
import [Link];
output: length=8
Enter a string:
i=len-1
language i=7
===Reverse of a string=====
egaugnal
vowels : a e i o u
Input: language
count of vowels:4
[Link]
package p1;
import [Link];
output:
Enter a string:
java language program
Count of vowels:8
Write a program to read a string and check the string is palindrome string or not
Note:
i/p: madam
apple
The unique numeric number which is generated when a key is pressed from the
keyboard is known as ASCII(American standard code for information interchange)
code
Every key in keyboard will have its own ASCII Value
Write a program to generate upper case letters, lower case letters and number(0-9)
package p1;
output:
full stack java batch-21 Page 1
output:
Input
output:
Count of numbers:8
package p1;
import [Link];
}
}
output:
Enter the string:
java 19 version on 20th sept 2022
=====Result======
Count of numbers:8
wipro 2020
input
language
logic:
for(int j=len-1;j>=0;j--)
{
char ch=[Link](j);
}
import [Link];
}
}
output:
Enter the string:
language
l a n g u a g e | e g a u g n a l
Assignment
Input
java19, by 2020%year.
output
Count of vowels:4
full stack java batch-21 Page 5
Count of vowels:4
Count of consonants:6
Count of Numbers:6
Count of others:5
Hackerrank
An e-commerce website wishes to find the lucky customer who will be eligible for full value
cash back. For this purpose,a number N is fed to the system. It will return another number
that is calculated by an algorithm. In the algorithm, a sequence is generated, in which each
number n the sum of the preceding numbers. initially the sequence will have two 1's in it.
The System will return the Nth number from the generated sequence which is treated as the
order ID. The lucky customer will be one who has placed that order. Write an alorithm to
help the website find the lucky customer.
From <[Link]
Program:
n=8
1 1 2 3 5 8 13 21
order=21
n=5
1 1 2 3 5
order=5
n=6
1 1 2 3 5 8
order=8
n=9
n=1
1 1 2 3 5 8 13 21 34
1 1
full stack java batch-21 Page 1
n=1
1 1 2 3 5 8 13 21 34
1 1
order=34
output=1
Program: n=2
import [Link]; 1 1
public class LuckyCustomer{
public static int findLuckyCustomer(int N){ output=1
if(N==1 || N==2){
return 1;
}
Flow of execution
int a=1,b=1;
int nextNumber=0; N=8
for(int i=3;i<=N;i++){ a b
nextNumber=a+b; 1 1
a=b;
b=nextNumber; i=3
} 3<=8 True
return b; nextNumber=a+b
} =1+1
public static void main(String[] args){ =2
Scanner s=new Scanner([Link]); nextNumber=2
int N=[Link](); a=1
[Link](findLuckyCustomer(N)); b=2
}
} 21 i=4
4<=8 True
nextNumber=a+b
output:21 =1+2
=3
nextNumber=3
a=2
b=3
i=5
5<=8(True)
nextNumber=2+3=5
a=3
b=5
full stack java batch-21 Page 2
b=5
i=6
6<=8(True)
nextNumber=3+5=8
a=5
b=8
i=7
7<=8(True)
nextNumber=5+8=13
a=8
b=13
i=8
8<=8(True)
nextNumber=21
a=13
b=21
i=9
8<=9(False)
Program:
package p1;
import [Link];
output:
Enter the string:
java 19,by 2022%year.
Count of vowels:4
Count of consonents:6
Count of numbers:6
Count of others:5
Define substring()
substring() method is used to retrieve the part of the string based on index values
language length=8
2 index to 4 index-->ngu
0 index to 2 index-->lan
0 index to 3 index-->lang
3 index to 6 index-->guag
5 index to 7 index-->age
substring(int)
substring(int,int)
package p1;
full stack java batch-21 Page 1
package p1;
import [Link];
output:
Enter a string:
program
The substring of s1 is:ram
The substring of s2 is:rogr
Write a program to read student hall ticket number and display the branch based
on the branch code.
01==>civil
02==>EEE 226N120591
03-->mech
04--->ece
substring(6,8)
05-->cse
[Link]
package p1;
public class Generatebranch {
public String generate(String brCode)
{
return switch(brCode)
{
case "01": yield "CIVIL";
case "02": yield "EEE";
case "03": yield "MECH";
case "04": yield "ECE";
case "05": yield "CSE";
default: yield null;
[Link]
package p2;
import [Link];
import [Link];
}
else
{
[Link]("Invalid Hall Ticket Number");
}
}
}
output:
Enter the Hall Ticket Number:
226N120591
Hall Ticket Number Belongs to:CSE
a)equals() method
b)compareTo() method
c)"is equalto(==)" operator
syntax:
[Link](s2)
output:
[Link]
package p1;
import [Link];
b)compareTo()
syntax:
int z=[Link](s2)
Example:
abc
Abc
apple
doNkey
dog
package p1;
import [Link];
output:
String s1="apple"
String s2="apple"
The seperate partition of heap area where string objects are created is known as
"String constant pool" If objects are created by using string literal process , the
objects are stored in "string constant pool"
*******
Inside string constant pool , duplicate object creation for same content is not
possible
What is the difference between string literal process and "new operator process"?
In string literal process , the execution control will check the string constant pool,
whether the string constant pool is containing any object with same data
if the object with same data is not available then new object will be created
if the object with same data is available then new object will not be created
In new operator process new object will be created for every data.
The process of combining multiple strings into a single string is known as string
concatenation process
i) "+" Operator
ii) concat() method
package p1;
output:
S4:javaoraclepython
S5:javapython
S6:javaoraclepython
stringbuffer class
[Link]()
[Link]()
full stack java batch-21 Page 1
[Link]()
[Link]()
[Link]()
[Link](int)
[Link](String)
[Link](CharSequence)
Inorder to access the methods inside the StringBuffer class we have to create object to
StringBuffer class
In this syntax StringBuffer object is created with the default capacity equal to 16
characters. we use append() method to add the data to StringBuffer objects
==>16,34,70
package p1;
import [Link];
output:
====Buffer Status=====
Default Capacity:16
package p1;
import [Link];
}
}
}
output
====Buffer Status=====
Default Capacity:16
length:0
=====choice======
[Link]()
[Link]()
Enter the choice:
1
Enter the data:
java
data in buffer:java
Default Capacity:16
length:4
=====choice======
[Link]()
[Link]()
Enter the choice:
1
Enter the data:
programming
data in buffer:javaprogramming
Default Capacity:16
length:15
=====choice======
[Link]()
[Link]()
Enter the choice:
1
Enter the data:
a
data in buffer:javaprogramminga
Default Capacity:16
package p1;
import [Link];
}
else {
[Link]("buffer is empty...");
}
}
[Link]("Default capacity:"+[Link]());
[Link]("length:"+[Link]());
}
}
}
package p1;
import [Link];
}
else {
[Link]("buffer is empty...");
}
break;
case 4:
if([Link]()!=0) {
[Link]();
[Link]("The reverse string is:"+[Link]());
}
else {
[Link]("Buffer is empty");
}
}
[Link]("Default capacity:"+[Link]());
[Link]("length:"+[Link]());
}
}
}
=====BufferStatus======
Default capacity:16
length:0
=====Choice=======
[Link]()
[Link](int,string)
[Link]()
[Link]()
Enter the choice:
4
Buffer is empty
Default capacity:16
length:0
=====Choice=======
[Link]()
[Link](int,string)
[Link]()
[Link]()
Syntax:
StringBuffer sb=new StringBuffer(int);
example:
javaa
full stack java batch-21 Page 3
javaa
4+4+2=10
sb=4
package p1;
Default Capacity:4
length:0
The data inside buffer object:java
Default Capacity:4
length:4
The data inside the buffer object:javaA
Default Capacity:10
length:5
output:
package p1;
Default Capacity:20
length:4
The data inside buffer object:javaprogram
Default Capacity:20
length:11
The data inside the buffer object:javaprogramdeveleopers
Default Capacity:42
length:22
Syntax
program:
full stack java batch-21 Page 5
program:
package p1;
output
==========sb1======
sb1:developer
capacity:25
length:9
==========sb2======
sb2:developer
capacity:25
length:9
==========operation on sb2======
sb2:veloper
capacity:25
length:7
==========sb1======
sb1:developer
capacity:25
length:9
Syntax
package p1;
output
==========sb1======
sb1:developer
capacity:25
length:9
==========sb2======
sb2:developer
capacity:25
length:9
==========operation on sb2======
sb2:veloper
capacity:25
length:7
==========sb1======
String Tokenizer
i)hasMoreTokens()
ii)nextToken()
iii)countTokens()
i)hasMoreTokens()
syntax:
boolean hasMoreTokens();
ii)nextToken()
syntax:
String nextToken();
iii)countTokens()
syntax:
int countTokens();
package p1;
import [Link].*;
Program:
package p1;
import [Link].*;
output:
Wrapper Class
The predefined class from [Link] package which are used to make primitive data
types available in the form of objects are known as wrapper classes.
Every primitive data type will have its own wrapper class and there are 8 wrapper
classes
*** Java Tools and Frameworks will hold data only in the form objects, because of
this reason we have to make primitive data types available in the form of objects
The process of binding primitive data types into wrapper class object is known as
Boxing process
example:
package p1;
}
}
output:
full stack java batch-21 Page 2
output:
===Display data from Objects=====
ob1:12
ob2:23
ob3:12.3
ob4:1234567.8
ob5:23.1
ob6:12345.7
The process of storing primitive type out of wrapper object without using toString()
is known as unboxing process
byte byteValue();
short shortValue();
int intValue();
long longValue();
float floatValue();
double doubleValue();
char charValue();
boolean boolenValue();
package p1;
//unboxing process
int i1=[Link]();
int i2=[Link]();
float i3=[Link]();
[Link]("===Display data from Objects=====");
[Link]("ob1:"+i1);
[Link]("ob2:"+i2);
[Link]("ob3:"+i3);
full stack java batch-21 Page 3
[Link]("ob3:"+i3);
}
}
Output
===Display data from Objects=====
ob1:12
ob2:23
ob3:12.3
The process of assigning a value directly to an object without using new keyword is
known as autoboxing process
example:
package p1;
//Autounboxing process
int i1=ob1;
float f1=ob2;
char ch=ob3;
boolean b1=ob4;
[Link]("Displaying the values:");
[Link]("i1:"+i1);
[Link]("f1:"+f1);
[Link]("ch:"+ch);
[Link]("b1:"+b1);
}
}
output:
Displaying the values:
i1:12
f1:12.34
ch:A
b1:true
The tag based information which is added to the programming component is known
as Annotation
@SuppressWarning("removal")
package p1;
//unboxing process
int i1=[Link]();
int i2=[Link]();
float i3=[Link]();
[Link]("===Display data from Objects=====");
[Link]("ob1:"+i1);
[Link]("ob2:"+i2);
[Link]("ob3:"+i3);
full stack java batch-21 Page 2
[Link]("ob3:"+i3);
}
}
Arrays in Java:
Types of Arrays
The arrrays which are declared with one dimension(with one row or one column)
are called as single dimensional arrays
Syntax:
package p1;
import [Link];
output:
Enter the size of Array:
5
31
32
33
34
35
31
32
33
34
35
i)length
ii)length()
i)length
ii) length()
Extended for loop is introduced in java 5 version and which is used to retrieve
elements from array-objects on the array-name
Syntax:
for(Wrapper_class var_name:array_name)
{
full stack java batch-21 Page 4
{
//loop body
}
package p1;
import [Link];
Extended for loop is auto executable loop which executes automatically and there is
no concept of intialization, condition and increment/decrement
Write a program to read and display Multiple string values using array.
[Link]
package p1;
[Link]
package p1;
import [Link];
[Link]
package p1;
import [Link];
[Link]
package p1;
output:
Object Array is from [Link] package, object array can hold disimilar values which
means values generated from different classes
syntax:
[Link]
package p1;
[Link]
package p1;
MultiDimensional Arrays
The arrays which are decalared with multiple dimensions are known as multi
dimensional arrays
package p1;
import [Link];
output:
Enter the number of rows:
3
Enter the number of columns:
3
Enter the Integer Elements:
11
22
33
44
55
66
77
88
99
====Displaying the data=======
11 22 33
44 55 66
77 88 99
s1=s1+d
=0+3
s1=3
n=n/10
10)123(12
120
------------
3
n=12
True
d=n%10
10)12(1
10
------
2
d=2
s1=s1+d
=3+ 2
s1=
n=n/10
n=12/10
10)12(1
10
-----
full stack java batch-21 Page 1
-----
2
n=1
d=n%10
10)1(0
0
------
1
d=1
s1=s1+d
=5+1
s1=6
n=n/10
=1/10
10)1(0
0
- --------
1
n=0
package p1;
import [Link];
}
[Link]("====Displaying 3X3 Matrix======");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
[Link](ob[i][j].toString()+" ");
}
[Link]();
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
(i)smallest element
(ii)largest element
Logic explanation
int val=0;
int greater(Integer a[])
{
for(int i=0;i<[Link];i++)
{
if(a[i]>val) n=5====>length
{
val=a[i]; Elements
}
} a[0]=5
return val; a[1]=7
} a[2]=8
} a[3]=4
a[4]=3
val=0;
a[0]>val
5>0 True
full stack java batch-21 Page 3
5>0 True
val=5
a[1]>val largest=8
7>5 True
val=7
a[2]>val
8>7
val=8
a[3]>val
4>8 False
a[4]>val
3>8 false
[Link]
package p1;
[Link]
package p1;
[Link]
package p1;
class Main1
{
public static void main(String[] args)
{
[Link]("===Main() method======");
for(String k:args)
{
[Link]([Link]());
}
}
}
package p1;
output
12
12.38
python
hyd
A
a) arguments
b) parameters
int x=12,y=13
add(x,y)
When we pass variables to a methd while method call then these variables are
called as parameters
when we pass values directly to a method while method_call these values are
called as arguments
***Imp
Relations in java
[Link]
[Link]
[Link]
address
[Link]
The process in which one object holding the reference of another object is called as
reference concept
[Link]
package p1;
[Link]
package p1;
[Link]
package p1;
[Link]
package p1;
import [Link];
Inheritance:
The process in which one class takes the features or properties of another class is
known as inheritance
syntax:
class ClassA
{
//body
}
class ClassB extends ClassA
{
//body
}
Syntax
[Link]
package p1;
[Link]
package p1;
full stack java batch-21 Page 1
package p1;
[Link]
package p1;
import [Link];
}
}
output
Constructors in inheritance
0-arg constructor
[Link]
package p1;
public PClass()
{
[Link]("====PClass()======");
}
full stack java batch-21 Page 3
}
}
[Link]
package p1;
[Link]
package p1;
import [Link];
super()
[Link]
package p1;
[Link]
package p1;
[Link]
package p1;
output
====PClass()=====
The value of K:123
Explanation
==============
Imp:
(i) super()
(ii)this()
i)super()
ii) this()
Blocks in inheritance
PClass
package p1;
CClass
package p1;
Main1
package p1;
output:
Empty
reference CClass ob=new CClass();
PClass
object
package p1;
CClass
package p1;
Main1
package p1;
}
}
package p1;
CClass
package p1;
}
}
"Empty object reference" is created when we create object for the class holding
only static members
package p1;
package p1;
Static block in PClass will have highest priority in execution than static block
available in child class
Instance block in pclass will have highest priority in execution than instance block
available in CClass
If we have a method with same method signature in PClass and Cclass then PClass
method is replaced by CClass method is known as Method overriding process
return type
method name
para_list
para_type
package p1;
package p1;
package p1;
output:
====CClass method=====
Result:1331
package p1;
package p1;
package p1;
package p1;
package p1;
When we have same satic method signature in PClass and Cclass, then execution
control will execute CClass-method it will not reach PClass-method, this is known as
method hiding Process(Pclass method is Hided by Cclass method)
package p1;
package p1;
package p1;
c)Constructor overriding
**** Same instance method signature in PClass and CClass is known as Method
overriding process
***** Same static method signature in PClass and CClass is known as Method Hiding
Process
More than one Method with same method name but differentiated by parameter list
or parameter type is known as method overloading
More than one instance method with same method name but different parameter list or
parameter type is known as Instance method overloading process
this:
"this" keyword is used to access methods and variables from the same class
super:
full stack java batch-21 Page 2
super:
package p1;
package p1;
package p1;
More than one static method with same name but different parameter list is known as
static method overloading
package p1;
package p1;
package p1;
Constructor overloading
More than one constructor with different parameter list is known as constructor
overloading
this():
super():
package p1;
package p1;
package p1;
}
}
Types of inheritance
[Link] inheritance
[Link] inheritancec
[Link]-level inheritance
[Link] inheritance
[Link] Inheritance
The process of extracting the features from one class at a time is known as single
inhertiance
Multiple inheritance
single inheritance
multiple inheritance
Multiple inheritance process using classes is not available in java, which generates
ambiguity(confusion) to the JVM because the multiple inheritance is using repetation
of same programming components. The ambiguity generates wrong results.
Interfaces in java:
(upto java 7 version interface is a collection of variables and abstract methods, which
means interface cannot hold concrete methods)
abstract methods
The methods which are declared without method_body are known as abstract methods
syntax:
return_type method_name(para_list)
The methods which are declared with method body are known as concrete
methods
syntax:
return_type method_name(para_list)
{
//concrete method
}
Rule 1:
syntax:
interface interface_name
{
Rule 2:
The programming components which are declared with in the interface are "public"
Rule 3:
In interface we can declare both primitive data types and non primitive data types
Rule 4:
The variables which are declared within in the interface are of automatically "static"
and "final"
static variables in interface will get the memory within the interface and can be
accessed with interface_name
final variables are variables with values once intialized cannot be modified.
Rule 5:
The methods which are declared within in the interface are automatically Nonstatic
abstract methods
Rule 6:
The interfaces are implemented to a class using "implements" keyword and the classes
are known as implementation classes
Rule:7
Implementation classes must construct body for all abstract methods of interface
Rule 8:
We can also declare Non implemented methods with in the implementation class
Rule 9:
Interfaces cannot be instantiated, which means we cannot create object for interaces
full stack java batch-21 Page 1
Interfaces cannot be instantiated, which means we cannot create object for interaces
directly
Arithmetic
===========
package p1;
[Link]
=============
package p1;
[Link]
===================
package p1;
output:
faq:
The methods which are taked from the interface and constructed body are known as
Implemented methods
(ii)
Non Implemented method
The methods which are not taken from the interface are known as non implemented
methods
Rule 10:
package p1;
package p1;
package p1;
package p1;
import [Link];
output:
Rule 11:
From java8 version onwards Interface can be declared with concrete methods.
The concrete methods which are declared in interfaces with 'static' keyword are
known as "static concrete methods".
Static concrete methods will get the memory within the interface and can accessed
with interface_name.
static concrete methods of interface are not available to implementation classes, which
means static concrete methods of interface cannot be accessed by implementation
classname.
package p1;
package p1;
package p1;
ouput:
=====m1(x)======
The value of x:11
====Static void m2(y)=======
The value of y:12
The concrete methods in interface which are decalared with "default" keyword are
known as default concrete methods(default concrete methods are non static methods)
Default concrete methods are available to implementation class, which means default
concrete methods will get the memory within the object of implementation classes, and
can be accessed with implementation class object name
ITest
========
package p1;
}
public default void m3(int z) {
[Link]("====default m3(z)=======");
[Link]("The value of z:"+z);
}
}
IClass
========
package p1;
main1
=========
package p1;
output:
====m1(x)=======
The value of x:11
=====Static m2(y)========
The value of y:13
====default m3(z)=======
The value of z:13
private concrete methods in interfaces are accessed with in the interface, which means
private concrete methods are accessed by non private concrete methods of same
interface
Itest
========
package p1;
IClass
========
package p1;
main3
=======
package p1;
====m1(x)=======
The value of x:11
=====dis1(a)========
The value of a:12
====dis1(b)=======
The value of b:13
Rule 13:
Interface can be extended from another interface, which means one interface can
have features of another interface
package p1;
package p1;
package p1;
package p1;
output:
====m1(x)=====
The value of x:11
====m2(y)======
The value of y:12
import [Link].*;
import [Link].*;
n=n/10
234/10
n=23
========
step:2
23!=0
True
n=n%10
23%10
rem=3
3%2==1
rem%2!=0
n=n/10
n=23/10
n=2
=======
step 3:
n=2
n!=0
2!=0
full stack java batch-21 Page 1
step 3:
n=2
n!=0
2!=0
rem=n%10
2%10
rem=2
rem%2
sum = sum+ rem;
=4+2
=6
n=n/10
2/10
n=0
output:
6
[Link]
Model-1:
package p1;
package p1;
package p1;
package p1;
package p1;
package p1;
package p1;
package p1;
*****m1(x)****
The value of x:12
******ITest1 static m2(y)*****
The value of y:13
******ITest2 static m2(y)*****
The value of y:14
example:
package p1;
package p1;
package p1;
package p1;
Model:2
Extracting the features from one class and any number of interfaces into a class
(class extends from one class and can be implemented from any number of interfaces)
package p1;
package p1;
package p1;
package p1;
****m1(x)*****
The value of x:12
****m2(y)*****
The value of y:13
package p1;
full stack java batch-21 Page 2
package p1;
package p1;
package p1;
package p1;
*****m1(x)*****
The value of x:12
****m2(y)*****
The value of y:13
****dis(k)******
****The value of k:123
Model:3
Extracting the features from more than one interface into a interface
(Interface extending from more than one interface)
package p1;
package p1;
package p1;
package p1;
package p1;
====m1(x)=====
The value of x:12
===m2(y)=====
The value of y:13
===m3(z)=====
The value of z:14
Abstract classes
------------------
The classes which are declared with "abstract" keyword are known as abstract classes
Abstract classes can be declared with both abstract methods and concerete methods
Abstract classes cannot be instantiated , which means we cannot create object for abstract
classes
This abstract class are extended to a class using "extends" keyword and the classes are
known as "Extended classes or Implemented classes"
package p1;
package p1;
package p1;
===m1(x)====
The value of x:12
===m2(y)=====
The value of y:13
(i) interface
(ii)Abstract class
Components in interface are automatically public, but components in abstract class are
automatically default
Blocks and constructors are not available in interfaces, but abstract classes can hold blocks
and constructors
Abstract classes can hold variables, abstract methods, concrete methods,blocks, constructors
(a) class
(b)Abstract class
class can hold only concrete methods but abstract class can hold both abstract methods
and concrete methods
Generalization Process:
The process in which one object created holding all the members of PClass and only
overriding members from the CClass is known as Generalization Process
The Generalization process can also be applied on interfaces and abstract class
syntax:
[Link]
package p1;
full stack java batch-21 Page 1
package p1;
[Link]
package p1;
[Link]
package p1;
=====Class Generalization======
====CClass m1(x)(overriding)======
The value of x:12
===PClass m2(y)===
The value of y:13
[Link]
package p1;
[Link]
package p1;
package p1;
===Class Generalization====
===CClass m1(x)(Overriding)====
The value of x:12
===PClass m2(y)====
The value of y:13
=====Implemented dis1(a)=====
The value of a:23
====ITest Default dis2(b)====
The value of b:34
The process of hiding the implementation and showing the functionality is known as
abstraction.
The process of binding all the programming components into a single unit is known as
encapsulation
i) class in c++
ii) class in java
class in c++
class in c++ can hold variables and functions but cannot hold main()
class in java
class in java can hold variables,methods,blocks, constructors and main()
Innerclasses
---------------
Innerclasses in java:
The process of declaring class inside the class is known as innerclass or nested class
The inner classes which are declared as members of a class are known as member inner
classes
The inner classes which are declared with static keyword are known as static inner
classes
i)static member inner classes can be declared with both static and non static
members.
ii) Instance methods of static member inner classes will have behaviour like static
methods and can acccess only static members of outer classes, but cannot access
instance members of outer class
iii) The static members of static member inner class can access only static members
of outer class
[Link]
package p1;
[Link]
package p1;
output:
***OuterClass m1()*****
The member inner classes which are declared without static keyword are known as
Non static member inner classes
The non static member inner classes are categorized into two types
The non static member inner classes which are declared outside the methods of outer
classes are known as instance member inner classes
coding rules
[Link] member inner classes can be declared with both static members and non
static members
[Link] methods of instance member inner classes can access all members of outer
class directly
[Link] methods of instance member inner classes can access only static members of
outer class
package p1;
}
}
}
package p1;
*****OuterClass m1()*****
The value of a:10
The value of b:20
*****InnerClass Instance m2()****
The value of x:100
The value of y:200
The value of a:10
The value of b:20
***Innerclass static m22()******
The value of y:200
The value of b:20
The process of declaring inner classes inside the method of outer classes are known as
full stack java batch-21 Page 2
The process of declaring inner classes inside the method of outer classes are known as
local member innerclasses
Local member inner classes can be declared inside both static and instance methods of
outerclasses
Local member inner classes in instance method of outerclasses are called as instance
member inner classes
Local member inner classes in static method of outer classes are called as static local
member inner classes
Coding rule:
Local member inner classes objects are created inside the method where innerclasses
are declared
package p1;
package p1;
package p1;
package p1;
===CClass m1(x)====
The value of x:12
==PClass m2(y)===
The value of y:13
package p1;
package p1;
{
public void dis1(int a)
{
[Link]("===dis1(a)====");
[Link]("The value of a:"+a);
}
};
ob2.dis1(23);
ob2.dis2(45);
}
}
(para_list)->
{
method_body
}
(para_list)->
{
method_body
}
Note:
syntax:
interface Iarithmetic
{
public abstract void calculate(int x, int y);
}
Rule:1
Rule 2:
Normal Interface:
Functional interface
package p1;
package p1;
}
}
package p1;
package p1;
output:
Define exception?
[Link]
[Link]
[Link]
[Link]
"try block will hold the statements which are going to raise
the exception
try
{
//statements
}
[Link]
"Catch block will hold the value thrown from the try block and
the required msg is generated if the value received from the
try block is not within the input range
package p1;
import [Link].*;
output:
[Link]
"catch" block will hold the value thrown from the try block and then required msg
is generated if the value received from try block is not within the input range
step 1: The user defined class must be extended from predefined Exception class
step 2: The userdefined class must be declared with parameterized constructor with
string as parameter
step3: This parameterized constructor will take the message while object creation
and pass the message to the pclass
step 6: If the condition is true, then create object for userdefined class and while
object creation pass exception msg as parameter
step 7: use "throw" keyword to throw the object reference onto catch block
Program:
package p1;
import [Link].*;
public class Exception1 extends Exception {
public Exception1(String msg)
{
super(msg);
}
public static void main(String[] args) {
Scanner s=new Scanner([Link]);
try
{
[Link]("Enter the BasicSal:");
int bSal=[Link](); //Exception
if(bSal<12000)
{
Exception1 ob=new Exception1("Invalid Bsal");
throw ob;
}
int totSal=bSal+12*bSal;
[Link]("BasicSal:"+bSal);
[Link]("TotSal:"+totSal);
}//end of try
catch(Exception1 ob)
{
[Link]([Link]());
}
catch(InputMismatchException ob) {
[Link]("Enter only Integer BasicSal....");
}
finally
{
[Link]();
}
}
}
output:
full stack java batch-21 Page 2
output:
Enter the BasicSal:
11000
Invalid Bsal
Faq:
[Link]()
[Link]()
[Link]()
getMessage():
getMessage() method is used to display only exception message from the object
toString()
toString() is used to display exception-msg with the class name from where the
exception is raised
printStackTrace()
package p1;
import [Link].*;
public class Exception1 extends Exception {
public Exception1(String msg)
{
super(msg);
}
public static void main(String[] args) {
Scanner s=new Scanner([Link]);
try
{
[Link]("Enter the BasicSal:");
int bSal=[Link](); //Exception
if(bSal<12000)
{
Exception1 ob=new Exception1("Invalid Bsal");
throw ob;
}
full stack java batch-21 Page 1
}
int totSal=bSal+12*bSal;
[Link]("BasicSal:"+bSal);
[Link]("TotSal:"+totSal);
}//end of try
catch(Exception1 ob)
{
//[Link]([Link]());
//[Link]([Link]());
[Link]();
}
catch(InputMismatchException ob) {
[Link]("Enter only Integer BasicSal....");
}
finally
{
[Link]();
}
}
}
ouput:
Read RollNo
==>rollno must be length 10 digits, else we should raise exception
Program:
package p1;
import [Link];
output:
Enter the Roll no:
1234567890
RollNo:1234567890
The exceptions raised from the applications are categorized into two types
a)unchecked exception
b)checked exception
unchecked exception:
The exceptions which are not identified by the compiler at compilation stage
will be raised at execution stage are known as unchecked exceptions or runtime
exceptions
checked exceptions
The exceptions which are identified by the compiler at compilation stage are known as
checked exceptions
forName() method
Note:
full stack java batch-21 Page 3
Note:
"new" keyword cannot create object for classes loaded at runtime which means
"new" keyword will create object for the classes loaded at compilation stage
we will use "newInstance() method to create objects for classes loaded at runtime.
[Link]
package p1;
[Link]
package p2;
output:
==dis(k)====
Challenge-9
Lisa always forgets her birthday which is on th 5th July. So develop a function/method
which will be helpful to remember her birthday. The function/method checkBirthday return
an integer 1, if it is her birthday else return 0. the function/method checkBirthday accepts
two [Link], a string representing the month of her birth and day, an integer
representing the data of her birthday.
program:
import [Link].*;
import [Link].*;
}
}
package p2;
throw keyword
throw keyword is used to throw the object reference onto catch block in the
process of handling exception.
faq:
forName() method:
cart = {0, 0, 0, 0}
[Link]();
[Link]("Enter product number: ");
1
int productIndex = [Link]() - 1;
productIndex=1-1
productIndex=0
[Link]("Enter quantity: ");
Enter quantity:1
int quantity = [Link]();
quantity=1
[Link](productIndex, quantity);
break;
cart = {0, 0, 0, 0}
[Link]();
[Link]("Enter product number: ");
1
int productIndex = [Link]() - 1;
productIndex=1-1
productIndex=0
[Link]("Enter quantity: ");
Enter quantity:1
int quantity = [Link]();
quantity=1
[Link](productIndex, quantity);
cart[productIndex] += quantity;
stock[productIndex] -= quantity;
cart[productIndex] += quantity;
cart[0]+=1
cart[0]=cart[0]+1
cart[0]=0+1
cart[0]=1
cart={1,0,0,0}
stock[productIndex] -= quantity;
stock[productIndex]=stock[productIndex]-quantity;
stock[0]=stock[0]-quantity
stock[0]=5-1
stock[0]=4
stock = {4, 10, 15, 8};
[Link](removeIndex, removeQuantity);
break;
cart[productIndex] -= quantity;
stock[productIndex] += quantity;
cart[productIndex] -= quantity;
cart[productIndex]=cart[productIndex]-quantity
cart[0]=cart[0]-1
cart[0]=1-1
cart[0]=0
cart={0,0,0,0}
cart={1,0,0,0}
The finally block in java is used to executed important code regardless of whether an
exception occurs or not.
class FinallyExample
{
public static void main(String[] args){
int result=10/0;
[Link]("Hai");
}
}
output:
D:\>
D:\>java FinallyExample
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
class FinallyExample
{
public static void main(String[] args){
try{
int result=10/0;
}finally{
[Link]("Hai");
}
}
}
example:
class FinallyExample
{
full stack java batch-21 Page 1
{
public static void main(String[] args){
try{
int result=10/0;
}
catch(ArithmeticException ob){
[Link]("cannot divide by zero");
}
finally{
[Link]("Hai");
}
}
}
D:\>java FinallyExample
cannot divide by zero
Hai
finalize()
class FinalizeExample{
public void finalize(){
[Link]("Garbage collector has remove an object:");
}
public static void main(String[] args){
full stack java batch-21 Page 2
public static void main(String[] args){
FinalizeExample ob1=new FinalizeExample();
ob1=null;
[Link]();
}
}
class FinalizeExample{
public void finalize(){
[Link]("Garbage collector has remove an object:");
}
public static void main(String[] args){
FinalizeExample ob1=new FinalizeExample();
FinalizeExample ob2=new FinalizeExample();
ob1=null;
ob2=null;
[Link]();
}
}
D:\>java FinalizeExample
Garbage collector has remove an object:
D:\>javac [Link]
[Link]: warning: [removal] finalize() in Object has been deprecated and
marked for removal
public void finalize(){
^
1 warning
D:\>java FinalizeExample
Garbage collector has remove an object:
D:\>javac [Link]
[Link]: warning: [removal] finalize() in Object has been deprecated and
marked for removal
public void finalize(){
^
1 warning
D:\>
finalize()
The finalize() method is used for garbage collection before an object is destroyed
Final Variables(Constants)
When a variable is declared as final, its value cannot be changed after initialization
It must be initialized at the time of declaration
class Example{
final int max_speed=120;
void display(){
max_speed=150;
[Link]("max speed:"+max_speed);
}
}
D:\>javac [Link]
[Link]: error: cannot assign a value to final variable max_speed
max_speed=150;
^
1 error
class Parent{
final void show(){
[Link]("This is a final method.");
}
}
class Child extends Parent{
void show(){
[Link]("Child class method.");
}
}
output:
D:\>javac [Link]
[Link]: error: show() in Child cannot override show() in Parent
void show(){
full stack java batch-21 Page 1
void show(){
^
overridden method is final
1 error
output:
D:\>javac [Link]
[Link]: error: cannot inherit from final Vehicle
class Car extends Vehicle{
^
1 error
[Link]
[Link]
[Link]
[Link]
[Link]
Unchecked Exceptions
[Link]
[Link]
[Link] BoundsException
[Link]
ClassNotFoundException
class ExceptionExample{
public static void main(String[] args){
try{
[Link]("abc");
[Link]("Class loaded Successfully!");
}catch(ClassNotFoundException e){
[Link]("Class Not Found");
}
}
}
output:
D:\>javac [Link]
D:\>java ExceptionExample
Class Not Found
InstantiationException
================
abstract class Vehicle{
abstract void start();
}
full stack java batch-21 Page 3
}
class exceptionexample{
public static void main(String[] args)
{
try{
Vehicle obj=[Link]();
}catch(InstantiationException e)
{
[Link]("Error:Cannot Instantiate an abstract class");
}catch(IllegalAccessException e){
output:
1 error
D:\>javac [Link]
Note: [Link] uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
D:\>java exceptionexample
Error:Cannot Instantiate an abstract class
class Exception1{
public static String str;
public static void main(String[] args){
[Link]("Value of str:"+str);
int len=[Link]();
[Link]("length of str"+len);
}
}
D:\>java Exception1
Value of str:null
Exception in thread "main" [Link]: Cannot invoke
"[Link]()" because "[Link]" is null
at [Link]([Link])
Arthmetic Exception,ArrayIndexOutOfBoundsException
=========================================
class Exception1{
public static void main(String[] args){
try{
int a=10,b=0,c;
c=a/b;
[Link](c)
}
catch(ArithmeticException a)
{
[Link]("cannot divide by zero");
}
try
{
int a[]={10,20,30,40};
[Link](a[5]);
}
catch(ArrayIndexOutOfBoundsException b);
{
[Link]("Beyond the array limit");
}
}
}
output:
D:\>java Exception1
cannot divide by zero
Beyond the array limit
NoSuchElementsException
class Exception1{
public static void main(String[] args){
Scanner s=new Scanner("");//Empty input source
try{
[Link]("Enter a number:")
int number=[Link]();
full stack java batch-21 Page 1
int number=[Link]();
[Link]("you entered:" + number);
}catch (NoSuchElementException e){
[Link]("No input available to read");
}
}
}
D:\>javac [Link]
D:\>java Exception1
Enter a number:
No input available to read
[Link]
multithreading
[Link]
[Link]
[Link]
oracle
ui
advance java
4capstone
linkedin optimization
github customization
portfolio website
resume preparation
polymorphism
Two methods are said to be overloaded methods if and only if two methods are having
same name but differen argument list.
Types of overloading
[Link] overloading
[Link] overloading
[Link] overloading
Method Overloading
=============
class Overloading
{
void m1(char ch)
{
[Link]("Char-arg method");
}
void m1(int i)
{
[Link]("int-arg method");
full stack java batch-21 Page 3
[Link]("int-arg method");
}
void m1(int i, int j){
[Link]("2 arg int method");
}
void m1()
{
[Link]("hello");
}
public static void main(String [] args)
{
Overloading ob=new Overloading1();
ob.m1('a');
ob.m1(10);
ob.m1(10,20);
ob.m1();
}
}
output:
D:\>java Overloading
Char-arg method
int-arg method
2 arg int method
hello
Constructor overloading
The constructors are having same name but different arguments list such type of
constructors are called as overloaded constructors
class Main1
{
Main1()
{
[Link]("0-arg constructor");
}
Main1(int i)
{
[Link]("1-arg constructor");
full stack java batch-21 Page 4
[Link]("1-arg constructor");
}
Main1(char ch,int i)
{
System .[Link] ("Constructor with different data types");
}
public static void main(String[] args){
Main1 ob1=new Main1();//calling of zero argument constructor
Main1 ob2=new Main1(10);//calling of one argument constructor
Main1 ob3=new Main1('a',100);//calling of two argument constructor
}
}
output:
D:\>java Main1
0-arg constructor Tomorrow there is a class
1-arg constructor Monday there is no class
Constructor with different data types
2444
4
output:
3
import [Link].*;
import [Link].*;
one operator can act as more than one form is called as operator overloading. The only one
operator overloaded in java is '+'
class Operator
{
public static void main(String[] args)
full stack java batch-21 Page 2
public static void main(String[] args)
{
String str1="java";
String str2="Programming";
[Link](str1);
[Link](str2);
[Link](str1+str2);
int a=10;
int b=20;
[Link](a);
[Link](b);
[Link](a+b);
}
}
output:
D:\>java Operator
java
Programming
javaProgramming
10
20
30
Runtime polymorphism
Method overriding
If same methods with same name are present both in parent class and child class then parent
class method is overrided by child class method
In overriding concept the child class and parent class method signatures must be same
otherwise we will get compilation error
[Link]
class PClass
{
void m1()
{
full stack java batch-21 Page 3
{
[Link]("I am learning python programming");
}
void m2()
{
[Link]("I am learning ui programming");
}
}
output:
Multithreading
1) Whenever we are calling [Link]() method, the jvm search for the start() in the child
class but the start() is not present in the child class so jvm goes to the parent class
and will call Thread class and search for start() method
2) In the Thread class start() method is available hence jvm is executing start()
method
3) Whenever the thread class start() method is executed , it is responsible to register
the child class inside the Thread Scheduler and the start() will call the run()
4) Finally the run() automatically executed whenever we are calling start()
5) wheneve we are giving a chance to the thread class start() then only a new thread
will be created
D:\>java Threadprogram
main Thread
main Thread
main Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
main Thread
main Thread
main Thread
main Thread
User defined Thread
User defined Thread
User defined Thread
main Thread
main Thread
main Thread
full stack java batch-21 Page 2
main Thread
User defined Thread
User defined Thread
D:\>java Threadprogram
main Thread
main Thread
main Thread
main Thread
User defined Thread
User defined Thread
main Thread
User defined Thread
main Thread
main Thread
User defined Thread
User defined Thread
main Thread
User defined Thread
User defined Thread
User defined Thread
main Thread
User defined Thread
main Thread
User defined Thread
D:\>java Threadprogram
main Thread
main Thread
main Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
main Thread
main Thread
main Thread
User defined Thread
main Thread
main Thread
main Thread
full stack java batch-21 Page 3
main Thread
main Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
D:\>java Threadprogram
main Thread
main Thread
main Thread
main Thread
User defined Thread
main Thread
User defined Thread
main Thread
User defined Thread
User defined Thread
main Thread
User defined Thread
main Thread
User defined Thread
User defined Thread
main Thread
User defined Thread
main Thread
User defined Thread
User defined Thread
D:\>javac [Link]
D:\>java Threadprogram
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
full stack java batch-21 Page 4
User defined Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
output:
D:\>java Threadprogram
User defined Thread
User defined Thread
User defined Thread
full stack java batch-21 Page 5
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
D:\>java Threadprogram
main Thread
User defined Thread
main Thread
User defined Thread
main Thread
User defined Thread
main Thread
User defined Thread
main Thread
main Thread
User defined Thread
main Thread
User defined Thread
main Thread
User defined Thread
main Thread
User defined Thread
main Thread
User defined Thread
User defined Thread
1)New
2)Ready
3)Running State
4)Blocked state/Wating state/non-running state
5)Dead state
New state
Ready state
[Link]()
Running state
If the thread scheduler allocate cpu memory for particular thread, then Thread goes
to running state.
Blocked state
If the running thread goes to the sleeping state then the thread is said to be in
blocked state
Dead state
If the logic execution of a thread program is completed , that means the execution of
run() is completed then our thread program reaches to a dead state
Thread methods
getName()
class Threadprogram1
{
public static void main(String[] args)
{
MyThread t=new MyThread();
[Link]();
for(int i=0;i<10;i++)
{
[Link]("main Thread");
}
[Link]([Link]());
}
}
output
D:\>java Threadprogram1
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
User defined Thread
main Thread
main Thread
main Thread
main Thread
Thread-0
setName()
The setName() is used to change the name of the thread inside the Thread scheduler
full stack java batch-21 Page 2
The setName() is used to change the name of the thread inside the Thread scheduler
Example
class Threadprogram1
{
public static void main(String[] args)
{
MyThread t=new MyThread();
[Link]();
for(int i=0;i<10;i++)
{
[Link]("main Thread");
}
[Link]("codingbrains")
[Link]([Link]());
}
}
output:
D:\>java Threadprogram1
main Thread
main Thread
User defined Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
main Thread
codingbrains
Every Thread in java has some priority. it may be default priority by JVM or we
can provide customized priority
The valid range of thread priority is 1-10 where 1 is the lowest priority and 10 is the
highest priority
class Threadprogram1
{
public static void main(String[] args)
{
MyThread t=new MyThread();
[Link]();
[Link](10);
for(int i=0;i<10;i++)
{
[Link]("main Thread");
}
}
}
class Threadprogram1
{
public static void main(String[] args)
{
MyThread t=new MyThread();
[Link]();
[Link](5);
for(int i=0;i<10;i++)
{
[Link]("main Thread");
}
}
}
activeCount()
The activeCount() method of Thread class is used to return the number of active
threads of the current thread group.
class Threadprogram1
{
public static void main(String[] args)
{
MyThread t=new MyThread();
[Link]();
[Link]([Link]());
}
full stack java batch-21 Page 5
}
}
output:
D:\>java Threadprogram1
2
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
sleep():
The sleep() method causes the current Thread to sleep for a specified amount of time
in milliseconds
[Link](3000);
[Link]("user defined Thread");
}
}
}
class ThreadMain
{
public static void main(String[] args)
{
Thread t1=new Thread1();
[Link]();
}
}
D:\>javac [Link]
[Link]: error: unreported exception InterruptedException; must be caught
or declared to be thrown
[Link](3000);
^
1 error
join()
activecount()
Interface
Files
enum
collections
oracle
ui
isAlive():
This method checks whether the Thread is present in the Thread Scheduler or not and
returns the boolean value as output
class ThreadMain
{
public static void main(String[] args)
{
Thread1 t1=new Thread1();
[Link]();
[Link]([Link]());
}
}
output:
D:\>java ThreadMain
true
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
full stack java batch-21 Page 1
User defined Thread
D:\>javac [Link]
[Link]: error: ';' expected
[Link]("main thread")
^
[Link]: error: reached end of file while parsing
}
^
2 errors
D:\>javac [Link]
[Link]: error: reached end of file while parsing
}
^
1 error
D:\>javac [Link]
D:\>java ThreadProgram
main thread
main thread
User defined Thread
User defined Thread
main thread
User defined Thread
main thread
User defined Thread
main thread
User defined Thread
User defined Thread
main thread
User defined Thread
User defined Thread
User defined Thread
main thread
main thread
User defined Thread
main thread
full stack java batch-21 Page 3
main thread
main thread
D:\>java ThreadProgram
main thread
User defined Thread
main thread
User defined Thread
main thread
User defined Thread
main thread
User defined Thread
main thread
main thread
User defined Thread
User defined Thread
User defined Thread
main thread
main thread
User defined Thread
main thread
User defined Thread
main thread
User defined Thread
D:\>java ThreadProgram
main thread
main thread
main thread
main thread
main thread
main thread
main thread
User defined Thread
main thread
User defined Thread
main thread
User defined Thread
main thread
User defined Thread
User defined Thread
User defined Thread
User defined Thread
full stack java batch-21 Page 4
User defined Thread
User defined Thread
User defined Thread
User defined Thread
D:\>
package p1;
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
package p1;
full stack java batch-21 Page 5
package p1;
import [Link];
import [Link];
isHidden()
public class File1 {
public static void main(String[] args) throws IOException{
File f=new File("D:/TestFiles1/[Link]");
if([Link]());
[Link]();
[Link]([Link]());
}
}
package p1;
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
import [Link];
output:
getName()
package p1;
import [Link];
import [Link];
import [Link];
[Link]
[Link]
[Link]
[Link]
package p1;
import [Link];
import [Link];
full stack java batch-21 Page 4
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
import [Link];
import [Link];
[Link]
[Link]
[Link]
package p1;
import [Link];
full stack java batch-21 Page 2
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
import [Link];
import [Link];
[Link] java
enum [Link] java
collections [Link]
oracle [Link]
ui==>html, css, bootstrap
3 projects
github deploy
ui
database
advance java java
resume preparation
portfolio website
github customization
linkedin optimization
class TestEnum{
enum Day{
SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY
}
D:\>javac [Link]
D:\>java TestEnum
It's Friday!,Time to enjoy
Array:
In java, an array holds a fixed number of values of a single Type, arrays are used to store
multiple values in a single variable,
class DayArrayExample{
"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY
full stack java batch-21 Page 1
String[] days={
"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY
","SATURDAY"
};
String today=days[5];
if([Link]("FRIDAY")){
[Link]("It's Friday!,Time to enjoy");
}else if([Link]("MONDAY")){
[Link]("Back to work");
} else{
[Link]("Just another day...");
}
}
}
D:\>java DayArrayExample
It's Friday!,Time to enjoy
class DayArrayExample{
"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SA
TURDAY"
};
String today=days[7];
if([Link]("FRIDAY")){
[Link]("It's Friday!,Time to enjoy");
}else if([Link]("MONDAY")){
[Link]("Back to work");
} else{
[Link]("Just another day...");
}
}
}
D:\>javac [Link]
Enum will give compile time errors, Array will give only run time errors
valueOf()
class EnumInput{
enum Day{
SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY
}
public static void main(String[] args){
Scanner s=new Scanner([Link]);
[Link]("Enter the day of the week:"); friday
String input=[Link]().trim().toUpperCase(); friday
try{ friday
Day today=[Link](input); //Convert string to enum constant
switch(today){
case MONDAY:
[Link]("Back to Work!");
break;
case FRIDAY:
[Link]("It is a friday,time to enjoy");
break;
default:
[Link]("Just another day");
}
}catch(IllegalArgumentException e){
[Link]("Invalid Day [Link] try again");
}
}
}
The valuOf method in enum is a built in method in the Enum class , It is used to
convert a string data into corresponding enum constant
compareTo()
In java, the compareTo method is predefined from Enum class, and it is used to
full stack java batch-21 Page 3
In java, the compareTo method is predefined from Enum class, and it is used to
compare two enum constants based on their ordinal values( i.e., their position in the
enum definition)
enum Day{
SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY
}
class EnumCompareExample{
public static void main(String[] args)
{
Day day1=[Link]; result=[Link]()-[Link]()
Day day2=[Link]; =1-5
int result=[Link](day2); =-4
if(result==0){
[Link]("Both days are same");
}else if(result<0){
[Link]("Day 1 comes before day2");
}else{
[Link]("Day 1 comes after day 2 in the enum");
}
}
[Link](result);
}
}
D:\>java EnumCompareExample
Day 1 comes before day2
-4
values()
enum Day{
SUNDAY,
MONDAY, alldays=[
TUESDAY, SUNDAY,
WEDNESDAY, MONDAY,
THURSDAY, TUESDAY,
FRIDAY, WEDNESDAY,
SATURDAY THURSDAY,
} FRIDAY,
class EnumExample{ SATURDAY]
public static void main(String[] args){
Day allDays[]=[Link]();
for(Day x:allDays){
[Link](x);
}
}
}
output:
D:\>javac [Link]
D:\>java EnumExample
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
ordinal()
The ordinal() in enum is used to retrieve the position of an enum constant in its enum
declaration, starting from 0 for the first constant, 1 for the second, and so [Link] is
full stack java batch-21 Page 1
declaration, starting from 0 for the first constant, 1 for the second, and so [Link] is
predefined method.
enum Day{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
class EnumExample{
public static void main(String[] args)
{
Day day1=[Link];
Day day2=[Link];
[Link]([Link]());
[Link]([Link]())
}
}
D:\>java EnumExample
0
3
An array is a fixed size , ordered collection of elements that are of the same data type,
stored in continous memory [Link] element is accessed using index, starting
from 0
Fixed array
Arrays have fixed length, once created you cannot grow or shrink them dynamically
collections dynamic resizing
int numbers[]={10,20,30,40}
for(int i=0;i<[Link];i++)
{
[Link](numbers[i])
}
add()
remove()
contains()
clear()
[Link]
[Link]
full stack java batch-21 Page 1
[Link]
[Link]
[Link]
[Link]
[Link] List
package p1;
import [Link];
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");
[Link]("Orange");
[Link]("First Fruit:"+[Link](0));
[Link]("Size:"+[Link]());
[Link]("Capacity:"+[Link]());
if([Link]("Grapes")) {
[Link]("Banana is in the list.");
}
//Remove an element
[Link]("Apple");
[Link]("After removing Apple:" +fruits);
}
full stack java batch-21 Page 1
}
}
output:
package p1;
import [Link];
[Link](10);
[Link](20);
[Link](30);
[Link](40);
if([Link](20)) {
[Link]("The vector contains 20");
}
[Link]([Link](20));//Removes 20
[Link]("Vector after removing 20:" +numbers);
full stack java batch-21 Page 2
[Link]("Vector after removing 20:" +numbers);
[Link](1,25);//Adds 25 at index 1
[Link]("Vector after adding 25 at index 1:" +numbers);
[Link]();
[Link]("Vector after clearing all elements:"+numbers);
}
}
output:
A vector is a class in java that implements the List interface provides growable
array of objects
package p1;
import [Link];
package p1;
import [Link];
package p1;
import [Link];
package p1;
import [Link];
package p1;
import [Link];
import [Link];
at V1/[Link]([Link])
Iterator:
The iterator interface is part of [Link] package, it provides methods to iterate over a
collection(such as list,set,queue)
package p1;
import [Link];
import [Link];
ArrayList
=========
When you create an arraylist without specifying the capacity, java initializes it with a
default capcity of 10
Quiz application
=============
package p1;
import [Link];
import [Link];
int score=0;
for(int i=0;i<[Link]();i++) {
[Link]("Q" + (i+1) + ":" + [Link](i));
[Link]("Your answer: ");
String userAnswer=[Link]();
if([Link]([Link](i))) {
[Link]("Correct ✅");
score++;
}else {
[Link]("Wrong ❌. Correct answer:" +[Link](i));
}
}
}
}
Quiz Applications
package p1;
import [Link].*;
int score=0;
for(int i=0;i<[Link]();i++) {
[Link]("Q" + (i+1) + ":" + [Link](i));
[Link]("Your answer: ");
String userAnswer=[Link]();
if([Link]([Link](i))) {
[Link]("Correct ✅");
score++;
}else {
[Link]("Wrong ❌. Correct answer:" +[Link](i));
}
}
//Final Score
LinkedList
A linked list in java is a linear data structure that stores elements in non contiguous
memory locations. Each element( called as node) contains two parts
import [Link];
[Link]("Hyderabad");
[Link]("Delhi");
[Link]("Mumbai");
[Link]("Bangalore"); //Adds at Beginning
[Link]("Chennai"); //Adds at Last
[Link]("Cities:" +cities);
//Access by index
[Link](3);
[Link]("Ater removing index 3:" +cities);
[Link]();
[Link]();
Todo application
package p1;
import [Link];
import [Link];
do {
[Link]("\n TO-DO LIST MENU");
[Link]("1. Add Task");
[Link]("2. View Tasks");
[Link]("3. Remove Task");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
[Link](); // consume newline
switch (choice) {
case 1:
[Link]("Enter the task: ");
String x = [Link]();
[Link](x);
[Link]("✅ Task added!");
break;
case 2:
[Link]("\n Your Tasks:");
if([Link]()) {
[Link]("No tasks found");
}else {
full stack java batch-21 Page 1
}else {
for(int i=0;i<[Link]();i++) {
[Link]([Link](i));
}
}
break;
case 3:
[Link]("Enter the task number to remove:");
int taskNum=[Link]();
if(taskNum<=[Link]()) {
[Link](taskNum);
[Link]("❌ Task removed.");
}
}
}while(choice!=4);
}
}
To do list:
package p1;
import [Link];
import [Link];
do {
[Link]("\n TO-DO LIST MENU");
[Link]("1. Add Task");
[Link]("2. View Tasks");
[Link]("3. Remove Task");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
[Link]();
switch (choice) {
case 1:
[Link]("Enter the task: ");
full stack java batch-21 Page 1
[Link]("Enter the task: ");
String x = [Link]();
[Link](x);
[Link]("✅ Task added!");
break;
case 2:
[Link]("\n Your Tasks:");
if([Link]()) {
[Link]("No tasks found");
}else {
for(int i=0;i<[Link]();i++) {
[Link]([Link](i));
}
}
break;
case 3:
[Link]("Enter the task number to remove:");
int taskNum=[Link]();
if(taskNum<[Link]()) {
[Link](taskNum);
[Link]("❌ Task removed.");
}else {
[Link]("⚠ Invalid task number.");
}
break;
case 4:
[Link](" Exiting... Have a productive day!");
break;
}
}while(choice!=4);
}
}
set
A set in java is a collection that doesnot allow duplicate elements. It is a part of java collections
frame work
Interfaces in java cannot be instantiated directly, we must use a class that implements
the set [Link] interface is implemented in Hashset class
package p1;
import [Link];
[Link]("Cat");
[Link]("Dog");
[Link]("Elephant");
[Link]("Cat");
[Link](animals);
}
}
output:
[Cat, Elephant, Dog]
package p1;
import [Link];
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Apple"); //Duplicate, will be ignored
[Link](set);
if([Link]("Apple")) {
[Link]("Apple is in the set");
}else {
[Link]("Banana");
[Link](set);//Output:[Apple,Orange]
if([Link]("Mango")) {
[Link]("Mango was removed");
}else {
[Link]("Mango was not found in the set");
}
if([Link]()) {
[Link]("The set is empty");
}else {
[Link]("The set is not empty");
}
[Link]();
[Link](set);
output:
[Apple, Orange, Banana]
Apple is in the set
Size of the set:3
[Apple, Orange]
Mango was not found in the set
The set is not empty
[]
Size of the set after clearing:0
package p1;
import [Link];
import [Link];
}
[Link]("Current Registered Users:" +usernames);
[Link]("---------------------------------------");
}
[Link](" Final list of registered usernames:" +usernames);
}
}
output:
Method Description
add(e) Adds element to the queue
poll() Removes and returns head
peek() Returns head without
removing
output:
package p1;
import [Link];
import [Link];
package p1;
import [Link];
import [Link];
while(![Link]()) {
String customer=[Link]();//Retrieves and removes the head
[Link](customer + " is being Served a ticket");
[Link]("Queue after serving:" +ticketQueue);
}
[Link]("All customers are served");
}
}
package p1;
import [Link];
output:
Example overview:
Features:
Program:
import [Link];
import [Link];
import [Link];
int choice=[Link]();
[Link]();
switch(choice) {
case 1:
[Link]("Enter Caller Name:");
String caller=[Link]();
[Link](caller);
[Link]("Call from "+caller +" added to Queue");
break;
case 2:
if(![Link]()) {
String served=[Link]();
[Link]("Serving call from: " + served);
}else {
[Link]("No calls to serve");
}
break;
case 3:
[Link]("Current Waiting Calls: " +callQueue);
break;
case 4:
running=false;
[Link]("Exiting [Link]!");
break;
}
}
}
}
Hashmap
A Hash map is a part of java collections framework and is used to store data in key-
value pairs. It is one of the most commonly used classes for insertion and deletes
package p1;
import [Link];
output:
{1=One, 20=Twenty, 5=Five, 10=Ten, 15=Fifteen}
Treemap
A Treemap is a class in java , and it is a part of collection framework, it stores key-
value pairs in a ascending order of keys
package p1;
import [Link];
PhoneBook
package p1;
import [Link];
//Adding Contacts
[Link]("Suresh", "9898981234");
[Link]("kishore", "9898981235");
[Link]("kumar", "9898981236");
String searchName="sai";
if([Link](searchName)) {
[Link]("Found " + searchName + ":" +[Link](searchName));
} else {
full stack java batch-21 Page 2
} else {
[Link](searchName + " not found in phoneBook");
}
//Remove Contact
[Link]("Suresh");
[Link]("After removing Suresh:");
[Link](phoneBook);
}
}
output:
PhoneBook Contacts
Suresh-9898981234
kishore-9898981235
kumar-9898981236
sai not found in phoneBook
After removing Suresh:
{kishore=9898981235, kumar=9898981236}
retainAll()
The retainAll() method is used to modify a set by keep only elements that are
present in both the sets
package p1;
import [Link];
import [Link];
Integer[] array1={1,2,3,4};
Integer[] array2={2,3,5};
//Step 2: Create two Hashsets and add elements from the arrays
for(Integer x:array1){
[Link](x);
}
[Link](set2);
}
}
output:
Common elements:[2, 3]
{1,2,3,4}
set1=[1,2,3,4]
import [Link].*;
You are given a list of ages of several individuals. Your task is to count the number of
individuals in each age group. Age groups are defined as follows:
0-9 (inclusive)
10-19 (inclusive)
20-29 (inclusive)
30-39 (inclusive)
40-49 (inclusive)
50 and above
Solution:
import [Link].*;
for(int i=0;i<n;i++)
{
[Link]([Link]());
}
[Link]("0-9",0);
full stack java batch-21 Page 1
[Link]("0-9",0);
[Link]("10-19",0);
[Link]("20-29",0);
[Link]("30-39",0); [
[Link]("40-49",0); ("0-9",1),
[Link]("50+",0); ("10-19",1),
("20-29",1),
//Classify each age into its respective ("30-39",1),
("40-49",1),
for(int age:ages){ ("50+",1)
if(age>=0 && age<=9){ ]
[Link]("0-9",[Link]("0-9")+1);
}else if(age>=10 && age<=19){ age=5
[Link]("10-19",[Link]("10-19")+1);
}else if(age>=20 && age<=29){
[Link]("20-29",[Link]("20-29")+1);
}else if(age>=30 && age<=39){
[Link]("30-39",[Link]("30-39")+1);
}else if(age>=40 && age<=49){
[Link]("40-49",[Link]("40-49")+1);
}else if(age>=50){
[Link]("50+",[Link]("50+")+1);
}
}
for([Link]<String,Integer>entry:[Link]()) {
[Link]([Link]());
}
}
}
[Link]