0% found this document useful (0 votes)
78 views

Java

C was developed by Dennis Ritchie in 1972 as a procedure-oriented language. C++ was developed by Bjarne Stroustrup in 1980 as an extension of C with classes. Java was developed by Sun Microsystems engineers in 1991 and is a pure object-oriented language derived from C and C++ syntax. It is mainly used for developing internet-based applications and is platform independent.

Uploaded by

ramu
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Java

C was developed by Dennis Ritchie in 1972 as a procedure-oriented language. C++ was developed by Bjarne Stroustrup in 1980 as an extension of C with classes. Java was developed by Sun Microsystems engineers in 1991 and is a pure object-oriented language derived from C and C++ syntax. It is mainly used for developing internet-based applications and is platform independent.

Uploaded by

ramu
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 36

c - Lang

======
--> it is a Procedure or Structure Oriented Programming Language
--> It was Developed by "Dennis Ritchie" in the year 1972.

c++
===
--> c++ is derived from c-lang(basic syntax) and
simula-67(class concepts)
--> It was developed "Bjarne Stroustrup" in the year 1980.
--> it was Initially called "c with classes"

Java
==
--> it is a Pure Object Oriented Programming Language..

Define OOP
=========
--> representing the relationships b/w Objects
--> Object holds Datas and Methods
--> It is derived from c[Basic Syntax] and c++[OOPs]
--> it is mainly used for Developing Internet based applications
--> it was developed by sun-micro system Engineers in the year1991(James
Gosling,Chris Warth,Patrick Naughton)
--> it is a Plat-form independent Language
--> it is a compiler and Interpreter Language
--> it is a case-sensitive Language

JDK (Java Developer Kit)


===
Versions of JDK --> 1.0,1.1,1.2,1.3,1.4,1.5,1.6 and 1.7,1.8

1) J2SE(Java 2 Standard Edition) --> used to Develope the Console Applications


like c and C++
2) J2EE(Java 2 Enterprise Edition) --> used to develope Internet based
Applications

*) RMI
*) Servlets
*) EJB
*) JSP
*) Struts
*) Hibernate
*) Springs

3) J2ME(Java2 Micro Edition) --> used to develope Mobile Aps

IDE(Integrated Developement Environment)


===============================
--> It is a graphical tool which is used to create, compile, debug, execute and
deploy our Applications.

*) NetBeans
*) Eclipse

Java Basic Programming Structure


======================
class Sample
{
public static void main(String args[])
{
//local variables
//Executable Statements
}

Packages
=======
--> collection of classes and Interfaces

*) java.io
*) java.lang(Default Package)
*) java.util
*) java.sql

Accessing the classes from the Package


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

"import" statement is used to access the classes from the Specified package.

Ex : Accessing all classes


==
import java.io.*;

Ex: Accessing the Specific class from the package


==
import java.io.DataInputStream;
import java.io.BufferedReader;

Output Statements
=============

*) System.out.print()
*) System.out.println()

Ex:
==
System.out.print("hi..");
System.out.print("Welcome to Java");

o/P:
==
Hi..Welcome to Java

Ex:
==
System.out.println("hi..");
System.out.print("Welcome to Java");

o/P:
==
Hi..
Welcome to Java
Java code Execution Process
====================

Source Code (test.java)

|| javac test.java

Byte code (test.class)

|| java test

Target Machine Code


(0's and 1's)
||
Output
(Monitor)

java.io package classes


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

*) BufferedReader
*) DataInputStream

System.in --> input stream --> by default it is referred as "keyboard"


System.out --> output stream --> by default it is referred as "Monitor"

creating the Object for "DataInputStream" class


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

DataInputStream din=new DataInputStream(System.in);

methods of DataInputStream class


---------------------------------

*) char read() --> used to read a single character data from the user
and returns in the form of integer(ASCII value)
A --> 65
a --> 97

char ch;
System.out.print("Enter a character : ");
ch=(char)din.read();
System.out.println("The Given character is "+ch);

o/p:
==
Enter a Character : s
The Given character is s

*) String readLine() --> used to read a String values from the user and also
returns as a String

Ex:
==
String s;
System.out.print("Enter ur name : ");
s=din.readLine();
System.out.println("ur name is "+s);

o/p:
==
Enter ur name : nawin
ur name is nawin

*) Reading the Integer values


========================
---> Integer.parseInt() --> used to convert from String type to Integer
type..

Ex:
==
int a;
System.out.print("Enter a value : ");
a=Integer.parseInt(din.readLine());
System.out.println("a = "+a);

o/p:
==
Enter a value : 100
a = 100

java tokens(Smallest individual Element)


=============================
*) constants
---> unchanged Value
1.Numeric Constant
-> Integer Constant(Without Decimal Point) --> 67,87
-> Real Constant(With Decimal Point) --> 78.78,54.34
2.Non-Numeric Constant
-> character Constant('w' | '4' | '*')
-> String Constant("Welcome" | "4433" | "$#&")

*) datatypes

---> used to specify the type of values to be stored in a Variable

1. Integral Datatype

--> int (4 bytes)


--> byte (1 byte)
--> short (2 bytes)
--> long (8 bytes)

2. Floating Datatype
--> float (4 bytes)
--> double (8 bytes)
3. character datatypes
--> char (2 bytes)
--> String --> it is a class

Ex:
==
String s="java";

4. boolean Datatype
--> boolean (true/false)

Ex: boolean b=true;


System.out.println(b);

*) variables

--> it is an Identifier, which is used to store user data


--> it can be changed during the Execution of a Program
syntax
======
datatype varname;
Ex:
==
int a;

*) operators

---> used to perform some operations based on one or two or more


operands..

Expression:
========
--> combination of operators and operands

Ex: a + b
a,b --> operands
+ --> Operator

Types of Operators
==============
1.Arithmetic Operators(+,-,*,/,%)

Ex:
==
int a=10,b=2,c;
c=a/b; //c=5;
c=a%b; //c=0;
2.Relational Operators (<,>,<=,>=,==,!=)
--> used to compare two values and produces the result as either true
or false

Ex: int a=10,b=4;


a>b --> true
a<b --> false
a==b --> false
a!=b --> true

3.Logical Operators

*) logical AND (&&)


*) logical OR ( || )
*) logical NOT ( ! )
--> used to compare the result of two relational Expressions and
combine them into a Single Result

Ex : int a=10,b=20,c=15;

(a>b) && (a>c) ---> false


(a>b) || (a<c) --> true
!(a>b) --> true

4.Bitwise Operators
--> used to perform operations based on binary digits
*) bitwise AND (&)
*) bitwise OR ( | )

Ex : int a=14,b=10,c;

c=a&b; //c=10;
c=a| b; //c=14;

16 8 4 2 1
14 --> 0
1 1 1 0
10 --> 0
1 0 1 0
-------------
0 1 0 1 0
-------------
0 1 1 1 0
------------
5.Assignment Operators(=)
--> used to assign the values to a Variable

syntax
===
varname=value;
Ex: int a;
a=100;
6. Arithmetic Assignment Operators(Short-hand assignment operator)
--> used to assign the Expression to a Variable

--> The operators are +=,-=,*=,/=,%=

Ex:
==
int a=10,b=20;
a=a+b; // a+=b;
a=a-b; // a-=b;
a=b+c; //

7. Conditional Operator (Ternary Operator)


--> used to perform simple conditional Operations
--> ternary operator "?:" is called "conditional operator"

syntax
=====
Exp1 ? Exp2 : Exp3 ;
(cond) T F

Ex:
==
int a=10,b=8,max;
max=(a>b)?a:b;
System.out.println("max = "+max);
o/p:
==
max = 10

8. Inc/Dec operators (unary operators)

Increment[++]
------------
--> used to increment the value by 1 from its current value

*) pre-Inc --> increment is before to Operation

syntax : ++varname;

Ex: int a=10,b;


==
b=++a; // a=11;b=11;
*) post-Inc --> increment is next to Operation

syntax
=====
varname++;
Ex: int a=10,b;
==
b=a++; //a=11;b=10;

*) operands
*) keywords
--> keywords are resrved words, they already defined in the Compiler
--> we cant change the meaning of those keywords
--> we cant use the keyword name for variable

*) Identifiers
--> user-defined things like variable,classes and methods are considered
as " Identifiers"

Control Statements
==============
--> used to change the Flow of Execution of a Program

*) Conditional Control Statements


1.Decision making or branching Statements
--> simple if
--> if..else
--> else if ladder
--> nested if
--> switch()
2.Looping or Iteration Statements
--> for loop
--> while loop
--> do..while loop
--> nested loops
*) Un-Conditional Control Statements
--> break
--> continue

1) simple if (one-way branching)


=======
--> it is used to check only one condition and also executes only one
block (i.e true block)

syntax
=====
if(cond)
{
//true block statements
}

Ex:
==
int a=3;
if(a>0)
{
S.o.p("Positive Number..");
}

2) if..else statement (two-way branching)


=============
--> it is also used to check only one condition but executes either true or
false block

syntax
=====
if(cond)
{
//true block statements
}
else
{
//false block statements
}

Ex:
==
int a=10,b=14;
if(a>b)
{
S.o.p("a is greatest..");
}
else
{
S.o.p("b is greatest..");
}

*). write a program to check whether the given no is odd or Even


*). write a program to check whether the given year is leap year or not

3) else if ladder (multi-way branching)


=========
--> it is used to check more than one condition and executes the block which
one satisfy the Condition

syntax
=====
if(cond-1)
{
//statements1
}
else if(cond-2)
{
//statements2
}
.
.
else if(cond-n)
{
//statement-n
}
else
{
//default statements
}

Ex:
==

int mark=35;
if(mark>=90)
S.o.p("Grade: A");
else if(mark>=70)
S.o.p("Grade : B");
else if(mark>=40)
S.o.p("Grade : C");
else
S.o.p("Grade : D");

4.Nested If statement
==============
--> if inside another if is called "nested if"
--> it is also used to check more than one condition

syntax
====
if(cond-1)
{
if(cond-2)
//statements
else
//statements
}
else
{
if(cond-3)
//statements
else
//statements
}
// program to check greatest among given three nos

int a=10,b=20,c=56;

if(a>b)
{
if(a>c)
S.o.p("a is greatest..");
else
S.o.p("c is greatest..");
}
else
{
if(b>c)
S.o.p("b is greatest..");
else
S.o.p("c is greatest..");

5.switch() statement
=============
--> it is similar to else if ladder statement
--> used to compare a single value with list values and where match is found
that the statements are Executes

syntax
=====

switch(expression)
{
case 1:
//stmts
break;
case 2:
//stmts
break;
.
.
case n:
//stmts
break;
default:
//stmts
break;
}

Ex:
==
int no=1;
switch(no)
{
case 1:
S.o.p("ONE");
break;
case 2:
S.o.p("TWO");
break;
case 3:
S.o.p("THREE");
break;
default:
S.o.p("no is > 3");
break;
}

*) program to check whether the given char is vowel or not

Looping Statements
=============
---> used for repeated Execution of Particular stmts in a Program

1) for loop (Entry Check loop)


--> Executes the block statements repeatedly until the Specific Condition is
true.
--> it has three parts

*) Initialization
*) Condition
*) Inc/Dec
--> syntax

for(init; cond; inc/dec)


{
--
}

Ex:
===
//print nos from 1 to 10

int i;
for(i=1;i<=10;i++)
{
S.o.p(i);
}

// program for printing the Even nos from 2 to 22

2.while loop
========
--> it is also "Entry Check Loop"
--> it is similar to for loop
syntax
=====

initialization;
while(condition)
{
//statements
//inc/dec
}

//program for printing the nos from 10 to 1


int i;
i=10;
while(i>=1)
{
S.o.p(i);
i--;
}

//write a program for printing the ODD nos from 1 to 25

3.do..while loop
===========
--> it is a bottom or exit check loop

syntax
===
initialization;
do
{
//stmts;
//inc/dec
}while(cond);

//program for print the nos from 10 to 20

int i;
i=10;
do
{
S.o.p(i);
i++;
}while(i<=20);

Nested Loops
========
--> loop inside another loop is called "Nested Loops"
--> used to show the Data in the Form of rows and cols

syntax
=====
for(init-1;cond-1;inc/dec) (row)
{
for(init-2: cond-2; inc/dec) (column)
{
//inner loop stmts
}
//outer loop stmts
}

Ex:
==
1 1 1
2 2 2
3 3 3
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
System.out.print(i+"\t");
}
System.out.println();
}

Ex:
==
1)
1 2 3
1 2 3
1 2 3
2)
1
2 3
4 5 6
7 8 9 10

foreach loop
=========
--> used to iterate the control through a raw of values

syntax
=====
for(datatype var:arrayname)
{
//loop statements
}

Ex:
==

int[] a={ 10,20,30,40 };

for(int s : a)
{
System.out.println(s);
}

//program to chek whether the given no is Amstrong or not


//program to check whether the given no is palindrome or not

break
====
--> it is used to terminate the block or loop
--> it must be placed inside the Looping or decision making stmts

syntax
=====
break;

Ex:
==
for(i=1;i<=10;i++)
{
S.o.p(i);
if(i==5)
break;
}

continue
======
--> it is used to bypass the control to next iteration(re-initialization step)
--> The statements after the "continue" will not be executes inside the loop.

syntax
=====
continue;

Ex:
==

for(i=1;i<=10;i++)
{
if(i<=5)
{
continue;
}
S.o.p(i);
}

Arrays
=====
--> Group of similar data items, which can shares the Common Variablename and
are stored in sequence memory locations
--> Array Index starts with "0" and ends with "n-1"

*) Numeric Array(1-D,2-D)
*) Non-Numeric Array(1-D)

Steps in Array Process


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

1) Declare a Variable to hold an Array

syntax
=====
datatype varname[];

Ex:
==
int a[];

2) create a new Array objects and assign them to Variable

syntax
===
varname=new datatype[size];

Ex:
==
a=new int[5];

or

int a[]=new int[5];

3) Storing the Values


=============
syntax: var[index]=value;

Ex:
===
a[0]=10;
.
a[4]=50;

Array Initialization
============
*) Compile-time
*) Run-time

*) Compile-time
=========
int a[]={10,20,30,40,50};

*) Run-time
======
int a[]=new int[3];
int i;
S.o.pln("Enter the Array Elements..");
for(i=0;i<a.length;i++)
{
a[i]=Integer.parseInt(din.readLine());
}

*) write a program for sorting an Array Elements


*) write a program for searching an Array Element

2-D array
=======
--> used to store data in the form of rows and cols
--> used to perform matrix operations like add,sub and so on..

syntax
=====
datatype[] var=new datatype[row,col];

Ex:
==
int[,] a=new int[2,2];

Array Initialization
==============
*) compile-time Initialization

int[,] a= {
{10,20,30},
{24,56,78},
{10,34,67}
};

*) Run-time Initialization
===============
int[,] a=new int[2,2];

int i,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
a[i,j]=int.Parse(C.RL());
}
}

OOPs Concepts
============
--> Representing the relationship among methods and fields of one object to
another object

1.class
2.Object
3.Data Abstraction
4. Data Encapsulation
5. Data Hiding
6. polymorphism
7. Inheritance
8. message passing

1.Class
=====
--> A class is a Template, which defines the Data members and member functions
common to all Objects of a certain kind.
--> Hence, a class is a collection of Objects..
--> classes define
*) what an Object knows (Data members)
*) what an Object Does(Member functions)
--> a class is a blue print for an Object..
syntax
=====
class classname
{
access datatype mem1,...;
access returntype methodname(parameters)
{
//local variables
//stmts
}
.
.
}

Access_Specifiers
============
--> defines the scope of the data members and member functions
*) private --> inside the class
*) public --> inside + outside
*) protected ---> base + derived

Ex:
==
class Sample
{
priavte int a,b; //data members (attributes or fields)
public void get() // methods
{
---
}
public void show()
{
---
}
}

2.Object
=====
--> it is an Instance of a class
--> class type variable is called "Object"
--> it is a real-time entity

syntax
=====

classname refname; //declare a reference to hold an Object


refname=new classname(); //create an object and assign it to refname

Ex:
==
Sample s;
s=new Sample();

or

Sample s=new Sample();

Accessing the Members of a class


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

.(dot) operator is used to access the members of a class through an Object

syntax
=====
objectname.member;
objectname.method();

Ex:
==
s.get();
s.show();

3. Data Abstraction
============
--> it is the process of representing the essential features without
including the background details or Explanations..

Ex:
==
input(3) ----> factorial --> output(6)

4. Data Encapsulation
===============
-> combining the data members and member functions into a single unit(class)
is called "data Encapsulation"

5. Data Hiding
=========
--> the datas and functions declared under the private access cannot be
accessed by outside members.
--> only those functions which are wrapped in the class, can access the
private members..

6. polymorphism
==========
poly--> many
morph --> forms or shapes

--> ability to take more than one form in a single interface


--> "single interface, multiple forms"

types
====
*) compile-time polymorphism(static binding or Early binding)

Ex:
==
function overloading

*) Run-time Polymorphism(dynamic binding or late binding)

Ex:
==
*) abstract classes

7.Inheritance
========
---> deriving a new class from an Existing class

*) new class --> derived or child or sub class


*) Existing class --> base or parent or super class

Advantages
========
*) code reusability
*) new datas and methods can be added easily without modifying the
Existing one

types
====
*) single inheritance
*) multi-level inheritance
*) multiple inheritance[ we can implement through "interface" ]
*) hierarchical inheritance
*) hybrid Inheritance

static data member


==============
--> it is automatically initialized to "zero" when the First object is Created..
--> it belongs to a class
--> only one copy is created per class
--> it can be shared by all the Objects of a class

syntax
=====
static datatype var;
static Methods
===========
--> no need to create instance to access the static members of a class
--> they can be called by using classname

Rules
====
--> static methods can call only another static methods
--> they can access only static data members

Ex:
==
class Sample
{
private int x;
private static int y;
public void M1()
{
//x is accessable
//y is accessable
}
public static void M2()
{
//x is not accessable
//y is accessable
}

String Handling
===========
--> Group of characters is called "String"
--> we can use the "String" class object to store the string values
--> once string object is created it cannot be changed
--> like array string index also begins with "0"
--> it is defined in "java.lang" package

String class Methods


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

1) int length() --> it is used to find the Length of the String..

String s="welcome";
int len=s.length();
S.o.pln(len);

2) boolean equals() --> used to check whether two strings are equal or not
--> it considers the case differences

Ex:
==
String s1="welcome";
String s2="Welcome";
boolean b=s1.equals(s2);

3) boolean equalsIgnoreCase() --> it is similar to equals() method


--> it wont considers the case
differences

Ex:
==
String s1="welcome";
String s2="Welcome";
boolean b=s1.equalsIgnoreCase(s2);

4) String toUpperCase() --> used to convert from lower case to upper case

Ex:
==
String s1="java";
String s2=s1.toUpperCase();

5) String toLowerCase() --> used to convert from upper to lower case

Ex:
==
String s1="JAVA";
String s2=s1.toLowerCase();

5) boolean startsWith() --> used to Check whether the Given String starts with
the pecified String or not

Ex:
==
String s="Visual Basic";
boolean b=s.startsWith("Vis");

6) boolean endsWith() --> used to Check whether the Given String Ends with the
specified String or not

Ex:
==
String s="Visual Basic";
boolean b=s.endsWith("sic");

7) int compareTo() --> used to compare two strings

String1 > String2 ===> 1(postive)


String1 < String2 ===> -1(negative)
String1 == String2 ===> 0
Ex:
==
String s1="vino";
String s2="varun";
int i=s1.compareTo(s2);
if(i>0)
S.o.p("S1 is greatest..");
else if(i<0)
S.o.p("S2 is Greatest..");
else
S.o.p("s1 and s2 are equals..");

8. char[] toCharArray() --> used to convert from String to character


Array

Ex:
==
String s="Java";
char c[]=s.toCharArray();

9. String[] split() --> used to divide the String into sub strings based on the
Specifed value

Ex:
==
String s = "3452-2455-56433-34234";
String g[] = s.split("-");
for (int i = 0; i < g.length; i++)
{
S.o.pln(g[i]);
}

10. String replace() --> replaces the all occurance of old char by new char

Ex:
==
String s = "Core Java";
String r = s.replace('a', 'A');
S.o.pln("s = " + s);
S.o.pln ("r = "+r);

constructor
========
--> it is a special type of method, which is used to initialize the data members
of a class..

points to Constructor
==============
*) it must have the same name of class.
*) it doesnot have any returntype
*) it allows arguments, hence it can be overloaded.
*) it executes automatically when we create an Object
*) it allocates memory space to an Object.

Types of Constructor
==============
*) Default Constructor --> it doesnot contins arguments
*) Parameterized Constructor ---> it contains arguments
*) Copy Constructor --> used to copy the content of One Object to another
Object..
(Object must be passed as argument to copy Constructor)

Ex:
==
class Sample
{
public Sample()
{

//default Constructor
}
public Sample(int i,int j)
{
//Parameterized Constructor
}

public Sample(Sample s)
{

//copy Constructor
}

Function Overloading or method overloading


===============================
--> giving the Special Meaning to an Existing Function is called "Function
Overloading"
--> Overloading refers --> using the same thing to perform a different variety
of tasks
--> Each Overloaded Function should differ either based on no of parameters or
type of parameters.
--> we can have more than one function with the same name but the parameter list
is different

Ex:
==
class OverDemo
{
public void add(int i,int j)
{
//adding two integers
}
public void add(float i,float j)
{
//adding two floats
}
public void add(int i,int j,int k)
{
//adding three integers
}
}

Exception Handling
=================
Exception : it is a run-time Error, that occurs in a program code during Run-
time..

Bug : Error in a Program


Debugging : Removing the Errors from the Program

Types of Error
==========
*) Compile-time Errors
--> all syntax errors will be considered as Compile-time errors
*) Run-time Errors
--> occurs when the user have done the following mistakes during the
execution time
*) giving the Invalid input
*) when dividing the Integer value by zero
*) when the File is not found for read or write Operation

*) Logical Errors
--> System cant find the logical errors
--> when we get the partial o/p instead of Expected output,
the program may contains the Logical Error

Keywords for Exception Handling in Java


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

*) try
*) catch
*) throw
*) throws
*) finally

syntax : Exception handling


=====

try
{

//Statements that cause an Exception


}
catch(ExceptionType obj)
{

//statements that handles the Exception


}
finally [optional]
{

//statements that releases the System resources (i.e closing the DB


connection, closing the File)
}

Exception [base class]


| |
ArithmeticException FileNotFoundException

throw Keyword
============
--> it is used to throw an Exception Explicitly
--> it is also used to throw a user-defined Exception

syntax
===

throw new classname(parameters);

Creating the New user-Exception class


===========================
--> we can create a new User Exception class by Inheriting the "Exception" class

Ex:
==

class MyException extends ExceptionDemo


{
//data members
//member functions

Example:
=======
//Exception Handling
class ExceptionDemo
{
public static void main(String args[])
{
int a=10,b=0,c;
try
{
c=a/b;
System.out.println("c = "+c);
}
catch(Exception ae)
{
System.out.println("Attempting to Divide by Zero..");
}
finally
{
System.out.println("Finaly block is Executed..");
}
}
}
throw Example
===========
class MyException extends Exception
{
private String str;
public MyException (String s)
{
str=s;
}
public String getMessage()
{
return str;
}
}

class UserException
{
p.s.v.m(String Args[])
{
Scanner sr=new Scanner(System.in);
int age;
S.o.pln("Enter ur age");
age= Integer.parseInt(sr.nextLine());
try
{
if(age>100)
throw new MyException("plz enter age b/w 1 to 100.....");
else
{
if(age>=18)
S.o.pln("major");
else
S.o.pln("minor");
}
}
catch(Exception me)
{
S.o.pln(me.getMessage());
}
}
}

Files
====
--> Collection of records or Information, which are stored in Memory of
Computer HardDisk.

Operations on File
=============

--> Read
--> Write
--> Read/Write
--> copy

Stream
=====
--> Flow of Data from one point to another Point
--> File Stream classes defined in "java.io" package

types
====
--> byte based

*) FileInputStream
*) FileOutputStream

--> character based

*) FileReader
*) FileWriter

types of Streams
=============

*) Input Stream

--> flow of data from input devices(keyboard,mouse,scanner,files) to


program

*) Output Stream

--> flow of data from program to output devices(monitor,printer,files)

Creating the Object to "FileInputStream" class


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

try
{
FileInputStream fin=new FileInputStream("d:/java/sss.txt");
}
catch(FileNotFoundException fe)
{
S.o.p("File is not Existing..");
}

Reading the Info from the File


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

methods
======
1) int read() --> it is used to read one byte data at a time from the File
and returns in the form of Integer (ASCII value)

--> if the End of the File is reached, it returns -1

Ex :
==

int i;

do
{
i=fin.read();
if(i!=-1)
S.o.print((char)i);
}while(i!=-1);

2) void close() -- >it is used to close a File

Ex : fin.close();

Creating the Object for "FileOutputStream" class


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

try
{
FileOutputStream fout=new FileOutputStream("dddd.txt");
}
catch(FileNotFoundException fe)
{
System.out.println("File is not Created for Write operation..");
}

Writing the Contents to a File


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

1) void write() --> it is used to write a data in the form of bytes

2) void close() --> closes the output Stream

PRogram(FileReadDemo)
========
import java.io.*;
class FileReadDemo
{
public static void main(String args[]) throws IOException
{
FileInputStream fin;
int i;
try
{
fin=new FileInputStream("D:\\java notes (1)\\java notes\\Files
note.txt");
do
{
i=fin.read();
if(i!=-1)
System.out.print((char)i);
}while(i!=-1);
fin.close();

}
catch(FileNotFoundException fe)
{
System.out.println("File is not Existing..");
}
}
}

program
======

//writing the Datas to a File


import java.io.*;
class FileWriteDemo
{
public static void main(String args[]) throws IOException
{
FileOutputStream fout;
String s;
DataInputStream din;
System.out.println("Welcome to File Write Operation..");
try
{
din=new DataInputStream(System.in);
fout=new FileOutputStream("Cri.doc");
System.out.print("Enter Data to Write : ");
s=din.readLine();
s=s+"\n";
byte b[ ]=s.getBytes();
fout.write(b);
System.out.println("Datas Written to a File..");

}
catch(FileNotFoundException fe)
{
System.out.println("File is not Created..");
}
}
}
Inheritance
========
---> deriving a new class from an Existing class

*) new class --> derived or child or sub class


*) Existing class --> base or parent or super class

Advantages
========
*) code reusability
*) new datas and methods can be added easily without modifying the
Existing one

types
====
*) single inheritance
*) multi-level inheritance
*) multiple inheritance[ we can implement through "interface" ]
*) hierarchical inheritance
*) hybrid Inheritance
single inheritance
=============
if a new class is created from only one base class

Synatx
---------

class Der_class extends base_class_name


{

Example
=======

class A
{

class B Extends A
{

Multi-Level Inheritance
==================
if a new class is created from another derived class,that is already
from base class

Example
=======
class A
{

class B Extends A
{

}
class C Extends B
{

Hierarchical Inheritance
==================

If a new serval classes are created from only one base class

Example
=======
class A
{

}
class B Extends A
{

}
class C Extends A
{

}
class D Extends A
{

Hybrid Inheritance
===============
It combination of any two types of Inhertiance

Multiple Inheritance[ we can implement through "interface" ]


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

Syntax
=====
interface interfaceName
{
//methods DEclartions
}

Example
======

interface one
{
void display();
}

Interface inherits another Interface


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

Syntax
=====
interface Der_interface extends Base_interface
{

Example
======
interface two extends one
{

class can inherits interface


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

Syntax
=====

class class_name implements interface_name


{

Example
=======

class A implements two

{
public void show()

public void dispaly()

class B implements two

public void show()


{

}
public void dispaly()

}
}

// void main
B b1=new B();
A a1=new A();
Mutiple Inheritance
===============
If a new class is created from two or more base classes,then it is
called "Mutiple Inheritance"

Example
======

class A
{

Interface B
{

interface c
{

}
class D extends A implements B,c
{

Threading
========
--> a thread is a separate unit of dispatchable code in a program

Multi-Tasking
=============
--> two or more tasks can perform at the same time
Eg: os

Muti-Threading
============
--> two or more parts of the program can run different or similar

Syntax
=====

Class MyThread extends Thread


{
public void run()

}
}

Thread Life class States


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

1.New born state


2.Runnable state
3.Running state
4.Blocked state
5.Dead state

Thread class methods


===============
getName() --> used to get the name of the Thread.
setName() --> used to set or change the name of the Thread
sleep() --> it is static method, which is used to suspend a thread until some
period of time
start() --> used to start a thread by calling the run() method..
suspend() --> used to suspend the thread execution unitl some event occurs
resume() --> it is used to restart a thread
getPriority() --> used to get a priority of a Thread(default : 5)
setPriority() --> used to set a priority value to a Thread
MIN_PRIORITY : 1
NORMAL_PRIORITY : 5 (default)
MAX_PRIORITY :10

Creating the New Thread


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

--> we can create a new thread class by extending the "Thread" class..

syntax
======
class <thread_class_name> extends Thread
{

public void run()


{
// thread code here for execution
}
}

Ex:
==
class ChildThread extends Thread
{
public void run()
{

packages
======= import java.lang

class ThreadDemo
{
p.s.v.m(string args[])
{
for(int i=1;i<=5;i++)
{
S.o.pln("i="+i);
Thread.Sleep(3000);
}
}
}

Final Keyword
============

It can be used in three ways

*) to declare the constants

ex:- final int x=100;

*)To prevent the classes from inheriting


--> final class can inherit other classes but other classes cannot
inherit final classes

Example
=======

class A{.............................}
Final class B extends A {........................}
class C extends B {...................................}

**class B(cannot be inherited because it is final class)

*)To Protect the base class methods from "overriding"

class A
{
public final void show()
{

}
}
class B extends A
{
public void show()
{

}
}

"this" keyword
===========
--> it is an implicit Object
--> used to reffered as current class object

class Sample
{
private int x,y;
public void set(int x,int y)
{
this.x=x;
this.y=y;
}
}

"Super" Keyword
=============
It used to access the hidden feature of base class in derived class
it must be first statment in the derived class "constructor"
Example
========

class Sample
{
public Sample(int x)
{
}
public void show()
{

}
}

class Sample1 extends Sample


{
public Sample1(int i,int j)
{
super(i);
}
public void show()
{
super.show();
}
}

Creating the Object


===============
Sample1 obj=new Sample1(10,20);
obj.show();

Applets
======
--> an applet is window based Java Program(GUI)
--> it is executed on appletviewer or InternetExplorer (Web browser)
--> The Packages required for creating the Applets are

*) java.awt
*) java.awt.event
*) java.applet
--> it is Embed in Web page using the <applet>....</applet> tag

syntax
=====
<applet code="classname" width="value" height="value">
</applet>

--> Applet lifecycle methods

*) init()
public void init() { ------ }
*) start()
public void start() { ----- }
*) paint()
public void paint(Graphics g) { ----- }
*) stop()
public void stop() { ------ }
*) destroy()
public void destroy() { ---- }

//sample applet program


import java.awt.*;
import java.applet.*;

public class MyApplet extends Applet


{
public void init()
{
setBackground(Color.yellow);
setForeground(Color.green);
System.out.println("---init----");
}
public void paint(Graphics g)
{
g.drawString("Welcome to Applet",50,300);
System.out.println("--paint()---");
}
}

/*
<applet code="MyApplet" width=400 height=400>
</applet>
*/

You might also like