0% found this document useful (0 votes)
3 views37 pages

Java Notes

JN

Uploaded by

sabariv688
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views37 pages

Java Notes

JN

Uploaded by

sabariv688
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Introduction of java:

Java was originally developed by James Gosling at


Sun Microsystems (which has since been acquired by Oracle) and released in 1995
as a core component of Sun Microsystems' Java platform.
Java is a high-level, class-based, object-oriented programming language.It is a general-purpose
programming language intended to let application developers write once, run anywhere (WORA).
Features of java
1. Simple
In java memory allocation and deallocation happens automatically.
The process of automatically deallocation memory is called garbage collection.
Note: Java does not support pointers and consists of the built-in functionality to manage
memory.
2. Object oriented:
In java, the entire program code must be encapsulated inside a class.
3. Platform independance:
In java, when you compile an error-free code, the compiler converts the program to a platform independent
code, known as the bytecode. There after, the Java Virtual Machine interprets this bytecode into the machine
code that can be run on that machine.
4. Portable:
Portability refers to the ability of a program to run on any platform without changing the source code of
the program.
5. Distributed:
Java can be used for the development of those application s that can be distributed on multiple machines in a
network.
6. Secure:
Java has built in security features.
7. Robust:
java provides various features, such as memory management and exception handling make it a robust
programming language.
8. Multithreaded:
Multithreading that alows a program to simultaneously execute multiple tasks by using threads.
=============================================================================
SOURCE FILE:
A java application contains the source code that enables an application contains the source code that enables
an application to provide its desired functionalities.
CLASS FILE:
Once created a java file is compiled to generate the .class file. A class contains the bytecode that is generated
by the compiler.
JVM:
The JVM is an application that is responsible for executing java programs on a computer. It resides in the
Random Access Memory(RAM) and is specific for every platform.
The major components for JVM are:
class loader.
Execution engine and Just-In-Time compiler.
Bytecode verifier.
class loader:
The class loader loads the class files required by a program that needs to be executed. The classes are
loaded dynamically when required by the running program.
Execution Engine and JIT compiler:
The Java execution engine acts as an interpreter that interprets the bytecode one line after anotherr and
executes it. The line by line interpretation is a time-consuming taks and reduces the performance of a
program.
To enhance the performance, the JIT compiler has been introducesd in the JVM.
Bytecode verifier:
Before being executed by the JVM, the bytecide is verified by using the bytecode verifier.
API:
The java API is a collection of software components, such as classes, interfaes and methods which provides
various capabilities, such GUI, Data and time and calender. The related classes and interfaces of the
java API are grouped into packages.
===========================================================================
BLOCKS OF A JAVA PROGRAM:
A program in java comprises the following building blocks.
classes
Data types
Class members
Packages
DEFINING A CLASS:
A class defines the characteristics and behavior of an object. Any concept that you need to implement in a java
program is encapsulated within a class.
A class defines the member variables and methods of object that share common characteristics..
class <class-name>
{
int a,b,c;
display()
{
int a;

}
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");

String userName = myObj.nextLine();


String name="Punitha";
System.out.println("Username is: " + userName);
System.out.println(name);
}

}
==================================================================
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 ASSIGNMENT OPERATOR:


The assignment operator can be categorized into
1. Simple assignment operator x=4
2. Compound assignment operator a+=b; a=a+b a-=b

simple assignment operator:


The simple assignment operator is used to assign the value to the variables. a+=b a=a+b
x=4;
Complex assignement operator:
The complex assignment operator are also known as arithmetic operator. The benefits of these operators
are that they are shorthand for their equivalen long forms.
USING COMPARISON OPERATOR:
Comparison operator are used to compare two values and perform an action on the basis of the result
of the result of that comparison.
OPERATOR NAME
< less than boolean result; result=x<y
> Greater than.
<= Greater than or equal to
>= Lessthan or equal to
== Equal to
!= Not equal to 5<6 7>8 9==9 9!=9
=========================================================================
There is one more comparison operator called the instanceof operator. The instanceof operator is used to
test whether an object is an instance of a specific class at runtime or not.
Syntax:
op1 instanceof op2;
op1 is the name of object and op2 is the name of a class. The instanceof operator returns true value if the
op1m object is an instance of the op2 class.
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);
if(obj1 instanceof Boolean)
System.out.println("hi");
}

}
====================================================================
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++;

The value of n will be 6 and the value of m will be 5.


======================================================================
BITWISE OPERATOR:
Bitwise operator are used for the manipulations of data at the bit level. The bitwise operators operate on
the individual bit of their operands. The operands can be of various data types, such as int, short, long, char
and bytes.
When you use a bitwise operator, the operands are first converted into their binary equivalent, and then
the
bitwise operator operates on the bits.
The result in binary form is then converted into its decimal equivalent.
Bitwise AND (&)
Bitwise OR(|)
Bitwise NOT(~)
Bitwise XOR(^)
1. Bitwise AND
2- 0010 0000 0010
3- 0 0 1 1 0000 0011
----------- ---------------------------
0 0 1 0 - 2&3 - 2 0 0 0 0 0 0 1 0
2. Bitwise OR
2- 0 0 1 0 1 1 0 1+1
3- 0 0 1 1
--------------
0 0 1 1 - 2|3 - 3
Bitwise NOT
2- 0 0 1 0 0 0 0 0 0 0 1 0
----------------1 1 1 1 1 1 0 1 = -3
1 1 0 1 ~2=-3
Bitwise XOR
2- 0 0 1 0
3- 0 0 1 1
-------------
0 0 0 1 2^3=1
class bit
{
public static void main(String args[])
{
int a=2;
int b=3;
System.out.println("The binary value is:"+(a&b));
}
}
=========================================================================
SHIFT OPERATORS:
A shift operator is used to shift the bits of its operand either to the left or to the right. The types of shift
operators are:
Right shift operator
Left shift operator
Unsigned right shift operator.
RIGHT SHIFT OPERATOR:
The right shift operator shifts all the bits of a binary number in the right direction.
syntax:
operand>>num.
The binary representation of 5 in 8 bits is 00000101.
00000101
00000010
00000001
LEFT SHIFT OPERATOR:
The left shift operator <<, shifts all the bits of a binary number in the left direction.
SYNTAX:
operand<<num
00000101
00001010
00010100
public class shift
{
public static void main(String args[])
{
byte x, y;
x=10;
y=-10;
System.out.println("Left Shift: x<<2 = "+(x<<2));
System.out.println("Right Shift: x>>2 = "+(x>>2));

}
}

=====================================================================
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");
}
}
}
}

THE SWITCH CONSTRUCT:


The switch construct evalutes an exprssion for multiple values.
SYNTAX:
switch(expression)
{
case 1:
statements;
break;
case 2:
statements;
break;
default:
statements;
}
class ifDemo
{
public static void main(String args[])
{
char ch='#';
switch(ch)
{
case 'A':
System.out.println("This is A");
break;
case 'B':
System.out.println("This is B");
break;
default:
System.out.println("This is not a letter");

}
}
}
===================================================================
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.*;

public class compounddemo {

public static void main(String[] args)


{
for(int i=0;i<=5;i++) //0<=5 3
{
if(i==3) (3==3)
{
continue;

}
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];

int mark[]= {1,2,3};


for(int i=0;i<3;i++)
{
System.out.println(mark[i]);
}
for each loop
Syntax:
for(datatype variable: arrayname)
{
//statments(variable);
}
=========================================================================
import java.util.Scanner;
class demo90
{
public static void main(String args[])
{

Scanner sc=new Scanner(System.in);

int[] mark=new int[3];


for(int i=0;i<3;i++)
{
mark[i]=sc.nextInt();
}

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)

int array1[][]={ {45,67,8},{1,2,3}};


for(int i=0;i<array1.length;i++)
{
for(int j=0;j<array1[i].length;j++)
{
System.out.println(array1[i][j]);
}
}

==================================================================

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);
}
}

public class inherdemo {


public static void main(String args[])
{
A a1=new A(101,"punitha");
a1.display();
}
}

=======================================================================
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 {

static int a=15;


public static void main(String args[])
{
int a1=10;
System.out.println(a1);
//inherdemo n1=new inherdemo();
System.out.println(a);

}
}
=============================================================
public class inherdemo {
static
{
System.out.println("hi");
}

public static void main(String args[])


{
System.out.println("Hello");
}
}

=====================================================================
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);

private int value;


private Stu(int value){
this.value=value;
}
int result()
{
return value;
}
}
public static void main(String args[]){
Stu s1=Stu.average;
System.out.println(s1.result());

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

StringBuilder s1=new StringBuilder("hello");


System.out.println(s1.append("hi"));
//System.out.println(s1.reverse());
System.out.println(s1.delete(2, 5));
//System.out.println(s1);
System.out.println(s1.insert(2, 'a'));

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.

Whenever you create the instance of subclass, an instance of parent class is


created implicitly which is referred by super reference variable.
Usage of Java super Keyword
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
class vehicle
{
int speed=210;
void showspeed()
{
System.out.println(speed);
}
}
class car extends vehicle
{
int speed=180;
void superspeed()
{
System.out.println(speed);
System.out.println(super.speed);
}
}
public class inheritDemo
{
public static void main(String args[])
{
car c1=new car();
c1.superspeed();
}
}
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 display()
{
super();
super.display();
display()
{
System.out.println(pageno);
System.out.println(authorname);
System.out.println(name);
System.out.println(price);

System.out.println("The charge is"+charge);


}
}
public class inheritDemo
{
public static void main(String args[])
{
paperbooks pb=new paperbooks();
pb.display();
pb.display();
}
}
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

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");
}
}

public class inherdemo {


public static void main(String args[])
{
A a1=new B();
a1.employee();
C c1=new C();
c1.employee();
B b1=new B();
b1.employee();
}
}

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;
}

int calculate(int a,int b,int c)


{
this.c=c;
this.d=d;
this.e=e;
return a*b*c;
}
}
public class inherdemo {

public static void main(String args[])


{
A a1=new A(14,16);
System.out.println(a1.calculate());
System.out.println(a1.calculate(14,15,16));
}

}
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");
}
}

public class poly {


public static void main(String args[])
{

student s1=new student();


s1.show();

}
}

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>{

// declare constant fields


// declare methods that abstract

}
package def;
interface A
{
void print();
}
interface B
{
void print();
}
class D implements A,B
{
public void print()
{
System.out.println("hi");
}
}

public class inherdemo {


public static void main(String args[])
{
D s=new D();
s.print();

}
}
==================================================================
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{

public static void main(String args[])


{
try
{
fun();
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
}
}

}}

class Test12
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
}

public static void main(String args[])


{
avg();
}
}
========================================================================
public class trydemo {
public static void main(String[] args) {

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 {

public static void validate(int age) {


if(age<18) {

throw new ArithmeticException("Person is not eligible to vote");


}
else {
System.out.println("Person is eligible to vote!!");
}
}

public static void main(String args[]){

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;

public class swingdemo extends JFrame {


JFrame obj;
public swingdemo()
{
obj=new JFrame();
obj.setTitle("Punitha");
obj.setVisible(true);
obj.setSize(300,300);
}

public static void main(String[] args) {

swingdemo fobj=new swingdemo();

}
================================================================
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 class tab extends JFrame {


JTabbedPane obj;
public tab()
{
obj=new JTabbedPane(JTabbedPane.BOTTOM);
obj.addTab("Tab1",null);
obj.addTab("Tab1",null);
obj.setSize(100,100);
this.setTitle("punitha");
this.setVisible(true);
this.setSize(300,200);
this.add(obj);
}

public static void main(String[] args) {


tab t=new tab();
}
}
===================================================
JMENU:
JFrame fr;
JMenu m1,m2;
JMenuItem t1,t2;
JMenuBar me;
public tab()
{
me=new JMenuBar();
m1=new JMenu("File");
m1=new JMenu("Edit");
t1=new JMenuItem("New");
t2=new JMenuItem("open");
m1.add(t1);
m2.add(t2);
me.add(m1);
me.add(m2);
setJMenuBar(me);
setTitle("punitha");
setSize(300,300);
setVisible(true);
}

================================================================
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 class tab extends JFrame {


public static void main(String[] args) {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu Label");
menuBar.add(menu);

JMenuItem item1 = new JMenuItem("Item Label1");


JMenuItem item2 = new JMenuItem("Item Label2");
JMenuItem item3 = new JMenuItem("Item Label3");
JMenuItem item4 = new JMenuItem("Item Label4");
menu.add(item1);
menu.add(item2);
menu.add(item3);
menu.add(item4);

JFrame frame = new JFrame();


frame.setJMenuBar(menuBar);
frame.setVisible(true);
frame.setSize(200,300);
}
}
===================================================================
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 class tab extends JFrame {


JPanel Jp;
JLabel firstname,lastname;
public tab()
{
Jp=new JPanel();
firstname=new JLabel("Firstname");
lastname=new JLabel("Lastname");
Jp.add(firstname);
Jp.add(lastname);
setTitle("JLable Demo");
setVisible(true);
setSize(300,200);
add(Jp);

}
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 class tab extends JFrame {


JPanel Jp;
JTextField firstname,lastname;
public tab()
{
Jp=new JPanel();
firstname=new JTextField(" ");
lastname=new JTextField(" ");
Jp.add(firstname);
Jp.add(lastname);
setTitle("JLable Demo");
setVisible(true);
setSize(300,200);
add(Jp);

}
public static void main(String[] args) {
tab t=new tab();
}
}
==========================================================
package wsa;
import javax.swing.*;
public class rghj extends JFrame{

JMenu fileMenu, editMenu, exitMenu;


JMenuBar menuBar;

public rghj()
{

menuBar = new JMenuBar ();

fileMenu = new JMenu ("Abdul");


editMenu = new JMenu ("Edit");
exitMenu = new JMenu ("Exit");

menuBar.add (fileMenu);
menuBar.add (editMenu);
menuBar.add (exitMenu);

setJMenuBar (menuBar);
setTitle ("JMenu Demo");
setSize (300,300);
setVisible (true);

public static void main(String[] args) {

rghj obj = new rghj ();

}
============================================================
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);

public static void main(String[] args) {

rghj obj = new rghj ();

}
====================================================
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

You might also like