Here I discuss about Java programming language and easiest way to solve programming problem. Java basic syntax and their uses are described briefly so that anyone can easily understand within very short time. If anyone follow the slide with proper way,I assure that he or she will find java programming interesting.
2. What is Java?
Java is a programming language and a platform.
A simple,object‐ oriented, distributed, interpreted,robust,
secure, architecture neutral, portable, high ‐performance,
multithreaded, and dynamic language
PlatformAny hardware or software environment in which a
program runs, known as a platform. Since Java has its own
Runtime Environment (JRE) andAPI, it is called platform.
3. Java Editions
Java has 3 editions.
Java 2 Platform, Standard Edition (J2SE)
Used for developing Desktop ‐ based application and
networking applications.
Java 2 Platform, Enterprise Edition (J2EE)
Used for developing large‐ scale, distributed networking
applications andWeb ‐based applications.
Java 2 Platform, Micro Edition (J2ME)
Used for developing applications for small memory‐
constrained devices, such as cell phones, pagers and PDAs.
4. Bytecodes
They are not machine language binary code.
They are independent of any particular microprocessor or hardware
platform.
They are platform‐ independent instructions.
Another entity or interpreter is required to convert the bytecodes
into machine codes that the underlying microprocessor understands.
This is the job of theJVM (JavaVirtual Machine).
Java programs actually go through two compilation phases
Source code ‐ > bytecodes
Bytecodes‐ > machine language
5. What is the difference between JRE,JVM and JDK?
JVM (JavaVirtual 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).The JVM performs four main
tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for the:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
6. 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.
7. JDK
JDK is an acronym for Java Development Kit.It physically
exists.It contains JRE + development tools.
8. Variable
Variable is name of reserved area allocated in memory.
There are three types of variables in java
1. local variable(A variable that is declared inside the method
is called local variable)
2. instance variable(A variable that is declared inside the class
but outside the method is called instance variable . It is not
declared as static)
3. static variable( A variable that is declared as static is called
static variable. It cannot be local)
9. public static void main(String args[ ]) is the starting
point of every Java application.
public is used to make the method accessible by all.
static is used to make main a static method of class MyClass.
static methods can be called without using any object; just
using the class name is enough. Being static, main can be called
by the JVM using the ClassName.methodName notation.
void means main does not return anything.
String args[ ] represents a function parameter that is an array
of String objects.This array holds the command line arguments
passed to the application.
10. FAQ
Think of JVM as a Java entity who tries to access the main
method of class MyClass .
To do that main must be accessible from outside of class
MyClass. So, main must be declared as a public member of
class MyClass .
Also, JVM wants to access main without creating an object of
class MyClass .So,main must be declared as static.
Also JVM wants to pass an array of String objects containing
the command line arguments. So,main must take an array of
String as parameter.
11. System.out.println() is used to print a line of text
followed by a new line
System is a class inside the Java API.
out is a public static member of class System .
out is an object of another class of the Java API
out represents the standard output (similar to stdout or
cout ).
println is a public method of the class of which out
is an object
javac (the Java compiler)
12. Constructor & keyword new
Each class you declare can provide a special method called a
constructor that can be used to initialize an object of a class
when the object is created. In fact, Java requires a
constructor call for every object that’s created. Keyword new
requests memory from the system to store an object, then
calls the corresponding class’s constructor to initialize the
object.The call is indicated by the parentheses after the class
name.A constructor must have the same name as the class.
13. Methods setMethodName and
getMethodName ?
Method setMethodName does not return any data when it
completes its task,so its return type is void.The method
receives one parameter— name which represents the
variable name that will be passed to the method as an
argument.
Method getMethodName returns a particular Class
object’s variableName.The method has an empty parameter
list, so it does not require additional information to perform
its task.The method specifies that it returns a String —this is
the method’s return type.When a method that specifies a
return type other than void is called and completes its task,
the method returns a result to its calling method.
14. Why do we need to import class Scanner,but
not classes System , String or MyClass ?
Classes System and String are in package java.lang,which is
implicitly imported into every Java program, so all programs
can use that package’s classes without explicitly importing
them. Most other classes you’ll use in Java programs must be
imported explicitly.
16. Why char uses 2 byte in java and what is u0000 ?
Java uses unicode system rather than ASCII code system. u0000 is the lowest
range of unicode system.Unicode is a universal international standard character
encoding that is capable of representing most of the world's written languages.
Before Unicode, there were many language standards:
ASCII (American Standard Code for Information Interchange) for the United States.
ISO 8859-1 forWestern European Language.
KOI-8 for Russian.
GB18030 and BIG-5 for chinese, and so on.
This caused two problems:A particular code value corresponds to different
letters in the various language standards.
The encodings for languages with large character sets have variable length.Some
common characters are encoded as single bytes, other require two or more byte.
To solve these problems, a new language standard was developed i.e.
Unicode System.In unicode, character holds 2 byte, so java also uses 2 byte
for characters.lowest value:u0000,highest value:uFFFF
17. OOPs (Object Oriented Programming System)
Object means a real word entity such as pen, chair, table
etc. Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects. It
simplifies the software development and maintenance by
providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
18. Characteristics of OOP
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
Collection of objects is called class. It is a logical entity.
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.
19. Characteristics of OOP
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.
Abstraction
Hiding internal details and showing functionality is
known as abstraction. For example: phone call, we don't know
the internal processing.
In java, we use abstract class and interface to achieve
abstraction.
20. OOP
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.
21. What is difference between object-oriented programming
language and object-based programming language?
Object based programming language follows all the features
of OOPs except Inheritance. JavaScript andVBScript are
examples of object based programming languages.
22. Naming convention
Name Convention
class name Should begin with uppercase letter and be a noun e.g. String
,System,Thread etc
Interface
name
Should begin with uppercase letter and be an adjective(wherever
possible) e.g. Runnable(),ActionListener() etc
method name Should begin with lowercase letter and be a verb. e.g.
main(),print(),println(),actionListenerPerformed()
Variable name Should begin with lowercase letter e.g. firstName,orderNumber etc
Package name Should be in lowercase letter e.g. java,lang,sql,util etc
Constants
name
Should be in uppercase letter. E.g. RED,YELLOW,MAX_PRIORITY
etc
23. Object
A runtime entity that has state and behaviour is known as an object.
An object has three characterstics:
state:represents the data of an object.
behaviour:represents the behaviour of an object.
identity:Object identity is typically implemented via a unique ID.
The value of the ID is not visible to the external user, but is used
internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white
etc. known as its state. It is used to write, so writing is its behaviour.
Object is an instance of a class.Class is a template or blueprint
from which objects are created.So object is the instance(result) of a
class.
24. Class
A class is a group of objects that have common property. It is a template or
blueprint from which objects are created.A class in java can contain:
data member
method
constructor
block
A variable that is created inside the class but outside the method, is known as
instance variable.Instance variable doesn't get memory at compile time.It
gets memory at runtime when object(instance) is created.That is why, it is
known as instance variable.
Method
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
Code Reusability
Code Optimization
25. What are the different ways to create an object in Java?
There are many ways to create an object in java.They are:
By new keyword
By newInstance() method
By clone() method
By factory method etc.
new keyword
The new keyword is used to allocate memory at runtime.
26. Annonymous object
Annonymous simply means nameless.An object that have no reference is
known as annonymous object.If you have to use an object only once,
annonymous object is a good approach.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with annonymous object
}
}
27. Creating multiple objects by one type only
We can create multiple objects by one type only as we do in
case of primitives.
Rectangle r1=new Rectangle(),r2=new Rectangle();//cre
ating two objects
28. Method overloading
If a class have multiple methods by same name but different
parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name
of the methods increases the readability of the program.
Advantage of method overloading?
Method overloading increases the readability of the
program.
Different ways to overload the method
1. There are two ways to overload the method in javaBy
changing number of arguments
2. By changing the data type
29. Why Method Overloading is not possible by changing the
return type of method?
In java, method overloading is not possible by changing the
return type of the method because there may occur ambiguity.
Let's see how ambiguity may occur: because there was
problem:
class Calculation{
int sum(int a,int b){System.out.println(a+b);}
double sum(int a,int b){System.out.println(a+b);}
public static void main(String args[]){
Calculation obj=new Calculation();
int result=obj.sum(20,20); //CompileTime Error
}
}
30. Can we overload main() method?
Yes, by method overloading.You can have any number of main
methods in a class by method overloading. Let's see the simple
example:
class Simple{
public static void main(int a){
System.out.println(a);
}
public static void main(String args[]){
System.out.println("main() method invoked");
main(10);
}
}
31. Constructor
Constructor is a special type of method that is used to
initialize the object.
Constructor is invoked at the time of object creation. It
constructs the values i.e. provides data for the object that is why it
is known as constructor.
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
32. Constructor
What is the purpose of default constructor?
Default constructor provides the default values to the object
like 0, null etc. depending on the type.
A constructor that have parameters is known as
parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values
to the distinct objects.
33. Constructor Overloading
class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "
+age);}
public static void main(String args[]){
Student s1 = new Student(111,“Tarif");
Student s2 = new Student(222,“Soheab",25);
s1.display();
s2.display();
}
}
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
34. What is the difference between constructor and method ?
Constructor Method
Constructor is used to initialize the state of
an object.
Method is used to expose behaviour of an
object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default
constructor if you don’t have any
constructor.
Method is not provided by compiler in any
case.
Constructor name must be same as the class
name.
Method name may or may not be same as
class name.
35. Copying the values of one object to another like copy
constructor in C++
There are many ways to copy the values of one object into
another.They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
36. In this example, we are going to copy the values of one object into another using constructor.
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(Student s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,“Tarif");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
}
37. FAQ
Does constructor return any value?
Ans:yes,that is current class instance (You cannot use return
type yet it returns a value).
Can constructor perform other tasks instead of
initialization?
Yes, like object creation, starting a thread, calling method
etc.You can perform any operation in the constructor as you
perform in the method.
38. static keyword
The static keyword is used in java mainly for memory
management.We may apply static keyword with variables,
methods, blocks and nested class.The static keyword belongs
to the class than instance of the class.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
39. static variable
If you declare any variable as static, it is known static
variable.The static variable can be used to refer the common
property of all objects (that is not unique for each object) e.g.
company name of employees,college name of students etc.
The static variable gets memory only once in class area at the
time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves
memory).
40. Program of counter without static variable
class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.print(count+“ ”);
}
public static void main(String args[]){
Counter c1 =new Counter();
Counter c2 =new Counter();
Counter c3 =new Counter();
}
} // Output:1 1 1
41. Program of counter by static variable
class Counter{
static int count=0;//will get memory only once and retain its value
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
42. static method
If you apply static keyword with any method, it is known as static
method
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an
instance of a class.
static method can access static data member and can change the
value of it.
why main method is static?
Ans) because object is not required to call static method. If it
were non-static method, jvm create object first then call main()
method that will lead the problem of extra memory allocation.
43. Restrictions for static method
There are two main restrictions for the static method.They
are:The static method can not use non static data member or
call non-static method directly.
this and super cannot be used in static context.
class A{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
} // compile time error
44. this keyword
There can be a lot of usage of this keyword. In java, this is
a reference variable that refers to the current object.
45. Usage of this keyword
Here is given the 6 usage of this keyword.
1. this keyword can be used to refer current class instance
variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method
(implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class
instance.
46. The this keyword can be used to refer current class instance variable.
class Student{
int id;
String name;
student(int id,String name){
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1 = new Student(111,“Tarif");
Student s2 = new Student(222,“Nazrul");
s1.display();
s2.display();
}
}
If there is ambiguity between the instance variable and parameter, this keyword
resolves the problem of ambiguity.
47. Inheritance
Inheritance is a mechanism in which one object acquires all
the properties and behaviours of parent object.
Inheritance represents the IS-A relationship.
Why use Inheritance ?
1. For method overriding(So runtime polymorphism)
2. For code Reusability.
48. Method Overriding
Having the same method in the subclass as declared in the parent
class is known as method overriding.
In other words, If subclass provides the specific implementation of
the method i.e. already provided by its parent class, it is known as
Method Overriding.
Advantage of Method Overriding
Method Overriding is used to provide specific implementation of a
method that is already provided by its super class.
Method Overriding is used for Runtime Polymorphism
Rules for Method Overriding:
1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be inheritance (IS-A) relationship.
49. FAQ
Can we override static method?
No, static method cannot be overridden. It can be proved by
runtime polymorphism.
Why we cannot override static method?
because static method is bound with class whereas instance
method is bound with object. Static belongs to class area and
instance belongs to heap area.
50. What is the difference between method Overloading and
Method Overriding?
Method Overloading Method Overriding
Method overloading is used to increase the
readability of the program.
Method overriding is used to provide the
specific implementation of the method that
is already provided by its super class.
Method overloading is performed within a
class.
Method overriding occurs in two classes that
have IS-A relationship.
In case of method overloading parameter
must be different.
In case of method overriding parameter
must be same.
51. super keyword
The super is a reference variable that is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of
parent class is created implicitly i.e. referred by super reference
variable.
Usage of super Keyword
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.
Is final method inherited?
Ans)Yes, final method is inherited but you cannot override it.
52. final keyword
The final keyword in java is used to restrict the user.The
final keyword can be used in many context. Final can be:
variable
method
class
If you make any variable as final, you cannot change the value
of final variable(It will be constant).
If you make any method as final, you cannot override it.
If you make any class as final, you cannot extend it.
Can we declare a constructor final?
No, because constructor is never inherited.
53. FAQ
What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is
known as blank final variable.
If you want to create a variable that is initialized at the time of
creating object and once initialized may not be changed, it is
useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.
Can we initialize blank final variable?
Yes, but only in constructor.
static blank final variable
A static final variable that is not initialized at the time of
declaration is known as static blank final variable. It can be
initialized only in static block.
54. Runtime Polymorphism
Runtime polymorphism or Dynamic Method
Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.
An overridden method is called through the reference
variable of a superclass.The determination of the method to
be called is based on the object being referred to by the
reference variable.
55. Example
class Bike{
void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Honda();//upcasting
b.run();
}
} //output: running safely with 60km
56. Abstract class
A class that is declared with abstract keyword, is known as abstract
class.
Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
Another way, it shows only important things to the user and hides the
internal details for example sending sms, you just type the text and send
the message.You don't know the internal processing about the message
delivery.
Abstraction lets you focus on what the object does instead of how it does
it.
Ways to achieve Abstaction
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
57. Abstract class
A class that is declared as abstract is known as abstract
class. It needs to be extended and its method implemented.
It cannot be instantiated.
A method that is declared as abstract and does not have
implementation is known as abstract method.
If there is any abstract method in a class,that class must
be abstract.
58. Example
abstract class Bike{
abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}
}
59. Interface
An interface is a blueprint of a class. It has static constants and
abstract methods.
The interface is a mechanism to achieve fully abstraction in
java.There can be only abstract methods in the interface. It is used to
achieve fully abstraction and multiple inheritance in Java.
Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
There are mainly three reasons to use interface.
1. It is used to achieve fully abstraction.
2. By interface, we can support the functionality of multiple
inheritance.
3. It can be used to achieve loose coupling.
60. Understanding relationship between classes and interfaces
A class implements interface but One interface extends another
interface .As shown in the figure given below, a class extends
another class, an interface extends another interface but a class
implements an interface.
61. Multiple inheritance is not supported in case of class but
it is supported in case of interface, why?
Multiple inheritance is not supported in case of class. But it is
supported in case of interface because there is no ambiguity
as implementation is provided by the implementation class.
For example:
interface Printable{
void print();
}
interface Showable{
void print();
}
class A implements Printable,Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A obj = new A();
obj.print();
}
}
Output: Hello
62. Package
A package is a group of similar types of classes, interfaces
and sub-packages.
Package can be categorized in two form, built-in package and
user-defined package.There are many built-in packages such
as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Package
Package is used to categorize the classes and interfaces so that
they can be easily maintained.
Package provides access protection.
Package removes naming collision.
64. Access Modifiers
There are two types of modifiers in java: access
modifier and non-access modifier.The access modifiers
specifies accessibility (scope) of a datamember, method,
constructor or class.
There are 4 types of access modifiers:
private
default
protected
public
There are many non-access modifiers such as static, abstract,
synchronized, native, volatile, transient etc.
65. private
The private access modifier is accessible only within class.
If you make any class constructor private, you cannot create
the instance of that class from outside the class. A class
cannot be private or protected except nested class.
class A{
private A(){}//private constructo
r
void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();//CompileTime Error
}
}
66. default
If you don't use any modifier, it is treated as default by default.The
default modifier is accessible only within package.
protected
The protected access modifier is accessible within package and
outside the package but through inheritance only.
The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
public
The public access modifier is accessible everywhere. It has the
widest scope among all other modifiers.
67. Understanding all java access modifiers
Access
Modifier
Within class Within
package
Outside
package by
subclass only
Outside
package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
68. Encapsulation
Encapsulation is a process of wrapping code and data
together into a single unit e.g. capsule i.e mixed of several
medicines.
We can create a fully encapsulated class by making all the
data members of the class private. Now we can use setter and
getter methods to set and get the data in it.
Advantage of Encapsulation
By providing only setter or getter method, you can make the
class read-only or write-only.
It provides you the control over the data. Suppose you
want to set the value of id i.e. greater than 100 only, you can
write the logic inside the setter method.
69. Array
Array is an object the contains elements of similar data type. It is a
data structure where we store similar elements.We can store only
fixed elements in an array.
Array is index based, first element of the array is stored at 0 index.
Advantage of Array
Code Optimization: It makes the code optimized, we can retrieve
or sort the data easily.
Random access:We can get any data located at any index position.
Disadvantage of Array
Size Limit:We can store only fixed size of elements in the array. It
doesn't grow its size at runtime.To solve this problem, collection
framework is used in java.
There are two types of array.
Single DimensionalArray
MultidimensionalArray
70. Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we
call a method passing a value, it is known as call by value.The
changes being done in the called method, is not affected in
the calling method.
class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be
in the local variable only
}
//output:
before change 50
after change 50
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op
.data);
op.change(500);
System.out.println("after change "+op.d
ata);
}
}
72. Types of Exception:
There are mainly two types of exceptions: checked and
unchecked where error is considered as unchecked
exception.
The sun microsystem says there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
73. What is the difference between checked and unchecked
exceptions ?
1)Checked Exception
The classes that extendThrowable class except RuntimeException
and Error are known as checked exceptions e.g.IOException,
SQLException etc. Checked exceptions are checked at compile-
time.
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked
exceptions e.g.ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are
not checked at compile-time rather they are checked at runtime.
3)Error
Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError,AssertionError etc.
74. FAQ
If we divide any number by zero, there occurs an ArithmeticException.
If we have null value in any variable, performing any operation by the variable
occurs an NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
The wrong formatting of any value, may occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
75. Exception Handling
Five keywords used in Exception handling:
I. try
II. catch
III. finally
IV. throw
V. throws
try block
Enclose the code that might throw an exception in try block. It must
be used within the method and must be followed by either catch or
finally block.
Catch block is used to handle the Exception. It must be used after
the try block.
The finally block is a block that is always executed. It is mainly used
to perform some important tasks such as closing connection,
stream etc.
76. finally block
Why use finally block?
finally block can be used to put "cleanup" code such as closing a
file,closing connection etc.
The throw keyword is used to explictily throw an exception.We
can throw either checked or uncheked exception.The throw
keyword is mainly used to throw custom exception.
Which exception should we declare?
Ans) checked exception only, because:unchecked
Exception: under your control so correct your code.
error: beyond your control e.g. you are unable to do anything if
there occursVirtualMachineError or StackOverflowError.
77. throws keyword
The throws keyword is used to declare an exception. It
gives an information to the programmer that there may
occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can
be maintained.Exception Handling is mainly used to handle
the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers
fault that he is not performing check up before the code
being used.
78. Difference between throw and throws
throw keyword throws keyword
Throw is used to explicitly throw an
exception.
Throws is used to declare an exception.
Checked exception can not be propagated
without throws.
Checked exception can be propagated with
throws.
Throw is used within the method. Throws is used with the method signature.
Throw is followed by an instance. Throws is followed by class.
You can not throw multiple exception You can declare multiple exception e.g.
public void method()throws
IOException,SQLException.
79. Multithreading
Multithreading is a process of executing multiple threads
simultaneously.
Thread is basically a lightweight subprocess, a smallest unit of
processing. Multiprocessing and multithreading, both are
used to achieve multitasking. But we use multithreading than
mulitprocessing because threads share a common memory
area.They don't allocate separate memory area so save
memory, and context-switching between the threads takes
less time than processes.
Multithreading is mostly used in games, animation etc.
80. Multitasking
Multitasking is a process of executing multiple tasks
simultaneously.We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
Process-based Multitasking (Multiprocessing)
Each process have its own address in memory i.e. each process
allocates separate memory area.
Process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another require some time for
saving and loading registers, memory maps, updating lists etc.
81. 2)Thread-based Multitasking (Multithreading)
Threads share the same address space.
Thread is lightweight.
Cost of communication between the thread is low.
Note:At least one process is required for each thread.
What isThread?
A thread is a lightweight subprocess, a smallest unit of
processing. It is a separate path of execution. It shares the
memory area of process.
82. Life cycle of a Thread (Thread States)
A thread can be in one of the five states in the thread.
According to sun, there is only 4 states new, runnable, non-
runnable and terminated.There is no running state. But for
better understanding the threads, we are explaining it in the 5
states.The life cycle of the thread is controlled by JVM.The
thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
83. How to create thread:
There are two ways to create a thread:
1. By extendingThread class
2. By implementing Runnable interface
Thread class:
Thread class provide constructors and methods to create and
perform operations on a thread.Thread class extends Object
class and implements Runnable interface.Commonly used
Constructors ofThread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
84. Can we start a thread twice?
No.After staring a thread, it can never be started again. If
you does so, an IllegalThreadStateException is thrown.
class Multi extendsThread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
t1.start();
}
}
Output:running
Exception in thread "main" java.lang.IllegalThreadStateException
86. AWT
Container:
The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc.The classes that extends Container class
are known as container.
Window:
The window is the container that have no borders and menubars.You must
use frame, dialog or another window for creating a window.
Panel:
The Panel is the container that doesn't contain title bar and MenuBars. It can
have other components like button, textfield etc.
Frame:
The Frame is the container that contain title bar and can have MenuBars. It
can have other components like button, textfield etc.
There are two ways to create a frame:
By extending Frame class (inheritance)
By creating the object of Frame class (association)
88. Layout Managers
The LayoutManagers are used to arrange components in a particular
manner. LayoutManager is an interface that is implemented by all
the classes of layout managers.There are following classes that
represents the layout managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout
javax.swing.SpringLayout etc.
89. BorderLayout
The BorderLayout is used to arrange the components in five regions:
north, south, east, west and center. Each region (area) may contain one
component only. It is the default layout of frame or window.The
BorderLayout provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final intWEST
public static final int CENTER
90. GridLayout()
The GridLayout is used to arrange the components in rectangular grid. One
component is dispalyed in each rectangle.Constructors of GridLayout class:
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows
and columns but no gaps between the components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout
with the given rows and columns alongwith given horizontal and vertical gaps.
91. FlowLayout
The FlowLayout is used to arrange the components in a line,
one after another (in a flow). It is the default layout of applet or
panel.Fields of FlowLayout class:
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final intTRAILING
92. Applet
Applet is a special type of program that is embedded in the
webpage to generate the dynamic content. It runs inside the
browser and works at client side.Advantage ofApplet
There are many advantages of applet.They are as follows:It
works at client side so less response time.
Secured
It can be executed by browsers running under many
plateforms, including Linux,Windows, Mac Os etc.
String details from book…….
93. Assignment
Argument passing,message passing,token ?
Difference among java,c & c++ ?
Why java is so popular ?
Create calculator by Using Java GUI
Create a simple chat and echo server
Read Details on:
Java Graphics
Java Networking
Java Database Management System