Installing Eclipse
Installing Eclipse
1. Goto “src”.
2. Click on “New”.
3. Click on “Package”.
Step 13) Writing package name.
Java Programming is a widely used robust technology. Let's start learning of java from basic
questions like what is java ,core java, where it is used, what type of applications are created in
java and why use java.
What is Java
Java is a programming language and a platform.
Java Example
Let's have a quick look at java programming example. A detailed description of hello java
example is given in next page.
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Output:
Hello java
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently
used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in, javapoint.com etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
9.
1) Standalone Application
2) Web Application
An application that runs on the server side and creates dynamic page, is called web application.
Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in
java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for creating
enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.
History of Java
1. Brief history of Java
2. Java Version History
Java history is interesting to know. The history of java starts from Green Team. Java team
members (also known as Green Team), initiated a revolutionary task to develop a language
for digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for
internet programming. Later, Java technology as incorporated by Netscape.
James Gosling
Currently, Java is used in internet programming, mobile devices, games, e-business solutions
etc. There are given the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project
in June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like U.S.A.,
France, Germany, Romania etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Why Java name for java language?
7) Why they choosed java name for java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They
wanted something that reflected the essence of the technology: revolutionary, dynamic, lively,
cool, unique, and easy to spell and fun to say.
According to James Gosling "Java was one of the top choices along with Silk". Since java was
so unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
There are many java versions that has been released. Current stable release of Java is Java SE
8.
Features of Java
1. Features of Java
1. Simple
2. Object-Oriented
3. Platform Independent
4. secured
5. Robust
6. Architecture Neutral
7. Portable
8. High Performance
9. Distributed
10. Multi-threaded
There is given many features of java. They are also known as java buzzwords. The Java
Features given below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading
etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection in java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that
incorporates both data and behaviour.
Platform Independent
A platform is the hardware or software environment in which a program runs. There are two types
of platforms software-based and hardware-based. Java provides software-based platform. The Java
platform differs from most other platforms in the sense that it's a software-based platform that runs
on top of other hardware-based platforms.It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Secured
Java is secured because:
• No explicit pointer
• Programs run inside virtual machine sandbox.
• Classloader- adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
• Bytecode Verifier- checks the code fragments for illegal code that can violate access right to
objects.
• Security Manager- determines what resources a class can access such as reading and writing
to the local disk.
These security are provided by java language. Some security can also be provided by application
developer through SSL,JAAS,cryptography etc.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that
avoids security problem. There is automatic garbage collection in java. There is exception handling
and type checking mechanism in java. All these points makes java robust.
Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat
slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.
We can write a simple hello java program easily after installing the JDK.
To create a simple java program, you need to create a class that contains main method. Let's
understand the requirement first.
• install the JDK if you don't have installed it, download the JDK and install it.
• set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
• create the java program
• compile and run the java program
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Output:Hello Java
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
we have learned about the first program, how to compile and how to run the first java program.
Here, we are going to learn, what happens while compiling and running the java program.
Moreover, we will see some question based on the first program.
At compile time, java file is compiled by Java Compiler (It does not interact with OS) and
converts the java code into bytecode.
What happens at runtime?
At runtime, following steps are performed:
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects.
→Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
Understanding the difference between JDK, JRE and JVM is important in Java. We are having
brief overview of JVM here.
If you want to get the detailed knowledge of Java Virtural Machine, move to the next page.
Firstly, let's see the basic differences between the JDK, JRE and JVM.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the
implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at
runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.
JVM (Java Virtual Machine)
1. Java Virtual Machine
2. Internal Architecture of JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform
dependent).
What is JVM?
It is:
What it does?
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
• Memory area
• Class file format
• Register set
• Garbage-collected heap
• Fatal error reporting etc.
2) Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap:
4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
PC (program counter) register. It contains the address of the Java virtual machine instruction
currently being executed.
6) Native Method Stack:
7) Execution Engine:
It contains:
1) A virtual processor
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of the byte
code that have similar functionality at the same time, and hence reduces the amount of time needed
for compilation.Here the term ?compiler? refers to a translator from the instruction set of a Java
virtual machine (JVM) to the instruction set of a specific CPU.
Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example:
to convense the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because
all the data members are private here.
2)OOPs provides data hiding whereas in Procedure-oriented prgramming language a global data can
be accessed from anywhere.
3)OOPs provides ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.
Variables are nothing but reserved memory locations to store values. This means that when you create
a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you can store
integers, decimals, or characters in these variables.
There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a keyword. Let us now look into detail about the eight primitive data types.
byte:
short:
int:
long:
float:
double:
boolean:
char:
• Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed.
For example, Employee, Puppy etc.
• Class objects, and various type of array variables come under reference data type.
• Default value of any reference variable is null.
• A reference variable can be used to refer to any object of the declared type or any compatible
type.
• Example: Animal animal = new Animal("giraffe");
Java Literals:
A literal is a source code representation of a fixed value. They are represented directly in the code
without any computation.
byte a = 68;
char a = 'A'
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8)
number systems as well.
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number systems
for literals. For example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
String literals in Java are specified like they are in most other languages by enclosing a sequence of
characters between a pair of double quotes. Examples of string literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example:
char a = '\u0001';
String a = "\u0001";
Java language supports few special escape sequences for String and char literals as well. They are:
\n Newline (0x0a)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\\ backslash
Variables
In Java, all variables must be declared before they can be used. The basic form of a variable declaration
is shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java's datatypes. The identifier is the name of the variable. To declare more than one
variable of the specified type, use a comma-separated list.
Here are several examples of variable declarations of various types. Note that some include an
initialization.
This chapter will explain various variable types available in Java Language. There are three kinds of
variables in Java:
• Local variables
• Instance variables
• Class/static variables
Local variables:
Example:
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to this
method only.
Example:
Following example uses age without initializing it, so it would give an error at the time of compilation.
Instance variables:
• Instance variables are declared in a class, but outside a method, constructor or any block.
• When a space is allocated for an object in the heap, a slot for each instance variable value is
created.
• Instance variables are created when an object is created with the use of the keyword 'new' and
destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method, constructor
or block, or essential parts of an object's state that must be present throughout the class.
Example:
import java.io.*;
public class Employee{
// this instance variable is visible for any child class.
public String name;
name : Ransika
salary :1000.0
Scope refers to the range of code where you can access a variable. You can literally print out
your program, and draw a box to show where a variable is valid. It's textual in nature. We can
divide scope into
• method body scope Variable is accessible in method body only (local variables,
parameters)
• class definition scope Variable is accessible i class definition (instance variables)
Lifetime refers to the amount of time a variable (or object) exists. Since object variables are
both a box (holding a handle) and an object, the lifetimes may differ. An object variable could
disappear (for example, a local variable disappears once you exit the method where the local
variable is declared), yet the object still exists.
• method body lifetime Exists on method body entry, disappears on method body exit.
(local variables, parameters)
• class definition lifetime Exists as long as object is around (instance variables)
• [an error occurred while processing this directive]
Type conversion:
•In some cases we might want to assign value of one type to variable of another type. If both
the source and destination types are compatible, then java performs the conversion
implicitly(automatically).
•Examples of compatible types are int, long, short and byte. Also float and double are
compatible with each other.
•Java automatically converts from one type to another only when the following two conditions
are satisfied:
•When the above two conditions are satisfied, java performs an implicit conversion. This is also
known as “Widening Conversion”.
•int can be auto converted to long since the size of long is 64, where as size of int is 32. Similarly
a byte can be auto converted or implicitly converted to int.
•If we want to convert two types which are incompatible or if the size of destination type is less
than the size of source type, then we must do the conversion explicitly. This process is also
called as “type casting”.
•For example if we want to convert a int value to byte, java cannot do this automatically as the
size of int is 32 and size of byte is only 8. So, we must explicitly cast an int to byte. This is also
known as “narrowing conversion”
•Syntax for type casting is:
Widening − Converting a lower datatype to a higher datatype is known as widening. In this case the
casting/conversion is done automatically therefore, it is known as implicit type casting. In this case both
datatypes should be compatible with each other.
Example
Output
Integer value of the given character: 67
Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case the
casting/conversion is not done automatically, you need to convert explicitly using the cast operator “(
)” explicitly. Therefore, it is known as explicit type casting. In this case both datatypes need not be
compatible with each other.
Example
import java.util.Scanner;
public class NarrowingExample {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer value: ");
int i = sc.nextInt();
char ch = (char) i;
System.out.println("Character value of the given integer: "+ch);
}
}
Output
Enter an integer value:
67
Character value of the given integer: C
Java Basics
===========
control flow statements
-----------------------
2. the instructions will be executed from top to bottom, without skiping any instruction.
1. Selection Statements
1. simple if
2. if else
3. else if
4. nested if
5. switch case
1. while loop
2. do while loop
3. for loop
3. Transfer Statements
1. break
2. continue
System.out.println("even number");
System.out.println("odd number");
Eg: 1...5
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
Eg: 1...5000
System.out.println(i);
Eg: 0.....500
--> when ever we are getting 420 can u pls stop the process
--> whenever we are getting 420 can u pls stop current iteration and starts from 421
---------
if(condition)
true_block statements;
Eg: WJP to accept salary of an emp, and update salary based on gender
---------------------------------------------------------------------
import java.util.Scanner;
class Test
if(gender.equals("female"))
System.out.println("Updated Salary:"+salary);
male
1000
Updated Salary:1000.0
female
1000
Updated Salary:1200.0
if else:
--------
if(condition)
true_block statements;
else
false_block statements;
}
--------------------------------------
import java.util.Scanner;
class Test
int a = obj.nextInt();
int b = obj.nextInt();
if(a>b)
System.out.println(a+" is big");
else
System.out.println(b+" is big");
100
200
200 is big
100
50
100 is big
Eg: WJP to check whether the given two numbers are equal or not
---------------------------------------------------------------
import java.util.Scanner;
class Test
int a = obj.nextInt();
int b = obj.nextInt();
if(a==b)
else
}
10
20
111
111
-------------------------------------------------------------
import java.util.Scanner;
class Test
if(gender.equals("male"))
else
System.out.println("Updated Salary:"+salary);
male
10000
Updated Salary:15000.0
female
20000
Updated Salary:32000.0
-------------------------------------------------------------
import java.util.Scanner;
class Test
if(age>=18)
{
System.out.println("Eligible for vote");
else
-------------------------------------------------------
-------
if(condition1)
TRUE_BLOCK_1
else if(condition2)
TRUE_BLOCK_2
else if(condition3)
TRUE_BLOCK_3
else
FALSE_BLOCK
----------------------------------------
import java.util.Scanner;
class Test
int a = obj.nextInt();
int b = obj.nextInt();
int c = obj.nextInt();
System.out.println(a+" is big");
System.out.println(b+" is big");
else
System.out.println(c+" is big");
10
20
30
30 is big
import java.util.Scanner;
class Test
if(per>=75)
System.out.println("Grade A");
else if(per>=60)
System.out.println("Grade B");
else if(per>=50)
System.out.println("Grade C");
else if(per>=40)
System.out.println("Grade D");
else
50
60
70
80
90
Grade B
nested if
---------
Eg:
import java.util.Scanner;
class Test
{
if(per>=75)
System.out.println("Grade A");
else if(per>=60)
System.out.println("Grade B");
else if(per>=50)
System.out.println("Grade C");
else if(per>=40)
System.out.println("Grade D");
else
System.out.println("Unable to issue degree");
else
100
85
95
75
65
Grade A
switch case:
-----------
--> syntax
switch(choice)
default: stmt;
Eg:
import java.util.Scanner;
class Test
int n = obj.nextInt();
switch(n)
default: System.out.println("invalid");
one
two
three
four
five
6
invalid
---> if there is no break, then it will execute all the cases from matching case.
Eg:
import java.util.Scanner;
class Test
int n = obj.nextInt();
switch(n)
case 1: System.out.println("one");
case 2: System.out.println("two");
case 3: System.out.println("three");
case 4: System.out.println("four");
case 5: System.out.println("five");
default: System.out.println("invalid");
}
}
invalid
one
two
three
four
five
invalid
two
three
four
five
invalid
five
invalid
iterative statements
--------------------
2. do while loop--> if we dn't know the number of iterations in advance, min 1 time execution
while loop:
----------
while(condition)
TRUE_BLOCK_STATEMENTS
import java.util.Scanner;
class Test
int n = obj.nextInt();
while(n!=0)
System.out.println(n%10);
n=n/10;
123
45678
5
4
-----------------------------------------------------
import java.util.Scanner;
class Test
s=0;
while(n!=0)
d=n%10;
s=s+d;
n=n/10;
System.out.println("sum of digits:"+s);
123
sum of digits:6
12345
sum of digits:15
do while loop:
-------------
do
statements
}while(condition);
Eg1:
import java.util.Scanner;
class Test
int a=95,b=100;
while(a<=b)
System.out.println(a++);//95,96,97,98,99,100
}
for loop:
--------
3. syntax
for(intialization;condition;update)
statements
C--->2,5,....
U--->4,7,....
B--->3,6,....
----------------------------------------------
import java.util.Scanner;
class Test
int i;
for(i=0;i<=10;i++)
{
System.out.println(i);
-------------------------------------------
import java.util.Scanner;
class Test
int i;
for(i=0;i<=10;i=i+2)
System.out.println(i);
6
8
10
------------------------------------------
import java.util.Scanner;
class Test
int i;
for(i=1;i<=10;i=i+2)
System.out.println(i);
9
for each loop:
-------------
--> syntax
statements
Eg:
import java.util.Scanner;
class Test
int[] a = {111,222,333,444,555};
for(int t:a)
System.out.println(t);
}
}
111
222
333
444
555
Eg:
import java.util.Scanner;
class Test
for(String t:names)
System.out.println(t);
}
C
C++
JAVA
PYTHON
transfer statements
-------------------
--> continue: terminates current iteration and starts with new iteration
Eg:
import java.util.Scanner;
class Test
int i;
for(i=1;i<=500;i++)
if(i==420)
break;
else
System.out.print("\t"+i);
}
Eg:
import java.util.Scanner;
class Test
int i;
for(i=1;i<=500;i++)
if(i==420)
continue;
else
System.out.print("\t"+i);
arrays:
=======
introduction:
-------------
3. advantage arrays
4. disadvantages arrays
declaration of an array:
------------------------
datatype[] arrayname;
Eg:
int[] a;
int a[];
int []a;
Eg:
int[][] a;
int a[][];
int [][]a;
int[] a[];
int[] []a;
int []a[];
-----------------------------
int a[];
a = new int[size];
Eg:
RuntimException: NegativeArraySizeException
index concept:
--------------
1. index is the special concept, which is used to access the array elements.
5. out of index then we wn't get any compile time error, but execution fails
--------------------------------
System.out.println(a[0]) #0
System.out.println(a[1]) #0
System.out.println(a[2]) #0
a[0] = 111;
a[1] = 222;
a[2] = 333;
System.out.println(a[0]) #111
System.out.println(a[1]) #222
System.out.println(a[2]) #333
System.out.println(a[3]) #AIOOBE
int[] a = {11,22,33,44,55};
size:5
array name:a
dimension:1
index: 0,1,2,3,4
--------------------------------
length identifier.
System.out.println(a.length); //5
int[] a = {1,2,3,4,5,6,7,8};
System.out.println(a.length); //8
--------------------------------
Reading an array
import java.util.Scanner;
Write an array
Eg1:
import java.util.Scanner;
class Test
1 error
Eg2:
import java.util.Scanner;
class Test
for(int i:a)
System.out.println(i);
Eg3:
import java.util.Scanner;
class Test
a[1] = 777;
a[2] = 999;
for(int i:a)
System.out.println(i);
777
999
Eg4:
import java.util.Scanner;
class Test
for(double i:a)
System.out.println(i);
0.0
0.0
0.0
0.0
0.0
Eg5:
import java.util.Scanner;
class Test
for(boolean i:a)
System.out.println(i);
false
false
false
false
Eg6:
import java.util.Scanner;
class Test
for(String i:a)
System.out.println(i);
null
null
null
null
Eg7:
import java.util.Scanner;
class Test
System.out.println(a.length);
0
Eg8:
import java.util.Scanner;
class Test
System.out.println(a.length);
at Test.main(Test.java:6)
Eg9:
import java.util.Scanner;
class Test
System.out.println(a[0]);//0
System.out.println(a[1]);//0
System.out.println(a[2]);//0
System.out.println(a[3]);//AIOOBE
at Test.main(Test.java:10)
Eg10:
import java.util.Scanner;
class Test
System.out.println(a.length);//3
for(int i:a)
System.out.println("Element:"+i);
Element:1
Element:2
Element:3
Eg11:
import java.util.Scanner;
class Test
for(int i:a)
System.out.println(i);
for(int i:a)
required: int
found: int[]
1 error
Eg12:
import java.util.Scanner;
class Test
{
for(int i[]:a)
for(int j:i)
System.out.print(" "+j);
System.out.println();
123
456
789
import java.util.Scanner;
class Test
for(int i=0;i<a.length;i++)//3
for(int j=0;j<a[i].length;j++)
{
/*
*/
import java.util.Scanner;
class Test
int i,factors=0;
for(i=1;i<=n;i++)
if(n%i==0)
factors++;
if(factors==2)
return true;
else
return false;
int n = obj.nextInt();
int i,s=0;
for(i=2;i<=n;i++)
{
if(isPrime(i))
s=s+i;
10
-----------------------------------
import java.util.Scanner;
class Test
for(i=0;i<a.length;i++)
a[i] = obj.nextInt();
for(int t:a)
System.out.println(t);
10
20
15
25
10
20
15
25
8
AP2) Read array elements and calcualte sum of the given values
--------------------------------------------------------------
import java.util.Scanner;
class Test
for(i=0;i<a.length;i++)
a[i] = obj.nextInt();
for(int t:a)
s=s+t;
10
3
AP4) Read array elements and calcualte sum of even elements the given values
AP5) Read array elements and calcualte sum of odd elements the given values
AP6) Read array elements and calcualte sum of prime elements the given values
AP7) Read array elements and calculate max element in the given array
---------------------------------------------------------------------
import java.util.Scanner;
class Test
for(i=0;i<a.length;i++)
a[i] = obj.nextInt();
max=a[0];
for(int t:a)
if(max<t)
max = t;
10
-20
30
-40
50
-60
70
-80
AP8) Read array elements and calculate min element in the given array
---------------------------------------------------------------
import java.util.Scanner;
class Test
{
for(i=0;i<a.length;i++)
a[i] = obj.nextInt();
for(int t:a)
System.out.println(t);
//logic
for(i=0;i<a.length;i++)
for(j=i+1;j<a.length;j++)
if(a[i]>a[j])
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
System.out.println("Array elements after sorting:");
for(int t:a)
System.out.println(t);
-----------------------------
[12]
[34]
[2][2]
i=0--->j=0------>(0,0)
i=0--->j=1------>(0,1)
i=1--->j=0------>(1,0)
i=1--->j=1------>(1,1)
import java.util.Scanner;
class Test
for(j=0;j<a[i].length;j++)
a[i][j] = obj.nextInt();
System.out.println("Matrix:");
for(i=0;i<a.length;i++)
for(j=0;j<a[i].length;j++)
System.out.print(" "+a[i][j]);
System.out.println();
7
8
Matrix:
123
456
789
Matrix:
100
010
001
---------------------------------------
import java.util.Scanner;
class Test
{
for(i=0;i<a.length;i++)
for(j=0;j<a[i].length;j++)
a[i][j] = obj.nextInt();
System.out.println("Give Matrix:");
for(i=0;i<a.length;i++)
for(j=0;j<a[i].length;j++)
System.out.print(" "+a[i][j]);
System.out.println();
System.out.println("Transpose Matrix:");
for(i=0;i<a.length;i++)
for(j=0;j<a[i].length;j++)
{
System.out.print(" "+a[j][i]);
System.out.println();
Give Matrix:
123
456
789
Transpose Matrix:
147
258
369
Enter array elements for 3x3 matrix:
Give Matrix:
100
010
001
Transpose Matrix:
100
010
001
---------------------
import java.util.Scanner;
class Test
{
Scanner obj = new Scanner(System.in);
int i,j;
for(i=0;i<a.length;i++)
for(j=0;j<a[i].length;j++)
a[i][j] = obj.nextInt();
for(i=0;i<b.length;i++)
for(j=0;j<b[i].length;j++)
b[i][j] = obj.nextInt();
for(i=0;i<3;i++)
for(j=0;j<3;j++)
}
}
System.out.println("Result Matrix:");
for(i=0;i<c.length;i++)
for(j=0;j<c[i].length;j++)
System.out.print(" "+c[j][i]);
System.out.println();
0
0
Result Matrix:
247
268
3 6 10
import java.util.Scanner;
class Test
int i,j,k;
for(i=0;i<a.length;i++)
{
for(j=0;j<a[i].length;j++)
a[i][j] = obj.nextInt();
for(i=0;i<b.length;i++)
for(j=0;j<b[i].length;j++)
b[i][j] = obj.nextInt();
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j] = 0;
for(k=0;k<3;k++)
System.out.println("Result Matrix:");
for(i=0;i<c.length;i++)
{
for(j=0;j<c[i].length;j++)
System.out.print(" "+c[i][j]);
System.out.println();
123
456
789
100
010
001
Result Matrix:
123
456
789
Constructors in Java
---------------->2.Parameterized constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time
of object creation.
eg....
class Bike1{
Bike1()
System.out.println("Bike is created");
//main method
output...Bike is created
The default constructor is used to provide the default values to the object like 0, null, etc., depending
on the type.
eg---
class Student3{
int id;
String name;
//creating objects
s1.display();
s2.display();
}
}
...
output---
0 null
0 null
.............................
In this example, we have created the constructor of Student class that have two parameters.
eg---
class Student4{
int id;
String name;
id = i;
name = n;
s1.display();
s2.display();
-----
output---
111 Karan
222 Aryan
--------------------------------------------------
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.
eg----
class Student5{
int id;
String name;
int age;
id = i;
name = n;
name = n;
age=a;
s1.display();
s2.display();
-----------------
output---
111 Karan 0
222 Aryan 25
Method in Java
--------------------------
------------->A method is a way to perform some task. Similarly, the method in Java is a collection of
instructions that performs a specific task.
predefind method
ex----
public class Demo
output---
----In the above example, we have used three predefined methods main(), print(), and max()
ex-----
import java.util.Scanner;
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
output----
12 is even
| | | |
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility
of the method. Java provides four types of access specifier:
----->Public: The method is accessible by all classes when we use public specifier in our application.
-------Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
-------Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
-------Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
java Enums
The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY) ,
According to the Java naming conventions, we should have all constants in capital
letters.
•So, what happens when the names of instance variables and the parameters are
same?
•In the above case the parameters “hide” the instance variables. This is an
ambiguous situation.
class Box
length = length;
width = width;
height = height;
•In the example we just saw, the names of instance variables and names of
parameters are same.
•How to solve this issue? There are two ways to solve this.
•“this” can be used to resolve the naming conflicts between instance variables and
parameters.
•So, by using the “this” keyword, our program can be return as follows…
class Box
this.length = length;
this.width = width;
this.height = height;
string literal
String s = “GeeksforGeeks”;
String Methods
------------------------
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
Ex---prgm
}
}
OUTPUT---
Checking Length: 20
----------------------------------------------------------
Recursion in Java
------------------------------------------------------
count++;
if(count<=5){
System.out.println("hello "+count);
p();
p();
------- output
hello 1
hello 2
hello 3
hello 4
hello 5
s1=null;
s2=null;
System.gc();
output
break continue
1. Can be used in switch and loop (for,
1. Can be only used with loop statements
while, do while) statements
Example break:
1
for (int i = 0; i < 5; i++)
2 {
3 if (i == 3)
4 {
5 break;
}
6
System.out.println(i);
7 }
8
Example continue:
1
for (int i = 0; i < 5; i++)
2 {
3 if(i == 2)
4 {
5 continue;
}
6
System.out.println(i);
7 }
8
Q3. What is the difference between this() and super() in Java?
In Java, super() and this(), both are special keywords that are used to call the constructor.
this() super()
1. this() represents the current instance of a 1. super() represents the current instance of a
class parent/base class
2. Used to call the default constructor of the 2. Used to call the default constructor of the
same class parent/base class
3. Used to access methods of the current
3. Used to access methods of the base class
class
4. Used for pointing the current class
4. Used for pointing the superclass instance
instance
5. Must be the first line of a block 5. Must be the first line of a block
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs
The idea behind inheritance in Java is that you can create new classes
that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee
// Driver class
--------------------------
Hierarchical Inheritance
------------
class A {
public void print_A() { System.out.println("Class A"); }
}
class B extends A {
public void print_B() { System.out.println("Class B"); }
}
class C extends A {
public void print_C() { System.out.println("Class C"); }
}
class D extends A {
public void print_D() { System.out.println("Class D"); }
}
// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
While one of Java's strengths is the concept of inheritance, in which one class can derive from
another, sometimes it's desirable to prevent inheritance by another class. To prevent
inheritance, use the keyword "final" when creating the class.
The main reason to prevent inheritance is to make sure the way a class behaves is not corrupted
by a subclass.
Suppose we have a class Account and a subclass that extends it, OverdraftAccount. Class
Account has a method getBalance():
This means that the Account class cannot be a superclass, and the OverdraftAccount class can
no longer be its subclass.
Sometimes, you may wish to limit only certain behaviors of a superclass to avoid corruption
by a subclass. For example, OverdraftAccount still could be a subclass of Account, but it should
be prevented from overriding the getBalance() method.
final is a non-access modifier for Java elements. The final modifier is used for finalizing the
implementations of classes, methods, and variables.
By using final keyword with a class orBy using a private constructor in a class.
How to prevent class from being inherited in java is one of the important technical interview
questions for which we need to detail all possible solutions.
Problem Statement: Let’s say we have a class A and we don’t want to allow any other class to
be derived from it. What are the possible solutions?
Solution-1: Using final keyword
Using final keyword before a class declaration we can stop a class to be inherited by other
classes. For example,
If we try to extend the class A which is final, compiler will flash an error i.e.
“The Type B cannot the subclass the final Class A”, if class B is trying to extend final class A.
public class B extends A{//Error :The Type B cannot the subclass the Final Class A
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block
only. We will have detailed learning of these. Let's first learn the basics of final keyword.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.
class Bike9{
Polymorphism
1 class Car {
2 void run()
3 {
4 System.out.println(“car is running”);
5 }
6 }
7 class Audi extends Car {
8 void run()
9 {
10 System.out.prinltn(“Audi is running safely with 100km”);
11 }
12 public static void main(String args[])
13 {
14 Car b= new Audi(); //upcasting
15 b.run();
16 }
17 }
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.
Method Overloading
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
10. Output:
11. 22
12. 33
In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
o Method overriding is used to provide the specific implementation of a method which
is already provided by its superclass.
o Method overriding is used for runtime polymorphism
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter of the
method are the same, and there is IS-A relationship between the classes, so there is
method overriding.
Output:
----------------------------------------
----------------------
The abstract class in Java cannot be instantiated (we cannot create objects of abstract classes).
----------------
For example
------------
...
// throws an error
--------------------------------------
note:An abstract class can have both the regular methods and abstract methods
-----------------------------------------
for example
---------------------
// abstract method
// regular method
void method2() {
---------------------------------------------------------------------------------
--------------------------
----------------------------------------------------------------
For example
-----------
----------------------------
If a class contains an abstract method, then the class should be declared abstract.
Otherwise,
-------------------------------
obj.display();
Output
----------------------
------------------------------
Java Abstraction
The major use of abstract classes and methods is to achieve abstraction in Java.
Abstraction is an important concept of object-oriented programming
that allows us to hide unnecessary details and only show the needed information..
UNIT-III:
Interface in Java
An Interface means Any Service requirement Specification [SRS].
And
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
→ A class implements an interface, thereby inheriting the abstract methods of the interface.
→ Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
There are mainly three reasons to use interface. They are given below.
A class that implements an interface must implement all the methods declared in the
interface.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to
declare an interface −
Example
Following is an example of an interface −
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }
Output:Hello
Welcome
Interface inheritance
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
11. TestInterface4 obj = new TestInterface4();
12. obj.print();
13. obj.show();
14. }
15. }
Output:
Hello
Welcome
Implementing Interfaces
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform
all the behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the
declaration.
Example
/* File name : MammalInt.java */
public class MammalInt implements Animal {
Output
Mammal eats
Mammal travels
1. The interface is a fully un-implemented class used for declaring a set of operations
of an object.
2. An abstract class is a partially implemented class. It implements some of the
operations of the object those are declared in its interface. These implemented
operations are common for all next-level subclasses. The remaining operations are
implemented by the next level subclasses according to their requirement.
3. The interface allows us to develop multiple inheritances. So we must start object
design with an interface whereas abstract class does not support multiple
inheritances so it always comes next to the interface in the object creation process.
The interface supports Multiple Abstract class does not support Multiple
Inheritance. Inheritance.
An interface contains only incomplete An abstract class contains both complete and
members. incomplete members.
II-PART
Packages- Defining, creating and accessing a package, importing
packages.
The package is a collection of classes and interfaces in the form of .class files. It helps
organize your classes into a folder structure and makes it easy to locate and use them.
More importantly, it helps improve re-usability. Each package in Java has its unique name
and organizes its classes and interfaces into a separate namespace, or name group.
Although interfaces and classes with the same name cannot appear in the same package,
they can appear in different packages.
Packages are used for:
1. Preventing naming conflicts.
2. Making searching and usage of classes, interfaces, enumerations, and annotations
easier.
3. Offers access protection such as protected classes, default classes, and private
classes.
4. Packages can be considered as data encapsulation (or data-hiding).
5. With packages, you can organize your project better and easily locate related
classes.
In-Built Packages
In-Built Packages are the packages that are given by Sun Microsystems or some other
companies as a part of Java. We have the following three types of in-built packages:
1. Core Packages: Core Packages are predefined packages given by Sun
MicroSystems which begin with “java”.
1.java.lang :
This package is the collection of classes and interfaces using which we can perform basic
operations like parsing, storing strings, etc. This package is by default available for every
java program. Example: Object, String, Integer, etc.
2.java.io :
This package is the collection of classes and interfaces using which we can perform basic
input and output operations. Example: BufferedReader, Printstream, FileReader, etc.
3.java.util :
This package is the collection of classes and interfaces using which we can display the
date, store the group of objects(Collection API). Example: Date, Collection, ArrayList, etc.
4.java.text :
This package is the collection of classes and interfaces using which we can perform
operations like formatting the date, number, etc. Example: NumberFormat, DateFormat,
etc.
5.java.net :
This package is the collection of classes and interfaces using which we can develop
network-related applications. Example: Socket, ServerSocket, etc.
6.java.sql :
This package is the collection of classes and interfaces using which we can perform
JDBC-related operations like connecting to DB, creating the tables, inserting records, etc.
Example: Connection, Driver, DriverManager, etc.
7.java.awt :
This package is the collection of classes and interfaces using which we can develop GUI-
based applications. Example: Frame, Label, Button, etc.
8.javax.swing :
This package is the collection of classes and interfaces using which we can develop better
GUI-based Applications. Example: JFrame, JLabel, JButton, etc.
9.java.applet :
This package is the collection of classes and interfaces using which we can develop
applications that run in the browser. Example : Applet, AppletContext, etc.
Rules:
1. While writing the package name we can specify packages in any number of levels
but specifying one level is mandatory.
2. The package statement must be written as the first executable statement in the
program.
3. We can write at most one package statement in the program
Example: Program to demonstrate Packages in Java
package Demo;
public class PackageDemo {
Or
javac –d E: PackageDemo.java
Or
javac –d D:\practice PackageDemo.java
Here,
-d: This option is used to create the package based on the name specified in the program
using the package statements and locate the generated class into the package. E: or D:
– Specify the location where to locate the created package.
How to execute the Java Package Program?
You need to use a fully qualified name to run the class.
To Compile javac -d . PackageDemo.java
We can use all the classes and interfaces are available in the above two packages but if
we want to use classes and interfaces that are available in the other packages we must
import them into our program by using any one of the following two ways:
1. Using Fully Qualified Name
2. Using import Statement
Using Fully Qualified Name
A fully Qualified Name means writing the class name using the package name directly.
Using this concept we can import only one class at a time. This concept will increase the
code size and decrease the readability of the program and this concept is not
recommended to use. The Syntax is shown in the below image.
Implicit import :
By using implicit import we can import many classes from the package.
Syntax :
import package.*;
import package1.package2.*;
Example :
import java.io.*;
class ReadingData{
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
}
}
Here, the compiler will decide what class to be loaded in the program hence it is called
implicit import.
Explicit import :
By using explicit import we can import only one class from the package.
Syntax :
import package.ClassName;
import package1.package2.ClassName;
Example :
import java.io.BufferedReader;
import java.io.InputstreamReader;
import java.io.IOException;
class ReadingData{
Public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new
InputstreamReader(System.in));
}
}
Here, the programmer is specifying explicitly what classes to be loaded hence it is called
an explicit import.
Note: It is always recommended to use explicit import in the industry because it always
improves the readability of the program.
1. Import statements must be written after the package statement and before the
class declaration.
2. We can write any number of import statements.
3.
Difference Between Implicit Import and Explicit Import
Using implicit import or explicit import both are the same but explicit import will take a little
bit more compilation time compared to implicit import but at run time there is no difference.
Advantages of Packages in Java
1. The package is used to categorize the classes and interfaces so that they can be
easily maintained.
2. Application development time is less because reuse the code
3. Application memory space is less (main memory)
4. Application execution time is less
5. Application performance is enhanced (improve)
6. Redundancy (repetition) of code is minimized
7. The package provides access protection
8. Package removes naming collision
UNIT-IV:
Multithreading – Differences between multiple processes and multiple threads, thread life cycle,
creating threads, interrupting threads, thread priorities, synchronizing threads, inter- thread
communication, producer consumer problem
Exception
An exception is a problem that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore these exceptions are to be handled.
What is Exception in Java?
An exception can occur for many different reasons, below given are some scenarios where
exception occurs.
3.A network connection has been lost in the middle of communications or the JVM has run out
of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
• Classification of exceptions
•
•
1.ArithmeticException
3ArrayStoreException
4ClassCastException
Invalid cast.
5IllegalArgumentException
6IllegalMonitorStateException
7IllegalStateException
8IllegalThreadStateException
10 NegativeArraySizeException
11 NullPointerException
12 NumberFormatException
13 SecurityException
14 StringIndexOutOfBounds
15 UnsupportedOperationException
1 ClassNotFoundException
2 CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable interface.
3 IllegalAccessException
4 InstantiationException
5 InterruptedException
6 NoSuchFieldException
7 NoSuchMethodException
A requested method does not exist.
If(condition……….){
throw ex;
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions.
Forexample, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime..
if you use FileReader class in your program to read data from a file, if the file specified in its
constructor doesn't exist, then an FileNotFoundException occurs, and compiler prompts the
programmer to handle the exception.
Example program:
import java.io.File;
import java.io.FileReader;
If you try to compile the above program you will get exceptions as shown below.
C:\>javac FilenotFound_Demo.java FilenotFound_Demo.java:
^ 1 error
Note: Since the methods read and close of FileReader class throws IOException, you can observe
that compiler notifies to handle IOException, along with FileNotFoundException
2) Unchecked Exception
An Unchecked exception is an exception that occurs at the time of execution, these are also called as
Runtime Exceptions, these include programming bugs, such as logic errors or improper use of an API.
runtime exceptions are ignored at the time of compilation.
For example,
if you have declared an array of size 5 in your program, and trying to call the 6th element of the array
then an ArrayIndexOutOfBoundsExceptionexception occurs
Example program:
{ int num[]={1,2,3,4};
System.out.println(num[5]);
If you compile and execute the above program you will get exception as shown below.
5 at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything about
an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time
of compilation.
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
Try The "try" keyword is used to specify a block where we should place
an exception code.
It must be preceded by try block which means we can't use catch block alone.
finally The "finally" block is used to execute the necessary code of the program.
It specifies that there may occur an exception in the method. It doesn't throw an
• Exception Handling
• Syntax
• Code
• try { // protected code }
• catch(Exception _name exception_1)
• { // catch block
• }
• catch( Exception_ name exception_2)
• {
• // catch block
• }
Try to understand the difference between throws and throw keywords, throws is used to postpone
the handling of a checked exception and throw is used to invoke an exception explicitly
import java.io.*;
We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related
to user inputs, server, etc.
Output:
try {
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Run Code
Output
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
Example: Java Exception Handling using finally block
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}
Run Code
Output
Unit-4
Multithreading – Differences between multiple processes and multiple
threads, thread life cycle, creating threads, interrupting threads, thread
priorities, synchronizing threads, inter- thread communication, producer
consumer problem.
What is Single-Tasking?
Single-Tasking means executing one task at a time. Here much of the processor
time will be wasted because waiting time is very high and the processor gives a
late response. Example: DOS
What is Multitasking?
To execute all the above applications, the operating system internally makes use
of processes. A process is a part of the operating system (or a component under
the operating system) which is responsible for executing the program or
application. So, to execute each and every program or application, there will be a
process.
You can see this using the Task Manager. Just right-click on the Taskbar and
click on the Task Manager option which will open the Task Manager window.
From that window, just click on the “Processes” button as shown below.
As you can see from the above image, each application is executed by one
corresponding process. Along the same line, there are also multiple processes that
are running in the background which are known as the background processes.
These background processes are known as windows services and the Operating
system runs a lot of windows services in the background.
So, we have an operating system and under the operating system, we have
processes that run our applications. So under the process, an application runs. To
run the code of an application the process will make use of a concept called
Thread.
Types of Multi-Tasking
For example, while typing a java program we can listen to a song and at the same
time we can download a file from the internet, all these tasks are executed
simultaneously and there is no relationship between these tasks. All these tasks
have their own independent address space as shown below. This type of multi-
tasking is developed at the OS level.
Thread-based multitasking (Multithreading)
For executing each task a unit of CPU time is given for its execution which is
called a time slice or time quantum. The thread scheduler runs each thread for a
short amount of time. Each thread alternatively gets a slice (quantum) of the
CPU’s time.
Thread Scheduler :
Advantages of Multitasking:
We can develop a multithread program in java very easily because java provides
in-build support for creating custom threads by providing API- Runnable, Thread,
ThreadGroup.
We can consider JVM is also a process, when JVM is created in its java stack
area by default two threads are created with names
What is Thread?
By default, every process has at least one thread that is responsible for executing
the application code and that thread is called Main Thread. So, every application
by default is a single-threaded application.
A thread is a:
System.out.println("Single Thread");
It is a process of creating multiple threads in the Java Stack Area (JSA) for
executing multiple tasks concurrently to finish their execution in a short time by
using the processor’s ideal time effectively.
Multithreading means executing multiple threads at the same time simultaneously
where each thread is called a separated task of the program that executes
separately.
1. The users are not blocked because threads are independent, and we can
perform multiple operations at times
2. As such the threads are independent, the other threads won’t get affected if
one thread meets an exception.
3.
Why do we need multithreading in Java?
//statements;
}
Here, the run() method is called the entry-point for the user-defined thread, and
all the jobs are done by the user-defined thread will be written here itself.
If we want to create the Thread using this approach we have to follow the
following five steps:
t.start ();
Output:
t.start ();
Output:
Difference between extending thread class and implementing a runnable
interface
If we create any thread by extending the Thread class then we have no chance of
extending from any other class. But if we create any thread by implementing the
Runnable interface then we have a chance for extending from one class. It is
always recommended to create the user define threads by implementing Runnable
Interface only.
JVM is creating a thread to start executing the code in the main method and we call this
thread as Main Thread.
It is the Operating System that schedules the threads to be processed by the Processor.
So the scheduling behavior is dependent on the OS.
Again there is a Thread Scheduler inside JVM which coordinates with OS Scheduler.
For every Java program, there will be a default thread created by JVM which is nothing
but Main Thread. The entry point for Main Thread is the main() method.
System.out.println (ct);
System.out.println (ct.getName ());
Output:
A thread goes through various stages in its life cycle. According to Sun, there are only 4
states in the thread life cycle in java new, runnable, non-runnable, and terminated. There
is no running state. But for a better understanding of the threads, we are explaining it in
the 5 states. The life cycle of the thread in java is controlled by JVM.
For a better understanding please have a look at the below diagram. The java thread
states are as follows:
1. Newborn
2. Runnable
3. Running
4. Blocked (Non-Runnable)
5. Dead (Terminated)
Following are the stages of the life cycle –
New – A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread. In simple words, a thread
has been created, but it has not yet been started. A thread is started by calling its start()
method.
Runnable – The thread is in the runnable state after the invocation of the start() method,
but the thread scheduler has not selected it to be the running thread. A thread starts life
in the Ready-to-run state by calling the start method and waiting for its turn. The thread
scheduler decides which thread runs and for how long.
Running – When the thread starts executing, then the state is changed to a “running”
state. The scheduler selects one thread from the thread pool, and it starts executing in the
application.
Dead – This is the state when the thread is terminated. The thread is in a running state
and as soon as it is completed processing it is in a “dead state”. Once a thread is in this
state, the thread cannot even run again.
Blocked (Non-runnable state):
This is the state when the thread is still alive but is currently not eligible to run. A thread
that is blocked waiting for a monitor lock is in this state.
Here we are giving a simple example of the Thread life cycle. In this example, we will
create a Java class where we will create a Thread, and then we will use some of its
methods that represents its life cycle.
A1.java
class A1 extends Thread
try
Thread.sleep (1000);
catch (InterruptedException e)
e.printStackTrace ();
• Preemptive scheduling: If a thread with a higher priority than the current running
thread, then the current running thread is preempted(moves to the ready-to-run
state) to let the higher priority thread execute.
Priority means the number of resources allocated to a particular thread. Every thread
created in JVM is assigned a priority. The priority range is between 1 and 10.
1. Thread.MIN_PRIORITY;
2. Thread.NORM_PRIORITY;
3. Thread.MAX_PRIORITY;
m1.setPriority (Thread.MIN_PRIORITY);
m2.setPriority (Thread.MAX_PRIORITY);
m1.start ();
m2.start ();
}
Output:
We can allow multiple threads to modify the objects sequentially only by executing that
objects’ mutator methods logic in sequence from multiple threads.
Thread Synchronization is a process of allowing only one thread to use the object when
multiple threads are trying to use the particular object at the same time.
To achieve this Thread Synchronization we have to use a java keyword or modifier called
“synchronized”. Synchronization in java is the capability to control the access of multiple
threads to any shared resource. Java Synchronization is a better option where we want to
allow only one thread to access the shared resource.
General Syntax:
synchronized(objectidentifier)
{
// Access shared variables and other shared resources;
}
Types of Synchronization
1. Mutual Exclusive
2. Cooperation (Inter-Thread Communication) (I will discuss in the next article)
3.
Mutual Exclusive:
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
Mutual Exclusion can be achieved in three ways in java:
1. Synchronized Method
2. Synchronized Block
3. Static Synchronization
Thread Synchronization using Synchronized Method in Java:
Method level synchronization is used for making a method code thread-safe, i.e. only one
thread must be executing this method code.
Syntax :
{
//synchronized code
int tickets = 3;
static int i = 1, j = 2, k = 3;
else
if (name.equals ("t1"))
else
t1.setName ("t1");
t2.setName ("t2");
t3.setName ("t3");
t1.start ();
t2.start ();
t3.start ();
Output:
Syntax:
synchronized (object reference expression) {
//code block
int token = 1;
synchronized (this)
token++;
class SynchroBlock
A a1 = new A ();
t1.setName ("t1");
t2.setName ("t2");
t3.setName ("t3");
t1.start ();
t2.start ();
t3.start ();
Output:
For example online video players, audio players, etc. In both types of players generally,
there are two types of threads: Buffer Thread and Playing Thread.
The buffer Thread is responsible to download content from the server into a buffer memory
and whereas the playing thread is responsible to play content and these actions will be
done based on thread communication only.
Producer-Consumer Problem
Problem:
There are two processes, a producer and a consumer, that share a common buffer with a
limited size. The producer “produces” data and stores it in the buffer, and the consumer
“consumes” the data, removing it from the buffer. Having two processes that run in parallel,
we need to make sure that the producer will not put new data in the buffer when the buffer
is full and the consumer won’t try to remove data from the buffer if the buffer is empty.
Solution:
For solving this concurrency problem, the producer and the consumer will have to
communicate with each other. If the buffer is full, the producer will go to sleep and will wait
to be notified. After the consumer will remove some data from the buffer, it will notify the
producer, and then, the producer will start refilling the buffer again. The same process will
happen if the buffer is empty, but in this case, the consumer will wait to be notified by the
producer.
class ShowRoom
int value;
if (pro_thread == true)
value = i;
pro_thread = false;
notify ();
try
wait ();
}
if (pro_thread == true)
try
wait();
pro_thread = true;
notify ();
return value;
ShowRoom sr;
this.sr = sr;
int i = 1;
sr.produce (i);
try
Thread.sleep (1000);
ShowRoom sr;
this.sr = sr;
}
public void run ()
while (true)
try
Thread.sleep (1000);
t1.start ();
t2.start ();
Output:
UNIT - 5
What is a Framework?
Collection Object:
Collection Class:
Here objects o1, o2, o3, and o4 are stored two times
thereby we are wasting thememory within the JVM. To save
the memory within the JVM when the objects are stored in
Collection Interfaces :
In order to use functionalities of the List interface, we can use these classes:
1. ArrayList
2. LinkedList
3. Vector
4. Stack
These classes are defined in the Collections framework and implement the
List interface.
import java.util.ArrayList;
import java.util.List;
// Creation of ArrayList
al.add (30);
al.add (40);
al.add (50);
System.out.println (al);
System.out.println (al);
System.out.println (al);
al.remove (0);
System.out.println (al);
System.out.println (al.size ());
System.out.println (v);
//Searching an element
//Copying
Output: the array list into another list
ArrayList < Integer > al1 = new ArrayList < Integer > (al);
System.out.println (al1);
}
Note: In add(), remove(), get(), set() methods if we write any
wrong index which is not available then it will throw a run time
exception called IndexOutOfBoundException. ArrayList
supports storing multiple null values.
Creation of LinkedList
class LinkedListDemo
animals.add ("Dog");
animals.add ("Cat");
animals.add ("Horse");
//Iterator method
}
Output:
Creation of Vector
Methods of Vector
We can use all Collections Method to work with the
LinkedList. We can also use legacy methods like
addElement(), removeElement(), setElement(),….
Sample Program to demonstrate Vector Collection in Java
import java.util.*;
class VectorDemo {
mammals.add(2, "Cat");
// Using addAll()
animals.add("Crocodile");
animals.addAll(mammals);
// Using get()
// Using iterator()
System.out.print("Vector: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
Output:
Creation of Stack
S
t
a
c
k
C
o
n
s
t
r
u
c
t
o
r
p
u
b
l
i
c
S
t
a
c
k
(
)
The Stack class contains only the default constructor that creates an empty
stack.
Methods of Stack
import java.util.*;
s.push(10.2);
s.push(50.2);
s.push(30.2);
s.push(40.2);
s.push(70.2);
System.out.println(s);
System.out.println(s.pop());
System.out.println(s);
System.out.println(s.peek());
System.out.println(s);
Output:
Points to remember
o A Hashtable is an array of a list. Each list is known as a
bucket. The position of the bucket is identified by calling
the hashcode() method. A Hashtable contains values
based on the key.
o Java Hashtable class contains unique elements.
import java.util.*;
1. class Hashtable1{
2. public static void main(String args[]){
3. Hashtable<Integer,String>
hm=new Hashtable<Integer,String>(); 4.
hm.put(100,"Amit");
5. hm.put(102,"Ravi");
6. hm.put(101,"Vijay");
7. hm.put(103,"Rahul");
8. for(Map.Entry m:hm.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue());
10. }
11. }
12. }
14.103 Rahul
102 Ravi
101 Vijay
100 Amit
Stream
A series of data is referred to as a stream. In Java, Stream
is classified into two types,i.e., Byte Stream and Character
Stream.
Byte Stream
Character Stream
File Operations
We can perform the following operation on a file:
o Create a File
o Write to a File
o Delete a File
Create a File
CreateFile.java
19. }
20. }
Output:
Explanation:
FileInfo.java
25. }
26. }
Write to a File
Let's take an example to understand how we can write data into a file.
WriteToFile.java
14.14.
15. // Closing the stream
16. fwrite.close();
17. System.out.println("Content is successfully wrote to the file.");
18. } catch (IOException e) {
19. System.out.println("Unexpected error occurred");
20. e.printStackTrace();
21. }
22. }
23. }
Output:
Explanation:
Let's take an example to understand how we can read data from a file.
ReadFromFile.java
18. dataReader.close();
19. } catch (FileNotFoundException exception) {
20. System.out.println("Unexcpected error occurred!");
21. exception.printStackTrace();
22. }
23. }
24. }
Output: