Sunteți pe pagina 1din 26

Document Prepared By Shreenath Waramballi

INTRODUCTION TO CORE JAVA

Java technology is both a programming language and a platform. The Java programming
language is a high-level language. In the Java programming language, all source code is first
written in plain text files ending with the .java extension. Those source files are then
compiled into .class files by the javac compiler. A .class file does not contain code that is
native to your processor; it instead contains bytecodes the machine language of the Java
Virtual Machine (Java VM). The java launcher tool then runs your application with an
instance of the Java Virtual Machine.
There are mainly 4 type of applications that can be created using java:-
1)Standalone Application/Desktop Application
2) Web Application
3) Enterprise Application
4) Mobile Application
1) Standalone Application/Desktop Application :-It is also known as desktop application
or window-based application. An application that we need to install on every machine such as
media player, antivirus etc. AWT and Swing are used in java for creating standalone
applications.
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.

Features Of Java
There is given many features of java. They are also known as java buzzwords.
1.Object Oriented:-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:-
i)Object
ii)Class
iii)Inheritance
iv)Polymorphism
v)Abstraction
vi)Encapsulation
2.Platform independent:-Java runs on a variety of platforms, such as Windows, Mac OS,
and the various versions of UNIX.
3.Simple:-Java was designed to be easy for the professional programmer to learn and use
effectively. If you already understand the basic concepts of object-oriented programming,
learning Java will be even easier.Best of all, if you are an experienced C++ programmer,
Document Prepared By Shreenath Waramballi

moving to Java will require very little effort. Because Java inherits the C/C++ syntax and
many of the object-oriented features of C++, most programmers have little trouble learning
Java.
4.Secured:-Java is secured because:i) No explicit pointerii) Programs run inside virtual
machine sandbox.
5.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.
6. Architectural-neutral:-There is no implementation dependent features
e.g. size of primitive types is set.
7.Portable:-We may carry the java bytecode to any platform.
8.Dyanamic:-Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at run time. This makes it
possible to dynamically link code in a safe and expedient manner. This is crucial to the
robustness of the Java environment, in which small fragments of bytecode may be
dynamically updated on a running system
.9.Interpreted:- As described earlier, Java enables the creation of cross-platform programs
by compiling into an intermediate representation called Java bytecode. This code can be
executed on any system that implements the Java Virtual Machine. Most previous attempts at
cross-platform solutions have done so at the expense of performance.
10.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++)
11.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.
12.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.
==================================================================
The following keywords are reserved in Java:- Reserved words or Keywords are words that
have a specific meaning to the compiler and can not be used for other purposes..
Document Prepared By Shreenath Waramballi

Data Types Memory Size Minimum and Maximum Values


Byte 1 byte -128 to +127
Short 2 bytes -32768 to + 32767
Int 4 bytes -2147483648 to + 2147483647
Long 8 bytes -9223372036854775808 to +9223372036854775807

Float 4 bytes -3.4e38 to -.4e-45 for negative values and 1.4e-45 to 3.4e+038 for
positive values.

Double 8 bytes -1.8e08 to -4.9e-324 for negative values and 4.9e-324 to 1.8e+308
for positive values.
Char 2 bytes 0 to 65535
Boolean true or false

Java Simple Program


public class Demo
{
//Start of Main Method
public static void main(string args[])
{
System.out.println(" Simple demo program");

} //End of Main Method

} //End of Demo Class


Java Operators
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables. Java
supports a rich set of operators.
1.Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Assignment Operators
5.Increment and Decrement Operators 6.Conditional Operators 7. Bitwise Operators 8.
Special Operators
1.Arithmetic Operators:- Different arithmetic operators supported by java language are
listed below:-
Symbol Used Operation Performed
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Document Prepared By Shreenath Waramballi

2.Relational Operators:- These operators are used to compare the values of the operands
that must be compitable, in order to facilitate decision-making. Java supports 6 relational
operators are:-
Symbol Used Operation Performed
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not Equal to
3. Logical Operators:- Java has the following three logical operators.
Symbol Used Operation Performed
! Logical NOT
&& Logical AND
|| Logical OR

The logical operators && and || are used when we want to test more than one condition and
make decisions. Ex:-i)if(a>b && x==10) ii) if(age>55 && salary<2000)
4.Assignment Operator:- Assignment operators are used to assign the result of an
expression to a variable. Assignment Operator:- '=' Ex:- c = a+b.
5. Increment / Decrement Operator:- Java supports two very useful operators increment
(++) and decrement operator (--), these are not generally found in other languages. The
increment operator adds 1 from the operand, while decrement operator subtracts 1 from the
operand. Both are unary operators and takes the following form:- ++m (pre
incrementation) or m++ (post incrementation) --m (pre decrementation) or m--
(post decrementation)
6.Conditional Operator (?:) :- A ternary operator pair "?:" is available in the java to
construct conditional expression of the form Exp1 ? Exp2 : Exp3 This the only operator
that take 3 operands Result = Testing Expression : Exp1 : Exp2 If Testing Expression is True
perform expression 1 and assign to result. If Testing Expression is False perform expression 2
and assign to resut
7. Bitwise Operator:-These operator are used for testing the bits or for shifting them right or
left. Bitwise operators may not be appiled to float or double.
Different bitwise operators supported by Java Language are listed below are:-
Symbol Used Operation Performed
>> Shift-right
<< Shift-left
>>> Shift-right with zero fill
- One's complement
& Bitwise AND
Document Prepared By Shreenath Waramballi

! Bitwise OR
^ Bitwise Exclusive OR

8. Special Operator:- Java supports some special operators such as instanceof operator, Dot
operator.
Instanceof: This operator is used only for the obect refernce variables. The operator checks
wether the object is of a pirticular type (class type or interface type). instanceof operator is
written as: (Object reference variable) instanceof (class/ interface type)

Control Flow Statement


The statements inside your source files are generally executed from top to bottom, in the
order that they appear. Control flow statements, however, break up the flow of execution by
employing decision making, looping, and branching, enabling your program to conditionally
execute particular blocks of code. This section describes the decision-making statements (if,
if...else, switch), the looping statements (for, while, do-while), and the branching statements
(break, continue, return) supported by the Java programming language.
1) Decision-making statements:- i) if statement ii) if....else statement iii) Nested if....else
statement iv) else if ladder
i) if statement:- The general form of a simple "if" statement is Syntax:-
if( expression)
{
Statement(s);
}
ii) if....else statement:- The "if....else" statement is an extention of simple "if" statement. The
Syntax:-
if(expression)
{
True-statement;
}

else
{
False-statement;
}
iii) Nested if....else statement:- Series of decisions are involved, we may have to use more
than one "if....else" statement in nested if else as follows:-
Syntax:-
if(condition1)
{
if(condition2)
{
Statement1;
}
else
Document Prepared By Shreenath Waramballi

{
block2;
}
}
else
{
block3;
}
iv)else if ladder statement:- Series of multiple decisions are involved.
Syntax:-
if(condition1)
Statement-1
{
else if(condition2)
{
Statement-2;
}
else if(condition3)
{
Statement-3;
}
}
else if(condition n)
{
Statement n;
}
else
Default Statement block
=================================================================
Control Flow Statement
2.Looping Statements:-
i) for loop
ii) while loop
iii) do .. while loop
i) for loop or statement:- The for statement provides a compact way to iterate over a range
of values. Programmers often refer to it as the "for loop" because of the way in which it
repeatedly loops until a particular condition is satisfied. The general form of the for statement
can be expressed as follows:

Syntax:-
for (initialization; termination; increment/decrement)
{
statements block;
}
Document Prepared By Shreenath Waramballi

ii) while loop:- The while statement continually executes a block of statements while a
particular condition is true. Its syntax can be expressed as:
Syntax:-
while (expression)
{
statement block;
}
iii) do .. while loop:-

Syntax:-
do {
statement block;
}while (expression);
Object-Oriented Programming Concepts
=================================================================
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:-
i) Object
ii) Class
iii) Inheritance
iv) Interface
v) Polymorphism
vi) Abstraction
vii) Encapsulation
i) Object:- An object is a software bundle of related state and behaviour. 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
ii)Class:- Collection of objects is called class. It is a logical entity. In the real world, you'll
often find many individual objects all of the same kind. There may be thousands of other
bicycles in existence, all of the same make and model. Each bicycle was built from the same
set of blueprints and therefore contains the same components. In object-oriented terms, we
say that your bicycle is an instance of the class of objects known as bicycles. A class is the
blueprint from which individual objects are created.
iii)Inheritance:- Different kinds of objects often have a certain amount in common with each
other.Object-oriented programming allows classes to inherit commonly used state and
behavior from other classes.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.
iv)Interface:- 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.
Document Prepared By Shreenath Waramballi

v)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.
vi)Abstraction:- Abstraction refers to the act of representing essential features without
including background details or exceptions. Abstraction refers to the ability to make a class
abstract in Object oriented programming.
vii)Encapsulation:- The wrapping up of data and methods into a single unit (called class) is
known as Encapsulation. Encapsulation is one of the four fundamental OOP concepts. The
other three are inheritance, polymorphism, and abstraction.
Java Classes and Objects
Java is a true object-oriented language and therefore the underlying structure of all java
programs is classes. Anything we wise to represent in a java program must be encapsulated in
a class that defines the state and behaviour of the basic program components known as
objects. An object is anything that really exists in the world and can be distingushed from
others. Every thing that we see physically will come into this definition, for example:- human
being, a book, tree, a table, a pen, and so on.Collection of objects is called class. It is a logical
entity.
Syntax for class:-
[Access Specifier/Modifier-List] class < class name> [extends SuperClass] [implements
Interface-List]
Syntax for object:-classname reference_variable = new classname([parameter-list]);
Java Access Specifiers
Access specifier defines the boundary and scope to access the method, variable, and class etc.
Java has defines four type of access specifiers such as:-
1. public
2. private
3. protected
4. default
These access specifiers are defines the scope for variables/methods. If you are not defining
any access specifier so it will be as 'default' access specifier for variables/methods.
1. public access specifier:- If we declare any variable/ function as public access specifier so
you can used it from anywhere of the program.
Syntax:-
< Access Specifier > data type variable /function ;
Ex:-
public int number;
2. private access specifier:- If you declare any variable/ function as private access specifier
so you can used within the java class itself, not from outside the class, package and others.
Syntax:-
< Access Specifier > data type variable / function;
Ex:-
private int number=10;
3. protected access specifier:- If you want to access the private variable of parent class
Document Prepared By Shreenath Waramballi

within your child class so you can declare those variable as protected. If your
variable/method is declared as protected so that variables/methods can be access same Class
name, Package name, and sub class.
Syntax:-
< Access Specifier > data type variable / function;
Ex:-
protected int number=10;
4. default access specifier:- Actually, there is no default access modifier; the absence of a
modifier is treated as default. A method or variable, declared default( that is, no access
modifier specified at all ), can be accessed by any class belonging to the same package.
Classes belonging to other packages cannot access. That is why default access modifier is
known as package level access. A class can be either default or public.
==================================================================
Java Method Overloading-An overloaded method is more than one method: it is two or
more separate methods using the same method name( of course, with different parameters ).
Methods are defined in classes. Methods are distinguished by the compiler by their method
signatures. A method signature includes method name, number of parameters and their type.
But in procedural languages like in C, method overloading is not permitted.

Method overloading allows to group methods of same functionality under one name. Always
the name of the method should reflect its functionality( that is, what is it going to give us). In
method overloading, compiler does not consider return type in differentiating the methods.
//Start Of MethodOverLoading Class
public class MethodOverLoading
{
public void add(int i, int j)
{
int k = i+j;
System.out.println("Addition is :" +k);

}
public void add(String s, String t)
{
int k = Integer.parseInt(s) + Integer.parseInt(t);
System.out.println("Addition is :" +k);

}
}
class Test
{
public static void main(String args[])
{
MethodOverLoading ob = new MethodOverLoading();
ob.add(10,30);

ob.add("20", "40");
} }
Document Prepared By Shreenath Waramballi

Java Method Overriding:If the method signatures of a method in superclass and subclass
are same, we say superclass method is overridden in subclass. In method overriding the return
type also must be same of that of superclass. The subclass method must have the same name,
parameter list and return type as the superclass method. That is, by using the same method
name of the superclass, the subclass gives different output.When you extend a class and write
a method in the derived class which is exactly similiar to the one present in the base class, it
is termed as overriding.
Example:-
public class BaseClass
{
public void MethodOveriding()
{
System.out.println("Base Class Method");

}
}
public class DerivedClass extends BaseClass
{
//Start of MethodOverriding()
public void MethodOverriding()
{
System.out.println("Derived Class Method");

}
}
class Test
{
public static void main(String args[])
{
//Create DerivedClass object
DerivedClass obj = new DerivedClass();
obj.MethodOverriding();

}
}
Java Constructors
A constructor is a special member method which will be called by the JVM
implicitly(automatically) for placing user/programmer defined values instead of placing
default values.Constructors are meant for initializing the object. Constructor is a special type
of method that is used to initialize the state of an object. Constructor is invoked at the time of
object creation. It constructs the values i.e. data for the object that is why it is known as
constructor.Constructor is just like the instance method but it does not have any explicit
return type. Advantages of Constructors:
1. A constructor eliminates placing the default values.
Document Prepared By Shreenath Waramballi

2. A constructor eliminates callling the normal method implicitly.


RULES/CHARACTERISTICS of a Constructor:
1. Constructor name must be same as its class name.
2. Constructor should not return any value even void also.
3. Costructors should not be static .
4. Constructors should not be private.
5. Constructors will not be inherited at all.
6. Constructors are called automatically whenever an object is cereating.
Types of Constructors:
There are two types of constructors:-
1. Default constructor (no-argument constructor)
2. Parameterized constructor
1.Default constructor (no-argument constructor):- A constructor is one which will not
take any parameter.A constructor that have no parameter is known as default constructor.
Syntax:-
class < class name >
{
classname() //default constructor
{
Block of statements;
...................;
...................;
}
..................;
..................;
};
Example:-

//Start Of TestConstructor
class Test
{
int a, b;
Test ()
{
System.out.println(" Default Constructor !!!");
a = 10;
b = 20;
System.out.println("Value of a = " +a);
System.out.println("Value of b = " +b);
}
}
class Demo
{
public static void main(String args[])
Document Prepared By Shreenath Waramballi

{
Test ob= new Test ();

}
}

2.Parameterized Constructor:- A constructor is one which takes some parameters.

Syntax:-
class < class name >
{
classname(list of parameters) //paramiterized constructor
{
Block of statements;
...................;
...................;
}
..................;
..................;
}

Example:-

//Start Of TestConstructor
class Test
{
int a, b;
Test (int x, int y)
{
System.out.println(" Parameterized Constructor !!!");
a = x;
b = y;
System.out.println("Value of a = " +a);
System.out.println("Value of b = " +b);
}
};
class Demo
{
public static void main(String args[])
{
Test ob = new Test (10,20);

}
Document Prepared By Shreenath Waramballi

Super Keyword
super keyword gives explicit access to the constructors, methods and variables of its super
class. The super keyword works with inheritance. Inheritance gives implicit access to
subclass to call its superclass members. But implicit access is blocked by method overriding
or by declaring the same instance variables in subclass what superclass is having. Here, super
keyword is used. That is super keyword gives explicit access to immediate superclass parts,
even if access is blocked.
Usage of super with variables:In the following program, the instance variable x is blocked
by the subclass variable. Here super is used to print the superclass variable.
Example:-

class A
{
int x = 10 ;
}

public class B extends A


{
int x = 20 ;

public void display( )


{
System.out.println( x ) ; // prints 20
System.out.println( super.x ) ; // prints 10
System.out.println( x + super.x) ; // prints 30
}

public static void main(String args[ ] )


{
B b new B( ) ;
b.display( ) ;

}
}
Usage of super with methods:
In the following program, the display method is blocked by the subclass overridden method.
Here super is used to call the super class method.
class A
{
public void display( )
{
Document Prepared By Shreenath Waramballi

System.out.println( "Hello1" ) ;
}
}

public class B extends A


{
public void display( )
{
System.out.println( "Hello2 " ) ;
}

public void show( )


{
display( ) ; // Hello2 is printed
super.display( ) ; // Hello1 is printed
}

public static void main(String args[ ] )


{
B b new B( ) ;
b.show( );
}
}
Usage of super with constructors - super( ) :super keyword should be called in a different
way with constructors, because constructors are not inherited but accessed. To access the
superclass constructor from a subclass constructor we use super( ). JVM distinguishes which
superclass consturctor is to be called by matching the parameters we pass with super( ).

class A
{
A( )
{
System.out.println( " Default A" ) ;

A( int x )
{
System.out.println( x ) ;

}
class B extends A
{
B( )
{
System.out.println( "Default B" ) ;

B( int x )
Document Prepared By Shreenath Waramballi

{
super( 10 ) ; // calls superclass A( int x ) constructor

System.out.println( x ) ;

public static void main(String args[ ] )


{
B b = new B( 5 ) ;

}
} // output is 10 and 5
final Keyword
final is a keyword in Java which generically means, cannot be changed once created. Any
final keyword when declared with variables, methods and classes specifically means: a final
variable cannot be reassigned once initialized. a final method cannot be overridden. a final
class cannot be sub classed. Classes are usually declared final for either performance or
security reasons. final methods work like inline code of C++.
final with variables: final variables work like const of C-language that can't be altered in the
whole program. That is, final variables once created can't be changed and they must be used
as it is by all the program.
Example:-
public static void main( String args[ ] )
{
int x = 10;
final int y = 20 ;
x = 100 ; // not an error as x is not final
y = 200 ; // error because y is final
}
final with methods:Generally, a superclass method can be overriden by the subclass if it
wants a different functionality. Or, it can use the same method if it wants the same
functionality( output ). If the superclass desires that the subclass shoud not override its
method by the subclass, it declares the method as final. That is mehods declared final can not
be overridden( else it is a compilation error )
Example:-
class A
{
final void display( )
{
System.out.println( "Barik" ) ;

}
}
class B extends A
Document Prepared By Shreenath Waramballi

{
void display( )
{
System.out.println( " Tarun" ) ;

} // raises an error

} // as display( ) is declared as final in the superclass


final with classes: If we want the class not be subclassed by any other class, declare it final.
Classes declared final can not be extended.
Example:-
final class A
{
}
class B extends A
{
} // error because class A is declared final

this Keyword
'this' is a keyword that refers to the object of the class where it is used. In other
words, 'this' refers to the object of the present class. When an object is created to a class, a
default reference is also created internally to the object. This default reference is nothing but
'this'.

Example:-

class Student
{
int id;
String name;
student(int id, String name)
{
this.id = id;
this.name = name;
}
Document Prepared By Shreenath Waramballi

void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{

Student stud1 = new Student(01,"Sachin ");


Student stud2 = new Student(02,"Varun");
stud1.display();
stud2.display();
}
}
Output:-
01 Sachin
02 Varun
=================================================================
Interface
Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body. Using the keyword interface, you can fully abstract a
class, interface from its implementation. That is, using interface, you can specify what a
class must do, but not how it does it. Once interface is defined, any number of classes can
implement it. Also, one class can implement any number of interfaces. Interfaces are
designed to support dynamic method resolution at run time.
Example of interface:-
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("Hello Interface!!!");
}
public static void main(String args[])
{
B ob= new A();
ob.display();
}
}
Output:- Hello Interface!!!
What are Abstract Classes?
An abstract class is like a class but it will have abstract methods and concrete methods.
Abstract methods don’t have an implementation. It will only have the method declaration.
Rules to be followed for Abstract Class
1.The abstract class cannot be instantiated.
Document Prepared By Shreenath Waramballi

2.Child class which extends the abstract class should implement all the abstract methods of
the parent class or the Child class should be declared as an abstract class.
public abstract class EmployeeDetails
{
private String name;
private int emp_ID;
public void commonEmpDetaills()
{
System.out.println("Name"+name);
System.out.println("emp_ID"+emp_ID);
}
public abstract void confidentialDetails(int s,String p);
}
public class HR extends EmployeeDetails {
private int salary;
private String performance;
public void confidentialDetails(int s,String p) {
this.salary=s;
this.performance=p;
System.out.println("salary=="+salary);
System.out.println("performance=="+performance);
}
public static void main(String[] args) {
HR hr =new HR();
hr.confidentialDetails(5000,"good");
}
}

=================================================================
Arrays: Array is a collection of similar type of elements that have contigious memory
location.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.
Document Prepared By Shreenath Waramballi

Creation of arrays:Arrays are data structures that can store large amount of information of
the same data type grouped together and known by a common name. Each member is called
an element of the array.Arrays are capable of storing primitive data types as well as objects.
The elements of the array can be accessed by its index value that starts from 0. Once array is
declared, its size cannot be altered dynamically. Arrays can be :- a) declared and later
assigned or b) initialized.

int subject[ ] = new int[ 10 ] ; // declaration of an array


// if not assigned, default 0 is assigned for int element
System.out.println( subject[ 1 ] ) ;
// assigning a value to an element
subject[ 1 ] = 45 ;
System.out.println( subject[ 1 ] ) ; // now, prints 45
Example:-Single Dimensional Array
class Demo
{
public static void main(String args[])
{
int a []=new int[6];
a [0]=100;
a [1]=200;
a [2]=300;
a [3]=400;
a [4]=500;
a [5]=600;
for(int i=0;i< a.length;i++)
System.out.println(a[i]);
}

}
Output:-
100
200
300
400
500
600
Document Prepared By Shreenath Waramballi

Example:-Multidimensional Array

//Start of MultiArray class


class MultiArray
{
//Start of Main Method
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i< 3;i++)
{
for(int j=0;j< 3;j++)
{
//printing 2D array
System.out.print(arr[i][j]+" ");

}//End of inner for loop


System.out.println();

}
}
Output:-
123
245
445

Strings
A sequence of character data enclosed in double quotes is called a string. Strings of Java
work differently from that of C and C + +. In C, string is an array of characters with a
terminating \ 0. But in Java, string is an object of String class. That is manipulation of strings
is quite different from C and in Java, it is very easy due the rich methods of String class. For
example, we can concatenate strings with + operator. Java platform provides two string
classes to manipulate strings String, for constant strings and StringBuffer, for strings that can
change. Strings are immutable. That is, strings once created cannot be changed at the same
memory location. Whenever a new value is assigned to a string, a new memory location is
created and the new value is stored in it and the old location( with old value ) is garbage
collected. It is definitely a overhead to the operating system. But this is made to increase the
performance and for the same reason String class is declared as final. The following the class
signature of String class defined in java.lang package:
public final class String extends Object implements Serializable, Comparable
Document Prepared By Shreenath Waramballi

To overcome the OS overhead( due to immutable nature of strings), we can use StringBuffer
class. Some methods of String class:
1.valueOf( parameter ):valueOf() method is static and is overloaded many times in String
class. It's job is to convert any primitive data type or object, passed as parameter, into a string
form. Its function similar to toString() method of Object class. But toString() method
converts only objects into string form.
Example:- converting a data type into string:
int x = 10 ;
String str = String.valueOf( x ) ;

System.out.println( str ) ; // prints 10


2. length( ) :length( ) is an instance method in String class which returns an int value. It must
be called with an instance of String class and returns the number of characters present in the
string instance.
String str1 = " Hello " ;
String str2 = new String( " Student " ) ; // We can create strings in either way
System.out.println( str1.length( ) ); // prints 5 length of string
System.out.println( str2.length( ) ) ; // prints 7 length of string
3.equals( ):equals( ) method is inherited from Object class and is overridden in String class.
It returns a boolean value of true if the strings are same or false, if the strings are different. In
the comparison, case( upper or lower) of the letters is considered.
String str1 = "Sachin" ;
String str2 = "sachin" ;
System.out.println( str1.equals( str2 ) ) ;
The above println statement prints false because case of letters is different. This can
overcome with equalsIgnoreCase( ) method which does not consider case of the letters into
account in comparison. The following statement illustrates: System.out.println(
str1.equalsIgnoreCase( str2 ) ) ; //prints true
4.toLowerCase( ) and toUpperCase( ) : toLowerCase( ) is an instance method and converts
all uppercase letters of the string into lowercase. toUpperCase( ) does in the reverse way.
String str1 = " Sachin " ;
String str2 = "sachin" ;
System.out.println( str1.toLowerCase( ) ) ; // prints sachin
System.out.println( str2.toUpperCase( ) ) ; // prints SACHIN
Java - Exceptions
An exception is an event that occurs during the execution(or run time) of a program that
disrupts(stop) the normal flow of control. If an exception is raised( at run time ), the program
terminates by displaying the cause of exception. If we handle the exception properly, the
program flow will be normal and continues further. This facility is not available in C
language. All exceptions can be broadly divided into two categories:-
1. Checked exceptions
2. Unchecked exceptions.
Document Prepared By Shreenath Waramballi

Unchecked exceptions:-All the subclasses of RuntimeException are called unchecked


exceptions. Some examples are ArithmeticException andArrayIndexOutOfBoundsException.
These exceptions are called unchecked for the reason, even if the programmer does not
provide any try - catch mechanism, the program compiles. System checks them at runtime
and if an exception occurs program terminates. If a try - catch block is provided for these
exceptions, program execution continues further when exception really occurs.
Checked exceptions:- All the subclasses of Exception class except RuntimeException are
called checked exceptions. For these exceptions, programmer should provide a try - catch
block whether really exception raises or not, else program does not compile.
Generally, these exceptions are written in the method signature itself with throws clause.
Following are the examples from Java API:
public FileInputStream( String filename ) throws FileNotFoundException
public void sleep( int milliseconds ) throws InterruptedException
In the above statements, FileNotFoundException and InterruptedException are checked
exceptions. That is, when FileInputStream( String filename ) constructor is used by the
programmer, he should write a try - catch mechanism for FileNotFoundException whether
the file passed as parameter really exists in the hard disk or not..
public class Demo
{
public static void main(String args[ ] )
{
int a = 5, b = 0, c ;

try
{
c=a/b;
System.out.println( c ) ;

}
catch( ArithmeticException e )
{
System.out.println( "Don't divide by zero sir " + e ) ;
}
finally
{
System.out.println( "Guaranteed execution " ) ;
}
}
}
try :try is a keyword in Java that defines a block of statements. First, we must identify the
statements, in a program, that may raise the exception. Then place those statements in the try
block.That is, the statements that are placed in the try block, may cause( throw ) the
exception. If exception is not raised, the system simply ignores the try block.
catch:catch is a keyword in Java and denotes a block of statements. Every try block should
be followed by a catch block. The exception thrown by the try block is caught( or handled )
by the catch block.We must provide a suitable exception class that can handle( or catch) the
Document Prepared By Shreenath Waramballi

exception thrown by the try block. That is, catch block contains the exception handler.
When an exception handler present in the catch block successfully catches the exception, the
program execution goes in a normal way and continues further.
One program can contain any number of try - catch blocks. A try block can have any number
of catch blocks.
finally:finally is a keyword in Java and denotes a block of statements. The statements placed
in the finally block are definitely executed whether catch block successfully catches the
exception or not. Generally, we write clean up statements in this block, like closing of
streams or closing of sockets etc. finally block is optional.
==================================================================
Java - Multithreading
A thread is actually a lightweight process.Unlike many other computer languages, Java
provides built-in support for multithreaded programming. A multithreaded program contains
two or more parts that can run concurrently. Each part of such a program is called thread and
each thread defines a separate path of execution. Thus, multithreading is a specialized form of
multitasking.
Thread Class and Runnable Interface:Java’s multithreading system is built upon the
Thread class, its methods, and its companion interface, Runnable. To create a new thread,
your program will either extend Thread or implement the Runnable interface. The Thread
class defines several methods that help manage threads.The table below displays the same.

Method Meaning
getName Obtain thread’s name
getPriority Obtain thread’s priority
isAlive Determine if a thread is still running
join Wait for a thread to terminate
run Entry point for the thread
sleep Suspend a thread for a period of time
start Start a thread by calling its run method

Creating a Java Thread-Java lets you create thread in following two ways:-
1.By implementing the Runnable interface. 2.By extending the Thread
Runnable Interface:The easiest way to create a thread is to create a class that implements
the Runnable interface.To implement Runnable interface, a class need only implement a
single method called run( ), which is declared like this: public void run().Inside run( ), we
will define the code that constitutes the new thread.
class Test implements Runnable
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Test m1=new Test ();
Document Prepared By Shreenath Waramballi

Thread t1 =new Thread(m1);


t1.start();
}
}

When the thread is started it will call the run() method of the Test instance .
Extending Java Thread
The second way to create a thread is to create a new class that extends Thread, then override
the run() method and then to create an instance of that class. The run() method is what is
executed by the thread after you call start(). Here is an example of creating a Java Thread
subclass.
class Test extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Test t1=new Test();
t1.start();
}
}

What is Exception in Java


In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.when any exception is raised an exception object is getting
created.
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc
Checked Exceptions:Checked Exceptions are exceptional scenarios that we can anticipate in
a program and try to recover from it, for example FileNotFoundException.
Runtime Exception: Runtime Exceptions are cause by bad programming, for example trying
to retrieve an element from the Array. We should check the length of array first before trying
to retrieve the element otherwise it might throw ArrayIndexOutOfBoundExceptionat
runtime..

Keyword Description

try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we can't
use try block alone.
Document Prepared By Shreenath Waramballi

catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.

finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception.
It specifies that there may occur an exception in the method. It is always used with
method signature.

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.
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. The catch block must be used after the try block only. We can use
multiple catch block with a single try block.
public class Test {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Java finally block: Java finally block is a block that is used to execute important code such
as closing connection, stream etc. Java finally block is always executed whether exception is
handled or not.

class Test{
Document Prepared By Shreenath Waramballi

public static void main(String args[]){


try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Java throw and throws example
void m() {
throw new ArithmeticException("New Exceptiom");
}
void m()throws ArithmeticException
{
//method code
}
================================================================

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