Overview of Java Development Kit
Overview of Java Development Kit
stands for java runtime environment and JVM stands for java virtual [Link] provides
all the tools to work with java language.
JRE:-JRE stands for Java runtime environment its provide an environment to execute the
java [Link] internally contains JVM which is responsible to execute a java program.
(X)JVM:-JVM stand for java virtual machine it is the software in the form of interpreter
witter in “C” language through which we can execute our java programs.
JVM+libery
JRE JRE=JVM+libary
JDK JDK=JRE+JVM(library)
Q. What is java?
[Link] is a class based high level object oriented programming language developed by
“James gosling” and his friend in the year 1991.
The first version of java(jdk 1.0)was released
on the year 23 rd jun,1996 by sun micro system.
[Link] of java?.
Java is a totally computer based programming language developed by “sun micro
system”.
In the year 1991 “James gosling” and his friend start a project.
Team->Green talk
James gosling->greentalk
Extension-> .gt
Greentalk->Oak(rename)
Oak- Oak technology
National tree(USA,France etc)
Oak-Java(1995)
Java-setbox,television,remote etc.
Java-Internate programming
Version-JDK alpha & Beta,1995 (By sun micro system)
Lates version-JDK 15(2020,oracle)
[Link]-oracle car portion,2010.
JAVA
output
JVM memory
[Link] is comment?
[Link] are the statement that are totally ignored by the compiler and interpreter.
[Link] we used comment?
Ans.1)The comments can be used to provide explanation about the program.
2) Comment makes program more understandable and readable to the other.
Type:-I)Single line comment//. . . . //
Ii)Multilevel line comment/*. . . . */
Ii)Documentation comment/**. . . .*/
[Link] type java:- Data type specify the different sizes and values that can be stored in
the variable.
Data type
Syntex:- class A
{
Int a ;//instance variable
}
3)Static variable:-A variable which is declared with the help of static keyword called static
variable.
Syntax- static int x;
Ex 1. class A
{
static int b=20; //static
int c=30; //instance
Ex-2
class A
{
static int b=10; //static
void fun()
{
int b=10;
[Link](a+" "+b);//10
++a;
++b;//11
}
public static void main(String[ ],args)
{
A r=new A();
[Link]();
[Link]();
}
}
output- 10 10
11 10
Ex-3
class
{
public static void main(String args[])
{
int a=10,b=20;
[Link]("sum="+(a+b));
}
}
output- sum =30
[Link] is Type casting?
[Link] casting is nothing but converting one data type to another data type is called
type casting.
Type casting
Implicit Explicit
1) Implicit type casting:- It is automatically performed by the compiler.
Ex- class
{
public static void main(String args[ ])
{
int a=10; //4 byte
double b=a; // 8 byte
[Link](b)
} } output-10.0
2) Explicit type casting:-By default the compiler,doesn’t allow the explicit type casting.
Ex-
class A
{
public static void main(Strings args[])
{
double a=10.5;
int b=(int) a;
[Link](b);
}
}
output -10.
[Link](scanner class):- Scanner is predefined class in java which is available a
[Link]. It is used to get user input.
Rule:- 1)If we use scanner class ,must have to create object of scanner class.
Syntex object_name=new Scanner([Link]);
2 ) Scanner class method-
1) nextLine(); : String
2) nextInt(); :Integer
3) nextFloat(); :Floating
4) nextBoolean(); : True or false
5) nextDouble(); : Double
3) Import Scanner class package at the top line of program:
Syntex: import [Link] Scanner;
4) Wrong Input (Input mismatch Exception)
[Link]([Link]()):- It is an output statement in java through which we can
point the variable,expression and many more context.
Syntex:- 1) pre defined class
2) [Link] package.
out in
System
Exapmle-class A
{
public static void main(String args[])
{
float a;
[Link]("Enter data");
Scanner obj=new Scanner([Link]);
a=[Link]();
[Link]("Get data",+a);
}
}
output-Enter data
get data 1.00
User Input-
import [Link];
class Userinput
{
public static void main(String args[])
{
int a, b;
Scanner obj=new Scanner([Link]);
[Link]("Enter value");
a=[Link]();
b=[Link]();
[Link](a+" "+b);
}
}
[Link] is token?
[Link] is the smallest element of a program that is identified by a compiler. Every java
statement and expression are created using token.
Token type- keyword identifier operater separater literal .
Example-
class A
{
public static void main(String args[])
{
int a=10;
b=20;
int c=a+b;
[Link](c);
}
}
*** 1)Keyword- int,static,void
50 - 2 unused
48
2)Identifier:- Variable,method,class_name.
3) Operator:-+,-,*,/,%,&&,||,++,--.
4) Separate:-; , . : () {}
5) Litreral
Q.1)What is keyword?
[Link]’s are the reserved word whose meaning is already defined in the compiler
called keyword.
Note - * (not used)
**(Added in 1.2V)
***(Added in 1.4V)
****(Added in 5.0V) 50 keyword --- 2 unused
48 keyword are used
Java key words:-
Int continue instanced super boolean
Short break interface this abstract
Byte dafault native switch case
Long double new synchronized catch
If extends package throw class
Else implement private throws const*
For final protected try goto*
While finally public transient strictfp****
Do float return void enum***
Char import static volatile assert
T,F and null just like keyword ,but they are actually literals.
2)identifiers:-
[Link] is identifier?
[Link] java, on identifier is the name of the a variable ,method,class,package or interface
that is used for the purpose of identification.
Example-
Note: -
1)Keyword can’t be used as a identifier.
2Identifier are case -sensitive.
3) We can’t use white space in between identifier.
4) Identifier always starts with letter $(dollar)
Or- . ex- int a.23;
Int _a;
Int $ a;
[Link] is Operater?
[Link] is a symbol that is used to perform operation according to user
requirement(Variable and Values).
Operater Type-
1)Arithmetic(+,-,*,%, -)
2) Relational(<,>,<=,>=,=!,==)
3) Logical(&&,||,!)
4) Increment and Decrement operater
Pre increment : ++I
Post increment: I++
Pre Decrement: --I
Pre Decrement: I--
5) Assigment simple: (=)
Component(+=,-=,*=,etc)
6) Ternary operater(? :)
7) Bitwise(AND,OR,XOR,complement)
[Link] operater example.
Ans.
import [Link].*;
class A {
public static void main(String[] args) {
int a, b;
[Link]("Enter two num");
Scanner obj = new Scanner([Link]);
a = [Link]();
b = [Link]();
[Link]("add = " + (a + b));
[Link]("sub = " + (a - b));
[Link]("multi = " + (a * b));
[Link]("div = " + (a / b));
[Link]("modul = " + (a % b));
}
}
Enter two num 5 6
add = 11
sub = -1
multi = 30
div = 0
modul = 5
[Link] operation example.
import [Link].*;
class A {
public static void main(String[] args) {
int a, b;
[Link]("Enter two num");
Scanner obj = new Scanner([Link]);
a = [Link]();
b = [Link]();
[Link]("true/false " + (a > b));
[Link]("true/false " + (a < b));
[Link]("true/false " + (a <= b));
[Link]("true/false " + (a >= b));
[Link]("true/false " + (a == b));
[Link]("true/false " + (a != b));
}
}
[Link] operater example.
Ans.
import [Link].*;
class Logical {
public static void main(String[] args) {
[Link]("logical AND");
[Link]((10 > 5) && (2 > 1));
[Link]((10 > 5) && (2 < 1));
[Link]((10 < 5) && (2 < 1));
[Link]("Logical OR");
[Link]("logical Not");
[Link](!(10 > 5));
[Link](!(10 < 5));
}
}
[Link]/Decrement operater example:-
import [Link].*;
class A {
public static void main(String[] args) {
int a = 10;
[Link](a);
[Link]("pre,post inrement..");
[Link](a++);
[Link](++a);
Output-AND 5
OR 0
XOR 2
Complement -6
Decision Making.
class Simple {
public static void main(String[] args) {
int age;
[Link]("Enter your age");
Scanner r = new Scanner([Link]);
age = [Link]();
if (age >= 18) {
[Link]("Eligible for votes..");
}
[Link]("Thank you..");
}
}
example end
import [Link];
class Simple {
public static void main(String[] args) {
int n;
[Link]("Enter any nuber");
Scanner r = new Scanner([Link]);
n = [Link]();
if (n >= 0)
[Link]("+ve number");
else
[Link]("-ve number");
}
}
R. If else if ladder statement:-If is used when we have only one if is used when we have
only one if block ,multiple else if blocks and at lost one else block.
Syntex:- flowchart
If(condition) start
{
} condition true if st
.elseif(condition)
{ false
} condition true else if st
.elseif(condition)
{ false
} condition true else if st
.else
{ false false
} st
end
Example-
import [Link];
class Ladder {
public static void main(String[] args) {
int marks;
[Link]("Enter marks");
Scanner ref = new Scanner([Link]);
marks = [Link]();
if (marks > 80) {
[Link]("Topper");
} else if (marks < 80 && marks >= 60) {
[Link]("first");
} else {
[Link]("second");
}
}
}
[Link] if else statement:-Whenever use define if else block,inside this if else block use
define another if else block is called Nested if else statement.
Syntex:-.. flowchart
if()
{ start
if()
{ Condition F Condition
}
Else T T F
{
} Condition F Nested nested
} if statement else st
else
{
if() T
{
}
Else Nested if st Nested else
statement
{
} end
}
Example-
import [Link];
class Nested {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
if (a > b) {
if (a > c) {
[Link](a);
} else {
[Link](c);
}
} else {
if (b > c) {
[Link](b);
} else {
[Link](c);
}
}
}
}
[Link] statement:-switch is a multiple choice decision making selection statement,it
used when we want to select only one case out of multiple cases.
Syntex:- flowchart
switch(Exp)
{ start
case 1:Statement 1;
break; switch(condition)
case 2:Statement 2;
break; case 1 true st 1 break
case n:Statement n;
break; false
default: Statement ;
} case 2 true st 2 break
Default true st
end
Example-
import [Link];
class Switch {
public static void main(String[] args) {
int a = 10, b = 20, ch;
[Link]("Enter user choice");
Scanner r = new Scanner([Link]);
ch = [Link]();
switch (ch) {
case 1:
[Link]("sum " + (a + b));
break;
case 2:
[Link]("sub " + (a - b));
break;
case 3:
[Link]("Multi " + (a * b));
break;
case 4:
[Link]("Div " + (a / b));
break;
default:
[Link]("Invalid choice...!");
}
[Link]("out of switch....!");
}
}
Looping Statement:-whenever we have to repeat certain statement several times is called
[Link]:-
Start
Loop statement
Condition true
False
end
Advantage:-I)Fast execution
Ii)Reusability
Iii)Decrease loc(line of code)
iV)Memory less
Type:-
i. While
ii. Do-while
iii. For loop
iv. For each loop
1) While loop:-while loop is a pre test loop,it is used when we don’t know that no of
iteration .In advance.
It is also known as entry control loop.
Syntax:-
1. while (condition){ Flowchart
2. //code to be executed
3. Increment / decrement statement
4. }
Example:-10 time print
import [Link];
class While {
public static void main(String[] args) {
int n = 1;
while (n <= 10) {
[Link]("hellllo");
n++;
}
}
}
Example 2:-Infinite time print
import [Link];
class While {
public static void main(String[] args) {
int n;
[Link]("Enter value ");
Scanner ref = new Scanner([Link]);
n = [Link]();
while (n >= 0) {
[Link]("Learn coding");
}
}
}
2)Do-while loop:-Do while loop is a post test loop,it is used when we want to execute loop body at
least once even condition is [Link] is also know as exit.
Systex-
Example-
import [Link].*;
class Dowhile {
public static void main(String[] args) {
int n = 1;
do {
[Link](n + " ");
n++;
} while (n < 10);
}
}
2) For loop:-For loop is the most commonly used loop it is used when we want to perform
initialization,condition and increment/decrement operation in single line.
It is also called entry control loop.
Syntax: Flowchart
Example:-
import [Link].*;
class For {
public static void main(String[] args) {
int i;
for(i=1;i<10;i++)
{
[Link](i+" ");
}
}
}
Reverse: for(int I=10;I>=1;I--)
4)For each loop:For each loop mainly used to fetch the values from a collection like array.
Syntax: Floachart
.for(data type var1:var2)
{
}
Example:
import [Link].*;
class For_each {
public static void main(String[] args) {
int a[] = { 10, 20, 30, 40, 50 };
for (int b : a) {
[Link](b + " ");
}
} }
5) Nested for loop:-A for loop which contain inside another for loop is called nested for
loop.
Q. Odd/Even number print ?
import [Link].*;
class Oddeven {
public static void main(String[] args) {
int n;
[Link]("Enter any number: ");
Scanner ref = new Scanner([Link]);
n = [Link]();
if (n % 2 == 0) {
[Link]("Even number");
} else {
[Link]("Odd number");
}
}
}
[Link] of two number ?
import [Link].*;
class Add{
public static void main(String[] args) {
int a, b, sum;
[Link]("Enter two num..");
Scanner ref = new Scanner([Link]);
a = [Link]();
b = [Link]();
sum = a + b;
[Link]("Add :" + sum);
}
}
[Link] N natural”Number.
import [Link].*;
class Natural {
public static void main(String[] args) {
int n, i;
[Link]("Enter [Link] term");
Scanner r = new Scanner([Link]);
n = [Link]();
for (i = 1; i < n; i++) {
[Link](i + " ");
}
}
}
Enter [Link] term
5
1234
Q.”Sum of first N natural “Number?
import [Link].*;
class Sum {
public static void main(String[] args) {
int n, i, sum = 0;
[Link]("Enter two digit");
Scanner r = new Scanner([Link]);
n = [Link]();
for (i = 1; i < n; i++) {
sum = sum + i;
}
[Link]("Add " + sum);
}
}
[Link] “odd number”in given range.
import [Link].*;
class Odd {
public static void main(String[] args) {
int n, i;
[Link]("Enter no of term");
Scanner r = new Scanner([Link]);
n = [Link]();
for (i = 1; i < n; i = i + 2)
[Link](i);
}
}
[Link]”Even number”in given range…
import [Link].*;
class Odd {
public static void main(String[] args) {
int n, i;
[Link]("Enter no of term");
Scanner r = new Scanner([Link]);
n = [Link]();
for (i = 0; i < n; i = i + 2)
[Link](i);
}
}
class Calculate {
public static void main(String[] args) {
int n1, n2, ch, cal;
[Link]("Enter two number");
Scanner r = new Scanner([Link]);
n1 = [Link]();
n2 = [Link]();
[Link]("select operation");
ch = [Link]();
if (ch == 1) {
cal = n1 + n2;
[Link]("Addition" + cal);
} else if (ch == 2) {
cal = n1 - n2;
[Link]("Subtraction" + cal);
} else if (ch == 3) {
cal = n1 * n2;
[Link]("Multiplication" + cal);
} else if (ch == 4) {
cal = n1 / n2;
[Link]("Division" + cal);
} else {
cal = n1 % n2;
[Link]("Remainder" + cal);
}
}
}
[Link] of rectangle program..
import [Link].*;
class Rectangle {
public static void main(String[] args) {
int l, b, area;
[Link]("Enter value for sides");
Scanner r = new Scanner([Link]);
l = [Link]();
b = [Link]();
area = l * b;
[Link]("Area of rectangle " + area);
}
}
[Link] of circle program.
import [Link].*;
class Area {
public static void main(String[] args) {
final double PI = 3.14, area;
int r;
[Link]("Enter radius of circle");
Scanner ref = new Scanner([Link]);
r = [Link]();
area = PI * r * r;
[Link]("Area of circle " + area);
}
}
[Link] of Square program.
import [Link].*;
class Square {
public static void main(String[] args) {
int n, area;
[Link]("Enter side square");
Scanner r = new Scanner([Link]);
n = [Link]();
area = n * n;
[Link]("Area of square " + area);
}
}
[Link] of triangle program.
Ans.
[Link] in java.
import [Link].*;
class Swap {
public static void main(String[] args) {
int a, b, temp;
[Link]("Enter two number");
Scanner r = new Scanner([Link]);
a = [Link]();
b = [Link]();
[Link]("Before swapping " + a + " " + b);
temp = a;
a = b;
b = temp;
[Link]("After swapping " + a + " " + b);
}
}
[Link] without using 3rd variable in java.
import [Link].*;
class Swap {
public static void main(String[] args) {
int a, b;
[Link]("Enter two number");
Scanner r = new Scanner([Link]);
a = [Link]();
b = [Link]();
[Link]("Before swapping " + a + " " + b);
a = a + b;
b = a - b;
a = a - b;
[Link]("After swapping " + a + " " + b);
}
}
[Link] character lower to upper in java
import [Link];
import [Link].*;
class lower {
public static void main(String[] args) {
char ch;
int ascii;
Scanner ref = new Scanner([Link]);
[Link]("Enter a character in lowercase: ");
ch = [Link]().charAt(0);
ascii = ch;
ascii = ascii - 32;
ch = (char) ascii;
[Link]("Equivalent character in Uppercase=" + ch);
}
}
[Link] number is positive or negative.
import [Link].*;
class Check {
public static void main(String[] args) {
int n;
[Link]("Enter any number");
Scanner a = new Scanner([Link]);
n = [Link]();
if (n > 0) {
[Link]("+ve number");
} else if (n < 0) {
[Link]("-ve number ");
} else {
[Link]("Neither +ve nor -ve number");
}
}
}
[Link] year program.
import [Link].*;
class Leapyear{
public static void main(String[] args) {
int y;
[Link]("Enter any number");
Scanner a = new Scanner([Link]);
y = [Link]();
if(y%100==0 && y%400==0||y%100!=0 && y%4==0)
{
[Link]("Leap year");
}
else{
[Link]("Not leap year");
}
}
}
[Link] to check Divisibility of 5.
import [Link].*;
class Divisible {
public static void main(String[] args) {
int n;
[Link]("Enter any number");
Scanner r = new Scanner([Link]);
n = [Link]();
if (n % 5 == 0) {
[Link]("DIvisible by 5");
} else {
[Link]("not divisible by 5");
}
}
}
[Link] code of day and print name of day then weekend.
Ans.
import [Link].*;
class Divisible {
public static void main(String[] args) {
int n;
[Link]("Enter any number");
Scanner r = new Scanner([Link]);
n = [Link]();
switch (n) {
case 1:
[Link]("Sunday");
break;
case 2:
[Link]("Monday");
break;
case 3:
[Link]("Tuesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Satarday");
break;
}
}
}
[Link] factor of a number .
import [Link].*;
import [Link].*;
class Fact {
public static void main(String args[]) {
Scanner s = new Scanner([Link]);
int a, fact = 1, i;
[Link]("Enter any number");
a = [Link]();
for (i = 1; i <= a; i++) {
fact = fact * i;
}
[Link]("Fact of " + a + "=" + fact);
}
}
[Link] month number and print number of day in a month.
import [Link].*;
class Month {
public static void main(String[] args) {
int n;
[Link]("Enter any number");
Scanner r = new Scanner([Link]);
n = [Link]();
if (n == 1) {
[Link]("jan = 31 days");
} else if (n == 2) {
[Link]("Feb=28 days");
} else if (n == 3) {
[Link]("march=31 days");
} else if (n == 4) {
[Link]("April=29 days");
} else if (n == 5) {
[Link]("May=31 days");
} else if (n == 6) {
[Link]("Jun=30 days");
} else if (n == 7) {
[Link]("July=30 days");
} else if (n == 8) {
[Link]("August=31 days");
} else if (n == 9) {
[Link]("September=30 days");
} else if (n == 10) {
[Link]("October=29 days");
} else if (n == 11) {
[Link]("November=31 days");
} else if (n == 12) {
[Link]("December= 31");
} else {
[Link]("Invalid month number");
}
} }
[Link] number program
import [Link].*;
class Reverse {
public static void main(String[] args) {
int n, r;
[Link]("Enter any number");
Scanner ref = new Scanner([Link]);
n = [Link]();
while (n > 0) {
r = n % 10;
[Link](r + " ");
n = n / 10;
}
}
}
[Link] of digits
import [Link].*;
class Sum {
public static void main(String[] args) {
int n, r,sum=0;
[Link]("Enter any number");
Scanner ref = new Scanner([Link]);
n = [Link]();
while (n > 0) {
r = n % 10;
sum=sum+r;
n = n / 10;
[Link]("Sum of digits"+sum);
}
}
}
[Link] Number.(121)
import [Link].*;
class Palindrom {
public static void main(String[] args) {
int n, r, c, s = 0;
[Link]("Enter any number.." + " ");
Scanner ref = new Scanner([Link]);
n = [Link]();
c = n;
while (n > 0) {
r = n % 10;
s = (s * 10) + r;
n = n / 10;
}
if (c == s)
[Link]("palindrome number");
else
[Link]("Not palindrom number");
}
}
[Link] number program.(153)
import [Link].*;
class Armstrong {
public static void main(String[] args) {
int n, c, arm = 0, rem;
[Link]("Enter any number.." + " ");
Scanner ref = new Scanner([Link]);
n = [Link]();
c = n;
while (n > 0) {
rem = n % 10;
arm = (rem * rem * rem) + arm;
n = n / 10;
}
if (c == arm)
[Link]("Armstrong number");
else
[Link]("Not Armstrong number");
}
}
Q***.Find square root of a number
import [Link].*;
class Squareroot {
public static void main(String[] args) {
int n;
[Link]("Enter any number.." + " ");
Scanner ref = new Scanner([Link]);
n = [Link]();
double m = [Link](n);
[Link]("Square root of " + n + " is " + m);
}
} output-Enter any number.. 16
Square root of 16 is 4.0
[Link] numebr.
import [Link].*;
class Prime{
public static void main(String[] args) {
int n, i, count = 0;
[Link]("Enter any number.." + " ");
Scanner ref = new Scanner([Link]);
n = [Link]();
for (i = 1; i <= n; i++) {
if (n % i == 0) {
count++;
}
}
if (count == 2)
[Link]("prime number");
else
[Link]("Not prime number");
}
}
[Link] number.
import [Link].*;
class Perfect{
public static void main(String[] args) {
int n, i, sum = 0;
[Link]("Enter any number.." + " ");
Scanner ref = new Scanner([Link]);
n = [Link]();
for (i = 1; i <= n; i++) {
if (n % i == 0) {
sum=sum+i;
}
}
if(n==sum)
[Link]("perfect number");
else
[Link]("Not perfect number");
}
}
[Link] between two number.
Ans.
[Link] of Variable Declaration:-
1)The name of the variable is the combination of character(A to Z or a to Z)number
(0 to 9)and two special symbol such as underscore(-) and dollar(&).
Example-int A; int-a;int $;int a2;
2)Varibale name always maintains in the left hand side of assignment operator.
Example-int a=10;
3)First character of variable name must be a letters or underscore or dollar($)
Example-int a; int _a; int $ a;
4)Their should be no blanks between the name of the variable.
Example- int su_m=10 X
5)Except underscore(-)we can’t use any special symbol in the middle of variable
Example-int su_m=10;
6)variable are cause sensitive in java .
Example-int AB=10; [Link](ab) X
7)You can’t use any keywords as a variable name.
Example-int int =10 X
Syntax-data type var_name=value;
Int var _name=10;
Example:-
import [Link].*;
class A {
public static void main(String[] args) {
int a = 10;
[Link](a);
int _b = 20;
[Link](_b);
int $c = 30;
[Link]($c);
int a1 = 40;
[Link](a1);
class D {
public static void main(String[] args) {
int size;
Scanner r = new Scanner([Link]);
[Link]("Enter size of array: ");
size = [Link]();
int a[] = new int[size];
for (int i = 0; i < size; i++) {
a[i] = [Link]();
}
[Link]("Printed array element");
for (int i = 0; i < size; i++) {
[Link](a[i] + " ");
}
}
}
Output-Enter size of array: 3
20 10 30
Printed array element
20 10 30
import [Link].*;
import [Link].*;
class D {
public static void main(String[] args) {
int a[] = new int[5];
int i, n, count = 0;
Scanner r = new Scanner([Link]);
[Link]("Enter element in array: ");
for (i = 0; i < [Link]; i++) {
a[i] = [Link]();
}
[Link]("Array element: ");
for (i = 0; i < [Link]; i++) {
[Link](a[i] + " ");
}
[Link]("Enter the search element");
n = [Link]();
for (i = 0; i < [Link]; i++) {
if (a[i] == n) {
count++;
}
}
if (count > 0) {
[Link]("item found" + count + "time");
} else {
[Link]("item not found");
}
}
}
Output-Enter element in array: 5 6 7 8 9
Array element: 5 6 7 8 9
Enter the search element: 1
item not found
[Link] average of array element.
import [Link].*;
class D {
public static void main(String[] args) {
int a[] = new int[5];
int i, sum = 0;
double avg;
Scanner r = new Scanner([Link]);
[Link]("Enter array element:");
for (i = 0; i < 5; i++) {
a[i] = [Link]();
}
[Link]("Array element: ");
for (i = 0; i < 5; i++) {
[Link](a[i] + " ");
}
for (i = 0; i < 5; i++) {
sum = a[i] + sum;
}
avg = sum / 5.0;
[Link]("\nAddition" + sum + "\nAverage" + avg);
}
}
Output-Enter array element:1 2 3 4 5 6 7
Array element: 1 2 3 4 5
Addition15
Average3.0
[Link] array element in ascending order.
import [Link].*;
import [Link].*;
class D {
public static void main(String[] args) {
int a[] = new int[5];
int i, j, temp;
Scanner r = new Scanner([Link]);
[Link]("Enter array element: ");
for (i = 0; i < 5; i++) {
a[i] = [Link]();
}
for (i = 0; i < 5; i++) {
for (j = i + 1; j < 5; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (i = 0; i < 5; i++) {
[Link](a[i] + " ");
}
}
}Output:-Enter array element: 8 4 2 9 3 0
23489
[Link] array element in descending order.
import [Link].*;
import [Link].*;
class D {
public static void main(String[] args) {
int a[] = new int[5];
int i, j, temp;
Scanner r = new Scanner([Link]);
[Link]("Enter array element: ");
for (i = 0; i < 5; i++) {
a[i] = [Link]();
}
for (i = 0; i < 5; i++) {
for (j = i + 1; j < 5; j++) {
if (a[i] < a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (i = 0; i < 5; i++) {
[Link](a[i] + " ");
}
}
}
Output-Enter array element: 8 3 9 2 4 3
98432
[Link] sort () method .
import [Link].*;
import [Link].*;
class D {
public static void main(String[] args) {
int a[] = new int[5];
Scanner r = new Scanner([Link]);
[Link]("Enter any element: ");
for (int i = 0; i < [Link]; i++) {
a[i] = [Link]();
}
[Link](a);
for (int i = 0; i < [Link]; i++) {
[Link](a[i] + " ");
}
}
}
Output-Enter any element: 3 9 2 7 1 8
12379
Matrix
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int m, n;
class Mirror {
public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Please enter the rows(r) and columns(c): ");
int r = [Link]();
int c = [Link]();
int array[][] = new int[r][c];
int newArray[][] = new int[r][c];
for (int i = 0; i < r; i++) {
[Link]("Enter thr rows " + (i + 1) + ":");
for (int j = 0; j < c; j++) {
array[i][j] = [Link]();
}
}
[Link]("The user input array is:");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
[Link](array[i][j] + "\t");
}
[Link]();
}
for (int j = 0; j < c; j++) {
for (int i = 0; i < r; i++) {
newArray[i][c - 1 - j] = array[i][j];
}
}
[Link]("Mirror Image of the Given Array is:");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
[Link](newArray[i][j] + "\t");
}
[Link]();
}
}
}
[Link] is Method ?
[Link] is a group/block of code which take input from the user,processed it and
give output
Note:-method runs only when it called
Method
Predefind Userdefined
Print(); Add()
Sort(); Sub()
Sqrt(); M1()
nextInt(); Show()
Syntex: return_type method_name(parameters list)
{
//body of the method
Return value;[optimal]
}
[Link] we use method ?
Ans.1)Decrease LOC(Line of code)
3) Redability
4) Repeatation
import [Link].*;
class Fun {
int n1, n2;
int Add, sub, multi, div, rem;
public static void main(String[] args) {
Fun ref = new Fun();
[Link]();
[Link]();
[Link]();
}
void input() {
Scanner r = new Scanner([Link]);
[Link]("Enter two number: ");
n1 = [Link]();
n2 = [Link]();
}
void process() {
Add = n1 + n2;
sub = n1 - n2;
multi = n1 * n2;
div = n1 / n2;
rem = n1 % n2;
}
void output() {
[Link]("Add of 2 number: " + Add);
[Link]("\nSub of 2 num: " + sub);
[Link]("\nMulti of 2 number:" + multi);
[Link]("\nDiv of 2 number:" + div);
[Link]("\nRem of 2 number:" + rem);
}
}Output-Enter two number: 3 4
Add of 2 number: 7
Sub of 2 num: -1
Multi of 2 number:12
Div of 2 number:0
Rem of 2 number:3
[Link] is Recursion ?
Ans.A method that calls itself is called recursive method,and this technique in known
as recursion.
Syntex- return _type method_name( - - - ) Argument
{
methodName(- - - ) Argument
}
Recursion in java
Example-1
import [Link].*;
import [Link].*;
class Itself {
public static void main(String[] args) {
Itself r = new Itself();
int a = [Link](3);
[Link]("Sum 1st n natural num: " + a);
}
int sum(int b) {
if (b > 0) {
return b + sum(b - 1);
} else {
return 0;
}
}
}Output-Sum 1st n natural num: 6
Example-2 Factorial using recursion.
import [Link].*;
class A {
public static void main(String[] args) {
int n;
[Link]("Enter any number");
Scanner r = new Scanner([Link]);
n = [Link]();
A obj = new A();
int result = [Link](n);
[Link]("Factorial of given number: " + result);
}
int fact(int n) {
if (n == 1)
return 1;
else
return n * fact(n - 1);
}
}Output-Enter any number :5
Factorial of given number: 120
String
[Link] is string ?
[Link] strings are object that allows us to store sequence of character which may
contain alpha numeric values enclosed in double quotes (“Deb”);
Note:-1)String are immutable in java.
3) It contains methods that can perform certain operation an strings(con
cat(),equal(),length(),etc……
There are two ways to create string object- 1)String literal 2)new keyword
2) New keyword:
String a=new String(“java”); String [Link]
A. concat(“python”); java python
String a=”java” Heap Memory
String Example- Concatenate
import [Link].*;
import [Link].*;
class A
{
public static void main(String[] args) {
String a="java";
[Link](a);
String b="Python";
[Link](b);
a=[Link](" "+" HTML");
[Link](a);
}
}Output-java
Python
java HTML
Or,
import [Link].*;
import [Link].*;
class A {
public static void main(String[] args) {
String a = new String("java");
[Link](a);
String b = new String("HTML");
[Link](b);
a = [Link](" " + "python");
[Link](a);
}
}Output-java
HTML
java python
[Link]([Link](a));
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link](2));
[Link]([Link]("V"));
[Link]([Link](a));
[Link]([Link]('C', 'S'));
}
}
Output-java
PYHTON
pyhtonJAVA
6
HTLM
false
h
2
false
S++
[Link] reverse in java ?
import [Link].*;
import [Link].*;
class A {
public static void main(String[] args) {
StringBuffer r = new StringBuffer("JAVA");
[Link]([Link]());
StringBuilder ref = new StringBuilder("Python");
[Link]([Link]());
}
}Output-AVAJ
nohtyP
Or,
import [Link].*;
import [Link].*;
class A {
public static void main(String[] args) {
int i, l;
String r = "JAVA";
String r2 = "";
l = [Link]();
for (i = l - 1; i >= 0; i--) {
r2 = r2 + [Link](i);
}
[Link](r2);
}
}Output-AVAJ
class A {
public static void main(String[] args) {
String str;
char ch[];
Console obj = [Link]();
[Link]("Enter username: ");
str = [Link]();
[Link]("Enter password");
ch = [Link]();
String a = [Link](ch);
[Link]("Username: " + str);
[Link]("Password:" + ch);
}
}
Q. JAVA Python
1)Java is compiled language 1)Python is a interpreted language
5)It has large no of fram works. 5)It has lower no of frame works.
7)Example- 7)Example-print(“python”);
class A
{
Public static void main(String []args);
{
[Link](“Java);
}
}
[Link] is BLC?
Ans:If we have a class but inside a class we don’t have main method then that class is
called business logic class.
Example-
class Amazon class Flipcart
{ {
--
} }
Note-We can use above BLC class in our all project(ELC)
[Link] is ELC?
[Link] we write the main method inside a class then the class is called executable
logic class.
Example-
class user1
{
Public static void main(String[] args)
{
//Here BLC is accessible
}
Example-//file 1
class amazon {
int a, b, c, d;
void input() {
a = 20;
b = 10;
}
void show() {
c = a + b;
d = a - b;
[Link](c + " " + d);
}
}
//file 2
class flipkart {
int a, b, c, d;
void input() {
a = 20;
b = 10;
}
void show() {
c = a * b;
d = a / b;
[Link](c + " " + d);
}
}
//file 3
class sana {
public static void main(String[] args) {
int n = 30, m = 90;
int rem = n % m;
[Link](rem);
[Link] is OOP ?
[Link] stands for object oriented programming language the main purpose of OOP
is to deal with real world entity using programming language.
OOPs Features:-
Class
Object
Inheritance
Polymorphism
Encapsulation
Abstraction
[Link] is class ?
[Link] is a collection of object and it doesn’t take any space on memory,class is
also called as blueprint/logical entity.
Class
[Link] is Constructor ?
[Link] is a special type of method whose name is same as class name.
Type of constructor
Private Copy
Default
Parameterized
[Link] is Default constructor ?
Ans.A constructor which does not have any parameter is called constructor.
Syntax-
class A
{ No any parameter
A()
{
}
}
Example-
import [Link].*;
import [Link].*;
class Computer {
int Ram, Rom;
Computer() {
Ram = 4;
Rom = 512;
}
public void display() {
[Link]("Ram:" + Ram + "GB");
[Link]("Rom:" + Rom + "GB");
}
public static void main(String[] args) {
Computer r = new Computer();
[Link]();
}
}Output-Ram:4GB
Rom:512GB
class A
{
int a;String b;
A()
{
a=10;b="JAVA";
[Link](a+" "+b);
}
A(A ref)
{
a=ref.a;
b=ref.b;
[Link](a+" "+b);
}
}
class B
{
public static void main(String[]args)
{
A r=new A();
A r2=new A(r);
}
}
Output-
10 JAVA
10 JAVA
[Link] is private constructor ?
[Link] java it is possible to write a constructor as a private but according to rule we
can’t access private member outside of class.
Example-
class class_name
{
Private class_name()
{
}
}
Example-import [Link].*;
import [Link].*;
class A {
int a;
double b;
String c;
private A() {
a = 10;
b = 89.980;
c = "java";
[Link](a + " " + b + " " + c);
}
Syntex-
class A
{
{
//code
}
}
Example-import [Link].*;
import [Link].*;
class A {
int a, b;
static void show() {
[Link]("java");
}
A() {
a = 30;
b = 40;
[Link](a + " " + b);
}
{
a = 10;
b = 20;
[Link](a + " " + b);
}
}
class b {
public static void main(String[] args) {
A r = new A();
[Link]();
}
}Output-10 20
30 40
Java
[Link] is Static block ?
[Link] block is such kind of block in java which gets executed at the time of
loading the .class file into JVM memory.
A. Java
Class loader
Javac Byte code verifier
Execution engine
[Link] JVM
Syntex-
Class A
{
static
{
}
}
Example-
import [Link].*;
import [Link].*;
class A {
public static void main(String[] args) {
A r = new A();
}
static {
[Link]("java");
}
}Output- java
Q. Instance vs static block
[Instance block-Without obj run hobe na]
import [Link].*;
import [Link].*;
class A {
public static void main(String[] args)
{
A r = new A(); // obj
}
{
[Link]("java");
}
A() {
[Link]("Python");
}
}Output-java
Python
[Static block-class er sathe deal kore obj na dileo Run hobe]
import [Link].*;
import [Link].*;
class A {
static {
[Link]("HTML");
}
public static void main(String[] args) {
}
}
2) Executed at the time of object creation 2)Executed at the time of loaded .class file
In java
3) No any keyword required 3)Static keyword is required
4) Static and non static variable can be 4)Only static variable can be accessed inside
Accessed inside the instance block. The static block.
[Link] is inheritance ?
Ans:-when we construct a new class from existing class in such a way that the new
class access all the features and proper of existing class called inheritance.
}
Class B extends A
{
}
Types:-1)Simple/simple inheritance:-
Syntax 2
Sub 2+1=3
2)Multi-level inheritance :-
Super
Sub 1
Sub 2
Sub 3
3)Multiple inheritance ( java support kore na)
Super 1 Super 2
sub
4)Hierarchical inheritance :-
Super
} Sub class
Class sub extends super
{
}
Example-
import [Link].*;
import [Link].*;
class student {
int roll, marks;
String name;
void input() {
[Link]("Student roll,name and marks: ");
}
}
class sana extends student {
void disp() {
roll = 1;
name = "sana";
marks = 100;
[Link](roll + " " + name + " " + marks);
}
public static void main(String[] args) {
sana r = new sana();
[Link]();
[Link]();
}
}Output:Student roll,name and marks: 1 sana 100
}
Class sub1 extends super
{
}
Class sub2 extends sub1
{
}
Example-
class A{
void msg()
{
[Link]("Hello");}
}
class B{
void msg()
{
[Link]("Welcome");}
}
class C extends A,B{
public static void main(String args[]){
C obj=new C();
[Link]();
}
}
Example-Multiple inheritance using interface in java.
import [Link].*;
import [Link].*;
interface A {
void Show();
}
interface B {
void Disp();
}
class C extends A,B
{
public void Show()
{
[Link]("Interface A ");
}
public void Disp() {
[Link]("Interface B");
}
public static void main(String[] args) {
C m = new C();
[Link]();
[Link]();
}
}
[Link] java doesn’t support multiple inheritance ?
[Link] a sub class wants to inherit the property of two or more super classes that have same
[Link] compiler can,t describe which class method is should inherit.
Then their might be a chance of memory duplication I.e a reason java doesn’t support multiple
inheritance through classed.
[Link] inheritance :-A inheritance which contain only one super class and multiple sub class
and all sub class directly extends super class called hierarchical inheritance.
Syntax- Super
Class A
{ sub 1 sub 2 sub 3
}
Class B extend A / class C extends A
{ {
} }
Example- Class A
{
public void methodA()
{
[Link]("Super class method");
}
}
Class B extends A
{
public void methodB()
{
[Link]("Sub class Method B");
}
}
Class C extends A
{
public void methodC()
{
[Link]("Sub class Method C");
}
public static void main(String args[])
{
A obj1 = new A();
B obj2 = new B();
C obj3 = new C();
[Link](); //calling super class method
[Link](); //calling A method from subclass object
[Link](); //calling A method from subclass object
}
}
[Link] keyword:-Super keyword refers to the objects of super class it is used when we
want to call the super class variable,method and constructor through sub class object.
Note-1)Whenever the super class and sub class variable and method name both are same than it can
be used only.
2)To avoid the confusion between super class and sub classes variable and methods that have same
name we should use super keyword.
Super
Variable constructor
Method
Super keyword Syntax:-
class A //super class
{
A()
{
}
}
class B extends A //sub class
{
B()
{
}
}
Example-Super keyword called
class A {
int a = 10;
class B extends A {
int a = 20;
}
void show() {
[Link](a);
[Link](super.a);
}
}
class Test {
public static void main(String[] args) {
B r = new B();
[Link]();
}
}
Example-In constructor super keyword use.
class A {
A(int a) {
[Link]("Java" + a);
}
}
class B extends A {
B() {
super(30);
[Link]("python");
}
}
class Test {
public static void main(String[] args) {
B r = new B();
}
}
[Link] is this keyword ?
Ans.1)This keyword refers to the current object inside a method or constructor.
Example-class A
{
void show()
{
[Link](this);
}
public static void main(String[] args) {
A r=new A();
[Link](r);
[Link]();
}
}
2)Whenever the name of instance and local variable both are same then our runtime
environment JVM gets confused that which one is local variable and which one is
instance variable ,to avoid this problem we should use this keyword.
Example-class A
{
Int a //instance
A(int a) //local
{
a=a;
[Link](a);
}
}
Example- Method overloading : whenever a class contain more than one method with
same name and different types of parameters called method overloading.
Syntex- return type method-name(para 1);
Return type method-name(para, para);
Example-
class A {
int Add() {
int a = 10, b = 20, c;
c = a + b;
return c;
}
void add(int x, int y) {
int c;
c = x + y;
[Link](c);
}
void add(int x, double y) {
double c;
c = x + y;
[Link](c);
}
public static void main(String[] args) {
A r = new A();
[Link]();
[Link](100, 200);
[Link](50, 45.32);
int add = [Link]();
[Link](add);
}
}
[Link] is run time polymorphism ?
Ans.A polymorphism which exists at the time of execution of program is called runtime
polymorphism.
Overridden or not
Yes No
Example-
import [Link].*;
import [Link].*;
class shape {
void draw() {
[Link]("can't say shape type");
}
}
class square extends shape {
@Override
void draw() {
[Link]();
[Link]("Square shape");
}
}
class Demo {
public static void main(String[] args) {
shape r = new square();
[Link]();
}
}
}
2)It may or may not contain abstract method.
3)It can have abstract and non abstract methods.
4)To use an abstract class you have to inherit it from sub classes.
5)If a class contain partial implementation than we should declare a class as abstract.
Example-abstract class A
{
Abstract void m1();
}
Class A
{
}
Public void m1()
{
}
Input
Output
Client interface Developer
[Link] Introduction Example:
import [Link].*;
import [Link].*;
interface Client {
void Input(); // public+abstract
void Output(); // public+abstract
}
class Raju implements Client {
String name;
double sal;
public void Input() {
Scanner r = new Scanner([Link]);
[Link]("Enter username: ");
name = [Link]();
[Link]("Enter salary: ");
sal = [Link]();
}
public void Output() {
[Link](name + " " + sal);
}
public static void main(String[] args) {
Client c = new Raju();
[Link]();
[Link]();
}
}Output-Enter username:Debraj
Enter salary:30,000
Debraj 30000.0
Interface Variable:-
import [Link].*;
import [Link].*;
interface CustomerRaj {
int amt = 5;
void purchase();
}
class SellerChotu implements CustomerRaj {
@Override
public void purchase() {
[Link]("Raj needs" + amt + "kg rice");
}
}
class Check {
public static void main(String[] args) {
CustomerRaj c = new SellerChotu();
[Link]();
[Link]([Link]);
}
}Output-Raj needs5kg rice 5
Interface Method:-
import [Link].*;
import [Link].*;
interface Client {
void Webdesign();
void Webdevelope();
}
abstract class RajTech implements Client {
@Override
public void Webdesign() {
[Link]("Green ,top menu,three dot button");
}
}
class RahuleTech extends RajTech {
@Override
public void Webdevelope() {
[Link]("HTML,CSS,JAVASCRIPT");
}
}
class Check {
public static void main(String[] args) {
RahuleTech r = new RahuleTech();
[Link]();
[Link]();
}
}Output-Green ,top menu,three dot button
HTML,CSS,JAVASCRIPT
[Link] inheritance using interface ?
Ans:We can achieve multiple inheritance through interface because interfaces because
interface contains only abstract method,which implementation is provide by the sub
classes.
Note-Class C extends A,B
Class C implement A,B
Example-
import [Link].*;
import [Link].*;
class A {
void show() {
[Link]("This is class A");
}
}
class B {
void show() {
[Link]("This is class B");
}
}
interface A {
void show();
}
interface B {
void show();
}
class Multiple implements A, B {
public void show() {
[Link]("Interface A & B");
}
public static void main(String[] args) {
Multiple m = new Multiple();
[Link]();
}
}
Example Extending Interface:
import [Link].*;
import [Link].*;
interface Gill {
void add();
}
interface Raj extends Gill {
void sub();
}
class Ankit implements Raj {
@Override
public void add() {
int a = 10, b = 20, c;
c = a + b;
[Link]("Addition" + c);
}
@Override
public void sub() {
int a = 10, b = 20, c;
c = a - b;
[Link]("Subtraction" + c);
}
}
class Main {
public static void main(String[] args) {
Raj r = new Ankit();
[Link]();
[Link]();
}
}Output-Addition30
Subtraction-10
Final keyword in java
[Link] is final ?
[Link] is a modifier which provides restriction in java we can we final in three
way- Final
@Override
void atmPIN() {
[Link]("8944");
}
}
class Final {
public static void main(String[] args) {
Thief t = new Thief();
[Link]();
[Link]();
}
}
[Link] is new Keyword ?
[Link] keyword creates new objects and it is used to allocate dynamic memory at
runtime.
Syntax-
Class A
{
//data
//method
}
A r=new A();
[Link];
[Link]
Usage- 1)call interface variable and non static method .
2)Call constructor.
3)Array
Example:-
import [Link].*;
import [Link].*;
class newKeyword {
public static void main(String[] args) {
int i, size;
[Link]("Enter array size: ");
Scanner r = new Scanner([Link]);
size = [Link]();
int a[] = new int[size];
[Link]("Enter array element : ");
for (i = 0; i < size; i++) {
a[i] = [Link]();
}
[Link]("Array element:");
for (int m : a) {
[Link](m + " ");
}
}
}Output-Enter array size: 3
Enter array element : 2 3 4
Array element:2 3 4
[Link] is Exception ?
Ans.A exception is unexception/unwanted/abnormal situation that occurred at
runtime called exception.
Example-1)File not found Exception 2)Power cat Exception 3) Ill-exception
Runtime Exception:
Arithmetic Exception
Mill pointer Exception
Number format exception
Index out of Bands exception
Array index out bound Exception
String index out of bound Exception
I/O Exception:
EDE Exception
File not found exception
Example- Test .java(source code)
Javac
[Link]
JVM Exception/error
import [Link].*;
import [Link].*;
class D {
public static void main(String[] args) {
String str = null; // sana
try {
[Link]([Link]());
} catch (NullPointerException n) {
[Link]("null can't be casted");
}
}Output-SANA
} [Link] can't be casted
Example:
import [Link].*;
import [Link].*;
class D {
public static void main(String[] args) {
String str = "123";//sana
try {
int a = [Link](str);
[Link](a);
} catch (NumberFormatException n) {
[Link]("String " + str + " can't be converted to integer");
}
[Link]("Main method ended");
}
}Output-123
Main method ended
Or,String sana can't be converted to integer
Main method ended
Execution No
yes
Ignore the rest code ignore catch
of try block block
Finally
end
Example- Try,catch,finally
import [Link].*;
import [Link].*;
class Handling {
public static void main(String[] args) {
try {
[Link]("XYZ \n");
int a = 20, b = 2, c;
c = a / b;
[Link](c);
[Link]("HTML");
} catch (ArithmeticException a) {
[Link]("Can,t divided by zero");
} finally {
[Link]("JAVA");
}
[Link]("Main method ended");
}
}
Output-XYZ or,XYZ
10 Can,t divided by zero
HTML JAVA
JAVA Main method ended
Main method ended
Q.
} catch (ArithmeticException a) {
[Link]("Can,t divided by zero");
}
try {
int a[] = { 10, 20, 30, 40 };
[Link](a[5]);
} catch (ArrayIndexOutOfBoundsException b) {
[Link]("Beyond the array limit");
}
}
}Output-Can,t divided by zero or,5
Beyond the array limit Beyond the array limit
.
Throwable
Exception Error
StackoverFlow Error
Runtime Exception VertualMachineError
Arithmetic Exception OutfMemoryError
Nullointer Exception Unchecked IDError
Number formet Exception Exception
1) IO Exception
2) InterruptedException EX
3) SQL Exception
[Link] is package ?
Ans.A package average number of classes interfaces and sub package of same type
into a particular group.
Note- Package is nothing but folder in windows.
Types
Package
3) [Link]:IO stands for input/output this package is very useful perform I/o
operation on [Link]-File,File Writer,File Reader etc. Ex-File, File writer,file
Reader etc.
5) [Link]:awt stands for abstract window tool kit. It is also web to develop GUI
application the only difference between applet and awt program is,awt programs are
stand alone program and it contain main() unlike applet,
Example- Frame,Bottom,TextFeild etc.
import [Link];
import [Link].*;
import [Link].*;
class FileReader {
public static void main(String[] args) {
try {
file r = new file("C:\\Users\\Windows 10\\Desktop\\[Link]");
Scanner sc = new Scanner(r);
while ([Link]()) {
[Link]([Link]());
}
} catch (IOException e) {
[Link]("Exception Handled");
}
}
}
[Link] is user defined package ?
[Link] package which are created by java program or user for their own use are
called used defined package.
Syntax-Package package-name;
Rule-1)Package statement must be first line of the program.
2) The way of compilation of there classes would be different .
Example-Java [Link] [Link]
Member accessibility:-
//file 1
import [Link].*;
//package sana;
class A {
protected void show() {
[Link]("JAVAAA");
}
}
class B extends A {
public static void main(String[] args) {
A r = new A();
[Link]();
}
}
//file 2
class A {
protected void show() {
[Link]("JAVAAA");
}
}
//file 3
import [Link].*;
package D;
import sana.A;
class C extends A {
public static void main(String[] args) {
C r = new C();
[Link]();
}
}
File 1
import [Link].*;
//package sana;
public class A {
public void show() {
[Link]("saAVAAA");
}
}
//file 2
import [Link].*;
//package D;
import sana.A;
class C {
public static void main(String[] args) {
A r = new A();
[Link]();
}
}
[Link] is Multi threading ?
[Link] threading is a process to execute multiple threads at the same time
without dependency of other threads called multithreading.
[Link] is thread ?
[Link] is a pre defined class which is available in [Link] package.
Thread is a basic unit of CPU and it is well known for independent execution
}
}
}
class B {
public static void main(String[] args) throws InterruptedException {
A t = new A();
[Link]();
for (int i = 1; i <= 5; i++) {
[Link]("Pythonn");
[Link](1000);
}
}
}
[Link] imlementing Runnable interface
Ans.
import [Link].*;
import [Link].*;
class A implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("My child thread");
}
}
}
class B {
public static void main(String[] args) {
A r = new A();
Thread t = new Thread(r);
[Link]();
for (int i = 1; i <= 5; i++) {
[Link]("main thread");
}
}
}
[Link] is thread scheduler ?
[Link] scheduler is the part of JVM which executes multiple threads on a single
processor randomly.
Example-
import [Link].*;
import [Link].*;
class A extends thread {
public void run() {
String n = [Link]().getName();
for (int i = 1; i <= 3; i++) {
[Link](n);
}
}
}
class B {
public static void main(String[] args) {
A t1 = new A();
A t2 = new A();
A t3 = new A();
[Link]("Thread 1");
[Link]("Thread 2");
[Link]("Thread 3");
[Link]();
[Link]();
[Link]();
String n = [Link]().getName();
for (int i = 1; i <= 3; i++) {
[Link](n);
}
}
}
[Link] is life cycle ?
[Link] we know a thread is well known for independent [Link] the file
cycle thread can move from different states.
1) New states(Born)
2) Runnable state(Execution)
3) Running state(Execution)
4) Waiting state(Blocked)
5) Dead state(Exit)
[Link] is synchronized ?
[Link] is a technique through which we can control multiple threads or
among the no of threads only one thread will enter inside the synchronized area.
Thread1(Table t) {
this.t = t;
}
public void run() {
[Link](5);
}
}
class Thread2 extends Thread {
Table t;
Thread2(Table t) {
this.t = t;
}
public void run() {
[Link](7);
}
}
class main {
public static void main(String[] args) {
Table obj = new Table();
Thread1 t1 = new Thread1(obj);
Thread2 t2 = new Thread2(obj);
[Link]();
[Link]();
}
}Output-5 10 15 20 25 30 35 40 45 50 7 14 21 28 35 42 49 56 63 70
[Link] is Synchronized block ?
[Link] block level synchronized the entire method is not get synchronized only the
part of the method get synchronized we have to enclosed those few lines of the code
put inside synchronized block.
Example-
import [Link].*;
import [Link].*;
class msg {
public synchronized void show(String name) {
;;;;;;
for (int i = 1; i <= 3; i++) {
[Link]("How are you:" + name);
}
;;;;;;
}
}
class OurThread extends Thread {
msg m;
String name;
}
or,
import [Link].*;
import [Link].*;
class msg {
public void show(String name) {
;;;;;;
synchronized (this) {
for (int i = 1; i <= 3; i++) {
[Link]("How are you:" + name);
}
}
;;;;;;
}
}
class OurThread extends Thread {
msg m;
String name;
OurThread(msg m, String name) {
this.m = m;
[Link] = name;
}
public void run() {
[Link](name);
}
}
class D {
public static void main(String[] args) {
msg m = new msg();
OurThread t1 = new OurThread(m, "sana");
OurThread t2 = new OurThread(m, "sara");
[Link]();
[Link]();
}
}
Multithreading problem:-
import [Link].*;
import [Link].*;
class Bank extends Thread {
int bal = 5000;
int withdraw;
Bank(int withdraw) {
[Link] = withdraw;
}
public void run() {
String name = [Link]().getName();
if (withdraw <= bal) {
[Link](name + " withdraw money");
bal = bal - withdraw;
} else {
[Link](" Insuficient balance");
}
}
}
class Customer {
public static void main(String[] args) {
Bank obj = new Bank(5000);
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
[Link]("sana");
[Link]("sara");
Bank obj2 = new Bank();
Thread t3 = new Thread(obj2);
Thread t4 = new Thread(obj2);
[Link]("Bunny");
[Link]("Sunny");
[Link]();
[Link]();
[Link]();
[Link]();
}
}
[Link] with more than one object:As we know every object has a lock,in
java and this lock can,be given to only one thread but if we have multiple objects
then we can also have multiple threads so,again we will got currented data even in
the synchronized area.
Example-
import [Link].*;
import [Link].*;
class Bank extends Thread {
static int bal = 5000;
static int withdraw;
Bank(int withdraw) {
[Link] = withdraw;
}
public static synchronized void withdraw() {
String name = [Link]().getName();
if (withdraw >= bal) {
[Link](name + " withdraw money");
bal = bal - withdraw;
} else {
[Link](" Insuficient balance");
}
}
public void run()
{
withdraw();
}
}
class Customer {
public static void main(String[] args) {
Bank obj = new Bank(5000);
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
[Link]("sana");
[Link]("sara");
Bank obj2 = new Bank();
Thread t3 = new Thread(obj2);
Thread t4 = new Thread(obj2);
[Link]("Bunny");
[Link]("Sunny");
[Link]();
[Link]();
[Link]();
[Link]();
}
}
[Link] is collection ?
[Link] collection are the set of pre defined classes and Interface that helps of
data,structure operator like-”sorting,searching,traversing,storing and processing
data efficient”.
Example-
import [Link].*;
import [Link].*;
class JavaCollection {
public static void main(String[] args) {
ArrayList<String> Name = new ArrayList<String>();
[Link]("Sunny");
[Link]("Sana");
[Link]("Sara");
[Link](Name);
[Link]("Buny");
[Link](Name);
[Link](1, "Sanjana");
[Link](Name);
[Link](0, "Sanjana");
[Link](Name);
}
}
Output-[Sunny, Sana, Sara]
[Sunny, Sana, Sara, Buny]
[Sunny, Sanjana, Sana, Sara, Buny]
[Sanjana, Sunny, Sanjana, Sana, Sara, Buny]
Example2-
import [Link].*;
import [Link].*;
class JavaCollection {
public static void main(String[] args) {
ArrayList<String> Name = new ArrayList<String>();
[Link]("Sunny");
[Link]("Sana");
[Link]("Sara");
[Link](Name);
[Link](0, "Sanjana");
[Link](Name);
[Link]([Link](2));
}
}Output-[Sunny, Sana, Sara]
[Sanjana, Sana, Sara]
Sara
Example-
import [Link].*;
import [Link].*;
class JavaCollection {
public static void main(String[] args) {
ArrayList<String> Name = new ArrayList<String>();
[Link]("Sunny");
[Link]("Sana");
[Link]("Sara");
[Link](Name);
[Link]();
[Link](Name);
}
}Output-[Sunny, Sana, Sara]
[]
Example-
import [Link].*;
import [Link].*;
import [Link].*;
class JavaCollection {
public static void main(String[] args) {
LinkedList<String> Name = new LinkedList<String>();
[Link]("Sunny");
[Link]("Sana");
[Link]("Sara");
[Link](Name);
[Link]("Bunny");
[Link]("Cat");
[Link](Name);
[Link](3, "Khogo");
[Link](Name);
}
}
Output-[Sunny, Sana, Sara]
[Bunny, Sunny, Sana, Sara, Cat]
[Bunny, Sunny, Sana, Khogo, Sara, Cat]
Example-
import [Link].*;
import [Link].*;
import [Link].*;
class JavaCollection {
public static void main(String[] args) {
LinkedList<String> Name = new LinkedList<String>();
[Link]("Sunny");
[Link]("Sana");
[Link]("Sara");
[Link](Name);
[Link]();
[Link](Name);
}
}
Output-[Sunny, Sana, Sara]
[Sunny, Sana]
Multithreading can lead to data consistency issues when multiple threads try to access and modify shared resources simultaneously, resulting in corrupted data or incorrect results. Synchronization in Java is used to address this problem by ensuring that only one thread can access the synchronized block or method at a time. This prevents other threads from entering the synchronized block until the current thread exits, thus maintaining data consistency . Method level synchronization syncs entire methods, whereas block level synchronizes specific sections of code, providing more fine-grained control over code execution .
A 'do-while' loop is preferred over a 'for' loop when the loop body needs to be executed at least once regardless of the condition being true. This is particularly useful in user-driven scenarios, such as menu-driven programs where user input is required at least once before running additional logic. The 'do-while' loop ensures that the loop body executes, checking its condition after and thus allowing post-execution decision making . In contrast, a 'for' loop is used when conditions are set to control entry into the loop from the beginning, allowing a single line syntax for initialization, condition check, and increment/decrement operations .
The isAlive() method plays a crucial role in debugging multithreaded programs by allowing developers to check if a thread has started and is still running. It returns true if the thread has been started and has not yet died, which can help in understanding the concurrent behavior of the program and identifying threads that might be unexpectedly terminating or not starting at all. This method can be used to assert thread liveness at various checkpoints, aiding in the diagnosis of thread lifecycle issues and ensuring that no thread is inadvertently blocked or terminated prematurely .
The 'Thread.sleep' method is used to pause the execution of a thread for a specified duration, effectively placing the thread into a timed waiting state. This can be useful in managing the thread's lifecycle, for example, in simulating delays or pacing executions. When a thread goes into a sleeping state, it temporarily relinquishes control over the CPU, allowing other threads to execute. During this period, the thread retains all of its resources and locks it holds, but it is not runnable until it wakes up after the sleep duration or is interrupted. This method throws an InterruptedException if another thread interrupts the sleeping thread, prompting necessary exception handling .
The 'yield' method in Java allows a currently executing thread to pause and let other threads of the same priority run in its place. By calling 'yield', the thread suggests to the thread scheduler that it is willing to relinquish its current use of CPU resources, giving other threads a chance to execute. However, the actual thread scheduling decision is determined by the thread scheduler, which may or may not give another thread a chance, making it platform dependent. Yield is often used to improve CPU efficiency and promote more cooperative multitasking but doesn't guarantee precise control over thread execution order .
The key difference between the for loop and the do-while loop in Java lies in their execution sequence and condition checking. The for loop is an entry-controlled loop, meaning it checks the condition before executing the loop body. It's used for scenarios where initialization, condition testing, and increment/decrement operations need to be performed in a single line . In contrast, the do-while loop is a post-test loop, executing the loop body at least once before the condition is checked, making it suitable for scenarios where we need the loop to execute at least once regardless of the condition .
Not using synchronization in a Java multithreaded application can lead to race conditions, where two or more threads access shared resources simultaneously, introducing conflicts and data inconsistency. Threads may read stale data, overwrite changes, or leave shared resources in a corrupted state, causing erratic program behavior and making debugging extremely difficult. Without proper synchronization, ensuring atomicity of operations becomes impossible, increasing the risk of serious logical errors and decreasing program reliability . Synchronization mechanisms like synchronized methods and blocks are essential for maintaining data integrity and ensuring correct program execution .
The 'ASCII value of character' program in Java takes a character as input, converts it to its corresponding ASCII integer value, and prints it. This conversion is done using typecasting, where the character data type is cast to an integer type, reflecting its ASCII equivalent. Use cases for this functionality include implementing custom character encoding schemes, debugging character-related operations, or integrating with systems and protocols requiring ASCII values. Additionally, it serves educational purposes for understanding Java's typecasting and the relationship between characters and their ASCII representations .
The 'join' method in Java thread management is used to ensure that a particular thread completes its execution before the rest of the program or certain threads continue execution. It places the current thread into a waiting state until the thread on which 'join' is called finishes executing. This is particularly useful when the outcome of a thread's execution is essential for the subsequent operations . The join method helps in achieving synchronization between threads to correctly sequence the execution of multiple threads .
Method-level synchronization in Java concurrent programming ensures that only one thread can execute a synchronized method at one time. This is critical in preventing data loss because it effectively prevents race conditions, where multiple threads compete to read and modify shared resources simultaneously, potentially leading to inconsistent states and data corruption. By synchronizing whole methods, Java guarantees the atomicity of critical sections of code, ensuring consistent behavior and correctness . This type of synchronization is particularly useful when the entire method operates on shared resources that require coherent access control .