SlideShare a Scribd company logo
1 of 127
Download to read offline
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
1
C++ JAVA
C++ is platform-
dependent.
Java is platform-independent.
C++ is mainly used
for system
programming.
Java is mainly used for application
programming. It is widely used in
window, web-based,mobile
applications.
C++ supports goto
statement.
Java doesn't support goto statement.
C++ supports multiple
inheritance.
Java doesn't support multiple
inheritance through class. It can be
achieved by interfaces in java.
C++ supports operator
overloading.
Java doesn't support operator
overloading.
C++ supports
pointers.
Java supports pointer internally. But
you can't write the pointer program in
java. It means java has restricted
pointer support in java.
C++ uses compiler
only.
Java uses compiler and interpreter
both.
C++ supports both
call by value and call
by reference.
Java supports call by value only.
C++ supports
structures and unions.
Java doesn't support structures and
unions.
C++ doesn't have
built-in support for
threads.
Java has built-in thread support.
C++ doesn't support
documentation
comment.
Java supports documentation
comment (/** ... */) to create
documentation for java source code.
C++ supports virtual
keyword .
Java has no virtual keyword. methods
are virtual by default.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
2
Q. Features of Java
1.Simple
Java is very easy to learn and its syntax is simple, clean and easy to understand
2. Object-oriented
Java is Object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects
that incorporates both data and behaviour.
Feature of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3.Platform Independent
Java is platform independent because it is different from other languages like C, C++ etc.
which are compiled into platform specific machines while Java is a write once, run
anywhere language.
4. Secured
Java is best known for its security
C++ doesn't support
>>> operator.
Java supports right shift >>>
operator
C++ Support delete
operatore
Java doesn’t support delete operator.
Java support garbage collection
C++support destructor Java doen’t support destructor
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
3
5. Robust
Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There are lack of pointers that avoids security problem.
o There is automatic garbage collection in java.
o There is exception handling and type checking mechanism in java. All these
points makes java robust.
6.Architecture-neutral
Java is architecture neutral because there is no implementation dependent features e.g.
size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for
both 32 and 64 bit architectures.
7.Portable
Java is portable because it facilitates you to carry the java bytecode to any platform.
8.High-performance
Java support for multithreading,bytcode etc
9.Distributed
Java is distributed because it facilitates us to create distributed applications in java.
RMI and EJB are used for creating distributed applications. It may access files by
calling the methods from any machine on the internet.
10.Multi-threaded
It support multiple thread.
First Java Program
class Sample
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
4
{
public static void main(String args[])
{
System.out.println("Hello TY");
}
}
Public
It is an Access Modifier, which defines who can access this Method. Public means that
this Method will be accessible by any Class(If other Classes are able to access this
Class.).
Static
Is a keyword which identifies the class related thing. This means the given Method or
variable is not instance(object) related but Class related. It can be accessed without
creating the instance of a Class.
void
Is used to define the Return Type of the Method. It defines what the method can return.
main
Is the name of the Method. This Method name is searched by JVM as a starting point for
an application with a particular signature only.
String args[]
It is the parameter to the main Method.(Command Line argument)
Q. System.out.println meaning
▪ System is a Class
▪ out is a member of System class & object of PrintStream class
▪ println() is a method
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
5
Q. Compilation and Execution of a Java Program(How To compile & interpreter
execution in java program)
1.Compilation(Javac command)
The source ‘.java’ file is passed through the compiler, which then encodes the source
code into a machine independent encoding, known as Bytecode. The content of each
class contained in the source file is stored in a separate ‘.class’ file.
2.Execution(using java)
The class files generated by the compiler are independent of the machine or the OS,
which allows them to be run on any system. To run, the main class file (the class that
contains the method main) is passed to the JVM, and then goes through three main stages
before the final machine code is executed.
3.JVM:
Defintion:A Java virtual machine (JVM) is an abstract computing machine that
enables a computer to run a Java program.
Its ontain as follows
4.Class Loader
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
6
Definition:The class loader is a used for loading class files.
5.Bytecode Verifier
After the bytecode of a class is loaded by the class loader, it has to be inspected
by the bytecode verifier, whose job is to check that the instructions don’t perform
damaging actions.
6.Just-In-Time Compiler
This is the final stage encountered by the java program, and its job is to convert
the loaded bytecode into machine code.
Q.JAVA TOOLS
java: Starts a Java application.
javac: Reads Java class and interface definitions and compiles them into bytecode and
create class files.
javadoc: Generates HTML pages of API documentation from Java source files.
javah: Generates C header and source files from a Java class.
javap: Disassembles one or more class files.
jdb: Finds and fixes bugs in Java platform programs
appletviewer: Runs applets outside of a web browser.
Q.Java Comments
1.Java Single Line Comment
The single line comment is used to comment only one line.
//This is single line comment
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
7
2. Java Multi Line Comment
The multi line comment is used to comment multiple lines of code.
/*
This is multi line comment */
3. Java Documentation Comment
The javadoc tool uses to create documentation comment.
/**
This is documentation comment
*/
Q.Data type in java
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
8
Data Type Default Value Default size
boolean False 1 bit
Char 'u0000'(Unicode) 2 byte
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
Float 0.0f 4 byte
Double 0.0d 8 byte
Q.Java Operator
Operator
Type
Category Precedence
Unary Postfix expr++ expr--
Prefix ++expr --expr +expr -
expr ~ !
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
9
Arithmetic Multiplicative * / %
Additive + -
Shift Shift << >> >>>
Relational Comparison < > <= >= instanceof
Equality == !=
Bitwise bitwise AND &
bitwise
exclusive OR
^
bitwise
inclusive OR
|
Logical logical AND &&
logical OR ||
Ternary Ternary ? :
Assignment Assignment = += -= *= /= %= &= ^=
|= <<= >>= >>>=
Q.Control Strcture:
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
10
1.Contional Statement
1. If Statement
Syntax
if(condition)
{
//code to be executed
}
e.g
int age=20;
if(age>18){
{
System.out.print("Age is greater than 18");
}
2. If-else Statement
Syntax
if(condition)
{
//code if condition is true
}
Else
{
//code if condition is false
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
11
e.g
int n=5;
if(n>0)
{
System.out.print("No is positive");
}
else
{
System.out.print("No is negative");
}
3. Nested If-else statement
Syntax
if(condition1)
{
//code to be executed if condition1 is true
}
else
if(condition2)
{
//code to be executed if condition2 is true
}
else
if(condition3)
{
//code to be executed if condition3 is true
}
Else
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
12
{
//code to be executed if all the conditions are false
}
e.g
int marks=65;
if(marks>=70)
{
System.out.println("A");
}
else if(marks>=60)
{
System.out.println("B");
}
else if(marks>=50)
{
System.out.println("C ");
}
else if(marks>=40)
{
System.out.println("D");
}
Else
{
System.out.println("fail");
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
13
4. Switch case statement
Syntax
switch(expression)
{
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
code to be executed if all cases are not matched;
}
e.g
int number=20;
switch(number)
{
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
default:System.out.println("Not in 10, 20 or 30");
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
14
Loop
1.while
Syntax
while (condition)
{
//code to be executed
Increment / decrement statement
}
e.g
int i=1
while(i<=3)
{
System.out.println(i);
i++;
}
2. Do-while
Syntax
do
{
//code to be executed
Increment / decrement statement
} while (condition);
e.g
int i=1
do
{
System.out.println(i);
i++;
}while(i<=3);
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
15
3. for loop
Syntax
for(initialization; condition; increment/decrement)
{
//statement or code to be executed
}
e.g
for(i=1;i<=3;i++)
{
System.out.println(i);
}
Q.Labelled break statement
Labeled break statement terminated loop of specified label.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
16
first:
for( int i = 1; i < 5; i++)
{
for(int j = 1; j < 3; j ++ )
{
System.out.println(“ j = " +j);
if ( i == 2)
break first;
}
}
}
Q. Labeled Continue statement
Labeled Continue statement skip loop of specified label.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
17
e.g
label:
for (int i = 1; i < 3; ++i)
{
for (int j = 1; j < 5; ++j)
{
if (j == 2)
continue label;
System.out.println("i = " + i + "; j = " + j);
}
}
Q.Accepting input from user & display it
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
18
import java.util.*;
public class Demo
{
public static void main(String[] args)
{
try
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter integer value");
int a1= scan.nextInt();
System.out.print("Enter float value");
float a2 = scan.nextFloat();
System.out.print("Enter name");
String a3 = scan.next();
System.out.println("Integer value is "+a1);
System.out.println("float value is "+a2);
System.out.println("string value is "+a3);
}
catch(Exception e)
{
System.out.println(“error”+e);
}
}
}
Q. Final keyword
It is used dealered constant variable(Its value canot changed value of variable).
e.g final float pi=3.14f;
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
19
Q.Array
An array is a collection of similar data types.
1.Single Dimensional Array in java
Syntax
Declaration of 1d array
dataType arr[ ];
Instantiation of an Array in java
arr=new datatype[size];
e.g int arr[ ]
arr=new int[4];
OR
Delcration & Instantiation of an Array in java
datatype arr[]=new datatype[size];
e.g
int arr[]=new int[4];
import java.util.*;
class Sample
{
public static void main(String args[])
{
try
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter limit");
int n= scan.nextInt();
int arr[]=new int[n];
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
20
int i;
for(i=0;i<arr.length;i++)
{
System.out.println("Enter data");
arr[i]= scan.nextInt();
}
System.out.println("display is");
for(i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
catch(Exception e)
{
}
}
}
Initialization 1d array
e.g
int a[]={33,3,4,5};
2.Multidimensional array in java
Syntax
Declaration of 2d array
dataType arr[ ][ ];
Instantiation of an Array in java
arr=new datatype[rowsize][colsize];
e.g int arr[ ][ ]
arr=new int[2][2];
OR
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
21
Delcration & Instantiation of an Array in java
datatype arr[ ][ ]=new datatype[rowsize][colsize];
e.g
int arr[][]=new int[2][2];
import java.util.*;
class Sample
{
public static void main(String args[])
{
try
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter row limit");
int r= scan.nextInt();
System.out.println("Enter col limit");
int c= scan.nextInt();
int arr[][]=new int[r][c];
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.println("Enter data");
arr[i][j]=scan.nextInt();
}
}
System.out.println("display is");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.println(arr[i][j]);
}
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
22
catch(Exception e)
{
}
}
}
Initialization 2d array
e.g
int a[][]={{1,2},{3,4}};
Q.class & object
A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.
import java.util.*;
class Student
{
public int rno;
public String name;
public void read() throws Exception
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter rollno");
rno=scan.nextInt();
System.out.println("Enter name");
name=scan.next();
}
public void display()
{
System.out.println("rollno"+rno);
System.out.println("name"+name);
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
23
class Sample
{
public static void main(String args[])
{
try
{
Student s=new Student();
s.read();
s.display();
}
catch(Exception e)
{
}
}
}
Instance Member: Those member declared inside the class known as Instance
Member.
Instance Method:Those member declared inside the class known as Instance method
To creation of object kown as instantiation
Q. Access Modifiers in java
Access Modifier within
class
within
package
outside
package by
subclass only
outside
package
Private Y N N N
Default(friendly) Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
24
There are 4 types of java access modifiers:
1. private
2. default(friendly)
3. protected
4. public
1.private modifier
The private access modifier is accessible only within class.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Sample
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
2.public modifier
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
class A
{
public int data=40;
public void msg()
{
System.out.println("Hello java");
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
25
public class Sample
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);
obj.msg();
}
}
3.default access modifier
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package
class A
{
int data=40;
void msg()
{
System.out.println("Hello java");
}
}
4.protected access modifier
The protected access modifier is accessible within package and outside the package but
through inheritance only
class A
{
protected int data=40;
protected void msg()
{
System.out.println("Hello java");
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
26
Q. USE OF ARRAY OF OBJECT
import java.util.*;
class Student
{
public int rno;
public String name;
public void read() throws Exception
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter rollno");
rno=scan.nextInt();
System.out.println("Enter name");
name=scan.next();
}
public void display()
{
System.out.println("rollno"+rno);
System.out.println("name"+name);
}
}
class Sample
{
public static void main(String args[])
{
try
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter limit");
int n=scan.nextInt();
Student s[]=new Student[n];
int i;
for(i=0;i<n;i++)
{
s[i]=new Student();
s[i].read();
}
System.out.println("Display is");
for(i=0;i<n;i++)
{
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
27
s[i].display();
}
}
catch(Exception e)
{
}
}
}
Q. Constructor
A constructor in Java is a block of code similar to a method that's called when a object is
created.
1.non parameterized constructor
A constructor that has no parameter is known as default constructor. If we don’t define a
constructor in a class, then compiler creates default constructor(with no arguments) for
the class.
class Student
{
public int rno;
public String name;
Student()
{
rno=1;
name=”om”
}
}
class Sample
{
public static void main(String args[])
{
try
{
Student s=new Student();
s.read();
s.display();
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
28
catch(Exception e)
{
}
}
}
2.Parameterized Constructor: A constructor that has parameters is known as
parameterized constructor.
class Student
{
public int rno;
public String name;
Student(int r,String s)
{
rno=r;
name=s;
}
}
class Sample
{
public static void main(String args[])
{
try
{
Student s=new Student(1,”om”);
s.read();
s.display();
}
catch(Exception e)
{
}
}
}
Q. Garbage Collector
• Java doesnot support delete operator
• Garbage Collector is a program that manages memory automatically wherein de-
allocation of objects is handled by Java .
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
29
• In the Java programming language, dynamic allocation of objects is achieved
using the new operator. An object once created uses some memory and the
memory remains allocated till there are references for the use of the object.When
there are no references to an object, it is assumed to be no longer needed, and the
memory, occupied by the object can be reclaimed. There is no explicit need to
destroy an object. Java handles the de-allocation automatically.The technique is
known as Garbage Collection
Q.Finalize() method
• Java doesnot support destructor
• Finalize() is used to perform clean up processing just before object is garbage
collected.
• if an object is holding some non-java resource such as a file handle or window
character font, then it may want to make sure these resources are freed before an
object is destroyed. To handle such situations, java provides a mechanism called
finalization. By using finalization, It can define specific actions that will occur
when an object is just about to be reclaimed by the garbage collector.
• Finalize() method added any class.
protected void finalize()
{
// finalization code here
}
The keyword protected is a specifier that prevents access to finalize() by code defined
outside its class.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
30
Q.THIS keyword
This is a reference variable that refers to the current object.
Usage
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
class Student
{
public int rno;
public String name;
Student(int rno,String name)
{
this->rno=rno;
this->name=name;
}
}
Q.Static variable
Static variable in Java is variable which belongs to the class(not balong instance or
object) and initialized only once at the start of the execution.
• It is a variable which belongs to the class and not to object(instance)
• Static variables are initialized only once, at the start of the execution. These
variables will be initialized first, before the initialization of any instance variables
• A single copy to be shared by all instances of the class
• A static variable can be accessed directly by the class name and doesn’t need any
object
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
31
Syntax
<class-name>.<variable-name>
Q. Static Method
Static method in Java is a method which belongs to the class and not to the object. A
static method can access only static data.
• It is a method which belongs to the class and not to the object(instance)
• A static method can access only static data. It can not access non-static data
(instance variables)
• A static method can call only other static methods and can not call a non-static
method from it.
• A static method can be accessed directly by the class name and doesn’t need any
object
• A static method cannot refer to "this" or "super" keywords in anyway
Syntax
<class-name>.<method-name>
class Sample
{
static int age=30;
static void disp()
{
System.out.println("Age is: "+age);
}
public static void main(String args[])
{
System.out.println("Age is: "+Sample.age);
Sample.disp();
}
}
Q.Static block
Static block is used for initializing the static variables.This block gets executed when
the class is loaded in the memory
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
32
class Sample
{
static int age;
static
{
System.out.println("static block");
age=30;
}
public static void main(String args[])
{
System.out.println("Age is: "+Sample.age);
}
}
Q.Inheritance
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
extends is the keyword used to inherit the properties of a class.
Syntax
class Super {
.....
.....
}
class Sub extends Super
{
.....
.....
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
33
Types of inheritance
1.Single inheritance: Single inheritance have only one base class known as Single
Inheritance.
class A
{
void dispA()
{
System.out.println("class A");
}
}
class B extends A
{
void dispB()
{
System.out.println("class B");
}
}
class Inh
{
public static void main(String args[])
{
B ob=new B();
ob.dispA();
ob.dispB();
}
}
Constructor
1.non parametrized constructor
class A
{
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
34
A()
{
System.out.println("class A");
}
}
class B extends A
{
B()
{
System.out.println("class B");
}
}
class Inh
{
public static void main(String args[])
{
B ob=new B();
}
}
2.paramerized constructor
Q.Super keyword
The super keyword in java is a reference variable which is used to refer immediate
parent class object.
Use of super
1.super() can be used to invoke immediate parent class constructor.
class A
{
int a;
A(int a1)
{
a=a1;
System.out.println(a);
}
}
class B extends A
{
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
35
int b;
B(int a1,int b1)
{
super(a1);
b=b1;
System.out.println(b);
}
}
class Inh
{
public static void main(String args[])
{
B ob=new B(1,2);
}
}
2. It can use super keyword to access the data member or field of parent class. It is
used if parent class and child class have same fields.
class A
{
int a=1;
}
class B extends A
{
int a=2;
void disp()
{
System.out.println(a);
System.out.println(super.a);
}
}
class Inh
{
public static void main(String args[])
{
B ob=new B();
ob.disp();
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
36
3. The super keyword can also be used to invoke parent class method. It should be
used if subclass contains the same method as parent class(method overiding).
class A
{
void disp()
{
System.out.println("class A");
}
}
class B extends A
{
void disp()
{
super.disp();
System.out.println("class B");
}
}
class Inh
{
public static void main(String args[])
{
B ob=new B();
ob.disp();
}
}
2.Multilevel inheritance: When a class is derived from a class which is also derived
from another class, i.e. a class having more than one parent classes, such inheritance is
called Multilevel Inheritance
class A
{
void dispA()
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
37
{
System.out.println("class A");
}
}
class B extends A
{
void dispB()
{
System.out.println("class B");
}
}
class C extends B
{
void dispC()
{
System.out.println("class C");
}
}
class Inh
{
public static void main(String args[])
{
C ob=new C();
ob.dispA();
ob.dispB();
ob.dispC();
}
}
3 Hierachical inheritance: When more than one classes are derived from a single base
class, such inheritance is known asHierarchical Inheritance
class A
{
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
38
void dispA()
{
System.out.println("class A");
}
}
class B extends A
{
void dispB()
{
System.out.println("class B");
}
}
class C extends A
{
void dispC()
{
System.out.println("class C");
}
}
class Inh
{
public static void main(String args[])
{
B ob1=new B();
ob1.dispA();
ob1.dispB();
C ob2=new C();
ob2.dispA();
ob2.dispC();
}
}
Function overloading
Definition:function Overloading is a feature that allows a class to have more than
one method having the same name.
class A
{
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
39
void disp(int a)
{
System.out.println(a);
}
void disp()
{
int b=2;
System.out.println(b);
}
}
class Inh
{
public static void main(String args[])
{
A ob =new A();
ob.disp(2);
ob.disp();
}
}
Function overriding
If subclass (child class) has the same method as declared in the parent class in same
prototype, it is known as method overriding in java
class A
{
void disp()
{
System.out.println("class A");
}
}
class B extends A
{
void disp()
{
super.disp();
System.out.println("class B");
}
}
class Inh
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
40
{
public static void main(String args[])
{
B ob=new B();
ob.disp();
}
}
Q.Abstract class
Definition:An abstract class is a class that is declared abstract—it may or may not
include abstract methods. Abstract classes cannot be instantiated, but they can be
subclassed.
abstract method:A method that is declared as abstract and does not have
implementation (no body)is known as abstract method
abstract class A
{
abstract void disp();
}
class B extends A
{
void disp()
{
System.out.println("class b");
}
}
class Inh
{
public static void main(String args[])
{
B ob =new B();
ob.disp();
}
}
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
41
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println("drawing circle");
}
}
class Test
{
public static void main(String args[])
{
Shape s1=new Circle1();
s1.draw();
Shape s2=new Rectangle();
s2.draw();
}
}
Q.Need of interface(Why java doenot support muiliple inheritance)
1.Diamond Problem:
In above diag there is every chance of multiple properties of multiple objects with the
same name available to the sub class object with same priorities leads for the ambiguity.
Such problem kown as diamond problem
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
42
2. Simplicity – Multiple inheritance is not supported by Java using classes , handling the
complexity that causes due to multiple inheritance is very complex.
Q.Interface
Defintion:An interface in java is a blueprint of a class. It has static constants(final
)variables and abstract methods only.
Syntax
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Class classname implements interface name
{
//implemts abstract methods
}
e.g
interface A
{
void disp();
}
class B implements A
{
public void disp()
{
System.out.println("class b");
}
}
class Inh
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
43
{
public static void main(String args[])
{
B ob =new B();
ob.disp();
}
}
Feature
• All of the methods in an interface are abstract.
• It can’t instantiate an interface in java
• It contains fields in an interface must be declared both static and final.
• An interface is not extended by a class; it is implemented by a class by using
implements keyword.
• An interface can extend multiple interface
• All methods in an interface are implicitly public and abstract
Q.Possible form of interface
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
44
2.
3.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
45
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
46
abstract class Interface
1) Abstract class can have abstract
and non-abstract methods.
Interface can have only
abstract methods.
2) Abstract class doesn't support
multiple inheritance.
Interface supports multiple
inheritance.
3) Abstract class can have final,
non-final, static and non-static
variables.
Interface has only static and
final variables.
4) Abstract class can provide the
implementation of interface.
Interface can't provide the
implementation of abstract
class.
5) The abstract keyword is used to
declare abstract class.
The interface keyword is used to
declare interface.
6) An abstract class can extend
another Java class and implement
multiple Java interfaces.
An interface can extend another
Java interface only.
7) A Java abstract class can have
class members like private,
protected, etc.
Members of a Java interface are
public by default.
8)Example:
abstract class Shape
{
abstract void draw();
}
Example:
interface Shape
{
void draw();
}
Q.Nested Class
The Java programming language allows you to define a class within another class. Such a
class is called a nested class
There are 2 type
1. Static nested class(static inner class)
2. Non static nested class(inner class)
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
47
Static nested class(static inner class) Non static nested class(inner class)
1.A outer class contain static class is called
Nested class or static Inner class.
A outer class contain non static class is
called Inner class.
2. Nested static class doesn’t need
reference of Outer class
Non Nested static class does need reference
of Outer class
3. Nested static class cannot access non-
static members of the Outer class. It can
access only static members of Outer class
Inner class(or non-static nested class) can
access both static and non-static members
of Outer class
public class Outer
{
int i = 100;
static int j=200;
static class Inner
{
int v = 20;
void disp()
{
System.out.println(j);
System.out.println(v);
}
}
public static void main(String[] args)
{
Outer out = new Outer();
Inner inb = new Inner();
inb.disp();
}
}
public class Outer
{
int i = 100;
static int j=200;
class Inner
{
int v = 20;
void disp()
{
System.out.println(i);
System.out.println(j);
System.out.println(v);
}
}
public static void main(String[] args)
{
Outer out = new Outer();
Inner inb = out.new Inner();
inb.disp();
}
}
Q.Anonymous Inner Class
A class that have no name is known as anonymous inner class is known as
Anonymous inner class.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
48
It should be used if you have to override method of class or interface. Java Anonymous
inner class can be created by two ways:
1.Class (may be abstract or concrete).
abstract class Person
{
abstract void eat();
}
class TestAnonymousInner
{
public static void main(String args[])
{
Person p=new Person()
{
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
2.Using Interface
interface Eatable
{
void eat();
}
class TestAnnonymousInner1
{
public static void main(String args[])
{
Eatable e=new Eatable(){
public void eat()
{
System.out.println("nice fruits");
}
};
e.eat();
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
49
Q.Object Cloneing
Object cloning refers to creation of exact copy of an object. It creates a new instance of
the class of current object and initializes all its fields with exactly the contents of the
corresponding fields of this object.
Syntax
protected Object clone() throws CloneNotSupportedException
class Test2 implements Cloneable
{
int a;
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
public class Main
{
public static void main(String args[]) throws
CloneNotSupportedException
{
Test2 t1 = new Test2();
t1.a = 10;
Test2 t2 = (Test2)t1.clone();
System.out.println(t2.a);
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
50
Packages
Def:Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces
Built-in Packages
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
User-defined packages
The following steps are creating user defined packages
1. Declare the package at the beginning of a file using following form
package packagename;
e.g package comp;
2. Create directory & its name same as package name
3. Define a class &added in the directory.
4. Compile the class file
5. Accessing package
Following ways to access the package
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
51
1.import package.*: all the classes and interfaces of this package will be accessible
but not subpackages.
2.packagename.classname: package.classname then only declared class of this
package will be accessible
The import keyword is used to make the classes and interface of another package
accessible to the current package
package comp;
public class Bcs
{
Public void show()
{
System.out.println(“show in bcs”);
}
}
import comp.*;
class Main
{
public static void main(String args[])
{
Bcs ob=new Bcs();
ob.show();
}
}
Q.Static import
It access the static member without class name.
import static java.lang.System.out;
public class HelloWorld
{
public static void main(String[] args)
{
out.println("Hello World!");
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
52
Q.Wrapper class
Definition:It is mechanism to convert primitive data type into object
Autoboxing
Converts primitive data type into object called as autoboxing
Unboxing
converts object into primitive data type called as unboxing
Primitive
Type
Wrapper
class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
1.To convert primitive data type into object
1.int i=2
Integer ival=new Integer(i);
2.float f=2.5f;
Float fval=new Float(f);
2.To convert object into primitive data type using typeValue() method
1. int i=ival.intValue();
2. float f=fval.floatValue();
3.To convert number into string by using toString() method
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
53
1. int i=2;
String s=Integer.toString(i);
2 float f=2.5f;
String s=Float.toString(f);
3.To convert string into numeric object by using valueOf() method
1. Integer ival=Integer.ValueOf(“4”);
2. Float fval=Float.ValueOf(“1.5”);
4.To convert numeric string into primitive datatyoe using parse method
1. int i=Integer.parseInt(“3”);
2. float f=Float.parseFloat(“2.5”);
JAR(Java Archive File)
JAR (Java Archive) is a package file format typically used to aggregate many
Java class files and associated metadata and resources (text, images, etc.) into one
file to distribute application software or libraries on the Java platform.
Creating JAR File
jar cf jar-filename input-files
The c option indicates that you wish to create a jar and the f option indicates that
output should be sent to a file, jar-filename is the name of the resulting Jar file
and input-files are the files you wish to include.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
54
Mainfest File
The Jar file automatically adds a manifest file to the jar file, the file is always in a
directory named META-INF and file is named MANIFEST.MF.This file
contains information about the jar file.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
55
String and Stringbuffer
The java.lang package contains two string classes String and Stringbuffer
String class
A combination of character is a string.
Q.Possible String Constructors
1.String(); =>Empty Constructor
2.String(char chars[ ])
3.String(char chars[ ], int startIndex, int numChars)
4.String(String strObj)
E.g
class MakeString
{
public static void main(String args[])
{
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
String s = new String(c, 1, 2);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
ava
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
56
Q.String Methods
1.Length()
The length of a string is the number of characters that it contains.
int length( )
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
2.String Concatenation
Using + operations.
For example, the following fragment concatenates three strings:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
This displays the string “He is 9 years old.”
3.toString( ) method
Syntax
String toString( )
The toString() method returns the string representation of the object. If you print
any object, java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output in the form of string.
class Student
{
int rollno;
String name;
Student(int r, String s)
{
rollno=r;
name=s;
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
57
}
public String toString()
{
return rollno+" "+name+;
}
public static void main(String args[])
{
Student s1=new Student(101,"vision");
System.out.println(s1);//compiler writes here s1.toString()
}
}
Character Extraction
1.charAt( )
To extract a single character from a String.
char charAt(int where)
char ch;
String s=”abc”;
ch = s.charAt(1);
assigns the value “b” to ch.
Q. String Comparison
1.equals( ) and equalsIgnoreCase( )
To compare two strings for equality, use equals( ). It
returns true if the strings contain the same characters in the same order, and false
otherwise.
It has this general form:
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
58
boolean equals(String str) => The comparison is case-sensitive.
boolean equalsIgnoreCase(String str)=> The comparison is not case-sensitive.
String s1 = "Hello";
String s2 = "HELLO";
If(s1.equals(s2))
System.out.println(“equals”);
Else
System.out.println(“not equals”);
If(s1.equalsIgnoreCase(s4))
System.out.println(“equals”);
Else
System.out.println(“not equals”);
2.startsWith( ) and endsWith( )
boolean startsWith(String str)
boolean endsWith(String str)
String s="Foobar"
s.endsWith("bar")
s.startsWith("Foo")
are both true.
3.equals( ) Versus ==
The equals( ) method compares the characters inside a String object.
The == checks to see if the 2 object names are basically references to the same
memory location.
// equals() vs = =
String s1 = "Hello";
String s2 = new String(s1);
if(s1.equals(s2))
System.out.println(“equals”);
Else
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
59
System.out.println(“not equals”);
if(s1==s2)
System.out.println(“equals”);
Else
System.out.println(“not equals”);
String obj1 = new String("xyz");
// now obj2 and obj1 reference the same place in memory
String obj2 = obj1;
if(obj1 == obj2)
System.out.printlln("TRUE");
else
System.out.println("FALSE");
4.compareTo( )
It has this general form:
int compareTo(String str)
Here, str is the String being compared with the invoking String. The result of the
comparison is returned and is interpreted as shown here:
Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.
e.g String s1=”hello”
int k=s1.compareTo(“hello”)
o/p 0
Substring():It return substring
String substring(int startIndex)
String substring(int startIndex, int endIndex)
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
60
1.Concat( )
String concat(String str)
String s1 = "one";
String s2 = s1.concat("two");
puts the string “onetwo” into s2.
2.replace( )
The replace( ) method replaces all occurrences of one character in the invoking string
with another character.
String replace(char original, char replacement)
String s1=”hello”
String s = s1.replace('l', 'w');
Changing the Case of Characters
The method toLowerCase( ) converts all the characters in a string from uppercase to
lowercase. The toUpperCase( ) method converts all the characters in a string from
lowercase to uppercase.
Sring toLowerCase( )
String toUpperCase( )
String s = "This is a test.";
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
61
2.StringBuffer
• A string buffer is mutable(Once the string object is creatred,the object can be changed).
StringBuffer Constructors
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
1.append( )
The append( ) method concatenates the string representation of any other type of data
to the end of the invoking StringBuffer object. It has overloaded versions for all the
built-in types and for Object.
Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
int a = 42;
StringBuffer sb = new StringBuffer(40);
sb = sb.append("a = ").
sb = sb.append(a).
System.out.println(sb);
2.insert( )
The insert( ) method inserts one string into another.
These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
62
StringBuffer insert(int index, Object obj)
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
The output of this example is shown here:
I like Java!
3.reverse( )
You can reverse the characters within a StringBuffer object using reverse( )
StringBuffer reverse( )
StringBuffer s = new StringBuffer("abcdef");
s.reverse();
System.out.println(s);
4.delete( ) and deleteCharAt( )
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
The following output is produced:
After delete: This a test.
After deleteCharAt: his a test.
5.replace( )
StringBuffer replace(int startIndex, int endIndex, String str)
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
Here is the output:
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
63
After replace: This was a test.
STRING STRINGBUFFER
The length of the String object
is fixed.
The length of the StringBuffer can be
increased.
String object is immutable. StringBuffer object is mutable.
It is slower during
concatenation.
It is faster during concatenation.
Consumes more memory. Consumes less memory.
String s=new String(“vision”) StringBuffer sb=new StringBuffer(“vision)
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
64
EXCEPTION HANDLING
Error can be 2 categories
1.Compile time error:
• Missing semicolon
• Missing brackets in classes and method.
• Misspelling of identifiers and keywords
• Missing double quotes in string.
• Use of understand variable
• Incomplete types in assignments/initialization.
• Bad reference object
• Use of = in place of = = operator.
2.RunTime Errors
• Dividing an integer by zero.
• Accessing an element that is out of the bound of an array.
• Trying to store a value into an array of an incomplete class or type.
• Trying to cast an instance of a class to one of its subclass.
• Attempting to use a negative size of an array.
• Converting invalid string to a number.
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Or
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
65
class Exc1 {
static void subroutine() {
int d = 0;
int a = 10 / d;
}
public static void main(String args[]) {
Exc1.subroutine();
}
}
o/p
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
66
Exception:
It is condition that is caused by run time error in the program.
Types Of Exception
Checked Exceptions
Throwable and its subclasses except Error and RuntimeException put together are
called as checked exceptions. If these exceptions are not handled or checked by the
programmer in coding, the program does not compile. That is, compiler bothers much of
this type of exceptions because they are raised in some special cases in the code which if
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
67
not handled, the program may lead to many troubles. Common examples are
FileNotFoundException, IOException and InterruptedException etc.
Unchecked Exceptions
RuntimeException and its all subclasses including Error are known as unchecked
exceptions. As the name indicates, even if they are not handled or checked by the
programmer, the program simply compiles. If at runtime, problems arise, the execution
simply terminates. That is, regarding unchecked exceptions, the compiler does not bother.
Common examples are ArithmeticException, ArrayIndexOutOfBoundsException,
NumberFormatException, NullPointerException etc.
Java exception handling is managed via five keywords: try, catch, throw, throws,
and finally.
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
//…………….
finally {
// block of code to be executed before try block ends
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
68
Using try and catch
int d, a;
try
{
d = 0;
a = 42 / d;
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
OR
System.out.println("Error"+e);
}
Exception class have 2 methods
1. String getMessage();
It is method of throwable class. This methods print only the message part of the
output printed by object e.
int d, a;
try
{
d = 0;
a = 42 / d;
}
catch (ArithmeticException e)
{
System.out.println("Error"+e.getMessage())
}
2. void printStackTrace();
It is method of throwable class.This method print the same message of “e” object
& line number where the exception occurred.
int d, a;
try
{
d = 0;
a = 42 / d;
}
catch (ArithmeticException e)
{
e. printStackTrace();
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
69
}
Q.Multiple catch Clauses
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
}
}
Here is the output generated by running it both ways:
C:>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.
OR
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
70
Try using exception class
try
{
int a = 0;
int b = 42 / a;
}
catch(Exception e)
{
System.out.println("error1"+e);
}
Q.Nested try Statements
class NestTry
{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try
{
if(a==1)
a = a/(a-a);
if(a==2)
{
int c[] = { 1 };
c[42] = 99;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
71
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
C:>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException
Q.Use try..catch in function
class MethNestTry
{
static void nesttry(int a)
{
try
{
if(a==1) a = a/(a-a);
if(a==2)
{
int c[] = { 1 };
c[42] = 99;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
72
}
public static void main(String args[])
{
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
nesttry(a);
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
Q.Finally Statement
1. Java support statement known as finally statement.
2. finally block can be used to handle any exception generated within try block.
3. When finally block is defined, that is guaranteed to execute, regardless of whether
or not an exception is thrown.
4. finally use to perform certain house-keeping operation such as closing files and
releasing resources.
5. It may be added immediately after the try block or after last catch block shown as
follow.
try
{
……………….
………..
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
73
finally
{
……………
……….
}
Or
try
{
……………….
………..
}
catch(…)
{
…………
……….
}
finally
{
……………
……….
}
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
74
catch (ArithmeticException e)
{
System.out.println("Error"+e);
}
finally
{
System.out.println("finally block");
}
Q.THROW
The Java throw keyword is used to explicitly throw an exception.It can throw either
checked or uncheked exception in java by throw keyword.
Syntax
throw new throwable_subclass;
throw new NullPointerException("null exception");
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestExp
{
public static void main(String args[])
{
int x=5;
try
{
If (x<0)
throw new MyException(“no is negative”);
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
75
}
catch(MyException e)
{
System.out.println(e.getMessage());
}
}
}
// Demonstrate throw.
class ThrowDemo
{
static void demoproc()
{
try
{
throw new NullPointerException("demo");
} catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
try
{
demoproc();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
76
Q.throws
Throws keyword is used to declare that a method may throw one or some exceptions.
Thorws is used with the method signature.
Syntax
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
Try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
77
Exception Class Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible
type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
IllegalStateException Environment or application is in incorrect state
IllegalThreadStateException Requested operation not compatible with current
thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was Encountered
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or
interface.
InterruptedException One thread has been interrupted by
another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist..
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
78
Q.Assertion
Assertion is used to debugging purpose.An assertion is a statement containing a
boolean expression that is assumed to be true when the statement is executed.The
system report a AssertionError if the expression to false.
Syntax
1. assert expression1 : expression2;
e.g
int age=11;
assert age>=18:" Not valid";
System.out.println("age is "+value);
o/p
Exception in thread "main" java.lang.AssertionError: Not valid
Note
To Enabling assertion
Compile it by: javac AssertionExample.java
Run it by: java -ea AssertionExample
To Disable assertion
Run it by: java -da AssertionExample
Advantage of assertion
1.The assertion machanisum allows to put in checks during testing
2.Excution of code with assertion is faster as compared to exception
3.Code size in small
4.Assertion facility can be enabled or disabled.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
79
Rules of assertion
1. Assertions should not be used to replace error messages
2. Assertions should not be used to check arguments in the public methods as they
may be provided by user. Error handling should be used to handle errors provided
by user.
3.Assertions should not be used on command line arguments.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
80
AWT (Abstract Window toolkit) &Swing
java.lang Object
Component
java.awt
Container
Window Panel
Frame Applet
Javax.swing Jframe Japplet
AWT(Abstract window toolkit) SWING
AWT components are platform-
dependent.
Java swing components are platform-
independent.
AWT components are heavyweight. Swing components are lightweight.
AWT provides less components than
Swing.
Swing provides more powerful
components such as tables, lists,
scrollpanes, tabbedpane etc.
AWT doesn't support pluggable look and
feel.
Swing supports pluggable look and feel.
AWT doesn't follows MVC(Model View
Controller) where model represents data,
view represents presentation and controller
Swing support MVC
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
81
acts as an interface between model and
view.
e.g Button e.g JButton
Container
1. JFrame – This is a top-level container which can hold components and containers like
panels.
Constructors
JFrame()
JFrame(String title)
Important Methods
setSize(int width, int height) Specifies size of the frame in pixels
setLocation(int x, int y) Specifies upper left corner
setVisible(boolean visible) Set true to display the frame
setTitle(String title) Sets the frame title
setDefaultCloseOperation(int mode) -Specifies the operation when frame is
closed.
Where
The modes are:
JFrame.EXIT_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DISPOSE_ON_CLOSE
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
82
public class JFrameDemo extends JFrame
{
public JFrameDemo()
{
super("Ty");
setSize(200,200);
setLocation(100,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new JFrameDemo();
}
}
2. JPanel – The JPanel is a simplest container class. It provides space in which an
application can attach any other component. It inherits the JComponents class.It doesn't
have title bar.
Constructors
JPanel()
public class Pan extends JFrame
{
public Pan()
{
setLayout(new BorderLayout());
add(new TextArea(),BorderLayout.CENTER);
JPanel p = new JPanel();
p.setLayout(new FlowLayout(FlowLayout.CENTER));
p.add(new Button("OK"));
p.add(new Button("CANCEL"));
add(p, BorderLayout.SOUTH);
setVisible(true);
}
public static void main(String args[])
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
83
{
new Pan();
}
}
Component
1.ImageIcon
ImageIcon(String filename)
ImageIcon(URL url)
2.Label
JLabel class, you can display unselectable text and images.
Constructors-
JLabel(Icon i)
Label(Icon I , int align)
JLabel(String s)
JLabel(String s, Icon i, int align)
JLabel(String s, int align)
JLabel()
Algin => LEFT (default), CENTER, RIGHT, LEADING, or TRAILING.
Methods
Set or get the text displayed by the label.
void setText(String)
String getText()
public class JLabelDemo extends JFrame
{
public JLabelDemo()
{
super("Label Demo");
JLabel l=new JLabel("Enter value1");
add(l);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
84
}
public static void main(String[] args)
{
new JLabelDemo();
}
}
Using Image
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class JIconDemo extends JFrame
{
public JIconDemo()
{
super("Icon Demo");
ImageIcon img=new ImageIcon("c:water.jpg");
JLabel l=new JLabel(img);
add(l);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new JIconDemo();
}
}
3.Button
A Swing button can display both text and an image.
Constructors
JButton(Icon I)
JButton(String s)
JButton(String s, Icon I)
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
85
Methods
String getText()
void setText(String)
Event- ActionEvent
public class JButtonDemo extends JFrame
{
public JButtonDemo()
{
super("Button Demo");
JButton b=new JButton("ok");
add(b);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new JButtonDemo();
}
}
4.JTextField
Constructors
JTextField()
JTextField(String)
JTextField t=new JTextField(20);
add(t);
5.JPasswordField
Constructors
JPasswordField()
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
86
JPasswordField(String)
JPasswordField t=new JPasswordField(20);
add(t);
6.JTextArea
Represents a text area which can hold multiple lines of text
Constructors-
JTextArea (int row, int cols)
JTextArea (String s, int row, int cols)
JTextArea t=new JTextArea(20,30);
add(t);
Q. LayoutManagers
Def:The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout
managers.
Each container has a layout manager associated with it. To change the layout manager for
a container, use the setLayout() method.
Syntax
setLayout(LayoutManager obj)
The predefined managers are listed below:
1. FlowLayout
2.GridLayout
3. BoxLayout
4.CardLayout
5.GridBagLayout
1.FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow).
It is the default layout of applet or panel.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
87
Here are the constructors for FlowLayout:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
horz and vert follows:
specify the horizontal and vertical space left between components in
horz and vert, respectively.
e.g
setLayout(new FlowLayout(FlowLayout.LEFT));
b1=new JButton("1");
b2=new JButton("2");
add(b1);
add(b2);
2 BorderLayout
Border layout manager is the layout manager that divides the container into 5 regions
such as north,east,west,south,center..
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
88
BorderLayout( )
BorderLayout(int horz, int vert)
BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
void add(Component compObj, Object region);
e.g
setLayout(new BorderLayout(5,5));
b1=new JButton("SOUTH");
b2=new JButton("NORTH");
b3=new JButton("EAST");
b4=new JButton("WEST");
b5=new JButton("CENTER");
3.GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.
GridLayout( )
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
89
GridLayout(int numRows, int numColumns )
GridLayout(int numRows, int numColumns, int horz, int vert)
e.g
setLayout(new GridLayout(4,4));
4.GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or
along their baseline.
The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as
its display area. Each component associates an instance of GridBagConstraints. With the
help of constraints object we arrange component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine component's size.
GridBagLayout()
e.g
setLayout(new GridBagLayout());
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
90
5.CardLayout
CardLayout is the only layout class which can hold several layouts in it.
The card layout manager generates a stack of components, one on top of the other. The
first component that you add to the container will be at the top of the stack, and therefore
visible,and the last one will be at the bottom.
Constructor as follows
CardLayout( )
CardLayout(int horz, int vert)
5.BoxLayout
It Allows components to be arranged left-to-right or top-to-bottom in a container
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
91
NOTE:FlowLayout is the default layout for Panel,Applet. BorderLayout is
the default layout forFrame
Manually Position Components
setLayout(null);
e.g
setLayout(null);
b1=new JButton("OK");
b1.setLocation(25,50);
b1.setSize(60,40);
add(b1);
Check box
Constructors
JCheckBox(Icon i)
CheckBox(Icon i,booean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon I, boolean state)
Method
Void setSelected(boolean state)
String getText()
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
92
void setText(String s)
Boolean isSelected()
Event- ItemEvent
public class Chk extends JFrame implements ItemListener
{
JCheckBox ch1;
public Chk()
{
super("chk Demo");
setLayout(new FlowLayout(FlowLayout.LEFT));
ch1=new JCheckBox("red");
t1=new JTextField(20);
add(ch1);
ch1.addItemListener(this);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
if(ch1.isSelected())
{
String s=ch1.getText();
JOptionPane.showMessageDialog(this,"selected is ."+s);
}
else
JOptionPane.showMessageDialog(this,"not selected is.");
}
public static void main(String[] args)
{
new Chk();
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
93
Radio Button
Class- JRadioButton
Constructors
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, Boolean state)
JRadioButton()
To create a button group-
ButtonGroup()
Adds a button to the group, or removes a button from the group.
public class Border extends JFrame implements ItemListener
{
JRadioButton r1,r2,r3,r4;
public Border()
{
super("chk Demo");
setLayout(new FlowLayout(FlowLayout.LEFT));
r1=new JRadioButton("male");
r2=new JRadioButton("female");
t1=new JTextField(20);
ButtonGroup bg1=new ButtonGroup();
bg1.add(r1);
bg1.add(r2);
add(r1);
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
94
add(r2);
r1.addItemListener(this);
r2.addItemListener(this);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
if(r1.isSelected())
JOptionPane.showMessageDialog(this,"You are Male.");
else
if(r2.isSelected())
JOptionPane.showMessageDialog(this,"You are female.");
}
public static void main(String[] args)
{
new Border();
}
}
Combo Box
Class- JComboBox
Constructors- JComboBox()
Methods
Void addItem(Object)
Object getItemAt(int)
Object getSelectedItem()
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
95
int getItemCount()
Event- ItemEvent
public class Border extends JFrame implements ItemListener
{
JComboBox cb;
public Border()
{
super("chk Demo");
setLayout(new FlowLayout(FlowLayout.CENTER));
JComboBox cb=new JComboBox();
cb.addItem("red");
cb.addItem("yellow");
cb.addItem("pink");
add(cb);
cb.addItemListener(this);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
JComboBox ob=(JComboBox)e.getSource();
JOptionPane.showMessageDialog(this,"selected is ."+(String)ob.getSelectedItem());
}
public static void main(String[] args)
{
new Border();
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
96
List
Constructor- JList(ListModel)
List models-
1. SINGLE_SELECTION - Only one item can be selected at a time. When the user
selects an item, any previously selected item is deselected first.
2. SINGLE_INTERVAL_SELECTION- Multiple, contiguous items can be selected.
When the user begins a new selection range, any previously selected items are
deselected first.
3. MULTIPLE_INTERVAL_SELECTION- The default. Any combination of items can
be selected. The user must explicitly deselect items.
Methods
Boolean isSelectedIndex(int)
void setSelectedIndex(int)
void setSelectedIndices(int[])
void setSelectedValue(Object, boolean)
void setSelectedInterval(int, int)
int getSelectedIndex()
int getMinSelectionIndex()
int getMaxSelectionIndex()
int[] getSelectedIndices()
Object getSelectedValue()
Object[] getSelectedValues()
Event- ActionEvent
public class Cd extends JFrame
{
JList l;
public Cd()
{
super("chk Demo");
setLayout(new FlowLayout());
String[] s= { "green", "red"};
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
97
l = new JList(s);
add(l);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new Cd();
}
}
Tabbed Panes
A tabbed pane is a component that appears as a group of folders in a file cabinet. Each
folder has a title. When a user selects a folder, its contents become visible. Only one of
the folders may be selected at a time. Tabbed panes are commonly used for setting
configuration options.
The general procedure to use a tabbed pane in an applet is outlined here:
1. Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane. (The arguments to this method define
the title of the tab and the component it contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane in to the container.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo extends JFrame
{
public Demo()
{
//setLayout(new FlowLayout());
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("BCS", new BcsPanel());
jtp.addTab("BCA", new BcaPanel());
add(jtp);
setVisible(true);
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
98
}
class BcsPanel extends JPanel
{
BcsPanel()
{
add(new JButton("ok"));
add(new JButton("cancel"));
}
}
class BcaPanel extends JPanel
{
BcaPanel()
{
add(new JButton("yes"));
add(new JButton("no"));
}
}
public static void main(String args[])
{
new Demo();
}
}
JTable
A table is a component that displays rows and columns of data.
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and colHeads
is a one-dimensional array with the column headings.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
99
Steps
1. Create a JTable object.
2. Create a JScrollPane object. (The arguments to the constructor specify the table
and the policies for vertical and horizontal scroll bars.)
3. Add the table to the scroll pane.
4. Add the scroll pane into the container
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo extends JFrame
{
public Demo()
{
String[] colHeads = { "Name", "Phone", "Fax" };
final Object[][] data = {
{ "amol", "4567", "8675" },
{ "kiran", "7566", "5555" },
{ "sagar", "5634", "5887" },
{ "punit", "7345", "9222" },
{ "umesh", "1237", "3333" },
};
JTable table = new JTable(data, colHeads);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
add(jsp, BorderLayout.CENTER);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
100
JScrollPane
A scroll pane is a container that represents a small area to view other component. If the
component is larger than the visible area, scroll pane provides horizontal and/or vertical
scroll bars automatically for scrolling the components through the pane
JScrollPane()
JScrollPane(Component)
JScrollPane(vscroll, hscroll)
JScrollPane(Component, vscroll,hscroll)
HORIZONTAL_SCROLLBAR_ALWAYS
VERTICAL_SCROLLBAR_ALWAYS
HORIZONTAL_SCROLLBAR_AS_NEEDED
VERTICAL_SCROLLBAR_AS_NEEDED
e.g
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
Menu
Menus are composed of three hierarchical pieces. The menu bar contains the various
menus.
Creating Menus
You should build the menus before you display them. The typical order is:
1. Create a new MenuBar.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
101
2. Create a new Menu.
3. Add items to the Menu.
4. Add the Menu to the MenuBar.
5. If necessary repeat steps 2 through 4.
6. Add the MenuBar into the container
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Demo extends JFrame
{
public Demo()
{
JMenu fm = new JMenu("File");
fm.add(new JMenuItem("Open"));
fm.addSeparator( );
fm.add(new JMenuItem("Save"));
JMenu fe = new JMenu("Edit");
fe.add(new JMenuItem("Copy"));
fe.add(new JMenuItem("Cut"));
JMenuBar mb = new JMenuBar( );
mb.add(fm);
mb.add(fe);
setJMenuBar(mb);
setVisible(true);
}
public static void main(String args[])
{
new Demo();
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
102
Dialogs
message dialog
Displays a message to the user, usually accompanied by an OK button.
confirmation dialog
Ask a question and displays answer buttons, usually Yes, No, and Cancel.
input dialog
Asks the user to type in a string.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Dialog
{
public static void main(String args[])
{
JFrame f = new JFrame("Vision Academy");
JOptionPane.showMessageDialog(f, "You have mail.");
int result = JOptionPane.showConfirmDialog(null,
"Do you want to remove Windows now?");
String name = JOptionPane.showInputDialog(null,
"Please enter your name.");
}
}
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
103
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
104
Q.EVENT
Java has two types of events:
1. Low-Level Events: Low-level events represent direct communication from
user. A low level event is a key press or a key release, a mouse click, drag, move or
release,and so on. Following are low level events.
2. High-Level Events: High-level (also called as semantic events) events encapsulate the
meaning of a user interface component. These include following events.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
105
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
106
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
107
Q.Adapter Classes
An adapter class provides an empty implementation of all methods in an event
listener interface i.e this class itself write definition for methods which are present in
particular event listener interface.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
108
Suppose you want to use MouseClicked Event or method from MouseListener, if you do
not use adapter class then unnecessarily you have to define all other methods from
MouseListener such as MouseReleased, MousePressed etc.
But If you use adapter class then you can only define MouseClicked method and don’t
worry about other method definition because class provides an empty implementation of
all methods in an event listener interface.
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
Before Using Adapter Class
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame implements MouseListener
{
public Demo()
{
addMouseListener(this);
setVisible(true);
}
public void mouseClicked(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{
}
public void mouseExited(MouseEvent me)
{
}
public void mousePressed(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
109
{
}
public static void main(String args[])
{
new Demo();
}
}
After using Adapter Class
import java.awt.*;
import java.awt.event.*;
public class Demo extends Frame
{
public Demo()
{
setVisible(true);
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
System.out.println("mouse click");
}
});
}
public static void main(String args[])
{
new Demo();
}
}
Q.MVC Architecture(Model view controller)
MVC stands for Model View and Controller. It is a design pattern that separates the
business logic, presentation logic and data.
Controller acts as an interface between View and Model. Controller intercepts all the
incoming requests.
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
110
Model represents the state of the application i.e. data. It can also have business logic.
View represents the presentaion i.e. UI(User Interface).
Advantage of MVC (Model 2) Architecture
1. Navigation Control is centralized
2. Easy to maintain the large application
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
111
Applet
Applet(java.applet.Applet) is a special type of program that is embedded in the webpage
to generate the dynamic content. It runs inside the browser and works at client side.
Q.Life Cycle of applet
The Basic Applet Life Cycle
Born initialization
(Load Applet)
Start()
Stop()
Display()
stopped
Paint()
Start()
Destroyed end
BORN
RUNNING
IDLE
DEAD
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
112
1. Initialization state
Applet enters the initialization state when it is first loaded. This is achieved by calling
init() method of Applet Class. The applet is born. At this stage ,It may the following, if
required.
1. Create object needed by applet.
2. Set up initial values.
3. Load images or fonts.
4. Set up colors.
The initialization occurs only once in the applet’s life cycle. To provide any of the
behaviors mentioned above, it must override the init() method.
public void init()
{
---------------
//action
}
2. Running State
This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off
to other pages.
public void start()
{
---------------
//action
}
3. Idle or stopped state.
This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
public void stop()
{
---------------
//action
}
4.Dead state
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
113
An applet is said to be dead when it is removed from memory. This occurs
automatically by invoking the destroy() method when it quit the browser.
It override the destroy() method to clean up these resources.
public void destroy()
{
---------------
//action
}
5. Display State
Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser.
public void paint(Graphics g)
{
---------------
//action
}
import java.awt.*;
import java.applet.*;
public class AppletSkel extends Applet
{
// Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start() {
// start or resume execution
}
// Called when the applet is stopped.
public void stop() {
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
114
// suspends execution
}
/* Called when applet is terminated. This is the last
method executed. */
public void destroy() {
// perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g) {
// redisplay contents of window
}
}
The HTML APPLET Tag
The APPLET tag
< APPLET
[CODEBASE = appletURL]
CODE = appletClassFile
[ALT = alternateText]
[ARCHIVE = archiveFile]
[NAME = appletInstanceName]
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue />]
</APPLET>
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
115
How to run applet
1. compile the HelloWorldApplet.java program. i.e
C:javac HelloWorldApplet.java
import java.applet.Applet;
import java.awt.*;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}
2. Insert the HelloWorldApplet.class in the following HTML tag. And save HTML
file(Hello.html)
<html>
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
116
<body>
This is the applet:<P>
<applet code="HelloWorldApplet" width="150" height="50" name=”visionacademy”>
</applet>
</body>
</html>
3. Use appletviewer command .
C: appletviewer Hello.html
Or
import java.applet.Applet;
import java.awt.*;
/*
<applet code=" HelloWorldApplet" width=300 height=100>
</applet>
*/
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}
Compile
C: javac HelloWorldApplet.java
Run
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
117
C: appletviewer HelloWorldApplet.java
Simple Applet Display Methods
Use drawString( ), which is a member of the Graphics class.
It has the following general form:
void drawString(String message, int x, int y)
Difference between paint(),update(),repaint() methods
repaint() –> update() –> paint()
paint():This method holds instructions to paint this component. It shouldn't call this
method directly, It should call by using repaint().
public void paint(Graphics g)
{
}
Repaint():Repaint() method calls automatically update() method and in turn update()
method calls paint() method
Update():An update method is called on calling the repaint method. The default
implementation of the update() method clears the screen and calls the paint() method.
Background & Forground Color
void setBackground(Color newColor)
void setForeground(Color newColor)
Here, newColor specifies the new color. The class Color defines the constants shown
here that can be used to specify colors:
Color.black Color.magenta
Color.blue Color.orange
For example, this sets the background color to green and the text color to red:
Vision Academy
(9822506209/9823037693 http://www.visionacademe.com)
(SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET
Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY)
Java Note
118
setBackground(Color.green);
setForeground(Color.red);
/* A simple applet that sets the foreground and
background colors and outputs a string. */
import java.awt.*;
import java.applet.*;
/*
<applet code="Appletcolor" width=300 height=100>
</applet>
*/
public class Appletcolor extends Applet
{
String msg;
// set the foreground and background colors.
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";
}
}
PARAM Tag
To pass parameter or value to the applet using PARAM Tag
Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags between the
opening and closing APPLET tags. Inside the applet, you read the values passed through
the PARAM tags with the getParameter() method of the java.applet.Applet
class.
Java bcs 21_vision academy_final
Java bcs 21_vision academy_final
Java bcs 21_vision academy_final
Java bcs 21_vision academy_final
Java bcs 21_vision academy_final
Java bcs 21_vision academy_final
Java bcs 21_vision academy_final
Java bcs 21_vision academy_final
Java bcs 21_vision academy_final

More Related Content

What's hot

Use of Java™ Technology-Based Class Loaders to Design and Implement a Java P...
Use of Java™ Technology-Based Class Loaders  to Design and Implement a Java P...Use of Java™ Technology-Based Class Loaders  to Design and Implement a Java P...
Use of Java™ Technology-Based Class Loaders to Design and Implement a Java P...gustavoeliano
 
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...Edureka!
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaEdureka!
 
Java 9 Module System
Java 9 Module SystemJava 9 Module System
Java 9 Module SystemHasan Ünal
 
Introduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
Introduction to Loops in Java | For, While, Do While, Infinite Loops | EdurekaIntroduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
Introduction to Loops in Java | For, While, Do While, Infinite Loops | EdurekaEdureka!
 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers GuideDaisyWatson5
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Edureka!
 
java tutorial for beginner - Free Download
java tutorial for beginner - Free Downloadjava tutorial for beginner - Free Download
java tutorial for beginner - Free DownloadTIB Academy
 
Java course-in-mumbai
Java course-in-mumbaiJava course-in-mumbai
Java course-in-mumbaiUnmesh Baile
 
Java Certification Tutorial | Java Tutorial For Beginners | Java Training | E...
Java Certification Tutorial | Java Tutorial For Beginners | Java Training | E...Java Certification Tutorial | Java Tutorial For Beginners | Java Training | E...
Java Certification Tutorial | Java Tutorial For Beginners | Java Training | E...Edureka!
 
Support formation vidéo : OCA Java SE 8 Programmer (1Z0-808) (2)
Support formation vidéo : OCA Java SE 8 Programmer (1Z0-808) (2)Support formation vidéo : OCA Java SE 8 Programmer (1Z0-808) (2)
Support formation vidéo : OCA Java SE 8 Programmer (1Z0-808) (2)SmartnSkilled
 
Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersWhizlabs
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questionsRohit Singh
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPSrithustutorials
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Kernel Training
 

What's hot (20)

Use of Java™ Technology-Based Class Loaders to Design and Implement a Java P...
Use of Java™ Technology-Based Class Loaders  to Design and Implement a Java P...Use of Java™ Technology-Based Class Loaders  to Design and Implement a Java P...
Use of Java™ Technology-Based Class Loaders to Design and Implement a Java P...
 
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
 
Java 9 Module System
Java 9 Module SystemJava 9 Module System
Java 9 Module System
 
Introduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
Introduction to Loops in Java | For, While, Do While, Infinite Loops | EdurekaIntroduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
Introduction to Loops in Java | For, While, Do While, Infinite Loops | Edureka
 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers Guide
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
java tutorial for beginner - Free Download
java tutorial for beginner - Free Downloadjava tutorial for beginner - Free Download
java tutorial for beginner - Free Download
 
Java course-in-mumbai
Java course-in-mumbaiJava course-in-mumbai
Java course-in-mumbai
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Java Certification Tutorial | Java Tutorial For Beginners | Java Training | E...
Java Certification Tutorial | Java Tutorial For Beginners | Java Training | E...Java Certification Tutorial | Java Tutorial For Beginners | Java Training | E...
Java Certification Tutorial | Java Tutorial For Beginners | Java Training | E...
 
Support formation vidéo : OCA Java SE 8 Programmer (1Z0-808) (2)
Support formation vidéo : OCA Java SE 8 Programmer (1Z0-808) (2)Support formation vidéo : OCA Java SE 8 Programmer (1Z0-808) (2)
Support formation vidéo : OCA Java SE 8 Programmer (1Z0-808) (2)
 
Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed Answers
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPS
 
Java Programming - 01 intro to java
Java Programming - 01 intro to javaJava Programming - 01 intro to java
Java Programming - 01 intro to java
 
Class loaders
Class loadersClass loaders
Class loaders
 
Java Class Loading
Java Class LoadingJava Class Loading
Java Class Loading
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
 
Java Classloaders
Java ClassloadersJava Classloaders
Java Classloaders
 

Similar to Java bcs 21_vision academy_final

Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction AKR Education
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdfVisionAcademyProfSac
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdfbhagyashri686896
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
 
Ajava final(sachin sir9822506209)_vision_academy_21
Ajava final(sachin sir9822506209)_vision_academy_21Ajava final(sachin sir9822506209)_vision_academy_21
Ajava final(sachin sir9822506209)_vision_academy_21SachinZurange
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxPoonam60376
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)Prof. Erwin Globio
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java CertificationVskills
 
Certified Core Java Developer
Certified Core Java DeveloperCertified Core Java Developer
Certified Core Java DeveloperNarender Rana
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdfamitbhachne
 

Similar to Java bcs 21_vision academy_final (20)

OOPS JAVA.pdf
OOPS JAVA.pdfOOPS JAVA.pdf
OOPS JAVA.pdf
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22.pdf
 
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdfVision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
Vision_Academy_Ajava_final(sachin_sir9823037693)_22 (1).pdf
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
java basic .pdf
java basic .pdfjava basic .pdf
java basic .pdf
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Ajava final(sachin sir9822506209)_vision_academy_21
Ajava final(sachin sir9822506209)_vision_academy_21Ajava final(sachin sir9822506209)_vision_academy_21
Ajava final(sachin sir9822506209)_vision_academy_21
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)JAVA Object Oriented Programming (OOP)
JAVA Object Oriented Programming (OOP)
 
DAY_1.1.pptx
DAY_1.1.pptxDAY_1.1.pptx
DAY_1.1.pptx
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java Certification
 
Certified Core Java Developer
Certified Core Java DeveloperCertified Core Java Developer
Certified Core Java Developer
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 

Recently uploaded

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 

Recently uploaded (20)

TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

Java bcs 21_vision academy_final

  • 1. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 1 C++ JAVA C++ is platform- dependent. Java is platform-independent. C++ is mainly used for system programming. Java is mainly used for application programming. It is widely used in window, web-based,mobile applications. C++ supports goto statement. Java doesn't support goto statement. C++ supports multiple inheritance. Java doesn't support multiple inheritance through class. It can be achieved by interfaces in java. C++ supports operator overloading. Java doesn't support operator overloading. C++ supports pointers. Java supports pointer internally. But you can't write the pointer program in java. It means java has restricted pointer support in java. C++ uses compiler only. Java uses compiler and interpreter both. C++ supports both call by value and call by reference. Java supports call by value only. C++ supports structures and unions. Java doesn't support structures and unions. C++ doesn't have built-in support for threads. Java has built-in thread support. C++ doesn't support documentation comment. Java supports documentation comment (/** ... */) to create documentation for java source code. C++ supports virtual keyword . Java has no virtual keyword. methods are virtual by default.
  • 2. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 2 Q. Features of Java 1.Simple Java is very easy to learn and its syntax is simple, clean and easy to understand 2. Object-oriented Java is Object-oriented programming language. Everything in Java is an object. Object- oriented means we organize our software as a combination of different types of objects that incorporates both data and behaviour. Feature of OOPs are: 1. Object 2. Class 3. Inheritance 4. Polymorphism 5. Abstraction 6. Encapsulation 3.Platform Independent Java is platform independent because it is different from other languages like C, C++ etc. which are compiled into platform specific machines while Java is a write once, run anywhere language. 4. Secured Java is best known for its security C++ doesn't support >>> operator. Java supports right shift >>> operator C++ Support delete operatore Java doesn’t support delete operator. Java support garbage collection C++support destructor Java doen’t support destructor
  • 3. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 3 5. Robust Robust simply means strong. Java is robust because: o It uses strong memory management. o There are lack of pointers that avoids security problem. o There is automatic garbage collection in java. o There is exception handling and type checking mechanism in java. All these points makes java robust. 6.Architecture-neutral Java is architecture neutral because there is no implementation dependent features e.g. size of primitive types is fixed. In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures. 7.Portable Java is portable because it facilitates you to carry the java bytecode to any platform. 8.High-performance Java support for multithreading,bytcode etc 9.Distributed Java is distributed because it facilitates us to create distributed applications in java. RMI and EJB are used for creating distributed applications. It may access files by calling the methods from any machine on the internet. 10.Multi-threaded It support multiple thread. First Java Program class Sample
  • 4. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 4 { public static void main(String args[]) { System.out.println("Hello TY"); } } Public It is an Access Modifier, which defines who can access this Method. Public means that this Method will be accessible by any Class(If other Classes are able to access this Class.). Static Is a keyword which identifies the class related thing. This means the given Method or variable is not instance(object) related but Class related. It can be accessed without creating the instance of a Class. void Is used to define the Return Type of the Method. It defines what the method can return. main Is the name of the Method. This Method name is searched by JVM as a starting point for an application with a particular signature only. String args[] It is the parameter to the main Method.(Command Line argument) Q. System.out.println meaning ▪ System is a Class ▪ out is a member of System class & object of PrintStream class ▪ println() is a method
  • 5. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 5 Q. Compilation and Execution of a Java Program(How To compile & interpreter execution in java program) 1.Compilation(Javac command) The source ‘.java’ file is passed through the compiler, which then encodes the source code into a machine independent encoding, known as Bytecode. The content of each class contained in the source file is stored in a separate ‘.class’ file. 2.Execution(using java) The class files generated by the compiler are independent of the machine or the OS, which allows them to be run on any system. To run, the main class file (the class that contains the method main) is passed to the JVM, and then goes through three main stages before the final machine code is executed. 3.JVM: Defintion:A Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a Java program. Its ontain as follows 4.Class Loader
  • 6. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 6 Definition:The class loader is a used for loading class files. 5.Bytecode Verifier After the bytecode of a class is loaded by the class loader, it has to be inspected by the bytecode verifier, whose job is to check that the instructions don’t perform damaging actions. 6.Just-In-Time Compiler This is the final stage encountered by the java program, and its job is to convert the loaded bytecode into machine code. Q.JAVA TOOLS java: Starts a Java application. javac: Reads Java class and interface definitions and compiles them into bytecode and create class files. javadoc: Generates HTML pages of API documentation from Java source files. javah: Generates C header and source files from a Java class. javap: Disassembles one or more class files. jdb: Finds and fixes bugs in Java platform programs appletviewer: Runs applets outside of a web browser. Q.Java Comments 1.Java Single Line Comment The single line comment is used to comment only one line. //This is single line comment
  • 7. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 7 2. Java Multi Line Comment The multi line comment is used to comment multiple lines of code. /* This is multi line comment */ 3. Java Documentation Comment The javadoc tool uses to create documentation comment. /** This is documentation comment */ Q.Data type in java
  • 8. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 8 Data Type Default Value Default size boolean False 1 bit Char 'u0000'(Unicode) 2 byte Byte 0 1 byte Short 0 2 byte Int 0 4 byte Long 0L 8 byte Float 0.0f 4 byte Double 0.0d 8 byte Q.Java Operator Operator Type Category Precedence Unary Postfix expr++ expr-- Prefix ++expr --expr +expr - expr ~ !
  • 9. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 9 Arithmetic Multiplicative * / % Additive + - Shift Shift << >> >>> Relational Comparison < > <= >= instanceof Equality == != Bitwise bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | Logical logical AND && logical OR || Ternary Ternary ? : Assignment Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>= Q.Control Strcture:
  • 10. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 10 1.Contional Statement 1. If Statement Syntax if(condition) { //code to be executed } e.g int age=20; if(age>18){ { System.out.print("Age is greater than 18"); } 2. If-else Statement Syntax if(condition) { //code if condition is true } Else { //code if condition is false }
  • 11. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 11 e.g int n=5; if(n>0) { System.out.print("No is positive"); } else { System.out.print("No is negative"); } 3. Nested If-else statement Syntax if(condition1) { //code to be executed if condition1 is true } else if(condition2) { //code to be executed if condition2 is true } else if(condition3) { //code to be executed if condition3 is true } Else
  • 12. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 12 { //code to be executed if all the conditions are false } e.g int marks=65; if(marks>=70) { System.out.println("A"); } else if(marks>=60) { System.out.println("B"); } else if(marks>=50) { System.out.println("C "); } else if(marks>=40) { System.out.println("D"); } Else { System.out.println("fail"); }
  • 13. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 13 4. Switch case statement Syntax switch(expression) { case value1: //code to be executed; break; case value2: //code to be executed; break; ...... default: code to be executed if all cases are not matched; } e.g int number=20; switch(number) { case 10: System.out.println("10"); break; case 20: System.out.println("20"); break; case 30: System.out.println("30"); break; default:System.out.println("Not in 10, 20 or 30"); }
  • 14. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 14 Loop 1.while Syntax while (condition) { //code to be executed Increment / decrement statement } e.g int i=1 while(i<=3) { System.out.println(i); i++; } 2. Do-while Syntax do { //code to be executed Increment / decrement statement } while (condition); e.g int i=1 do { System.out.println(i); i++; }while(i<=3);
  • 15. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 15 3. for loop Syntax for(initialization; condition; increment/decrement) { //statement or code to be executed } e.g for(i=1;i<=3;i++) { System.out.println(i); } Q.Labelled break statement Labeled break statement terminated loop of specified label.
  • 16. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 16 first: for( int i = 1; i < 5; i++) { for(int j = 1; j < 3; j ++ ) { System.out.println(“ j = " +j); if ( i == 2) break first; } } } Q. Labeled Continue statement Labeled Continue statement skip loop of specified label.
  • 17. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 17 e.g label: for (int i = 1; i < 3; ++i) { for (int j = 1; j < 5; ++j) { if (j == 2) continue label; System.out.println("i = " + i + "; j = " + j); } } Q.Accepting input from user & display it
  • 18. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 18 import java.util.*; public class Demo { public static void main(String[] args) { try { Scanner scan = new Scanner(System.in); System.out.print("Enter integer value"); int a1= scan.nextInt(); System.out.print("Enter float value"); float a2 = scan.nextFloat(); System.out.print("Enter name"); String a3 = scan.next(); System.out.println("Integer value is "+a1); System.out.println("float value is "+a2); System.out.println("string value is "+a3); } catch(Exception e) { System.out.println(“error”+e); } } } Q. Final keyword It is used dealered constant variable(Its value canot changed value of variable). e.g final float pi=3.14f;
  • 19. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 19 Q.Array An array is a collection of similar data types. 1.Single Dimensional Array in java Syntax Declaration of 1d array dataType arr[ ]; Instantiation of an Array in java arr=new datatype[size]; e.g int arr[ ] arr=new int[4]; OR Delcration & Instantiation of an Array in java datatype arr[]=new datatype[size]; e.g int arr[]=new int[4]; import java.util.*; class Sample { public static void main(String args[]) { try { Scanner scan = new Scanner(System.in); System.out.println("Enter limit"); int n= scan.nextInt(); int arr[]=new int[n];
  • 20. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 20 int i; for(i=0;i<arr.length;i++) { System.out.println("Enter data"); arr[i]= scan.nextInt(); } System.out.println("display is"); for(i=0;i<arr.length;i++) { System.out.println(arr[i]); } } catch(Exception e) { } } } Initialization 1d array e.g int a[]={33,3,4,5}; 2.Multidimensional array in java Syntax Declaration of 2d array dataType arr[ ][ ]; Instantiation of an Array in java arr=new datatype[rowsize][colsize]; e.g int arr[ ][ ] arr=new int[2][2]; OR
  • 21. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 21 Delcration & Instantiation of an Array in java datatype arr[ ][ ]=new datatype[rowsize][colsize]; e.g int arr[][]=new int[2][2]; import java.util.*; class Sample { public static void main(String args[]) { try { Scanner scan = new Scanner(System.in); System.out.println("Enter row limit"); int r= scan.nextInt(); System.out.println("Enter col limit"); int c= scan.nextInt(); int arr[][]=new int[r][c]; int i,j; for(i=0;i<r;i++) { for(j=0;j<c;j++) { System.out.println("Enter data"); arr[i][j]=scan.nextInt(); } } System.out.println("display is"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { System.out.println(arr[i][j]); } } }
  • 22. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 22 catch(Exception e) { } } } Initialization 2d array e.g int a[][]={{1,2},{3,4}}; Q.class & object A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. import java.util.*; class Student { public int rno; public String name; public void read() throws Exception { Scanner scan = new Scanner(System.in); System.out.println("Enter rollno"); rno=scan.nextInt(); System.out.println("Enter name"); name=scan.next(); } public void display() { System.out.println("rollno"+rno); System.out.println("name"+name); } }
  • 23. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 23 class Sample { public static void main(String args[]) { try { Student s=new Student(); s.read(); s.display(); } catch(Exception e) { } } } Instance Member: Those member declared inside the class known as Instance Member. Instance Method:Those member declared inside the class known as Instance method To creation of object kown as instantiation Q. Access Modifiers in java Access Modifier within class within package outside package by subclass only outside package Private Y N N N Default(friendly) Y Y N N Protected Y Y Y N Public Y Y Y Y
  • 24. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 24 There are 4 types of java access modifiers: 1. private 2. default(friendly) 3. protected 4. public 1.private modifier The private access modifier is accessible only within class. class A { private int data=40; private void msg() { System.out.println("Hello java"); } } public class Sample { public static void main(String args[]) { A obj=new A(); System.out.println(obj.data);//Compile Time Error obj.msg();//Compile Time Error } } 2.public modifier The public access modifier is accessible everywhere. It has the widest scope among all other modifiers. class A { public int data=40; public void msg() { System.out.println("Hello java"); } }
  • 25. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 25 public class Sample { public static void main(String args[]) { A obj=new A(); System.out.println(obj.data); obj.msg(); } } 3.default access modifier If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package class A { int data=40; void msg() { System.out.println("Hello java"); } } 4.protected access modifier The protected access modifier is accessible within package and outside the package but through inheritance only class A { protected int data=40; protected void msg() { System.out.println("Hello java"); } }
  • 26. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 26 Q. USE OF ARRAY OF OBJECT import java.util.*; class Student { public int rno; public String name; public void read() throws Exception { Scanner scan = new Scanner(System.in); System.out.println("Enter rollno"); rno=scan.nextInt(); System.out.println("Enter name"); name=scan.next(); } public void display() { System.out.println("rollno"+rno); System.out.println("name"+name); } } class Sample { public static void main(String args[]) { try { Scanner scan = new Scanner(System.in); System.out.println("Enter limit"); int n=scan.nextInt(); Student s[]=new Student[n]; int i; for(i=0;i<n;i++) { s[i]=new Student(); s[i].read(); } System.out.println("Display is"); for(i=0;i<n;i++) {
  • 27. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 27 s[i].display(); } } catch(Exception e) { } } } Q. Constructor A constructor in Java is a block of code similar to a method that's called when a object is created. 1.non parameterized constructor A constructor that has no parameter is known as default constructor. If we don’t define a constructor in a class, then compiler creates default constructor(with no arguments) for the class. class Student { public int rno; public String name; Student() { rno=1; name=”om” } } class Sample { public static void main(String args[]) { try { Student s=new Student(); s.read(); s.display(); }
  • 28. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 28 catch(Exception e) { } } } 2.Parameterized Constructor: A constructor that has parameters is known as parameterized constructor. class Student { public int rno; public String name; Student(int r,String s) { rno=r; name=s; } } class Sample { public static void main(String args[]) { try { Student s=new Student(1,”om”); s.read(); s.display(); } catch(Exception e) { } } } Q. Garbage Collector • Java doesnot support delete operator • Garbage Collector is a program that manages memory automatically wherein de- allocation of objects is handled by Java .
  • 29. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 29 • In the Java programming language, dynamic allocation of objects is achieved using the new operator. An object once created uses some memory and the memory remains allocated till there are references for the use of the object.When there are no references to an object, it is assumed to be no longer needed, and the memory, occupied by the object can be reclaimed. There is no explicit need to destroy an object. Java handles the de-allocation automatically.The technique is known as Garbage Collection Q.Finalize() method • Java doesnot support destructor • Finalize() is used to perform clean up processing just before object is garbage collected. • if an object is holding some non-java resource such as a file handle or window character font, then it may want to make sure these resources are freed before an object is destroyed. To handle such situations, java provides a mechanism called finalization. By using finalization, It can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. • Finalize() method added any class. protected void finalize() { // finalization code here } The keyword protected is a specifier that prevents access to finalize() by code defined outside its class.
  • 30. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 30 Q.THIS keyword This is a reference variable that refers to the current object. Usage 1. this can be used to refer current class instance variable. 2. this can be used to invoke current class method (implicitly) 3. this() can be used to invoke current class constructor. 4. this can be passed as an argument in the method call. 5. this can be passed as argument in the constructor call. 6. this can be used to return the current class instance from the method. class Student { public int rno; public String name; Student(int rno,String name) { this->rno=rno; this->name=name; } } Q.Static variable Static variable in Java is variable which belongs to the class(not balong instance or object) and initialized only once at the start of the execution. • It is a variable which belongs to the class and not to object(instance) • Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables • A single copy to be shared by all instances of the class • A static variable can be accessed directly by the class name and doesn’t need any object
  • 31. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 31 Syntax <class-name>.<variable-name> Q. Static Method Static method in Java is a method which belongs to the class and not to the object. A static method can access only static data. • It is a method which belongs to the class and not to the object(instance) • A static method can access only static data. It can not access non-static data (instance variables) • A static method can call only other static methods and can not call a non-static method from it. • A static method can be accessed directly by the class name and doesn’t need any object • A static method cannot refer to "this" or "super" keywords in anyway Syntax <class-name>.<method-name> class Sample { static int age=30; static void disp() { System.out.println("Age is: "+age); } public static void main(String args[]) { System.out.println("Age is: "+Sample.age); Sample.disp(); } } Q.Static block Static block is used for initializing the static variables.This block gets executed when the class is loaded in the memory
  • 32. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 32 class Sample { static int age; static { System.out.println("static block"); age=30; } public static void main(String args[]) { System.out.println("Age is: "+Sample.age); } } Q.Inheritance Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class). extends is the keyword used to inherit the properties of a class. Syntax class Super { ..... ..... } class Sub extends Super { ..... ..... }
  • 33. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 33 Types of inheritance 1.Single inheritance: Single inheritance have only one base class known as Single Inheritance. class A { void dispA() { System.out.println("class A"); } } class B extends A { void dispB() { System.out.println("class B"); } } class Inh { public static void main(String args[]) { B ob=new B(); ob.dispA(); ob.dispB(); } } Constructor 1.non parametrized constructor class A {
  • 34. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 34 A() { System.out.println("class A"); } } class B extends A { B() { System.out.println("class B"); } } class Inh { public static void main(String args[]) { B ob=new B(); } } 2.paramerized constructor Q.Super keyword The super keyword in java is a reference variable which is used to refer immediate parent class object. Use of super 1.super() can be used to invoke immediate parent class constructor. class A { int a; A(int a1) { a=a1; System.out.println(a); } } class B extends A {
  • 35. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 35 int b; B(int a1,int b1) { super(a1); b=b1; System.out.println(b); } } class Inh { public static void main(String args[]) { B ob=new B(1,2); } } 2. It can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields. class A { int a=1; } class B extends A { int a=2; void disp() { System.out.println(a); System.out.println(super.a); } } class Inh { public static void main(String args[]) { B ob=new B(); ob.disp(); } }
  • 36. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 36 3. The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class(method overiding). class A { void disp() { System.out.println("class A"); } } class B extends A { void disp() { super.disp(); System.out.println("class B"); } } class Inh { public static void main(String args[]) { B ob=new B(); ob.disp(); } } 2.Multilevel inheritance: When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent classes, such inheritance is called Multilevel Inheritance class A { void dispA()
  • 37. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 37 { System.out.println("class A"); } } class B extends A { void dispB() { System.out.println("class B"); } } class C extends B { void dispC() { System.out.println("class C"); } } class Inh { public static void main(String args[]) { C ob=new C(); ob.dispA(); ob.dispB(); ob.dispC(); } } 3 Hierachical inheritance: When more than one classes are derived from a single base class, such inheritance is known asHierarchical Inheritance class A {
  • 38. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 38 void dispA() { System.out.println("class A"); } } class B extends A { void dispB() { System.out.println("class B"); } } class C extends A { void dispC() { System.out.println("class C"); } } class Inh { public static void main(String args[]) { B ob1=new B(); ob1.dispA(); ob1.dispB(); C ob2=new C(); ob2.dispA(); ob2.dispC(); } } Function overloading Definition:function Overloading is a feature that allows a class to have more than one method having the same name. class A {
  • 39. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 39 void disp(int a) { System.out.println(a); } void disp() { int b=2; System.out.println(b); } } class Inh { public static void main(String args[]) { A ob =new A(); ob.disp(2); ob.disp(); } } Function overriding If subclass (child class) has the same method as declared in the parent class in same prototype, it is known as method overriding in java class A { void disp() { System.out.println("class A"); } } class B extends A { void disp() { super.disp(); System.out.println("class B"); } } class Inh
  • 40. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 40 { public static void main(String args[]) { B ob=new B(); ob.disp(); } } Q.Abstract class Definition:An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed. abstract method:A method that is declared as abstract and does not have implementation (no body)is known as abstract method abstract class A { abstract void disp(); } class B extends A { void disp() { System.out.println("class b"); } } class Inh { public static void main(String args[]) { B ob =new B(); ob.disp(); } } abstract class Shape { abstract void draw(); } class Rectangle extends Shape
  • 41. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 41 { void draw() { System.out.println("drawing rectangle"); } } class Circle1 extends Shape { void draw() { System.out.println("drawing circle"); } } class Test { public static void main(String args[]) { Shape s1=new Circle1(); s1.draw(); Shape s2=new Rectangle(); s2.draw(); } } Q.Need of interface(Why java doenot support muiliple inheritance) 1.Diamond Problem: In above diag there is every chance of multiple properties of multiple objects with the same name available to the sub class object with same priorities leads for the ambiguity. Such problem kown as diamond problem
  • 42. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 42 2. Simplicity – Multiple inheritance is not supported by Java using classes , handling the complexity that causes due to multiple inheritance is very complex. Q.Interface Defintion:An interface in java is a blueprint of a class. It has static constants(final )variables and abstract methods only. Syntax interface <interface_name> { // declare constant fields // declare methods that abstract // by default. } Class classname implements interface name { //implemts abstract methods } e.g interface A { void disp(); } class B implements A { public void disp() { System.out.println("class b"); } } class Inh
  • 43. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 43 { public static void main(String args[]) { B ob =new B(); ob.disp(); } } Feature • All of the methods in an interface are abstract. • It can’t instantiate an interface in java • It contains fields in an interface must be declared both static and final. • An interface is not extended by a class; it is implemented by a class by using implements keyword. • An interface can extend multiple interface • All methods in an interface are implicitly public and abstract Q.Possible form of interface
  • 44. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 44 2. 3.
  • 45. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 45
  • 46. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 46 abstract class Interface 1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance. 3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables. 4) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. 5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface. 6) An abstract class can extend another Java class and implement multiple Java interfaces. An interface can extend another Java interface only. 7) A Java abstract class can have class members like private, protected, etc. Members of a Java interface are public by default. 8)Example: abstract class Shape { abstract void draw(); } Example: interface Shape { void draw(); } Q.Nested Class The Java programming language allows you to define a class within another class. Such a class is called a nested class There are 2 type 1. Static nested class(static inner class) 2. Non static nested class(inner class)
  • 47. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 47 Static nested class(static inner class) Non static nested class(inner class) 1.A outer class contain static class is called Nested class or static Inner class. A outer class contain non static class is called Inner class. 2. Nested static class doesn’t need reference of Outer class Non Nested static class does need reference of Outer class 3. Nested static class cannot access non- static members of the Outer class. It can access only static members of Outer class Inner class(or non-static nested class) can access both static and non-static members of Outer class public class Outer { int i = 100; static int j=200; static class Inner { int v = 20; void disp() { System.out.println(j); System.out.println(v); } } public static void main(String[] args) { Outer out = new Outer(); Inner inb = new Inner(); inb.disp(); } } public class Outer { int i = 100; static int j=200; class Inner { int v = 20; void disp() { System.out.println(i); System.out.println(j); System.out.println(v); } } public static void main(String[] args) { Outer out = new Outer(); Inner inb = out.new Inner(); inb.disp(); } } Q.Anonymous Inner Class A class that have no name is known as anonymous inner class is known as Anonymous inner class.
  • 48. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 48 It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways: 1.Class (may be abstract or concrete). abstract class Person { abstract void eat(); } class TestAnonymousInner { public static void main(String args[]) { Person p=new Person() { void eat(){System.out.println("nice fruits");} }; p.eat(); } } 2.Using Interface interface Eatable { void eat(); } class TestAnnonymousInner1 { public static void main(String args[]) { Eatable e=new Eatable(){ public void eat() { System.out.println("nice fruits"); } }; e.eat(); } }
  • 49. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 49 Q.Object Cloneing Object cloning refers to creation of exact copy of an object. It creates a new instance of the class of current object and initializes all its fields with exactly the contents of the corresponding fields of this object. Syntax protected Object clone() throws CloneNotSupportedException class Test2 implements Cloneable { int a; public Object clone() throws CloneNotSupportedException { return super.clone(); } } public class Main { public static void main(String args[]) throws CloneNotSupportedException { Test2 t1 = new Test2(); t1.a = 10; Test2 t2 = (Test2)t1.clone(); System.out.println(t2.a); } }
  • 50. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 50 Packages Def:Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces Built-in Packages 1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported. 2) java.io: Contains classed for supporting input / output operations. 3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations. 4) java.applet: Contains classes for creating Applets. 5) java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc). 6) java.net: Contain classes for supporting networking operations. User-defined packages The following steps are creating user defined packages 1. Declare the package at the beginning of a file using following form package packagename; e.g package comp; 2. Create directory & its name same as package name 3. Define a class &added in the directory. 4. Compile the class file 5. Accessing package Following ways to access the package
  • 51. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 51 1.import package.*: all the classes and interfaces of this package will be accessible but not subpackages. 2.packagename.classname: package.classname then only declared class of this package will be accessible The import keyword is used to make the classes and interface of another package accessible to the current package package comp; public class Bcs { Public void show() { System.out.println(“show in bcs”); } } import comp.*; class Main { public static void main(String args[]) { Bcs ob=new Bcs(); ob.show(); } } Q.Static import It access the static member without class name. import static java.lang.System.out; public class HelloWorld { public static void main(String[] args) { out.println("Hello World!"); } }
  • 52. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 52 Q.Wrapper class Definition:It is mechanism to convert primitive data type into object Autoboxing Converts primitive data type into object called as autoboxing Unboxing converts object into primitive data type called as unboxing Primitive Type Wrapper class boolean Boolean char Character byte Byte short Short int Integer long Long float Float double Double 1.To convert primitive data type into object 1.int i=2 Integer ival=new Integer(i); 2.float f=2.5f; Float fval=new Float(f); 2.To convert object into primitive data type using typeValue() method 1. int i=ival.intValue(); 2. float f=fval.floatValue(); 3.To convert number into string by using toString() method
  • 53. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 53 1. int i=2; String s=Integer.toString(i); 2 float f=2.5f; String s=Float.toString(f); 3.To convert string into numeric object by using valueOf() method 1. Integer ival=Integer.ValueOf(“4”); 2. Float fval=Float.ValueOf(“1.5”); 4.To convert numeric string into primitive datatyoe using parse method 1. int i=Integer.parseInt(“3”); 2. float f=Float.parseFloat(“2.5”); JAR(Java Archive File) JAR (Java Archive) is a package file format typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one file to distribute application software or libraries on the Java platform. Creating JAR File jar cf jar-filename input-files The c option indicates that you wish to create a jar and the f option indicates that output should be sent to a file, jar-filename is the name of the resulting Jar file and input-files are the files you wish to include.
  • 54. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 54 Mainfest File The Jar file automatically adds a manifest file to the jar file, the file is always in a directory named META-INF and file is named MANIFEST.MF.This file contains information about the jar file.
  • 55. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 55 String and Stringbuffer The java.lang package contains two string classes String and Stringbuffer String class A combination of character is a string. Q.Possible String Constructors 1.String(); =>Empty Constructor 2.String(char chars[ ]) 3.String(char chars[ ], int startIndex, int numChars) 4.String(String strObj) E.g class MakeString { public static void main(String args[]) { char c[] = {'J', 'a', 'v', 'a'}; String s1 = new String(c); String s2 = new String(s1); String s = new String(c, 1, 2); System.out.println(s1); System.out.println(s2); } } The output from this program is as follows: Java Java ava
  • 56. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 56 Q.String Methods 1.Length() The length of a string is the number of characters that it contains. int length( ) char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length()); 2.String Concatenation Using + operations. For example, the following fragment concatenates three strings: String age = "9"; String s = "He is " + age + " years old."; System.out.println(s); This displays the string “He is 9 years old.” 3.toString( ) method Syntax String toString( ) The toString() method returns the string representation of the object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output in the form of string. class Student { int rollno; String name; Student(int r, String s) { rollno=r; name=s;
  • 57. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 57 } public String toString() { return rollno+" "+name+; } public static void main(String args[]) { Student s1=new Student(101,"vision"); System.out.println(s1);//compiler writes here s1.toString() } } Character Extraction 1.charAt( ) To extract a single character from a String. char charAt(int where) char ch; String s=”abc”; ch = s.charAt(1); assigns the value “b” to ch. Q. String Comparison 1.equals( ) and equalsIgnoreCase( ) To compare two strings for equality, use equals( ). It returns true if the strings contain the same characters in the same order, and false otherwise. It has this general form:
  • 58. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 58 boolean equals(String str) => The comparison is case-sensitive. boolean equalsIgnoreCase(String str)=> The comparison is not case-sensitive. String s1 = "Hello"; String s2 = "HELLO"; If(s1.equals(s2)) System.out.println(“equals”); Else System.out.println(“not equals”); If(s1.equalsIgnoreCase(s4)) System.out.println(“equals”); Else System.out.println(“not equals”); 2.startsWith( ) and endsWith( ) boolean startsWith(String str) boolean endsWith(String str) String s="Foobar" s.endsWith("bar") s.startsWith("Foo") are both true. 3.equals( ) Versus == The equals( ) method compares the characters inside a String object. The == checks to see if the 2 object names are basically references to the same memory location. // equals() vs = = String s1 = "Hello"; String s2 = new String(s1); if(s1.equals(s2)) System.out.println(“equals”); Else
  • 59. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 59 System.out.println(“not equals”); if(s1==s2) System.out.println(“equals”); Else System.out.println(“not equals”); String obj1 = new String("xyz"); // now obj2 and obj1 reference the same place in memory String obj2 = obj1; if(obj1 == obj2) System.out.printlln("TRUE"); else System.out.println("FALSE"); 4.compareTo( ) It has this general form: int compareTo(String str) Here, str is the String being compared with the invoking String. The result of the comparison is returned and is interpreted as shown here: Value Meaning Less than zero The invoking string is less than str. Greater than zero The invoking string is greater than str. Zero The two strings are equal. e.g String s1=”hello” int k=s1.compareTo(“hello”) o/p 0 Substring():It return substring String substring(int startIndex) String substring(int startIndex, int endIndex)
  • 60. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 60 1.Concat( ) String concat(String str) String s1 = "one"; String s2 = s1.concat("two"); puts the string “onetwo” into s2. 2.replace( ) The replace( ) method replaces all occurrences of one character in the invoking string with another character. String replace(char original, char replacement) String s1=”hello” String s = s1.replace('l', 'w'); Changing the Case of Characters The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. The toUpperCase( ) method converts all the characters in a string from lowercase to uppercase. Sring toLowerCase( ) String toUpperCase( ) String s = "This is a test."; String upper = s.toUpperCase(); String lower = s.toLowerCase(); System.out.println("Uppercase: " + upper); System.out.println("Lowercase: " + lower);
  • 61. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 61 2.StringBuffer • A string buffer is mutable(Once the string object is creatred,the object can be changed). StringBuffer Constructors StringBuffer( ) StringBuffer(int size) StringBuffer(String str) 1.append( ) The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. It has overloaded versions for all the built-in types and for Object. Here are a few of its forms: StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj) int a = 42; StringBuffer sb = new StringBuffer(40); sb = sb.append("a = "). sb = sb.append(a). System.out.println(sb); 2.insert( ) The insert( ) method inserts one string into another. These are a few of its forms: StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch)
  • 62. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 62 StringBuffer insert(int index, Object obj) StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb); The output of this example is shown here: I like Java! 3.reverse( ) You can reverse the characters within a StringBuffer object using reverse( ) StringBuffer reverse( ) StringBuffer s = new StringBuffer("abcdef"); s.reverse(); System.out.println(s); 4.delete( ) and deleteCharAt( ) StringBuffer delete(int startIndex, int endIndex) StringBuffer deleteCharAt(int loc) StringBuffer sb = new StringBuffer("This is a test."); sb.delete(4, 7); System.out.println("After delete: " + sb); sb.deleteCharAt(0); System.out.println("After deleteCharAt: " + sb); The following output is produced: After delete: This a test. After deleteCharAt: his a test. 5.replace( ) StringBuffer replace(int startIndex, int endIndex, String str) StringBuffer sb = new StringBuffer("This is a test."); sb.replace(5, 7, "was"); System.out.println("After replace: " + sb); Here is the output:
  • 63. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 63 After replace: This was a test. STRING STRINGBUFFER The length of the String object is fixed. The length of the StringBuffer can be increased. String object is immutable. StringBuffer object is mutable. It is slower during concatenation. It is faster during concatenation. Consumes more memory. Consumes less memory. String s=new String(“vision”) StringBuffer sb=new StringBuffer(“vision)
  • 64. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 64 EXCEPTION HANDLING Error can be 2 categories 1.Compile time error: • Missing semicolon • Missing brackets in classes and method. • Misspelling of identifiers and keywords • Missing double quotes in string. • Use of understand variable • Incomplete types in assignments/initialization. • Bad reference object • Use of = in place of = = operator. 2.RunTime Errors • Dividing an integer by zero. • Accessing an element that is out of the bound of an array. • Trying to store a value into an array of an incomplete class or type. • Trying to cast an instance of a class to one of its subclass. • Attempting to use a negative size of an array. • Converting invalid string to a number. class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } } java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4) Or
  • 65. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 65 class Exc1 { static void subroutine() { int d = 0; int a = 10 / d; } public static void main(String args[]) { Exc1.subroutine(); } } o/p java.lang.ArithmeticException: / by zero at Exc1.subroutine(Exc1.java:4) at Exc1.main(Exc1.java:7)
  • 66. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 66 Exception: It is condition that is caused by run time error in the program. Types Of Exception Checked Exceptions Throwable and its subclasses except Error and RuntimeException put together are called as checked exceptions. If these exceptions are not handled or checked by the programmer in coding, the program does not compile. That is, compiler bothers much of this type of exceptions because they are raised in some special cases in the code which if
  • 67. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 67 not handled, the program may lead to many troubles. Common examples are FileNotFoundException, IOException and InterruptedException etc. Unchecked Exceptions RuntimeException and its all subclasses including Error are known as unchecked exceptions. As the name indicates, even if they are not handled or checked by the programmer, the program simply compiles. If at runtime, problems arise, the execution simply terminates. That is, regarding unchecked exceptions, the compiler does not bother. Common examples are ArithmeticException, ArrayIndexOutOfBoundsException, NumberFormatException, NullPointerException etc. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } //……………. finally { // block of code to be executed before try block ends }
  • 68. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 68 Using try and catch int d, a; try { d = 0; a = 42 / d; } catch (ArithmeticException e) { System.out.println("Division by zero."); OR System.out.println("Error"+e); } Exception class have 2 methods 1. String getMessage(); It is method of throwable class. This methods print only the message part of the output printed by object e. int d, a; try { d = 0; a = 42 / d; } catch (ArithmeticException e) { System.out.println("Error"+e.getMessage()) } 2. void printStackTrace(); It is method of throwable class.This method print the same message of “e” object & line number where the exception occurred. int d, a; try { d = 0; a = 42 / d; } catch (ArithmeticException e) { e. printStackTrace();
  • 69. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 69 } Q.Multiple catch Clauses class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } } } Here is the output generated by running it both ways: C:>java MultiCatch a = 0 Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks. C:>java MultiCatch TestArg a = 1 Array index oob: java.lang.ArrayIndexOutOfBoundsException After try/catch blocks. OR
  • 70. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 70 Try using exception class try { int a = 0; int b = 42 / a; } catch(Exception e) { System.out.println("error1"+e); } Q.Nested try Statements class NestTry { public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); try { if(a==1) a = a/(a-a); if(a==2) { int c[] = { 1 }; c[42] = 99; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); }
  • 71. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 71 } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } } C:>java NestTry Divide by 0: java.lang.ArithmeticException: / by zero C:>java NestTry One a = 1 Divide by 0: java.lang.ArithmeticException: / by zero C:>java NestTry One Two a = 2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException Q.Use try..catch in function class MethNestTry { static void nesttry(int a) { try { if(a==1) a = a/(a-a); if(a==2) { int c[] = { 1 }; c[42] = 99; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); }
  • 72. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 72 } public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); nesttry(a); } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } } Q.Finally Statement 1. Java support statement known as finally statement. 2. finally block can be used to handle any exception generated within try block. 3. When finally block is defined, that is guaranteed to execute, regardless of whether or not an exception is thrown. 4. finally use to perform certain house-keeping operation such as closing files and releasing resources. 5. It may be added immediately after the try block or after last catch block shown as follow. try { ………………. ……….. }
  • 73. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 73 finally { …………… ………. } Or try { ………………. ……….. } catch(…) { ………… ………. } finally { …………… ………. } class Exc2 { public static void main(String args[]) { int d, a; try { d = 0; a = 42 / d; }
  • 74. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 74 catch (ArithmeticException e) { System.out.println("Error"+e); } finally { System.out.println("finally block"); } Q.THROW The Java throw keyword is used to explicitly throw an exception.It can throw either checked or uncheked exception in java by throw keyword. Syntax throw new throwable_subclass; throw new NullPointerException("null exception"); class MyException extends Exception { MyException(String message) { super(message); } } class TestExp { public static void main(String args[]) { int x=5; try { If (x<0) throw new MyException(“no is negative”);
  • 75. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 75 } catch(MyException e) { System.out.println(e.getMessage()); } } } // Demonstrate throw. class ThrowDemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // rethrow the exception } } public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } }
  • 76. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 76 Q.throws Throws keyword is used to declare that a method may throw one or some exceptions. Thorws is used with the method signature. Syntax type method-name(parameter-list) throws exception-list { // body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { Try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } Here is the output generated by running this example program: inside throwOne caught java.lang.IllegalAccessException: demo
  • 77. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 77 Exception Class Meaning ArithmeticException Arithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsException Array index is out-of-bounds. ArrayStoreException Assignment to an array element of an incompatible type. ClassCastException Invalid cast. IllegalArgumentException Illegal argument used to invoke a method. IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread. IllegalStateException Environment or application is in incorrect state IllegalThreadStateException Requested operation not compatible with current thread state. IndexOutOfBoundsException Some type of index is out-of-bounds. NegativeArraySizeException Array created with a negative size. NullPointerException Invalid use of a null reference. NumberFormatException Invalid conversion of a string to a numeric format. SecurityException Attempt to violate security. StringIndexOutOfBounds Attempt to index outside the bounds of a string. UnsupportedOperationException An unsupported operation was Encountered ClassNotFoundException Class not found. CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface. IllegalAccessException Access to a class is denied. InstantiationException Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted by another thread. NoSuchFieldException A requested field does not exist. NoSuchMethodException A requested method does not exist..
  • 78. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 78 Q.Assertion Assertion is used to debugging purpose.An assertion is a statement containing a boolean expression that is assumed to be true when the statement is executed.The system report a AssertionError if the expression to false. Syntax 1. assert expression1 : expression2; e.g int age=11; assert age>=18:" Not valid"; System.out.println("age is "+value); o/p Exception in thread "main" java.lang.AssertionError: Not valid Note To Enabling assertion Compile it by: javac AssertionExample.java Run it by: java -ea AssertionExample To Disable assertion Run it by: java -da AssertionExample Advantage of assertion 1.The assertion machanisum allows to put in checks during testing 2.Excution of code with assertion is faster as compared to exception 3.Code size in small 4.Assertion facility can be enabled or disabled.
  • 79. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 79 Rules of assertion 1. Assertions should not be used to replace error messages 2. Assertions should not be used to check arguments in the public methods as they may be provided by user. Error handling should be used to handle errors provided by user. 3.Assertions should not be used on command line arguments.
  • 80. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 80 AWT (Abstract Window toolkit) &Swing java.lang Object Component java.awt Container Window Panel Frame Applet Javax.swing Jframe Japplet AWT(Abstract window toolkit) SWING AWT components are platform- dependent. Java swing components are platform- independent. AWT components are heavyweight. Swing components are lightweight. AWT provides less components than Swing. Swing provides more powerful components such as tables, lists, scrollpanes, tabbedpane etc. AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel. AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller Swing support MVC
  • 81. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 81 acts as an interface between model and view. e.g Button e.g JButton Container 1. JFrame – This is a top-level container which can hold components and containers like panels. Constructors JFrame() JFrame(String title) Important Methods setSize(int width, int height) Specifies size of the frame in pixels setLocation(int x, int y) Specifies upper left corner setVisible(boolean visible) Set true to display the frame setTitle(String title) Sets the frame title setDefaultCloseOperation(int mode) -Specifies the operation when frame is closed. Where The modes are: JFrame.EXIT_ON_CLOSE JFrame.DO_NOTHING_ON_CLOSE JFrame.HIDE_ON_CLOSE JFrame.DISPOSE_ON_CLOSE import java.awt.event.*; import javax.swing.*; import java.awt.*;
  • 82. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 82 public class JFrameDemo extends JFrame { public JFrameDemo() { super("Ty"); setSize(200,200); setLocation(100,150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new JFrameDemo(); } } 2. JPanel – The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class.It doesn't have title bar. Constructors JPanel() public class Pan extends JFrame { public Pan() { setLayout(new BorderLayout()); add(new TextArea(),BorderLayout.CENTER); JPanel p = new JPanel(); p.setLayout(new FlowLayout(FlowLayout.CENTER)); p.add(new Button("OK")); p.add(new Button("CANCEL")); add(p, BorderLayout.SOUTH); setVisible(true); } public static void main(String args[])
  • 83. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 83 { new Pan(); } } Component 1.ImageIcon ImageIcon(String filename) ImageIcon(URL url) 2.Label JLabel class, you can display unselectable text and images. Constructors- JLabel(Icon i) Label(Icon I , int align) JLabel(String s) JLabel(String s, Icon i, int align) JLabel(String s, int align) JLabel() Algin => LEFT (default), CENTER, RIGHT, LEADING, or TRAILING. Methods Set or get the text displayed by the label. void setText(String) String getText() public class JLabelDemo extends JFrame { public JLabelDemo() { super("Label Demo"); JLabel l=new JLabel("Enter value1"); add(l); setSize(200,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);
  • 84. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 84 } public static void main(String[] args) { new JLabelDemo(); } } Using Image import java.awt.event.*; import javax.swing.*; import java.awt.*; public class JIconDemo extends JFrame { public JIconDemo() { super("Icon Demo"); ImageIcon img=new ImageIcon("c:water.jpg"); JLabel l=new JLabel(img); add(l); setSize(200,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new JIconDemo(); } } 3.Button A Swing button can display both text and an image. Constructors JButton(Icon I) JButton(String s) JButton(String s, Icon I)
  • 85. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 85 Methods String getText() void setText(String) Event- ActionEvent public class JButtonDemo extends JFrame { public JButtonDemo() { super("Button Demo"); JButton b=new JButton("ok"); add(b); setSize(200,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new JButtonDemo(); } } 4.JTextField Constructors JTextField() JTextField(String) JTextField t=new JTextField(20); add(t); 5.JPasswordField Constructors JPasswordField()
  • 86. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 86 JPasswordField(String) JPasswordField t=new JPasswordField(20); add(t); 6.JTextArea Represents a text area which can hold multiple lines of text Constructors- JTextArea (int row, int cols) JTextArea (String s, int row, int cols) JTextArea t=new JTextArea(20,30); add(t); Q. LayoutManagers Def:The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. Each container has a layout manager associated with it. To change the layout manager for a container, use the setLayout() method. Syntax setLayout(LayoutManager obj) The predefined managers are listed below: 1. FlowLayout 2.GridLayout 3. BoxLayout 4.CardLayout 5.GridBagLayout 1.FlowLayout The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel.
  • 87. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 87 Here are the constructors for FlowLayout: FlowLayout( ) FlowLayout(int how) FlowLayout(int how, int horz, int vert) how are as follows: FlowLayout.LEFT FlowLayout.CENTER FlowLayout.RIGHT horz and vert follows: specify the horizontal and vertical space left between components in horz and vert, respectively. e.g setLayout(new FlowLayout(FlowLayout.LEFT)); b1=new JButton("1"); b2=new JButton("2"); add(b1); add(b2); 2 BorderLayout Border layout manager is the layout manager that divides the container into 5 regions such as north,east,west,south,center..
  • 88. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 88 BorderLayout( ) BorderLayout(int horz, int vert) BorderLayout defines the following constants that specify the regions: BorderLayout.CENTER BorderLayout.SOUTH BorderLayout.EAST BorderLayout.WEST BorderLayout.NORTH void add(Component compObj, Object region); e.g setLayout(new BorderLayout(5,5)); b1=new JButton("SOUTH"); b2=new JButton("NORTH"); b3=new JButton("EAST"); b4=new JButton("WEST"); b5=new JButton("CENTER"); 3.GridLayout The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle. GridLayout( )
  • 89. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 89 GridLayout(int numRows, int numColumns ) GridLayout(int numRows, int numColumns, int horz, int vert) e.g setLayout(new GridLayout(4,4)); 4.GridBagLayout The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline. The components may not be of same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells. Each component occupies one or more cells known as its display area. Each component associates an instance of GridBagConstraints. With the help of constraints object we arrange component's display area on the grid. The GridBagLayout manages each component's minimum and preferred sizes in order to determine component's size. GridBagLayout() e.g setLayout(new GridBagLayout());
  • 90. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 90 5.CardLayout CardLayout is the only layout class which can hold several layouts in it. The card layout manager generates a stack of components, one on top of the other. The first component that you add to the container will be at the top of the stack, and therefore visible,and the last one will be at the bottom. Constructor as follows CardLayout( ) CardLayout(int horz, int vert) 5.BoxLayout It Allows components to be arranged left-to-right or top-to-bottom in a container
  • 91. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 91 NOTE:FlowLayout is the default layout for Panel,Applet. BorderLayout is the default layout forFrame Manually Position Components setLayout(null); e.g setLayout(null); b1=new JButton("OK"); b1.setLocation(25,50); b1.setSize(60,40); add(b1); Check box Constructors JCheckBox(Icon i) CheckBox(Icon i,booean state) JCheckBox(String s) JCheckBox(String s, boolean state) JCheckBox(String s, Icon i) JCheckBox(String s, Icon I, boolean state) Method Void setSelected(boolean state) String getText()
  • 92. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 92 void setText(String s) Boolean isSelected() Event- ItemEvent public class Chk extends JFrame implements ItemListener { JCheckBox ch1; public Chk() { super("chk Demo"); setLayout(new FlowLayout(FlowLayout.LEFT)); ch1=new JCheckBox("red"); t1=new JTextField(20); add(ch1); ch1.addItemListener(this); setSize(200,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void itemStateChanged(ItemEvent e) { if(ch1.isSelected()) { String s=ch1.getText(); JOptionPane.showMessageDialog(this,"selected is ."+s); } else JOptionPane.showMessageDialog(this,"not selected is."); } public static void main(String[] args) { new Chk(); } }
  • 93. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 93 Radio Button Class- JRadioButton Constructors JRadioButton(Icon i) JRadioButton(Icon i, boolean state) JRadioButton(String s, Icon i) JRadioButton(String s, Icon i, Boolean state) JRadioButton() To create a button group- ButtonGroup() Adds a button to the group, or removes a button from the group. public class Border extends JFrame implements ItemListener { JRadioButton r1,r2,r3,r4; public Border() { super("chk Demo"); setLayout(new FlowLayout(FlowLayout.LEFT)); r1=new JRadioButton("male"); r2=new JRadioButton("female"); t1=new JTextField(20); ButtonGroup bg1=new ButtonGroup(); bg1.add(r1); bg1.add(r2); add(r1);
  • 94. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 94 add(r2); r1.addItemListener(this); r2.addItemListener(this); setSize(200,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void itemStateChanged(ItemEvent e) { if(r1.isSelected()) JOptionPane.showMessageDialog(this,"You are Male."); else if(r2.isSelected()) JOptionPane.showMessageDialog(this,"You are female."); } public static void main(String[] args) { new Border(); } } Combo Box Class- JComboBox Constructors- JComboBox() Methods Void addItem(Object) Object getItemAt(int) Object getSelectedItem()
  • 95. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 95 int getItemCount() Event- ItemEvent public class Border extends JFrame implements ItemListener { JComboBox cb; public Border() { super("chk Demo"); setLayout(new FlowLayout(FlowLayout.CENTER)); JComboBox cb=new JComboBox(); cb.addItem("red"); cb.addItem("yellow"); cb.addItem("pink"); add(cb); cb.addItemListener(this); setSize(200,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void itemStateChanged(ItemEvent e) { JComboBox ob=(JComboBox)e.getSource(); JOptionPane.showMessageDialog(this,"selected is ."+(String)ob.getSelectedItem()); } public static void main(String[] args) { new Border(); } }
  • 96. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 96 List Constructor- JList(ListModel) List models- 1. SINGLE_SELECTION - Only one item can be selected at a time. When the user selects an item, any previously selected item is deselected first. 2. SINGLE_INTERVAL_SELECTION- Multiple, contiguous items can be selected. When the user begins a new selection range, any previously selected items are deselected first. 3. MULTIPLE_INTERVAL_SELECTION- The default. Any combination of items can be selected. The user must explicitly deselect items. Methods Boolean isSelectedIndex(int) void setSelectedIndex(int) void setSelectedIndices(int[]) void setSelectedValue(Object, boolean) void setSelectedInterval(int, int) int getSelectedIndex() int getMinSelectionIndex() int getMaxSelectionIndex() int[] getSelectedIndices() Object getSelectedValue() Object[] getSelectedValues() Event- ActionEvent public class Cd extends JFrame { JList l; public Cd() { super("chk Demo"); setLayout(new FlowLayout()); String[] s= { "green", "red"};
  • 97. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 97 l = new JList(s); add(l); setSize(200,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new Cd(); } } Tabbed Panes A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title. When a user selects a folder, its contents become visible. Only one of the folders may be selected at a time. Tabbed panes are commonly used for setting configuration options. The general procedure to use a tabbed pane in an applet is outlined here: 1. Create a JTabbedPane object. 2. Call addTab( ) to add a tab to the pane. (The arguments to this method define the title of the tab and the component it contains.) 3. Repeat step 2 for each tab. 4. Add the tabbed pane in to the container. import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Demo extends JFrame { public Demo() { //setLayout(new FlowLayout()); JTabbedPane jtp = new JTabbedPane(); jtp.addTab("BCS", new BcsPanel()); jtp.addTab("BCA", new BcaPanel()); add(jtp); setVisible(true);
  • 98. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 98 } class BcsPanel extends JPanel { BcsPanel() { add(new JButton("ok")); add(new JButton("cancel")); } } class BcaPanel extends JPanel { BcaPanel() { add(new JButton("yes")); add(new JButton("no")); } } public static void main(String args[]) { new Demo(); } } JTable A table is a component that displays rows and columns of data. JTable(Object data[ ][ ], Object colHeads[ ]) Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings.
  • 99. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 99 Steps 1. Create a JTable object. 2. Create a JScrollPane object. (The arguments to the constructor specify the table and the policies for vertical and horizontal scroll bars.) 3. Add the table to the scroll pane. 4. Add the scroll pane into the container import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Demo extends JFrame { public Demo() { String[] colHeads = { "Name", "Phone", "Fax" }; final Object[][] data = { { "amol", "4567", "8675" }, { "kiran", "7566", "5555" }, { "sagar", "5634", "5887" }, { "punit", "7345", "9222" }, { "umesh", "1237", "3333" }, }; JTable table = new JTable(data, colHeads); int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(table, v, h); add(jsp, BorderLayout.CENTER); setVisible(true); } public static void main(String args[]) { new Demo(); } }
  • 100. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 100 JScrollPane A scroll pane is a container that represents a small area to view other component. If the component is larger than the visible area, scroll pane provides horizontal and/or vertical scroll bars automatically for scrolling the components through the pane JScrollPane() JScrollPane(Component) JScrollPane(vscroll, hscroll) JScrollPane(Component, vscroll,hscroll) HORIZONTAL_SCROLLBAR_ALWAYS VERTICAL_SCROLLBAR_ALWAYS HORIZONTAL_SCROLLBAR_AS_NEEDED VERTICAL_SCROLLBAR_AS_NEEDED e.g int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(table, v, h); Menu Menus are composed of three hierarchical pieces. The menu bar contains the various menus. Creating Menus You should build the menus before you display them. The typical order is: 1. Create a new MenuBar.
  • 101. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 101 2. Create a new Menu. 3. Add items to the Menu. 4. Add the Menu to the MenuBar. 5. If necessary repeat steps 2 through 4. 6. Add the MenuBar into the container import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Demo extends JFrame { public Demo() { JMenu fm = new JMenu("File"); fm.add(new JMenuItem("Open")); fm.addSeparator( ); fm.add(new JMenuItem("Save")); JMenu fe = new JMenu("Edit"); fe.add(new JMenuItem("Copy")); fe.add(new JMenuItem("Cut")); JMenuBar mb = new JMenuBar( ); mb.add(fm); mb.add(fe); setJMenuBar(mb); setVisible(true); } public static void main(String args[]) { new Demo(); } }
  • 102. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 102 Dialogs message dialog Displays a message to the user, usually accompanied by an OK button. confirmation dialog Ask a question and displays answer buttons, usually Yes, No, and Cancel. input dialog Asks the user to type in a string. import java.awt.*; import java.awt.event.*; import javax.swing.*; class Dialog { public static void main(String args[]) { JFrame f = new JFrame("Vision Academy"); JOptionPane.showMessageDialog(f, "You have mail."); int result = JOptionPane.showConfirmDialog(null, "Do you want to remove Windows now?"); String name = JOptionPane.showInputDialog(null, "Please enter your name."); } }
  • 103. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 103
  • 104. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 104 Q.EVENT Java has two types of events: 1. Low-Level Events: Low-level events represent direct communication from user. A low level event is a key press or a key release, a mouse click, drag, move or release,and so on. Following are low level events. 2. High-Level Events: High-level (also called as semantic events) events encapsulate the meaning of a user interface component. These include following events.
  • 105. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 105
  • 106. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 106
  • 107. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 107 Q.Adapter Classes An adapter class provides an empty implementation of all methods in an event listener interface i.e this class itself write definition for methods which are present in particular event listener interface.
  • 108. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 108 Suppose you want to use MouseClicked Event or method from MouseListener, if you do not use adapter class then unnecessarily you have to define all other methods from MouseListener such as MouseReleased, MousePressed etc. But If you use adapter class then you can only define MouseClicked method and don’t worry about other method definition because class provides an empty implementation of all methods in an event listener interface. Adapter Class Listener Interface ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapter WindowListener Before Using Adapter Class import java.awt.*; import java.awt.event.*; public class Demo extends Frame implements MouseListener { public Demo() { addMouseListener(this); setVisible(true); } public void mouseClicked(MouseEvent me) { } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mousePressed(MouseEvent me) { } public void mouseReleased(MouseEvent me)
  • 109. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 109 { } public static void main(String args[]) { new Demo(); } } After using Adapter Class import java.awt.*; import java.awt.event.*; public class Demo extends Frame { public Demo() { setVisible(true); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { System.out.println("mouse click"); } }); } public static void main(String args[]) { new Demo(); } } Q.MVC Architecture(Model view controller) MVC stands for Model View and Controller. It is a design pattern that separates the business logic, presentation logic and data. Controller acts as an interface between View and Model. Controller intercepts all the incoming requests.
  • 110. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 110 Model represents the state of the application i.e. data. It can also have business logic. View represents the presentaion i.e. UI(User Interface). Advantage of MVC (Model 2) Architecture 1. Navigation Control is centralized 2. Easy to maintain the large application
  • 111. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 111 Applet Applet(java.applet.Applet) is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side. Q.Life Cycle of applet The Basic Applet Life Cycle Born initialization (Load Applet) Start() Stop() Display() stopped Paint() Start() Destroyed end BORN RUNNING IDLE DEAD
  • 112. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 112 1. Initialization state Applet enters the initialization state when it is first loaded. This is achieved by calling init() method of Applet Class. The applet is born. At this stage ,It may the following, if required. 1. Create object needed by applet. 2. Set up initial values. 3. Load images or fonts. 4. Set up colors. The initialization occurs only once in the applet’s life cycle. To provide any of the behaviors mentioned above, it must override the init() method. public void init() { --------------- //action } 2. Running State This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages. public void start() { --------------- //action } 3. Idle or stopped state. This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet. public void stop() { --------------- //action } 4.Dead state
  • 113. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 113 An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy() method when it quit the browser. It override the destroy() method to clean up these resources. public void destroy() { --------------- //action } 5. Display State Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. public void paint(Graphics g) { --------------- //action } import java.awt.*; import java.applet.*; public class AppletSkel extends Applet { // Called first. public void init() { // initialization } /* Called second, after init(). Also called whenever the applet is restarted. */ public void start() { // start or resume execution } // Called when the applet is stopped. public void stop() {
  • 114. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 114 // suspends execution } /* Called when applet is terminated. This is the last method executed. */ public void destroy() { // perform shutdown activities } // Called when an applet's window must be restored. public void paint(Graphics g) { // redisplay contents of window } } The HTML APPLET Tag The APPLET tag < APPLET [CODEBASE = appletURL] CODE = appletClassFile [ALT = alternateText] [ARCHIVE = archiveFile] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [< PARAM NAME = AttributeName VALUE = AttributeValue />] </APPLET>
  • 115. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 115 How to run applet 1. compile the HelloWorldApplet.java program. i.e C:javac HelloWorldApplet.java import java.applet.Applet; import java.awt.*; public class HelloWorldApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } } 2. Insert the HelloWorldApplet.class in the following HTML tag. And save HTML file(Hello.html) <html>
  • 116. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 116 <body> This is the applet:<P> <applet code="HelloWorldApplet" width="150" height="50" name=”visionacademy”> </applet> </body> </html> 3. Use appletviewer command . C: appletviewer Hello.html Or import java.applet.Applet; import java.awt.*; /* <applet code=" HelloWorldApplet" width=300 height=100> </applet> */ public class HelloWorldApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } } Compile C: javac HelloWorldApplet.java Run
  • 117. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 117 C: appletviewer HelloWorldApplet.java Simple Applet Display Methods Use drawString( ), which is a member of the Graphics class. It has the following general form: void drawString(String message, int x, int y) Difference between paint(),update(),repaint() methods repaint() –> update() –> paint() paint():This method holds instructions to paint this component. It shouldn't call this method directly, It should call by using repaint(). public void paint(Graphics g) { } Repaint():Repaint() method calls automatically update() method and in turn update() method calls paint() method Update():An update method is called on calling the repaint method. The default implementation of the update() method clears the screen and calls the paint() method. Background & Forground Color void setBackground(Color newColor) void setForeground(Color newColor) Here, newColor specifies the new color. The class Color defines the constants shown here that can be used to specify colors: Color.black Color.magenta Color.blue Color.orange For example, this sets the background color to green and the text color to red:
  • 118. Vision Academy (9822506209/9823037693 http://www.visionacademe.com) (SACHIN SIR MCS In Scientific Computing From ISSC,UOP ),SET Classes For BCA/BBA/BCS/MCS/MCA/MCS/BE(ANY) Java Note 118 setBackground(Color.green); setForeground(Color.red); /* A simple applet that sets the foreground and background colors and outputs a string. */ import java.awt.*; import java.applet.*; /* <applet code="Appletcolor" width=300 height=100> </applet> */ public class Appletcolor extends Applet { String msg; // set the foreground and background colors. public void init() { setBackground(Color.cyan); setForeground(Color.red); msg = "Inside init( ) --"; } } PARAM Tag To pass parameter or value to the applet using PARAM Tag Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags between the opening and closing APPLET tags. Inside the applet, you read the values passed through the PARAM tags with the getParameter() method of the java.applet.Applet class.