Sunteți pe pagina 1din 24

JAVA NOTES AND SYNTAX

https://www.tutorialspoint.com
http://www.learnjavaonline.org
http://www.java2novice.com/data-structures-in-java/stacks/introduction/

1. The four important features of any object oriented programming are


Encapsulation, Polymorphism, Inheritance, and Abstraction.

Encapsulation is a programming mechanism that binds together code


and the data it manipulates, and that keeps both safe from outside
interference and misuse. In an object-oriented language, code and data
can be bound together in such a way that a self-contained black box is
created. Within the box are all necessary data and code. When code and
data are linked together in this fashion, an object is created. In other
words, an object is the device that supports encapsulation. Within an
object, code, data, or both may be private to that object or public. Private
code or data is known to and accessible by only another part of the object.
That is, private code or data cannot be accessed by a piece of the
program that exists outside the object. When code or data is public, other
parts of your program can access it even though it is defined within an
object. Typically, the public parts of an object are used to provide a
controlled interface to the private elements of the object. Javas basic unit
of encapsulation is the class. Although the class will be examined in great
detail later in this book, the following brief discussion will be helpful now.
A class defines the form of an object. It specifies both the data and the
code that will operate on that data. Java uses a class specification to
construct objects. Objects are instances of a class. Thus, a class is
essentially a set of plans that specify how to build an object. The code and
data that constitute a class are called members of the class. Specifically,
the data defined by the class are referred to as member variables or
instance variables. The code that operates on that data is referred to as
member methods or just methods. Method is Javas term for a subroutine.
Encapsulation: Encapsulation is one of the four fundamental OOP
concepts. The other three are inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and
code acting
on the data (methods) together as a single unit. In encapsulation, the
variables of a
class will be hidden from other classes, and can be accessed only through
the methods
of their current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables
values.
Polymorphism:
Polymorphism helps reduce complexity by allowing the same interface to be
used to specify a general class of action. It is the compilers job to select the
specific action (i.e., method) as it applies to each situation. You, the
programmer, dont need to do this selection manually. You need only
remember and utilize the general interface.
Polymorphism is the ability of an object to take on many forms. The most
common use of polymorphism in OOP occurs when a parent class reference is
used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be
polymorphic. In Java, all Java objects are polymorphic since any object will
pass the IS-A test for their own type and for the class Object.
It is important to know that the only possible way to access an object is
through a reference variable. A reference variable can be of only one type.
Once declared, the type of a reference variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is
not declared final. The type of the reference variable would determine the
methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any
subtype of its declared type. A reference variable can be declared as a class
or interface type.
Abstraction: As per dictionary, abstraction is the quality of dealing with
ideas rather than events. For example, when you consider the case of e-mail,
complex details such as what happens as soon as you send an e-mail, the
protocol your e-mail server uses are hidden from the user. Therefore, to send
an e-mail you just need to type the content, mention the address of the
receiver, and click send. Likewise in Object-oriented programming,
abstraction is a process of hiding the implementation details from the user,
only the functionality will be provided to the user. In other words, the user will
have the information on what the object does instead of how it does it.
In Java, abstraction is achieved using Abstract classes and interfaces. A class
that has abstract
keyword is an abstract class.

Inheritance: Inheritance can be defined as the process where one class


acquires the properties (methods and fields) of another. With the use of
inheritance, the information is made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass


(derived class, child class) and the class whose properties are inherited is
known as superclass (base class, parent class).
extends Keyword. extends is the keyword used to inherit the properties of
a class. Following is the syntax of extends keyword.

2. Java Virtual Machine :


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.

The JVM performs following main tasks:

Loads code, Verifies code, Executes code, Provides runtime environment.


It is:

1. A specification where working of Java Virtual Machine is specified. But


implementation provider is independent to choose the algorithm. Its
implementation has been provided by Sun and other companies.

2. An implementation Its implementation is known as JRE (Java Runtime


Environment).

3. Runtime Instance Whenever you write java command on the command


prompt to run the java class, an instance of JVM is created.

JVM provides definitions for the:

o Memory area

o Class file format


o Register set

o Garbage-collected heap

o Fatal error reporting etc.

3. Java Runtime Environment: 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.
4. Java Development Kit: JDK is an acronym for Java Development Kit. It
physically exists. It contains JRE + development tools.

5. Java is an Object Oriented Program that has the three important traits
encapsulation, polymorphism, abstraction and inheritance
6. Java consists of Classes, Objects, Methods, Constructors, and etc.
7. /* Multiline comments*/ for multiple line comments in the java program
8. //single line comment for single line comment in the java program
9. The Java program name should be equal to the class name.
10.Class name should start with a capital letter and it should be like a camel
humps.
11.Java keywords cannot be used for variables, class, or method.
12.A variable is a named memory location that can be assigned a value.
Further, the value of a variable can be changed during the execution of a
program. That is, the content of a variable is changeable, not fixed. In
Java, all variables must be declared before they are used. Further, the
type of values that the variable can hold must also be specified. This is
called the type of the variable.
RAM

A variable is of three types.


1. Local: A variable which is declared inside the method is called
local variable
2. Instance variable: A variable which 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.
13.Variable names may start with any letter of the alphabet, an underscore,
or a dollar sign.
14.Methods should start with a small alphabet and should be like a camel
humps.
15.true, false, and null are values defined by Java which cannot be used for
the names of variables, classes, and so on.
16.Relational Operators:
a. == is equal to
b. != not equal to
c. > greater than
d. >= greater than or equal to
e. < less than
f. <= less than or equal to
17.Arithmetic Operators
a. +, -, *, /
b. %, modulus operator : e.g., a % b yields the remainder of the
division a/b, e.g., 10 % 3 = 1, 10.0%3.0 =1.
c. +=, -=, *=, /=, assigment coupled with binary arithmetic e.g.,
a+=5 is same as a=a+5, a-=5 is same as a=a-5, a *= 5 is same a
= a * 5; a/=5 is same as a=a/5
d. x++, post-increment x.
e. ++x, pre-increment x
f. x--, post-decrement
g. --x, pre-decrement
18.Logical Operators (Boolean expressions)
a. a & b (true if a is true and b is true): e.g., ((length <= 100) &
(length % 10 == 1))
b. a | b (true if a is true or b is true)
c. !a (unary) (true if a is false, otherwise false)
d. a^b (exclusive or--true if a is true and b is false, or if b is true and a
is false, otherwise, false)
e. a && b short-circuit And logical operators it does not work on the
instructions where division with 0.
f. a || b short-circuit Or logical operators. Here the right-hand operand
is not taken into consideration.
19.Primitive Types:
a. byte -- 8-bit integer
b. char -- one character is unsigned 16-bit type , e.g. 'F', 'x', '6'
c. short -- 16 bit integer
d. int -- 32 bit integer, e.g. 1, -22, 0
e. float --32 bit single precision floating point, e.g. 6.41, -0.375 and
while using as literal we have to use 6.41F
f. long -- 64 bit integer e.g 12 and while using this for a long literal
we have to use 12L
g. double --64 bit double-precision floating point, e.g 10.19. By
default floats are of type double.
h. boolean -- true or false
i. byte range is -128 to 127
j. short range is -32768 to 32767
k. int range is 2,147,483,648 to 2,147,483,647
l. long range is 9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
m. Char range is 0 to 65536
n. Hexadecimal, Octal, and Binary Literals
o. bin = 0b1100; // 12 in binary
p. hex = 0xFF; // 255 in decimal
q. oct = 011; // 9 in decimal
20.Non-Primitive Types (Objects): Strings, Arrays.

21.When one type of data is assigned to another type of variable, an


automatic type conversion will take place if
a. The destination type is larger than the source type.
b. The two types are compatible.
c. byte to int, long to double etc.
d. int can be assigned to char but char cannot be assigned to int
22.Casting is an instruction to the compiler to convert one type into another
type.
23.Urinary operator ~ :
System.out.println(~10); Gives the output -11
System.out.println(~(-9)); Gives the output 8.
24.Shift operator:
System.out.println(10<<2); Gives //10*2^2=10*4=40
System.out.println(20>>2); Gives //20/2^2=20/4=5
25.if double x needs to be changed to integer then the cast instruction is
(int)x.
26.String is not a primitive type!
27.Java key words:
a. Data types: byte, short, int, long, double, float, char, Boolean(8)
b. Flow control types: if, else, switch, case, default, break, for, while,
else, do, continue (10).
c. Object level: new, this, super, instanceof (4)
d. Methods: void, return (2)
e. Source file: class, extends, interface, implements, package, import
(6)
f. Exception handling: try, catch, finally, throws, throw (5)
g. Java 5: enum, assert (2)
h. Un used: goto, const(2)
i. Modifiers: public, private, protected, final, static, abstract,
synchronized, strictif, volatile, transient, native (11)(default can also
be included here but more appropriate place is flow control types)

28.Different print statements:


a. System.out.print(); This is to print in a line. If the statements to be
printed one after another then we use it.
b. System.out.print(a+ + b + + c); The output will be the
letters one after another in a same line.
c. System.out.println(): This is to print in a new line. If the statements
to be printed one by one, we use this.
d. System.out.println(a+"\n"+b+"\n"+c); The output will be the letters
one by one in a new line.
e. String str="Hello World!"; System.out.println (str + "\nA new
line+"\t" + "Tab"+"\n" + "A new line"); The output will be
Hello World!
A new line Tab
A new line
29.Declarations:
a. Int a;
b. Int a, b, c;
c. char ch;
d. char ch, sa;
e. String
30.Declarations and initializations:
a. Int a = 0, b = 1, c = 2;
b. char ch = A;
c. char ch = A, sa = B;
31.Control Statements:
Inside a method, execution proceeds from one statement to the next, top
to bottom. However, it is possible to alter this flow through the use of the
various program control statements supported by Java.
a. The if statement: if(condition) statement;
b. The if-else statements: if(condition) statement; else statement;
c. The if -else loop:
if(condition) { statement sequence } else { statement
sequence }
d. The nested if:
A nested if is an if statement that is the target of another if or else.
Nested ifs are very common in programming.

e. The if else ladder

f. The for loop:

for(initialization; condition; iteration) statement;


for (int a = 10, b = 3; b > 3;, b++} Legal expression
for (int a = 0; (a>3),(b>5); a++) Illegal expression
for (;a<3;) Legal expression

g. The switch statement:

h. Nested switch statements:

i. The infinite loop:


AND AND

j. Loops with no body:

k. The while loop:

l. The do while loop:

m. Break statement: It is possible to force an immediate exit from a


loop, bypassing any remaining code in the body of the loop and the
loops conditional test, by using the break statement. When a break
statement is encountered inside a loop, the loop is terminated and
program control resumes at the next statement following the loop.
n. Continue statement: It is possible to force an early iteration of a
loop, bypassing the loops normal control structure. This is
accomplished using continue. The continue statement forces the
next iteration of the loop to take place, skipping any code between
itself and the conditional expression that controls the loop. Thus,
continue is essentially the complement of break.
o. Return statement: This is a statement in the code. When this
statement executes, program control returns to the caller, skipping
any remaining code in the method.
p. The Break, Continue, and Return statements are known as Jump
statements.
32.Class is a plan for objects and can be imagined as a blueprint for a
building before construction. A class is a template that defines the form of
an object. It specifies both the data and the code that will operate on that
data. Java uses a class specification to construct objects. Objects are
instances of a class. Thus, a class is essentially a set of plans that specify
how to build an object. a class is a logical abstraction. It is not until an
object of that class has been created that a physical representation of that
class exists in memory. The methods and variables that constitute a class
are called members of the class. The data members are also referred to as
instance variables.
33.An object is an instance of a class. Object has three features.
State: Represents data (value) of an object.
Behavior: Represents the behavior (functionality) of an object such as deposit,
withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. But, it is used internally by the JVM to
identify each object uniquely.

Object is a real world entity, a run time entity, instance of a class, an


entity which has both state and behavior.

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 behavior.

34. Passing Objects to Methods: Objects can be passed to methods.


35. Passing arguments to Methods: Arguments can be passed to Methods.
36.Access Modifiers:
Member access control is achieved through the use of three access
modifiers: public, private, and protected. When a member of a class is
modified by the public specifier, that member can be accessed by any
other code in your program. This includes methods defined inside other
classes. When a member of a class is specified as private, that member
can be accessed only by other members of its class. Thus, methods in
other classes cannot access a private member of another class.
A private member can be used freely by other members of its class, but it
cannot be accessed by code outside its class.
When a class is declared as public, it is accessible by any other code. If a
class has default access, it can be accessed only by other code within its
same package. Also, a class that is declared public must reside in a file by
the same name.
To make a java class file in one package available to other packages, the
class should be made public, its constructor must be made public, and
finally its show() method needs to be public. a protected member is
available for all subclasses to use but is still protected from arbitrary
access by code outside its package.

37.A class always consists of


a. Names
b. Attributes (Instance variables, member variables). These are
variables declared inside the class and not inside a method.
c. Methods (Functions and Procedures). These are nothing but the
things an object can do or the things that manipulates the object
state or share. Methods are subroutines that manipulate the data
defined by the class and, in many cases, provide access to that
data. In most cases, other parts of programs will interact with a
class through its methods. A method contains one or more
statements. In well-written Java code, each method performs only
one task. Each method has a name, and it is this name that is used
to call the method. In general, you can give a method whatever
name you please. However, remember that main( ) is reserved for
the method that begins execution of your program. Also, dont use
Javas keywords for method names.

Here, ret-type specifies the type of data returned by the method.


This can be any valid type, including class types that you create. If
the method does not return a value, its return type must be void.
The name of the method is specified by name. This can be any legal
identifier other than those already used by other items within the
current scope. The parameter-list is a sequence of type and
identifier pairs separated by commas. Parameters are essentially
variables that receive the value of the arguments passed to the
method when it is called. If the method has no parameters, the
parameter list will be empty.
A method is always invoked relative to some object of its class.
Once this invocation has occurred, the object is known. Thus, within
a method, there is no need to specify the object a second time.
38.Return: This is a statement in the code. When this statement executes,
program control returns to the caller, skipping any remaining code in the
method.
39.Method name is verb based lowerCamelCase.
40.Argument: A value passed to a method is called an argument
41.Parameters: Inside the method, the variable that receives the argument is
called a parameter. These are the comma separated list of primitives. A
parameter is within the scope of its method, and aside from its special
task of receiving an argument, it acts like any other local variable. A
method can have more than one parameter.
42.State is the set of all attributes and their values
43.Behavior is the set of methods
44.For each file, there is one class, the name of a class is a noun and not a
verb and it follows the UpperCamel case.
45.Class generally has a main() method only if it is the entry point of the
program.
46.Garbage Collection: To recover free memory from unused objects, making
that memory available for subsequent reallocation, Java has a feature of
Garbage collection. When no references to an object exist, that object is
assumed to be no longer needed, and the memory occupied by the object
is released. This recycled memory can then be used for a subsequent
allocation.
47.Constructor is a block of command or is a special type of subroutine or a
type of method called to create an object. It prepares the new object for
use, often accepting arguments that the constructor uses to set required
member variables that calls the objects of a class. Java 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.
This is of two types
a. Default Constructor or No arg Constructor. If there is no constructor
in a class, compiler automatically creates a default constructor
while the program is being executed. Default constructor provides
the default values to the object like 0 for numeric primitives, null for
strings etc. depending on the type.
Example : <class_name>(){}
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
b. Parametrized constructor. It is a constructor that has a parameter. It is
used to
provide different values to the distinct objects.
Example : public Triangle(double base, double
height) {
this.base = base;
this.height = height;

48.Constructor Overloading: 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.
class Student5{
int id; String name; int age;
Student5(int i,String n){
id = i; name = n;
}
Student5(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[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
It displays 111 Karan 0 and 222 Aryan 25 in the output.

Java Constructor Java Method


Constructor is used to initialize the state of an Method is used to expose
object. 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 Method is not provided by
if you don't have any constructor. compiler in any case.
Constructor name must be same as the class Method name may or may
name. not be same as class name.
There are many ways to copy the values of one object into another in java.
They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class

49.get is a method to return an element of a class


Example : public double getBase() {
return base;}
50.set is a method to assign a value to an element of a class
Example : public double setBase(double b) {
base = b;}
51.scale is method to increase the elements of a class to some scaleFactor
times.
Example : public void scale(double scaleFactor){
base *= scaleFactor;}
52.toString() is a method that prints a string by returning its val. This method
is used when we need a string representation of an object. It is defined in
Object class. This method can be overridden to customize the String
representation of the Object.
Example : public String toString(){
String rval = + base + getArea();
return rval; }
53.this is a java keyword that is used to refer to the current object
Example : this.a = 5; is same as int a =5; it also can be shown as
public Test(int a){
this.a = a;
}
54.Array is the combination of similar items. There are two dimensional, three
dimensional arrays. arrays can have one or more dimensions, although
the one-dimensional array is the most common. Arrays are used for a
variety of purposes because they offer a convenient means of grouping
together related variables. For example, you might use an array to hold a
record of the daily high temperature for a month, a list of stock price
averages, or a list of your collection of programming books.
55.One-Dimensional Arrays: A one-dimensional array is a list of related
variables. Such lists are common in programming. For example, you might
use a one-dimensional array to store the account numbers of the active
users on a network. Another array might be used to store the current
batting averages for a baseball team. To declare a one-dimensional array,
you can use this general form:
type array-name[ ] = new type[size];
int sample[] = new int[10];
56.Length of an array: The length of an array, table[] is table.length.
Another way to represent it is, System.out.println("I like Java".length())
57.For-each For loop: Page 155.

58.String: String is an array of characters and in Java it is a class.


Constructing a String:
String str = new String("Hello");

There is a method equals() in Java, that compares the character


sequences of two String objects for equality. Applying the == to two String
references simply determines whether the two references refer to the
same object.
The contents of a String object are immutable. That is, once created, the
character sequence that makes up the string cannot be altered. This
restriction allows Java to implement strings more efficiently.
59.The bit-wise operators:

The Bitwise operators can be used on values of type long, int, short,
char, or byte. Bitwise operations cannot be used on boolean, float, or
double, or class types. They are called the bitwise operators because
they are used to test, set, or shift the individual bits that make up a value.
60.The shift operators:

61.The finalize( ) Method: It is possible to define a method that will be called


just before an objects final destruction by the garbage collector. This
method is called finalize( ), and it can be used to ensure that an object
terminates cleanly. For example, you might use finalize( ) to make sure
that an open file owned by that object is closed. To add a finalizer to a
class, you simply define the finalize( ) method. The Java run-time system
calls that method whenever it is about to recycle an object of that class.
Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed.

Here, the keyword protected is a specifier that limits access to finalize( ).


This and the other access specifier. It is important to understand that
finalize( ) is called just before garbage collection. It is not called when an
object goes out of scope, for example. This means that you cannot know
whenor even iffinalize( ) will be executed. For example, if your
program ends before garbage collection occurs, finalize( ) will not execute.
Therefore, it should be used as a backup procedure to ensure the proper
handling of some resource, or for special-use applications, not as the
means that your program uses in its normal operation. In short, finalize( )
is a specialized method that is seldom needed by most programs.
62. Inheritance : Inheritance in java is a mechanism in which one object
acquires all the properties and behaviors of parent object.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 parent class, and you can add new methods and fields also. Inheritance
represents the IS-A relationship, also known as parent-child relationship. It is
used for Method Overriding (so runtime polymorphism can be achieved) and for
Code Reusability.

63. Method overloading: If a class has multiple methods having same name but
different in 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. The first program yields 22, 33 and the second
program yields 22, 24.9.

Method overriding: If subclass (child class) has the same method as declared in
the parent class, it is known as method overriding in java.In other words, If
subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as 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.
In this case, method name must be same as in the parent class. Method must
have same parameters as in the parent class. Must be IS-A
relationship(Inheritance). when a method in a subclass has the same return type
and signature as a method in its superclass, then the method in the subclass is
said to override the method in the superclass. When an overridden method is
called from within a subclass, it will always refer to the version of that method
defined by the subclass.

64. Super() can be used to call the super class constructor from the sub class. super
can be used to call the methods or instance variables of a super class from a sub
class.
65. Polymorphism: Polymorphism in java is a concept by which we can
perform a single action by different ways. Polymorphism is derived from 2 greek
words: poly and morphs. The word "poly" means many and "morphs" means
forms. So polymorphism means many forms. There are two types of
polymorphism in java: compile time polymorphism and runtime polymorphism.
We can perform polymorphism in java by method overloading and method
overriding. If you overload static method in java, it is the example of compile
time polymorphism. Here, we will focus on runtime polymorphism in java.
66. Abstract class: A class that is declared with abstract keyword, is known as
abstract class in java. It can have abstract and non-abstract methods (method
with body). Before learning java abstract class, let's understand the abstraction in
java first. Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
67. Final: Keyword final prevents a method from overridden. It also prevents a class
from being inherited by preceding its declaration with final. Similarly if a variable
of a class preceded by final then its value cannot be changed throughout the life
time of the program.
Ex : final void meth(); final class A;

68. Object class:


It returns true if the objects are equivalent, and false otherwise. The toString( )
method returns a string that contains a description of the object on which it is
called. Also, this method is automatically called when an object is output using
println( ). Many classes override this method. Doing so allows them to tailor a
description specifically for the types of objects that they create. One last point:
Notice the unusual syntax in the return type for getClass( ). This relates to Javas
generics feature. Generics allow the type of data used by a class or method to be
specified as a parameter.
69. Package: All classes in Java belong to some package. When no package
statement is specified, the default (global) package is used. Furthermore, the
default package has no name, which makes the default package transparent. This
is why you havent had to worry about packages before now. While the default
package is fine for short, sample programs, it is inadequate for real applications.
Most of the time, you will define one or more packages for your code. To create a
package, put a package command at the top of a Java source file. The classes
declared within that file will then belong to the specified package. Since a
package defines a namespace, the names of the classes that you put into the file
become part of that packages namespace. This is the general form of the
package statement:
package pkg; where pkg is the name of the package. This statement should be
on the top of the .jave file of any class. If we run on the command line with the
syntax javac -d . MinMaxDemo.java for the MinMaxDemo class file where the
package package Demo is coded, a Demo file automatically created in the
workspace.
Package is a way to organize files in java, it is used when a project consists of multiple
modules. It also helps resolve naming conflicts. Package's access level also allows you
to protect data from being used by the non-authorized classes.

70. Importing Packages: Using import you can bring one or more members of a
package into view. This allows you to use those members directly, without explicit
package qualification.
Here is the general form of the import statement:
import pkg.classname; Here, pkg is the name of the package, which can include
its full path, and classname is the name of the class being imported. If you want
to import the entire contents of a package, use an asterisk (*) for the class
name. Here are examples of both forms:
import mypack.MyClass import mypack.*;

In the first case, the MyClass class is imported from mypack. In the second, all of
the classes in mypack are imported. In a Java source file, import statements
occur immediately following the package statement (if it exists) and before any
class definitions.

import keyword is used to import built-in and user-defined packages into your java
source file. So that your class can refer to a class that is in another package by directly
using its name.
There are 3 different ways to refer to class that is present in different package
71. Interface: An interface in Java is a blue print of a class. It has static constants
and abstract methods.The interface in java is a mechanism to achieve
abstraction. There can be only abstract methods in the java interface not
method body. It is used to achieve abstraction and multiple inheritance in
Java.Java Interface also represents IS-A relationship. It cannot be
instantiated just like abstract class.

There are mainly three reasons to use interface. They are given below. It is used
to achieve abstraction. By interface, we can support the functionality of multiple
inheritance. It can be used to achieve loose coupling. Interface fields are public,
static and final by default, and methods are public and abstract.

Variables can be declared in an interface but they are implicitly public, static, and
final.
72. Exception: Exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime. This is of three types, checked
exception, unchecked exception(Runtime exception), error.
73. Exception Handling: The exception handling in java is one of the
powerful mechanism to handle the runtime errors so that normal flow of the
application can be maintained.
74. Exception Handling Hierarchy:

75. Checked exception: The classes that extend Throwable class except
RuntimeException and Error are known as checked exceptions e.g.IOException,
SQLException etc. Checked exceptions are checked at compile-time. These
exceptions cannot simply be ignored at the time of compilation, the
programmer should take care of (handle) these exceptions.

76. 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. Runtime exceptions are
ignored at the time of compilation.

77. Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


AssertionError etc.
Examples : 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
The wrong formatting of any value, may occur NumberFormatException. Suppose
I have a string variable that have characters, converting this variable into digit
will occur NumberFormatException.
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException. 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.

78. Java exception Handling key words: try, catch, throw, throws, finally.

Try block: Java try block is used to enclose the code that might throw an
exception. It must be used within the method.Java try block must be followed by
either catch or finally block.

Try catch block. Try finally block.

a. At a time only one exception is occurred and at a time only one catch
block is excuted.
b. All catch blocks must be ordered from most specific to most general. Like
catch for ArithmeticException must come before the catch Exception.
Finally block: Finally block in java can be used to put "cleanup" code such as
closing a file, closing connection etc.

Throw: This keyword is used to throw an exception explicitly. We can throw


either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception.

throw exception; and ex: throw new IOException("sorry device error);

Throws: This 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.

79. Difference between final, finalize, finally


80.

S-ar putea să vă placă și