Java Notes
Java Notes
}
show()
{
print(a);
}
A class contains three variable declaration
INSTANCE VARIABLE:
The instance variable is declared outside the method.
STATIC VARIABLE:
Only one copy of the memory is created for all the object.
LOCAL VARIABLE:
This variable in declared in the method, and method parameters also is called the local variable.
=========================================================================
A class is keyword that is used to declare a class, and classname is the name given to the class.
After defining a class, you need to save the file before it can be executed. The following naming
conventions should be followed for naming a java file.
A file name should be unique.
A file name cannot be a keyword.
If a class is specified as public, the file name and class name should be the same.
If a file contains multiple classes, only one class can be declared as public. the file name should be the
same as the class name that is declared public in the file.
If a file contains mulltiple classes that are not declard public, any file name can be specified for the
file.
In java class names are case-sensitive. For example , vehicle is not the same as Vehicle.
==============================================================================
DATA TYPES:
While working with an application, you need to store and manipulate varying data. Java supports various
data types. There are eight primitive data types in java.
INTEGER TYPE:
byte
short
int
long
Data type Size Range Default value
byte 1 byte -27 to 27-1 0
short 2 bytes -215 to 215-1 0
int 4 bytes -231 to 231-1 0
long 8 bytes -263 to 263-1 0
Floating point type:
float 4 bytes 3.4e-038 to 3.4 e+038 0.0
double 8 bytes 1.7e-308 to 1.7e+308 0.0
Boolean Type:
Can store only the values, true and false.
Character type:
Can store a single character, such as a symbol, letter and number. A character data type 2 bytes of memory
is allocated.
To store a string values, you need to use built in clasess such string, stringbuilder and stringbuffer.
===========================================================================
WRAPPER CLASSES:
Variables that are declared by using the primitive data types are not objects. The primitive data types,
such as int and char are not a apart of the object hierarchy.
Therefore in order to use the primitive data types as objects, java provides wrapper classes.
The wrapper classes are
Integer
Boolean
Character
Short
Long
Double
Float
======================================================================
CLASS MEMBERS:
1.variables
2.methods
3. object
4. inner classes
1. Variables:
A variables is used essentially as a container for the storage of varying kinds of data.
<type> <variable-name>;
example:
int choice;
public class punitha22
{
public static void main(String args[])
{
int a,b;
a=b=20;
//System.out.println("The value of a is"+a);
//System.out.println("The value of b is"+b);
System.out.println(a+" "+b);
}
}
LITERALS:
A literals contains a sequence of characters, such as digits alphabets or any other symbol.
Integer litrals
Floating point litrals
Character litrals
Boolean litrals
package scannerdemo;
import java.util.*;
public class scannerdemo {
public static void main(String args[])
{
boolean i=true;
Boolean obj=Boolean.valueOf(true);
System.out.println(obj);
}
Binary litrals
class binary33
{
public static void main(String[] args)
{
long b1 = 0b101000001;
byte b2 = 0B101;
System.out.println("Binary Literal in Byte");
System.out.println("b1 = "+b1);
System.out.println("b2 = "+b2);
}
}
========================================================================
Method Description
nextBoolean Reads a Boolean values from the user
nextDouble Reads a double value from the user.
nextFloat Reads a float value from the user.
nextInt Reads an integer value from the user.
nextLine Reads a string value from the user.
nextLong Reads a long value from the user.
nextShort Reads a short value from the user.
package scannerdemo;
import java.util.*;
public class scannerdemo {
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
}
==================================================================
METHOD:
A method is a set of statement that is intended to perform a specific task.
A method consist of two parts
method declaration
method definition
A syntax for defining a method:
<Access specifier> <Return-type> <method-name> (parameter list)
{
//body of the method;
}
Access specifier- Determines the extent to which a method can be accessed from another class.
Return type- A method can also return a value. The return types specifies the data type
of the value returned
by a method.
Method name- Is a unique identifier and is case sensitive.
parameter list- A method may or may not contain a parameter list depending upon its functionality.
The parameter list consists of list of parameter seprated by commas.
Method body- This contains the set of instructions that perform a specific taks.
While adding a method to a class, you should adhere to the following method naming conventions.
The method names should be verb-noun pairs.
The first letter of the method should be lowercase.
If the method name consists of several words.
=========================================================================
OBJECT:
An object is an instance of a class has a unique identity. The identity of an object distinguishes it from other
object.
To create an object, you need to declare and then instantiate an object.
class-name object-name;
To allocate memory to the object, you need to instantiate the object by using the new operator.
It also returns a reference to that memory location in the object variable.
object-name=new class-name();
class-name object-name=new class-name();
=========================================================================
INNER CLASSES:
In java, a class can also contain another class. Such a class is known as an inner cclass or neted class.
The class that contains the inner class is known as an outer class.
It contains the following benefits:
It improves encapsulation as a class can be hidden inside another class.
It [rovides a better readability.
It is useful for logically grouping classes.
class outerclass
{
static class innerclass
{
}
}
The following types of inner classes can be created in java.
1.Regular inner class
2. Static nested class
3. Method-local inner class
4. Anonymous inner class
=======================================================================
DEFINING A PACKAGE:
The package is a collection of classes. A package provides the space essentially used to organize classes
that are related to each other.
package <package-name>;
===========================================================================
ACCESSING CLASS MEMBERS:
The class members describe the characteristics and behaviour of an object. You may need to hide or protect
certain class members from other classes in a java application.
USING OBJECT:
Object are used to access the member of a class. You can access the data members of a class by specifying
the object name followed by the dot operator and the data member name.
object_name data_member_name;
USING ACCESS SPECIFIERS:
An access specifier controls the access the class member.
private
protected
public
THE PRIVATE ACCESS SPECIFIER:
The private access specifier allows a class to hide its member variables and member method from other classes.
class Jumble
{
private in score;
void show()
{
}
}
THE PROTECTED ACCESS SPECIFIER:
The protected access specifier are accessible to all the classes within the package and by the subclass outside the pac
kage.
THE PUBLIC ACCESS SPECIFIER:
The public access specifier are accessible by the classes present with in the package or outside the package.
==============================================================================
=============================================================================
OPERATORS:
An operator is a special symbol that is combined with one or more operands to perform operations, and
return the result.
1. Arithmetic operator
2. Assignment operator
3. Comparison operator
4. Logical operator
5. Unary operator
6. Bitwise operator
7. Shift operator
8. Ternary operator
==========================================================================
1. Arithmetic operator:
Arithmetic operators are used to perform arithmetic operations on operands.
operator Description
+ addition
- subtraction
* multiplication
/ division
% moudlar division
}
====================================================================
USING THE LOGICAL OPERATOR:
Logical operator are used to evaluate operands and return a boolean value.
operator Description
&& Logical AND
|| Logical OR
=====================================================================
USING THE UNARY OPERATORS:
An operator that requries one operand is called a unary operator.
OPERATOR EXAMPLE
+ x=+1;
- x=-1;
++ Increment the value by 1. a=5 a++ 6
-- Decrement the value by 1. a=5 a-- 4
! Inverts the value.
PREFIX FORM:
The value is incremented or decremented before it assigned to the operand.
n=5;
m=++n;
Once the preceding statements are executed, the values of both , m and n will be 6.
POSTFIX FORM:
The values in incremented or decremented after it has been assigned to the operand.
n=5;
m=n++;
}
}
=====================================================================
CONDITIONAL CONSTRUCTS:
1. The if construct
2. The if-else construct
3. The switch contruct
THE IF CONSTRUCT:
In the if construct, statements followed by the if statement will be executed, when expression evalutes
to true. However, if expression evalutes to false, statements will be skipped.
class ifDemo
{
public static void main(String args[])
{
Integer a=Integer.valueOf(5);
if(a<=5)
{
System.out.println("Hi");
System.out.println("Hello");
}
}
}
The if construct can contain either single statement or multiple statements.
There is need to check the condition based on another condition.
The java support the nested if construct.
SYNTAX:
if(condition)
{
if(condition)
{
//statements;
}
}
class ifDemo
{
public static void main(String args[])
{
Integer a=Integer.valueOf(4);
if(a<=5)
{
if(a==5)
{
System.out.println("Hi");
System.out.println("Hello");
}
}
}
}
IF-ELSE CONSTRUCT:
The if-else construct executes statements based on the sepcified condition.
SYNTAX:
if(expression)
{
//statments;
}
else
{
//statments;
}
class ifDemo
{
public static void main(String args[])
{
Integer a=Integer.valueOf(6);
if(a<=5)
{
System.out.println("Hi");
}
else
{
System.out.println("Hello");
}
}
}
The syntax of the nested if-else construct is:
if(expression)
{
if(expression)
{
statements;
}
else
{
statements;
}
}
else
{
if(expression)
{
statements;
}
else
{
//statments;
}
class ifDemo
{
public static void main(String args[])
{
Integer a=Integer.valueOf(4);
if(a<=5) /
{
if(a==5) // false
{
System.out.println("5");
}
else
{
System.out.println("Not a 5"); // execute
}
}
else
{
if(a>=5)//
{
System.out.println("A is bigger");
}
else
{
System.out.println("A is smaller");
}
}
}
}
}
}
}
===================================================================
LOOPING STATEMENTS:
A looping statements enables you to execute the same statements for a certain number of times. The
loop constructs executes the statements till the specified condition is met.
The for loop
The while loop
The do-while loop
SYNTAX:
for(initialization;condition;incre/decre)
{
Statements;
}
class ifDemo
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
System.out.println("The value of i is"+i);
}
}
}
You can create an infinite loop by keepoing all the three statements blank.
class ifDemo
{
public static void main(String args[])
{
for(; ;)
{
System.out.println("The value of i is");
}
}
}
After certain iterations you need to to exit from the loop. To achieve this java provides the break
statement. The break statment stops the execution of the reamining statments with in the body of
the loop.
The continue statement skips all the statements following the continue statment and moves the
control back to the loop statments.
class ifDemo
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
if(i==3)
{
continue;
}
System.out.println("The value of i is"+i);
}
}
}
II. WHILE LOOP:
The while loop construct provides the similar functionality of the for loop construct.
while(expression)
{
statments;
}
class ifDemo
{
public static void main(String args[])
{
int a=1;
while(a<=5)
{
System.out.println("The value of a is"+a);
a++;
}
}
}
You can also create an infinite loop by using the while loop construct,as displayed in the following code
snippts:
whiel(true)
{
//statements;
}
III. DO-WHILE LOOP:
The do-while loop cnstruct places the condition at the end of the loop, which makes statement to be executed
at least once.
Syntax:
do
{
statements;
}(expression);
class ifDemo
{
public static void main(String args[])
{
int a=5;
do
{
System.out.println("The value of a is"+a);
a++;
}while(a<=5);
}
}
CONTINUE:
When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.It can be used to loop and swith statement.
BREAK:
The continue statement is used in loop control structure when you need to jump to the next iteration
of the loop immediately. It can be used for looping statement.
package aqsdfg;
import java.util.*;
}
System.out.println(i);
}
}
}
{
int i=1;
while(i<=10){
if(i==5){
break; }
System.out.println(i);
i++;
}
}
class breakdemo
{
public static void main(String args[])
{
int i=1;
do
{
if(i==5)
{
++i;
continue;
}
System.out.println(i);
++i;
}while(i<=10);
}
}
=========================================================================
JAVA COMMENTS:
The Java comments are the statements in a program that are not executed by the compiler and interpreter.
The comments can be used to provide information or explanation about the variable, method,
class, or any statement.
Types of java comments:
Single line comment
Multi line comment
The single line comment is used to comment only one line of the code.
The multi-line comment is used to comment lines of code. It can be used to explain a complex code snippts
or to comment multiple lines of code at a time.
=========================================================================
ARRAY:
An array is a collection of elements of a single data type stored in adjacent memory locations.
You can access an array by specifying the name and the subscript number of the array. The subscript
number specifies the position of an element with the array. It is also called the index of the element.
The first element of an array has an index, 0 and the last element has an index one less than the size of the array.
CREATING ARRAY:
1. One dimensional array [] index subscript
2. Multi dimensional array
ONE DIMENSIONAL ARRAY:
A one dimensional array is a collection of elements with a single index value. A one dimensional array can
have multiple columns but only one row.
Syntax:
arraytype arrayname[]=new arraytype[size];
String[] name=new String[3];
for(int i=0;i<mark.length;i++)
{
System.out.println(mark[i]);
}
}
}=============================================================
MULTIDIMENSIONAL ARRAY:
Multidimensional arrays are arrays of arrys. An array having more than one dimension is called a multi dimensional
array.
Syntax:
arraytype arrayname[][]=new arraytype[row][column];
int array1[]= {45,67,8};
for(int j:array1)
{
System.out.println(j);
}
The for each loop increases the readability and simplifies the code as you need not take care of the three
operations, which are handled by the java program implicity.
Syntax:
for(type var:arrayobject)
==================================================================
class A
{
int i=10;
}
class B
{
int i=10;
B()
{
int i=12;
System.out.println(i);
}
}
public class demo90
{
public static void main(String args[])
{
B b1=new B();
//b1.display();
}
}
this keyword
There can be a lot of usage of Java this keyword. In Java,
this is a reference variable that refers to the current object.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
If local variables(formal arguments) and instance variables are different,
there is no need to use this keyword like in the following program
class Student{
int rollno;
String name;
float fee;
Student(int r,String n,float f){
rollno=r;
name=n;
fee=f;
}
this: to invoke current class method:
You may invoke the method of the current class by using the this keyword. If you don't use the this keyword,
compiler automatically adds this keyword while invoking the method.
class A{
void m(){
System.out.println("hello m");
}
void n()
{
System.out.println("hello n");
m();
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
package def;
class A
{
int id1;
String name1;
A(int id,String name)
{
id1=id;
name1=name;
}
void display()
{
System.out.println(id1);
System.out.println(name1);
}
}
=======================================================================
LOCAL AND GLOBAL VARIABLE:
package def;
class A
{
int a=15;
void display()
{
int a=10;
System.out.println(a);
}
}
public class inherdemo {
public static void main(String args[])
{
A a1=new A();
a1.display();
}
}
======================================================================
package def;
public class inherdemo {
}
}
=============================================================
public class inherdemo {
static
{
System.out.println("hi");
}
=====================================================================
ENUM:
The enum can be defined within or outside the class because it is similar to a class.
The semicolon (;) at the end of the enum constants are optional.
To declare an enum to define a fixed set of constant.
Syntax:
enum enum-name{constant1,constant2,constant3}
OR
enum enum-name {constant1,constant2,constant3; }
Example
enum stu{briliant,middele,lower}
In java enums are similar to classes. Enums can have constructors, variables and methods. However you
cannot create an instance of an enum using the new keyword.
The enum contructor get invoked when the enum constant are created, as these constant are treated as objects.
enum Season {
WINTER, SPRING, SUMMER, FALL;
public static void main(String[] args)
{
Season s=Season.WINTER;
switch(s)
{
case WINTER:
System.out.println("It is winter");
break;
case SPRING:
System.out.println("It is rain");
break;
default:
System.out.println("Not");
}
}
}
class Enumdemo4{
enum Stu{
average(1),middel(2),briliant(3);
}}
enum Season {
WINTER, SPRING, SUMMER, FALL;
public static void main(String[] args)
{
Season s=Season.WINTER;
switch(s)
{
case WINTER:
System.out.println("It is winter");
break;
case SPRING:
System.out.println("It is rain");
break;
default:
System.out.println("Not");
}
}
}
values() method :
The Java compiler internally adds the values() method when it creates an enum.
The values() method returns an array containing all the values of the enum.
valueOf() method
The Java compiler internally adds the valueOf() method when it creates an enum.
The valueOf() method returns the value of given constant enum.
ordinal() method
The Java compiler internally adds the ordinal() method when it creates an enum.
The ordinal() method returns the index of the enum value.
package not22;
enum stu
{good,average,poor}
public class notdemo {
public static void main(String args[]) {
for(stu s:stu.values())
{
System.out.println(s);
}
System.out.println(stu.valueOf("god"));
System.out.println(stu.valueOf("good"));
System.out.println(stu.valueOf("good").ordinal());
}
}
================================================================
MANIPULATING STRINGS:
To manipulate a string you can use following data types are available. These are string, stringBuilder,
StringBuffer.
USING STRING CLASS:
To store string literals, you can use the String class in the java.lang package.
String s1=new String("hello"); //string object
Creates a new string object in the heap memory, with a value, hello and assigns it to reference
variable, s1. In addition, it creates another string object with the value hello in the string constant pool.
In JVM a special memory names string constatnt pool is used to store string literals.
String s1="hello"; //string literals
A String class is an immutable class. This means that once a string object is created, you cannot
change its value.
picture:
In the preceding figure, s1 is a string reference variable, which refers to the string object with the value hello.
If you append the string literals, to the string referernce variable, s1, then a new striing object, Hello
World, is created in the memory and the variable, s1, will refer to the new string object.
However, the string object hello still exists in the memory but has no reference.
USING STRINGBUILDER AND STRINGBUFFER CLASSES:
You can also ues the StringBuilder and StringBuffer classes to work with strings. These classes are
mutable classes as they do not create any strings object when manipulated. Therefore, when you need to do
various manipulations, such as appending, concatenating and deleting with string literals, You should use
StringBuilder and StringBuffer.
StringBuilder s1=new StringBuilder("Hello");
StringBuffer s2=new StringBuffer("hello world");
STRING FUNCTIONS:
char charAt(int index) - It returns the character value of the particular index.
int length() - It return the string length.
boolean equals(object another)- It returns true or false after matching the sequence of char value.
boolean isEmpty() - It checks if string is empty.
//string concat(string str) - It concatenates the specified string.
String replace(charsequence old, charsequence new) - It replace all occurencre of the specified charsequnce.
string toLowerCase() - It returns a string in lowercase.
string toUpperCase() - It returns a string in uppercase.
String trim() - It removes beginning and ending spaces of this string.
public class StringDemo
{
public static void main(String args[])
{
int len;
String name="Welocme to NIIT";
//String name1="punitha";
//System.out.println(name.charAt(3));
//length=(name.length());
//System.out.println(length);
//System.out.println(name.equals(name1));
//System.out.println(name.isEmpty());
name.concat("hi");
System.out.println(name);
name=name.concat("hello");
System.out.println(name);
}
}
The following table lists the some of the most commonly used methods of the StringBuilder class.
StringBuilder.append(String obj) - Appends the argument to the string builder.
StringBuilder.delete(int start,int end) - Delets the sequence from start to end in the char sequence.
StringBuilder.insert(int offset,String obj) - Insert the second argument into the string builder.
The first argument indicates the index before which the data is to be insert
ed.
StringBuilder reverse() - The sequence of characters in the string builder is reversed.
String StringBuffer
The String class is immutable. The StringBuffer class is mutable.
String is slow and consumes more memory when we StringBuffer is fast and consumes less memory
concatenate too many strings because every time when we concatenate t strings.
it creates new instance.
String class overrides the equals() method of Object class. StringBuffer class doesn't override the equals()
method of Object class.
So you can compare the contents of two strings by equals() method.
String class is slower while performing concatenation operation. StringBuffer class is faster while performing c
oncatenation operation.
String class uses String constant pool. StringBuffer uses Heap memory
=================================================================
Inheritance in Java:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of the parent class. Moreover,
you can add new methods and fields in your current class also.
Class: A class is a group of objects which have common properties.
It is a template or blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class.
It is also called a derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
TYPES OF INHERITANCE:
1. Single level inheritance
2. Multilevel level inheritance
3. Hierarchical level inheritance
class Books
{
int pageno;
String authorname,name;
float price;
public Books()
{
pageno=50;
authorname="punitha";
name="niit";
price=15.78f;
}
void display()
{
System.out.println(pageno);
System.out.println(authorname);
System.out.println(name);
System.out.println(price);
}
}
class paperbooks extends Books
{
int charge=100;
public void print()
{
//display();
System.out.println("The charge is"+charge);
}
}
public class inheritDemo
{
public static void main(String args[])
{
paperbooks pb=new paperbooks();
pb.display();
pb.print();
}
}
SUPER KEYWORD:
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
ABSTRACT CLASS:
A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body).
Inheritance can also be implemented by using abstract class. An abstract class is a class that contains
one or more abstract methods. An abstract class cannot be instantiated but can be inherited by other
classes by using the extends keyword.
When an abstract class is inherited by a subclass, the subclass must provide the implementation
of all the abstract methods defined in the abstract class.
An abstract class can be used when we need to share the same method to all non-abstract
subclasses with their own specific implementations.
The abstract class acts as a blueprint for other classes.
SYNTAC FOR ABSTRACT CLASS:
<access-specifier> abstract class<abstract-class name>
{
variables;
abstract and concrete methods
}
example:
abstract return-type methodname(parameter-list);
package def;
abstract class A
{
abstract void employee();
}
class B extends A
{
void employee()
{
System.out.println("Welcome to the staff portal");
}
}
class C extends A
{
void employee()
{
System.out.println("Welcome to the student portal");
}
}
POLYMORPHSIM:
An entity such as method, can exist in multiple forms. This means that one or more methods an exist
with the same name but with a different argument list. This type of polymorphism,
when exhibited by methods, is known as method
overloading.
Two types of polymorphism:
Static polymorphism
Dynamic polymorphism
1. Static polymorphism:
When implementing method overloading, it is important to consider the following points about
overloaded methods.
They differ in the type and or number of their arguments.
They differ in the sequence of their parameter.
They differ in the data types of their parameters.
package def;
class A
{
int a,b;
int c,d,e;
A(int a,int b)
{
this.a=a;
this.b=b;
}
int calculate()
{
return a*b;
}
}
2. Dynamic polymorphism:
If a super class and subclass contain methods with the same name, the version to be invoked will
be decided by the JVM at runtime. Such a decision to invoke the appropriate method is known
as dynamic polymorphism.
Dynamic polymorphsim is implemented in java by method overriding.
Method overriding enables a subclass to provide its own implementation of a method that already
has an implementation defined in its superclass.
To overide a method present in the superclass, the supclass method should have the same name, same
parameters, and same return type as the method in the superclass.
It is important to consider the following points while implementing overriding.
Private methods cannot be overridden, as they are not accessible in subclasses.
Final methods cannot be overridden.
An overriden method cannot be granted more restrictives access rights in a suclass than it is assigned
in case of superclass.
class person
{
public void show()
{
System.out.println("hi");
}
}
class emp
{
public void show()
{
System.out.println("In the employee class");
}
}
class student extends person extends emp
{
public void show()
{
System.out.println("In the student class");
}
}
}
}
INTERFACE IN JAVA:
An interface in Java is a blueprint 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.
1. Collection of abstract class.
2. Cannot instantiate an interface.
3. An interface does not conatin any constructor.
4. All of the methods in an interface are abstract.
5. The only fields that can appear in an interface must be declared both static and final.
6. An interface is not extended by class, it is implemented by a class.
7. An interface can extend multiple inheritance.
It is used to achieve abstraction and multiple inheritance in Java
Syntax:
interface <interface_name>{
}
package def;
interface A
{
void print();
}
interface B
{
void print();
}
class D implements A,B
{
public void print()
{
System.out.println("hi");
}
}
}
}
==================================================================
THE THROWABLE CLASS:
The throwable class is the base class of exceptions in java. You can throw only those exception
objects that are derived from the Throwable class.
Exception
Error
The Exception class:
The exception class represents the conditions that a program should handle.
Error:
The error class defines the exceptions related to the java run-time environment.
For example outOfmemory is an error that occurs when there is infuffiecient system memory to
execute a program.
There are two types of exception is available in java.
1. Checked exception
2. Unchecked exception
CHECKED EXCEPTION:
These are the invalid conditions that occur in a java program due to the problems, such as accessing a file
that does not exist or referring a class that does not exist.
The checked exception are the object of the Exception class.
Exception Cause of Creation
ClassNotFoundException Is thorwn when the java run time system is unable to
find the referred class.
IllegalAccessException Is thrown when you refer an object, class, variable
constructor, or a method that is not accessible.
InstantiationException Is thrown when you try to create an instance of a class by
using the newsInstance() method, but the referred class
cannot be instantiated.
NosuchMethodException Is thrown when a particular method cannot be found.
UNCHECKED EXCEPTION:
The unchecked exception occur because of programming errors. Therefore, the compiler does not
force a programmer to handle these exceptions. Such error should be handled by writing by free codes.
For example in a calculator application, if you divide a number by zero, an unchecked exception is raised.
Exception
ArithmeticException Dividing a number by zero.
ArrayIndexOutOfBoundException Index of the array.
ArrayStoreException Not compatible with type of data
ClassCastException when you assign a reference variable of a class
to an incompatible reference variable of another class.
IllegalArgumentException Pass an argument of imcompatible data type to a method.
NegativeArraySizeException Create an array with a negative size.
NullPointerException Without allocation memory to it or calls a method of null object.
NumberFormatException Occurs when you want to convert a string in an incorrect
format to a numeric format.
NEXT METHOD:
The next() method in java is present in the Scanner class and is used to get the input from the user.
In order to use this method, a Scanner object needs to be created.
This method can read the input only until a space(” “) is encountered.
PARSEINT METHOD:
It is used to convert numeric string value to an integer value.
int num1,num2,result;
String s1,s2;
Scanner sc=new Scanner(System.in);
try
{
System.out.println("Enter two input");
s1=sc.next();
s2=sc.next();
num1=Integer.parseInt(s1);
num2=Integer.parseInt(s2);
result=num1+num2;
System.out.println("The result is"+result);
}
catch(Exception e)
{
System.out.println("Hi");
}
int num1,num2,result;
String s1,s2;
Scanner sc=new Scanner(System.in);
try
{
System.out.println("Enter two input");
num1=sc.nextInt();
num2=sc.nextInt();
result=num1/num2;
System.out.println("The result is"+result);
}
catch(ArithmeticException e)
{
System.out.println("He");
}
catch(Exception e)
{
System.out.println("Hi");
}
throw:
You can throw an exception in explicity, by using the throw keyword.
package def;
import java.util.Scanner;
class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public class inherdemo{
}}
class Test12
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
}
try{
System.out.println("try Block:: Begin");
int myArray[]=new int[5];
myArray [4]=10/0;
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception :: Divide by zero!!");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds :: Accessed index out of bounds");
}
catch(Exception e)
{
System.out.println("Exception :: " + e.getMessage ());
}
finally {
System.out.println (":: Finally Block::");
System.out.println ("No Exception::finally block executed");
}
System.out.println("rest of the code");
}
}
=======================================================
public class Test12 {
validate(13);
System.out.println("rest of the code...");
}
}
======================================================================
ASSERT KEYWORD :
int age;
Scanner sc=new Scanner(System.in);
System.out.println("Enter your age");
age=sc.nextInt();
assert(age>0)&&(age<130);
System.out.println(age);
Go to Run->run configuration
select java application in left nav pan.
right click and select New.
select Arguments tab
Add -ea in VM arguments.
==================================================================
JFrame:
The following table lists the most commonly used constructors of the JFrame class with their decription.
JFrmae() - Creates a default frame.
JFrame(String str) - Creates a default frame with the specified title.
void add(component comp) - Is used to add components on the frame.
void setseize(int width,int height) - Is used to resize the frame with the specified width and height.
package swing;
import javax.swing.JFrame;
import javax.swing.JPanel;
}
================================================================
package swingdemo;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
================================================================
package swingdemo;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
}
public static void main(String[] args) {
tab t=new tab();
}
}
=========================================================
package swingdemo;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
}
public static void main(String[] args) {
tab t=new tab();
}
}
==========================================================
package wsa;
import javax.swing.*;
public class rghj extends JFrame{
public rghj()
{
menuBar.add (fileMenu);
menuBar.add (editMenu);
menuBar.add (exitMenu);
setJMenuBar (menuBar);
setTitle ("JMenu Demo");
setSize (300,300);
setVisible (true);
}
============================================================
package wsa;
import javax.swing.*;
public class rghj extends JFrame{
JPanel jp;
JRadioButton male,female;
ButtonGroup bg;
rghj()
{
jp=new JPanel();
male=new JRadioButton("Male");
female=new JRadioButton("female");
bg=new ButtonGroup();
bg.add(male);
bg.add(female);
jp.add(male);
jp.add(female);
setTitle("Punitha");
setVisible(true);
setSize(300,200);
add(jp);
}
====================================================
Managing layouts:
Once you have created the UI components of an application, it is important to arrange them properly
to enhance the look and feel of the application.
To arrange the components in a container, you can use the various layout classes, such as Flowlayout