Core Java
Core Java
NOTE:
1. A Java program is also called as source code.
2. All Java program has .Java extension.
3. A Java Program consists of 3 stages:
a. Coding
b. Compilation (Javac followed by program_name or Class_name)
c. Execution (Java followed by program_ name or Class_Name)
4. Java Compiler: It takes the Source file as its input and generates Byte code as an Output.
5. The extension of Byte code is .class
6. Java Compiler checks Syntax error in a Java program, if the program has any error at the
compilation stage-it gives a Compile time error.
7. Java Virtual Machine (JVM): It takes Byte Code as input and generates Machine code as output.
8. JVM is also called as interpreter.
9. Byte code: It is neither in the form of user-understandable nor in the form of binary digits i.e.
machine understandable, so byte code is also called as Intermediate Programming Language. Only
JVM can understand byte code. JAVA only generates Byte Codes.
10. JAVA is both compiled and Interpreted Programming Language.
Components of JAVA:
1. JDK (Java Development tool Kit): It provides a platform or environment to develop Java program.
2. JRE (Java Runtime Environment): It provides a platform or environment to run Java program.
3. JVM (Java virtual Machine): It executes or run the program line by line.
4. JDK = JRE + JVM.
5. JRE = JVM + other files.
JRE
JVM
J
JDK
History of Java:
1. Java was invented by James Gosling and his team.
2. Java was developed by ‘SUN MICROSYSTEM’ in the year 1995.
3. In the year of 2000, Oracle Corporation acquired ‘SUN MICRO SYSTEM’.
4. Earlier name of JAVA is ‘OAK’.
5. According to Sun microsystem Java is categorised into 3 types:
a.J2SE (Java 2 standard edition): It is used to develop Java stand-alone Application.
b.J2EE (Java 2 Enterprise edition)
c. J2ME (Java 2 Micro edition)
Note: J2EE & J2ME are used to develop java web application.
6. Core Java comes under J2SE.
7. Advanced Java comes under J2EE.
8. Framework comes under J2ME.
9. Java version starts from Java 1.0 to Java 1.8(latest).
Installation of JDK
1. Download the JDK software.
2. Double Click on [Link] files.
3. Click on next option.
4. Click on finish.
How to set the path?
1. Go to My computer >> select C drive >> select program files>> select Java >> Select JDK 1.8
>>select bin option.
2. Copy the path.
3. Go to my computer >> Right click >>select properties>> select Advanced system setting.
4. Select Environment variables>> select new.
5. Give the path name as a “Path’’ or “JAVA_HOME”.
6. Click on finish option.
2. class Demo1
{
public static void main (String [] args)
{
[Link](“India\n\tUSA\n\t\tUK”);
}
}
Output: India
USA
UK
Note:
4. class value{
public static void main(String[] args){
int i=20;
[Link]("Value of i is "+i);
}}
Output:
Value of i is 20
[Link] Value{
public static void main(String[] args){
int i=20;
int j=10, k=40;
[Link]("Value of i is "+i+"\nValue of j is "+j+"\nValue of k is "+k);
}}
Output:
Value of i is 20
Value of j is 10
Value of k is 40
6. class Value{
public static void main(String[] args){
int i=20;
int j=10, k=40;
[Link](i+"\n"+j+"\n"+k);
}}
Output:
20
10
40
7. class India
{
public static void main(String[] args)
{
int i=20;
int j=10;
[Link]("I love India "+i+"\n I hate Pakistan "+j+" I love Qspiders");
}}
Output:
I love India 20
I hate Pakistan 10 I love Qspiders
DATA TYPES:
Data type is categorised into 2 types:
1. Primitive Data types: Data type which is supported by programming language is called primitive
data type. It is also called as inbuilt data type or predefined data types.
2. Non Primitive Data types: Data type which is supported by programmer or user is called Non
primitive data type. It is also called as User defined Data type.
Examples: String, class, interface and Arrays
Real Number: It can hold both whole numbers and fractional numbers.
Real number data types are:
a. float (4 bytes)
b. double (8 bytes)
NOTE:
*In Java Programing language Boolean values are either true or false; it shouldn’t be 0 and 1.
*Character values should be enclosed inside single quotes.
*String values should be enclosed inside double quotes.
*Boolean values should be in lower case i.e. true or false not True or False.
*While we are initializing fractional values to the float data type at the end we need to provide ‘f’
character because JVM would treat fractional values as double value by default.
Operators:
These are the symbols used to perform different actions. They are categorized into 5 types.
1. Arithmetic Operator: It is mainly used to perform mathematical operations. These are arithmetic
operators: + , - , * , / , %
2. Relational Operators: It is mainly used to perform comparison operations. These are relational
operators: >, <, >= , <= , == , !=
3. Logical operators: It is used to perform logical operations. These are logical operators: &&, ||, !
4. Assignment operators: It is used to assign values to the variable and it allows a programmer to
create a chain of expression. These are assignment operators: = , += , -= , *= , /=
5. Ternary Operator or conditional operator:
syntax: i > j ? i :j ;
If the first expression is true, it will execute second statement. If the first expression is false
it will skip the second statement and it will execute third statement.
Program:
[Link] Demo{
public static void main(String[] args){
int i=80, j=40;
int k = i>j?i:j;
[Link]("The value of k is " + k);
}
}
output: Value of k is 80
8. class Demo{
public static void main(String[] args){
int i=10;
if(i){
[Link]("Hello");
}
}
}
Output: error: incompatible types: int cannot be converted to Boolean
9. class Demo{
public static void main(String[] args){
int i=10;
int j=30;
if(i=j){
[Link]("Hello");
}
}
}
Output: error: incompatible types: int cannot be converted to Boolean
10. class Demo{
public static void main(String[] args){
boolean i=false;
if(i){
[Link]("Hi");
}
[Link]("Hello");
}
}
Output:Hello
11. class Demo{
public static void main(String[] args){
boolean i=true;
if(i){
[Link]("Hi");
}
[Link]("Hello");
}
}
Output:
Hi
Hello
12. class Demo{
public static void main(String[] args){
if(true)
[Link]("Hi");
[Link]("Hello");
}
}
Output:
Hi
Hello
13. class Demo{
public static void main(String[] args){
if(false)
[Link]("Hi");
[Link]("Hello");
}
}
Output:
Hello
IF CONDITION:
syntax: if (condition)
{ }
1. If condition satisfied or if the condition is true, it will enter inside the if block and it will execute
the statement.
2. Once if statement is executed, after the if block if any executable statements are present those
statements would be executed.
3. If the condition is not satisfied or if the condition is false, it will come out of the if block and after
the if block if any executable statements are present, those statement would be executed.
4. In if condition curly braces are optional.
5. If condition allows Boolean data type values.
6. If we try to provide any other data type value, it will give compile time error i.e. incompatible data
type.
IF ELSE CONDITION:
syntax: if (condition)
{ }
else
{ }
Case1: If the condition is satisfied it will enter inside the if block and execute the if statement. Once
if block is executed then else part won’t be executed. After the else part if any executable
statements are present then those part will be executed.
Case2: If condition is false it won’t execute if block, it will execute else part and after the else part if
any executable statements are present then those statement would be executed.
Note: The outcome of Relational operator and Logical operator is always Boolean value.
class Demo{
public static void main(String[] args){
int age=35;
if(age>=21 && age<=35){
[Link]("The candidate is eligible for IAS exam.");
}
else{ [Link]("The candidate is not eligible for IAS exam.");
}
}
}
Output: The candidate is eligible for IAS exam.
17. Write a program to print sanju if the number is divisible by 3 and to print geetha if the number is
divisible by 5 and to print sanju weds geetha if the number is divisible by both?
class Demo{
public static void main(String[] args){
int i=15;
if(i%3==0 && i%5==0){
[Link]("Sanju weds Geetha.");
}
else if(i%3==0){[Link]("Sanju");
}else if(i%5==0){
[Link]("Geetha");
}
}
}
Output: Sanju weds Geetha.
For loop:
syntax: for (initialisation; condition;increment/decrement)
{ //statements;
}
1. In for loop initialisation part is always executed once.
2. In for loop, first it will execute initialisation.
3. Once the initialisation part is executed control moves to the condition.
4. It will check whether the condition is true or false.
5. If the condition is true, it will enter inside the for loop and it will execute the statements.
6. If the condition is false it will come out of the for loop.
Syntax:
while (condition)
{ //statements
Do While: Do while is a post tested loop. Before checking the condition at least once it will execute
the statements then it will check the condition.
In do while at the end of the while condition we have to use a semicolon.
Syntax:
do
{ //statements
} while(condition);
Ex Q. Write a program to print from 1 to 10 using while loop.
class Whileloop
{public static void main (String [] args)
{ int i = 1;
while(i<=10)
{ [Link](i);
i++;
}}}
Note: 1. Num%10 123%103
2. Num/10123/1012
Syntax of a class:
Class classname
{Data type variable;
Data type variable;
return type method name()
{ //statements
}// end of method
return type method name()
{ //statements
}// end of method
}//end of class
Object Creation:
Eclipse:
1. Eclipse is a IDE (Integrated development environment).
2. [Link] .org.//downloads.
3. Downloaded.
4. Select eclipse folder, click on [Link] file.
5. Select a workplace.
6. Select workbench.
7. Select open perspective.
8. Select java perspective.
9. Go to file select new, select a java project, give project name, and click on finish.
10. Elaborate the project, right click on src, select new, select a class, give the class name, Sand
click on finish.
11. For the main method shortcut is main+ ctrl +space
12. For the [Link]() Sysout+ ctrl+ space
Ex:
public class Remote {
String name="Sony";//initialisation process
String color="Black";//also called as
instance,variables,datamembers
double cost=500.0;
void switchOff()
{
[Link]("Switch off");
}
public static void main(String[] args) {
2. class Ticket
{int no_of_tickets=20;
void avaibalitiy ()
{[Link]("Availability tickets are: " + no_of_tickets);
}
void book(int n)
{if (no_of_tickets >= n)
{ no_of_tickets = no_of_tickets -n;
[Link]("User booked " +n + "Tickects");
[Link]("Avalability tickets are "+ no_of_tickets);
}
else
{[Link]("Tickets are not availaible ");
}
}
void cancel( int m)
{ no_of_tickets = no_of_tickets+m;
[Link]("user cancelled "+ m+"tickets");
[Link]("Availability tickets are "+ no_of_tickets);
}
}
public class Demo2 {
public static void main(String[] args) {
Ticket t = new Ticket();
[Link]();
[Link](10);
[Link](5);
}
}
output:
Availability tickets are: 20
User booked 10Tickects
Avalability tickets are 10
user cancelled 5tickets
Availability tickets are 15
METHOD:
1. Method is just like a function which performs some functionality is called method.
Syntax:
return _type method name()
{//statements;
}
2. A method can have n number of input parameters or arguments.
3. Every method has a return type.
Ex:
divison()
{
[Link](“Hi”);
}
output: gives a compile time error because every method has a return type.
4. The variable which is declared inside the method is called as local variable.
5. If the method is not returning any value, then make the return type as Void.
6. If the method is returning any value, then make the return type as particular data type
(method data type should be same as return variable data type).
7. A method can return only one value at a time.
Ex:
Double mul(int p, double q)
{
double r= p*q;
double r1 + p+q;
return r;
return r1;
}
output: It gives compile time error because we can’t return more than one values.
8. If you want to a method to return more than one value at a time, it can be done by using
Arrays concept.
9. Return is the last logical statement inside the method.
Ex:
Double mul(int p, double q)
{ double r= p*q;
double r1= p+q;
return r;
[Link](“Hi”);
}
output: It gives compile time error because return should be last statements inside a
method.
Advantages of method:
1. Reusability.
2. Individual choice of calling i.e we can call only required methods.
IQ3. We can call all the methods inside the S.O.P except if the method return type is void.
EX:
class calculator
{
void add(int a, int b)
{
int c = a+b;
[Link]("value is "+ c);
}
int sub(int x, int y){
int z = x-y;
return z;
}
double mul (int p, double q)
{
double r = p*q;
return r;
}
}
public class Demo4 {
public static void main(String[] args) {
calculator c = new calculator();
[Link](20,10);
[Link](50,50);// we can call a method multiple time
[Link]([Link](20, 10));
[Link]([Link](10, 2.0));
//[Link]([Link](10,20)); compile time error
}
}
output:
value is 30
value is 100
10
20.0
Constructor:
1. Rules of the constructor:
ii) User define Non parameterised Constructor: If the constructor is not having any argument or if
the user is not passing any value inside the constructor is called user define non parameterised
constructor.
Ex:
public class Demo {
Demo() // Non parameterized constructor
{
[Link]("I am inside the constructor");
}
void display()// Method
{
[Link]("I am inside the Display method");
}
public static void main(String[] args) {
Demo d = new Demo();
[Link]();
}
}
Output:
I am inside the constructor
I am inside the Display method
Default Constructor:
}
}
Output: gives compile time error, because there is no default constructor is present in the above
class.
Purpose of Constructor:
1. Object creation.
2. To initialise the states i.e initialising the local variable values to the instance variables.
Note:
1. We can’t access the local variable value outside the method and outside the constructor.
2. Local variable value is within the method scope or within the constructor scope.
3. Constructor can’t return any value.
Ex:
class Student
{
String name;
int id;
String collegename;
Student(String n,int i,String c) // Constructor
{
name = n;
id = i;
collegename = c;
}
void display()
{[Link]("Name is "+name+"\n Id is "+ id + "\n college name is "+ collegename);
}
}
public class Sample {
public static void main(String[] args) {
Student S1 = new Student ("John",1,"KIT");
[Link]();
Student S2 = new Student ("Mike",2,"KIT");
[Link]();
Student S3 = new Student ("Adam",3,"KIT");
[Link]();
}
}
output:
Name is John
Id is 1
college name is KIT
Name is Mike
Id is 2
college name is KIT
Name is Adam
Id is 3
college name is KIT
Note: Whenever the local variable and instance variable name are same JVM will get
confused to identify local variable and instance variable. If we want to overcome this
problem we have to use this keyword. this is a keyword it always refers to the instance
variables of the current class.
Ex:
1. class Student
{
String name;
int id;
String collegename;
Student(String name, int id, String collegename) // Constructor
{
name = name;
id = id;
collegename = collegename;
}
void display()
{
[Link]("Name is "+name+"\n Id is "+ id + "\n college name is "+ collegename);
}
}
public class Sample {
public static void main(String[] args) {
Student S1 = new Student ("John",1,"KIT");
[Link]();
Student S2 = new Student ("Mike",2,"KIT");
[Link]();
Student S3 = new Student ("Adam",3,"KIT");
[Link]();
}
}
output:
Name is Null
Id is 0
college name is Null
Name is Null
Id is 0
college name is Null
Name is Null
Id is 0
college name is Null
[Link] Student
{
String name;
int id;
String collegename;
Student(String name,int id,String collegename) // Constructor
{
[Link] = name;
[Link] = id;
[Link] = collegename;
}
void display()
{
[Link]("Name is "+name+"\n Id is "+ id + "\n college name is "+ collegename);
}
}
public class Sample {
public static void main(String[] args) {
Student S1 = new Student ("John",1,"KIT");
[Link]();
Student S2 = new Student ("Mike",2,"KIT");
[Link]();
Student S3 = new Student ("Adam",3,"KIT");
[Link]();
}
}
output:
Name is John
Id is 1
college name is KIT
Name is Mike
Id is 2
college name is KIT
Name is Adam
Id is 3
college name is KIT
# Default Value:
String = Null
int = 0
byte = 0
short = 0
long = 0
float = 0.0
double = 0.0
char = space
Boolean = false
Method Overloading:
In a class when we have more than one method, having the same name with different input
parameters is called Method Overloading.
1. Different input parameters in the sense, we can change the number of parameter.
Ex: Void search (int i)
{
}
void search (int i , int j)
{
}
2. We can change the data types of the parameter.
Ex: Void search (int i)
{
}
void search (double d)
{
}
3. We can change the sequence of parameter.
Ex: Void search (int i , double d)
{
}
void search (double d , int i)
{
}
4. In method overloading return type doesn’t makes any difference (each method may have
different return type, it needn’t be same).
Ex: int search(int i)
{
return i ;
}
double search(double d )
{
return d;
}
5. In method overloading variable name is NOT considered, it may have same or different variable
names.
int search(int i)
{
return i ;
}
double search(double i )
{
return i ;
}
Note: Method Overloading is mainly used for searching purpose.
Ex:
public class Demo1
{
int Search(int i)
{
return i;
}
double Search (double i)
{
return i;
}
int Search (int i ,int j)
{
return i+j;
}
void Search (double d , String s)
{
[Link](d+"\n"+s);
}
void Search ( String s, double d)
{
[Link](s+"\n"+d);
}
public static void main(String[] args)
{
Demo1 d = new Demo1();
[Link]([Link](20));
[Link]([Link](20.0));
[Link]([Link](90,40));
[Link]("abc", 9.0);
[Link](3.0, "Rashda");
}
}
Output:
20
20.0
130
abc
9.0
3.0
Rashda
Ex:
1.)
void m1()
{
}
int m1()
{
int i= 10;
return i;
}
Output: Compile time error (not method overloading)
2.)
void m1(int i)
{
}
void m1(String s)
{
}
void m1(int j)
{
}
Output: Compile time error (not method overloading)
3.)
void m1()
{
}
void m1(int i, int j)
{
}
void m1(int i , int j, char c)
{
} // Method overloading.
4.)
void m1()
{
}
void m2(int i)
{
} // Not Method overloading, because method names are different.
Constructor Overloading:
1. In a class when we have more than one constructor having the same name but different input
parameters is called Constructor Overloading.
2. Different parameters in the sense, we can change the number of parameters.
3. We can change the data types of parameter.
4. We can change the sequence of the parameter.
5. In Constructor overloading variable name shouldn’t be considered.
Note: Constructor overloading is mainly used for object creation along with searching purpose.
Ex:
class Employee
{
Employee (String name)
{
[Link](name);
}
Employee (double sal)
{
[Link](sal);
}
Employee (String name, int id)
{
[Link](name+ "\n"+ id);
}
Employee (int id, String name)
{
[Link](name + "\n" +id);
}
}
public class Demo2
{
public static void main(String[] args)
{
Employee e1 = new Employee("John");
Employee e2 = new Employee("40000.0");
Employee e3 = new Employee(1,"Mike");
Employee e4 = new Employee("Adam", 2);
}
}
Output:
John
40000.0
Mike
1
Adam
2
INHERITANCE:
1. Acquiring the properties of one class by the other class is called Inheritance.
2. Inheritance is achieved by using a keyword Extends.
3. Inheritance is achieved by keeping all the common properties in a one class, that class is
called Parent class or Super class or Main class.
4. The class that acquires common properties from the Super class is called as Child or Sub
Class.
5. Once if we write extends keyword the properties which is present in Parent class is
automatically inherit to the Child class.
6. If we create an Object of Parent class we can access the properties of only Parent class.
7. If we create an Object of child class, that object is shared with Parent class and Child class i.e
we can access the properties of both Parent and Child class.
8. Inheritance is also called as is a relationship or Generalisation.
Types of Inheritance:
1. Single level Inheritance: One class is extended by only one class is called Single level
Inheritance.
Extends
B
Ola cab
Ola share
In this example Ola share inherit the features of Ola cab (booking, cancel, and tracking)
Ex:
class Employee1 //Parent class
{
double bonus = 2000.0;//Parent class variable
void working()//parent class method
{
[Link]("Working");
}
}
class Developer extends Employee1// child class
{
double sal = 50000.0;//child variable
void development()//child method
{
[Link]("developing code...");
}
}
public class Sample1 {
public static void main(String[] args) {
[Link]("Accessing parent members");
Employee1 e = new Employee1();//parent class object
[Link]([Link]);
[Link]();
[Link]("Accessing both parent and child");
Developer d = new Developer();// child class object
[Link]([Link]);
[Link]([Link]);
[Link]();
[Link]();
}
}
Output:
Accessing parent members
2000.0
Working
Accessing both parent and child
2000.0
50000.0
Working
developing code...
B
C
Ex:
While upgrading an application from one version to another version, in each upgrade new
version inherit features from previous one version.
1.0
1.1
1.2
Here we need to create only version 1.2 object, because it will automatically inherit the
features of 1.1 and 1.0.
Ex:
class flipkart
{
String prodname = "Mobile";
double cost = 20000.0;
String Color = "Black";
void orderdetails()
{
[Link]("Welcome to Flipkart");
[Link]("Product name is"+prodname +
"\nproduct color is"+Color+"\nproduct cost is"+cost);
}
}
class Firststatus extends flipkart
{
void packing()
{
[Link]("Your product has been packed succeessfully");
}
void Shipping()
{
[Link]("Your product has been shipped");
}
}
class Finalstatus extends Firststatus
{
void deliverystatus()
{
[Link]("Your product has been delivered succeessfully");
}
}
public class Sample1 {
public static void main(String[] args) {
Finalstatus f = new Finalstatus();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
output:
Welcome to Flipkart
Product name is Mobile
product color is Black
product cost is20000.0
Your product has been packed successfully
Your product has been shipped
Your product has been delivered successfully
3. Hierarchy:
When one super class is extended by so many subclasses it is called hierarchy inheritance.
B C D
Ex:
Employee
Test
Developer Engineer Manager
Ex:
class Employee2
{
String name;
int empid;
double sal;
String designation; //declaration
void swipecard()
{
[Link]("Employee name is "+ name+"\nEmployee Id is "+empid);
[Link]("Swiped Card");
}
void empfulldetails()
{
[Link]("****full details****");
[Link]("Employee name is "+name+"\nEmployee Id is "+empid+
"\nEmployee salary is "+sal+"\nEmployee Designation is "+designation);
}
}
class Developer extends Employee2
{
Developer(String n,int i, String d, double s)
{
name =n;
empid = i;
sal = s;
designation = d;
}
void developcode()
{
[Link]("Developing code");
}
}
class Tester extends Employee2
{
Tester(String n,int i, String d, double s)
{
name =n;
empid = i;
sal = s;
designation = d;
}
void testApplication()
{
[Link]("Testing the Application");
}
}
public class Sample1 {
public static void main(String[] args) {
Developer d = new Developer("Sushma", 1,"Developer",1000);
[Link]();
[Link]();
[Link]();
Tester t = new Tester ("Anupama",2,"Tester",2000);
[Link]();
[Link]();
[Link]();
Tester t1 = new Tester ("Uday",3,"Tester",3000);
[Link]();
[Link]();
[Link]();
}
}
Output:
Employee name is Sushma
Employee Id is 1
Swiped Card
Developing code
****full details****
Employee name is Sushma
Employee Id is 1
Employee salary is 1000.0
Employee Designation is Developer
Employee name is Anupama
Employee Id is 2
Swiped Card
Testing the Application
****full details****
Employee name is Anupama
Employee Id is 2
Employee salary is 2000.0
Employee Designation is Tester
Employee name is Uday
Employee Id is 3
Swiped Card
Testing the Application
****full details****
Employee name is Uday
Employee Id is 3
Employee salary is 3000.0
Employee Designation is Tester
#Multiple: One subclass can inherit only one Super class at a time, if it tries to inherit multiple Super
class, JVM will get confused or it will leave ambiguity. So multiple inheritance is not possible in JAVA
by using class. But it is possible by using Interface.
Ex:
B(m1) C(m1)
Class A extends B, C
{ A a = new A();
a.m1();}
In the above diagram class B and Class C are containing m1 method and we are invoking this m1
method by using A class object, then JVM will get confused should we need to invoke the m1
method which is present in B class or C class. This problem is known as ambiguity problem or
Diamond problem.
Ex:
class A
{
}
class B
{
}
class c
{
}
class D extends B, C
{
}
Output: Compile time error because in JAVA, we can’t use multiple inheritance by using class.
#Cyclic Inheritance:
Any subclass can inherit any Parent class but Parent class can’t inherit subclass, so cyclic inheritance
is not possible in JAVA.
A
B
class A extends B
{
}
class B extends A
{
}
output: Compile time error because, cyclic inheritance is not possible in JAVA.
Note:
1. JAVA supports only 3 kinds of Inheritance by using class i.e Single level, Multi-level, and Hierarchy.
2. JAVA doesn’t support multiple and Cyclic Inheritance.
Advantages of Inheritance:
1. Reusability.
2. Extendibility.
3. It takes less time to build an application.
4. Application takes less memory.
5. Execution is faster.
6. We can improve the performance of application.
Note:
3. This statement should be the first line of code inside any constructor.
Ex: cube(double h)
{
[Link]("Hi");
this(h,4.0);
}
output: Compile time error because this state statement should be first line of code inside any
constructor.
4. We can call any constructor inside other constructor, there is no sequence restriction.
5. Any constructor of a class wants to call constructor of the Super class by using Super statement or super
statement is used to call a super class constructor.
6. Super statement should be the first line of the code inside any Constructor.
7. We can’t have more than one super statement inside the Constructor.
8. We can have either this statement or super statement inside the constructor , i.e we shouldn’t
write this and super statement at a time inside the Constructor.
Ex: (super statement)
[Link] Cube//parent class
{
double height;
double width;
double length;
Cube(double l)
{
this(l,3.0);
}
Cube(double l,double w)
{
this(l,w,4.0);
}
Cube(double l,double w, double h)
{
height =h;
width= w;
length = l;
}
void display()
{
double volume = height*length*width;
[Link]("Volume of the Cube is "+volume);
}
}
class Cube1 extends Cube//child
{
Cube1()
{
super(3.0);
}
}
public class Sample2 {
public static void main(String[] args) {
Cube1 c1 = new Cube1();
[Link]();
}
}
output:
Packages:
Packages are nothing but collection of folders, which segregate different classes or files according to
related folders.
Q. Why packages?
Ans: Packages are required that we can easily categorised class or files.
Q. How to create a Package?
Ans: a. Create a java project
b. Under the src right click select new select a package give a package name click on
finish.
c. Under the package right click select newselect a classgive the class name click on
finish.
Note:
i. If the project is commercial we have to start the package name by using com.
ii. If the project is Organisational we have to start the package name by using org.
iii. If the project is Educational we have to start the package name by using edu.
iv. If the project is government we have to start the package name by using gov.
Import:
Import is a keyword, it indicates the JVM, that we are importing particular classes from the particular
package.
1. Package declaration should be the first line of the code in any class.
2. Import statement should be immediate next line of package declaration.
3. Star (*) represents importing all the classes from one package to another package.
Fully qualified Path name: It is a path which shows the location of class or file.
Ex:
package [Link];
public class Admin {
public void addproduct()
{
[Link]("Added product");
}
}
package [Link];
import [Link].*;
import [Link].*;
public class User {
Admin a = new Admin();
void display()
{
[Link]();
[Link]("Displayed product");
}
public static void main(String [] args)
{
User u = new User();
[Link]();
}
}
Output:
Added product
Displayed product
Note:
1. The default package in JAVA is [Link].
2. [Link] package is already imported in every Java file.
3. [Link]String, class, [Link], threads, Exception handling.
4. [Link] Scanner, collection, Date and framework.
5. [Link] File handling.
6. [Link] swings.
7. [Link] simpledate format.
Note:
1. If we uses the class which is present in [Link] package, no need to import the package
explicitly.
2. If we use the class which is present in other class than [Link] package, then we have to import
the package explicitly.
Access Modifier:
Outer class/ Variables Method Constructor
Inner class
Access Modifier:
1. Defines the scope of the every member.
2. In java Access modifiers are used to control the members of the class or variable or method or
constructor.
3. There are Eleven Access Modifiers available in Java:
Public, private, protected, Static, Abstract, Final, Synchronized, Transient, Volatile, Strictf, and
Native.
Note:
1. Abstract methods shouldn’t be private.
2. Outer class can’t be private and protected.
3. We can give any kind of Access modifiers to the inner class.
4. We shouldn’t give any access modifiers to the local variables, because we can’t access the local
variable value outside the method. Hence there is no use of giving access modifiers to the local
variables.
Has a relationship:
1. Associating an object of a class into the object of the other class is called Has a relationship , or
one object is containing another object is called Has a relationship.
2. Has a relationship is also called Aggregation.
Ex: Car has a Music System
Car has an Engine.
Person has a mobile.
Mobile has a battery.
Ex:
[Link] Car
{
String name = "Innova";
double cost= 300000.0;
String color = "Black";
MusicSystem m = new MusicSystem();// has a relationship
Engine e = new Engine();// has a relationship
void drive()
{
[Link]("Driving");
}
class MusicSystem
{
String name = "Sony";
double cost = 35000.0;
void PlayMusic()
{
[Link]("Playing music");
}
}
class Engine
{
String name ="Bosch";
}
}
public class Demo {
public static void main(String[] args) {
Car c = new Car();
[Link]("Car name is "+[Link]);
[Link]("Car color is "+[Link]);
[Link]();
[Link]("MusicSystem name is "+[Link]);
[Link]("MusicSystem cost is "+[Link]);
[Link]();
[Link]("Engine name is "+[Link]);
}
}
Output:
Car name is Innova
Car color is Black
Driving
MusicSystem name is Sony
MusicSystem cost is 35000.0
Playing music
Engine name is Bosch
2. class Mobile
{
Battery b = new Battery();//Has a relationship
void MakeCall()
{
[Link]("Jio Calling");
[Link]();
}
void sendmsg()
{
[Link]("Texting...");
[Link]();
}
void PlayGames()
{
[Link]("Playing Candycrush...");
[Link]();
}
void charging()
{
[Link]("Charging...");
[Link]();
}
}
class Battery
{
int charge = 100;
void recharge()
{
charge = charge+20;
}
void discharge()
{
charge = charge-10;
}
}
public class Demo3 {
public static void main(String[] args) {
Mobile m = new Mobile();
[Link]("Battery status is "+ [Link]+"%");
[Link]();
[Link]();
[Link]();
[Link]("Battery status is "+ [Link]+"%");
[Link]();
[Link]("Battery status is "+ [Link]+"%");
}
}
Output:
Battery status is 100%
Jio Calling
Texting...
Playing Candycrush...
Battery status is 70%
Charging...
Battery status is 90%
Note:
1. (I.Q) Private members can’t be inherited , because private members scope is within the class.
2. (I.Q) Constructor can’t be inherited, because Constructor name should be same as class name and
Constructor are not the members of the class, rather than Constructors are special members of the
class.
3. Every non Parameterised Constructor by default having a super statement, that super statement
is used to call super class Constructor.
Ex:
class Alpha
{
Alpha()
{
[Link]("I am in Alpha Constructor");
}
}
class Beta extends Alpha
{
Beta()
{
[Link]("I am in Beta Constructor");
}
}
class Gama extends Beta
{
Gama()
{
[Link]("I am in Gama constructor");
}
}
public class Demo4
{
public static void main(String[] args) {
Gama g = new Gama();
}
}
Output:
I am in Alpha Constructor
I am in Beta Constructor
I am in Gama constructor
Method Overriding:
1. It is a process of giving the child specific implementation by keeping the Parent method is called
Method Overriding.
2. Method Overriding is possible only in case of Inheritance.
3. While overriding the method return type, method name and parameters must be same, but
Implementation can be different.
Note: Method overloading is possible in case of Inheritance and without inheritance also.
Ex:
class Application
{
void register()//Parent method
{
[Link]("I am in Application");
}
}
class Application1 extends Application
{
void register(String name)//child method
{
[Link]("I am in Application1");
}
}
public class Sample3 {
public static void main(String[] args) {
Application1 a = new Application1();
[Link]();
[Link]("Sushma");
}
}
Output:
I am in Application
I am in Application1
Assignment: Q. Person has a Mobile, Mobile has a Setting, Setting has a Wifi?
class Person
{
String name = "Angel";
Mobile m = new Mobile();
void Talkingonmobile()
{
[Link](name+" talking on "+[Link]+" Mobile");
[Link]();
}
}
class Mobile
{
Setting s = new Setting();
String name = "Samsung";
double cost = 20000.0;
void checkingsetting()
{
[Link]("Checking Wifi connection in Mobile");
[Link]();
}
}
class Setting
{
Wifi w = new Wifi();
void connectedwifi()
{
[Link]("Settting....");
[Link]();
}
}
class Wifi
{
void statuswifi()
{
[Link]("connecting...");
}
void connectingwifi(String ssid, String Password)
{
if([Link]("Rashda") && [Link]("123!@#") )
{
[Link]("connected to Wifi....");
}
}
}public class Hasarelationship
{
public static void main(String[] args) {
Person p= new Person();
[Link]();
[Link]("Rashda","123!@#");
}
}
Output:
Angel talking on Samsung Mobile
Checking Wifi connection in Mobile
Settting....
connecting...
connected to Wifi....
Note:
While Overriding the method, access modifier visibility goes on Increasing i.e. If the parent class
method is Private then the child class method can be Private or default or protected or public.
If the parent class method is default then the child class method can be default or protected or
public but it shouldn’t be private.
If the parent class method is protected then the child class method can be protected or public but it
shouldn’t be private and default.
If the parent class method is public then the child class method can be public but it shouldn’t be
private, default and protected.
Typecasting:
1. Converting from one data type to other data type is called Typecasting.
2. Typecasting can be categorised into 2 types:
a. Implicit Typecasting:
i) Compiler will performs implicit typecasting.
ii) If we want to assign smaller data type value to bigger data type then it is called implicit
typecasting.
iii) There is no loss of information in implicit typecasting.
iv) It is also called as an up casting or widening conversion.
Ex:
public class ImplicitTypeCasting {
public static void main(String[] args) {
char c = 'A';
int i = c; //implicit type casting, Taking ASCII value A.
[Link](i);
int j = 30;
double d = j;//implicit type casting
[Link](d);
}
}
Output:
65
30.0
b. Explicit Typecasting:
i) Java doesn’t support to assign the bigger data type value to the smaller data type, but still if
we want to assign programmer has to typecasting explicitly .
ii) Programmer will perform explicit typecasting.
iii) There is loss of information in explicit typecasting.
iv) It is also called as down casting or narrowing conversion.
Ex:
public class ExplicitTypecasting {
public static void main(String[] args) {
double d = 30.0;
//int i = d; compile time error
int i = (int)d; //Explicit type casting
[Link](i);
int j = 90;
//byte b = j; compile time error
byte b = (byte)j; // Explicit type casting
[Link](b);
}
}
Output:
30
90
Up casting:
1. Any parent can refer to the any of the child class object in the entire Inheritance hierarchy or
assigning the child class object to the parent class reference variable is called Up casting.
2. By using parent class reference variable, we can access only parent class members.
3. By using a parent class object, we can’t access child specific members, but in case of overriding we
can take the implementation of child class.
Syntax: Parent p = new child();
Ex:
class Veg
{
void cook()// parent method
{
[Link]("Cooking...");
}
void chop()//Parent method
{
[Link]("Chopping");
}
}
class Carrot extends Veg
{
void preparehalwa()//Childmethod
{
[Link]("Prepare Halwa...");
}
void cook()//Parent method,Method Overriding
{
[Link]("Carrot cooking..");//Child implementation
}
}
public class Upcasting {
public static void main(String[] args) {
/* Veg v = new Veg();//Parent object
[Link]();
[Link]();
//[Link](); compile time error
Carrot c = new Carrot();// Child object
[Link]();
[Link]();
[Link]();*/
Veg v1 = new Carrot();
[Link]();
[Link]();
// [Link](); compile time error
}
}
Output:
Chopping
Carrot cooking..
2. If we calling same name variable present in both super and sub class by using child object then it
will execute child variable, because child object first consider child members.
Ex:
class Alpha3
{
void display()//parent method
{
[Link]("I am in parent class");
}
}
class Beta3 extends Alpha3
{
void display()//overriding,parent method
{
[Link]("I am in child class");
}
}
public class Downcasting {
public static void main(String[] args) {
//Alpha3 a = new Beta3();upcasting
//Beta3 b = new Alpha3();Compile time error
/*Beta3 b = (Beta3) new Alpha3();//runtime error, Class cast exception
[Link]();
*/
Alpha3 a = new Beta3();//upcasting
Beta3 b = (Beta3) a;//downcasting
[Link]();
}
}
Output:
I am in child class
Ex:
class Animal//parent class
{
}
class Dog extends Animal//Child class
{
}
class Cat extends Animal//Child class
{
}
class Cow extends Animal// child class
{
}
class Display
{
void convert(Animal a)
{
if (a instanceof Dog)
{
Dog d = (Dog)a;
[Link]("Animal converted to Dog");
}
else if(a instanceof Cat)
{Cat c= (Cat)a;
[Link]("Animal converted to Cat");
}
else if(a instanceof Cow)
{Cow c= (Cow)a;
[Link]("Animal converted to Cow");
}
}
}
public class Downcasting1 {
public static void main(String[] args) {
Display d = new Display();
[Link](new Cow());
}
}
Output:
Animal converted to Cow
Static and Non Static:
If we make any variable as a static access modifiers i.e. we can call it as a static variable.
EX:
[Link] Student1
{
String name;
int Id;
static String Collegename = "KIT";
Student1(String n, int i)//constructor
{
name= n;
Id= i;
}
void Display()//method
{[Link]("Name is "+name+"\nId is "+Id+"\nCollegename is "+Collegename);
}
}
public class Staticnonstatic {
public static void main(String[] args) {
Student1 s1 = new Student1("John",1);
Student1 s2 = new Student1("Mike",2);
Student1 s3 = new Student1("Adam",3);
[Link]();
[Link]();
[Link]();
}
}
Output:
Name is John
Id is 1
Collegename is KIT
Name is Mike
Id is 2
Collegename is KIT
Name is Adam
Id is 3
Collegename is KIT
2. NameNonstatic
Id Nonstatic
Trainername Static
3. EmpnameNonstatic
Emp Id Nonstatic
Companyname Static
Note:
1. Any Non static method wants to call a non static method, we can call it directly by using method
name.
2. Any static method wants to call static method; we can call it directly by using method name.
3. Any Non static method wants to call a static method; we can call it by using class name.
[Link] Static method wants to call non static method, we can call it by using Object.
Ex:
public class Staticnonstatic1 {
void m1()
{
[Link](" m1 method");
}
static void m2()
{
new Staticnonstatic1().m1();
[Link](" m2 method");
}
void m3(){
Staticnonstatic1.m2();
[Link](" m3 method");
}
void m4()
{
m3();
[Link](" m4 method");
}
static void m5()
{m2();
[Link](" m5 method");
}
public static void main(String[] args) {
Staticnonstatic1 s = new Staticnonstatic1();
s.m4();
m5();//m5 and main both are static , so we can directly call it.
}
}
Output:
m1 method
m2 method
m3 method
m4 method
m1 method
m2 method
m5 method
Note:
1. If any static members present in same class, we can access it by using Class name or members
name.
2. If any static members present in different class, we can access it by using Class name.
3. If any Non static members are present in same class or different class, we have to call it by using
Object.
Ex:
class Employee1
{
String empname= "Adam";
static String Companyname= "Infosys";
void m1()
{
[Link]("m1 method");
}
static void m2()
{
[Link]("m2");
}
}
public class Staticnonstatic2 {
String name= "John";//non static
static String Trainername= "Sushma";//Static
void m3()//non static
{
[Link]("m3 method");
}
static void m4()//static
{
[Link]("m4");
public static void main(String[] args) {
[Link]("Static members accessing by using members name");
[Link](Trainername);
m4();
[Link]("Static members accessing by using class name");
[Link]([Link]);
Staticnonstatic2.m4();
//[Link](name); compile time error.
[Link]("Non Static members accessing by using Object ");
Staticnonstatic2 s= new Staticnonstatic2();
[Link]([Link]);
s.m3();
[Link]("Static members accessing in different class");
[Link]([Link]);
Employee1.m2();
[Link]("Non static members accessing by using Object");
Employee1 e = new Employee1();
[Link]([Link]);
e.m1();
}
}
Output:
Static members accessing by using members name
Sushma
m4
Static members accessing by using class name
Sushma
m4
Non Static members accessing by using Object
John
m3 method
Static members accessing in different class
Infosys
m2
Non static members accessing by using Object
Adam
m1 method
Note:
1. Static members doesn’t belong to the object, rather than it belongs to the class, hence static
members are also called as class members.
2. Non static members belong to the Object.
3. We can’t inherit static members.
4. Static methods can’t be overridden.
5. Static methods can be overloaded.
6. We can’t override main method, because it is static.
7. We can overload the main method.
8. There is a only one copy of the static members created inside the memory.
9. For each and every object, different copy should be created for non static members.
10. We can inherit non static members.
11. We can override non static members.
EX:
class Veg1//parent class
{
void cook()//parent method
{
[Link]("cooking...");//parent implementation
}
static void chop()// Parent method
{
[Link]("Chopping...");
}
}
class Carrot1 extends Veg1//Child class
{
void cook()//parent method,method overriding
{
[Link]("Carrot cooking...");//child implementation
}
static void chop()// child method, Method hiding
{
[Link]("Carrot Chopping...");
}
}
public class Staticnonstaic3 {
public static void main(String[] args) {
Veg1 v = new Carrot1();//Upcasting
[Link]();//carrot cooking
[Link]();//chopping
}
}
Output:
Carrot cooking...
Chopping...
Note:
1. In the above program , if both the members are non static i.e. we can call it as method
Overriding.
2. If both the methods are static i.e we can call it as method hiding (it look likes a method overriding,
but it is not a method overriding, it is method hiding)
3. By using the child class object, we can use the parent class static members but those static
members can’t be inherited to the child class.(because child object is also an object of parent class)
Ex:
class Animal1
{void eating()
{
[Link]("Eating..");
}
static void Sleeping()
{
[Link]("Sleeping..");
}
}
class Dog1 extends Animal1
{
void barking()
{
[Link]("Barking...");
}
}
public class staticnonstatic4 {
public static void main(String[] args) {
Dog1 d= new Dog1();
[Link]();
[Link]();
}
}
Output:
Eating..
Sleeping..
Static Block:
1. Static block is a block which is executed even before the main method.
2. JVM is always giving highest priority to the static block even before the main method, then priority
goes to the main method.
3. If a class is containing multiple static blocks then based on the sequences static block should be
executed.
Ex:
1. public class Static {
static //static block
{
[Link]("hello");
}
static
{
[Link]("hello1");
}
static
{
[Link]("hello2");
}
public static void main(String[] args) {
[Link]("Hi");
}
}
Output:
hello
hello1
hello2
Hi
2.
public class mysql {
static
{
checklicence();
checkservice();
checkport();
}
mysql()
{
[Link]("My SQL is Application is launched");
}
public static void main(String[] args) {
mysql m = new mysql();
}
static void checklicence()
{[Link]("licenced issued");
}
static void checkservice()
{
[Link]("Service is on");
}
static void checkport()
{
[Link]("Port number is present");
}
}
Output:
licenced issued
Service is on
Port number is present
My SQL is Application is launched
Non Static Block:
[Link] static blocks are executed at the time of object creation.
2. If the class is having multiple non static blocks then based on the sequence non static blocks
should be executed.
3. If the class is containing static block, Non static block, Constructor then the 1 st priority is goes to
static block, 2nd priorities is goes to non-static block and 3rd priority is goes to Constructor.
Ex:
[Link] class Nonstatic {
{
//nonstatic block, Instance block
[Link]("I am in Nonstatic block");
}
{
[Link]("I am in Nonstatic1 block");
}
{
[Link]("I am in Nonstatic2 block");
}
public static void main(String[] args) {
Nonstatic n = new Nonstatic();
[Link]("I am in main method");
}
}
Output:
I am in Nonstatic block
I am in Nonstatic1 block
I am in Nonstatic2 block
I am in main method
2.
public class staNonstaCon {
static
{[Link]("I am in static block");
}
staNonstaCon()
{
[Link]("I am in Constructor");
}
{
[Link]("I am in Non static block");
}
public static void main(String[] args) {
staNonstaCon s = new staNonstaCon();
}
}
Output:
I am in static block
I am in Non-static block
I am in Constructor
Note:
1. Static block allows only static members, it doesn’t allow non-static members.
2. Non static block allows both static and non-static members.
Ex:
public class staticblock {
static int i = 10;
int j= 20;
static//static block
{
//int x= i+j; Compile time error
}
{//Non static block
int k= i+j;
[Link](k);
}
public static void main(String[] args) {
staticblock s = new staticblock();
}
}
Output:
30
Note:
1. Non static members gets initialised at the time of object creation, because non static members
belongs to object.
2. Static members get initialised at the time of class loading, because static members belongs to
class.
3. Static members are stored in static pool of the Heap area.
4. Non static members are stored in non-static pool of the Heap area.
5. Object and instance variables are stored in a Heap area.
6. Methods and local variables are stored in a stack area.
7. PC register holds the instructions.
8. Other than Java language code would be stored in a Native.
9. Class loader is responsible to load the class.
10. For loading .class file memory is required.
11. Execution engine helps to execute the program.
Difference b/w Static and Non static members:
1. Static block gets executed before the 1. Non static block gets executed at the time of
main method. object creation.
2. Static blocks are used to initialise the 2. Non Static blocks are used to initialise the non
static members of the class. static members of the class.
3. Static block is also called as Static 3. Non Static block also called as instance
initialisation block. initialisation block.
4. Static block allows only static members 4. Allows both Static and non-static members.
of the class. 5. Non Static block gets executed whenever the
5 Static block gets executed only once for object is created.
the entire program execution.
POLYMORPHISM:
1. Poly means many, morphism means forms.
2. Polymorphism in java is a concept which we can perform single action by different ways is called
polymorphism.
3. OR the process of representing one form in a multiple forms is known as polymorphism.
4. Polymorphism can be categorised into 2 types:
a. Compile time Polymorphism:
[Link] the type of the object is determined at compile time by compiler is called compile time
polymorphism.
2. Compile time polymorphism is also called as a method overloading.
3. Compile time polymorphism is nothing but static polymorphism, static binding or early binding.
Ex: (a method overloading program), real time example of compile time polymorphism is flipkart
search.
b. Run time Polymorphism:
1. If the type of the object is determined at runtime by JVM is called Run time polymorphism.
2. It is also called Method overriding or Dynamic binding or Dynamic polymorphism or Late binding.
3. Run time polymorphism can be achieved by using the concept of Inheritance, Method overriding
and up casting.
4. In Runtime polymorphism based on the Object it will be showing multiple behaviours.
Ex: (a method overriding program), real time example updating App.
FINAL:
1. If we make any variable as a final it is called final variable.
2. We can’t change the value of final variable; it works like a constant value.
Ex: Pie value, Aadhar card number, PAN number, DOB.
3. We can’t override final method.
4. We can’t inherit final class.
5. We can’t declare final variable.
6. Final variable should be initialised.
Ex:
public class Final {
final int i = 80;//instance variable
void m1()//method
{
i= 90;//instance variable,compile time error because we can't change final variable value
[Link](i);
}
public static void main(String[] args) {
Final f = new Final();
f.m1();
}
}
Output:
Compile time error
Abstraction:
It is a process of hiding the implementation details from the user and we are exposing necessary
details to the user is called Abstraction.
Ex: Lose coupling (one object is compatible with any other object i.e. it is not tightly couple with only
one object)
Abstract method: A method which doesn’t have any implementation. It is incomplete method.
Ex: void show ();
Concrete method: : A method which is having implementation. It is complete method.
Ex: void show ()
{
Abstract Class:
1. Abstract class is an incomplete class.
2. It is a combination of abstract method and concrete method.
3. Abstract method is a method, which doesn’t have any implementation.
4. Concrete method is a method which is having implementation.
5. If any abstract methods are present in a class, then make the abstract method as abstract access
modifiers.
6. If any abstract methods are present in a class then make the class as an Abstract access modifier.
7. It is mandatory for a child class to override the Abstract method which is present in an abstract
class.
8. If we don’t override the Abstract method which is present in a class, make the child class as
Abstract.
9. We can’t create an object of Abstract class.
Ex:
1.
abstract class player//abstract class, incomplete class
{
void playsong()//concrete method
{
[Link]("Playing song");
}
abstract void pausecontrol();//abstract method, incomplete method
abstract void screencontrol();
}
class vlc extends player//child class
{void pausecontrol()
{
[Link]("press 'spacebar' to pause the song");
}
void screencontrol()
{
[Link]("press 's' to control the screen");
}
}
class Windows extends player//child class
{
void pausecontrol()
{
[Link]("press 'p' to pause the song");
}
void screencontrol()
{
[Link]("Do change sin the main button");
}
}
public class Abstract {
public static void main(String[] args) {
vlc v = new vlc();
[Link]();
[Link]();
[Link]();
[Link]("<________________>");
Windows w = new Windows();
[Link]();
[Link]();
[Link]();
[Link]("<________________>");
}
}
Output:
Playing song
press 'spacebar' to pause the song
press 's' to control the screen
<________________>
Playing song
press 'p' to pause the song
Do change sin the main button
<________________>
Note:
[Link] using Abstract class , we can achieve loose coupling.
2. By using Abstract class, we can achieve 0 to 100% abstraction.
2.
package assignment;
interface sim
{void makecall();
void sendmsg();
}
class jio implements sim
{
public void makecall() {
[Link]("Jio calling");
}
public void sendmsg() {
[Link]("Jio sending msg ");
}
}
class Airtel implements sim
{
public void makecall() {
[Link]("Airtel calling");
}
public void sendmsg() {
[Link]("Airtel sending msg ");
}
}
class mobile
{
void insertsim(sim s)
{
[Link]();
[Link]();
}
}
public class Abstract2 {
public static void main(String[] args) {
mobile m = new mobile();
[Link](new Airtel());
}
}
Output:
Airtel calling
Airtel sending msg
Note:
1. By using interface we can achieve loose coupling.
2. By using interface we can achieve 100% Abstraction.
3. Multiple inheritance is possible in java by using Interface.
4. A class can inherit other class at the same time, we can implement multiple interfaces.
5. Interface contains all the methods by default Abstract and public.
6. We can’t give any access modifiers to the Abstract method, inside the interface.
7. We can give any kind of access modifiers to the Abstract method, inside the Abstract class.
Note: Abstract methods shouldn’t be private, static and final because we can’t override private,
final and static method.
8. Inside the interface all the variables are by default Public, final and static.
Ex:
package [Link];
interface A
{
int i=10;// A interface variable
}
interface b extends A
{
int i=20;
}
public class rashda {
public static void main(String[] args) {
[Link](A.i);
[Link](b.i);
}
}
Output:
10
Abstract Class Interface
20
1. It contains both Abstract and 1. It contains only Abstract method.
concrete method.
Difference
2. Inside the abstract class we 2. We can’t give any kind of access between Abstract
modifiers to the abstract method
can give any kind of access class and
modifiers to the abstract inside the interface, because by
default it would be public and interface:
method.
3. We can give any kind of access Abstract.
modifiers to the variables inside 3. We can’t give any kind of access
the Abstract class. modifiers to the variables inside the
interface, because by default it
4. In abstract class we can’t would be public, static and final.
achieve multiple inheritance. 4. We can achieve multiple
inheritances by using Interface.
5. If any class is inheriting 5. If any class is inheriting interface
Abstract class by using extends by using implements keywords.
keywords.
6. If any Abstract methods are
6. If any Abstract methods are present in interface no need to make
present in abstract class explicitly it as an abstract access modifiers
we have to give abstract access because by default it would be
modifiers to the abstract abstract.
method. 7. Interface can’t contain
7. Abstract class can contain Constructor.
Constructor but we have to call it 8. Interface can’t have main method.
by using Super statement. 9. Interface can’t inherit Object class.
8. Abstract class can having main 10. We can achieve 100%
method (it works like a normal Abstraction in Interface.
class)
[Link] class inherit Object
class.
10. We can achieve 0 to 100%
Abstraction in abstract class.
Note:
1. Interface contain all the variables are by default final and static because if it is not a final , the
other class can change the implementation. But interface can’t contain any implementation.
2. If it is not a static, it can belong to other classes also, so other class can change the
implementation, so by default it would be static.
3. We can’t declare a variable inside the interface because those variables are by default final.
toString ():
toString() is a method , which is present inside the Object class. If we pass the reference variable
inside the S.O.P, it will invoke toString () method and this toString () method internally call hashcode
() method and hashcode () method returns hashcode to the toString () method. This toString ()
method it will convert hashcode into hexadecimal and it returns the implementation in the following
format: classname @ hashcode.
Ex:
[Link] class Demo {
public static void main(String[] args) {
Demo d = new Demo();
[Link](d);
}
}
Output:
[Link]@15db9742
STRING:
1. String is a non-primitive data type.
2. String is a final class, which is present in java. Lang package.
3. Strings are immutable i.e. once if the content is fix we can’t modify the content of String.
Ex:
1.
public class Sample {
public static void main(String[] args) {
String s1= "Sushma";
String s2= "QSP";
[Link](s2);
[Link](s1);
}
}
output:
Sushma
2.
public class Sample {
public static void main(String[] args) {
String s1= "Sushma";
String s2= "QSP";
String s3=[Link](s2);
[Link](s3);
}
}
Output:
SushmaQSP
3.
package [Link];
public class Sample {
public static void main(String[] args) {
String s1= "Sushma";
String s2= "QSP";
s1=[Link](s2);
[Link](s1);
}
}
Output:
SushmaQSP
in the above example there are 2 string objects created, but the object will refer to non-constant
pool(new keyword object).
Double equals (==) and equals method:
Double equals is always checking references and equals()method always check contains of the
string.
Ex:
1. public class Equals {
public static void main(String[] args) {
String s1="abc";//1000
String s2="pqr";//2000
String s3 ="abc";//1000
[Link](s1==s2);//false
[Link](s1==s3);//true
[Link]([Link](s2));//false
[Link]([Link](s3));//true
}
}
output:
false
true
false
true
2.
public class Equals {
public static void main(String[] args) {
String s1=new String("abc");//1000
String s2=new String("pqr");//2000
String s3 =new String ("abc");//3000
[Link](s1==s2);//false
[Link](s1==s3);//false
[Link]([Link](s2));//false
[Link]([Link](s3));//true
}
}
output:
false
false
false
true
3.
public class Equals {
public static void main(String[] args) {
String s1=new String("abc");//1000
String s2=new String("pqr");//2000
String s3 =new String ("abc");//1000
String s4="abc";
String s5="pqr";
String s6 ="abc";
[Link](s1==s4);//false
[Link](s1==s6);//false
[Link](s6==s3);//false
[Link](s5==s2);//false
[Link](s2==s4);//false
[Link](s3==s5);//false
[Link]([Link](s4));//true
[Link]([Link](s5));//true
}
}
output:
false
false
false
false
false
false
true
true
Ex: (String to Integer)
public class StringtoInteger {
public static void main(String[] args) {
String s1="10";
String s2="20";
[Link](s1+s2);
int i = [Link](s1);
int j = [Link](s2);
[Link](i+j);
/* String s5="Sushma";
int k =[Link](s5);
[Link](k);*/ //run time error, number format Exception.
}
}
Output:
1020
30
Note:
[Link] the size is known ,then we have to use for loop.
2. Whenever size is unknown, then we have to use for each loop.
Syntax:
for (data type variable: Array/collection)
{
}
Ex:
[Link] class Foreach {
public static void main(String[] args) {
String s= "Welcome to qspider institute";
String []s1=[Link]("\\s");
for(String obj: s1)
{[Link](obj);
}
}
}Output:
Welcome
to
qspider
institute
Note:
Every string class is overridden toString() method and it returns the implementation as String value.
Ex: (without overriding toString())
1. public class String1 {
public static void main(String[] args) {
Demo d = new Demo();//object
String s = "Sushma";//object
[Link](d);
[Link](s);
}
}
Output:
Demo@15db9742
Sushma
2. (with overriding toString())
public class Employee12 {
String name;
Employee12(String n)
{
name= n;
}
public String toString()
{
return"["+name+"]";
}
public static void main(String[] args) {
String s1="Sushma";
[Link](s1);
Employee12 e1= new Employee12("Raj");
Employee12 e2= new Employee12("Raj");
[Link](e1);
[Link](e2);
}
}
Output:
Sushma
[Raj]
[Raj]
Note:
1. Object class equals() method checks references but if we override equals ()method, it checks
contents.
2. In String class equals method is overridden and that equals method checks contents of the string.
Ex: (without overriding equals() method)
1. public class Employee12 {
String name;
Employee12(String n)
{
name= n;
}
public static void main(String[] args) {
String s1="Sushma";
String s2="Sushma";
Employee12 e1= new Employee12("Raj");
Employee12 e2= new Employee12("Raj");
[Link]([Link](e2));
[Link]([Link](s2));//equals method overridden
}
}
Output:
false
true
Q.(V.V.I) WAP to compare two object values?( (with overriding equals( ) method)
public class Employee12 {
String name;
Employee12(String n)
{
name= n;
}
public boolean equals([Link] o)
{
Employee12 e = (Employee12) o ;
return name==[Link];
}
public static void main(String[] args) {
String s1="Sushma";
String s2="Sushma";
Employee12 e1= new Employee12("Raj");
Employee12 e2= new Employee12("Raj");
[Link]([Link](e2));
[Link]([Link](s2));
}
}
Output:
true
true
Q. WAP to use override hash code method?
To generate hash code right clickgo to source click on generate hash code.
1.(without overriding hashcode)
public class Employee12 {
String name;
Employee12(String n)
{
name= n;
}
public static void main(String[] args) {
String s1="Sushma";
String s2="Sushma";
Employee12 e1= new Employee12("Raj");
Employee12 e2= new Employee12("Raj");
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
Output:
-1807166421
-1807166421
366712642
1829164700
2.(with overriding hashcode)
public class Employee12 {
String name;
Employee12(String n)
{
name= n;
}
public static void main(String[] args) {
String s1="Sushma";
String s2="Sushma";
Employee12 e1= new Employee12("Raj");
Employee12 e2= new Employee12("Raj");
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : [Link]());
return result;
}
@Override
public boolean equals([Link] obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != [Link]())
return false;
Employee12 other = (Employee12) obj;
if (name == null) {
if ([Link] != null)
return false;
} else if ()
return false;
return true;
}
}
Output:
-1807166421
-1807166421
81946
81946
Q:WAP to reverse a String?
import [Link];
public class String1 {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter a String");
String s = [Link]();
String rev="";
for(int i= [Link]()-1;i>=0;i--)
{
rev=rev+[Link](i);
}
[Link]("String reverse: "+rev);
}
}
Ex:
package [Link];
public class SBufferBuilder {
public static void main(String[] args) {
StringBuffer s1= new StringBuffer("abc");
StringBuffer s2= new StringBuffer("pqr");
[Link](s2);
[Link](s1);
StringBuilder s3= new StringBuilder("abc");
StringBuilder s4= new StringBuilder("pqr");
[Link](s4);
[Link](s3);
String s5="abc";
String s6= "pqr";
[Link](s6);
[Link](s5);
}
}
Output:
abcpqr
abcpqr
abc
ARRAY:
Array is a collection of homogeneous data type value.
Advantages: By using a single variable we can represent multiple values.
Drawback:
1. Array always allows homogeneous(same) data type value.
2. Array is of fixed size.
3. There is no utility methods are present in array for every action (e.g.: sort, contain).
4. There is no underlying data structure for Array.
Declaration of Array:
Single Dimensional Array 2 Dimensional Array 3 Dimensional Array
int [] i; int[] [] i; int[][][]i;
int i [] ; int i [] [] ; int i [][][];
int [] i; int[]i [] ; int[][][] i;
char [] c; int[] [] i; int[] []i[];
double [] d; int[] [][]i;
String [] s; int[] i[][];
Note: we can create nth dimensional Array.
Array creation:
Multi-Dimensional Array:
In java programming language multi-dimensional arrays are implemented on Arrays of Arrays
concept.
1.
2.
Ex:
public class Array4 {
public static void main(String[] args) {
int []a={1,4,6,8,9};
[Link]([Link]);
[Link]("<-------->");
for(int i=0;i<[Link];i++)
{
[Link](a[i]);
}
}
}
output:
5
<-------->
1
4
6
8
9
[Link] to find out sum of the Array elements?
public class Array5 {
public static void main(String[] args) {
int []a={1,4,6,8,9};
int sum=0;
for(int i=0;i<[Link];i++)
{sum=sum+a[i];
}
[Link]("Sum of array elemts "+ sum);
}
output:
Sum of array elemts 28
3.
import [Link];
public class Array8 {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter m size");
int m =[Link]();
[Link]("Enter n size");
int n =[Link]();
int[][] a = new int[m][n];
[Link]("Enter array elements");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=[Link]();
}
}
[Link]("<-------->");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
[Link](a[i][j]+" ");
}
[Link]();
}
}
}
output:
Enter m size
3
Enter n size
3
Enter array elements
1
21
3
4
5
6
7
8
9
<-------->
1 21 3
456
789
Encapsulation:
1. Encapsulation is a process of binding the data and code into a single component; it ensures that
data and code is safe. It is not freely available outside of the class.
2. Encapsulation can be achieved by declaring the fields as a private, by giving access to this field via
getter and setter.
Ex:
import [Link];
class Employee{
private String name;
private int id;
private int age;
private double sal;
public String getName() {
return name;}
public void setName(String name) {
[Link] = name;}
public int getId() {
return id;}
public void setId(int id) {
[Link] = id;}
public int getAge() {
return age;}
public void setAge(int age) {
[Link] = age;}
public double getSal() {
return sal;}
public void setSal(double sal) {
[Link] = sal;}
}
class DataBase{
void StoreData(Employee e)
{
[Link]("Name is "+[Link]()+"\nEmp Id is "+[Link]()+"\nEmployee age
is "+[Link]() +"\nEmployee salary is "+[Link]());
}
}
public class Encapsulation {
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
[Link]("Enter name:");
String name = [Link]();
[Link]("Enter Emp Id:");
int id = [Link]();
[Link]("Enter Age:");
int age = [Link]();
[Link]("Enter salary:");
double sal = [Link]();
Employee e = new Employee();
[Link](name);
[Link](id);
[Link](age);
[Link](sal);
DataBase d =new DataBase();
[Link](e);
}
}
output:
Enter name:
abc
Enter Emp Id:
1
Enter Age:
22
Enter salary:
5000
Name is abc
Emp Id is 1
Employee age is 22
Employee salary is 5000.0
Wrapper Class:
Converting from primitive data type to object and object to primitive data type is called wrapper
class.
Primitive (data type) Object (class)
1. byte Byte
2. short Short
3. int Integer
4. long Long
5. float Float
6. double Double
7. char Character
8. boolean Boolean
Throw able
}
output: It gives a compile time error, because try block should be followed by either catch or finally.
2. try block can be followed by multiple catch block.
3. The lines of code which may or not may not give an exception have to be enclosed inside try
block.
4. Once if the exception occurs inside the try block, control will immediately come out of try block by
not executing rest of the code.
5. Once if the control comes out of try block, it will search for corresponding catch block.
6. Once if the corresponding catch block found, that catch block is executed and rest of the catch
blocks wouldn’t be executed and after the catch block if any executable statements are present,
then those statements would be executed.
7. If the corresponding catch block is not found then program will get terminated and the
statements after the catch block wouldn’t be executed.
Note: After handling the exception in catch block the control will not go back to try block, so we
always write less codes inside the try block.
Syntax (try & catch block):
try
{
}
catch ()
{
}
catch ()
{ Statement4
}
Statement5
Case1: There is no exception statement 1, 2, 3 and 5 will execute.
Case2: If Exception occurs at statement 2 and if there is corresponding catch block then statement 1,
4 and 5 will execute.
Case3: If exception occurs at statement 2 and corresponding catch block is not found then
statement1 followed by abnormal termination.
Note: If any exception occurred which is not a part of try block i.e. always abnormal termination.
Ex:
1. package exceptionHandling;
public class Sample {
public static void main(String[] args) {
int num1=10;
int num2=0;
try
{
int num3=num1/num2;
[Link](num3);
[Link]("Hi");
}
catch (ArithmeticException e
{
[Link]("Arithmatic Exception Handled");
}
[Link]("I am out of Try n Catch Block");
}
}
Output: Arithmatic Exception Handled
I am out of Try n Catch Block
[Link] class Sample1 {
public static void main(String[] args) {
try
{String s = null;
[Link]([Link]());}
catch (ArithmeticException e)
{[Link]("Arithmatic Exception Handled");}
[Link]("I am out of Try n Catch Block");
}
}
Output:Run Time Error
Exception in thread "main" [Link] at
[Link]([Link])
3. public class Sample3 {
public static void main(String[] args) {
try{
int[] i=new int[4];
i[9]=10;}
catch (ArithmeticException e){
[Link]("Arithmatic Exception Handled");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array Index Out Of Bound Handled");
}
catch(Exception e)
{
[Link]("General Exception");}
[Link]("I am out of Try n Catch Block");}
}
Output:
Array Index Out Of Bound Handled
I am out of Try n Catch Block
Note: catch (Exception e) is a general exception, if there is no specific exception for try block then it
will execute general exception.
Ex:
4. public class Sample4 {
public static void main(String[] args) {
try
{
int[] i=new int[4];
i[3]=10;
try{
String s = "Sushma";
int j=[Link](s);
[Link](j);
}catch(Exception e)
{[Link]("General Exception Handled");}
}
catch (NumberFormatException e)
{
[Link]("Number Format Exception Handled");
}
[Link]("I am out of Try n Catch Block");
}
}
output:
General Exception Handled
I am out of Try n Catch Block
5.
package exceptionHandling;
public class Sample5 {
public static void main(String[] args) {
try{
int[] i=new int[4];
i[8]=10;
try{
String s = "Sushma";
int j=[Link](s);
[Link](j);
}catch(Exception e)
{
[Link]("General Exception Handled");
}
}
catch (NumberFormatException e)
{[Link]("Number Format Exception Handled");
}
[Link]("I am out of Try n Catch Block");
}
}
output:
Exception in thread "main" [Link]: 8
at [Link]([Link])
6.
public class Sample6 {
public static void main(String[] args) {
try
{int[] i=new int[4];
i[3]=10;
try{
String s = "Sushma";
int j=[Link](s);
[Link](j);
}catch(NullPointerException e)
{
[Link]("Null Pointer Exception Handled");
}
}
catch (NumberFormatException e)
{[Link]("Number Format Exception Handled");}
[Link]("I am out of Try n Catch Block");
}
}
Output:
Number Format Exception Handled
I am out of Try n Catch Block
Note:
1. We can have nested try catch block.
2. If the nested try catch block is not handled the exception, it will throw the exception to the main
try block and if the main try block is having any corresponding catch block, then that catch block will
handle the exception.
7. public class Sample7 {
public static void main(String[] args) {
try
{int[] i=new int[4];
i[9]=10;
try{
String s = "Sushma";
int j=[Link](s);
[Link](j);
}catch(ArrayIndexOutOfBoundsException e)
{[Link]("ArrayIndexOutOfBounds Exception Handled");}
}
catch (NumberFormatException e){
[Link]("Number Format Exception Handled");
}
[Link]("I am out of Try n Catch Block");
}
}
output:
Exception in thread "main" [Link]: 9
at [Link]([Link])
Note:
Catch block should be most specific to most general, it shouldn’t be most general to most specific.
Ex:
public class Sample8 {
public static void main(String[] args) {
try{int i=10/0;
[Link](i);}
catch (Exception e){
[Link]("General Exception Handled");
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception Handled");}
[Link]("I am out of Try n Catch Block");
}
}
Output:gives compile time error.
Note:
We shouldn’t write executable statement between try catch block.
Ex:
public class Sample9 {
public static void main(String[] args) {
try{int i=10/0;
[Link](i);}
[Link]("Hi");
catch(Exception e)
{[Link]("General Exception Handled");
}
}
}
output: gives compile time error.
Ex:
public class Sample9 {
public static void main(String[] args) {
try
{
int i=10/0;
[Link](i);
}
catch(Exception e)
{
[Link](e);
}
}
}
Output:
[Link]: / by zero
Note:
There are 3 ways to get exception information:
[Link] message()method: It returns only description of the exception.
[Link] () method: It returns description along with the exception name.
[Link] () method: It returns description, exception name & location.
Ex: public class Sample10 {
public static void main(String[] args) {
try
{
int i=10/0;
[Link](i);
}
catch(Exception e)
{//[Link]([Link]());
//[Link]([Link]());
[Link]();
}
}
}
Output:
[Link]: / by zero
at [Link]([Link])
finally:
1. It is a block which is executed for sure, even if you handle the exception.
2. If we want some code to be execute without fail, then we must write that code inside finally block.
3. finally block is mainly used to clean up the resources.
4. It is always recommend to write clean up code inside the finally block.
5. A single try block can have only one finally block.
Ex:
1. public class Sample11 {
public static void main(String[] args) {
try
{
int i=10/0;
[Link](i);
}
catch(NullPointerException e)
{
[Link]("NullPointerException handled");}
finally{
[Link]("I am in finally block");}
[Link]("Hi");}
}
output:
I am in finally block
Runtime error.
2.
public class Sample12{
public static void main(String[] args) {
try{
int i=10/0;
[Link](i);
}
catch(ArithmeticException e)
{[Link]("ArithmeticException handled");}
finally
{[Link]("I am in finally block");
}
[Link]("Hi");
}
}
output:
ArithmeticException handled
I am in finally block
Hi
3. package exceptionHandling;
import [Link];
class MinAge extends Exception//custom exception class
{
public String toString()
{
return "Sorry your age should be greater than 18";
}
}
class MaxAge extends Exception//custom exception class
{
public String toString()
{
return "Sorry your age should be less than 30";
}
}
class Display2
{
void check(int age) throws MinAge,MaxAge
{
if(age>18&&age<30)
{
[Link]("License issued");
}
else if(age<18)
{
throw new MinAge();
}
else if(age>30){
throw new MaxAge();
}
}
}
public class throwandthrows2 {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter age");
int age= [Link]();
Display2 d = new Display2();
try
{
[Link](age);
}
catch(MinAge m)
{[Link](m);
}
catch(MaxAge n)
{[Link](n);
}
}
}
Output:
Enter age
14
Sorry your age should be greater than 18
throw throws
Note:
Checked exception are handle in 2 ways:
[Link]&catch block:
handle the exception in the same method where the exception occur.
[Link]:
throws is used to delicate the exception handling to the caller method so that the caller method
provide handling code.
Array Collection
1. Array allows Homogeneous data type 1. Collection allows Homogeneous data type
values. values.
2. It is of fixed size. 2. It is growable and shrinkable.
3. No utility methods are present. 3. Utility methods are present.
4. No underlying data structure for Array. 4. Every collection classes have underlying data
5. With respect to performance Array is structure.
good. 5. With respect to performance collection is bad.
6. With respect to memory Array is bad. 6. With respect to memory collection is good.
Collection:
1. It is an interface which is present in [Link] package.
2. It is collection of individual object as single entity.
Note: Route of collection is iterable.
Collections:
It is a utility class and all the utility methods are present in collection class.
Methods of collections:
1. Add(object o)
2. addAll(collection c)
[Link](object o)
4. removeAll(collection c)
5. Size
6. Contains (object o)
7. containsAll(collection c)
8. Get (int index)
[Link] ()
10. Iterator ()
Collection (I)
Stack(c) v1.0
Note:
Vector and stack are legacy classes (which ever classes introduced in earlier version we call it as
legacy classes).
3. Set (I): It is a child class interface of collection interface. If we want to represent group of objects
as a single entity where duplicate objects is not allowed and insertion order is not preserved then we
should go for Set interface.
Collection (I)
Set (I)
Hash set(c)
4. Sorted Set (I): It is a child class interface of collection interface. If we want to represent group of
objects as a single entity where duplicate objects are not allowed but insertion order is preserved.
Collection (I)
Set (I)
4. Navigable Set (I): It is a child class interface of Sorted set interface. Mainly used for navigation
purpose.
Collection (I)
Set (I)
Queue (I)
Note: collection is mainly used to transfer collection of individual object from one place to another
place.
Note: Whenever we are adding the value to the collection classes there is 2 operations performed
internally
1. Up casting.
2. Autoboxing.
Ex:
import [Link];
public class collection1 {
public static void main(String[] args) {
ArrayList a= new ArrayList();
[Link](5);
[Link]("rashda");
[Link]('a');
[Link](20.0);
[Link](5);
[Link](a);
}
}
output:
[5, rashda, a, 20.0, 5]
Note:
1. Every collection classes is overridden toString() method and it returns the implementation in the
following format: [obj1, obj2, obj3…….]
[Link] we add values to the collection classes every collection class would be treated as object
and there are 2 operations that get performed internally : [Link] b. Up casting.
Ex: import [Link];
public class collection2 {
public static void main(String[] args) {
ArrayList a = new ArrayList();
[Link](4);
[Link]("Sushma");
[Link](2.0);
[Link]('a');
[Link](4);
for(Object obj : a)
{
[Link](obj);
}
}
}
output:
4
Sushma
2.0
a
4
Ex:
import [Link];
import [Link];
public class collection3 {
public static void main(String[] args) {
ArrayList a = new ArrayList();
[Link](4);
[Link]("Sushma");
[Link](2.0);
[Link]('a');
[Link](4);
Iterator it = [Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
Output:
4
Sushma
2.0
a
4
[Link] to display even number and remove add number from collection?
import [Link];
import [Link];
public class collection5 {
public static void main(String[] args) {
ArrayList l= new ArrayList();
[Link](4);
[Link](1);
[Link](5);
[Link](6);
[Link](10);
[Link](l);
Iterator it = [Link]();
while([Link]())
{Integer i=(Integer) [Link]();
if(i%2==0)
{
[Link](i);
}
else
{[Link]();
}
}
[Link](l);
}
}
output:
[4, 1, 5, 6, 10]
4
6
10
[4, 6, 10]
[Link] to delete abc, add spider when qspider , replace jspider with sushma?
package collection;
import [Link];
import [Link];
public class Collection6{
public static void main(String[] args) {
LinkedList l = new LinkedList();
[Link]("abc");//remove
[Link]("qspider");//add spider
[Link]("jspider");//sushma
[Link]("pqr");
[Link]("xyz");
[Link](l);
ListIterator it = [Link]();
while([Link]())
{String s= (String)[Link]();
if([Link]("abc"))
{
[Link]();
}
else if([Link]("qspider"))
{[Link]("spider");
}
else if([Link]("jspider"))
{
[Link]("Sushma");
}
}
[Link](l);
}
}
output
[abc, qspider, jspider, pqr, xyz]
[qspider, spider, Sushma, pqr, xyz]
Q.
import [Link];
import [Link];
public class collection7 {
public static void main(String[] args) {
Vector v = new Vector();
[Link](2);
[Link]("abc");
[Link]('a');
[Link](5.0);
[Link](2);
Enumeration e= [Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
output:
2
abc
a
5.0
2
Types of Cursor:
[Link]:
a. It was introduced in 1.o version.
b. It is applicable only for legacy classes and it is not applicable for Array list, linked list and set
interface classes. Hence it is not universal cursor. It is a single directional cursor i.e. we can display
the object only in forward direction. By using Enumeration cursor we can perform only read
operation.
2. Iterator:
a. It is a universal cursor i.e. it is applicable for all kind of list interface classes and set interface
classes.
b. It is a single directional cursor i.e. we can display the elements only in forward direction. By using
iterator we can perform only read and remove operation (we can’t perform addition and
replacement).
3. List iterator:
a. It is a bidirectional cursor i.e. we can display the elements in both forward & backward direction.
b. It is not a universal cursor i.e. it is applicable only for all kind of list interface classes and it is not
applicable for set interface classes.
c. By using List iterator we can perform read, remove, add and replacement operation.
Array List:
[Link] dynamic array to store the elements.
2. In Array list bit shifting is required, if any elements are removed from the Array or if any elements
added to the array all the bits are shifted to the memory, so manipulation is slow.
3. All the methods of Array list are not synchronized and not a thread safe and it is multithreaded. 4.
Once if the array list object is created the initial capacity of Array list is 10, once if it exceeds it uses
one formula to create the memory allocation i.e.
new capacity = old capacity *3/2+1
4. The underlying data structure is dynamic Array.
5. Duplicate objects are allowed, Insertion order is preserved, heterogeneous values are allowed.
6. It is an index based collection, Array list is best choice if our frequent operation is retrievable.
Array list implements random access interface, this random access interface helps us to retrieve the
object faster.
Linked list:
[Link] doubly linked list to store the elements.
2. In linked list bit shifting is not required, so manipulation is fast.
3. The underlying data structure is doubly linked list.
4. Duplicate objects are allowed, Insertion order is preserved, heterogeneous values are allowed.
5. It is a best choice if our frequent operation is addition or deletion. It is a worst choice if our
frequent operation is retrievable (compare to array list).
Vector:
[Link] dynamic array to store the elements.
2. All the methods of vector are synchronized and it is a single threaded and it is a thread safe.
3. It is internally uses dynamic Array to store the elements.
4. Duplicate objects are not allowed, Insertion order is preserved, heterogeneous values are allowed.
5. It is a best choice if our frequent operation is retrievable. Every methods of vector are
synchronised.
Note:
1. Array list and vector are best choice if our frequent operation is retrievable. (Retrievable means in
between storing and displaying we don’t required any addition and deletion).
2. Array list and vector are worst choice if our frequent operation is addition or deletion.
3. Linked list is a best choice if our frequent operation is addition or deletion.
Hash Set:
1. Hash set is a child interface of set interface.
2. The underlying data structure is hash table.
3. Duplicate objects are not allowed, Insertion order is not preserved, heterogeneous objects are
allowed.
Ex:
import [Link];
import [Link];
public class hasset {
public static void main(String[] args) {
HashSet h = new HashSet();
[Link](7);
[Link](1);
[Link](9);
[Link]("sushma");
[Link](7);
[Link](h);
[Link]("<....for each loop......>");
for(Object o:h)
{
[Link](o);
}
[Link]("<.......Iterator cursor........>");
Iterator it = [Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
output:
[1, 7, sushma, 9]
<....for each loop......>
1
7
sushma
9
<.......Iterator cursor........>
1
7
sushma
9
Linked Hash Set:
[Link] Hash set is a child class of hash set.
2. Duplicate objects are not allowed, Insertion order is preserved, heterogeneous objects are
allowed.
Ex:
import [Link];
import [Link];
public class linkedhashset {
public static void main(String[] args) {
LinkedHashSet h = new LinkedHashSet();
[Link](7);
[Link](1);
[Link](9);
[Link]("sushma");
[Link](7);
Iterator it = [Link]();
while([Link]())
{[Link]([Link]());
}
}
}
output:
7
1
9
sushma
Tree Set:
Duplicate objects are not allowed, Insertion order is preserved, heterogeneous objects are not
allowed, if we are trying to add heterogeneous object we will get class cast exception(because
objects are inserted /display in ascending order).Insertion order is not preserved because object will
be inserted according to ascending order.
Ex:
import [Link];
import [Link];
public class treeset {
public static void main(String[] args) {
TreeSet t = new TreeSet();
[Link](7);
[Link](1);
[Link](9);
//[Link]("sushma"); gives compile time error,class cast exception
[Link](4);
[Link](10);
[Link](4);
Iterator it = [Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
output:
1
4
7
9
10
Note: the number one searching mechanism is hashing mechanism (hash set or linked hash set)
I.Q: Why hash set and linked hash set or set don’t allow duplicate values?
Ans: Because hash set and linked hash set uses hash table to store the value where duplicate object
not allowed to store .when we create duplicate object , it get stored in same hash bucket in hash
table.
Ex:
public class collection8 {
public static void main(String[] args) {
collection8 d= new collection8();
[Link](d);//classname@hashcode,in hexadecimal.
[Link]([Link]());//hashcode, in decimal
}
}
output:
collection.collection8@15db9742
366712642
Map:
Map is an interface which is present in [Link] package. If we want to represent collection of
individual object as a key value pair then we should go for map interface.
Syntax: Map<key, value>
Key is an object, value is an object, duplicate keys are not allowed, and duplicate values are
allowed.
1. Hash Map:
The underlying data structure is Hash table. Duplicate keys are not allowed. However, duplicate
values are allowed, insertion order is not preserved i.e. we can’t maintain the order.
Ex:
import [Link];
import [Link];
public class hashmap {
public static void main(String[] args) {
HashMap<Integer,String> h= new HashMap<Integer,String>();
[Link](2, "john");
[Link](1, "Mike");
[Link](10, "Adam");
[Link](5, "Sam");
for([Link] obj: [Link]())
{
[Link]([Link]()+"\t\t"+[Link]());
}
}
}
output:
1 Mike
2 john
5 Sam
10 Adam
2. Linked Hash Map: The underlying data structure is Hash table. Duplicate keys are not allowed,
duplicate values are allowed, and insertion order is preserved.
Ex:
import [Link];
import [Link];
public class linkedhashmap {
public static void main(String[] args) {
LinkedHashMap<Integer,String> h= new LinkedHashMap<Integer,String>();
[Link](2, "john");
[Link](1, "Mike");
[Link](10, "Adam");
[Link](5, "Sam");
for([Link] obj: [Link]())
{
[Link]([Link]()+"\t\t"+[Link]());
}
}
}
output:
2 john
1 Mike
10 Adam
5 Sam
3. Tree Map:
Duplicate keys are not allowed, duplicate values are allowed, insertion order is not preserved all the
elements are sorted according to ascending order.
Ex:
import [Link];
import [Link];
public class treemap {
public static void main(String[] args) {
TreeMap<Integer,String> h= new TreeMap<Integer,String>();
[Link](2, "john");
[Link](1, "Mike");
[Link](10, "Adam");
[Link](5, "Sam");
[Link](1, "pqr");
[Link](7, "abc");
for([Link] obj: [Link]())
{
[Link]([Link]()+"\t\t"+[Link]());
}
}
}
output:
1 pqr
2 john
5 Sam
7 abc
10 Adam
Note:
[Link] () method:
It is a method used to add object to the map interface.
2. Enter Set ():
It is a method used to iterate the object from map interface.
3. Map is an interface; Entry is a sub interface of Map interface.
4. getkey () and get value () methods are available inside [Link].
5. getkey () is a method which is used to get all the keys.
6. getvalue() is a method used to get all the values.
File Handling:
Q. WAP to create a text file?
import [Link];
import [Link];
public class createtextfile
{
public static void main(String[] args)throws IOException
{
File f = new File("[Link]");
[Link]([Link]());
try
{
[Link]();
}
catch(IOException e)
{
[Link]("Handled");
}
[Link]([Link]());
}
}
output:
For the first time execution false & true, and second time execution output is true & true.
[Link] to check what is the output if we are not providing a name while creating the file?
import [Link];
import [Link];
public class createtextfile2
{
public static void main(String[] args)throws IOException
{
File f = new File(" ");
[Link]([Link]());
try
{
[Link]();
}
catch(IOException e)
{
[Link]("Handled");
}
[Link]([Link]());
}
}
output:
false
Handled
false
Note: mkdir() is a folder used to create a folder.
Ex:
import [Link];
import [Link];
public class createfolder {
public static void main(String[] args) throws IOException
{
File f = new File("Rashda");
[Link]([Link]());
try
{
[Link]();
}
catch(Exception e)
{
[Link]("Handled");
}
[Link]([Link]());
}
}
output:
For the first time execution false & true, and second time execution output is true & true.
Note:
1. FileWriter is a class which is present in [Link] package.
2. Flush() is a method used to cleanup all the resources.
[Link] tocreate a folder or file anywhere in the document?
import [Link];
import [Link];
public class createdir {
public static void main(String[] args) throws IOException
{
File f = new File("D:\\FileRashda1\\[Link]");
[Link]([Link]());
try
{
[Link]();
}
catch(Exception e)
{
[Link]("Handled");
}
[Link]([Link]());
}
}
output:
For the first time execution false & true, and second time execution output is true & true.
Q5. WAP to store the data to the text file?
import [Link];
import [Link];
public class storetextinfile {
public static void main(String[] args) throws IOException
{
FileWriter f = new FileWriter("D:\\FileRashda1\\[Link]");
[Link]("Qspider is a institute");
[Link]();
[Link]("execute");
}
}
output:execute
Q6. WAP to append data?
import [Link];
import [Link];
public class appenddata {
public static void main(String[] args) throws IOException
{
FileWriter f = new FileWriter("D:\\FileRashda1\\[Link]",true);
[Link]("jspider is a institute");
[Link]();
[Link]("execute");
}
}
output: execute
Note:
In fileWriter it store all the data character by character another drawback is it doesn’t support line
separator.
BufferdWriter:
It is a class which is present in [Link] package. It can’t communicate directly with any text file; it has
to communicate via FileWriter.
In BufferedWriter, it will store the data line by line.
If we want to overcome the drawbacks associated with FileWriter then we have to go for
Bufferedwriter.
Ex:
import [Link];
import [Link];
import [Link];
public class appenddatainnextline {
public static void main(String[] args) throws IOException
{
FileWriter f = new FileWriter("D:\\FileRashda1\\[Link]",true);
BufferedWriter b=new BufferedWriter(f);
[Link]("Qspider");
[Link]();
[Link]("jspider");
[Link]();
[Link]("spider");
[Link]();
[Link]();
[Link]("execute");
}
}
output:execute
Note:
1. FileReader is a class which is present in [Link] package.
2. Read () is a method used to read data character by character. Once if it is reaches end of the file
i.e. equal to -1.
3. Read() method return type is int.
Ex:
[Link] to read the data from the text file?
import [Link];
import [Link];
public class readdata {
public static void main(String[] args) throws IOException
{
FileReader f = new FileReader("D:\\FileRashda1\\[Link]");
int i;
while((i=[Link]())!=-1)
{[Link]((char)i);
}
}
}
output:
Qspider
jspider
spider
Note:
[Link] is a class present in [Link] package.
2. ReadLine () is a method that reads all the data line by line.
3. In BufferedReader once it reaches to the end of the line i.e. equal to null.
Ex:
import [Link];
import [Link];
import [Link];
public class readdatafromtextfile {
public static void main(String[] args) throws IOException
{
FileReader f = new FileReader("D:\\FileRashda1\\[Link]");
BufferedReader b= new BufferedReader(f);
String s;
while((s=[Link]())!=null)
{[Link](s);
}
}
}
output:
Qspider
jspider
spider
[Link] to list all the files? which is present in the given folder?
package filehandling;
import [Link];
import [Link];
public class listfiles {
public static void main(String[] args) throws IOException
{
File f = new File("D:\\FileRashda1 ");
File [] f1=[Link]();
for(File obj:f1)
{[Link](obj);
}
}
}
output:
D:\FileRashda1 \[Link]
D:\FileRashda1 \[Link]
D:\FileRashda1
[Link] take input from user using inuputstreamreader?
package filehandling;
import [Link];
import [Link];
import [Link];
public class bufferreader {
public static void main(String[] args) throws IOException
{
InputStreamReader i= new InputStreamReader([Link]);
BufferedReader b = new BufferedReader(i);
[Link]("Enter name");
String s= [Link]();
[Link](s);
}
}
output:
Enter name
rashda
rashda
Q. WAP to read the second line from the given file?
package filehandling;
import [Link];
import [Link];
import [Link];
public class secondlinefromfile {
public static void main(String[] args) throws IOException
{
String f=[Link]([Link]("D:\\FileRashda1\\[Link]")).get(1);
[Link](f);
}
}
output:
jspider
[Link] to count how many words are present in the given file?
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class countwordsinfile {
public static void main(String[] args) throws IOException
{File f = new File("[Link]");
[Link]();
if ([Link]())
{
[Link]("Total Words=" + getWordCount(f));
} else
{
[Link]("File does not exists!");
}
}
private static int getWordCount(File f) {
int words = 0;
try {
FileReader T = new FileReader(f);
BufferedReader br = new BufferedReader(T);
String line = [Link]();
while (line != null) {
String[] words1 = [Link](" ");
for (String w : words1) {
words++;
}
line = [Link]();
}
} catch (IOException e) {
[Link]("Handled"+e);}
return words;}
}
Multitasking:
Executing several task simultaneously is called multitasking. Multitasking is divided into 2 types:
[Link] or process based multitasking:
Executing several task simultaneously, where each task is having an independent process i.e. we can
call it as a multiprocessing.
2. Multithreading or Thread based multitasking:
Executing several tasks simultaneously, where each task is having an independent part of the same
program is called multithreading.
Thread:
[Link] is a class , which is present in [Link] package.
2. Thread has a separate path of execution.
3. Threads are independent i.e. if any exception occurs to the one thread it doesn’t affect to the
other thread.
4. Threads shares common memory.
Thread Life cycle:
Thread life cycle consist of 5 states:
[Link] or new state:
The thread is in a new state, once we create the object of thread class.
2. Runnable state:
Once we start the execution of thread, thread moves from new to runnable state.
3. Running state:
Once the threads are selected by thread scheduler, that thread is moving from runnable to running
state.
4. Dead state:
Once the run method invocation complete threads are move from running to dead state and the
threads get destroyed.
5. Block state:
In this state threads are still alive but not eligible to run.
Thread Scheduler:
It is just a part of JVM. There is no guarantee which thread would get selected by thread scheduler.
Methods of thread class:
1. Start() method: It is used to start the execution of thread.
2. Run () method: it is used to perform some action of the thread.
3. Sleep () method: it causes the currently executing thread to sleep for the specified number of
millisecond.
4. Wait () method: it makes the thread to wait in waiting state.
5. Notify () method: It wakes up only one thread, present in waiting state.
6. Notify All () method: It wakes up all the threads, present in waiting state.
7. getpriority () method: It returns priority of a thread.
8. setpriority() method: It changes the priority of thread.
9. getname() method: It returns name of a thread.
10. setname() method: It changes name of the thread.
Ex:
[Link] thread class:
public class extendingthreadclass extends Thread
{
public void run()
{
for(int i=0;i<=5;i++)
{
[Link](i);
}
}
public static void main(String[] args) {
extendingthreadclass d= new extendingthreadclass();//thread object
[Link]();
}
}
output:
0
1
2
3
4
5
[Link] runnable interface:
package thread;
public class implementingrunnableinterface implements Runnable {
public void run()
{
for(int i=0;i<=5;i++)
{
[Link](i);
}
}
public static void main(String[] args) {
implementingrunnableinterface d= new implementingrunnableinterface();//thread object
Thread t= new Thread(d);
[Link]();
}
}
output:
0
1
2
3
4
5
EX: sleep method:
public class sleep {
public static void main(String[] args)throws InterruptedException
{Thread t = new Thread();
[Link]("Hi");
[Link](3000);
[Link]("heloo");
[Link](3000);
[Link]("Bye");
[Link](3000);
[Link]("Qspider");
}
}
output:
Hi
heloo
Bye
Qspider
EX: (Multithreading)
class Display
{ void print(int n)
{
for(int i=1;i<=5;i++)
{
[Link](n*i);
try
{
[Link](3000);}
catch(InterruptedException e)
{
[Link]("Handled");
}
}
}
}
class MyThread1 extends Thread{
Display d;
MyThread1(Display d)
{this.d=d;}
public void run()
{
[Link](5);
}
}
class MyThread2 extends Thread
{
Display d;
MyThread2(Display d)
{this.d=d;}
public void run()
{
[Link](10);
}
}
public class Multithreading {
public static void main(String[] args) throws InterruptedException
{Display d= new Display();
MyThread1 m = new MyThread1(d);//Thread class object
MyThread2 n=new MyThread2(d);
[Link]();
[Link]();
}
}
output:
5
10
10
20
15
30
20
40
25
50
Note:
[Link] a user define class extended thread class then the object of user defined class is of thread
class object.
2. In the above program if you make the display class print method as a synchronized i.e. we can
make it single threaded and output is as:
output:
5
10
15
20
25
10
20
30
40
50
Synchronization:
[Link] java it is capability to control the access of multithread to any shared resource.
2. Java Synchronization is better option if we want to allow only one thread to access the shared
resource.
3. It is mainly used to prevent the consistency problem.
4. If we make any method as synchronised, we can call it as synchronised method.
5. Synchronization is built around an internal entity known as lock.
6. Every object has a lock associated with it.
7. Synchronised method is used to lock an object for any shared resource.
8. When a thread invokes a synchronised method it automatically acquires lock for that object and
releases it when the thread completes its task.
Q. WAP to sort in ascending order?
package thread;
import [Link];
import [Link];
class Movie implements Comparable<Movie>
{
String name;
double rating;
int year;
Movie(String n, double r, int y)
{name=n;
rating= r;
year= y;
}
public int compareTo(Movie m)
{
if([Link]>[Link])
return 1;
else if([Link]<[Link])
return -1;
else
return 0;}
}
public class sortobjects {
public static void main(String[] args)
{Movie m1= new Movie("Ricky",9.0,2016);
Movie m2= new Movie("Fastandfurious",10.0,2017);
Movie m3= new Movie("Bahubali",8.0,2015);
ArrayList<Movie> a = new ArrayList<Movie>();
[Link](m1);
[Link](m2);
[Link](m3);
[Link](a);
for(Movie obj :a)
{[Link]([Link]+"\t\t"+[Link]+"\t\t"+[Link]);
}
}
}
output:
Bahubali 8.0 2015
Ricky 9.0 2016
Fastandfurious 10.0 2017
Difference between Comparable and comparator:
Comparable Comparator
Note:
1. Compare method() ,compares the first object with 2nd object.
2. Compareto () method is used to compare the current object with the specified object.
3. Compareto () method is used mergesort () method to sort the element.
Ex: (comparator)
import [Link];
import [Link];
import [Link];
class Movie1
{
String name;
int year;
double rating;
Movie1(String n, int y, double r)
{
name= n;
year= y;
rating =r;
}
}
class Yearcomparator implements Comparator<Movie1>
{
public int compare(Movie1 m1, Movie1 m2) {
if([Link]>[Link])
return 1;
else if([Link]<[Link])
return -1;
else
return 0;
}
}
class Ratingcomparator implements Comparator<Movie1>
{
public int compare(Movie1 m1, Movie1 m2) {
if([Link]>[Link])
return 1;
else if([Link]<[Link])
return -1;
else
return 0;
}
}
public class comparator
{
public static void main(String[] args) {
Movie1 m1= new Movie1("Ricky", 2015,10.0);
Movie1 m2= new Movie1("Bahubali", 2017,8.0);
Movie1 m3= new Movie1("fastandFurious", 2016,9.0);
ArrayList<Movie1> a= new ArrayList <Movie1>();
[Link](m1);
[Link](m2);
[Link](m3);
[Link]("Sorting based on year");
[Link](a, new Yearcomparator());
for(Movie1 obj : a)
{
[Link]([Link]+"\t\t"+[Link]+"\t\t"+[Link]);
}
[Link]("Sorting based on rating");
[Link](a, new Ratingcomparator());
for(Movie1 obj : a)
{
[Link]([Link]+"\t\t"+[Link]+"\t\t"+[Link]);
}
}
}
output:
Sorting based on year
Ricky 10.0 2015
fastandFurious 9.0 2016
Bahubali 8.0 2017
Sorting based on rating
Bahubali 8.0 2017
fastandFurious 9.0 2016
Ricky 10.0 2015
Object Array:
Object Array allows both homogeneous and as well as heterogeneous value. We can iterate the
object Array element by using for loop or for each loop.
Ex:
[Link] class objectarray {
public static void main(String[] args) {
Object [] o= new Object[5];
o[0]=1;
o[1]=2.0;
o[2]='A';
o[3]="Rashda";
o[4]=true;
[Link]("By using for each loop");
for(Object obj : o)
{
[Link](obj);
}
[Link]("By using for loop");
for(int i=0;i<[Link];i++)
{[Link](o[i]);
}
}
}
output:
By using for each loop
1
2.0
A
Rashda
true
By using for loop
1
2.0
A
Rashda
2.
public class Arrayobject
{
public static void main(String[] args) {
Object [] o= new String[5];
o[0]=1;
o[1]=2.0;
o[2]='A';
o[3]="Rashda";
o[4]=true;
[Link]("By using for each loop");
for(Object obj : o)
{
[Link](obj);
}
[Link]("By using for loop");
for(int i=0;i<[Link];i++)
{[Link](o[i]);
Object [] o1= new Integer[5];
o1[0]=1;
o1[1]=2.0;
o1[2]='A';
o1[3]="Rashda";
o1[4]=true;
for(Object obj : o1)
{
[Link](obj);
}
}
}
}
output:
Gives runtime error ArrayStoreException.
I.Q: Difference between Array value of index and Array store exception?
Array Store Exception:
Whenever we are trying to add incompatible data type value , gives runtime error i.e. Array store
exception.
Singleton Class:
Singleton class is mainly used to create a single Object. In Singleton class, we must make the
constructor as private so that an object can’t be created outside of the class. Singleton pattern helps
us to keep only one instance of a class at any time. The purpose of singleton is to control the object
creation by keeping a private constructor.
Ex:
public class Mysingleton {
private static Mysingleton obj;
private Mysingleton()
{
}
static Mysingleton getInstance()
{
if(obj== null)
{
obj= new Mysingleton();
}
return obj;
}
void show()
{
[Link]("Hi");
}
public static void main(String[] args) {
Mysingleton m= [Link]();
[Link]();
}
}
Marker Interface:
[Link] is an interface that doesn’t contain any data . Ex: serialsable.
2. Converting from object to byte code is called serialisation.
3. Converting from bytecode to object is called as deserialization.
4. For serialisation, we need to use objectoutputstream class and have to use writeobj () method.
Ex: class CarRace implements Serialisable
{String Pn =”abc”;
int level=3;
int score = 1000;
Public static void main(String [] args)
{Fileoutputstream f= new Fileoutputstream(“[Link]”);//need to provide full path as D://[Link]
objectoutputstream o = new objectoutputstream(f);
CarRace c = new CarRace();
[Link](c);
[Link]();
}
}
5. For deserialization, we need to use objectinputstream class and have to use readobj () method.
Ex: class CarRace
{ Public static void main(String [] args)
{FileInputstream f= new FileoInputstream(“[Link]”);
objectInputstream obj = new objectinputstream(f);
CarRace c = ( CarRace) [Link]();
[Link](“[Link]”);
[Link](“[Link]”);
[Link](“[Link]”);
[Link]();
}
}
Stack overflow:
If the memory is not available to create a stack frame in the stack memory then we will get stack
overflow error.
Ex:
public class recurssion {
static void m1(){
m1();
[Link]("m1");
}
public static void main(String[] args) {
m1();
}
}
output:
gives runtime error(stack overflow).
[Link] to print 1 to 10 without using for loop?
public class recurssion {
static void m1(int i){
if(i<=10)
{
[Link](i);
i++;
m1(i);
}}
public static void main(String[] args) {
m1(1);
}
}
Finalize:
finalize is a method , which is used to remove the unused object from the memory.
finally is a method.
final is a class.
Inner class:
A class is contain in another class is called inner class. Inner class is mainly used to give the security
to the particular class.
Ex:
class Facebook//outerclass
{
Album a= new Album();
void login()
{[Link]("loginned succesfully");
[Link]();
}
class Album//nested class, inner class
{
void displayimages()
{
[Link]("Displaying images");
}
}
}
public class innerclass {
public static void main(String[] args) {
Facebook f= new Facebook();
[Link]();
}
}
output:
loginned successfully
Displaying images